import {z} from 'zod' export type GetApiCrawlDataArgs = {name: string, format?: string | undefined, type?: string | undefined, num?: string | undefined}; export type GetApiCrawlDataOptions = {baseUrl?: string | undefined, Authorization?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiCrawlDataResponse = z.array(z.object({sentiment: z.number().optional(), theCookie: z.string().optional(), humanLanguage: z.string().optional(), diffbotUri: z.string().optional(), siteName: z.string().optional(), pageUrl: z.string().optional(), html: z.string().optional(), text: z.string().optional(), type: z.string().optional(), title: z.string().optional(), docId: z.number().int().optional(), fromSeedUrl: z.string().optional(), seedUrlHash32: z.number().int().optional(), parentUrlDocId: z.number().int().optional(), gburl: z.string().optional(), lastCrawlTimeUTC: z.number().int().optional(), timestamp: z.string().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 Crawl Job Data * * GET /crawl/data */ export const getApiCrawlData = async (args: GetApiCrawlDataArgs, options?: GetApiCrawlDataOptions) => { const {baseUrl = "https://llm.diffbot.com/api/v1/web_search", fetch: fetchFn = fetch, Authorization} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.name != null) query.append("name", String(args.name)) if (args.format != null) query.append("format", String(args.format)) if (args.type != null) query.append("type", String(args.type)) if (args.num != null) query.append("num", String(args.num)) if (Authorization !== undefined) headers.set('authorization', `Bearer ${Authorization}`) const url = `${baseUrl.replace(/\/+$/, '')}/crawl/data${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(getApiCrawlDataResponse, await res.json()) };