import {z} from 'zod' export type CreateApiV1WebScrapeArgs = {body: {url: string, engine?: ('auto' | 'browser') | undefined, format?: ('html' | 'markdown' | 'text') | undefined, render_js?: boolean | undefined, wait_for?: string | undefined, wait_timeout?: number | undefined, wait_after_load?: number | undefined, js_scenario?: Array> | undefined, session_id?: string | undefined, retry_count?: number | undefined, retry_on_block?: boolean | undefined, country?: string | undefined, custom_headers?: Record | undefined, screenshot?: boolean | undefined, video?: boolean | undefined, anti_bot?: boolean | undefined, escalate?: boolean | undefined, max_cost?: number | undefined, ai_extract?: boolean | undefined, ai_prompt?: string | undefined}}; export type CreateApiV1WebScrapeOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiV1WebScrapeResponse = z.object({success: z.boolean().optional(), url: z.string().optional(), status_code: z.number().int().optional(), content: z.string().optional(), format: z.string().optional(), engine_used: z.string().optional(), credits_used: z.number().int().optional(), duration_ms: z.number().int().optional(), retries_used: z.number().int().optional(), content_length: z.number().int().optional(), screenshot_url: z.string().nullable().optional(), video_url: z.string().nullable().optional(), headers: z.object({}).optional(), blocking_detected: z.boolean().optional(), blocking_details: z.object({}).nullable().optional(), antibot_systems: z.array(z.unknown()).optional(), captcha_systems: z.array(z.unknown()).optional(), anti_bot_solved: z.boolean().optional(), solver_used: z.string().nullable().optional(), ai_extraction: z.unknown(), ai_model: z.string().nullable().optional(), ai_error: z.string().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 }; /** * Scrape URL * * POST /v1/web/scrape */ export const createApiV1WebScrape = async (args: CreateApiV1WebScrapeArgs, options?: CreateApiV1WebScrapeOptions) => { const {baseUrl = "https://scrapebadger.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (apiKey !== undefined) headers.set("x-api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/web/scrape${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(createApiV1WebScrapeResponse, await res.json()) };