import * as fetch_retry from 'fetch-retry'; import fastq from 'fastq'; /** * A server-extensible string enum: the listed values autocomplete, but the server may * return values not listed (the Batch API marks these `x-extensible-enum`). Response fields * use `Extensible<...>`, so callers must handle an unknown value. The named types stay closed * so they keep working as request input. */ type Extensible = T | (string & {}); type JobType = "regular" | "scheduled"; type JobStatus = "open" | "closed" | "deleted"; type ScheduleState = "active" | "paused"; type RunStatus = "pending" | "running" | "completed" | "failed" | "stopped" | "deleted"; /** * `expired`: a successful task whose result is past the retention window (14 days by * default). The row has no `result_url`, and its content endpoint answers 410 * `result_expired`. A `status: "successful"` filter still matches expired rows. */ type TaskStatus = "pending" | "processing" | "successful" | "failed" | "expired"; type PauseState = "active" | "paused"; type IngestStatus = "pending" | "done"; type ExportStatus = "pending" | "running" | "completed" | "failed"; /** What started a run: `manual` (a submit or rerun through the API) or `scheduled` (a schedule fired). */ type RunTrigger = "manual" | "scheduled"; /** HTTP method a task fetches its URL with. `GET` is the default. */ type TaskMethod = "GET" | "POST"; /** * Why a run auto-failed (`status == "failed"`). * - `insufficient_credits` — the account is out of credits. * - `subscription_inactive` — the subscription is not active. * - `api_key_cap_reached` — the job's API key reached one of its credit caps; resolves when * that cap's window resets or the cap is raised. `Run.failure_detail` says which. */ type RunFailureReason = "insufficient_credits" | "subscription_inactive" | "api_key_cap_reached"; interface Spend { credits: number; cost: number; } /** @deprecated Results listings never return per-task spend; see `TaskHistoryEvent.spend`. */ interface TaskSpend { total: Spend; last_attempt: Spend; } interface RunStats { total: number; completed: number; successful: number; failed: number; failure_reasons?: Record; spend?: Spend; } interface WebhookConfig { url: string; signature: boolean; } interface JobSchedule { at?: string; rate?: { every: number; unit: "minute" | "hour" | "day"; }; calendar?: { times_of_day: string[]; cadence: { daily?: object; weekly?: { days: string[]; }; monthly?: { days: number[]; }; }; }; timezone?: string; } interface Run { run_id: string; job_id: string; run_sequence: number; status: Extensible; /** What started this run. */ trigger?: Extensible; stats: RunStats; last_batch_received?: boolean; pause_state?: PauseState; ingest_status?: Extensible; failure_reason?: Extensible; /** Human-readable explanation of `failure_reason` (e.g. which cap, and when it resets, UTC). */ failure_detail?: string | null; created_at?: string; updated_at?: string; } interface Job { job_id: string; type: JobType; status: Extensible; format?: string; zenrows_params?: Record; external_id?: string; name?: string; metadata?: Record; schedule?: JobSchedule; next_scheduled_run?: string; schedule_state?: ScheduleState; webhook?: WebhookConfig; latest_run?: Run; created_at?: string; updated_at?: string; } interface ListJobsResponse { jobs: Job[]; next_cursor?: string; } interface ListJobRunsResponse { runs: Run[]; next_cursor?: string; } interface SubmitJobResponse { job_id: string; status: Extensible; latest_run?: Run; accepted_tasks: number; webhook?: WebhookConfig; } interface AddTasksResponse { accepted_tasks: number; job_status: Extensible; latest_run: Run; } interface RerunJobResponse { job_id: string; status: Extensible; latest_run: Run; rerun_of?: string; retried_tasks: number; inherited_tasks: number; } interface ProblemJson { type?: string; title?: string; status?: number; code?: string; detail?: string; instance?: string; } interface TaskResult { task_id: string; external_id?: string; run_id: string; url: string; metadata?: Record; method?: TaskMethod; status: Extensible; type?: string; result_url?: string; error?: ProblemJson; source_run_id?: string; /** When the task row was created (RFC 3339). */ created_at?: string; /** When the task row last changed, for example when an attempt settled (RFC 3339). */ updated_at?: string; /** * @deprecated Never set: results listings do not return per-task spend. Read per-attempt * spend from `getTaskHistory()`, or the run total from `run.stats.spend`. */ spend?: TaskSpend; } interface ListResultsResponse { results: TaskResult[]; next_cursor?: string; } interface TaskHistoryEvent { started_at: string; ended_at: string; attempt: number; error?: ProblemJson; spend?: Spend; } interface TaskHistoryResponse { events: TaskHistoryEvent[]; } interface StartExportResponse { export_id: string; status: Extensible; created_at: string; expires_at: string; } interface Export { export_id: string; status: Extensible; error?: string; download_url?: string; created_at: string; expires_at: string; } interface FileInputUploadTarget { method: "PUT"; url: string; headers?: Record; expires_at: string; } interface CreateJobInputResponse { file_input_id: string; upload: FileInputUploadTarget; expires_at: string; } interface HMACKeyMeta { kid: string; created_at: string; } interface HMACKeyList { active?: HMACKeyMeta; candidate?: HMACKeyMeta; } interface HMACKeyCreated { kid: string; secret: string; created_at: string; } interface HMACKeyFinalized { active_kid: string; created_at: string; } interface TestWebhookResponse { delivered: boolean; event_id: string; status_code?: number; error?: string; elapsed_ms: number; } /** Event types a Batch webhook delivers. `webhook.test` comes only from `testWebhook()`. */ type WebhookEventType = "run.completed" | "run.failed" | "webhook.test"; /** * The JSON body of a Batch webhook delivery (`schema: "zenrows.webhook/v1"`). Verify the * raw body with `verifyWebhookSignature()` before parsing it, and deduplicate deliveries on * `event_id` (also sent as the `X-ZenRows-Event-Id` header): a delivery can repeat. */ interface WebhookEvent { schema: Extensible<"zenrows.webhook/v1">; event_id: string; event_type: Extensible; /** When the event was queued (RFC 3339). */ occurred_at: string; job_id: string; external_id?: string; metadata?: Record; run_id: string; run_sequence: number; /** The run's counters when the event was queued. */ stats?: RunStats; /** Set on `run.failed` only. */ failure_reason?: Extensible; /** Set on `run.failed` only. */ failure_detail?: string; } declare const DEFAULT_MAX_FILES = 100000; declare const DEFAULT_MAX_BYTES_PER_FILE: number; declare const DEFAULT_MAX_COUNT_IN_MEMORY = 10000; declare const DEFAULT_MAX_TOTAL_BYTES_IN_MEMORY: number; interface DownloadedResult { taskId: string; externalId?: string; url: string; body: Buffer; } /** * A result row a bulk download left out because it has no body to fetch: an `expired` row * (a successful result past the retention window) or a `failed` task. Reported through the * `onSkip` option of `downloadToDir` / `downloadToMemory`. */ interface SkippedResult { taskId: string; externalId?: string; url: string; status: "expired" | "failed"; } interface DownloadToDirOptions { status?: string; nameFn?: (task: TaskResult) => string; useExternalId?: boolean; concurrency?: number; maxFiles?: number; maxBytesPerFile?: number; /** Called for each `expired` or `failed` row skipped because it has no body to fetch. */ onSkip?: (row: SkippedResult) => void; } /** * Write every task body in `results` to `targetDir`, one file per task, and return how many * files it wrote. `expired` and `failed` rows have no body: they are skipped (and passed to * `onSkip`) instead of failing the download. Any other row without a `result_url` still * fails it. */ declare function downloadToDir(results: AsyncIterable, targetDir: string, { nameFn, useExternalId, concurrency, maxFiles, maxBytesPerFile, onSkip, }?: DownloadToDirOptions): Promise; interface DownloadToMemoryOptions { concurrency?: number; maxCount?: number; maxTotalBytes?: number; maxBytesPerFile?: number; /** Called for each `expired` or `failed` row skipped because it has no body to fetch. */ onSkip?: (row: SkippedResult) => void; } /** * Load every task body in `results` into memory. `expired` and `failed` rows have no body: * they are skipped (and passed to `onSkip`). Any other row without a `result_url` still * fails the download. */ declare function downloadToMemory(results: AsyncIterable, { concurrency, maxCount, maxTotalBytes, maxBytesPerFile, onSkip, }?: DownloadToMemoryOptions): Promise; declare function downloadTaskToFile(task: TaskResult, target: string): Promise; declare function downloadTaskToMemory(task: TaskResult): Promise; /** * Client-side cost estimation, mirroring the Python SDK's rate card exactly. Pure — no * network call. Prices a job assuming every task succeeds once; `mode=auto` is billed * dynamically post-factum and is reported as a [1, 25] credit range, everything else is exact. */ declare const BASE_CREDITS = 1; declare const JS_CREDITS = 5; declare const PREMIUM_PROXY_CREDITS = 10; declare const JS_AND_PROXY_CREDITS = 25; declare const AUTO_MIN_CREDITS = 1; declare const AUTO_MAX_CREDITS = 25; type Tier = "base" | "js_render" | "premium_proxy" | "js_render+premium_proxy" | "auto"; type ParamValue = string | boolean | number | Record; type ParamMap = Record; interface EstimateTask { zenrows_params?: ParamMap; } type TaskLike = string | EstimateTask | Record; interface CostLine { tier: Tier; count: number; unitMin: number; unitMax: number; } interface CostEstimate { taskCount: number; min: number; max: number; breakdown: CostLine[]; exact: boolean; } /** * Estimate the credit cost of a job before submitting it. `tasks` accepts the same shapes * `submitRegular` does: bare URL strings or task objects. Each task is priced on the * job-level `zenrowsParams` overlaid with its own `zenrows_params` (the task wins on a key * collision), the same merge the API applies. * * Scrape params set directly on a task object (a flat `js_render` next to `url`) are not * counted: the API has no such task field and ignores it, so it doesn't change the price. * Put per-task params under `zenrows_params`. */ declare function estimateCost(tasks: Iterable, zenrowsParams?: ParamMap): CostEstimate; declare const DAYS_OF_WEEK: readonly ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]; type DayOfWeek = (typeof DAYS_OF_WEEK)[number]; /** * One-shot fire at a specific wall-clock time. `at` must be tz-naive: a plain ISO string * with no `Z`/offset suffix, or a `Date` — in which case its LOCAL getters (not UTC) are * read as the intended wall-clock time. `timezone` is the single authoritative interpreter, * which is what keeps DST transitions deterministic; passing a `Date` does NOT mean "this * instant" — it means "this wall-clock reading, in whatever zone `timezone` names." */ declare class At { readonly at: string; readonly timezone: string; constructor(at: string | Date, timezone: string); toRequestBody(): JobSchedule; } /** Interval-based fire policy — every N units, no alignment to wall clock. */ declare class Rate { readonly every: number; readonly unit: "minute" | "hour" | "day"; constructor(every: number, unit: "minute" | "hour" | "day"); toRequestBody(): JobSchedule; } /** Fire every day. No knobs. */ declare class Daily { } /** Fire on specific days of the week. `days` must be non-empty, lower-case 3-letter names. */ declare class Weekly { readonly days: DayOfWeek[]; constructor(days: DayOfWeek[]); } /** Fire on specific days of the month (1-31); days that don't exist in a given month are skipped. */ declare class Monthly { readonly days: number[]; constructor(days: number[]); } type Cadence = Daily | Weekly | Monthly; /** Calendar-style fire policy: a list of times-of-day on a daily/weekly/monthly cadence. */ declare class Calendar { readonly timesOfDay: string[]; readonly cadence: Cadence; readonly timezone: string; constructor(timesOfDay: string[], cadence: Cadence, timezone: string); toRequestBody(): JobSchedule; } type Schedule = At | Rate | Calendar; interface BatchTaskLike { url: string; external_id?: string; metadata?: Record; zenrows_params?: Record; /** HTTP method for the target fetch. Default `GET`. */ method?: TaskMethod; /** Request body for a `POST` task: a JSON value or a string, up to 16 KiB. */ body?: unknown; } /** A reference to a specific run by `(jobId, runId)`. No pause/stop — only the CURRENT run supports those. */ declare class RunRef { #private; readonly jobId: string; readonly runId: string; constructor(client: ZenRowsBatchClient, jobId: string, runId: string); load(): Promise; delete(): Promise; results(options?: { status?: string; }): AsyncGenerator; taskHistory(taskId: string): Promise; downloadToDir(targetDir: string, options?: DownloadToDirOptions & { status?: string; }): Promise; downloadToMemory(options?: DownloadToMemoryOptions & { status?: string; }): Promise; downloadTaskToFile(task: TaskResult, target: string): Promise; downloadTaskToMemory(task: TaskResult): Promise; wait(options?: { targetStatuses?: Set; failureStatuses?: Set; timeout?: number; pollInterval?: number; /** Keep polling while the run is paused instead of throwing `RunPausedError`. */ waitWhilePaused?: boolean; }): Promise; startExport(): Promise; export(exportId: string): ExportRef; downloadAllResults(targetPath: string, options?: { waitTimeout?: number; pollInterval?: number; }): Promise; } declare class RunHandle extends RunRef { readonly data: Run; constructor(client: ZenRowsBatchClient, jobId: string, runId: string, data: Run); get status(): Extensible; get stats(): RunStats; } declare class ExportRef { #private; readonly jobId: string; readonly runId: string; readonly exportId: string; readonly startResponse?: StartExportResponse | undefined; constructor(client: ZenRowsBatchClient, jobId: string, runId: string, exportId: string, startResponse?: StartExportResponse | undefined); load(): Promise; wait(options?: { targetStatuses?: Set; timeout?: number; pollInterval?: number; }): Promise; /** Stream the export zip to `targetPath`. The export must already be `completed`. */ downloadToPath(targetPath: string): Promise; } declare class ExportHandle extends ExportRef { readonly data: Export; constructor(client: ZenRowsBatchClient, jobId: string, runId: string, exportId: string, data: Export, startResponse?: StartExportResponse); get status(): Extensible; } /** Operations on a job's CURRENT run, reached via `job.run`. */ declare class CurrentRun { #private; readonly jobId: string; constructor(client: ZenRowsBatchClient, jobId: string); private currentRunId; load(): Promise; pause(): Promise; resume(): Promise; stop(): Promise; cancel(): Promise; wait(options?: { targetStatuses?: Set; failureStatuses?: Set; timeout?: number; pollInterval?: number; /** Keep polling while the run is paused instead of throwing `RunPausedError`. */ waitWhilePaused?: boolean; }): Promise; results(options?: { status?: string; }): AsyncGenerator; taskHistory(taskId: string): Promise; downloadToDir(targetDir: string, options?: DownloadToDirOptions & { status?: string; }): Promise; downloadToMemory(options?: DownloadToMemoryOptions & { status?: string; }): Promise; downloadTaskToFile(task: TaskResult, target: string): Promise; downloadTaskToMemory(task: TaskResult): Promise; startExport(): Promise; downloadAllResults(targetPath: string, options?: { waitTimeout?: number; pollInterval?: number; }): Promise; } /** Operations on a scheduled job's schedule, reached via `job.schedule`. Scheduled jobs only — regular jobs 409. */ declare class ScheduleControls { #private; readonly jobId: string; constructor(client: ZenRowsBatchClient, jobId: string); pause(): Promise; resume(): Promise; update(schedule: Schedule): Promise; } /** A reference to a job by id — job-template operations, plus `run`/`schedule` sub-facets. */ declare class JobRef { #private; readonly jobId: string; readonly submitResponse?: SubmitJobResponse | undefined; private runFacet?; private scheduleFacet?; constructor(client: ZenRowsBatchClient, jobId: string, submitResponse?: SubmitJobResponse | undefined); /** Operations on the CURRENT run — pause/resume/stop/wait/results/downloads/startExport. */ get run(): CurrentRun; /** Operations on the schedule — pause/resume/update (scheduled jobs only). */ get schedule(): ScheduleControls; /** The job status from the submit response — only known on refs from a `submit*` call. */ get status(): Extensible | undefined; get acceptedTasks(): number | undefined; load(): Promise; close(): Promise; delete(): Promise; /** * Start a new run. Without `status` every task runs again; with it (for example * `["failed", "pending"]`) only tasks in those states run and the rest are inherited. * * The API answers every rerun with 202 while it writes the new run's task rows, so * `results()` read straight after a rerun can be partial. Pass `waitForIngest: true` to * resolve only once ingestion is done (it polls up to 300 s), or call `waitForIngest()`. */ rerun(options?: { status?: string | string[]; idempotencyKey?: string; waitForIngest?: boolean; }): Promise; /** Shortcut for `rerun({ status: "failed" })` (or `"failed,pending"` with `includePending`). */ retryFailed(options?: { includePending?: boolean; idempotencyKey?: string; waitForIngest?: boolean; }): Promise; /** * Append tasks to an open job (up to 10,000 per call). With an `idempotencyKey`, a repeat of * the same call (same key, same body) returns the original answer instead of adding the * tasks again, so the SDK retries it on a transient failure. Without one, every call appends * its tasks and a failed call is not retried. */ addTasks(tasks: BatchTaskLike[], options?: { lastBatch?: boolean; idempotencyKey?: string; }): Promise<{ accepted_tasks: number; job_status: Extensible; latest_run: Run; }>; runs(pageSize?: number): AsyncGenerator; addFileInput(data: Uint8Array | string, options: { fields: { url: string | number; external_id?: string | number; }; header?: boolean; delimiter?: string; quote?: string; }): Promise; getWebhook(): Promise; setWebhook(url: string, signature: boolean): Promise; deleteWebhook(): Promise; /** * Block until ingestion has finished writing the run's task rows (`ingest_status` is no * longer `pending`), then return the loaded job. On a ref from a `submit*` call this waits * for the run that submit returned; otherwise for the job's latest run. A run stopped * mid-ingest still waits until the API has settled its rows. */ waitForIngest(options?: { timeout?: number; pollInterval?: number; maxPollInterval?: number; }): Promise; } declare class JobHandle extends JobRef { readonly data: Job; constructor(client: ZenRowsBatchClient, jobId: string, data: Job, submitResponse?: SubmitJobResponse); get status(): Extensible; } /** The request header that carries a signed delivery's signature. */ declare const WEBHOOK_SIGNATURE_HEADER = "X-Signature"; /** The request header that carries a delivery's event id. Deduplicate deliveries on it. */ declare const WEBHOOK_EVENT_ID_HEADER = "X-ZenRows-Event-Id"; /** How far, in seconds, a signature's timestamp may be from now by default. */ declare const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300; interface VerifyWebhookSignatureOptions { /** * Reject a delivery whose `t` is further than this from `now`, in seconds. Default 300. * `0` turns the check off. Anything that isn't a finite number of 0 or more makes every * delivery fail to verify. */ toleranceSeconds?: number; /** * The current time as a Unix timestamp in seconds. Defaults to the system clock. A value * that isn't a finite number makes every delivery fail to verify. */ now?: number; } /** * Check a Batch webhook delivery's `X-Signature` header. * * The header reads `t=,v1=,kid=`. The signature covers * `t`, a literal `.`, then the raw request body, keyed with the secret `rotateHmacKey()` * returned. That secret is base64; this helper decodes it to the key bytes. * * Pass the body exactly as received, before any JSON parsing. `secrets` maps each key id to * its base64 secret, so a receiver accepts both the old and the new key during a rotation; the * header's `kid` picks the one to check. The comparison is constant-time. * * Returns `false` for a missing or malformed header, an unknown `kid`, a secret that isn't a * 32-byte base64 key, a timestamp outside the tolerance, or a wrong signature. * Deliveries can repeat: deduplicate on the `X-ZenRows-Event-Id` header. */ declare function verifyWebhookSignature(rawBody: string | Uint8Array, signatureHeader: string | null | undefined, secrets: Record, options?: VerifyWebhookSignatureOptions): boolean; interface BatchClientConfig { /** Override the Batch API base URL. Matches the Go/Python batch clients' base-URL override. */ baseURL?: string; /** * Retries for transient failures (429/502/503/504 + network errors) on idempotent requests. * Default 3. A 429 `quota_exceeded` (an account limit) is never retried. */ retries?: number; /** * Seconds each API request may take. Default 30. Waiters (`wait`, `waitForRun`) poll with * many short requests, so this does not limit how long a wait lasts, and result downloads * from `result_url` are not limited by it either. */ timeout?: number; } interface BatchTask { url: string; external_id?: string; metadata?: Record; zenrows_params?: Record; /** HTTP method for the target fetch. Default `GET`. */ method?: TaskMethod; /** Request body for a `POST` task: a JSON value or a string, up to 16 KiB. */ body?: unknown; } interface BatchWebhookConfig { url: string; /** * Sign deliveries with the account's HMAC key. On `putJobWebhook`, pass it every time; * see that method for what happens when it is left out. */ signature?: boolean; } interface SubmitJobOptions { type?: JobType; status?: JobStatus; zenrows_params?: Record; tasks?: BatchTask[]; file_input_id?: string; external_id?: string; name?: string; metadata?: Record; webhook?: BatchWebhookConfig; idempotencyKey?: string; /** Block until ingestion finishes for a large (202) submission — see `JobRef.waitForIngest`. */ waitForIngest?: boolean; } interface SubmitTypedOptions { zenrowsParams?: ParamMap; externalId?: string; name?: string; metadata?: Record; webhook?: BatchWebhookConfig; idempotencyKey?: string; /** * Block until the run's task rows are written for a large (202) submission. No effect on * `submitScheduled`: a scheduled submit creates no run, the first one starts when the * schedule fires. */ waitForIngest?: boolean; } interface ListJobsOptions { status?: JobStatus; type?: JobType; limit?: number; cursor?: string; } interface GetResultsOptions { runId?: string; cursor?: string; /** * @deprecated Ignored and not sent: the results endpoint returns pages of a fixed size * (about 1,000 rows). Follow `next_cursor`, or use `iterResults`. */ limit?: number; status?: string; } interface WaitForRunOptions { runId?: string; /** * Statuses that resolve the wait. Defaults to every terminal status (`completed`, * `stopped`, `failed`, `deleted`), so an auto-failed run resolves with its * `failure_reason` / `failure_detail` instead of polling until `timeout`. */ targetStatuses?: Set; /** * Statuses that reject with `WaiterFailureError`. Takes precedence over `targetStatuses`, * so `new Set(["failed"])` makes a failed run throw. Empty by default. */ failureStatuses?: Set; timeout?: number; pollInterval?: number; maxPollInterval?: number; /** * A paused run never progresses until someone resumes it, so by default the wait stops * at once with a `RunPausedError` carrying the run. Set this to keep polling while * paused, for example when another process will resume it. */ waitWhilePaused?: boolean; } type TaskInput = string | { url: string; external_id?: string; metadata?: Record; /** Per-task scrape params, merged over the job-level `zenrowsParams` (task wins). */ zenrows_params?: Record; /** HTTP method for the target fetch. Default `GET`. */ method?: TaskMethod; /** Request body for a `POST` task: a JSON value or a string, up to 16 KiB. */ body?: unknown; }; /** * Client for the Zenrows Batch API (async, job/run/task model). Usable standalone * (`new ZenRowsBatchClient(apiKey)`, matching the Go and Python SDKs' batch clients) or via * the `client.batch` convenience property on a `ZenRows` instance. * * The **main pattern** is resource-style: `job(id)` / `submit*` return a `JobRef` (id-only, * no network); `getJob()` / `iterJobs()` return a loaded `JobHandle` with `.data`. Mutating * operations (`close`, `run.stop`, …) return a FRESH handle carrying the server's updated * state rather than mutating in place. */ declare class ZenRowsBatchClient { readonly apiKey: string; private readonly transport; constructor(apiKey: string, config?: BatchClientConfig); submitJob(options?: SubmitJobOptions): Promise; /** Submit a one-shot scraping job (closed, all tasks known upfront). */ submitRegular(urls?: TaskInput[], fileInputId?: string, opts?: SubmitTypedOptions): Promise; /** Submit a streaming-style job that stays open for more tasks via `JobRef.addTasks`. */ submitOpen(urls?: TaskInput[], opts?: SubmitTypedOptions): Promise; /** Submit a scheduled job. `schedule` is one of the `At`/`Rate`/`Calendar` builders. */ submitScheduled(schedule: Schedule, urls?: TaskInput[], fileInputId?: string, opts?: SubmitTypedOptions): Promise; estimateCost(tasks: Iterable, zenrowsParams?: ParamMap): CostEstimate; /** A `JobRef` for an existing job with no network call — prefer this to act on a known id. */ job(jobId: string): JobRef; getJob(jobId: string): Promise; listJobs(options?: ListJobsOptions): Promise; iterJobs(options?: Omit): AsyncGenerator; /** A `RunRef` for an existing run with no network call. */ run(jobId: string, runId: string): RunRef; getRun(jobId: string, runId: string): Promise; listRuns(jobId: string, options?: { limit?: number; cursor?: string; }): Promise; iterRuns(jobId: string, pageSize?: number): AsyncGenerator; getResults(jobId: string, options?: GetResultsOptions): Promise; iterResults(jobId: string, options?: { runId?: string; status?: string; }): AsyncGenerator; /** * Returns a task's stored content decoded as text (HTML, Markdown, plain text or JSON). * Text decoding corrupts binary bodies: for a `pdf` or other binary result, use * `getTaskContentBytes` instead. * * Throws a `ZenRowsBatchError`: 409 `task_not_ready` while the task runs, 422 with the * task's error for a failed task, and 410 `result_expired` past the retention window. */ getTaskContent(jobId: string, taskId: string, options?: { runId?: string; }): Promise; /** * Returns a task's stored content as raw bytes, so binary results such as PDFs arrive * intact. Same errors as `getTaskContent`. */ getTaskContentBytes(jobId: string, taskId: string, options?: { runId?: string; }): Promise; private contentPath; getTaskHistory(jobId: string, taskId: string, options?: { runId?: string; }): Promise; downloadToDir(jobId: string, runId: string | undefined, targetDir: string, opts?: DownloadToDirOptions): Promise; downloadToMemory(jobId: string, runId: string | undefined, opts?: DownloadToMemoryOptions & { status?: string; }): Promise; downloadTaskToFile(task: TaskResult, target: string): Promise; downloadTaskToMemory(task: TaskResult): Promise; getJobWebhook(jobId: string): Promise; /** * Replace a job's webhook. The API needs both `url` and `signature` on this call, so pass * `signature` whenever you know the setting you want. * * When `signature` is left out, the SDK reads the job's current setting first (`false` when * the job has no webhook yet) and sends that, so changing only the URL never turns signing * off. That is two requests, not one atomic update: a change someone else makes in between * is overwritten with the value read. */ putJobWebhook(jobId: string, config: BatchWebhookConfig): Promise; private currentWebhookSignature; deleteJobWebhook(jobId: string): Promise; testWebhook(config: BatchWebhookConfig): Promise; listHmacKeys(): Promise; /** Capture the returned `secret` HERE — it is not revealed again. */ rotateHmacKey(): Promise; finalizeHmacKey(): Promise; cancelHmacRotation(): Promise; createJobInput(body: { type: "csv"; csv: { delimiter?: string; quote?: string; header?: boolean; fields: { url: string | number; external_id?: string | number; }; }; }): Promise; /** Allocate a CSV slot + PUT the body. Returns the `file_input_id` to pass to `submitJob`. */ uploadCsv(data: Uint8Array | string, options: { fields: { url: string | number; external_id?: string | number; }; header?: boolean; delimiter?: string; quote?: string; }): Promise; startResultsExport(jobId: string, runId: string): Promise; getResultsExport(jobId: string, runId: string, exportId: string): Promise; waitForExport(jobId: string, runId: string, exportId: string, options?: { targetStatuses?: Set; timeout?: number; pollInterval?: number; maxPollInterval?: number; }): Promise; /** Start an export, wait for it, and save the zip to `targetPath`. The API caps the size of one export. */ downloadAllResults(jobId: string, runId: string, targetPath: string, options?: { waitTimeout?: number; pollInterval?: number; }): Promise; waitForRun(jobId: string, options?: WaitForRunOptions): Promise; /** @internal */ _getJobData(jobId: string): Promise; /** @internal */ _getRunData(jobId: string, runId: string): Promise; /** @internal */ _postClose(jobId: string): Promise; /** @internal */ _postStop(jobId: string): Promise; /** @internal */ _postPause(jobId: string): Promise; /** @internal */ _postResume(jobId: string): Promise; /** @internal */ _delete(jobId: string): Promise; /** @internal */ _deleteRun(jobId: string, runId: string): Promise; /** @internal */ _postRerun(jobId: string, options?: { status?: string | string[]; idempotencyKey?: string; }): Promise; /** @internal */ _putSchedule(jobId: string, schedule: JobSchedule): Promise; /** @internal */ _postScheduleState(jobId: string, state: "paused" | "active"): Promise; /** @internal */ _postTasks(jobId: string, tasks: BatchTask[], options?: { lastBatch?: boolean; idempotencyKey?: string; }): Promise; /** @internal */ _postExportStart(jobId: string, runId: string): Promise; /** @internal */ _getExport(jobId: string, runId: string, exportId: string): Promise; /** @internal */ _waitForRunRaw(jobId: string, options: WaitForRunOptions): Promise; /** @internal */ _waitForIngestRaw(jobId: string, options?: { timeout?: number; pollInterval?: number; maxPollInterval?: number; }): Promise; /** * @internal Wait for one run's ingestion, by run id. A replayed submit or rerun returns * the original run, which may no longer be the job's latest, so this never follows * `latest_run`. */ _waitForRunIngestRaw(jobId: string, runId: string, options?: { timeout?: number; pollInterval?: number; maxPollInterval?: number; }): Promise; } /** `running` until the crawl ends; the other three are terminal. */ type CrawlStatus = "running" | "completed" | "stopped" | "failed"; /** * What ended a crawl early: a limit (`status: completed`) or `stop()` (`status: stopped`). Absent on a * crawl that stopped because the account ran out of credits or the API key hit a credit cap: that one * carries `error` instead. */ type CrawlStopReason = "max_items" | "max_pages" | "user"; /** * Why a crawl failed (`status: failed`), or why it stopped on credits: `insufficient_credits` and * `api_key_cap_reached` come with `status: stopped`, and the pages fetched before that stay readable. * `seed_unreachable`: the start page could not be reached, was blocked, or came back empty, with no * visible text and no link. `no_items_found`: the crawl read the start page but found no data it could * use, so it had nothing to follow; start from a listing or product page. A crawl that returns nothing * for any other reason is not a failure: it ends `completed` with no results. */ type CrawlErrorCode = "insufficient_credits" | "api_key_cap_reached" | "seed_unreachable" | "domain_not_allowed" | "no_items_found" | "internal_error"; /** Where a kept URL's page stands, when the crawl has an `output_format`. */ type CrawlContentStatus = "pending" | "fetched" | "failed"; /** Return each kept URL's page, in this format. Absent means URLs only. */ type CrawlOutputFormat = "html" | "markdown"; /** How a crawl finds the URLs it follows on each page it walks. */ type CrawlDiscoveryStrategy = "links"; /** * The events a crawl's webhook can be sent. `crawl.started`: the crawl was created and runs. * `crawl.completed`, `crawl.stopped`, `crawl.failed`: the crawl reached that `status`; exactly * one of these three is sent per crawl. */ type CrawlWebhookEventType = "crawl.started" | "crawl.completed" | "crawl.stopped" | "crawl.failed"; interface CrawlCoverage { pages_fetched: number; pages_failed: number; items_found: number; } /** * Why a crawl failed, or why it stopped because the account ran out of credits or the API key hit a * credit cap. Present when `status` is `failed`, and when it is `stopped` with `code` * `insufficient_credits` or `api_key_cap_reached`. Part of the crawl, not an error response. */ interface CrawlRunError { code: Extensible; detail: string; } /** * The webhook a crawl sends its events to, as the crawl runs with it. Fixed at create: there is * no update. */ interface CrawlWebhook { url: string; /** The events the crawl sends: the ones the create asked for, or all four when it left them out. */ events: Extensible[]; /** Sent back with every event. Null or absent when the create set none. */ metadata?: Record | null; } /** * The JSON body of one crawl event (`schema: "zenrows.webhook/v1"`). Verify the raw body with * `verifyCrawlWebhookSignature()` before parsing it. Every delivery of one event carries the same * `event_id` (also sent as the `X-ZenRows-Event-Id` header): drop one you have already handled. * Events can arrive out of order, so a short crawl's end can come before its `crawl.started`: * order them by `occurred_at`, or read the crawl with `get()`. */ interface CrawlWebhookEvent { schema: Extensible<"zenrows.webhook/v1">; /** E.g. `ev_01M5AKXYZ_completed`: the crawl's id without its `c_`, and the event's last part. */ event_id: string; event_type: Extensible; /** When the crawl was created, for `crawl.started`; its `finished_at`, for the others. */ occurred_at: string; resource: { type: Extensible<"crawl">; /** The crawl's `crawl_id`. */ id: string; /** The crawl on the API. */ url?: string; }; /** The webhook's `metadata`. Absent when the crawl has none. */ metadata?: Record; } interface Crawl { crawl_id: string; status: Extensible; url: string; /** The depth limit the crawl was created with. Absent when it was created without one: no depth limit. */ depth?: number; max_items: number; max_pages: number; coverage: CrawlCoverage; created_at: string; stop_reason?: Extensible; error?: CrawlRunError; include_patterns?: string[]; exclude_patterns?: string[]; output_format?: Extensible; /** * The strategies the crawl finds URLs with. `["links"]` when the create left it out. * Absent when the server does not send the field. */ discovery?: Extensible[]; /** Where the crawl sends its events. Absent (or null) on a crawl created without a webhook. */ webhook?: CrawlWebhook | null; duplicates_removed?: number; /** Absent while the crawl runs. */ finished_at?: string; } interface CrawlResult { url: string; content_status?: Extensible; /** The page's path, e.g. `/v1/crawls/c_x/contents/ct_y`. Present when `content_status` is `fetched`. */ content_url?: string; } interface CrawlWithResults extends Crawl { results: CrawlResult[]; /** Never null while the crawl runs; null once it ended and this page holds its last URLs. */ next_cursor: string | null; } interface CrawlList { crawls: Crawl[]; /** Absent on the last page. */ next_cursor?: string; } /** What `stop()` returns: where the crawl stands, without counts. */ interface CrawlStop { crawl_id: string; status: Extensible; stop_reason?: Extensible; error?: CrawlRunError; finished_at?: string; } /** One line of a crawl's download. */ interface CrawlExportLine { url: string; content_status?: Extensible; /** The page, present when `content_status` is `fetched`: HTML text, or an object for a JSON crawl. */ content?: string | Record; } /** What `download()` returns. */ interface CrawlDownload { /** * The crawl's status when the file was read (`X-Crawl-Status`; undefined without it). * `running` means a later download may hold more lines. */ status: Extensible | undefined; lines: AsyncIterable; } /** * Check a crawl event's `X-Signature` header, before you trust or parse its body. * * The header reads `t=,v1=,kid=`. The signature covers * `t`, a literal `.`, then the raw request body, keyed with the account's webhook signing key * (base64, from the dashboard); this helper decodes it to the key bytes. * * Pass the body exactly as received. `secrets` maps each key id to its base64 secret, so a * receiver accepts both the old and the new key during a rotation; the header's `kid` picks the * one to check. The comparison is constant-time. * * Returns `false` for a missing or malformed header, an unknown `kid`, a secret that isn't a * 32-byte base64 key, a timestamp further than `toleranceSeconds` (default 300) from now, or a * wrong signature. An event can arrive more than once: drop a repeat by its `event_id`. */ declare function verifyCrawlWebhookSignature(rawBody: string | Uint8Array, signatureHeader: string | null | undefined, secrets: Record, options?: VerifyWebhookSignatureOptions): boolean; interface CrawlClientConfig { /** Override the Crawl API base URL. Default `https://api.zenrows.com/v1`. */ baseURL?: string; /** * Retries for transient failures (502/503/504, network errors, 429 on reads) on idempotent * requests, and for a `stop()` answered 429, 502, 503 or 504. Default 3. */ retries?: number; /** Seconds each HTTP request may take. Default 30. Does not limit reading a `download()` body. */ timeout?: number; } /** Where to send a crawl's events, and which ones. */ interface CrawlWebhookParams { /** The absolute `https` URL each event is posted to, up to 2,048 characters. Its host must resolve. */ url: string; /** The events to send, each named once, in any order. Omit it for all four. */ events?: CrawlWebhookEventType[]; /** * Sent back with every event, to match it to your own records. Up to 20 keys, each 1 to 64 * characters; each value any JSON, at most 1,024 bytes as compact JSON. */ metadata?: Record; } interface CreateCrawlParams { /** The page the crawl starts from: an absolute public `http`/`https` URL. */ url: string; /** * Link hops to follow from the start URL, 1–100000. Omit it for no depth limit: the crawl * follows links until `maxPages` or `maxItems` stops it, or no link is left to open. */ depth?: number; /** Stop once this many URLs are kept, 1–100000. Server default 100. */ maxItems?: number; /** Stop once this many pages are fetched, 1–100000; bounds the cost. Server default 100. */ maxPages?: number; /** * Keep a URL only if it contains at least one of these substrings. A crawl whose patterns reject * every link ends `completed` with no results and no `error`. */ includePatterns?: string[]; /** Drop a URL that contains any of these substrings, even if it matches an include pattern. */ excludePatterns?: string[]; /** Also fetch each kept URL's page, in this format. Absent means URLs only. */ outputFormat?: CrawlOutputFormat; /** * How the crawl finds the URLs it follows on each page it walks. `["links"]` follows the * links in the page's HTML, and is what a crawl runs with when you leave this out. */ discovery?: CrawlDiscoveryStrategy[]; /** * Get notified when the crawl starts, completes, stops or fails: each event is POSTed to * `webhook.url` as a `CrawlWebhookEvent`, signed with the account's webhook signing key * (create it in the dashboard). Check it with `verifyCrawlWebhookSignature()`. A failed * delivery is retried for up to 3 days. The account needs a signing key, or the create throws a 422 * `webhook_signing_key_required`; a bad `url`, `events` or `metadata` is a 422 `invalid_webhook`. */ webhook?: CrawlWebhookParams; } interface WaitForCrawlOptions { /** Seconds to poll before returning the crawl as it stands. Default 600. */ timeout?: number; } /** * Client for the Zenrows Crawl API (new): give it one start URL, read back the URLs behind it. * Usable standalone (`new ZenRowsCrawlClient(apiKey)`) or via `client.crawl` on a `ZenRows` * instance. A crawl runs asynchronously: `create()` returns at once, `wait()` polls until it * ends, and `results()` / `download()` read what it kept. * Crawl is still evolving: new features are coming, limits may be tuned, and the changelog announces each change. */ declare class ZenRowsCrawlClient { readonly apiKey: string; private readonly transport; private readonly retries; constructor(apiKey: string, config?: CrawlClientConfig); /** * Start a crawl. Sends only the fields you set. With an `idempotencyKey`, a retry returns the * crawl the first request created instead of starting another, and 5xx and network failures * are retried. A 429 `too_many_crawls` is never retried: it throws `ZenRowsCrawlError` with * `retryAfter` set. */ create(params: CreateCrawlParams, opts?: { idempotencyKey?: string; }): Promise; /** Read a crawl's status, coverage and one page of results (`limit` 1–10000, default 1000). */ get(crawlId: string, options?: { cursor?: string; limit?: number; }): Promise; /** One page of the account's crawls, newest first (`limit` 1–100, default 20). */ list(options?: { cursor?: string; limit?: number; }): Promise; /** * Every URL the crawl kept, following `next_cursor` (`limit` is the page size). On a running * crawl it yields the URLs kept so far and returns at the first empty page; it does not poll. * Call `wait()` first to read every result. */ results(crawlId: string, options?: { limit?: number; }): AsyncGenerator; /** * Stop a running crawl. Idempotent: a crawl that already ended answers as it ended. * Because a stop is safe to repeat, `stop()` retries a 429, 502, 503 (including `crawl_busy`, * which means the stop was not saved and the crawl is still running) or 504 up to `retries` * times, waiting `Retry-After` seconds (at most 30; 1 when the header is missing or unusable) * each time, then throws the last error. */ stop(crawlId: string): Promise; /** * One kept URL's page, in the crawl's output format. Pass the content id, a `content_url`, * or the `CrawlResult` itself (its `content_url` is present once `content_status` is * `fetched`). Throws `TypeError` when no content id can be read. * * With `download: true` the server sends the page as a file to save, named after its * content id, instead of one to show. The text is the same either way. */ content(crawlId: string, contentId: string | CrawlResult, options?: { download?: boolean; }): Promise; /** * Every result of the crawl in one download: its `status` and the parsed lines (with the * page when the crawl has an `output_format`). On a running crawl, `status` is `running` and * the lines hold only what was kept so far. */ download(crawlId: string): Promise; /** * Poll until the crawl ends (any status but `running`) or `timeout` seconds pass, and return * it, without results. A `failed` crawl resolves too: read `error`. So does a crawl that * `stopped` because credits ran out or the API key hit a credit cap; `error` says which. On * timeout the crawl is returned with status `running` and keeps running. */ wait(crawlId: string, options?: WaitForCrawlOptions): Promise; } /** Where a domain's Extract preparation stands. Use `status` to decide whether the domain * is usable; `state` is for progress display and may gain values later. */ interface PreparedDomainStatus { domain: string; status: "preparing" | "ready" | "failed"; state: "received" | "discovering" | "preparing" | "verifying" | "ready" | "failed" | string; /** Per-page-kind progress. Only returned to the account that submitted the domain. */ roles?: Array<{ role: string; status: string; url?: string; detail?: string; }>; /** Present when `status` is `"failed"`. */ failure?: { code: string; detail?: string; slot_consumed: boolean; }; submitted_at: string; updated_at: string; [key: string]: unknown; } /** An RFC 9457 problem from the prepared-domains endpoints, which may carry a `reason`. */ interface PreparedDomainProblem extends ProblemJson { reason?: string; } /** * A non-2xx answer from `prepareDomain()` or `preparedDomainStatus()`. Branch on `status` * and `code`; display `detail`, don't parse it. `code` is the problem's code, for example * `invalid_argument` (400), `not_found` (404), `in_progress` (409: a preparation is already * running, read its status instead of resubmitting), `out_of_allowance` (429: no preparations * left this month), or `overloaded` / `disabled` (503); undefined when the body has none. */ declare class ZenRowsPreparedDomainError extends Error { readonly status: number; readonly problem: PreparedDomainProblem | undefined; readonly code: string | undefined; readonly detail: string | undefined; readonly reason: string | undefined; /** Seconds from the `Retry-After` header, when the server sent one. */ readonly retryAfter: number | undefined; constructor(status: number, problem: PreparedDomainProblem | undefined, retryAfter?: number); } /** * The `code` values the Batch API sends in an error body, by name. Compare * `ZenRowsBatchError.code` (or a task's `error.code`) against these instead of a bare string. * The API may add codes, so keep a default branch. */ declare const BatchErrorCode: { /** 400. The request is invalid; a bad task is listed in `extras.invalid_tasks`. */ readonly InvalidArgument: "invalid_argument"; /** 404. */ readonly NotFound: "not_found"; /** 409. */ readonly Conflict: "conflict"; /** 401. The API key is missing or invalid. */ readonly Unauthenticated: "unauthenticated"; /** 401. The key is valid but the subscription is not active; fix it in Billing. */ readonly SubscriptionInactive: "subscription_inactive"; /** 402. The account is out of credits. */ readonly PaymentRequired: "payment_required"; /** 402. The API key reached one of its credit caps; `detail` names the cap and when it resets. */ readonly ApiKeyCapReached: "api_key_cap_reached"; /** 403. */ readonly PermissionDenied: "permission_denied"; /** * 429. An account limit: active jobs (shared with Crawl), scheduled jobs, or the task cap of * an open job. It clears only when a job finishes or is deleted, so it is not retried. */ readonly QuotaExceeded: "quota_exceeded"; /** 500. */ readonly Internal: "internal"; /** 501. */ readonly NotImplemented: "not_implemented"; readonly JobNotOpen: "job_not_open"; readonly RunNotTerminal: "run_not_terminal"; readonly RunNotStoppable: "run_not_stoppable"; readonly NoPriorRun: "no_prior_run"; /** A rerun with a status filter matched no task. */ readonly NoMatchingTasks: "no_matching_tasks"; readonly RunHasDescendants: "run_has_descendants"; readonly LastBatchReceived: "last_batch_received"; /** The same `Idempotency-Key` was sent with a different body. */ readonly IdempotencyKeyConflict: "idempotency_key_conflict"; /** The task is still pending or processing, so it has no content yet. */ readonly TaskNotReady: "task_not_ready"; /** 410. The result is past the retention window. */ readonly ResultExpired: "result_expired"; /** A partial rerun (`status` filter) more than 10 days after the run started; a full rerun still works. */ readonly PartialRerunWindowExpired: "partial_rerun_window_expired"; readonly CandidatePending: "candidate_pending"; readonly NoCandidate: "no_candidate"; readonly UnsupportedScheme: "unsupported_scheme"; readonly MalformedUrl: "malformed_url"; readonly MissingHost: "missing_host"; readonly UrlTooLong: "url_too_long"; readonly MetadataTooLarge: "metadata_too_large"; readonly MetadataKeyInvalid: "metadata_key_invalid"; readonly InvalidExternalId: "invalid_external_id"; readonly UnsupportedMethod: "unsupported_method"; readonly BodyNotAllowed: "body_not_allowed"; readonly BodyTooLarge: "body_too_large"; readonly BodyMalformed: "body_malformed"; readonly MethodParamConflict: "method_param_conflict"; /** 404. */ readonly FileInputNotFound: "file_input_not_found"; /** 409. */ readonly FileInputNotUploaded: "file_input_not_uploaded"; /** 409. */ readonly FileInputUnsupportedForJobType: "file_input_unsupported_for_job_type"; readonly CallbackUrlMustBeHttps: "callback_url_must_be_https"; readonly CallbackUrlUnresolvable: "callback_url_unresolvable"; readonly WebhookSigningRequiresActiveKey: "webhook_signing_requires_active_key"; readonly GatewayUnreachable: "gateway_unreachable"; }; /** One of the `BatchErrorCode` values. */ type BatchErrorCodeValue = (typeof BatchErrorCode)[keyof typeof BatchErrorCode]; /** * A non-2xx response from the Batch API, decoded as RFC 7807 `application/problem+json` * where possible. `code` is the stable Problem `code` member (e.g. `file_input_not_found`), * safe to branch on against `BatchErrorCode`; it is `"internal"` when the body wasn't valid * Problem JSON. */ declare class ZenRowsBatchError extends Error { readonly status: number; readonly problem: ProblemJson | undefined; readonly code: string; readonly extras: Record | undefined; /** The Problem `detail`: a human-readable explanation, when the body had one. */ readonly detail: string | undefined; /** Seconds from the `Retry-After` header, when the response had one. */ readonly retryAfter: number | undefined; constructor(status: number, problem: ProblemJson | undefined, extras?: Record, retryAfter?: number); } /** * Parse a Problem+JSON error body. Tolerant of non-JSON bodies (production servers * occasionally return a raw error page, e.g. from an edge proxy) — degrades to * `undefined` rather than throwing. */ declare function parseProblem(response: Response): Promise<{ problem: ProblemJson | undefined; extras: Record | undefined; }>; /** Raised when a waiter's `timeout` elapsed before the target state was reached. */ declare class WaiterTimeoutError extends Error { constructor(message: string); } /** Raised when the resource entered one of the caller's `isFailure` states. */ declare class WaiterFailureError extends Error { constructor(message: string); } /** * Raised by a run waiter when the run is paused (`pause_state: "paused"`) and not yet in a * target status. A paused run makes no progress until it is resumed, so the waiter stops * instead of polling until its timeout. `run` is the run as last read. */ declare class RunPausedError extends Error { readonly run: Run; constructor(run: Run); } interface PollUntilOptions { isDone(value: T): boolean; isFailure?(value: T): boolean; timeout?: number; initialInterval?: number; maxInterval?: number; backoff?: number; jitter?: number; } /** * Generic poll loop. Calls `fetch()` repeatedly until `isDone(value)` (returns the value), * `isFailure(value)` (throws `WaiterFailureError`), or `timeout` seconds elapse (throws * `WaiterTimeoutError`). The wait between calls starts at `initialInterval`, multiplies by * `backoff` each iteration, caps at `maxInterval`, and is jittered by ±`jitter` fraction so * concurrent waiters don't synchronise into thundering-herd patterns against the API. */ declare function pollUntil(fetch: () => Promise | T, { isDone, isFailure, timeout, initialInterval, maxInterval, backoff, jitter, }: PollUntilOptions): Promise; /** * The API's code for an account Crawl is not enabled on (403). */ declare const CRAWL_NOT_ENABLED_CODE = "REQS008"; /** * A non-2xx response from the Crawl API, decoded as RFC 9457 `application/problem+json` * where possible. Branch on `status` and `code` (e.g. `crawl_not_found`, `too_many_crawls`, * or `REQS008` when Crawl is not enabled for the account); `code` is undefined when the body * has none. */ declare class ZenRowsCrawlError extends Error { readonly status: number; readonly problem: ProblemJson | undefined; readonly code: string | undefined; readonly detail: string | undefined; readonly extras: Record | undefined; /** Seconds from the `Retry-After` header, e.g. 30 on a 429 `too_many_crawls`. */ readonly retryAfter: number | undefined; constructor(status: number, problem: ProblemJson | undefined, extras?: Record, retryAfter?: number); } /** True when a response is Extract's 422 `no_data_extracted`: Extract knows this kind * of page but found no data on it. The request is not charged and the client never * retries it, since another try returns the same answer. Reads via `.clone()`, so the * original response body is left unconsumed for the caller. */ declare function isNoDataExtracted(response: Response): Promise; type HttpMethods = "GET" | "POST" | "PUT"; /** Extract mode — see https://docs.zenrows.com/extract/setup for what each mode returns. */ type ExtractMode = "auto" | "native" | "standard"; interface ClientConfig { concurrency?: number; /** * Retries for `fetch()`, `get()` and `extract()`. Default 0: every request is sent once. * Retried: a 429, 502, 503 or 504, a 422 other than `no_data_extracted`, and a failure * before the request reached the API. `post()` is never retried. A status from the target * site (`original_status`, `allowed_status_codes`) is never retried. A network error after * the request was sent, a response timeout or an abort is never retried (a connect timeout is). */ retries?: number; /** The longest random wait between tries, in seconds. Default 30. It never caps a `Retry-After`. */ retryMaxWait?: number; /** No retry starts once the time since the first try plus the next wait would pass this many * seconds. Default 90. */ retryBudget?: number; /** Config for `client.crawl`: its own `baseURL`, `retries` and `timeout`. */ crawl?: CrawlClientConfig; } interface ZenRowsConfig { /** Set to "auto" to enable Adaptive Stealth Mode — Zenrows starts with the cheapest * viable request configuration and escalates to js_render/premium_proxy only when the * target needs it, billing only for the configuration that succeeds. */ mode?: "auto"; /** @deprecated Autoparse is deprecated. Use `client.extract()` for structured data, * or `css_extractor`. */ autoparse?: boolean; css_extractor?: string; js_render?: boolean; premium_proxy?: boolean; proxy_country?: string; wait_for?: string; wait?: number; block_resources?: string; window_width?: number; window_height?: number; device?: string; original_status?: boolean; custom_headers?: boolean; [x: string]: unknown; } interface Headers { [x: string]: string; } declare class ZenRows { readonly apiKey: string; readonly clientConfig: ClientConfig; readonly queue: fastq.queueAsPromised<{ url: string; method?: HttpMethods; config?: ZenRowsConfig; headers: Headers; data?: unknown; }, Response>; readonly fetchWithRetry: (input: string | URL | Request, init?: (RequestInit & fetch_retry.RequestInitRetryParams) | undefined) => Promise; /** Client for the Batch API (async job/run/task model) — see `./batch.ts`. */ readonly batch: ZenRowsBatchClient; /** Client for the Crawl API (new; one start URL in, the URLs behind it out). See `./crawl/client.ts`. */ readonly crawl: ZenRowsCrawlClient; private readonly retry; constructor(apiKey: string, clientConfig?: ClientConfig); /** * Fetch a URL through Zenrows — the main page-scraping product. This is the primary entry * point; `get()` remains as a deprecated alias for existing callers. */ fetch(url: string, config?: ZenRowsConfig, { headers }?: { headers?: Headers; }): Promise; /** @deprecated Use `fetch()` instead. Kept for backward compatibility. */ get(url: string, config?: ZenRowsConfig, opts?: { headers?: Headers; }): Promise; /** * Fetch a URL and run it through Extract — Zenrows' AI-powered structured extraction. * `mode` defaults to `"auto"`; pass `"native"` or `"standard"` to pick a * different extraction contract. This is a thin, typed wrapper over `fetch()` with the * `extract` param set — no separate endpoint or auth. * * Also sends Adaptive Stealth Mode (`mode: "auto"`) by default, so a target that needs * `js_render`/`premium_proxy` gets escalated automatically instead of failing with * REQS002. It is skipped when the config sets `js_render` or `premium_proxy` (the API * rejects either combined with Adaptive Stealth Mode) or its own `mode`. Pass * `adaptiveStealth: false` to turn it off entirely. * * Extract works on any prepared domain (you can prepare one yourself with * `POST /v1/extract/prepared-domains`), with any active API key. A 403 with * `code: "REQS007"` means Extract can't extract this page. Check `reason` in the problem * body (`(await response.json()).reason`) when present; older responses may not carry it: * * - `domain_not_prepared`: prepare the domain with `prepareDomain()`, poll * `preparedDomainStatus()` until `status` is `"ready"`, then retry. * - `page_not_recognised`: the domain is served, but this page isn't one Extract extracts * (a home, search, login or category page). Try a product, article or listing page, or * retry once in a few minutes. Preparing the domain again changes nothing. * - `domain_not_enabled`: preparing doesn't help. Use `css_extractor`, or contact support. * * The legacy domain-not-enabled error is a 402 with `code: "AUTH010"`. Both error * responses are returned to you as is, in one request; extract() never retries them with * autoparse. * * A 422 with `code: "no_data_extracted"` means Extract knows this kind of page but * found no data on it. It is not charged and is never retried; check it with * `isNoDataExtracted(response)`. */ extract(url: string, config?: ZenRowsConfig & { extract?: ExtractMode; /** @deprecated Has no effect: extract() no longer retries with autoparse. Passing * `true` emits a `DeprecationWarning` once per process. */ fallbackToAutoparse?: boolean; adaptiveStealth?: boolean; }, opts?: { headers?: Headers; }): Promise; /** * Submit `domain` for Extract preparation (`POST /v1/extract/prepared-domains`) and return * the parsed status object the API answers with `202`: `domain`, `status` (`"preparing"`, * `"ready"` or `"failed"`), `state`, `submitted_at`, `updated_at`. * * `domain` is the domain without a scheme. `exampleUrls` are 1 to 5 example URLs on that * domain. One works; we recommend 3 or more of the same page type (e.g. 3 product pages), * because Extract compares pages of one type to check the fields it found and fill in fields * one page is missing. Several page types can share the 5 (e.g. 3 product pages + 2 * search-result pages). Submitting a domain that is already prepared returns its current * status instead of starting a new run. * * Preparation takes minutes. This method does not wait for it: call * `preparedDomainStatus(domain)` until `status` is no longer `"preparing"`. These endpoints * don't fetch pages and cost no credits. * * Rejects with a `TypeError` for an empty `domain`, before any request, and with * `ZenRowsPreparedDomainError` on a non-2xx answer, for example 400 `invalid_argument`, 409 `in_progress`, 429 `out_of_allowance` or 503 `overloaded` / * `disabled`. */ prepareDomain(domain: string, exampleUrls: string[]): Promise; /** * Read the preparation status of `domain` (`GET /v1/extract/prepared-domains/{domain}`) * and return the parsed status object. `status` is `"preparing"`, `"ready"` or `"failed"`; * a failed preparation carries a `failure` with `code`, `detail` and `slot_consumed`. * * Rejects with a `TypeError` for an empty `domain`, before any request, and with * `ZenRowsPreparedDomainError` on a non-2xx answer, for example 404 `not_found` when your * account never submitted `domain`. */ preparedDomainStatus(domain: string): Promise; private preparedDomainsHeaders; post(url: string, config?: ZenRowsConfig, { headers, data }?: { headers?: Headers; data?: unknown; }): Promise; private worker; } export { AUTO_MAX_CREDITS, AUTO_MIN_CREDITS, type AddTasksResponse, At, BASE_CREDITS, type BatchClientConfig, BatchErrorCode, type BatchErrorCodeValue, type BatchTask, type BatchWebhookConfig, CRAWL_NOT_ENABLED_CODE, type Cadence, Calendar, type CostEstimate, type CostLine, type Crawl, type CrawlClientConfig, type CrawlContentStatus, type CrawlCoverage, type CrawlDiscoveryStrategy, type CrawlDownload, type CrawlErrorCode, type CrawlExportLine, type CrawlList, type CrawlOutputFormat, type CrawlResult, type CrawlRunError, type CrawlStatus, type CrawlStop, type CrawlStopReason, type CrawlWebhook, type CrawlWebhookEvent, type CrawlWebhookEventType, type CrawlWebhookParams, type CrawlWithResults, type CreateCrawlParams, type CreateJobInputResponse, CurrentRun, DEFAULT_MAX_BYTES_PER_FILE, DEFAULT_MAX_COUNT_IN_MEMORY, DEFAULT_MAX_FILES, DEFAULT_MAX_TOTAL_BYTES_IN_MEMORY, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, Daily, type DownloadToDirOptions, type DownloadToMemoryOptions, type DownloadedResult, type EstimateTask, type Export, ExportHandle, ExportRef, type ExportStatus, type Extensible, type ExtractMode, type FileInputUploadTarget, type GetResultsOptions, type HMACKeyCreated, type HMACKeyFinalized, type HMACKeyList, type HMACKeyMeta, type IngestStatus, JS_AND_PROXY_CREDITS, JS_CREDITS, type Job, JobHandle, JobRef, type JobSchedule, type JobStatus, type JobType, type ListJobRunsResponse, type ListJobsOptions, type ListJobsResponse, type ListResultsResponse, Monthly, PREMIUM_PROXY_CREDITS, type ParamMap, type ParamValue, type PauseState, type PollUntilOptions, type PreparedDomainProblem, type PreparedDomainStatus, type ProblemJson, Rate, type RerunJobResponse, type Run, type RunFailureReason, RunHandle, RunPausedError, RunRef, type RunStats, type RunStatus, type RunTrigger, type Schedule, type ScheduleState, type SkippedResult, type Spend, type StartExportResponse, type SubmitJobOptions, type SubmitJobResponse, type SubmitTypedOptions, type TaskHistoryEvent, type TaskHistoryResponse, type TaskLike, type TaskMethod, type TaskResult, type TaskSpend, type TaskStatus, type TestWebhookResponse, type Tier, type VerifyWebhookSignatureOptions, WEBHOOK_EVENT_ID_HEADER, WEBHOOK_SIGNATURE_HEADER, type WaitForCrawlOptions, type WaitForRunOptions, WaiterFailureError, WaiterTimeoutError, type WebhookConfig, type WebhookEvent, type WebhookEventType, Weekly, ZenRows, ZenRowsBatchClient, ZenRowsBatchError, type ZenRowsConfig, ZenRowsCrawlClient, ZenRowsCrawlError, ZenRowsPreparedDomainError, downloadTaskToFile, downloadTaskToMemory, downloadToDir, downloadToMemory, estimateCost, isNoDataExtracted, parseProblem, pollUntil, verifyCrawlWebhookSignature, verifyWebhookSignature };