import {z} from 'zod' export type GetApiProductsV2IdOrderbookArgs = {id: string}; export type GetApiProductsV2IdOrderbookOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiProductsV2IdOrderbookResponse = z.object({data: z.object({productId: z.string(), variants: z.array(z.object({variantId: z.string(), variantTitle: z.string(), listings: z.array(z.object({id: z.string(), price: z.number(), quantity: z.number(), spotPremium: z.number().nullable(), spotPremiumDollar: z.number().nullable(), premiumPercent: z.number().nullable(), premiumDollar: z.number().nullable(), type: z.string().nullable(), expiresAt: z.string().nullable(), createdAt: z.string().nullable(), updatedAt: z.string().nullable()})), offers: z.array(z.object({id: z.string(), price: z.number(), quantity: z.number(), spotPremium: z.number().nullable(), spotPremiumDollar: z.number().nullable(), premiumPercent: z.number().nullable(), premiumDollar: z.number().nullable(), type: z.string().nullable(), expiresAt: z.string().nullable(), createdAt: z.string().nullable(), updatedAt: z.string().nullable()}))}))})}); 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 }; /** * Get live orderbook for a product * * GET /products/v2/{id}/orderbook */ export const getApiProductsV2IdOrderbook = async (args: GetApiProductsV2IdOrderbookArgs, options?: GetApiProductsV2IdOrderbookOptions) => { const {baseUrl = "https://api.collectpure.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (apiKey !== undefined) headers.set("x-api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/products/v2/${encodeURIComponent(String(args.id))}/orderbook${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(getApiProductsV2IdOrderbookResponse, await res.json()) };