import {z} from 'zod' export type GetApiEloCalculatorArgs = {yourRating: number, opponentRating: number, result: 'win' | 'draw' | 'loss', system?: ('fide' | 'chesscom' | 'lichess') | undefined, kFactor?: number | undefined}; export type GetApiEloCalculatorOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const eloResponse = z.object({yourRating: z.number().int().optional(), opponentRating: z.number().int().optional(), result: z.enum(["win", "draw", "loss"]).optional(), system: z.enum(["fide", "chesscom", "lichess"]).optional(), kFactor: z.number().int().optional(), expectedScore: z.number().optional(), newRating: z.number().int().optional(), change: z.number().int().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 }; /** * Compute an Elo rating change for a single game * * GET /elo-calculator */ export const getApiEloCalculator = async (args: GetApiEloCalculatorArgs, options?: GetApiEloCalculatorOptions) => { 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") if (args.yourRating != null) query.append("yourRating", String(args.yourRating)) if (args.opponentRating != null) query.append("opponentRating", String(args.opponentRating)) if (args.result != null) query.append("result", String(args.result)) if (args.system != null) query.append("system", String(args.system)) if (args.kFactor != null) query.append("kFactor", String(args.kFactor)) const url = `${baseUrl.replace(/\/+$/, '')}/elo-calculator${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(eloResponse, await res.json()) };