import {z} from 'zod' export type GetApiBuyAvailabilityArgs = {url: string}; export type GetApiBuyAvailabilityOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiBuyAvailabilityResponse = z.object({ok: z.boolean(), url: z.string(), status: z.number().int().nullable().optional(), text: z.string().optional(), fetchedAt: z.string().optional(), data: z.object({up: z.boolean(), reachable: z.boolean(), httpStatus: z.number().int().nullable(), responseClass: z.enum(["1xx-informational", "2xx-success", "3xx-redirect", "4xx-client-error", "5xx-server-error", "unknown", "none"]), reason: z.string(), responseMs: z.number().int().nullable().optional(), rubric: z.string()}).optional(), attestation: z.object({}).optional(), error: z.string().optional()}).and(z.record(z.string(), z.unknown())); 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 }; /** * MERCURY Cited Availability Probe * * GET /buy/availability */ export const getApiBuyAvailability = async (args: GetApiBuyAvailabilityArgs, options?: GetApiBuyAvailabilityOptions) => { const {baseUrl = "https://network.mercury-hq.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.url != null) query.append("url", String(args.url)) const url = `${baseUrl.replace(/\/+$/, '')}/buy/availability${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(getApiBuyAvailabilityResponse, await res.json()) };