import {z} from 'zod' export type ModeType = 'fast' | 'standard'; export type BrowserProfileType = 'light' | 'stealth' | 'tf-browser' | 'tf-browser-154'; export type TetraProxy = {type?: 'tetra' | undefined, country_code?: string | undefined}; export type CustomProxy = {type?: 'custom' | undefined, url: string, username?: (string | null) | undefined, password?: (string | null) | undefined}; export type RestUrlQueryParams = {mode?: ModeType | undefined, wait_for?: number | undefined, is_scroll_to_bottom_enabled?: boolean | undefined, is_screenshot_enabled?: boolean | undefined, browser_profile?: BrowserProfileType | undefined, proxy?: (TetraProxy | CustomProxy | null) | undefined}; export type RestWebPageQueryRequest = {query?: (string | null) | undefined, prompt?: (string | null) | undefined, url?: (string | null) | undefined, html?: (string | null) | undefined, params?: RestUrlQueryParams | undefined}; export type CreateApiQueryDataArgs = {'X-TF-Request-Origin'?: string | undefined, 'content-type': string, body: RestWebPageQueryRequest}; export type CreateApiQueryDataOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const responseMetadata = z.object({request_id: z.string().optional(), generated_query: z.string().nullable().optional(), screenshot: z.string().nullable().optional()}); export const restQueryResponse = z.object({data: z.record(z.string(), z.unknown()), metadata: responseMetadata.nullable().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 }; /** * Query Data Service * * POST /query-data */ export const createApiQueryData = async (args: CreateApiQueryDataArgs, options: CreateApiQueryDataOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-TF-Request-Origin'] != null) headers.set("X-TF-Request-Origin", String(args['X-TF-Request-Origin'])) if (args['content-type'] != null) headers.set("content-type", String(args['content-type'])) if (APIKeyHeader !== undefined) headers.set("X-API-Key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/query-data${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(restQueryResponse, await res.json()) };