import {z} from 'zod' export type CreateApiAskArgs = {body: {query: {text: string, site?: string | undefined} | {[key: string]: unknown}, context?: ({'@type'?: string | undefined, prev?: Array | undefined, text?: string | undefined, memory?: string | undefined} | {[key: string]: unknown}) | undefined, prefer?: ({streaming?: boolean | undefined, response_format?: string | undefined, mode?: string | undefined, 'accept-language'?: string | undefined, 'user-agent'?: string | undefined, limit?: number | undefined} | {[key: string]: unknown}) | undefined, meta?: ({version?: string | undefined, session_context?: {[key: string]: unknown} | undefined, user?: (string | {[key: string]: unknown}) | undefined, remember?: boolean | undefined, request_id?: string | undefined} | {[key: string]: unknown}) | undefined} | {[key: string]: unknown}}; export type CreateApiAskOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiAskResponse = z.union([z.object({_meta: z.object({version: z.literal("0.55"), request_id: z.string().optional(), response_type: z.literal("answer"), response_format: z.literal("conversational_search"), release: z.object({id: z.string()})}).and(z.record(z.string(), z.unknown())), results: z.array(z.object({"@type": z.literal("WebPage"), url: z.string(), name: z.string(), site: z.string(), score: z.number(), description: z.string(), grounding: z.object({evidence: z.array(z.object({id: z.string(), documentId: z.string(), url: z.string(), text: z.string(), start: z.number().int().gte(0).lte(9007199254740991), end: z.number().int().gte(0).lte(9007199254740991), view: z.enum(["origin", "published"]), context: z.object({profile: z.literal("adjacent-passages-v1"), anchorStart: z.number().int().gte(0).lte(9007199254740991), anchorEnd: z.number().int().gte(0).lte(9007199254740991), passageIds: z.array(z.string())}).optional()}))})}))}), z.object({_meta: z.object({version: z.literal("0.55"), request_id: z.string().optional(), response_type: z.literal("failure")}).and(z.record(z.string(), z.unknown())), error: z.object({code: z.string(), message: z.string(), status: z.number().int().gte(-9007199254740991).lte(9007199254740991).optional(), retry_after: z.number().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 published website evidence * * POST /ask */ export const createApiAsk = async (args: CreateApiAskArgs, options?: CreateApiAskOptions) => { const {baseUrl = "https://appsflyer.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/ask${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiAskResponse, await res.json()) };