Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SPIDER — Universal Web Intelligence Engine8 * File : sdk/typescript/src/client.ts9 * Module : Sdk10 * Repository : https://git.spboucher.ai/spider11 * Project Website : Not specified12 * Created : 2026-12-0413 * Last Modified : 2026-12-0414 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : ISC34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/** Promise-based client of the SPIDER API (Node's built-in `fetch`, no runtime dependency). */44import { createHash, randomUUID } from "node:crypto";4546import {47 ApiError, ArtifactIntegrityError, JobTimeoutError, QuotaExceededError, TransportError, errorFromResponse,48} from "./errors.js";49import { ROUTES, TERMINAL_JOB_STATES, type RetryClass, type RouteName } from "./routes.js";50import { SSEParser } from "./sse.js";51import type {52 BatchItem, BatchResponse, ChangeEvent, CrawlRequest, DeepCaptureRequest, DiffRequest, DiffResult, ExportFormat,53 ExtractRequest, Health, Job, JobEvent, JobResult, JsonObject, MapRequest, Monitor, MonitorAction, MonitorRequest,54 MonitorSummary, NotCollected, OcrRequest, Page, ResultItem, ResultsPage, ScrapeRequest, ScreenshotRequest,55 SearchHit, SearchRequest, SiteGraph, VisionRequest,56} from "./types.js";57import { USER_AGENT } from "./version.js";5859export interface SpiderOptions {60 /** Origin (and optional path prefix) of the gateway, e.g. `https://spider.example.org`. */61 baseUrl: string;62 /** Sent only in the `Authorization` header; never in a URL, a log or an error message. */63 apiKey: string;64 /** Time allowed for one HTTP exchange (default 30 000 ms). Event streams have no body timeout. */65 timeoutMs?: number;66 /** Retries after the first attempt (default 3). */67 maxRetries?: number;68 backoffBaseMs?: number;69 backoffMaxMs?: number;70 /** A `Retry-After` longer than this is not waited for; the error is thrown (default 120 000 ms). */71 maxRetryAfterMs?: number;72 /** Appended to `spider-sdk-typescript/<version>`. */73 userAgent?: string;74 fetch?: typeof globalThis.fetch;75 /** Replaces the wait between attempts (tests). */76 sleep?: (ms: number) => Promise<void>;77}7879/** Options of a job submission. */80export interface SubmitOptions {81 /** Defaults to a fresh UUID, reused by every retry of this call. */82 idempotencyKey?: string;83 signal?: AbortSignal;84}8586export interface CallOptions {87 signal?: AbortSignal;88}8990export interface WaitOptions extends CallOptions {91 /** Default 300 000 ms. */92 timeoutMs?: number;93 pollIntervalMs?: number;94 maxPollIntervalMs?: number;95 /** Follow the event stream instead of polling. */96 useEvents?: boolean;97}9899export interface ResultsOptions extends CallOptions {100 limit?: number;101 cursor?: string;102 includeEvidence?: boolean;103 includeContent?: boolean;104 maskPii?: boolean;105}106107export interface RequestOptions extends CallOptions {108 body?: unknown;109 query?: Record<string, string | number | boolean | null | undefined>;110 headers?: Record<string, string>;111 idempotencyKey?: string;112}113114type Query = Record<string, string | number | boolean | null | undefined>;115116interface SendOptions {117 query?: Query | undefined;118 body?: unknown;119 headers?: Record<string, string> | undefined;120 retry: RetryClass;121 signal?: AbortSignal | undefined;122 stream?: boolean;123}124125const NEVER_CONNECTED = new Set([126 "ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT",127]);128const MANDATORY_POLICIES = ["respect_robots_txt", "stop_on_access_denied"] as const;129const RETRY_STATUSES = new Set([502, 503, 504]);130131const defaultSleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));132133export function isTerminal(job: { status: string }): boolean {134 return (TERMINAL_JOB_STATES as readonly string[]).includes(job.status);135}136137/** Refuse, before sending, a typed request that tries to disable a mandatory policy (also nested ones). */138function guardPolicies(body: unknown): void {139 if (body === null || typeof body !== "object") return;140 const o = body as Record<string, unknown>;141 const policy = o["policy"];142 if (policy !== null && typeof policy === "object") {143 for (const name of MANDATORY_POLICIES) {144 const v = (policy as Record<string, unknown>)[name];145 if (v !== undefined && v !== true) {146 throw new TypeError(`${name} is a mandatory policy of SPIDER and cannot be disabled`);147 }148 }149 }150 if (o["request"] !== undefined) guardPolicies(o["request"]);151 if (Array.isArray(o["items"])) for (const item of o["items"]) guardPolicies(item);152}153154function errorCode(e: unknown): string {155 for (let cur: unknown = e, depth = 0; cur !== null && typeof cur === "object" && depth < 4; depth++) {156 const code = (cur as { code?: unknown }).code;157 if (typeof code === "string") return code;158 cur = (cur as { cause?: unknown }).cause;159 }160 return "";161}162163export class Spider {164 readonly baseUrl: string;165 readonly maxRetries: number;166 readonly #apiKey: string;167 readonly #timeoutMs: number;168 readonly #backoffBaseMs: number;169 readonly #backoffMaxMs: number;170 readonly #maxRetryAfterMs: number;171 readonly #userAgent: string;172 readonly #fetch: typeof globalThis.fetch;173 readonly #sleep: (ms: number) => Promise<void>;174175 /**176 * Retries (at most `maxRetries`, exponential backoff with jitter, `Retry-After` honoured):177 * connection errors, 429 and 502/503/504 only. A job submission is retried because the SDK sends178 * an `Idempotency-Key` generated once per call and reused by every retry of that call, so a179 * submission whose answer was lost is replayed by the server, not duplicated. No other 4xx is180 * ever retried. Redirects are not followed: the key is never sent to another origin.181 */182 constructor(options: SpiderOptions) {183 let u: URL;184 try {185 u = new URL(options.baseUrl);186 } catch {187 throw new TypeError("baseUrl must be an http(s) URL");188 }189 if (u.protocol !== "http:" && u.protocol !== "https:") throw new TypeError("baseUrl must be an http(s) URL");190 if (u.username || u.password || u.search || u.hash) {191 throw new TypeError("baseUrl must not carry credentials, a query string or a fragment");192 }193 if (!options.apiKey || /\s/.test(options.apiKey)) throw new TypeError("apiKey is required");194 this.baseUrl = options.baseUrl.replace(/\/+$/, "");195 this.#apiKey = options.apiKey;196 this.#timeoutMs = options.timeoutMs ?? 30_000;197 this.maxRetries = Math.max(0, Math.trunc(options.maxRetries ?? 3));198 this.#backoffBaseMs = options.backoffBaseMs ?? 500;199 this.#backoffMaxMs = options.backoffMaxMs ?? 20_000;200 this.#maxRetryAfterMs = options.maxRetryAfterMs ?? 120_000;201 this.#userAgent = options.userAgent ? `${USER_AGENT} ${options.userAgent}` : USER_AGENT;202 this.#fetch = options.fetch ?? globalThis.fetch;203 this.#sleep = options.sleep ?? defaultSleep;204 }205206 toJSON(): { baseUrl: string } {207 return { baseUrl: this.baseUrl }; // the key is a private field: it never serialises208 }209210 // ------------------------------------------------------------------ transport211 #delay(attempt: number, retryAfterSeconds: number | null): number {212 if (retryAfterSeconds !== null) return retryAfterSeconds * 1000;213 return Math.min(this.#backoffMaxMs, this.#backoffBaseMs * 2 ** attempt) * (0.5 + Math.random() / 2);214 }215216 #url(path: string, query?: Query): string {217 const qs = new URLSearchParams();218 for (const [k, v] of Object.entries(query ?? {})) if (v !== undefined && v !== null) qs.set(k, String(v));219 const s = qs.toString();220 return this.baseUrl + path + (s ? `?${s}` : "");221 }222223 async #send(method: string, path: string, o: SendOptions): Promise<Response> {224 const url = this.#url(path, o.query);225 const headers: Record<string, string> = {226 Accept: "application/json", ...o.headers, Authorization: `Bearer ${this.#apiKey}`, "User-Agent": this.#userAgent,227 };228 const payload = o.body === undefined ? undefined : JSON.stringify(o.body);229 if (payload !== undefined) headers["Content-Type"] = "application/json";230 for (let attempt = 0; ; attempt++) {231 let error: Error;232 let retryable: boolean;233 let retryAfter: number | null = null;234 const ctl = new AbortController();235 const onAbort = (): void => ctl.abort(o.signal?.reason);236 if (o.signal?.aborted) throw o.signal.reason;237 o.signal?.addEventListener("abort", onAbort, { once: true });238 let timedOut = false;239 let streaming = false;240 const timer = setTimeout(() => {241 timedOut = true;242 ctl.abort();243 }, this.#timeoutMs);244 try {245 const init: RequestInit = { method, headers, redirect: "manual", signal: ctl.signal };246 if (payload !== undefined) init.body = payload;247 const resp = await this.#fetch(url, init);248 if (resp.status < 400) {249 if (o.stream) {250 streaming = true; // headers arrived; the body stays bound to the caller's signal, not to the timeout251 return resp;252 }253 const buf = await resp.arrayBuffer(); // read under the timeout, then hand over a detached copy254 const empty = [204, 205, 304].includes(resp.status);255 return new Response(empty ? null : buf, { status: resp.status, headers: resp.headers });256 }257 const text = await resp.text();258 let body: unknown;259 try {260 body = JSON.parse(text);261 } catch {262 body = undefined;263 }264 const apiError = errorFromResponse(resp.status, body, resp.headers, text);265 error = apiError;266 retryAfter = apiError.retryAfterSeconds;267 retryable = resp.status === 429268 ? !(apiError instanceof QuotaExceededError && retryAfter === null) // refused before any processing269 : RETRY_STATUSES.has(resp.status) && o.retry !== "unsafe";270 } catch (e) {271 if (o.signal?.aborted) throw o.signal.reason;272 const code = timedOut ? "timeout" : errorCode(e) || (e instanceof Error ? e.name : "error");273 error = new TransportError(`${code}: ${method} ${path}`);274 // a connection that was never established cannot have reached the application275 retryable = NEVER_CONNECTED.has(code) || o.retry !== "unsafe";276 } finally {277 clearTimeout(timer);278 if (!streaming) o.signal?.removeEventListener("abort", onAbort);279 }280 if (!retryable || attempt >= this.maxRetries || (retryAfter ?? 0) * 1000 > this.#maxRetryAfterMs) throw error;281 await this.#sleep(this.#delay(attempt, retryAfter));282 }283 }284285 static #path(route: RouteName, params: Record<string, string> = {}): string {286 return ROUTES[route].path.replace(/\{(\w+)\}/g, (_, name: string) => {287 const v = params[name];288 if (v === undefined || v === "") throw new TypeError(`${name} is required`);289 return encodeURIComponent(v);290 });291 }292293 async #call<T>(route: RouteName, o: { params?: Record<string, string>; query?: Query; body?: unknown;294 idempotencyKey?: string | undefined; signal?: AbortSignal | undefined } = {}): Promise<T> {295 const r = ROUTES[route];296 if (o.body !== undefined) guardPolicies(o.body);297 const headers = r.retry === "keyed" ? { "Idempotency-Key": o.idempotencyKey ?? randomUUID() } : undefined;298 const resp = await this.#send(r.method, Spider.#path(route, o.params), {299 query: o.query, body: o.body, headers, retry: r.retry, signal: o.signal,300 });301 return (await resp.json()) as T;302 }303304 /**305 * Low-level escape hatch: any endpoint, same authentication, errors and retry policy. The body306 * is sent as given (no typed check). GET, HEAD, PUT and DELETE are retried as safe requests; a307 * POST is retried on 5xx/transport errors only if `idempotencyKey` is given.308 */309 async request<T = unknown>(method: string, path: string, options: RequestOptions = {}): Promise<T> {310 const m = method.toUpperCase();311 const headers = { ...options.headers };312 if (options.idempotencyKey) headers["Idempotency-Key"] = options.idempotencyKey;313 const hasKey = Object.keys(headers).some((k) => k.toLowerCase() === "idempotency-key");314 const retry: RetryClass = ["GET", "HEAD", "PUT", "DELETE"].includes(m) ? "safe" : hasKey ? "keyed" : "unsafe";315 const resp = await this.#send(m, path, { query: options.query, body: options.body, headers, retry, signal: options.signal });316 if ((resp.headers.get("content-type") ?? "").includes("json")) return (await resp.json()) as T;317 return new Uint8Array(await resp.arrayBuffer()) as T;318 }319320 #submit(route: RouteName, body: unknown, o: SubmitOptions = {}): Promise<Job> {321 return this.#call<Job>(route, { body, idempotencyKey: o.idempotencyKey, signal: o.signal });322 }323324 // ------------------------------------------------------------------ job submissions (202)325 /** Collect one page. */326 scrape(request: ScrapeRequest, options?: SubmitOptions): Promise<Job> {327 return this.#submit("scrape", request, options);328 }329330 /** Multi-page exploration from a URL, a list of URLs or a sitemap, bounded by budgets. */331 crawl(request: CrawlRequest, options?: SubmitOptions): Promise<Job> {332 if (!request.url && !request.urls?.length && !request.sitemap) {333 return Promise.reject(new TypeError("one of url, urls or sitemap is required"));334 }335 return this.#submit("crawl", request, options);336 }337338 /** Discover the URL graph of a site without storing page content. */339 map(request: MapRequest, options?: SubmitOptions): Promise<Job> {340 return this.#submit("map", request, options);341 }342343 /** Targeted capture (viewport, full page, tiles, elements). */344 screenshot(request: ScreenshotRequest, options?: SubmitOptions): Promise<Job> {345 return this.#submit("screenshot", request, options);346 }347348 /** Tiled capture and exploration of interactive states. */349 deepCapture(request: DeepCaptureRequest, options?: SubmitOptions): Promise<Job> {350 return this.#submit("deepCapture", request, options);351 }352353 /** Schema-driven extraction with per-field evidence. */354 extract(request: ExtractRequest, options?: SubmitOptions): Promise<Job> {355 return this.#submit("extract", request, options);356 }357358 /** OCR of a stored image artifact. */359 ocr(request: OcrRequest, options?: SubmitOptions): Promise<Job> {360 return this.#submit("ocr", request, options);361 }362363 /** Local multimodal analysis of stored image artifacts. */364 vision(request: VisionRequest, options?: SubmitOptions): Promise<Job> {365 return this.#submit("vision", request, options);366 }367368 /** Submit independent jobs at once. */369 batch(items: BatchItem[], options: SubmitOptions = {}): Promise<BatchResponse> {370 return this.#call<BatchResponse>("batch", { body: { items }, idempotencyKey: options.idempotencyKey, signal: options.signal });371 }372373 // ------------------------------------------------------------------ watch and search374 /** Create a recurring watch. The API takes no idempotency key here: not retried after an ambiguous failure. */375 createMonitor(request: MonitorRequest, options: CallOptions = {}): Promise<Monitor> {376 return this.#call<Monitor>("createMonitor", { body: request, signal: options.signal });377 }378379 /** Compare two snapshots (text, layout, fields, pixels). */380 diff(request: DiffRequest, options: CallOptions = {}): Promise<DiffResult> {381 return this.#call<DiffResult>("diff", { body: request, signal: options.signal });382 }383384 /** One page of full-text search in the tenant's own corpus. */385 search(request: SearchRequest, options: CallOptions = {}): Promise<Page<SearchHit>> {386 return this.#call<Page<SearchHit>>("search", { body: request, signal: options.signal });387 }388389 /** Every search hit, following `next_cursor`. */390 async *iterSearch(request: Omit<SearchRequest, "cursor">, options: CallOptions = {}): AsyncGenerator<SearchHit, void, undefined> {391 let cursor: string | null = null;392 do {393 const page: Page<SearchHit> = await this.search(cursor ? { ...request, cursor } : request, options);394 yield* page.items;395 cursor = page.next_cursor ?? null;396 } while (cursor);397 }398399 // ------------------------------------------------------------------ jobs400 getJob(jobId: string, options: CallOptions = {}): Promise<Job> {401 return this.#call<Job>("getJob", { params: { job_id: jobId }, signal: options.signal });402 }403404 /** One page of jobs, newest first. */405 listJobs(filter: { status?: string; kind?: string; limit?: number; cursor?: string } = {}, options: CallOptions = {}): Promise<Page<Job>> {406 return this.#call<Page<Job>>("listJobs", { query: filter, signal: options.signal });407 }408409 /** Every job, following `next_cursor`. */410 async *iterJobs(filter: { status?: string; kind?: string; pageSize?: number } = {}, options: CallOptions = {}): AsyncGenerator<Job, void, undefined> {411 let cursor: string | null = null;412 do {413 const q: { status?: string; kind?: string; limit?: number; cursor?: string } = {};414 if (filter.status !== undefined) q.status = filter.status;415 if (filter.kind !== undefined) q.kind = filter.kind;416 if (filter.pageSize !== undefined) q.limit = filter.pageSize;417 if (cursor) q.cursor = cursor;418 const page: Page<Job> = await this.listJobs(q, options);419 yield* page.items;420 cursor = page.next_cursor ?? null;421 } while (cursor);422 }423424 cancelJob(jobId: string, options: CallOptions = {}): Promise<Job> {425 return this.#call<Job>("cancelJob", { params: { job_id: jobId }, signal: options.signal });426 }427428 pauseJob(jobId: string, options: CallOptions = {}): Promise<Job> {429 return this.#call<Job>("pauseJob", { params: { job_id: jobId }, signal: options.signal });430 }431432 resumeJob(jobId: string, options: CallOptions = {}): Promise<Job> {433 return this.#call<Job>("pauseJob", { params: { job_id: jobId }, query: { resume: true }, signal: options.signal });434 }435436 /** Re-queue the failed URLs of a finished job as a new job (never retried automatically). */437 retryJob(jobId: string, options: CallOptions = {}): Promise<Job> {438 return this.#call<Job>("retryJob", { params: { job_id: jobId }, signal: options.signal });439 }440441 /** One page of results (`items`, `not_collected`, `complete`, `next_cursor`). */442 getResults(jobId: string, options: ResultsOptions = {}): Promise<ResultsPage> {443 return this.#call<ResultsPage>("getResults", {444 params: { job_id: jobId },445 query: {446 limit: options.limit, cursor: options.cursor, include_evidence: options.includeEvidence,447 include_content: options.includeContent, mask: options.maskPii ? "pii" : undefined,448 },449 signal: options.signal,450 });451 }452453 /** Every result of a job, page after page, following `next_cursor`. */454 async *iterResults(jobId: string, options: Omit<ResultsOptions, "cursor" | "limit"> & { pageSize?: number } = {}): AsyncGenerator<ResultItem, void, undefined> {455 const { pageSize, ...rest } = options;456 let cursor: string | null = null;457 do {458 const o: ResultsOptions = { ...rest };459 if (pageSize !== undefined) o.limit = pageSize;460 if (cursor) o.cursor = cursor;461 const page: ResultsPage = await this.getResults(jobId, o);462 yield* page.items;463 cursor = page.next_cursor ?? null;464 } while (cursor);465 }466467 /**468 * Server-sent events of a job, ending after `job.finished`. A dropped stream is resumed with469 * `Last-Event-ID` (at most `maxRetries` consecutive reconnections without an event), so no event470 * is lost or repeated.471 */472 async *streamEvents(jobId: string, options: CallOptions & { lastEventId?: string; reconnect?: boolean } = {}): AsyncGenerator<JobEvent, void, undefined> {473 const r = ROUTES.streamEvents;474 const path = Spider.#path("streamEvents", { job_id: jobId });475 let lastEventId = options.lastEventId ?? null;476 const reconnect = options.reconnect ?? true;477 for (let failures = 0; ; ) {478 const headers: Record<string, string> = { Accept: "text/event-stream" };479 if (lastEventId) headers["Last-Event-ID"] = lastEventId;480 const resp = await this.#send(r.method, path, { headers, retry: r.retry, signal: options.signal, stream: true });481 const parser = new SSEParser();482 const decoder = new TextDecoder();483 let got = false;484 const reader = resp.body?.getReader();485 try {486 for (;;) {487 const chunk = await reader?.read();488 if (!chunk || chunk.done) break;489 for (const ev of parser.feed(decoder.decode(chunk.value, { stream: true }))) {490 got = true;491 lastEventId = ev.id ?? lastEventId;492 yield ev;493 if (ev.type === "job.finished") return;494 }495 }496 } catch (e) {497 if (options.signal?.aborted) throw options.signal.reason;498 if (!reconnect) throw new TransportError(`${errorCode(e) || "stream_error"}: event stream of job ${jobId}`);499 } finally {500 await reader?.cancel().catch(() => undefined);501 }502 if (!reconnect) return;503 failures = got ? 0 : failures + 1;504 if (failures > this.maxRetries) {505 throw new TransportError(`event stream of job ${jobId} ended ${failures} times without an event`);506 }507 await this.#sleep(this.#delay(failures, null));508 }509 }510511 /**512 * Wait until the job is terminal (partial, succeeded, failed, cancelled, blocked). Polls with a513 * growing interval, or follows the event stream with `useEvents`. Throws `JobTimeoutError` after514 * `timeoutMs`; the job is not cancelled.515 */516 async waitForJob(jobId: string, options: WaitOptions = {}): Promise<Job> {517 const timeoutMs = options.timeoutMs ?? 300_000;518 const deadline = Date.now() + timeoutMs;519 let last: string | null = null;520 if (options.useEvents) {521 const ctl = new AbortController();522 const onAbort = (): void => ctl.abort(options.signal?.reason);523 options.signal?.addEventListener("abort", onAbort, { once: true });524 const timeout = new JobTimeoutError(jobId, last, timeoutMs);525 const timer = setTimeout(() => ctl.abort(timeout), timeoutMs);526 try {527 for await (const ev of this.streamEvents(jobId, { signal: ctl.signal })) void ev;528 } finally {529 clearTimeout(timer);530 options.signal?.removeEventListener("abort", onAbort);531 }532 }533 let delay = options.pollIntervalMs ?? 500;534 const maxDelay = options.maxPollIntervalMs ?? 5_000;535 for (;;) {536 const job = await this.getJob(jobId, options);537 if (isTerminal(job)) return job;538 last = job.status;539 const remaining = deadline - Date.now();540 if (remaining <= 0) throw new JobTimeoutError(jobId, last, timeoutMs);541 await this.#sleep(Math.min(delay, remaining));542 delay = Math.min(maxDelay, delay * 1.5);543 }544 }545546 /** Wait for a job (id or accepted job), then gather every result page. */547 async collect(job: string | { job_id: string }, options: WaitOptions & { pageSize?: number } = {}): Promise<JobResult> {548 const jobId = typeof job === "string" ? job : job.job_id;549 const final = await this.waitForJob(jobId, options);550 const results: ResultItem[] = [];551 const notCollected: NotCollected[] = [];552 let cursor: string | null = null;553 do {554 const o: ResultsOptions = {};555 if (options.pageSize !== undefined) o.limit = options.pageSize;556 if (cursor) o.cursor = cursor;557 if (options.signal) o.signal = options.signal;558 const page: ResultsPage = await this.getResults(jobId, o);559 results.push(...page.items);560 notCollected.push(...(page.not_collected ?? []));561 cursor = page.next_cursor ?? null;562 } while (cursor);563 return { job: final, results, notCollected };564 }565566 /** `scrape` + `collect`. */567 async scrapeAndWait(request: ScrapeRequest, options: WaitOptions & SubmitOptions = {}): Promise<JobResult> {568 return this.collect(await this.scrape(request, options), options);569 }570571 /** `crawl` + `collect`. */572 async crawlAndWait(request: CrawlRequest, options: WaitOptions & SubmitOptions & { pageSize?: number } = {}): Promise<JobResult> {573 return this.collect(await this.crawl(request, options), options);574 }575576 /** `extract` + `collect`. */577 async extractAndWait(request: ExtractRequest, options: WaitOptions & SubmitOptions = {}): Promise<JobResult> {578 return this.collect(await this.extract(request, options), options);579 }580581 /** Export the results of a job as bytes (jsonl, csv, markdown, html or zip). */582 async export(jobId: string, options: CallOptions & { format?: ExportFormat; maskPii?: boolean } = {}): Promise<Uint8Array> {583 const r = ROUTES.export;584 const resp = await this.#send(r.method, Spider.#path("export", { job_id: jobId }), {585 query: { format: options.format ?? "jsonl", mask: options.maskPii ? "pii" : undefined },586 headers: { Accept: "*/*" }, retry: r.retry, signal: options.signal,587 });588 return new Uint8Array(await resp.arrayBuffer());589 }590591 // ------------------------------------------------------------------ artifacts and snapshots592 /**593 * Download an artifact and verify it against the `X-Spider-Sha256` response header. Throws594 * `ArtifactIntegrityError` when the header is missing or does not match the bytes (or595 * `expectedSha256`, e.g. the `sha256` listed in a result item, when given).596 */597 async getArtifact(artifactId: string, options: CallOptions & { expectedSha256?: string } = {}): Promise<Uint8Array> {598 const r = ROUTES.getArtifact;599 const resp = await this.#send(r.method, Spider.#path("getArtifact", { artifact_id: artifactId }), {600 headers: { Accept: "*/*" }, retry: r.retry, signal: options.signal,601 });602 const data = new Uint8Array(await resp.arrayBuffer());603 const actual = createHash("sha256").update(data).digest("hex");604 const announced = resp.headers.get("x-spider-sha256")?.trim().toLowerCase() || null;605 if (announced !== actual) throw new ArtifactIntegrityError(artifactId, announced, actual);606 if (options.expectedSha256 !== undefined && options.expectedSha256.toLowerCase() !== actual) {607 throw new ArtifactIntegrityError(artifactId, options.expectedSha256, actual);608 }609 return data;610 }611612 getSnapshot(snapshotId: string, options: CallOptions = {}): Promise<ResultItem> {613 return this.#call<ResultItem>("getSnapshot", { params: { snapshot_id: snapshotId }, signal: options.signal });614 }615616 /** Snapshots of a URL, newest first. */617 snapshotHistory(url: string, options: CallOptions & { limit?: number } = {}): Promise<{ url: string; items: JsonObject[] }> {618 return this.#call("snapshotHistory", { query: { url, limit: options.limit }, signal: options.signal });619 }620621 // ------------------------------------------------------------------ sites622 listSites(options: CallOptions = {}): Promise<{ items: JsonObject[] }> {623 return this.#call("listSites", { signal: options.signal });624 }625626 /** One page of the URL graph (`nodes`, `edges`, `next_cursor`). */627 siteGraph(siteId: string, options: CallOptions & { jobId?: string; limit?: number; cursor?: string } = {}): Promise<SiteGraph> {628 return this.#call<SiteGraph>("siteGraph", {629 params: { site_id: siteId }, query: { job_id: options.jobId, limit: options.limit, cursor: options.cursor },630 signal: options.signal,631 });632 }633634 siteCoverage(siteId: string, options: CallOptions & { jobId?: string } = {}): Promise<JsonObject> {635 return this.#call<JsonObject>("siteCoverage", { params: { site_id: siteId }, query: { job_id: options.jobId }, signal: options.signal });636 }637638 // ------------------------------------------------------------------ system and admin helpers639 health(options: CallOptions = {}): Promise<Health> {640 return this.#call<Health>("health", { signal: options.signal });641 }642643 me(options: CallOptions = {}): Promise<JsonObject> {644 return this.#call<JsonObject>("me", { signal: options.signal });645 }646647 listMonitors(options: CallOptions = {}): Promise<{ items: MonitorSummary[] }> {648 return this.#call("listMonitors", { signal: options.signal });649 }650651 monitorAction(scheduleId: string, action: MonitorAction, options: CallOptions = {}): Promise<{ schedule_id: string; action: string }> {652 if (!["enable", "disable", "run-now", "delete"].includes(action)) {653 return Promise.reject(new TypeError("action must be enable, disable, run-now or delete"));654 }655 return this.#call("monitorAction", { params: { schedule_id: scheduleId, action }, signal: options.signal });656 }657658 /** Change events detected by monitors, newest first. */659 listChanges(filter: { scheduleId?: string; limit?: number } = {}, options: CallOptions = {}): Promise<{ items: ChangeEvent[] }> {660 return this.#call("listChanges", { query: { schedule_id: filter.scheduleId, limit: filter.limit }, signal: options.signal });661 }662663 /** The tenant's webhook signing secret (admin scope). Treat it as a credential. */664 async webhookSecret(options: CallOptions = {}): Promise<string> {665 return (await this.#call<{ secret: string }>("webhookSecret", { signal: options.signal })).secret;666 }667}668669export { ApiError };670