import {z} from 'zod' export type GetApiV1VerifyOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const installationVerificationResponse = z.object({ok: z.literal(true), poweredBy: z.literal("On-Page.ai"), server_url: z.string(), authentication: z.object({type: z.literal("api_key"), api_key_id: z.string(), api_key_name: z.string().nullable(), api_key_prefix: z.string().nullable()}), organization: z.object({id: z.string()}), available_credits: z.number().gte(0), reserved_credits: z.number().gte(0), available_millicredits: z.number().int().gte(0), reserved_millicredits: z.number().int().gte(0), route_costs_credits: z.object({classify: z.number().gte(0), scan_lite: z.number().gte(0), scan: z.number().gte(0), scan_deep: z.number().gte(0)}), unit: z.literal("credits"), real_output_contract: z.object({queued_jobs_include: z.array(z.string()), completed_results_include: z.array(z.string()), warning: z.string()}), next_step: z.string()}); 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 }; /** * Verify that the On-Page.ai API key is installed and usable. * * GET /v1/verify */ export const getApiV1Verify = async (options?: GetApiV1VerifyOptions) => { const {baseUrl = "https://api.on-page.ai", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (apiKey !== undefined) headers.set('authorization', `Bearer ${apiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/verify${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(installationVerificationResponse, await res.json()) };