import {z} from 'zod' export type PracticeProblem = {problem_type: 'mcq' | 'frq' | 'selectall', problem_statement: string, correct_answer?: (string | Array | null) | undefined, difficulty?: ('easy' | 'medium' | 'hard') | undefined, answer_choices?: ({[key: string]: string} | null) | undefined, explanation?: (string | null) | undefined, scoring_details?: (string | null) | undefined, include_graph?: boolean | undefined, graph_description?: (string | null) | undefined, graph_url?: (string | null) | undefined, user_answer?: (string | Array | null) | undefined}; export type GradeFRQRequest = {problem: PracticeProblem}; export type CreateApiV1InteractivesPracticeGradeArgs = {body: GradeFRQRequest}; export type CreateApiV1InteractivesPracticeGradeOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const gradeFRQResponse = z.object({success: z.boolean(), timestamp: z.string(), score: z.number().int(), explanation: z.string(), max_score: z.number().int(), percentage: z.number()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Grade Practice * * POST /v1/interactives/practice/grade */ export const createApiV1InteractivesPracticeGrade = async (args: CreateApiV1InteractivesPracticeGradeArgs, options: CreateApiV1InteractivesPracticeGradeOptions) => { const {baseUrl, fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/interactives/practice/grade${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(gradeFRQResponse, await res.json()) };