SPB Git

Repository Public

README.md 8.0 KB

# SPIDER SDK for TypeScript

Client of the SPIDER web-intelligence API. Promise-based, strict types, ESM, zero runtime dependencies (Node's built-in fetch and node:crypto), Node 20 or later.

Package name: @spboucher/spider-sdk (private; nothing is published to a registry).

# Install from the repository

bash
cd sdk/typescript
pnpm install          # dev dependencies only: typescript, @types/node
pnpm run build        # tsc → dist/ (ESM + .d.ts)
pnpm test             # build, then node --test test/

Use it from another project with a path dependency:

jsonc
// package.json of your project
{ "dependencies": { "@spboucher/spider-sdk": "file:../spider/sdk/typescript" } }

# Quickstart

ts
import { Spider } from "@spboucher/spider-sdk";

const spider = new Spider({
  baseUrl: "https://spider.example.org",
  apiKey: process.env.SPIDER_API_KEY!,     // sent only in the Authorization header
  userAgent: "my-app/1.0",                 // → "spider-sdk-typescript/0.1.0 my-app/1.0"
  timeoutMs: 30_000,
});

const { job, results, notCollected } = await spider.scrapeAndWait(
  { url: "https://example.org/about", extract: { formats: ["markdown", "json"] } },
  { timeoutMs: 120_000 },
);
console.log(job.status, results[0]?.content?.markdown);

Job endpoints answer immediately with an accepted job (job_id, status_url, results_url, events_url); the work is asynchronous:

ts
const job = await spider.crawl({ url: "https://example.org/", budgets: { max_pages: 200, max_depth: 3 } });
const final = await spider.waitForJob(job.job_id, { timeoutMs: 900_000 });   // polling with backoff
// states: queued, running → partial | succeeded | failed | cancelled | blocked

Collect only sources you are authorised to collect.

# Methods

Area Methods
Submit (202) scrape, crawl, map, screenshot, deepCapture, extract, ocr, vision, batch
Convenience scrapeAndWait, crawlAndWait, extractAndWait, collect(job) → { job, results, notCollected }
Jobs getJob, listJobs, iterJobs, cancelJob, pauseJob, resumeJob, retryJob, waitForJob, streamEvents
Results getResults (one page), iterResults (all), export (bytes: jsonl, csv, markdown, html, zip)
Artifacts, snapshots getArtifact (hash-verified bytes), getSnapshot, snapshotHistory
Watch, search createMonitor, listMonitors, monitorAction, listChanges, diff, search, iterSearch
Sites, system listSites, siteGraph, siteCoverage, health, me, webhookSecret
Low level request(method, path, { body, query, headers, idempotencyKey })

# Mandatory policies

SPIDER always honours robots.txt and always stops on an access denial (login wall, CAPTCHA, paywall, 401/403). These are enforced by the server and the SDK offers no option to disable them: PolicyOptions has no respect_robots_txt or stop_on_access_denied field, and a typed call that smuggles one in as false is refused locally with a TypeError. Through the low-level request the server answers 422 mandatory_policy, surfaced as MandatoryPolicyError.

# Pagination

List endpoints return { items, next_cursor }. Use the one-page methods to drive it yourself, or the AsyncIterable helpers, which follow next_cursor until it is null:

ts
const page = await spider.getResults(job.job_id, { limit: 50 });            // one page
for await (const item of spider.iterResults(job.job_id, { pageSize: 50 })) { // every result
  console.log(item.url, item.record?.status);
}
for await (const j of spider.iterJobs({ kind: "crawl" })) console.log(j.job_id, j.status);
for await (const hit of spider.iterSearch({ query: "installation" })) console.log(hit.url);

Results are available while a job is running.

# Events (SSE)

ts
for await (const ev of spider.streamEvents(job.job_id)) {
  console.log(ev.id, ev.type, ev.data);          // ends after "job.finished"
}
const final = await spider.waitForJob(job.job_id, { useEvents: true });

A dropped stream is resumed with Last-Event-ID, so no event is lost or repeated. Pass { signal } (an AbortSignal) to stop early.

# Errors

Every API error ({"error": {code, message, details, request_id}}) is an ApiError with status, code, message, details, requestId and retryAfterSeconds:

Class When
AuthenticationError, PermissionDeniedError (both AuthError) 401, 403
ValidationError 400, 422
MandatoryPolicyError (a ValidationError) 422 mandatory_policy
NotFoundError 404
ConflictError, IdempotencyConflictError 409, 409 idempotency_conflict
RateLimitError, QuotaExceededError 429 rate_limited, 429 quota_exceeded
ServerError 5xx

Outside the API: TransportError (connection or timeout after the allowed retries), JobTimeoutError (waitForJob gave up; the job keeps running), ArtifactIntegrityError, WebhookVerificationError. All extend SpiderError.

ts
try {
  await spider.getJob(id);
} catch (e) {
  if (e instanceof NotFoundError) console.error(e.code, e.requestId);
  else throw e;
}

# Retries and idempotency

  • Retried: connection errors, 429 (waiting Retry-After, else details.retry_after_s) and 502/503/504, with exponential backoff and jitter, at most maxRetries times (default 3).
  • Never retried: any other 4xx, 500, and a 429 quota_exceeded that carries no delay.
  • Job submissions are retried only because they are idempotent: the SDK generates one Idempotency-Key (UUID) per call and reuses it for every retry of that call, so a submission whose answer was lost returns the same job (idempotent_replay: true) instead of creating a second one. Pass { idempotencyKey } to make your own retries (after a crash, for instance) just as safe.
  • createMonitor, retryJob and monitorAction take no idempotency key in the API: they are retried only when the request provably did not reach the application (connection never established, or 429).
  • request("POST", …) follows the same rule: retried on 5xx/transport errors only with an idempotencyKey.
  • Redirects are not followed, so the API key is never sent to another origin.

# Webhook verification

SPIDER signs <X-Spider-Timestamp>.<X-Spider-Delivery>.<raw body> with HMAC-SHA256 and sends X-Spider-Signature: v1=<hex>. The secret is per tenant (await spider.webhookSecret(), admin scope).

ts
import { createServer } from "node:http";
import { WebhookVerificationError, parseWebhook } from "@spboucher/spider-sdk";

const seen = new Set<string>();
createServer((req, res) => {
  const chunks: Buffer[] = [];
  req.on("data", (c) => chunks.push(c));
  req.on("end", () => {
    try {
      // the raw bytes, exactly as received; default tolerance 300 s
      const payload = parseWebhook(process.env.SPIDER_WEBHOOK_SECRET!, req.headers, Buffer.concat(chunks));
      const delivery = String(req.headers["x-spider-delivery"]);
      if (!seen.has(delivery)) { seen.add(delivery); handle(payload); }   // process a delivery id once
      res.writeHead(204).end();
    } catch (e) {
      res.writeHead(e instanceof WebhookVerificationError ? 401 : 500).end();
    }
  });
}).listen(8787);

verifyWebhook(secret, headers, rawBody, toleranceSeconds = 300) compares in constant time, rejects timestamps outside the tolerance and returns the delivery id; it throws WebhookVerificationError with a reason (missing_header, bad_timestamp, timestamp_out_of_tolerance, unsupported_version, bad_signature).

# Tests

  • test/client.test.mjs: retries, idempotency reuse, pagination, SSE parsing, artifacts, error mapping, against a local mock HTTP server.
  • test/webhooks.test.mjs: vectors computed with openssl dgst -sha256 -hmac.
  • test/contract.test.mjs: loads ../../docs/openapi.json; every route exists, every method's real requests (path, query parameters, Idempotency-Key, JSON body) match the operation described.
  • tests/integration/test_sdk_typescript.py (repository root) runs scripts/live.mjs against the in-process test stack.
Files main
Menu

Theme