import {z} from 'zod' export type GetApiGameGameIdArgs = {gameId: string}; export type GetApiGameGameIdOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const game = z.object({id: z.string().optional(), pgn: z.string().optional(), white_username: z.string().nullable().optional(), black_username: z.string().nullable().optional(), white_rating: z.number().int().nullable().optional(), black_rating: z.number().int().nullable().optional(), white_result: z.string().nullable().optional(), black_result: z.string().nullable().optional(), time_class: z.string().nullable().optional(), time_control: z.string().nullable().optional(), source: z.string().optional()}); export const gameAnalysisResponse = z.object({gameId: z.string().optional(), status: z.literal("completed").optional(), analysis: z.object({game: game.optional()}).optional(), metadata: z.object({analysisCompletedAt: z.string().optional(), version: z.string().optional()}).optional()}); 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 }; /** * Retrieve analysis for a submitted game * * GET /game/{gameId} */ export const getApiGameGameId = async (args: GetApiGameGameIdArgs, options?: GetApiGameGameIdOptions) => { const {baseUrl = "https://www.chessigma.com/public-api/v1", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/game/${encodeURIComponent(String(args.gameId))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(gameAnalysisResponse, await res.json()) };