@crawlbrulee/sdk 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -118,7 +118,7 @@ const page = await crawlbrulee.scrape({
118
118
  device_mode: 'desktop',
119
119
  },
120
120
  },
121
- // Shapes markdown, cleaned_html, links, images AND the screenshot.
121
+ // Shapes markdown, cleaned_html, links, images, elements AND the screenshot.
122
122
  // Never touches raw_html — that is always the page before any removal.
123
123
  cleanup: {
124
124
  ads_and_popups: true,
@@ -178,19 +178,53 @@ notes:
178
178
  - **`warnings`**: when we complete a scrape but something is worth flagging, the codes land on `page.warnings`, in two
179
179
  families. capped output: `screenshot_truncated` (a long page exceeded the scrolling-screenshot height cap),
180
180
  `links_truncated` (more than 30 000 links), `inline_images_truncated` (more than 10 000 inline images),
181
- `raw_html_truncated` (more than 10 000 000 characters of body html), and `metadata_truncated` (more than 2 000 000
182
- characters of `<head>` html, so some metadata may be missing). failed extraction of one section: `links_unavailable`,
183
- `inline_images_unavailable`, and `metadata_unavailable` — the field comes back omitted or empty while the rest of the
184
- scrape succeeds, which is how you tell "the page had none" from "we couldn't read them". they're stable, so you can
185
- switch on them — the union is exported as `ScrapeWarningCode`. warnings are stored with the result, so cache hits and
186
- async result fetches report them too, filtered to the outputs you asked for.
187
- - **`unsupported_fields`**: if you request an extract that doesn't apply to the content type (e.g. `markdown` of a pdf),
181
+ `raw_html_truncated` (more than 10 000 000 characters of body html), and `elements_truncated` (an `elements` value
182
+ hit a limit, see [elements](#elements)). failed extraction of one section: `links_unavailable`,
183
+ `inline_images_unavailable`, `metadata_unavailable`, and `screenshot_unavailable` (a screenshot was asked for, but the
184
+ page came back without one) — the field comes back omitted or empty while the rest of the scrape succeeds, which is
185
+ how you tell "the page had none" from "we couldn't read them". they're stable, so you can switch on them — the union
186
+ is exported as `ScrapeWarningCode`. `metadata_truncated` is retired and no longer sent; only results stored before
187
+ that change can carry it. warnings are stored with the result, so cache hits and async result fetches report them
188
+ too, filtered to the outputs you asked for.
189
+ - **`unsupported_fields`**: if you request an extract that doesn't apply to the content type (e.g. `metadata` or `elements` of a json file),
188
190
  that field name comes back on `page.unsupported_fields` and the rest of your payload is still returned.
189
191
 
190
192
  see [`ScrapeRequest`](src/types/scrape.ts) and [`ScrapeResponse`](src/types/scrape.ts) for every field, with inline
191
193
  documentation — and the [scrape endpoint](https://crawlbrulee.com/docs/scrape) reference for the api-side contract those
192
194
  types mirror.
193
195
 
196
+ #### elements
197
+
198
+ `extract.elements` reads named values from the page by CSS selector. each key is a name you pick. each value is a
199
+ selector (the text of the first match) or a spec: `output` (`text`, `html` or `attribute`), `all: true` for every match
200
+ as a list, and `fields` to read several values inside each match. the values come back on `page.elements` under the
201
+ same names. a name with no match is `null`, or `[]` with `all: true`. it costs no extra credits.
202
+
203
+ ```ts
204
+ const page = await crawlbrulee.scrape({
205
+ url: 'https://books.toscrape.com/',
206
+ extract: {
207
+ elements: {
208
+ heading: 'h1',
209
+ books: {
210
+ selector: 'article.product_pod',
211
+ all: true,
212
+ fields: {
213
+ title: { selector: 'h3 a', output: 'attribute', attribute: 'title' },
214
+ price: '.price_color',
215
+ },
216
+ },
217
+ },
218
+ },
219
+ })
220
+
221
+ page.elements?.heading // 'All products'
222
+ page.elements?.books // [{ title: 'A Light in the Attic', price: '£51.77' }, …]
223
+ ```
224
+
225
+ the request types are `ScrapeElements` and `ScrapeElementSpec`; each value on `page.elements` is a
226
+ `ScrapeElementValue`. selector rules and limits: see [elements](https://crawlbrulee.com/docs/scrape/elements).
227
+
194
228
  #### zero data retention
195
229
 
196
230
  pass `zero_data_retention: true` on `scrape`, `scrapeAsync` or `map` to keep the result out of the shared cache. anything stored to deliver it is kept for 24 hours, then deleted. it adds 1 credit and must be enabled for your organization. see [zero data retention](https://crawlbrulee.com/docs/zero-data-retention).
package/dist/index.cjs CHANGED
@@ -12,7 +12,7 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 0;
12
12
  /** Environment variable read by `Crawlbrulee.fromEnv()` to source the API key. */
13
13
  const ENV_API_KEY = "CRAWLBRULEE_API_KEY";
14
14
  /** Identifies the SDK in the `User-Agent` header. Kept in one place for easy bumping. */
15
- const USER_AGENT = "@crawlbrulee/sdk/1.2.1 (node)";
15
+ const USER_AGENT = "@crawlbrulee/sdk/1.3.0 (node)";
16
16
 
17
17
  //#endregion
18
18
  //#region src/errors.ts
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":[],"sources":["../src/config.ts","../src/errors.ts","../src/instrumentation.ts","../src/http.ts","../src/client.ts","../src/webhooks.ts"],"sourcesContent":["/**\n * Production base URL of the crawlbrulee API. Used by default when the caller\n * doesn't pass a `baseUrl` to {@link Crawlbrulee}. Local development and\n * staging callers point at their own host via that option.\n */\nexport const DEFAULT_BASE_URL = 'https://api.crawlbrulee.com'\n\n/** Default request timeout when the caller doesn't specify one (0 disables the timeout). */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 0\n\n/** Environment variable read by `Crawlbrulee.fromEnv()` to source the API key. */\nexport const ENV_API_KEY = 'CRAWLBRULEE_API_KEY'\n\n/** Identifies the SDK in the `User-Agent` header. Kept in one place for easy bumping. */\nexport const USER_AGENT = '@crawlbrulee/sdk/1.2.1 (node)'\n","import type {\n ApiErrorDetails,\n ApiErrorName,\n ApiErrorResponse,\n RateLimitErrorDetails,\n UsageAllocationErrorDetails,\n} from './types/common.js'\n\n/**\n * Base error class for every failure raised by the SDK.\n *\n * Two kinds of failures end up here:\n *\n * 1. **API errors** — the server returned a non-2xx response with a well-formed\n * JSON body. In that case `status`, `errorName` and (sometimes) `details`\n * are populated.\n * 2. **Transport errors** — the request never produced a structured response\n * (network failure, abort, timeout, non-JSON body, etc.). In that case\n * `status` may be `0` and `errorName` is one of the synthetic transport\n * names (`request_timeout`, `client_closed_request`) or `null`.\n *\n * Typed subclasses are exported for the most common cases. To branch on more\n * specific server-side errors, switch on `err.errorName` or use the\n * {@link isCrawlbruleeError} helper.\n */\nexport class CrawlbruleeError extends Error {\n /** HTTP status code; `0` for transport-level failures with no response. */\n readonly status: number\n /** The `name` field from the API error body, or `null` for transport errors. */\n readonly errorName: ApiErrorName | null\n /** Structured detail block from the API error body, if any. */\n readonly details?: ApiErrorDetails\n /** The original parsed error body, when one was received. */\n readonly response?: ApiErrorResponse\n\n constructor(\n message: string,\n options: {\n status: number\n errorName: ApiErrorName | null\n details?: ApiErrorDetails\n response?: ApiErrorResponse\n cause?: unknown\n }\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined)\n this.name = 'CrawlbruleeError'\n this.status = options.status\n this.errorName = options.errorName\n this.details = options.details\n this.response = options.response\n }\n}\n\n/**\n * Raised when the API rejects your credentials — a missing, invalid, or\n * unauthorized API key (`invalid_credentials`, `access_denied`).\n *\n * Not every 403 is a key problem: a 403 carrying `antibot_blocked` is the\n * *target site* blocking us and raises {@link AntibotBlockedError} instead.\n * A 403 carrying `zero_data_retention_not_enabled` raises\n * {@link ZeroDataRetentionNotEnabledError}. Only an unrecognized 403 name falls\n * back to this class.\n */\nexport class AuthenticationError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'AuthenticationError'\n }\n}\n\n/**\n * Raised when the target site's anti-bot protection blocked the request\n * (HTTP 403, `antibot_blocked`). Not an API-key problem — retrying the same\n * tier rarely helps; try a higher proxy tier or skip the site.\n */\nexport class AntibotBlockedError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'AntibotBlockedError'\n }\n}\n\n/**\n * Raised when the target site redirected the request in a loop, or through\n * more hops than the API follows (HTTP 422, `too_many_redirects`). Like\n * {@link AntibotBlockedError} this is the target's doing — not a key problem\n * and not a bad request — so it is neither an `AuthenticationError` nor a\n * `ValidationError`. Retrying rarely helps. Returned by both `scrape` and `map`.\n */\nexport class TooManyRedirectsError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'TooManyRedirectsError'\n }\n}\n\n/**\n * Raised when the page's HTML was too large to process (HTTP 422,\n * `page_too_large`). Like {@link TooManyRedirectsError} this is about the page,\n * not your request — so it is neither an `AuthenticationError` nor a\n * `ValidationError`. It is terminal: the same URL fails the same way, so do not\n * retry it. Returned by `scrape`.\n */\nexport class PageTooLargeError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'PageTooLargeError'\n }\n}\n\n/**\n * Raised when we could not reach the target site at all (HTTP 502,\n * `target_unreachable`) — for example the site did not answer in time or its\n * TLS certificate was not valid. We never got a page, so there is nothing to\n * return and you are not charged. The message is always \"Could not reach the\n * target site.\" and there are no `details`.\n *\n * This is about the site, not your key or your request, so it is neither an\n * `AuthenticationError` nor a `ValidationError`. It is also not our own\n * outage ({@link ServiceUnavailableError}). Retrying later may help, since\n * the site may come back. The SDK does not retry for you.\n *\n * Not the same as a page with an error status: when the site answers with a\n * 404 or 503 page, the scrape succeeds and the site's status is in\n * `page_status_code`. Returned by both `scrape` and `map`.\n */\nexport class TargetUnreachableError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'TargetUnreachableError'\n }\n}\n\n/**\n * Raised when you send `zero_data_retention: true` but the option is not\n * enabled for your organization (HTTP 403, `zero_data_retention_not_enabled`).\n * The request is not billed. Not an API-key problem, so it is not an\n * {@link AuthenticationError}. See https://crawlbrulee.com/docs/zero-data-retention.\n */\nexport class ZeroDataRetentionNotEnabledError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'ZeroDataRetentionNotEnabledError'\n }\n}\n\n/**\n * Raised for HTTP 429 responses. When the server included a `retry_after_ms`\n * hint in `details` it is surfaced directly on the instance.\n *\n * `errorName` is always the literal `'too_many_requests'` — the SDK normalizes\n * this even when the server returns a 429 with a different `name` field. The\n * original body is still available on `response`.\n */\nexport class RateLimitError extends CrawlbruleeError {\n override readonly errorName: 'too_many_requests'\n /** Suggested delay (ms) before retrying, when the server provided one. */\n readonly retryAfterMs?: number\n /** Which rate limit was tripped (e.g. `org`, `ip`), when provided. */\n readonly limitedBy?: string\n\n constructor(\n message: string,\n options: {\n status: number\n details?: RateLimitErrorDetails\n response?: ApiErrorResponse\n }\n ) {\n super(message, { ...options, errorName: 'too_many_requests', details: options.details })\n this.name = 'RateLimitError'\n this.errorName = 'too_many_requests'\n this.retryAfterMs = options.details?.retry_after_ms\n this.limitedBy = options.details?.limited_by\n }\n}\n\n/**\n * Raised when the API rejects a request because the org's plan limits would\n * be exceeded (credit limit, concurrency cap, overage hard cap, etc.).\n *\n * `errorName` is always the literal `'usage_allocation_error'`.\n */\nexport class UsageAllocationError extends CrawlbruleeError {\n override readonly errorName: 'usage_allocation_error'\n /** Specific reason the allocation was denied. */\n readonly reason: UsageAllocationErrorDetails['reason']\n /** Current usage / limit snapshot at the time of the rejection. */\n readonly usage?: UsageAllocationErrorDetails['details']\n\n constructor(\n message: string,\n options: {\n status: number\n details: UsageAllocationErrorDetails\n response?: ApiErrorResponse\n }\n ) {\n super(message, { ...options, errorName: 'usage_allocation_error' })\n this.name = 'UsageAllocationError'\n this.errorName = 'usage_allocation_error'\n this.reason = options.details.reason\n this.usage = options.details.details\n }\n}\n\n/** Raised for 4xx responses caused by an invalid request shape or arguments. */\nexport class ValidationError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'ValidationError'\n }\n}\n\n/**\n * Raised for 404 responses from the crawlbrulee api — something on our side\n * was not found, for example an unknown or expired async job ID.\n *\n * It never means the target page was not found. When the site you scrape\n * answers with a 404 page, the scrape succeeds and returns that page with\n * `page_status_code: 404`.\n */\nexport class NotFoundError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Raised for 503 responses — the API could not serve the request right now\n * (a transient infrastructure failure, not a problem with your request).\n *\n * This is **retryable**: back off and try again. In particular it is not an\n * authentication failure, so it is never a reason to rotate your API key —\n * a genuinely bad or expired key still comes back as a 401\n * (`invalid_credentials`) and raises {@link AuthenticationError}.\n */\nexport class ServiceUnavailableError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'ServiceUnavailableError'\n }\n}\n\n/**\n * Raised when a request cannot be sent or no structured response is parsed.\n *\n * The `errorName` discriminates the cause:\n * - `'request_timeout'` — the per-request timeout fired.\n * - `'client_closed_request'` — the caller's `AbortSignal` fired.\n * - `null` — generic transport failure (network error, non-JSON body, etc.).\n */\nexport class TransportError extends CrawlbruleeError {\n constructor(\n message: string,\n options: {\n status?: number\n errorName?: 'request_timeout' | 'client_closed_request' | null\n cause?: unknown\n } = {}\n ) {\n super(message, {\n status: options.status ?? 0,\n errorName: options.errorName ?? null,\n cause: options.cause,\n })\n this.name = 'TransportError'\n }\n}\n\n/** Narrow `unknown` to the SDK's base error type. */\nexport function isCrawlbruleeError(err: unknown): err is CrawlbruleeError {\n return err instanceof CrawlbruleeError\n}\n\n/**\n * Map an API error body + HTTP status to the most specific error class.\n *\n * Dispatch is **name-first**: the body's `name` field is the most reliable\n * signal of what went wrong. Status code is used only as a fallback when the\n * name is unrecognized (e.g. a CDN-synthesized error). This avoids\n * miscategorizing things like a 403 with `name: 'not_found'` as an auth error.\n *\n * Internal — used by the HTTP layer.\n */\nexport function createApiError(body: ApiErrorResponse, status: number): CrawlbruleeError {\n const { name, message, details } = body\n const response = body\n\n switch (name) {\n case 'too_many_requests':\n return new RateLimitError(message, {\n status,\n details: details?.error_name === 'too_many_requests' ? details : undefined,\n response,\n })\n\n case 'usage_allocation_error': {\n // Without a structured details block we still want a typed error — fall\n // back to a synthetic `internal_error` reason so callers can branch.\n const usageDetails: UsageAllocationErrorDetails =\n details?.error_name === 'usage_allocation_error'\n ? details\n : { error_name: 'usage_allocation_error', reason: 'internal_error' }\n return new UsageAllocationError(message, { status, details: usageDetails, response })\n }\n\n case 'antibot_blocked':\n return new AntibotBlockedError(message, { status, errorName: name, response })\n\n case 'too_many_redirects':\n return new TooManyRedirectsError(message, { status, errorName: name, response })\n\n case 'page_too_large':\n return new PageTooLargeError(message, { status, errorName: name, response })\n\n case 'target_unreachable':\n return new TargetUnreachableError(message, { status, errorName: name, response })\n\n case 'zero_data_retention_not_enabled':\n return new ZeroDataRetentionNotEnabledError(message, { status, errorName: name, response })\n\n case 'invalid_credentials':\n case 'access_denied':\n return new AuthenticationError(message, { status, errorName: name, response })\n\n case 'not_found':\n return new NotFoundError(message, { status, errorName: name, response })\n\n case 'service_unavailable':\n return new ServiceUnavailableError(message, { status, errorName: name, response })\n\n case 'validation_error':\n case 'invalid_url':\n case 'url_too_long':\n case 'unsupported_url_schema':\n case 'url_credentials_not_supported':\n case 'blocked_url':\n case 'unsupported_content':\n case 'unsupported_screenshot_output':\n return new ValidationError(message, { status, errorName: name, response })\n }\n\n // Name was not specific enough — fall back to status-based heuristics, but\n // never override what the name said. A 429 with an unrecognized name still\n // promotes to RateLimitError (the class invariant normalizes errorName).\n if (status === 429) {\n return new RateLimitError(message, { status, response })\n }\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { status, errorName: name, response })\n }\n if (status === 404) {\n return new NotFoundError(message, { status, errorName: name, response })\n }\n if (status === 503) {\n return new ServiceUnavailableError(message, { status, errorName: name, response })\n }\n\n return new CrawlbruleeError(message, { status, errorName: name, details, response })\n}\n","import { DEFAULT_BASE_URL } from './config.js'\nimport { CrawlbruleeError } from './errors.js'\n\n/** Function shape compatible with the global `fetch`. */\nexport type FetchLike = typeof fetch\n\n/**\n * Centralized factory for the low-level dependencies the SDK injects into its\n * HTTP layer. Production code resolves these to the runtime's global `fetch`\n * and the burned-in production base URL; tests stub this module to swap in\n * mocks and alternate hosts.\n *\n * This is internal — it is not exported from the package's public entry. Tests\n * import it from `src/instrumentation.js` directly and use `vi.spyOn` to\n * substitute behavior.\n */\nexport const CwblInstrumentation = {\n /**\n * Resolve the `fetch` implementation the SDK should use. Throws a\n * {@link CrawlbruleeError} if the runtime does not expose a global `fetch`.\n */\n getFetch(): FetchLike {\n const g = globalThis as { fetch?: FetchLike }\n if (typeof g.fetch !== 'function') {\n throw new CrawlbruleeError(\n 'No global fetch is available in this runtime. crawlbrulee requires Node.js 22+, Bun, Deno, or a modern browser/edge runtime.',\n { status: 0, errorName: null }\n )\n }\n return g.fetch.bind(globalThis)\n },\n\n /**\n * Resolve the base URL the SDK should target. Returns the production host by\n * default; tests stub this to point at a mock origin.\n */\n getBaseUrl(): string {\n return DEFAULT_BASE_URL\n },\n}\n","import { DEFAULT_REQUEST_TIMEOUT_MS, USER_AGENT } from './config.js'\nimport { TransportError, createApiError, type CrawlbruleeError } from './errors.js'\nimport { CwblInstrumentation, type FetchLike } from './instrumentation.js'\nimport type { ApiErrorResponse } from './types/common.js'\n\n/** HTTP methods used by the SDK. */\nexport type HttpMethod = 'GET' | 'POST'\n\n/** Options the SDK accepts at construction time for the HTTP layer. */\nexport interface HttpClientOptions {\n /** API key sent as `Authorization: Bearer <key>`. */\n apiKey: string\n /**\n * Override the base URL. Trailing slashes are stripped. Falls back to\n * {@link CwblInstrumentation.getBaseUrl} (which resolves to the production\n * host) when unset.\n */\n baseUrl?: string\n /**\n * Per-request timeout in milliseconds. Pass `0` (or omit) to disable the\n * timeout entirely.\n */\n timeoutMs?: number\n}\n\n/** Per-call overrides accepted on every resource method. */\nexport interface RequestOptions {\n /** Abort the request when this signal fires. Composable with the timeout. */\n signal?: AbortSignal\n /**\n * Override the constructor-level `timeoutMs` for this call. Pass `0` to\n * disable the timeout for this call.\n */\n timeoutMs?: number\n}\n\ninterface SendArgs extends RequestOptions {\n method: HttpMethod\n path: string\n body?: unknown\n}\n\ninterface ComposedSignal {\n signal: AbortSignal | undefined\n /** Returns `true` if the abort was triggered by the per-request timeout. */\n timedOut: () => boolean\n /** Releases the timer and any listeners attached to the caller's signal. */\n cleanup: () => void\n}\n\n/**\n * Minimal `fetch`-based HTTP layer used by {@link Crawlbrulee}. Handles:\n *\n * - URL composition (joining `baseUrl` and path safely).\n * - JSON serialization and parsing.\n * - The `Authorization: Bearer …` header.\n * - Composing the caller's `AbortSignal` with an internal timeout signal. The\n * timeout covers the WHOLE request, including the response body read — not\n * just the time-to-headers.\n * - Mapping non-2xx responses to typed `CrawlbruleeError` subclasses via\n * {@link createApiError}.\n *\n * The base URL and `fetch` implementation are sourced from\n * {@link CwblInstrumentation} at construction time so tests can stub the\n * module.\n */\nexport class HttpClient {\n readonly baseUrl: string\n private readonly apiKey: string\n private readonly fetch: FetchLike\n private readonly timeoutMs: number\n\n constructor(options: HttpClientOptions) {\n this.baseUrl = stripTrailingSlash(options.baseUrl ?? CwblInstrumentation.getBaseUrl())\n this.apiKey = options.apiKey\n this.fetch = CwblInstrumentation.getFetch()\n this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS\n }\n\n /** Send a `GET` request and parse the response as `T`. */\n get<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.send<T>({ method: 'GET', path, ...options })\n }\n\n /** Send a `POST` request with a JSON body and parse the response as `T`. */\n post<T>(path: string, body: unknown, options?: RequestOptions): Promise<T> {\n return this.send<T>({ method: 'POST', path, body, ...options })\n }\n\n private async send<T>(args: SendArgs): Promise<T> {\n const url = this.buildUrl(args.path)\n const headers = this.buildHeaders(args)\n const body = args.body === undefined ? undefined : JSON.stringify(args.body)\n const composed = this.composeSignal(args.signal, args.timeoutMs)\n\n try {\n let res: Response\n try {\n res = await this.fetch(url, {\n method: args.method,\n headers,\n body,\n signal: composed.signal,\n })\n } catch (cause: unknown) {\n throw abortOrNetworkError(cause, composed.timedOut(), args.timeoutMs ?? this.timeoutMs)\n }\n\n let text: string\n try {\n text = await res.text()\n } catch (cause: unknown) {\n if (isAbortError(cause)) {\n throw abortOrNetworkError(cause, composed.timedOut(), args.timeoutMs ?? this.timeoutMs)\n }\n throw new TransportError(`Failed to read response body (status ${res.status}).`, {\n status: res.status,\n cause,\n })\n }\n\n const parsed = parseJsonOrThrow(text, res.status)\n if (!res.ok) throw toApiError(parsed, res.status, text)\n return parsed as T\n } finally {\n composed.cleanup()\n }\n }\n\n private buildUrl(path: string): string {\n if (!path.startsWith('/')) {\n throw new TypeError(`crawlbrulee SDK: path must start with '/' (received '${path}')`)\n }\n return `${this.baseUrl}${path}`\n }\n\n private buildHeaders(args: SendArgs): Record<string, string> {\n const headers: Record<string, string> = {\n accept: 'application/json',\n 'user-agent': USER_AGENT,\n authorization: `Bearer ${this.apiKey}`,\n }\n if (args.body !== undefined) headers['content-type'] = 'application/json'\n return headers\n }\n\n /**\n * Build a single `AbortSignal` that fires when either the caller-supplied\n * signal aborts OR the per-request timeout elapses. The returned `cleanup`\n * callback MUST be invoked on every exit path so we don't leak timers or\n * dead listeners on long-lived caller signals.\n */\n private composeSignal(\n callerSignal: AbortSignal | undefined,\n overrideTimeoutMs: number | undefined\n ): ComposedSignal {\n const timeoutMs = overrideTimeoutMs ?? this.timeoutMs\n const hasTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0\n\n if (!hasTimeout && !callerSignal) {\n return { signal: undefined, timedOut: () => false, cleanup: () => {} }\n }\n\n if (!hasTimeout) {\n return { signal: callerSignal, timedOut: () => false, cleanup: () => {} }\n }\n\n const controller = new AbortController()\n let didTimeout = false\n const timer = setTimeout(() => {\n didTimeout = true\n controller.abort(new Error('request_timeout'))\n }, timeoutMs)\n\n let onCallerAbort: (() => void) | undefined\n if (callerSignal) {\n if (callerSignal.aborted) {\n clearTimeout(timer)\n controller.abort(callerSignal.reason)\n } else {\n onCallerAbort = () => {\n clearTimeout(timer)\n controller.abort(callerSignal.reason)\n }\n callerSignal.addEventListener('abort', onCallerAbort, { once: true })\n }\n }\n\n const cleanup = () => {\n clearTimeout(timer)\n if (onCallerAbort && callerSignal) {\n callerSignal.removeEventListener('abort', onCallerAbort)\n }\n }\n\n return { signal: controller.signal, timedOut: () => didTimeout, cleanup }\n }\n}\n\nfunction stripTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, '')\n}\n\nfunction isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === 'AbortError'\n}\n\nfunction abortOrNetworkError(cause: unknown, timedOut: boolean, timeoutMs: number): TransportError {\n if (isAbortError(cause)) {\n if (timedOut) {\n return new TransportError(`Request timed out after ${timeoutMs}ms.`, {\n errorName: 'request_timeout',\n cause,\n })\n }\n return new TransportError('Request aborted by caller.', {\n errorName: 'client_closed_request',\n cause,\n })\n }\n return new TransportError(formatNetworkErrorMessage(cause), { cause })\n}\n\nfunction formatNetworkErrorMessage(cause: unknown): string {\n if (cause instanceof Error) {\n return `Network error: ${cause.message}`\n }\n return 'Network error: unknown failure while sending the request.'\n}\n\nfunction parseJsonOrThrow(text: string, status: number): unknown {\n if (text === '') return {}\n try {\n return JSON.parse(text)\n } catch (cause: unknown) {\n const preview = text.length > 200 ? `${text.slice(0, 200)}…` : text\n throw new TransportError(`Unexpected non-JSON response (status ${status}): ${preview}`, {\n status,\n cause,\n })\n }\n}\n\nfunction toApiError(parsed: unknown, status: number, rawText: string): CrawlbruleeError {\n if (isApiErrorResponse(parsed)) {\n return createApiError(parsed, status)\n }\n const preview = rawText.length > 200 ? `${rawText.slice(0, 200)}…` : rawText\n return new TransportError(`HTTP ${status}: ${preview || '(empty body)'}`, { status })\n}\n\nfunction isApiErrorResponse(value: unknown): value is ApiErrorResponse {\n if (value === null || typeof value !== 'object') return false\n const v = value as Record<string, unknown>\n return typeof v.name === 'string' && typeof v.message === 'string'\n}\n","import { ENV_API_KEY } from './config.js'\nimport { CrawlbruleeError } from './errors.js'\nimport { HttpClient, type RequestOptions } from './http.js'\nimport type {\n AsyncJobStatusResponse,\n AsyncScrapeRequest,\n AsyncScrapeResponse,\n MapRequest,\n MapResponse,\n ScrapeCompleteWebhook,\n ScrapeRequest,\n ScrapeResponse,\n UsageResponse,\n WhoamiResponse,\n} from './types/index.js'\n\n/** Options accepted by the {@link Crawlbrulee} constructor. */\nexport interface CrawlbruleeOptions {\n /**\n * API key sent as `Authorization: Bearer <key>`. Required — to read from the\n * environment instead, use {@link Crawlbrulee.fromEnv}. Leading and trailing\n * whitespace is stripped; an empty / whitespace-only value is rejected.\n */\n apiKey: string\n /**\n * Override the base URL the SDK targets. Defaults to the production host\n * ({@link DEFAULT_BASE_URL}). Intended for local development and staging\n * (e.g. `https://api.<staging-domain>`) — production callers should\n * leave it unset. Trailing slashes are stripped.\n */\n baseUrl?: string\n /**\n * Per-request timeout in milliseconds. Defaults to `0` (no timeout). Set to a\n * positive number to abort slow requests; a per-call `timeoutMs` override\n * takes precedence. The timeout covers the WHOLE request, including the\n * response body read.\n */\n timeoutMs?: number\n}\n\n/**\n * Options accepted by {@link Crawlbrulee.waitForScrape}.\n *\n * Note: `timeoutMs` here is the OVERALL wait budget across all polls — not the\n * per-HTTP-request timeout. The per-poll HTTP timeout is whatever the client\n * was constructed with; if you want to bound each individual poll, construct\n * the client with `timeoutMs` set.\n */\nexport interface WaitForScrapeOptions extends Omit<RequestOptions, 'timeoutMs'> {\n /** Time between status polls in milliseconds. Default `2000`. */\n intervalMs?: number\n /**\n * Maximum total time to wait before giving up, in milliseconds. Default\n * `300_000` (5 minutes). Pass `0` to wait indefinitely.\n */\n timeoutMs?: number\n}\n\n/**\n * Official client for the crawlbrulee API.\n *\n * @example\n * ```ts\n * import { Crawlbrulee } from '@crawlbrulee/sdk'\n *\n * const crawlbrulee = new Crawlbrulee({ apiKey: 'cwbl_…' })\n * // or read CRAWLBRULEE_API_KEY from the environment:\n * const crawlbrulee = Crawlbrulee.fromEnv()\n *\n * const page = await crawlbrulee.scrape({\n * url: 'https://example.com',\n * extract: { markdown: true, links: true },\n * })\n * console.log(page.markdown)\n * ```\n */\nexport class Crawlbrulee {\n /** Resolved base URL — trailing slash already stripped. */\n readonly baseUrl: string\n /** Underlying HTTP layer. Exposed for advanced use cases (custom endpoints). */\n readonly http: HttpClient\n\n constructor(options: CrawlbruleeOptions) {\n const apiKey = options.apiKey?.trim()\n if (!apiKey) {\n throw new CrawlbruleeError(\n `Missing API key. Pass { apiKey } to Crawlbrulee or call Crawlbrulee.fromEnv() to read ${ENV_API_KEY}.`,\n { status: 0, errorName: null }\n )\n }\n this.http = new HttpClient({ apiKey, baseUrl: options.baseUrl, timeoutMs: options.timeoutMs })\n this.baseUrl = this.http.baseUrl\n }\n\n /**\n * Build a {@link Crawlbrulee} reading the API key from\n * `process.env.CRAWLBRULEE_API_KEY`. Throws if the variable is unset, empty,\n * or whitespace.\n *\n * Any other constructor option can be passed via `overrides`.\n *\n * @example\n * ```ts\n * const crawlbrulee = Crawlbrulee.fromEnv()\n * const crawlbrulee = Crawlbrulee.fromEnv({ timeoutMs: 30_000 })\n * ```\n */\n static fromEnv(overrides: Omit<CrawlbruleeOptions, 'apiKey'> = {}): Crawlbrulee {\n const apiKey = readEnv(ENV_API_KEY)\n if (!apiKey) {\n throw new CrawlbruleeError(\n `${ENV_API_KEY} is not set. Export it in your shell, or pass apiKey to new Crawlbrulee({ apiKey }).`,\n { status: 0, errorName: null }\n )\n }\n return new Crawlbrulee({ ...overrides, apiKey })\n }\n\n // ------------------------------------------------------------------\n // Scraping\n // ------------------------------------------------------------------\n\n /**\n * Scrape a URL synchronously and return the extracted content.\n *\n * The request blocks until the scrape is finished. For long-running jobs\n * (heavy JS rendering, screenshots of long pages) prefer\n * {@link Crawlbrulee.scrapeAsync} so the connection isn't held open.\n *\n * Any page the site really served is returned, whatever its status: a 404,\n * 410, 401 or 503 page resolves normally, with the site's status in\n * `page_status_code` — it does not throw. Check that field when the page's\n * status matters to you. The call throws when we could not return the page,\n * for example `TargetUnreachableError` when the site could not be reached,\n * `AntibotBlockedError`, or `PageTooLargeError`.\n *\n * @param request — body for `POST /api/scrape`.\n * @param options — per-call timeout and abort signal.\n */\n scrape(request: ScrapeRequest, options?: RequestOptions): Promise<ScrapeResponse> {\n return this.http.post<ScrapeResponse>('/api/scrape', request, options)\n }\n\n /**\n * Submit an asynchronous scrape job and return its `job_id`. Poll the job\n * with {@link Crawlbrulee.getScrapeStatus} or wait for completion with\n * {@link Crawlbrulee.waitForScrape}.\n *\n * Pass an optional `webhook` to have the API deliver a signed\n * `scrape.complete` `POST` to your endpoint when the job finishes (see\n * {@link AsyncScrapeWebhook}). This field is async-only.\n */\n scrapeAsync(request: AsyncScrapeRequest, options?: RequestOptions): Promise<AsyncScrapeResponse> {\n return this.http.post<AsyncScrapeResponse>('/api/scrape/async', request, options)\n }\n\n /** Look up the current status of an async scrape job. */\n getScrapeStatus(jobId: string, options?: RequestOptions): Promise<AsyncJobStatusResponse> {\n assertNonEmptyJobId(jobId)\n return this.http.get<AsyncJobStatusResponse>(\n `/api/scrape/status/${encodeURIComponent(jobId)}`,\n options\n )\n }\n\n /**\n * Fetch the result of a completed async scrape job. Throws if the job is\n * still pending/running — call {@link Crawlbrulee.getScrapeStatus}\n * first, or use {@link Crawlbrulee.waitForScrape} to poll-then-fetch.\n *\n * Like {@link Crawlbrulee.scrape}, a 404 (or any other) page the site served\n * is a completed job: the result carries the site's status in\n * `page_status_code`.\n */\n getScrapeResult(jobId: string, options?: RequestOptions): Promise<ScrapeResponse> {\n assertNonEmptyJobId(jobId)\n return this.http.get<ScrapeResponse>(`/api/scrape/result/${encodeURIComponent(jobId)}`, options)\n }\n\n /**\n * Fetch the scrape result referenced by a `scrape.complete` webhook body.\n *\n * Always verify the webhook signature with `verifyWebhookSignature` before\n * acting on it; this method trusts the parsed body it is handed.\n *\n * Behavior by `data.status`:\n * - `success` — delegates to {@link Crawlbrulee.getScrapeResult} for the\n * webhook's `job_id` and returns the parsed result.\n * - `failed` — throws a {@link CrawlbruleeError} carrying `data.error`\n * (`errorName: 'job_failed'`); there is no result to fetch.\n * - `cancelled` — throws a {@link CrawlbruleeError}\n * (`errorName: 'client_closed_request'`).\n *\n * A non-`scrape.complete` envelope throws a {@link CrawlbruleeError}\n * defensively. Any HTTP error from the underlying fetch propagates as the\n * usual typed `CrawlbruleeError` subclass.\n */\n async fetchScrapeResultFromWebhook(\n webhook: ScrapeCompleteWebhook,\n options?: RequestOptions\n ): Promise<ScrapeResponse> {\n if (webhook?.event !== 'scrape.complete') {\n throw new CrawlbruleeError(\n `Expected a 'scrape.complete' webhook but received '${String(webhook?.event)}'.`,\n { status: 0, errorName: 'validation_error' }\n )\n }\n\n const { job_id: jobId, status, error } = webhook.data\n\n switch (status) {\n case 'success':\n return this.getScrapeResult(jobId, options)\n\n case 'failed':\n throw new CrawlbruleeError(error ?? `Async scrape job ${jobId} failed.`, {\n status: 0,\n errorName: 'job_failed',\n })\n\n case 'cancelled':\n throw new CrawlbruleeError(`Async scrape job ${jobId} was cancelled.`, {\n status: 0,\n errorName: 'client_closed_request',\n })\n\n default:\n throw new CrawlbruleeError(\n `Async scrape webhook for job ${jobId} carried an unexpected status '${String(status)}'.`,\n { status: 0, errorName: 'validation_error' }\n )\n }\n }\n\n /**\n * Poll an async scrape job until it reaches a terminal state, then return\n * the scrape result.\n *\n * Throws a {@link CrawlbruleeError} when:\n * - the job ends in `failed` (`errorName: 'job_failed'`),\n * - the server reports an unexpected status (`errorName: 'job_failed'`),\n * - the overall wait exceeds `timeoutMs` (`errorName: 'request_timeout'`),\n * - the caller's `signal` aborts (`errorName: 'client_closed_request'`).\n */\n async waitForScrape(jobId: string, options: WaitForScrapeOptions = {}): Promise<ScrapeResponse> {\n assertNonEmptyJobId(jobId)\n const intervalMs = options.intervalMs ?? 2000\n const timeoutMs = options.timeoutMs ?? 300_000\n const deadline = timeoutMs > 0 ? Date.now() + timeoutMs : Number.POSITIVE_INFINITY\n\n while (true) {\n throwIfAborted(options.signal)\n if (Date.now() >= deadline) {\n throw new CrawlbruleeError(\n `Timed out after ${timeoutMs}ms waiting for async scrape job ${jobId}.`,\n { status: 0, errorName: 'request_timeout' }\n )\n }\n\n const status = await this.getScrapeStatus(jobId, { signal: options.signal })\n\n switch (status.status) {\n case 'done':\n return this.getScrapeResult(jobId, { signal: options.signal })\n\n case 'failed':\n throw new CrawlbruleeError(status.error ?? `Async scrape job ${jobId} failed.`, {\n status: 0,\n errorName: 'job_failed',\n })\n\n case 'pending':\n case 'running':\n break\n\n default:\n throw new CrawlbruleeError(\n `Async scrape job ${jobId} returned unexpected status '${String(status.status)}'.`,\n { status: 0, errorName: 'job_failed' }\n )\n }\n\n await sleep(intervalMs, options.signal)\n }\n }\n\n // ------------------------------------------------------------------\n // Mapping\n // ------------------------------------------------------------------\n\n /**\n * Build (or return a cached) site link-map for a domain. Combines sitemap\n * discovery with the freshest cached homepage scrape when available.\n */\n map(request: MapRequest, options?: RequestOptions): Promise<MapResponse> {\n return this.http.post<MapResponse>('/api/map', request, options)\n }\n\n // ------------------------------------------------------------------\n // Account\n // ------------------------------------------------------------------\n\n /**\n * Return the current billing-cycle usage: total/used/available credits,\n * used quota percentage, max concurrency, and when the cycle resets.\n */\n usage(options?: RequestOptions): Promise<UsageResponse> {\n return this.http.get<UsageResponse>('/api/usage', options)\n }\n\n /**\n * Return the organization name and identifying details of the API token\n * used to authenticate this request. Useful for confirming which key is in\n * use before performing destructive operations.\n */\n whoami(options?: RequestOptions): Promise<WhoamiResponse> {\n return this.http.get<WhoamiResponse>('/api/whoami', options)\n }\n}\n\n/**\n * Defensive read of `process.env[name]`. Guards both the absence of `process`\n * (browser / edge runtimes) and Deno's permission throw on env access without\n * `--allow-env`.\n */\nfunction readEnv(name: string): string | undefined {\n try {\n if (typeof process === 'undefined' || !process.env) return undefined\n const v = process.env[name]\n return typeof v === 'string' && v.trim().length > 0 ? v.trim() : undefined\n } catch {\n return undefined\n }\n}\n\nfunction assertNonEmptyJobId(jobId: string): void {\n if (typeof jobId !== 'string' || jobId.trim().length === 0) {\n throw new CrawlbruleeError('jobId must be a non-empty string.', {\n status: 0,\n errorName: null,\n })\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw new CrawlbruleeError('Request aborted by caller.', {\n status: 0,\n errorName: 'client_closed_request',\n cause: signal.reason,\n })\n }\n}\n\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer)\n reject(\n new CrawlbruleeError('Request aborted by caller.', {\n status: 0,\n errorName: 'client_closed_request',\n cause: signal?.reason,\n })\n )\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n if (signal) {\n if (signal.aborted) {\n clearTimeout(timer)\n onAbort()\n return\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n}\n","/**\n * Verification for async scrape completion webhooks.\n *\n * {@link verifyWebhookSignature} validates the signature crawlbrulee attaches to\n * every webhook delivery. It is a standalone, network-free helper built on Web\n * Crypto (`globalThis.crypto.subtle`) so it runs unchanged on Node.js 22+,\n * browsers, Bun, Deno, and edge runtimes — it never touches `node:crypto`.\n */\n\n/** HTTP header carrying the primary webhook signature (always present). */\nexport const WEBHOOK_SIGNATURE_HEADER = 'X-Cwbl-Signature'\n\n/**\n * HTTP header carrying a signature produced with the previous signing secret.\n * Present only during a signing-secret rotation grace window.\n */\nexport const WEBHOOK_SIGNATURE_ROTATED_HEADER = 'X-Cwbl-Signature-Rotated'\n\n/** HTTP header carrying the unique event id, useful for delivery de-duplication. */\nexport const WEBHOOK_EVENT_ID_HEADER = 'X-Cwbl-Event-Id'\n\n/** Default replay-protection window (seconds) applied to the signed timestamp. */\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300\n\n/** Which signature header satisfied verification. */\nexport type WebhookSignatureSource = 'primary' | 'rotated'\n\n/**\n * Why a webhook signature failed to verify.\n *\n * - `missing_signature` — neither the primary nor the rotated header was present.\n * - `malformed_signature` — a header was present but not in the expected\n * `t=<unix_seconds>,v1=<64_hex>` format.\n * - `timestamp_out_of_tolerance` — the signed timestamp drifted further from now\n * than `toleranceSeconds` allows (replay protection).\n * - `signature_mismatch` — a well-formed, in-tolerance signature did not match\n * the one computed from the payload and secret.\n */\nexport type WebhookVerificationFailureReason =\n | 'missing_signature'\n | 'malformed_signature'\n | 'timestamp_out_of_tolerance'\n | 'signature_mismatch'\n\n/** Result of {@link verifyWebhookSignature}. Verification failure is returned, not thrown. */\nexport type WebhookVerificationResult =\n | { verified: true; signedWith: WebhookSignatureSource }\n | { verified: false; reason: WebhookVerificationFailureReason }\n\n/** Options for {@link verifyWebhookSignature}. */\nexport interface VerifyWebhookSignatureOptions {\n /**\n * The raw request body, exactly as received. Pass the bytes/string the server\n * signed — do NOT re-serialize parsed JSON, or the signature will not match.\n */\n payload: string | Uint8Array\n /**\n * The request headers. Accepts a fetch `Headers` instance or a plain object\n * (Express/Node give lowercased keys, values possibly arrays). Lookup is\n * case-insensitive.\n */\n headers: Headers | Record<string, string | string[] | undefined>\n /** The current signing secret (`whsec_…`). */\n secret: string\n /**\n * Replay-protection window in seconds. Defaults to\n * {@link DEFAULT_WEBHOOK_TOLERANCE_SECONDS} (300). Pass `0` (or any falsy\n * value) to disable the timestamp check entirely.\n */\n toleranceSeconds?: number\n}\n\nconst SIGNATURE_FORMAT = /^t=(\\d+),v1=([0-9a-f]{64})$/\n\ninterface ParsedSignature {\n timestamp: number\n signature: string\n}\n\n/**\n * Verify a crawlbrulee webhook signature against the primary and rotated\n * headers.\n *\n * The signing scheme matches the backend:\n * - the signed payload is `` `${t}.${rawBody}` `` where `t` is the unix-seconds\n * integer from the header and `rawBody` is the raw request body,\n * - the signature is `HMAC-SHA256(secret, signedPayload)` as lowercase hex,\n * - the header value is `t=<unix_seconds>,v1=<64_hex>`.\n *\n * The supplied `secret` is tried against the primary header first, then the\n * rotated header (which the API emits during a signing-secret rotation grace\n * window). Whichever matches wins, and the result reports which header it was.\n *\n * This NEVER throws on a verification failure — failures are normal control\n * flow and are returned as `{ verified: false, reason }`.\n *\n * @example\n * ```ts\n * const result = await verifyWebhookSignature({\n * payload: rawBody,\n * headers: req.headers,\n * secret: process.env.CRAWLBRULEE_WEBHOOK_SECRET!,\n * })\n * if (!result.verified) return res.status(400).end()\n * ```\n */\nexport async function verifyWebhookSignature(\n options: VerifyWebhookSignatureOptions\n): Promise<WebhookVerificationResult> {\n const { payload, headers, secret } = options\n const toleranceSeconds = options.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS\n\n const primaryHeader = getHeader(headers, WEBHOOK_SIGNATURE_HEADER)\n const rotatedHeader = getHeader(headers, WEBHOOK_SIGNATURE_ROTATED_HEADER)\n\n if (primaryHeader === undefined && rotatedHeader === undefined) {\n return { verified: false, reason: 'missing_signature' }\n }\n\n const nowSeconds = Math.floor(Date.now() / 1000)\n const body = toBytes(payload)\n const key = await importHmacKey(secret)\n\n // Track the \"best\" failure reason so the result is informative: a real\n // mismatch should win over a malformed sibling header. Order from least to\n // most specific.\n let failure: WebhookVerificationFailureReason = 'malformed_signature'\n\n for (const source of ['primary', 'rotated'] as const) {\n const raw = source === 'primary' ? primaryHeader : rotatedHeader\n if (raw === undefined) continue\n\n const parsed = parseSignatureHeader(raw)\n if (!parsed) {\n // A malformed header can't verify; keep looking at the other one.\n continue\n }\n\n if (toleranceSeconds && Math.abs(nowSeconds - parsed.timestamp) > toleranceSeconds) {\n failure = mostSpecificFailure(failure, 'timestamp_out_of_tolerance')\n continue\n }\n\n const expected = await computeSignatureHex(key, parsed.timestamp, body)\n if (constantTimeEqualHex(expected, parsed.signature)) {\n return { verified: true, signedWith: source }\n }\n\n failure = mostSpecificFailure(failure, 'signature_mismatch')\n }\n\n return { verified: false, reason: failure }\n}\n\n/**\n * Rank verification failures so the returned reason reflects the most\n * actionable problem encountered across the two headers.\n */\nfunction mostSpecificFailure(\n current: WebhookVerificationFailureReason,\n candidate: WebhookVerificationFailureReason\n): WebhookVerificationFailureReason {\n const rank: Record<WebhookVerificationFailureReason, number> = {\n missing_signature: 0,\n malformed_signature: 1,\n timestamp_out_of_tolerance: 2,\n signature_mismatch: 3,\n }\n return rank[candidate] > rank[current] ? candidate : current\n}\n\n/** Case-insensitive header lookup over `Headers` or a plain object. */\nfunction getHeader(\n headers: Headers | Record<string, string | string[] | undefined>,\n name: string\n): string | undefined {\n if (typeof Headers !== 'undefined' && headers instanceof Headers) {\n return headers.get(name) ?? undefined\n }\n const target = name.toLowerCase()\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() !== target) continue\n const value = (headers as Record<string, string | string[] | undefined>)[key]\n if (Array.isArray(value)) return value[0]\n return value ?? undefined\n }\n return undefined\n}\n\nfunction parseSignatureHeader(value: string): ParsedSignature | null {\n const match = SIGNATURE_FORMAT.exec(value.trim())\n if (!match) return null\n const timestamp = Number(match[1])\n if (!Number.isSafeInteger(timestamp)) return null\n return { timestamp, signature: match[2]! }\n}\n\nfunction toBytes(payload: string | Uint8Array): Uint8Array {\n return typeof payload === 'string' ? new TextEncoder().encode(payload) : payload\n}\n\n/**\n * Web Crypto types, derived from the runtime global so we don't have to pull in\n * the DOM `lib` (the SDK compiles against `lib: ES2022` + `@types/node`).\n */\ntype SubtleCryptoLike = typeof globalThis.crypto.subtle\ntype CryptoKeyLike = Awaited<ReturnType<SubtleCryptoLike['importKey']>>\n\nfunction importHmacKey(secret: string): Promise<CryptoKeyLike> {\n return getSubtle().importKey(\n 'raw',\n new TextEncoder().encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign']\n )\n}\n\nasync function computeSignatureHex(\n key: CryptoKeyLike,\n timestamp: number,\n body: Uint8Array\n): Promise<string> {\n const prefix = new TextEncoder().encode(`${timestamp}.`)\n const message = new Uint8Array(prefix.length + body.length)\n message.set(prefix, 0)\n message.set(body, prefix.length)\n const digest = await getSubtle().sign('HMAC', key, message)\n return toHex(new Uint8Array(digest))\n}\n\nfunction toHex(bytes: Uint8Array): string {\n let hex = ''\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, '0')\n }\n return hex\n}\n\n/**\n * Length-checked, constant-time comparison of two lowercase hex strings. Folds\n * every byte into an accumulator with XOR — never early-returns on the first\n * mismatch — so timing does not leak how much of the signature matched.\n */\nfunction constantTimeEqualHex(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n }\n return diff === 0\n}\n\nfunction getSubtle(): SubtleCryptoLike {\n const subtle = globalThis.crypto?.subtle\n if (!subtle) {\n throw new Error(\n 'Web Crypto (globalThis.crypto.subtle) is not available in this runtime. crawlbrulee webhook verification requires Node.js 22+, Bun, Deno, or a modern browser/edge runtime.'\n )\n }\n return subtle\n}\n"],"mappings":";;;;;;;;AAKA,MAAa,mBAAmB;;AAGhC,MAAa,6BAA6B;;AAG1C,MAAa,cAAc;;AAG3B,MAAa,aAAa;;;;;;;;;;;;;;;;;;;;;ACW1B,IAAa,mBAAb,cAAsC,MAAM;;CAE1C,AAAS;;CAET,AAAS;;CAET,AAAS;;CAET,AAAS;CAET,YACE,SACA,SAOA;EACA,MAAM,SAAS,QAAQ,UAAU,SAAY,EAAE,OAAO,QAAQ,MAAM,IAAI,MAAS;EACjF,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,YAAY,QAAQ;EACzB,KAAK,UAAU,QAAQ;EACvB,KAAK,WAAW,QAAQ;CAC1B;AACF;;;;;;;;;;;AAYA,IAAa,sBAAb,cAAyC,iBAAiB;CACxD,YACE,SACA,SACA;EACA,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;;;;;;AAOA,IAAa,sBAAb,cAAyC,iBAAiB;C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AS,MAAM,OAA2B;CACxC,IAAI,MAAM;CACV,KAAK,MAAM,QAAQ,OACjB,OAAO,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG;CAE1C,OAAO;AACT;;;;;;AAOA,SAAS,qBAAqB,GAAW,GAAoB;CAC3D,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;CAClC,IAAI,OAAO;CACX,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAC5B,QAAQ,EAAE,WAAW,CAAC,IAAI,EAAE,WAAW,CAAC;CAE1C,OAAO,SAAS;AAClB;AAEA,SAAS,YAA8B;CACrC,MAAM,SAAS,WAAW,QAAQ;CAClC,IAAI,CAAC,QACH,MAAM,IAAI,MACR,6KACF;CAEF,OAAO;AACT"}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../src/config.ts","../src/errors.ts","../src/instrumentation.ts","../src/http.ts","../src/client.ts","../src/webhooks.ts"],"sourcesContent":["/**\n * Production base URL of the crawlbrulee API. Used by default when the caller\n * doesn't pass a `baseUrl` to {@link Crawlbrulee}. Local development and\n * staging callers point at their own host via that option.\n */\nexport const DEFAULT_BASE_URL = 'https://api.crawlbrulee.com'\n\n/** Default request timeout when the caller doesn't specify one (0 disables the timeout). */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 0\n\n/** Environment variable read by `Crawlbrulee.fromEnv()` to source the API key. */\nexport const ENV_API_KEY = 'CRAWLBRULEE_API_KEY'\n\n/** Identifies the SDK in the `User-Agent` header. Kept in one place for easy bumping. */\nexport const USER_AGENT = '@crawlbrulee/sdk/1.3.0 (node)'\n","import type {\n ApiErrorDetails,\n ApiErrorName,\n ApiErrorResponse,\n RateLimitErrorDetails,\n UsageAllocationErrorDetails,\n} from './types/common.js'\n\n/**\n * Base error class for every failure raised by the SDK.\n *\n * Two kinds of failures end up here:\n *\n * 1. **API errors** — the server returned a non-2xx response with a well-formed\n * JSON body. In that case `status`, `errorName` and (sometimes) `details`\n * are populated.\n * 2. **Transport errors** — the request never produced a structured response\n * (network failure, abort, timeout, non-JSON body, etc.). In that case\n * `status` may be `0` and `errorName` is one of the synthetic transport\n * names (`request_timeout`, `client_closed_request`) or `null`.\n *\n * Typed subclasses are exported for the most common cases. To branch on more\n * specific server-side errors, switch on `err.errorName` or use the\n * {@link isCrawlbruleeError} helper.\n */\nexport class CrawlbruleeError extends Error {\n /** HTTP status code; `0` for transport-level failures with no response. */\n readonly status: number\n /** The `name` field from the API error body, or `null` for transport errors. */\n readonly errorName: ApiErrorName | null\n /** Structured detail block from the API error body, if any. */\n readonly details?: ApiErrorDetails\n /** The original parsed error body, when one was received. */\n readonly response?: ApiErrorResponse\n\n constructor(\n message: string,\n options: {\n status: number\n errorName: ApiErrorName | null\n details?: ApiErrorDetails\n response?: ApiErrorResponse\n cause?: unknown\n }\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined)\n this.name = 'CrawlbruleeError'\n this.status = options.status\n this.errorName = options.errorName\n this.details = options.details\n this.response = options.response\n }\n}\n\n/**\n * Raised when the API rejects your credentials — a missing, invalid, or\n * unauthorized API key (`invalid_credentials`, `access_denied`).\n *\n * Not every 403 is a key problem: a 403 carrying `antibot_blocked` is the\n * *target site* blocking us and raises {@link AntibotBlockedError} instead.\n * A 403 carrying `zero_data_retention_not_enabled` raises\n * {@link ZeroDataRetentionNotEnabledError}. Only an unrecognized 403 name falls\n * back to this class.\n */\nexport class AuthenticationError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'AuthenticationError'\n }\n}\n\n/**\n * Raised when the target site's anti-bot protection blocked the request\n * (HTTP 403, `antibot_blocked`). Not an API-key problem — retrying the same\n * tier rarely helps; try a higher proxy tier or skip the site.\n */\nexport class AntibotBlockedError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'AntibotBlockedError'\n }\n}\n\n/**\n * Raised when the target site redirected the request in a loop, or through\n * more hops than the API follows (HTTP 422, `too_many_redirects`). Like\n * {@link AntibotBlockedError} this is the target's doing — not a key problem\n * and not a bad request — so it is neither an `AuthenticationError` nor a\n * `ValidationError`. Retrying rarely helps. Returned by both `scrape` and `map`.\n */\nexport class TooManyRedirectsError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'TooManyRedirectsError'\n }\n}\n\n/**\n * Raised when the page's HTML was too large to process (HTTP 422,\n * `page_too_large`). Like {@link TooManyRedirectsError} this is about the page,\n * not your request — so it is neither an `AuthenticationError` nor a\n * `ValidationError`. It is terminal: the same URL fails the same way, so do not\n * retry it. Returned by `scrape`.\n */\nexport class PageTooLargeError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'PageTooLargeError'\n }\n}\n\n/**\n * Raised when we could not reach the target site at all (HTTP 502,\n * `target_unreachable`) — for example the site did not answer in time or its\n * TLS certificate was not valid. We never got a page, so there is nothing to\n * return and you are not charged. The message is always \"Could not reach the\n * target site.\" and there are no `details`.\n *\n * This is about the site, not your key or your request, so it is neither an\n * `AuthenticationError` nor a `ValidationError`. It is also not our own\n * outage ({@link ServiceUnavailableError}). Retrying later may help, since\n * the site may come back. The SDK does not retry for you.\n *\n * Not the same as a page with an error status: when the site answers with a\n * 404 or 503 page, the scrape succeeds and the site's status is in\n * `page_status_code`. Returned by both `scrape` and `map`.\n */\nexport class TargetUnreachableError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'TargetUnreachableError'\n }\n}\n\n/**\n * Raised when you send `zero_data_retention: true` but the option is not\n * enabled for your organization (HTTP 403, `zero_data_retention_not_enabled`).\n * The request is not billed. Not an API-key problem, so it is not an\n * {@link AuthenticationError}. See https://crawlbrulee.com/docs/zero-data-retention.\n */\nexport class ZeroDataRetentionNotEnabledError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'ZeroDataRetentionNotEnabledError'\n }\n}\n\n/**\n * Raised for HTTP 429 responses. When the server included a `retry_after_ms`\n * hint in `details` it is surfaced directly on the instance.\n *\n * `errorName` is always the literal `'too_many_requests'` — the SDK normalizes\n * this even when the server returns a 429 with a different `name` field. The\n * original body is still available on `response`.\n */\nexport class RateLimitError extends CrawlbruleeError {\n override readonly errorName: 'too_many_requests'\n /** Suggested delay (ms) before retrying, when the server provided one. */\n readonly retryAfterMs?: number\n /** Which rate limit was tripped (e.g. `org`, `ip`), when provided. */\n readonly limitedBy?: string\n\n constructor(\n message: string,\n options: {\n status: number\n details?: RateLimitErrorDetails\n response?: ApiErrorResponse\n }\n ) {\n super(message, { ...options, errorName: 'too_many_requests', details: options.details })\n this.name = 'RateLimitError'\n this.errorName = 'too_many_requests'\n this.retryAfterMs = options.details?.retry_after_ms\n this.limitedBy = options.details?.limited_by\n }\n}\n\n/**\n * Raised when the API rejects a request because the org's plan limits would\n * be exceeded (credit limit, concurrency cap, overage hard cap, etc.).\n *\n * `errorName` is always the literal `'usage_allocation_error'`.\n */\nexport class UsageAllocationError extends CrawlbruleeError {\n override readonly errorName: 'usage_allocation_error'\n /** Specific reason the allocation was denied. */\n readonly reason: UsageAllocationErrorDetails['reason']\n /** Current usage / limit snapshot at the time of the rejection. */\n readonly usage?: UsageAllocationErrorDetails['details']\n\n constructor(\n message: string,\n options: {\n status: number\n details: UsageAllocationErrorDetails\n response?: ApiErrorResponse\n }\n ) {\n super(message, { ...options, errorName: 'usage_allocation_error' })\n this.name = 'UsageAllocationError'\n this.errorName = 'usage_allocation_error'\n this.reason = options.details.reason\n this.usage = options.details.details\n }\n}\n\n/** Raised for 4xx responses caused by an invalid request shape or arguments. */\nexport class ValidationError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'ValidationError'\n }\n}\n\n/**\n * Raised for 404 responses from the crawlbrulee api — something on our side\n * was not found, for example an unknown or expired async job ID.\n *\n * It never means the target page was not found. When the site you scrape\n * answers with a 404 page, the scrape succeeds and returns that page with\n * `page_status_code: 404`.\n */\nexport class NotFoundError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Raised for 503 responses — the API could not serve the request right now\n * (a transient infrastructure failure, not a problem with your request).\n *\n * This is **retryable**: back off and try again. In particular it is not an\n * authentication failure, so it is never a reason to rotate your API key —\n * a genuinely bad or expired key still comes back as a 401\n * (`invalid_credentials`) and raises {@link AuthenticationError}.\n */\nexport class ServiceUnavailableError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'ServiceUnavailableError'\n }\n}\n\n/**\n * Raised when a request cannot be sent or no structured response is parsed.\n *\n * The `errorName` discriminates the cause:\n * - `'request_timeout'` — the per-request timeout fired.\n * - `'client_closed_request'` — the caller's `AbortSignal` fired.\n * - `null` — generic transport failure (network error, non-JSON body, etc.).\n */\nexport class TransportError extends CrawlbruleeError {\n constructor(\n message: string,\n options: {\n status?: number\n errorName?: 'request_timeout' | 'client_closed_request' | null\n cause?: unknown\n } = {}\n ) {\n super(message, {\n status: options.status ?? 0,\n errorName: options.errorName ?? null,\n cause: options.cause,\n })\n this.name = 'TransportError'\n }\n}\n\n/** Narrow `unknown` to the SDK's base error type. */\nexport function isCrawlbruleeError(err: unknown): err is CrawlbruleeError {\n return err instanceof CrawlbruleeError\n}\n\n/**\n * Map an API error body + HTTP status to the most specific error class.\n *\n * Dispatch is **name-first**: the body's `name` field is the most reliable\n * signal of what went wrong. Status code is used only as a fallback when the\n * name is unrecognized (e.g. a CDN-synthesized error). This avoids\n * miscategorizing things like a 403 with `name: 'not_found'` as an auth error.\n *\n * Internal — used by the HTTP layer.\n */\nexport function createApiError(body: ApiErrorResponse, status: number): CrawlbruleeError {\n const { name, message, details } = body\n const response = body\n\n switch (name) {\n case 'too_many_requests':\n return new RateLimitError(message, {\n status,\n details: details?.error_name === 'too_many_requests' ? details : undefined,\n response,\n })\n\n case 'usage_allocation_error': {\n // Without a structured details block we still want a typed error — fall\n // back to a synthetic `internal_error` reason so callers can branch.\n const usageDetails: UsageAllocationErrorDetails =\n details?.error_name === 'usage_allocation_error'\n ? details\n : { error_name: 'usage_allocation_error', reason: 'internal_error' }\n return new UsageAllocationError(message, { status, details: usageDetails, response })\n }\n\n case 'antibot_blocked':\n return new AntibotBlockedError(message, { status, errorName: name, response })\n\n case 'too_many_redirects':\n return new TooManyRedirectsError(message, { status, errorName: name, response })\n\n case 'page_too_large':\n return new PageTooLargeError(message, { status, errorName: name, response })\n\n case 'target_unreachable':\n return new TargetUnreachableError(message, { status, errorName: name, response })\n\n case 'zero_data_retention_not_enabled':\n return new ZeroDataRetentionNotEnabledError(message, { status, errorName: name, response })\n\n case 'invalid_credentials':\n case 'access_denied':\n return new AuthenticationError(message, { status, errorName: name, response })\n\n case 'not_found':\n return new NotFoundError(message, { status, errorName: name, response })\n\n case 'service_unavailable':\n return new ServiceUnavailableError(message, { status, errorName: name, response })\n\n case 'validation_error':\n case 'invalid_url':\n case 'url_too_long':\n case 'unsupported_url_schema':\n case 'url_credentials_not_supported':\n case 'blocked_url':\n case 'unsupported_content':\n case 'unsupported_screenshot_output':\n return new ValidationError(message, { status, errorName: name, response })\n }\n\n // Name was not specific enough — fall back to status-based heuristics, but\n // never override what the name said. A 429 with an unrecognized name still\n // promotes to RateLimitError (the class invariant normalizes errorName).\n if (status === 429) {\n return new RateLimitError(message, { status, response })\n }\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { status, errorName: name, response })\n }\n if (status === 404) {\n return new NotFoundError(message, { status, errorName: name, response })\n }\n if (status === 503) {\n return new ServiceUnavailableError(message, { status, errorName: name, response })\n }\n\n return new CrawlbruleeError(message, { status, errorName: name, details, response })\n}\n","import { DEFAULT_BASE_URL } from './config.js'\nimport { CrawlbruleeError } from './errors.js'\n\n/** Function shape compatible with the global `fetch`. */\nexport type FetchLike = typeof fetch\n\n/**\n * Centralized factory for the low-level dependencies the SDK injects into its\n * HTTP layer. Production code resolves these to the runtime's global `fetch`\n * and the burned-in production base URL; tests stub this module to swap in\n * mocks and alternate hosts.\n *\n * This is internal — it is not exported from the package's public entry. Tests\n * import it from `src/instrumentation.js` directly and use `vi.spyOn` to\n * substitute behavior.\n */\nexport const CwblInstrumentation = {\n /**\n * Resolve the `fetch` implementation the SDK should use. Throws a\n * {@link CrawlbruleeError} if the runtime does not expose a global `fetch`.\n */\n getFetch(): FetchLike {\n const g = globalThis as { fetch?: FetchLike }\n if (typeof g.fetch !== 'function') {\n throw new CrawlbruleeError(\n 'No global fetch is available in this runtime. crawlbrulee requires Node.js 22+, Bun, Deno, or a modern browser/edge runtime.',\n { status: 0, errorName: null }\n )\n }\n return g.fetch.bind(globalThis)\n },\n\n /**\n * Resolve the base URL the SDK should target. Returns the production host by\n * default; tests stub this to point at a mock origin.\n */\n getBaseUrl(): string {\n return DEFAULT_BASE_URL\n },\n}\n","import { DEFAULT_REQUEST_TIMEOUT_MS, USER_AGENT } from './config.js'\nimport { TransportError, createApiError, type CrawlbruleeError } from './errors.js'\nimport { CwblInstrumentation, type FetchLike } from './instrumentation.js'\nimport type { ApiErrorResponse } from './types/common.js'\n\n/** HTTP methods used by the SDK. */\nexport type HttpMethod = 'GET' | 'POST'\n\n/** Options the SDK accepts at construction time for the HTTP layer. */\nexport interface HttpClientOptions {\n /** API key sent as `Authorization: Bearer <key>`. */\n apiKey: string\n /**\n * Override the base URL. Trailing slashes are stripped. Falls back to\n * {@link CwblInstrumentation.getBaseUrl} (which resolves to the production\n * host) when unset.\n */\n baseUrl?: string\n /**\n * Per-request timeout in milliseconds. Pass `0` (or omit) to disable the\n * timeout entirely.\n */\n timeoutMs?: number\n}\n\n/** Per-call overrides accepted on every resource method. */\nexport interface RequestOptions {\n /** Abort the request when this signal fires. Composable with the timeout. */\n signal?: AbortSignal\n /**\n * Override the constructor-level `timeoutMs` for this call. Pass `0` to\n * disable the timeout for this call.\n */\n timeoutMs?: number\n}\n\ninterface SendArgs extends RequestOptions {\n method: HttpMethod\n path: string\n body?: unknown\n}\n\ninterface ComposedSignal {\n signal: AbortSignal | undefined\n /** Returns `true` if the abort was triggered by the per-request timeout. */\n timedOut: () => boolean\n /** Releases the timer and any listeners attached to the caller's signal. */\n cleanup: () => void\n}\n\n/**\n * Minimal `fetch`-based HTTP layer used by {@link Crawlbrulee}. Handles:\n *\n * - URL composition (joining `baseUrl` and path safely).\n * - JSON serialization and parsing.\n * - The `Authorization: Bearer …` header.\n * - Composing the caller's `AbortSignal` with an internal timeout signal. The\n * timeout covers the WHOLE request, including the response body read — not\n * just the time-to-headers.\n * - Mapping non-2xx responses to typed `CrawlbruleeError` subclasses via\n * {@link createApiError}.\n *\n * The base URL and `fetch` implementation are sourced from\n * {@link CwblInstrumentation} at construction time so tests can stub the\n * module.\n */\nexport class HttpClient {\n readonly baseUrl: string\n private readonly apiKey: string\n private readonly fetch: FetchLike\n private readonly timeoutMs: number\n\n constructor(options: HttpClientOptions) {\n this.baseUrl = stripTrailingSlash(options.baseUrl ?? CwblInstrumentation.getBaseUrl())\n this.apiKey = options.apiKey\n this.fetch = CwblInstrumentation.getFetch()\n this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS\n }\n\n /** Send a `GET` request and parse the response as `T`. */\n get<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.send<T>({ method: 'GET', path, ...options })\n }\n\n /** Send a `POST` request with a JSON body and parse the response as `T`. */\n post<T>(path: string, body: unknown, options?: RequestOptions): Promise<T> {\n return this.send<T>({ method: 'POST', path, body, ...options })\n }\n\n private async send<T>(args: SendArgs): Promise<T> {\n const url = this.buildUrl(args.path)\n const headers = this.buildHeaders(args)\n const body = args.body === undefined ? undefined : JSON.stringify(args.body)\n const composed = this.composeSignal(args.signal, args.timeoutMs)\n\n try {\n let res: Response\n try {\n res = await this.fetch(url, {\n method: args.method,\n headers,\n body,\n signal: composed.signal,\n })\n } catch (cause: unknown) {\n throw abortOrNetworkError(cause, composed.timedOut(), args.timeoutMs ?? this.timeoutMs)\n }\n\n let text: string\n try {\n text = await res.text()\n } catch (cause: unknown) {\n if (isAbortError(cause)) {\n throw abortOrNetworkError(cause, composed.timedOut(), args.timeoutMs ?? this.timeoutMs)\n }\n throw new TransportError(`Failed to read response body (status ${res.status}).`, {\n status: res.status,\n cause,\n })\n }\n\n const parsed = parseJsonOrThrow(text, res.status)\n if (!res.ok) throw toApiError(parsed, res.status, text)\n return parsed as T\n } finally {\n composed.cleanup()\n }\n }\n\n private buildUrl(path: string): string {\n if (!path.startsWith('/')) {\n throw new TypeError(`crawlbrulee SDK: path must start with '/' (received '${path}')`)\n }\n return `${this.baseUrl}${path}`\n }\n\n private buildHeaders(args: SendArgs): Record<string, string> {\n const headers: Record<string, string> = {\n accept: 'application/json',\n 'user-agent': USER_AGENT,\n authorization: `Bearer ${this.apiKey}`,\n }\n if (args.body !== undefined) headers['content-type'] = 'application/json'\n return headers\n }\n\n /**\n * Build a single `AbortSignal` that fires when either the caller-supplied\n * signal aborts OR the per-request timeout elapses. The returned `cleanup`\n * callback MUST be invoked on every exit path so we don't leak timers or\n * dead listeners on long-lived caller signals.\n */\n private composeSignal(\n callerSignal: AbortSignal | undefined,\n overrideTimeoutMs: number | undefined\n ): ComposedSignal {\n const timeoutMs = overrideTimeoutMs ?? this.timeoutMs\n const hasTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0\n\n if (!hasTimeout && !callerSignal) {\n return { signal: undefined, timedOut: () => false, cleanup: () => {} }\n }\n\n if (!hasTimeout) {\n return { signal: callerSignal, timedOut: () => false, cleanup: () => {} }\n }\n\n const controller = new AbortController()\n let didTimeout = false\n const timer = setTimeout(() => {\n didTimeout = true\n controller.abort(new Error('request_timeout'))\n }, timeoutMs)\n\n let onCallerAbort: (() => void) | undefined\n if (callerSignal) {\n if (callerSignal.aborted) {\n clearTimeout(timer)\n controller.abort(callerSignal.reason)\n } else {\n onCallerAbort = () => {\n clearTimeout(timer)\n controller.abort(callerSignal.reason)\n }\n callerSignal.addEventListener('abort', onCallerAbort, { once: true })\n }\n }\n\n const cleanup = () => {\n clearTimeout(timer)\n if (onCallerAbort && callerSignal) {\n callerSignal.removeEventListener('abort', onCallerAbort)\n }\n }\n\n return { signal: controller.signal, timedOut: () => didTimeout, cleanup }\n }\n}\n\nfunction stripTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, '')\n}\n\nfunction isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === 'AbortError'\n}\n\nfunction abortOrNetworkError(cause: unknown, timedOut: boolean, timeoutMs: number): TransportError {\n if (isAbortError(cause)) {\n if (timedOut) {\n return new TransportError(`Request timed out after ${timeoutMs}ms.`, {\n errorName: 'request_timeout',\n cause,\n })\n }\n return new TransportError('Request aborted by caller.', {\n errorName: 'client_closed_request',\n cause,\n })\n }\n return new TransportError(formatNetworkErrorMessage(cause), { cause })\n}\n\nfunction formatNetworkErrorMessage(cause: unknown): string {\n if (cause instanceof Error) {\n return `Network error: ${cause.message}`\n }\n return 'Network error: unknown failure while sending the request.'\n}\n\nfunction parseJsonOrThrow(text: string, status: number): unknown {\n if (text === '') return {}\n try {\n return JSON.parse(text)\n } catch (cause: unknown) {\n const preview = text.length > 200 ? `${text.slice(0, 200)}…` : text\n throw new TransportError(`Unexpected non-JSON response (status ${status}): ${preview}`, {\n status,\n cause,\n })\n }\n}\n\nfunction toApiError(parsed: unknown, status: number, rawText: string): CrawlbruleeError {\n if (isApiErrorResponse(parsed)) {\n return createApiError(parsed, status)\n }\n const preview = rawText.length > 200 ? `${rawText.slice(0, 200)}…` : rawText\n return new TransportError(`HTTP ${status}: ${preview || '(empty body)'}`, { status })\n}\n\nfunction isApiErrorResponse(value: unknown): value is ApiErrorResponse {\n if (value === null || typeof value !== 'object') return false\n const v = value as Record<string, unknown>\n return typeof v.name === 'string' && typeof v.message === 'string'\n}\n","import { ENV_API_KEY } from './config.js'\nimport { CrawlbruleeError } from './errors.js'\nimport { HttpClient, type RequestOptions } from './http.js'\nimport type {\n AsyncJobStatusResponse,\n AsyncScrapeRequest,\n AsyncScrapeResponse,\n MapRequest,\n MapResponse,\n ScrapeCompleteWebhook,\n ScrapeRequest,\n ScrapeResponse,\n UsageResponse,\n WhoamiResponse,\n} from './types/index.js'\n\n/** Options accepted by the {@link Crawlbrulee} constructor. */\nexport interface CrawlbruleeOptions {\n /**\n * API key sent as `Authorization: Bearer <key>`. Required — to read from the\n * environment instead, use {@link Crawlbrulee.fromEnv}. Leading and trailing\n * whitespace is stripped; an empty / whitespace-only value is rejected.\n */\n apiKey: string\n /**\n * Override the base URL the SDK targets. Defaults to the production host\n * ({@link DEFAULT_BASE_URL}). Intended for local development and staging\n * (e.g. `https://api.<staging-domain>`) — production callers should\n * leave it unset. Trailing slashes are stripped.\n */\n baseUrl?: string\n /**\n * Per-request timeout in milliseconds. Defaults to `0` (no timeout). Set to a\n * positive number to abort slow requests; a per-call `timeoutMs` override\n * takes precedence. The timeout covers the WHOLE request, including the\n * response body read.\n */\n timeoutMs?: number\n}\n\n/**\n * Options accepted by {@link Crawlbrulee.waitForScrape}.\n *\n * Note: `timeoutMs` here is the OVERALL wait budget across all polls — not the\n * per-HTTP-request timeout. The per-poll HTTP timeout is whatever the client\n * was constructed with; if you want to bound each individual poll, construct\n * the client with `timeoutMs` set.\n */\nexport interface WaitForScrapeOptions extends Omit<RequestOptions, 'timeoutMs'> {\n /** Time between status polls in milliseconds. Default `2000`. */\n intervalMs?: number\n /**\n * Maximum total time to wait before giving up, in milliseconds. Default\n * `300_000` (5 minutes). Pass `0` to wait indefinitely.\n */\n timeoutMs?: number\n}\n\n/**\n * Official client for the crawlbrulee API.\n *\n * @example\n * ```ts\n * import { Crawlbrulee } from '@crawlbrulee/sdk'\n *\n * const crawlbrulee = new Crawlbrulee({ apiKey: 'cwbl_…' })\n * // or read CRAWLBRULEE_API_KEY from the environment:\n * const crawlbrulee = Crawlbrulee.fromEnv()\n *\n * const page = await crawlbrulee.scrape({\n * url: 'https://example.com',\n * extract: { markdown: true, links: true },\n * })\n * console.log(page.markdown)\n * ```\n */\nexport class Crawlbrulee {\n /** Resolved base URL — trailing slash already stripped. */\n readonly baseUrl: string\n /** Underlying HTTP layer. Exposed for advanced use cases (custom endpoints). */\n readonly http: HttpClient\n\n constructor(options: CrawlbruleeOptions) {\n const apiKey = options.apiKey?.trim()\n if (!apiKey) {\n throw new CrawlbruleeError(\n `Missing API key. Pass { apiKey } to Crawlbrulee or call Crawlbrulee.fromEnv() to read ${ENV_API_KEY}.`,\n { status: 0, errorName: null }\n )\n }\n this.http = new HttpClient({ apiKey, baseUrl: options.baseUrl, timeoutMs: options.timeoutMs })\n this.baseUrl = this.http.baseUrl\n }\n\n /**\n * Build a {@link Crawlbrulee} reading the API key from\n * `process.env.CRAWLBRULEE_API_KEY`. Throws if the variable is unset, empty,\n * or whitespace.\n *\n * Any other constructor option can be passed via `overrides`.\n *\n * @example\n * ```ts\n * const crawlbrulee = Crawlbrulee.fromEnv()\n * const crawlbrulee = Crawlbrulee.fromEnv({ timeoutMs: 30_000 })\n * ```\n */\n static fromEnv(overrides: Omit<CrawlbruleeOptions, 'apiKey'> = {}): Crawlbrulee {\n const apiKey = readEnv(ENV_API_KEY)\n if (!apiKey) {\n throw new CrawlbruleeError(\n `${ENV_API_KEY} is not set. Export it in your shell, or pass apiKey to new Crawlbrulee({ apiKey }).`,\n { status: 0, errorName: null }\n )\n }\n return new Crawlbrulee({ ...overrides, apiKey })\n }\n\n // ------------------------------------------------------------------\n // Scraping\n // ------------------------------------------------------------------\n\n /**\n * Scrape a URL synchronously and return the extracted content.\n *\n * The request blocks until the scrape is finished. For long-running jobs\n * (heavy JS rendering, screenshots of long pages) prefer\n * {@link Crawlbrulee.scrapeAsync} so the connection isn't held open.\n *\n * Any page the site really served is returned, whatever its status: a 404,\n * 410, 401 or 503 page resolves normally, with the site's status in\n * `page_status_code` — it does not throw. Check that field when the page's\n * status matters to you. The call throws when we could not return the page,\n * for example `TargetUnreachableError` when the site could not be reached,\n * `AntibotBlockedError`, or `PageTooLargeError`.\n *\n * @param request — body for `POST /api/scrape`.\n * @param options — per-call timeout and abort signal.\n */\n scrape(request: ScrapeRequest, options?: RequestOptions): Promise<ScrapeResponse> {\n return this.http.post<ScrapeResponse>('/api/scrape', request, options)\n }\n\n /**\n * Submit an asynchronous scrape job and return its `job_id`. Poll the job\n * with {@link Crawlbrulee.getScrapeStatus} or wait for completion with\n * {@link Crawlbrulee.waitForScrape}.\n *\n * Pass an optional `webhook` to have the API deliver a signed\n * `scrape.complete` `POST` to your endpoint when the job finishes (see\n * {@link AsyncScrapeWebhook}). This field is async-only.\n */\n scrapeAsync(request: AsyncScrapeRequest, options?: RequestOptions): Promise<AsyncScrapeResponse> {\n return this.http.post<AsyncScrapeResponse>('/api/scrape/async', request, options)\n }\n\n /** Look up the current status of an async scrape job. */\n getScrapeStatus(jobId: string, options?: RequestOptions): Promise<AsyncJobStatusResponse> {\n assertNonEmptyJobId(jobId)\n return this.http.get<AsyncJobStatusResponse>(\n `/api/scrape/status/${encodeURIComponent(jobId)}`,\n options\n )\n }\n\n /**\n * Fetch the result of a completed async scrape job. Throws if the job is\n * still pending/running — call {@link Crawlbrulee.getScrapeStatus}\n * first, or use {@link Crawlbrulee.waitForScrape} to poll-then-fetch.\n *\n * Like {@link Crawlbrulee.scrape}, a 404 (or any other) page the site served\n * is a completed job: the result carries the site's status in\n * `page_status_code`.\n */\n getScrapeResult(jobId: string, options?: RequestOptions): Promise<ScrapeResponse> {\n assertNonEmptyJobId(jobId)\n return this.http.get<ScrapeResponse>(`/api/scrape/result/${encodeURIComponent(jobId)}`, options)\n }\n\n /**\n * Fetch the scrape result referenced by a `scrape.complete` webhook body.\n *\n * Always verify the webhook signature with `verifyWebhookSignature` before\n * acting on it; this method trusts the parsed body it is handed.\n *\n * Behavior by `data.status`:\n * - `success` — delegates to {@link Crawlbrulee.getScrapeResult} for the\n * webhook's `job_id` and returns the parsed result.\n * - `failed` — throws a {@link CrawlbruleeError} carrying `data.error`\n * (`errorName: 'job_failed'`); there is no result to fetch.\n * - `cancelled` — throws a {@link CrawlbruleeError}\n * (`errorName: 'client_closed_request'`).\n *\n * A non-`scrape.complete` envelope throws a {@link CrawlbruleeError}\n * defensively. Any HTTP error from the underlying fetch propagates as the\n * usual typed `CrawlbruleeError` subclass.\n */\n async fetchScrapeResultFromWebhook(\n webhook: ScrapeCompleteWebhook,\n options?: RequestOptions\n ): Promise<ScrapeResponse> {\n if (webhook?.event !== 'scrape.complete') {\n throw new CrawlbruleeError(\n `Expected a 'scrape.complete' webhook but received '${String(webhook?.event)}'.`,\n { status: 0, errorName: 'validation_error' }\n )\n }\n\n const { job_id: jobId, status, error } = webhook.data\n\n switch (status) {\n case 'success':\n return this.getScrapeResult(jobId, options)\n\n case 'failed':\n throw new CrawlbruleeError(error ?? `Async scrape job ${jobId} failed.`, {\n status: 0,\n errorName: 'job_failed',\n })\n\n case 'cancelled':\n throw new CrawlbruleeError(`Async scrape job ${jobId} was cancelled.`, {\n status: 0,\n errorName: 'client_closed_request',\n })\n\n default:\n throw new CrawlbruleeError(\n `Async scrape webhook for job ${jobId} carried an unexpected status '${String(status)}'.`,\n { status: 0, errorName: 'validation_error' }\n )\n }\n }\n\n /**\n * Poll an async scrape job until it reaches a terminal state, then return\n * the scrape result.\n *\n * Throws a {@link CrawlbruleeError} when:\n * - the job ends in `failed` (`errorName: 'job_failed'`),\n * - the server reports an unexpected status (`errorName: 'job_failed'`),\n * - the overall wait exceeds `timeoutMs` (`errorName: 'request_timeout'`),\n * - the caller's `signal` aborts (`errorName: 'client_closed_request'`).\n */\n async waitForScrape(jobId: string, options: WaitForScrapeOptions = {}): Promise<ScrapeResponse> {\n assertNonEmptyJobId(jobId)\n const intervalMs = options.intervalMs ?? 2000\n const timeoutMs = options.timeoutMs ?? 300_000\n const deadline = timeoutMs > 0 ? Date.now() + timeoutMs : Number.POSITIVE_INFINITY\n\n while (true) {\n throwIfAborted(options.signal)\n if (Date.now() >= deadline) {\n throw new CrawlbruleeError(\n `Timed out after ${timeoutMs}ms waiting for async scrape job ${jobId}.`,\n { status: 0, errorName: 'request_timeout' }\n )\n }\n\n const status = await this.getScrapeStatus(jobId, { signal: options.signal })\n\n switch (status.status) {\n case 'done':\n return this.getScrapeResult(jobId, { signal: options.signal })\n\n case 'failed':\n throw new CrawlbruleeError(status.error ?? `Async scrape job ${jobId} failed.`, {\n status: 0,\n errorName: 'job_failed',\n })\n\n case 'pending':\n case 'running':\n break\n\n default:\n throw new CrawlbruleeError(\n `Async scrape job ${jobId} returned unexpected status '${String(status.status)}'.`,\n { status: 0, errorName: 'job_failed' }\n )\n }\n\n await sleep(intervalMs, options.signal)\n }\n }\n\n // ------------------------------------------------------------------\n // Mapping\n // ------------------------------------------------------------------\n\n /**\n * Build (or return a cached) site link-map for a domain. Combines sitemap\n * discovery with the freshest cached homepage scrape when available.\n */\n map(request: MapRequest, options?: RequestOptions): Promise<MapResponse> {\n return this.http.post<MapResponse>('/api/map', request, options)\n }\n\n // ------------------------------------------------------------------\n // Account\n // ------------------------------------------------------------------\n\n /**\n * Return the current billing-cycle usage: total/used/available credits,\n * used quota percentage, max concurrency, and when the cycle resets.\n */\n usage(options?: RequestOptions): Promise<UsageResponse> {\n return this.http.get<UsageResponse>('/api/usage', options)\n }\n\n /**\n * Return the organization name and identifying details of the API token\n * used to authenticate this request. Useful for confirming which key is in\n * use before performing destructive operations.\n */\n whoami(options?: RequestOptions): Promise<WhoamiResponse> {\n return this.http.get<WhoamiResponse>('/api/whoami', options)\n }\n}\n\n/**\n * Defensive read of `process.env[name]`. Guards both the absence of `process`\n * (browser / edge runtimes) and Deno's permission throw on env access without\n * `--allow-env`.\n */\nfunction readEnv(name: string): string | undefined {\n try {\n if (typeof process === 'undefined' || !process.env) return undefined\n const v = process.env[name]\n return typeof v === 'string' && v.trim().length > 0 ? v.trim() : undefined\n } catch {\n return undefined\n }\n}\n\nfunction assertNonEmptyJobId(jobId: string): void {\n if (typeof jobId !== 'string' || jobId.trim().length === 0) {\n throw new CrawlbruleeError('jobId must be a non-empty string.', {\n status: 0,\n errorName: null,\n })\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw new CrawlbruleeError('Request aborted by caller.', {\n status: 0,\n errorName: 'client_closed_request',\n cause: signal.reason,\n })\n }\n}\n\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer)\n reject(\n new CrawlbruleeError('Request aborted by caller.', {\n status: 0,\n errorName: 'client_closed_request',\n cause: signal?.reason,\n })\n )\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n if (signal) {\n if (signal.aborted) {\n clearTimeout(timer)\n onAbort()\n return\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n}\n","/**\n * Verification for async scrape completion webhooks.\n *\n * {@link verifyWebhookSignature} validates the signature crawlbrulee attaches to\n * every webhook delivery. It is a standalone, network-free helper built on Web\n * Crypto (`globalThis.crypto.subtle`) so it runs unchanged on Node.js 22+,\n * browsers, Bun, Deno, and edge runtimes — it never touches `node:crypto`.\n */\n\n/** HTTP header carrying the primary webhook signature (always present). */\nexport const WEBHOOK_SIGNATURE_HEADER = 'X-Cwbl-Signature'\n\n/**\n * HTTP header carrying a signature produced with the previous signing secret.\n * Present only during a signing-secret rotation grace window.\n */\nexport const WEBHOOK_SIGNATURE_ROTATED_HEADER = 'X-Cwbl-Signature-Rotated'\n\n/** HTTP header carrying the unique event id, useful for delivery de-duplication. */\nexport const WEBHOOK_EVENT_ID_HEADER = 'X-Cwbl-Event-Id'\n\n/** Default replay-protection window (seconds) applied to the signed timestamp. */\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300\n\n/** Which signature header satisfied verification. */\nexport type WebhookSignatureSource = 'primary' | 'rotated'\n\n/**\n * Why a webhook signature failed to verify.\n *\n * - `missing_signature` — neither the primary nor the rotated header was present.\n * - `malformed_signature` — a header was present but not in the expected\n * `t=<unix_seconds>,v1=<64_hex>` format.\n * - `timestamp_out_of_tolerance` — the signed timestamp drifted further from now\n * than `toleranceSeconds` allows (replay protection).\n * - `signature_mismatch` — a well-formed, in-tolerance signature did not match\n * the one computed from the payload and secret.\n */\nexport type WebhookVerificationFailureReason =\n | 'missing_signature'\n | 'malformed_signature'\n | 'timestamp_out_of_tolerance'\n | 'signature_mismatch'\n\n/** Result of {@link verifyWebhookSignature}. Verification failure is returned, not thrown. */\nexport type WebhookVerificationResult =\n | { verified: true; signedWith: WebhookSignatureSource }\n | { verified: false; reason: WebhookVerificationFailureReason }\n\n/** Options for {@link verifyWebhookSignature}. */\nexport interface VerifyWebhookSignatureOptions {\n /**\n * The raw request body, exactly as received. Pass the bytes/string the server\n * signed — do NOT re-serialize parsed JSON, or the signature will not match.\n */\n payload: string | Uint8Array\n /**\n * The request headers. Accepts a fetch `Headers` instance or a plain object\n * (Express/Node give lowercased keys, values possibly arrays). Lookup is\n * case-insensitive.\n */\n headers: Headers | Record<string, string | string[] | undefined>\n /** The current signing secret (`whsec_…`). */\n secret: string\n /**\n * Replay-protection window in seconds. Defaults to\n * {@link DEFAULT_WEBHOOK_TOLERANCE_SECONDS} (300). Pass `0` (or any falsy\n * value) to disable the timestamp check entirely.\n */\n toleranceSeconds?: number\n}\n\nconst SIGNATURE_FORMAT = /^t=(\\d+),v1=([0-9a-f]{64})$/\n\ninterface ParsedSignature {\n timestamp: number\n signature: string\n}\n\n/**\n * Verify a crawlbrulee webhook signature against the primary and rotated\n * headers.\n *\n * The signing scheme matches the backend:\n * - the signed payload is `` `${t}.${rawBody}` `` where `t` is the unix-seconds\n * integer from the header and `rawBody` is the raw request body,\n * - the signature is `HMAC-SHA256(secret, signedPayload)` as lowercase hex,\n * - the header value is `t=<unix_seconds>,v1=<64_hex>`.\n *\n * The supplied `secret` is tried against the primary header first, then the\n * rotated header (which the API emits during a signing-secret rotation grace\n * window). Whichever matches wins, and the result reports which header it was.\n *\n * This NEVER throws on a verification failure — failures are normal control\n * flow and are returned as `{ verified: false, reason }`.\n *\n * @example\n * ```ts\n * const result = await verifyWebhookSignature({\n * payload: rawBody,\n * headers: req.headers,\n * secret: process.env.CRAWLBRULEE_WEBHOOK_SECRET!,\n * })\n * if (!result.verified) return res.status(400).end()\n * ```\n */\nexport async function verifyWebhookSignature(\n options: VerifyWebhookSignatureOptions\n): Promise<WebhookVerificationResult> {\n const { payload, headers, secret } = options\n const toleranceSeconds = options.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS\n\n const primaryHeader = getHeader(headers, WEBHOOK_SIGNATURE_HEADER)\n const rotatedHeader = getHeader(headers, WEBHOOK_SIGNATURE_ROTATED_HEADER)\n\n if (primaryHeader === undefined && rotatedHeader === undefined) {\n return { verified: false, reason: 'missing_signature' }\n }\n\n const nowSeconds = Math.floor(Date.now() / 1000)\n const body = toBytes(payload)\n const key = await importHmacKey(secret)\n\n // Track the \"best\" failure reason so the result is informative: a real\n // mismatch should win over a malformed sibling header. Order from least to\n // most specific.\n let failure: WebhookVerificationFailureReason = 'malformed_signature'\n\n for (const source of ['primary', 'rotated'] as const) {\n const raw = source === 'primary' ? primaryHeader : rotatedHeader\n if (raw === undefined) continue\n\n const parsed = parseSignatureHeader(raw)\n if (!parsed) {\n // A malformed header can't verify; keep looking at the other one.\n continue\n }\n\n if (toleranceSeconds && Math.abs(nowSeconds - parsed.timestamp) > toleranceSeconds) {\n failure = mostSpecificFailure(failure, 'timestamp_out_of_tolerance')\n continue\n }\n\n const expected = await computeSignatureHex(key, parsed.timestamp, body)\n if (constantTimeEqualHex(expected, parsed.signature)) {\n return { verified: true, signedWith: source }\n }\n\n failure = mostSpecificFailure(failure, 'signature_mismatch')\n }\n\n return { verified: false, reason: failure }\n}\n\n/**\n * Rank verification failures so the returned reason reflects the most\n * actionable problem encountered across the two headers.\n */\nfunction mostSpecificFailure(\n current: WebhookVerificationFailureReason,\n candidate: WebhookVerificationFailureReason\n): WebhookVerificationFailureReason {\n const rank: Record<WebhookVerificationFailureReason, number> = {\n missing_signature: 0,\n malformed_signature: 1,\n timestamp_out_of_tolerance: 2,\n signature_mismatch: 3,\n }\n return rank[candidate] > rank[current] ? candidate : current\n}\n\n/** Case-insensitive header lookup over `Headers` or a plain object. */\nfunction getHeader(\n headers: Headers | Record<string, string | string[] | undefined>,\n name: string\n): string | undefined {\n if (typeof Headers !== 'undefined' && headers instanceof Headers) {\n return headers.get(name) ?? undefined\n }\n const target = name.toLowerCase()\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() !== target) continue\n const value = (headers as Record<string, string | string[] | undefined>)[key]\n if (Array.isArray(value)) return value[0]\n return value ?? undefined\n }\n return undefined\n}\n\nfunction parseSignatureHeader(value: string): ParsedSignature | null {\n const match = SIGNATURE_FORMAT.exec(value.trim())\n if (!match) return null\n const timestamp = Number(match[1])\n if (!Number.isSafeInteger(timestamp)) return null\n return { timestamp, signature: match[2]! }\n}\n\nfunction toBytes(payload: string | Uint8Array): Uint8Array {\n return typeof payload === 'string' ? new TextEncoder().encode(payload) : payload\n}\n\n/**\n * Web Crypto types, derived from the runtime global so we don't have to pull in\n * the DOM `lib` (the SDK compiles against `lib: ES2022` + `@types/node`).\n */\ntype SubtleCryptoLike = typeof globalThis.crypto.subtle\ntype CryptoKeyLike = Awaited<ReturnType<SubtleCryptoLike['importKey']>>\n\nfunction importHmacKey(secret: string): Promise<CryptoKeyLike> {\n return getSubtle().importKey(\n 'raw',\n new TextEncoder().encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign']\n )\n}\n\nasync function computeSignatureHex(\n key: CryptoKeyLike,\n timestamp: number,\n body: Uint8Array\n): Promise<string> {\n const prefix = new TextEncoder().encode(`${timestamp}.`)\n const message = new Uint8Array(prefix.length + body.length)\n message.set(prefix, 0)\n message.set(body, prefix.length)\n const digest = await getSubtle().sign('HMAC', key, message)\n return toHex(new Uint8Array(digest))\n}\n\nfunction toHex(bytes: Uint8Array): string {\n let hex = ''\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, '0')\n }\n return hex\n}\n\n/**\n * Length-checked, constant-time comparison of two lowercase hex strings. Folds\n * every byte into an accumulator with XOR — never early-returns on the first\n * mismatch — so timing does not leak how much of the signature matched.\n */\nfunction constantTimeEqualHex(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n }\n return diff === 0\n}\n\nfunction getSubtle(): SubtleCryptoLike {\n const subtle = globalThis.crypto?.subtle\n if (!subtle) {\n throw new Error(\n 'Web Crypto (globalThis.crypto.subtle) is not available in this runtime. crawlbrulee webhook verification requires Node.js 22+, Bun, Deno, or a modern browser/edge runtime.'\n )\n }\n return subtle\n}\n"],"mappings":";;;;;;;;AAKA,MAAa,mBAAmB;;AAGhC,MAAa,6BAA6B;;AAG1C,MAAa,cAAc;;AAG3B,MAAa,aAAa;;;;;;;;;;;;;;;;;;;;;ACW1B,IAAa,mBAAb,cAAsC,MAAM;;CAE1C,AAAS;;CAET,AAAS;;CAET,AAAS;;CAET,AAAS;CAET,YACE,SACA,SAOA;EACA,MAAM,SAAS,QAAQ,UAAU,SAAY,EAAE,OAAO,QAAQ,MAAM,IAAI,MAAS;EACjF,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,YAAY,QAAQ;EACzB,KAAK,UAAU,QAA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AM;CAC1D,QAAQ,IAAI,QAAQ,CAAC;CACrB,QAAQ,IAAI,MAAM,OAAO,MAAM;CAC/B,MAAM,SAAS,MAAM,UAAU,CAAC,CAAC,KAAK,QAAQ,KAAK,OAAO;CAC1D,OAAO,MAAM,IAAI,WAAW,MAAM,CAAC;AACrC;AAEA,SAAS,MAAM,OAA2B;CACxC,IAAI,MAAM;CACV,KAAK,MAAM,QAAQ,OACjB,OAAO,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG;CAE1C,OAAO;AACT;;;;;;AAOA,SAAS,qBAAqB,GAAW,GAAoB;CAC3D,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;CAClC,IAAI,OAAO;CACX,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAC5B,QAAQ,EAAE,WAAW,CAAC,IAAI,EAAE,WAAW,CAAC;CAE1C,OAAO,SAAS;AAClB;AAEA,SAAS,YAA8B;CACrC,MAAM,SAAS,WAAW,QAAQ;CAClC,IAAI,CAAC,QACH,MAAM,IAAI,MACR,6KACF;CAEF,OAAO;AACT"}
package/dist/index.d.cts CHANGED
@@ -257,6 +257,102 @@ interface ApiErrorResponse {
257
257
  }
258
258
  //#endregion
259
259
  //#region src/types/scrape.d.ts
260
+ /**
261
+ * What an `extract.elements` spec reads from each match: its `text` (the
262
+ * default), its outer `html`, or one `attribute`.
263
+ */
264
+ type ScrapeElementOutput = 'text' | 'html' | 'attribute';
265
+ /** What every spec has, with or without `fields`. */
266
+ interface ScrapeElementSpecBase {
267
+ /** CSS selector. At most 500 characters. */
268
+ selector: string;
269
+ /** Return every match as a list instead of the first match. Default `false`. */
270
+ all?: boolean;
271
+ }
272
+ /**
273
+ * A spec that reads one value from each match, with no `fields`. It is also the
274
+ * innermost spec: {@link ScrapeElementSpec} nests `fields` up to 3 levels, and a
275
+ * spec inside the third `fields` must be this one.
276
+ *
277
+ * See https://crawlbrulee.com/docs/scrape/elements for the selector rules and limits.
278
+ */
279
+ interface ScrapeElementLeafSpec extends ScrapeElementSpecBase {
280
+ /** What to read from the match. Default `text`. */
281
+ output?: ScrapeElementOutput;
282
+ /**
283
+ * The attribute to read, at most 100 characters. Required when `output` is
284
+ * `attribute`, and not allowed with any other `output`. `href` and `src` come
285
+ * back as full urls. A match without the attribute is `null`, and is left out
286
+ * of an `all: true` list.
287
+ */
288
+ attribute?: string;
289
+ /** Not allowed here. Use a spec with `fields` instead. */
290
+ fields?: never;
291
+ }
292
+ /**
293
+ * A spec with `fields`: each match becomes an object. `fields` can't be
294
+ * combined with `output` or `attribute`, and an empty `fields` is refused.
295
+ */
296
+ interface ScrapeElementSpecWithFields<Field> extends ScrapeElementSpecBase {
297
+ /** Values read inside each match, by name. At least one. */
298
+ fields: Record<string, string | Field>;
299
+ /** Not allowed with `fields`. */
300
+ output?: never;
301
+ /** Not allowed with `fields`. */
302
+ attribute?: never;
303
+ }
304
+ /**
305
+ * A spec inside the second `fields`. If it has `fields` of its own, that is the
306
+ * third and last `fields`, and the specs inside it have no `fields`.
307
+ */
308
+ type ScrapeElementNestedFieldSpec = ScrapeElementLeafSpec | ScrapeElementSpecWithFields<ScrapeElementLeafSpec>;
309
+ /** A spec inside the first `fields` (the one on a {@link ScrapeElementSpec}). */
310
+ type ScrapeElementFieldSpec = ScrapeElementLeafSpec | ScrapeElementSpecWithFields<ScrapeElementNestedFieldSpec>;
311
+ /**
312
+ * The full spec for one name in `extract.elements`.
313
+ *
314
+ * With `fields` (instead of `output` and `attribute`, never both), each match
315
+ * becomes an object: every field is a name and a selector read inside that
316
+ * match only. So a list of product cards can return a title, price and url per
317
+ * card. An empty `fields` is refused. Fields nest up to 3 levels; the types
318
+ * stop you from going deeper.
319
+ *
320
+ * See https://crawlbrulee.com/docs/scrape/elements for the selector rules and limits.
321
+ */
322
+ type ScrapeElementSpec = ScrapeElementLeafSpec | ScrapeElementSpecWithFields<ScrapeElementFieldSpec>;
323
+ /**
324
+ * Named values to read from the page by CSS selector, sent as
325
+ * `extract.elements`. Each key is a name you pick; each value is a selector
326
+ * string (the text of the first match) or a {@link ScrapeElementSpec}. The
327
+ * values come back on {@link ScrapeResponse.elements} under the same names.
328
+ *
329
+ * ```ts
330
+ * const elements: ScrapeElements = {
331
+ * heading: 'h1',
332
+ * books: {
333
+ * selector: 'article.product_pod',
334
+ * all: true,
335
+ * fields: {
336
+ * title: { selector: 'h3 a', output: 'attribute', attribute: 'title' },
337
+ * price: '.price_color',
338
+ * },
339
+ * },
340
+ * }
341
+ * ```
342
+ *
343
+ * See https://crawlbrulee.com/docs/scrape/elements.
344
+ */
345
+ type ScrapeElements = Record<string, string | ScrapeElementSpec>;
346
+ /** One match read with `fields`: field name → value. */
347
+ interface ScrapeElementObject {
348
+ [name: string]: ScrapeElementValue;
349
+ }
350
+ /**
351
+ * The value for one name in {@link ScrapeResponse.elements}: a string, an
352
+ * object (a spec with `fields`), a list of either (`all: true`), or `null` when
353
+ * nothing matched (`[]` with `all: true`).
354
+ */
355
+ type ScrapeElementValue = string | ScrapeElementObject | (string | ScrapeElementObject)[] | null;
260
356
  /**
261
357
  * Which content formats to extract from the scraped page. Every field is
262
358
  * optional; the server defaults are noted on each field. The default request
@@ -292,14 +388,22 @@ interface ScrapeExtract {
292
388
  * `inline_images_truncated` warning is returned.
293
389
  */
294
390
  images?: boolean;
391
+ /**
392
+ * Named values to read from the page by CSS selector. They come back on the
393
+ * top-level `elements` field under the same names. Read after `cleanup`, from
394
+ * the same page as `links` and `images`. No extra credits, also when the
395
+ * page comes from cache. See {@link ScrapeElements} and
396
+ * https://crawlbrulee.com/docs/scrape/elements.
397
+ */
398
+ elements?: ScrapeElements;
295
399
  /** Capture a screenshot. Omit to skip; set to a `ScreenshotRequest` to enable. */
296
400
  screenshot?: ScreenshotRequest;
297
401
  }
298
402
  /**
299
403
  * What is removed from the page before any output is built.
300
404
  *
301
- * Applies to `markdown`, `cleaned_html`, `links` and `images` on every engine,
302
- * and to the screenshot. It never applies to `raw_html` — that is always the
405
+ * Applies to `markdown`, `cleaned_html`, `links`, `images` and `elements` on
406
+ * every engine, and to the screenshot. It never applies to `raw_html` — that is always the
303
407
  * page as it arrived, before anything was removed.
304
408
  */
305
409
  interface ScrapeCleanup {
@@ -313,18 +417,18 @@ interface ScrapeCleanup {
313
417
  * CSS selectors whose elements are removed before anything is captured. Use
314
418
  * it for a banner or widget `ads_and_popups` does not recognise.
315
419
  *
316
- * At most 100 selectors, each at most 500 characters. Sending any selector
317
- * here makes the request skip the cache, so it always costs a live fetch.
420
+ * At most 100 selectors, each at most 500 characters. A cached result is
421
+ * only reused for a request that removes the same selectors.
318
422
  */
319
423
  exclude_selectors?: string[];
320
424
  }
321
425
  /**
322
426
  * Cache settings for a scrape request. `max_age` is the only cache control.
323
427
  * A cached result has to match the url, the screenshot setup (type, viewport,
324
- * device mode), `cleanup.ads_and_popups` and `location.locale`, and
325
- * `require_js: true` only matches browser-rendered results.
326
- * `cleanup.exclude_selectors` and a non-zero `actions_before` wait or scroll
327
- * disable caching for that request.
428
+ * device mode), `cleanup.ads_and_popups`, `cleanup.exclude_selectors` and
429
+ * `location.locale`, and `require_js: true` only matches browser-rendered
430
+ * results. A non-zero `actions_before` wait or scroll disables caching for that
431
+ * request.
328
432
  */
329
433
  interface ScrapeCache {
330
434
  /**
@@ -366,7 +470,7 @@ interface ScrapeRequest {
366
470
  require_js?: boolean;
367
471
  /**
368
472
  * What is removed from the page before any output is built. Shapes
369
- * `markdown`, `cleaned_html`, `links`, `images` and the screenshot.
473
+ * `markdown`, `cleaned_html`, `links`, `images`, `elements` and the screenshot.
370
474
  *
371
475
  * Never applies to `raw_html`, which is always the page before anything was
372
476
  * removed.
@@ -529,8 +633,9 @@ interface ScrapeMetadata {
529
633
  * - `links_truncated` — the page had more than 30 000 links.
530
634
  * - `inline_images_truncated` — the page had more than 10 000 inline images.
531
635
  * - `raw_html_truncated` — the page body exceeded 10 000 000 characters of HTML.
532
- * - `metadata_truncated` — the page `<head>` exceeded 2 000 000 characters of
533
- * HTML, so some metadata may be missing.
636
+ * - `elements_truncated` — at least one `elements` value hit a limit: a list
637
+ * was cut, or a value too large to return is `null` (never cut short). See
638
+ * https://crawlbrulee.com/docs/scrape/elements for the limits.
534
639
  *
535
640
  * Unavailability — that section's extraction failed, so the field is omitted
536
641
  * or empty while the rest of the scrape succeeded. These let you tell "the page
@@ -539,11 +644,17 @@ interface ScrapeMetadata {
539
644
  * - `links_unavailable` — link extraction failed.
540
645
  * - `inline_images_unavailable` — image extraction failed.
541
646
  * - `metadata_unavailable` — metadata extraction failed.
647
+ * - `screenshot_unavailable` — a screenshot was asked for, but the page came
648
+ * back without one. The rest of the result is there.
542
649
  *
543
650
  * The page body has no such code: if it can't be extracted the scrape fails
544
651
  * outright rather than returning a hollow `200`, and isn't billed.
652
+ *
653
+ * `metadata_truncated` is deprecated: metadata no longer has a size limit of
654
+ * its own, so new scrapes never send it. It stays in the union because results
655
+ * stored before that change can still carry it. Don't rely on it in new code.
545
656
  */
546
- type ScrapeWarningCode = 'screenshot_truncated' | 'links_truncated' | 'inline_images_truncated' | 'raw_html_truncated' | 'metadata_truncated' | 'links_unavailable' | 'inline_images_unavailable' | 'metadata_unavailable';
657
+ type ScrapeWarningCode = 'screenshot_truncated' | 'links_truncated' | 'inline_images_truncated' | 'raw_html_truncated' | 'metadata_truncated' | 'elements_truncated' | 'links_unavailable' | 'inline_images_unavailable' | 'metadata_unavailable' | 'screenshot_unavailable';
547
658
  /**
548
659
  * Successful response from `POST /api/scrape` and `GET /api/scrape/result/:jobId`.
549
660
  *
@@ -581,7 +692,7 @@ interface ScrapeResponse {
581
692
  content_type?: string;
582
693
  /**
583
694
  * Extract fields that were requested but aren't supported for this
584
- * content type (e.g. asking for `markdown` of a PDF).
695
+ * content type (e.g. asking for `metadata` or `elements` of a JSON file).
585
696
  */
586
697
  unsupported_fields?: string[];
587
698
  /** Page content converted to clean Markdown (when `extract.markdown`). */
@@ -597,11 +708,18 @@ interface ScrapeResponse {
597
708
  images?: PageInlineImage[];
598
709
  /** Links discovered on the page (when `extract.links`). */
599
710
  links?: PageLink[];
711
+ /**
712
+ * The values asked for in `extract.elements`, under the same names. Every
713
+ * requested name is present, at every level of `fields`; a name with no
714
+ * match is `null` (`[]` with `all: true`). See {@link ScrapeElementValue}.
715
+ */
716
+ elements?: Record<string, ScrapeElementValue>;
600
717
  /**
601
718
  * Captured screenshot (when `extract.screenshot`). In rare cases a screenshot
602
719
  * can't be captured; when you also requested other outputs those are still
603
- * returned and this field is simply left out (so it reads back as
604
- * `undefined`) — guard with `page.screenshot?.url`. A screenshot-only request
720
+ * returned and this field is left out (so it reads back as `undefined`), with
721
+ * a `screenshot_unavailable` warning on `warnings` to tell this case apart —
722
+ * guard with `page.screenshot?.url`. A screenshot-only request
605
723
  * that can't deliver fails instead of returning an empty response: a `422`
606
724
  * with `unsupported_screenshot_output` when the content type can't be
607
725
  * screenshotted, a `500` when the capture itself failed — and isn't billed.
@@ -1448,5 +1566,5 @@ interface VerifyWebhookSignatureOptions {
1448
1566
  */
1449
1567
  declare function verifyWebhookSignature(options: VerifyWebhookSignatureOptions): Promise<WebhookVerificationResult>;
1450
1568
  //#endregion
1451
- export { AntibotBlockedError, ApiErrorDetails, ApiErrorName, ApiErrorResponse, AsyncJobStatus, AsyncJobStatusResponse, AsyncScrapeRequest, AsyncScrapeResponse, AsyncScrapeWebhook, AuthenticationError, BillingEngine, Crawlbrulee, CrawlbruleeError, type CrawlbruleeOptions, DEFAULT_BASE_URL, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, ENV_API_KEY, type HttpMethod, MapBillingEngine, MapCache, MapDiscoveryCapReason, MapLinkItem, MapLocation, MapPagination, MapRequest, MapResponse, MapResponseMeta, MapTruncation, MapTypes, MapUsage, NotFoundError, PageInlineImage, PageLink, PageTooLargeError, ProxyTier, RateLimitError, RateLimitErrorDetails, type RequestOptions, ResolvedProxyTier, ResponseMeta, ScrapeCache, ScrapeCleanup, ScrapeCompleteWebhook, ScrapeCompleteWebhookData, ScrapeExtract, ScrapeLocation, ScrapeMetadata, ScrapeRequest, ScrapeResponse, ScrapeWarningCode, ScrapeWebhookStatus, ScreenshotAfterAction, ScreenshotBeforeAction, ScreenshotDeviceMode, ScreenshotProperties, ScreenshotRequest, ScreenshotResult, ScreenshotScrollAction, ScreenshotSlice, ScreenshotSliceAction, ScreenshotType, ScreenshotViewport, ScreenshotViewportInfo, ScreenshotWaitAction, ServiceUnavailableError, TargetUnreachableError, TooManyRedirectsError, TransportError, Usage, UsageAllocationError, UsageAllocationErrorDetails, UsageAllocationReason, UsageLimitDetails, UsageResponse, ValidationError, type VerifyWebhookSignatureOptions, WEBHOOK_EVENT_ID_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_SIGNATURE_ROTATED_HEADER, type WaitForScrapeOptions, type WebhookSignatureSource, type WebhookVerificationFailureReason, type WebhookVerificationResult, WhoamiResponse, ZeroDataRetentionNotEnabledError, isCrawlbruleeError, verifyWebhookSignature };
1569
+ export { AntibotBlockedError, ApiErrorDetails, ApiErrorName, ApiErrorResponse, AsyncJobStatus, AsyncJobStatusResponse, AsyncScrapeRequest, AsyncScrapeResponse, AsyncScrapeWebhook, AuthenticationError, BillingEngine, Crawlbrulee, CrawlbruleeError, type CrawlbruleeOptions, DEFAULT_BASE_URL, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, ENV_API_KEY, type HttpMethod, MapBillingEngine, MapCache, MapDiscoveryCapReason, MapLinkItem, MapLocation, MapPagination, MapRequest, MapResponse, MapResponseMeta, MapTruncation, MapTypes, MapUsage, NotFoundError, PageInlineImage, PageLink, PageTooLargeError, ProxyTier, RateLimitError, RateLimitErrorDetails, type RequestOptions, ResolvedProxyTier, ResponseMeta, ScrapeCache, ScrapeCleanup, ScrapeCompleteWebhook, ScrapeCompleteWebhookData, ScrapeElementFieldSpec, ScrapeElementLeafSpec, ScrapeElementNestedFieldSpec, ScrapeElementObject, ScrapeElementOutput, ScrapeElementSpec, ScrapeElementValue, ScrapeElements, ScrapeExtract, ScrapeLocation, ScrapeMetadata, ScrapeRequest, ScrapeResponse, ScrapeWarningCode, ScrapeWebhookStatus, ScreenshotAfterAction, ScreenshotBeforeAction, ScreenshotDeviceMode, ScreenshotProperties, ScreenshotRequest, ScreenshotResult, ScreenshotScrollAction, ScreenshotSlice, ScreenshotSliceAction, ScreenshotType, ScreenshotViewport, ScreenshotViewportInfo, ScreenshotWaitAction, ServiceUnavailableError, TargetUnreachableError, TooManyRedirectsError, TransportError, Usage, UsageAllocationError, UsageAllocationErrorDetails, UsageAllocationReason, UsageLimitDetails, UsageResponse, ValidationError, type VerifyWebhookSignatureOptions, WEBHOOK_EVENT_ID_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_SIGNATURE_ROTATED_HEADER, type WaitForScrapeOptions, type WebhookSignatureSource, type WebhookVerificationFailureReason, type WebhookVerificationResult, WhoamiResponse, ZeroDataRetentionNotEnabledError, isCrawlbruleeError, verifyWebhookSignature };
1452
1570
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -257,6 +257,102 @@ interface ApiErrorResponse {
257
257
  }
258
258
  //#endregion
259
259
  //#region src/types/scrape.d.ts
260
+ /**
261
+ * What an `extract.elements` spec reads from each match: its `text` (the
262
+ * default), its outer `html`, or one `attribute`.
263
+ */
264
+ type ScrapeElementOutput = 'text' | 'html' | 'attribute';
265
+ /** What every spec has, with or without `fields`. */
266
+ interface ScrapeElementSpecBase {
267
+ /** CSS selector. At most 500 characters. */
268
+ selector: string;
269
+ /** Return every match as a list instead of the first match. Default `false`. */
270
+ all?: boolean;
271
+ }
272
+ /**
273
+ * A spec that reads one value from each match, with no `fields`. It is also the
274
+ * innermost spec: {@link ScrapeElementSpec} nests `fields` up to 3 levels, and a
275
+ * spec inside the third `fields` must be this one.
276
+ *
277
+ * See https://crawlbrulee.com/docs/scrape/elements for the selector rules and limits.
278
+ */
279
+ interface ScrapeElementLeafSpec extends ScrapeElementSpecBase {
280
+ /** What to read from the match. Default `text`. */
281
+ output?: ScrapeElementOutput;
282
+ /**
283
+ * The attribute to read, at most 100 characters. Required when `output` is
284
+ * `attribute`, and not allowed with any other `output`. `href` and `src` come
285
+ * back as full urls. A match without the attribute is `null`, and is left out
286
+ * of an `all: true` list.
287
+ */
288
+ attribute?: string;
289
+ /** Not allowed here. Use a spec with `fields` instead. */
290
+ fields?: never;
291
+ }
292
+ /**
293
+ * A spec with `fields`: each match becomes an object. `fields` can't be
294
+ * combined with `output` or `attribute`, and an empty `fields` is refused.
295
+ */
296
+ interface ScrapeElementSpecWithFields<Field> extends ScrapeElementSpecBase {
297
+ /** Values read inside each match, by name. At least one. */
298
+ fields: Record<string, string | Field>;
299
+ /** Not allowed with `fields`. */
300
+ output?: never;
301
+ /** Not allowed with `fields`. */
302
+ attribute?: never;
303
+ }
304
+ /**
305
+ * A spec inside the second `fields`. If it has `fields` of its own, that is the
306
+ * third and last `fields`, and the specs inside it have no `fields`.
307
+ */
308
+ type ScrapeElementNestedFieldSpec = ScrapeElementLeafSpec | ScrapeElementSpecWithFields<ScrapeElementLeafSpec>;
309
+ /** A spec inside the first `fields` (the one on a {@link ScrapeElementSpec}). */
310
+ type ScrapeElementFieldSpec = ScrapeElementLeafSpec | ScrapeElementSpecWithFields<ScrapeElementNestedFieldSpec>;
311
+ /**
312
+ * The full spec for one name in `extract.elements`.
313
+ *
314
+ * With `fields` (instead of `output` and `attribute`, never both), each match
315
+ * becomes an object: every field is a name and a selector read inside that
316
+ * match only. So a list of product cards can return a title, price and url per
317
+ * card. An empty `fields` is refused. Fields nest up to 3 levels; the types
318
+ * stop you from going deeper.
319
+ *
320
+ * See https://crawlbrulee.com/docs/scrape/elements for the selector rules and limits.
321
+ */
322
+ type ScrapeElementSpec = ScrapeElementLeafSpec | ScrapeElementSpecWithFields<ScrapeElementFieldSpec>;
323
+ /**
324
+ * Named values to read from the page by CSS selector, sent as
325
+ * `extract.elements`. Each key is a name you pick; each value is a selector
326
+ * string (the text of the first match) or a {@link ScrapeElementSpec}. The
327
+ * values come back on {@link ScrapeResponse.elements} under the same names.
328
+ *
329
+ * ```ts
330
+ * const elements: ScrapeElements = {
331
+ * heading: 'h1',
332
+ * books: {
333
+ * selector: 'article.product_pod',
334
+ * all: true,
335
+ * fields: {
336
+ * title: { selector: 'h3 a', output: 'attribute', attribute: 'title' },
337
+ * price: '.price_color',
338
+ * },
339
+ * },
340
+ * }
341
+ * ```
342
+ *
343
+ * See https://crawlbrulee.com/docs/scrape/elements.
344
+ */
345
+ type ScrapeElements = Record<string, string | ScrapeElementSpec>;
346
+ /** One match read with `fields`: field name → value. */
347
+ interface ScrapeElementObject {
348
+ [name: string]: ScrapeElementValue;
349
+ }
350
+ /**
351
+ * The value for one name in {@link ScrapeResponse.elements}: a string, an
352
+ * object (a spec with `fields`), a list of either (`all: true`), or `null` when
353
+ * nothing matched (`[]` with `all: true`).
354
+ */
355
+ type ScrapeElementValue = string | ScrapeElementObject | (string | ScrapeElementObject)[] | null;
260
356
  /**
261
357
  * Which content formats to extract from the scraped page. Every field is
262
358
  * optional; the server defaults are noted on each field. The default request
@@ -292,14 +388,22 @@ interface ScrapeExtract {
292
388
  * `inline_images_truncated` warning is returned.
293
389
  */
294
390
  images?: boolean;
391
+ /**
392
+ * Named values to read from the page by CSS selector. They come back on the
393
+ * top-level `elements` field under the same names. Read after `cleanup`, from
394
+ * the same page as `links` and `images`. No extra credits, also when the
395
+ * page comes from cache. See {@link ScrapeElements} and
396
+ * https://crawlbrulee.com/docs/scrape/elements.
397
+ */
398
+ elements?: ScrapeElements;
295
399
  /** Capture a screenshot. Omit to skip; set to a `ScreenshotRequest` to enable. */
296
400
  screenshot?: ScreenshotRequest;
297
401
  }
298
402
  /**
299
403
  * What is removed from the page before any output is built.
300
404
  *
301
- * Applies to `markdown`, `cleaned_html`, `links` and `images` on every engine,
302
- * and to the screenshot. It never applies to `raw_html` — that is always the
405
+ * Applies to `markdown`, `cleaned_html`, `links`, `images` and `elements` on
406
+ * every engine, and to the screenshot. It never applies to `raw_html` — that is always the
303
407
  * page as it arrived, before anything was removed.
304
408
  */
305
409
  interface ScrapeCleanup {
@@ -313,18 +417,18 @@ interface ScrapeCleanup {
313
417
  * CSS selectors whose elements are removed before anything is captured. Use
314
418
  * it for a banner or widget `ads_and_popups` does not recognise.
315
419
  *
316
- * At most 100 selectors, each at most 500 characters. Sending any selector
317
- * here makes the request skip the cache, so it always costs a live fetch.
420
+ * At most 100 selectors, each at most 500 characters. A cached result is
421
+ * only reused for a request that removes the same selectors.
318
422
  */
319
423
  exclude_selectors?: string[];
320
424
  }
321
425
  /**
322
426
  * Cache settings for a scrape request. `max_age` is the only cache control.
323
427
  * A cached result has to match the url, the screenshot setup (type, viewport,
324
- * device mode), `cleanup.ads_and_popups` and `location.locale`, and
325
- * `require_js: true` only matches browser-rendered results.
326
- * `cleanup.exclude_selectors` and a non-zero `actions_before` wait or scroll
327
- * disable caching for that request.
428
+ * device mode), `cleanup.ads_and_popups`, `cleanup.exclude_selectors` and
429
+ * `location.locale`, and `require_js: true` only matches browser-rendered
430
+ * results. A non-zero `actions_before` wait or scroll disables caching for that
431
+ * request.
328
432
  */
329
433
  interface ScrapeCache {
330
434
  /**
@@ -366,7 +470,7 @@ interface ScrapeRequest {
366
470
  require_js?: boolean;
367
471
  /**
368
472
  * What is removed from the page before any output is built. Shapes
369
- * `markdown`, `cleaned_html`, `links`, `images` and the screenshot.
473
+ * `markdown`, `cleaned_html`, `links`, `images`, `elements` and the screenshot.
370
474
  *
371
475
  * Never applies to `raw_html`, which is always the page before anything was
372
476
  * removed.
@@ -529,8 +633,9 @@ interface ScrapeMetadata {
529
633
  * - `links_truncated` — the page had more than 30 000 links.
530
634
  * - `inline_images_truncated` — the page had more than 10 000 inline images.
531
635
  * - `raw_html_truncated` — the page body exceeded 10 000 000 characters of HTML.
532
- * - `metadata_truncated` — the page `<head>` exceeded 2 000 000 characters of
533
- * HTML, so some metadata may be missing.
636
+ * - `elements_truncated` — at least one `elements` value hit a limit: a list
637
+ * was cut, or a value too large to return is `null` (never cut short). See
638
+ * https://crawlbrulee.com/docs/scrape/elements for the limits.
534
639
  *
535
640
  * Unavailability — that section's extraction failed, so the field is omitted
536
641
  * or empty while the rest of the scrape succeeded. These let you tell "the page
@@ -539,11 +644,17 @@ interface ScrapeMetadata {
539
644
  * - `links_unavailable` — link extraction failed.
540
645
  * - `inline_images_unavailable` — image extraction failed.
541
646
  * - `metadata_unavailable` — metadata extraction failed.
647
+ * - `screenshot_unavailable` — a screenshot was asked for, but the page came
648
+ * back without one. The rest of the result is there.
542
649
  *
543
650
  * The page body has no such code: if it can't be extracted the scrape fails
544
651
  * outright rather than returning a hollow `200`, and isn't billed.
652
+ *
653
+ * `metadata_truncated` is deprecated: metadata no longer has a size limit of
654
+ * its own, so new scrapes never send it. It stays in the union because results
655
+ * stored before that change can still carry it. Don't rely on it in new code.
545
656
  */
546
- type ScrapeWarningCode = 'screenshot_truncated' | 'links_truncated' | 'inline_images_truncated' | 'raw_html_truncated' | 'metadata_truncated' | 'links_unavailable' | 'inline_images_unavailable' | 'metadata_unavailable';
657
+ type ScrapeWarningCode = 'screenshot_truncated' | 'links_truncated' | 'inline_images_truncated' | 'raw_html_truncated' | 'metadata_truncated' | 'elements_truncated' | 'links_unavailable' | 'inline_images_unavailable' | 'metadata_unavailable' | 'screenshot_unavailable';
547
658
  /**
548
659
  * Successful response from `POST /api/scrape` and `GET /api/scrape/result/:jobId`.
549
660
  *
@@ -581,7 +692,7 @@ interface ScrapeResponse {
581
692
  content_type?: string;
582
693
  /**
583
694
  * Extract fields that were requested but aren't supported for this
584
- * content type (e.g. asking for `markdown` of a PDF).
695
+ * content type (e.g. asking for `metadata` or `elements` of a JSON file).
585
696
  */
586
697
  unsupported_fields?: string[];
587
698
  /** Page content converted to clean Markdown (when `extract.markdown`). */
@@ -597,11 +708,18 @@ interface ScrapeResponse {
597
708
  images?: PageInlineImage[];
598
709
  /** Links discovered on the page (when `extract.links`). */
599
710
  links?: PageLink[];
711
+ /**
712
+ * The values asked for in `extract.elements`, under the same names. Every
713
+ * requested name is present, at every level of `fields`; a name with no
714
+ * match is `null` (`[]` with `all: true`). See {@link ScrapeElementValue}.
715
+ */
716
+ elements?: Record<string, ScrapeElementValue>;
600
717
  /**
601
718
  * Captured screenshot (when `extract.screenshot`). In rare cases a screenshot
602
719
  * can't be captured; when you also requested other outputs those are still
603
- * returned and this field is simply left out (so it reads back as
604
- * `undefined`) — guard with `page.screenshot?.url`. A screenshot-only request
720
+ * returned and this field is left out (so it reads back as `undefined`), with
721
+ * a `screenshot_unavailable` warning on `warnings` to tell this case apart —
722
+ * guard with `page.screenshot?.url`. A screenshot-only request
605
723
  * that can't deliver fails instead of returning an empty response: a `422`
606
724
  * with `unsupported_screenshot_output` when the content type can't be
607
725
  * screenshotted, a `500` when the capture itself failed — and isn't billed.
@@ -1448,5 +1566,5 @@ interface VerifyWebhookSignatureOptions {
1448
1566
  */
1449
1567
  declare function verifyWebhookSignature(options: VerifyWebhookSignatureOptions): Promise<WebhookVerificationResult>;
1450
1568
  //#endregion
1451
- export { AntibotBlockedError, ApiErrorDetails, ApiErrorName, ApiErrorResponse, AsyncJobStatus, AsyncJobStatusResponse, AsyncScrapeRequest, AsyncScrapeResponse, AsyncScrapeWebhook, AuthenticationError, BillingEngine, Crawlbrulee, CrawlbruleeError, type CrawlbruleeOptions, DEFAULT_BASE_URL, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, ENV_API_KEY, type HttpMethod, MapBillingEngine, MapCache, MapDiscoveryCapReason, MapLinkItem, MapLocation, MapPagination, MapRequest, MapResponse, MapResponseMeta, MapTruncation, MapTypes, MapUsage, NotFoundError, PageInlineImage, PageLink, PageTooLargeError, ProxyTier, RateLimitError, RateLimitErrorDetails, type RequestOptions, ResolvedProxyTier, ResponseMeta, ScrapeCache, ScrapeCleanup, ScrapeCompleteWebhook, ScrapeCompleteWebhookData, ScrapeExtract, ScrapeLocation, ScrapeMetadata, ScrapeRequest, ScrapeResponse, ScrapeWarningCode, ScrapeWebhookStatus, ScreenshotAfterAction, ScreenshotBeforeAction, ScreenshotDeviceMode, ScreenshotProperties, ScreenshotRequest, ScreenshotResult, ScreenshotScrollAction, ScreenshotSlice, ScreenshotSliceAction, ScreenshotType, ScreenshotViewport, ScreenshotViewportInfo, ScreenshotWaitAction, ServiceUnavailableError, TargetUnreachableError, TooManyRedirectsError, TransportError, Usage, UsageAllocationError, UsageAllocationErrorDetails, UsageAllocationReason, UsageLimitDetails, UsageResponse, ValidationError, type VerifyWebhookSignatureOptions, WEBHOOK_EVENT_ID_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_SIGNATURE_ROTATED_HEADER, type WaitForScrapeOptions, type WebhookSignatureSource, type WebhookVerificationFailureReason, type WebhookVerificationResult, WhoamiResponse, ZeroDataRetentionNotEnabledError, isCrawlbruleeError, verifyWebhookSignature };
1569
+ export { AntibotBlockedError, ApiErrorDetails, ApiErrorName, ApiErrorResponse, AsyncJobStatus, AsyncJobStatusResponse, AsyncScrapeRequest, AsyncScrapeResponse, AsyncScrapeWebhook, AuthenticationError, BillingEngine, Crawlbrulee, CrawlbruleeError, type CrawlbruleeOptions, DEFAULT_BASE_URL, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, ENV_API_KEY, type HttpMethod, MapBillingEngine, MapCache, MapDiscoveryCapReason, MapLinkItem, MapLocation, MapPagination, MapRequest, MapResponse, MapResponseMeta, MapTruncation, MapTypes, MapUsage, NotFoundError, PageInlineImage, PageLink, PageTooLargeError, ProxyTier, RateLimitError, RateLimitErrorDetails, type RequestOptions, ResolvedProxyTier, ResponseMeta, ScrapeCache, ScrapeCleanup, ScrapeCompleteWebhook, ScrapeCompleteWebhookData, ScrapeElementFieldSpec, ScrapeElementLeafSpec, ScrapeElementNestedFieldSpec, ScrapeElementObject, ScrapeElementOutput, ScrapeElementSpec, ScrapeElementValue, ScrapeElements, ScrapeExtract, ScrapeLocation, ScrapeMetadata, ScrapeRequest, ScrapeResponse, ScrapeWarningCode, ScrapeWebhookStatus, ScreenshotAfterAction, ScreenshotBeforeAction, ScreenshotDeviceMode, ScreenshotProperties, ScreenshotRequest, ScreenshotResult, ScreenshotScrollAction, ScreenshotSlice, ScreenshotSliceAction, ScreenshotType, ScreenshotViewport, ScreenshotViewportInfo, ScreenshotWaitAction, ServiceUnavailableError, TargetUnreachableError, TooManyRedirectsError, TransportError, Usage, UsageAllocationError, UsageAllocationErrorDetails, UsageAllocationReason, UsageLimitDetails, UsageResponse, ValidationError, type VerifyWebhookSignatureOptions, WEBHOOK_EVENT_ID_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_SIGNATURE_ROTATED_HEADER, type WaitForScrapeOptions, type WebhookSignatureSource, type WebhookVerificationFailureReason, type WebhookVerificationResult, WhoamiResponse, ZeroDataRetentionNotEnabledError, isCrawlbruleeError, verifyWebhookSignature };
1452
1570
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 0;
10
10
  /** Environment variable read by `Crawlbrulee.fromEnv()` to source the API key. */
11
11
  const ENV_API_KEY = "CRAWLBRULEE_API_KEY";
12
12
  /** Identifies the SDK in the `User-Agent` header. Kept in one place for easy bumping. */
13
- const USER_AGENT = "@crawlbrulee/sdk/1.2.1 (node)";
13
+ const USER_AGENT = "@crawlbrulee/sdk/1.3.0 (node)";
14
14
 
15
15
  //#endregion
16
16
  //#region src/errors.ts
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/config.ts","../src/errors.ts","../src/instrumentation.ts","../src/http.ts","../src/client.ts","../src/webhooks.ts"],"sourcesContent":["/**\n * Production base URL of the crawlbrulee API. Used by default when the caller\n * doesn't pass a `baseUrl` to {@link Crawlbrulee}. Local development and\n * staging callers point at their own host via that option.\n */\nexport const DEFAULT_BASE_URL = 'https://api.crawlbrulee.com'\n\n/** Default request timeout when the caller doesn't specify one (0 disables the timeout). */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 0\n\n/** Environment variable read by `Crawlbrulee.fromEnv()` to source the API key. */\nexport const ENV_API_KEY = 'CRAWLBRULEE_API_KEY'\n\n/** Identifies the SDK in the `User-Agent` header. Kept in one place for easy bumping. */\nexport const USER_AGENT = '@crawlbrulee/sdk/1.2.1 (node)'\n","import type {\n ApiErrorDetails,\n ApiErrorName,\n ApiErrorResponse,\n RateLimitErrorDetails,\n UsageAllocationErrorDetails,\n} from './types/common.js'\n\n/**\n * Base error class for every failure raised by the SDK.\n *\n * Two kinds of failures end up here:\n *\n * 1. **API errors** — the server returned a non-2xx response with a well-formed\n * JSON body. In that case `status`, `errorName` and (sometimes) `details`\n * are populated.\n * 2. **Transport errors** — the request never produced a structured response\n * (network failure, abort, timeout, non-JSON body, etc.). In that case\n * `status` may be `0` and `errorName` is one of the synthetic transport\n * names (`request_timeout`, `client_closed_request`) or `null`.\n *\n * Typed subclasses are exported for the most common cases. To branch on more\n * specific server-side errors, switch on `err.errorName` or use the\n * {@link isCrawlbruleeError} helper.\n */\nexport class CrawlbruleeError extends Error {\n /** HTTP status code; `0` for transport-level failures with no response. */\n readonly status: number\n /** The `name` field from the API error body, or `null` for transport errors. */\n readonly errorName: ApiErrorName | null\n /** Structured detail block from the API error body, if any. */\n readonly details?: ApiErrorDetails\n /** The original parsed error body, when one was received. */\n readonly response?: ApiErrorResponse\n\n constructor(\n message: string,\n options: {\n status: number\n errorName: ApiErrorName | null\n details?: ApiErrorDetails\n response?: ApiErrorResponse\n cause?: unknown\n }\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined)\n this.name = 'CrawlbruleeError'\n this.status = options.status\n this.errorName = options.errorName\n this.details = options.details\n this.response = options.response\n }\n}\n\n/**\n * Raised when the API rejects your credentials — a missing, invalid, or\n * unauthorized API key (`invalid_credentials`, `access_denied`).\n *\n * Not every 403 is a key problem: a 403 carrying `antibot_blocked` is the\n * *target site* blocking us and raises {@link AntibotBlockedError} instead.\n * A 403 carrying `zero_data_retention_not_enabled` raises\n * {@link ZeroDataRetentionNotEnabledError}. Only an unrecognized 403 name falls\n * back to this class.\n */\nexport class AuthenticationError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'AuthenticationError'\n }\n}\n\n/**\n * Raised when the target site's anti-bot protection blocked the request\n * (HTTP 403, `antibot_blocked`). Not an API-key problem — retrying the same\n * tier rarely helps; try a higher proxy tier or skip the site.\n */\nexport class AntibotBlockedError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'AntibotBlockedError'\n }\n}\n\n/**\n * Raised when the target site redirected the request in a loop, or through\n * more hops than the API follows (HTTP 422, `too_many_redirects`). Like\n * {@link AntibotBlockedError} this is the target's doing — not a key problem\n * and not a bad request — so it is neither an `AuthenticationError` nor a\n * `ValidationError`. Retrying rarely helps. Returned by both `scrape` and `map`.\n */\nexport class TooManyRedirectsError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'TooManyRedirectsError'\n }\n}\n\n/**\n * Raised when the page's HTML was too large to process (HTTP 422,\n * `page_too_large`). Like {@link TooManyRedirectsError} this is about the page,\n * not your request — so it is neither an `AuthenticationError` nor a\n * `ValidationError`. It is terminal: the same URL fails the same way, so do not\n * retry it. Returned by `scrape`.\n */\nexport class PageTooLargeError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'PageTooLargeError'\n }\n}\n\n/**\n * Raised when we could not reach the target site at all (HTTP 502,\n * `target_unreachable`) — for example the site did not answer in time or its\n * TLS certificate was not valid. We never got a page, so there is nothing to\n * return and you are not charged. The message is always \"Could not reach the\n * target site.\" and there are no `details`.\n *\n * This is about the site, not your key or your request, so it is neither an\n * `AuthenticationError` nor a `ValidationError`. It is also not our own\n * outage ({@link ServiceUnavailableError}). Retrying later may help, since\n * the site may come back. The SDK does not retry for you.\n *\n * Not the same as a page with an error status: when the site answers with a\n * 404 or 503 page, the scrape succeeds and the site's status is in\n * `page_status_code`. Returned by both `scrape` and `map`.\n */\nexport class TargetUnreachableError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'TargetUnreachableError'\n }\n}\n\n/**\n * Raised when you send `zero_data_retention: true` but the option is not\n * enabled for your organization (HTTP 403, `zero_data_retention_not_enabled`).\n * The request is not billed. Not an API-key problem, so it is not an\n * {@link AuthenticationError}. See https://crawlbrulee.com/docs/zero-data-retention.\n */\nexport class ZeroDataRetentionNotEnabledError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'ZeroDataRetentionNotEnabledError'\n }\n}\n\n/**\n * Raised for HTTP 429 responses. When the server included a `retry_after_ms`\n * hint in `details` it is surfaced directly on the instance.\n *\n * `errorName` is always the literal `'too_many_requests'` — the SDK normalizes\n * this even when the server returns a 429 with a different `name` field. The\n * original body is still available on `response`.\n */\nexport class RateLimitError extends CrawlbruleeError {\n override readonly errorName: 'too_many_requests'\n /** Suggested delay (ms) before retrying, when the server provided one. */\n readonly retryAfterMs?: number\n /** Which rate limit was tripped (e.g. `org`, `ip`), when provided. */\n readonly limitedBy?: string\n\n constructor(\n message: string,\n options: {\n status: number\n details?: RateLimitErrorDetails\n response?: ApiErrorResponse\n }\n ) {\n super(message, { ...options, errorName: 'too_many_requests', details: options.details })\n this.name = 'RateLimitError'\n this.errorName = 'too_many_requests'\n this.retryAfterMs = options.details?.retry_after_ms\n this.limitedBy = options.details?.limited_by\n }\n}\n\n/**\n * Raised when the API rejects a request because the org's plan limits would\n * be exceeded (credit limit, concurrency cap, overage hard cap, etc.).\n *\n * `errorName` is always the literal `'usage_allocation_error'`.\n */\nexport class UsageAllocationError extends CrawlbruleeError {\n override readonly errorName: 'usage_allocation_error'\n /** Specific reason the allocation was denied. */\n readonly reason: UsageAllocationErrorDetails['reason']\n /** Current usage / limit snapshot at the time of the rejection. */\n readonly usage?: UsageAllocationErrorDetails['details']\n\n constructor(\n message: string,\n options: {\n status: number\n details: UsageAllocationErrorDetails\n response?: ApiErrorResponse\n }\n ) {\n super(message, { ...options, errorName: 'usage_allocation_error' })\n this.name = 'UsageAllocationError'\n this.errorName = 'usage_allocation_error'\n this.reason = options.details.reason\n this.usage = options.details.details\n }\n}\n\n/** Raised for 4xx responses caused by an invalid request shape or arguments. */\nexport class ValidationError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'ValidationError'\n }\n}\n\n/**\n * Raised for 404 responses from the crawlbrulee api — something on our side\n * was not found, for example an unknown or expired async job ID.\n *\n * It never means the target page was not found. When the site you scrape\n * answers with a 404 page, the scrape succeeds and returns that page with\n * `page_status_code: 404`.\n */\nexport class NotFoundError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Raised for 503 responses — the API could not serve the request right now\n * (a transient infrastructure failure, not a problem with your request).\n *\n * This is **retryable**: back off and try again. In particular it is not an\n * authentication failure, so it is never a reason to rotate your API key —\n * a genuinely bad or expired key still comes back as a 401\n * (`invalid_credentials`) and raises {@link AuthenticationError}.\n */\nexport class ServiceUnavailableError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'ServiceUnavailableError'\n }\n}\n\n/**\n * Raised when a request cannot be sent or no structured response is parsed.\n *\n * The `errorName` discriminates the cause:\n * - `'request_timeout'` — the per-request timeout fired.\n * - `'client_closed_request'` — the caller's `AbortSignal` fired.\n * - `null` — generic transport failure (network error, non-JSON body, etc.).\n */\nexport class TransportError extends CrawlbruleeError {\n constructor(\n message: string,\n options: {\n status?: number\n errorName?: 'request_timeout' | 'client_closed_request' | null\n cause?: unknown\n } = {}\n ) {\n super(message, {\n status: options.status ?? 0,\n errorName: options.errorName ?? null,\n cause: options.cause,\n })\n this.name = 'TransportError'\n }\n}\n\n/** Narrow `unknown` to the SDK's base error type. */\nexport function isCrawlbruleeError(err: unknown): err is CrawlbruleeError {\n return err instanceof CrawlbruleeError\n}\n\n/**\n * Map an API error body + HTTP status to the most specific error class.\n *\n * Dispatch is **name-first**: the body's `name` field is the most reliable\n * signal of what went wrong. Status code is used only as a fallback when the\n * name is unrecognized (e.g. a CDN-synthesized error). This avoids\n * miscategorizing things like a 403 with `name: 'not_found'` as an auth error.\n *\n * Internal — used by the HTTP layer.\n */\nexport function createApiError(body: ApiErrorResponse, status: number): CrawlbruleeError {\n const { name, message, details } = body\n const response = body\n\n switch (name) {\n case 'too_many_requests':\n return new RateLimitError(message, {\n status,\n details: details?.error_name === 'too_many_requests' ? details : undefined,\n response,\n })\n\n case 'usage_allocation_error': {\n // Without a structured details block we still want a typed error — fall\n // back to a synthetic `internal_error` reason so callers can branch.\n const usageDetails: UsageAllocationErrorDetails =\n details?.error_name === 'usage_allocation_error'\n ? details\n : { error_name: 'usage_allocation_error', reason: 'internal_error' }\n return new UsageAllocationError(message, { status, details: usageDetails, response })\n }\n\n case 'antibot_blocked':\n return new AntibotBlockedError(message, { status, errorName: name, response })\n\n case 'too_many_redirects':\n return new TooManyRedirectsError(message, { status, errorName: name, response })\n\n case 'page_too_large':\n return new PageTooLargeError(message, { status, errorName: name, response })\n\n case 'target_unreachable':\n return new TargetUnreachableError(message, { status, errorName: name, response })\n\n case 'zero_data_retention_not_enabled':\n return new ZeroDataRetentionNotEnabledError(message, { status, errorName: name, response })\n\n case 'invalid_credentials':\n case 'access_denied':\n return new AuthenticationError(message, { status, errorName: name, response })\n\n case 'not_found':\n return new NotFoundError(message, { status, errorName: name, response })\n\n case 'service_unavailable':\n return new ServiceUnavailableError(message, { status, errorName: name, response })\n\n case 'validation_error':\n case 'invalid_url':\n case 'url_too_long':\n case 'unsupported_url_schema':\n case 'url_credentials_not_supported':\n case 'blocked_url':\n case 'unsupported_content':\n case 'unsupported_screenshot_output':\n return new ValidationError(message, { status, errorName: name, response })\n }\n\n // Name was not specific enough — fall back to status-based heuristics, but\n // never override what the name said. A 429 with an unrecognized name still\n // promotes to RateLimitError (the class invariant normalizes errorName).\n if (status === 429) {\n return new RateLimitError(message, { status, response })\n }\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { status, errorName: name, response })\n }\n if (status === 404) {\n return new NotFoundError(message, { status, errorName: name, response })\n }\n if (status === 503) {\n return new ServiceUnavailableError(message, { status, errorName: name, response })\n }\n\n return new CrawlbruleeError(message, { status, errorName: name, details, response })\n}\n","import { DEFAULT_BASE_URL } from './config.js'\nimport { CrawlbruleeError } from './errors.js'\n\n/** Function shape compatible with the global `fetch`. */\nexport type FetchLike = typeof fetch\n\n/**\n * Centralized factory for the low-level dependencies the SDK injects into its\n * HTTP layer. Production code resolves these to the runtime's global `fetch`\n * and the burned-in production base URL; tests stub this module to swap in\n * mocks and alternate hosts.\n *\n * This is internal — it is not exported from the package's public entry. Tests\n * import it from `src/instrumentation.js` directly and use `vi.spyOn` to\n * substitute behavior.\n */\nexport const CwblInstrumentation = {\n /**\n * Resolve the `fetch` implementation the SDK should use. Throws a\n * {@link CrawlbruleeError} if the runtime does not expose a global `fetch`.\n */\n getFetch(): FetchLike {\n const g = globalThis as { fetch?: FetchLike }\n if (typeof g.fetch !== 'function') {\n throw new CrawlbruleeError(\n 'No global fetch is available in this runtime. crawlbrulee requires Node.js 22+, Bun, Deno, or a modern browser/edge runtime.',\n { status: 0, errorName: null }\n )\n }\n return g.fetch.bind(globalThis)\n },\n\n /**\n * Resolve the base URL the SDK should target. Returns the production host by\n * default; tests stub this to point at a mock origin.\n */\n getBaseUrl(): string {\n return DEFAULT_BASE_URL\n },\n}\n","import { DEFAULT_REQUEST_TIMEOUT_MS, USER_AGENT } from './config.js'\nimport { TransportError, createApiError, type CrawlbruleeError } from './errors.js'\nimport { CwblInstrumentation, type FetchLike } from './instrumentation.js'\nimport type { ApiErrorResponse } from './types/common.js'\n\n/** HTTP methods used by the SDK. */\nexport type HttpMethod = 'GET' | 'POST'\n\n/** Options the SDK accepts at construction time for the HTTP layer. */\nexport interface HttpClientOptions {\n /** API key sent as `Authorization: Bearer <key>`. */\n apiKey: string\n /**\n * Override the base URL. Trailing slashes are stripped. Falls back to\n * {@link CwblInstrumentation.getBaseUrl} (which resolves to the production\n * host) when unset.\n */\n baseUrl?: string\n /**\n * Per-request timeout in milliseconds. Pass `0` (or omit) to disable the\n * timeout entirely.\n */\n timeoutMs?: number\n}\n\n/** Per-call overrides accepted on every resource method. */\nexport interface RequestOptions {\n /** Abort the request when this signal fires. Composable with the timeout. */\n signal?: AbortSignal\n /**\n * Override the constructor-level `timeoutMs` for this call. Pass `0` to\n * disable the timeout for this call.\n */\n timeoutMs?: number\n}\n\ninterface SendArgs extends RequestOptions {\n method: HttpMethod\n path: string\n body?: unknown\n}\n\ninterface ComposedSignal {\n signal: AbortSignal | undefined\n /** Returns `true` if the abort was triggered by the per-request timeout. */\n timedOut: () => boolean\n /** Releases the timer and any listeners attached to the caller's signal. */\n cleanup: () => void\n}\n\n/**\n * Minimal `fetch`-based HTTP layer used by {@link Crawlbrulee}. Handles:\n *\n * - URL composition (joining `baseUrl` and path safely).\n * - JSON serialization and parsing.\n * - The `Authorization: Bearer …` header.\n * - Composing the caller's `AbortSignal` with an internal timeout signal. The\n * timeout covers the WHOLE request, including the response body read — not\n * just the time-to-headers.\n * - Mapping non-2xx responses to typed `CrawlbruleeError` subclasses via\n * {@link createApiError}.\n *\n * The base URL and `fetch` implementation are sourced from\n * {@link CwblInstrumentation} at construction time so tests can stub the\n * module.\n */\nexport class HttpClient {\n readonly baseUrl: string\n private readonly apiKey: string\n private readonly fetch: FetchLike\n private readonly timeoutMs: number\n\n constructor(options: HttpClientOptions) {\n this.baseUrl = stripTrailingSlash(options.baseUrl ?? CwblInstrumentation.getBaseUrl())\n this.apiKey = options.apiKey\n this.fetch = CwblInstrumentation.getFetch()\n this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS\n }\n\n /** Send a `GET` request and parse the response as `T`. */\n get<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.send<T>({ method: 'GET', path, ...options })\n }\n\n /** Send a `POST` request with a JSON body and parse the response as `T`. */\n post<T>(path: string, body: unknown, options?: RequestOptions): Promise<T> {\n return this.send<T>({ method: 'POST', path, body, ...options })\n }\n\n private async send<T>(args: SendArgs): Promise<T> {\n const url = this.buildUrl(args.path)\n const headers = this.buildHeaders(args)\n const body = args.body === undefined ? undefined : JSON.stringify(args.body)\n const composed = this.composeSignal(args.signal, args.timeoutMs)\n\n try {\n let res: Response\n try {\n res = await this.fetch(url, {\n method: args.method,\n headers,\n body,\n signal: composed.signal,\n })\n } catch (cause: unknown) {\n throw abortOrNetworkError(cause, composed.timedOut(), args.timeoutMs ?? this.timeoutMs)\n }\n\n let text: string\n try {\n text = await res.text()\n } catch (cause: unknown) {\n if (isAbortError(cause)) {\n throw abortOrNetworkError(cause, composed.timedOut(), args.timeoutMs ?? this.timeoutMs)\n }\n throw new TransportError(`Failed to read response body (status ${res.status}).`, {\n status: res.status,\n cause,\n })\n }\n\n const parsed = parseJsonOrThrow(text, res.status)\n if (!res.ok) throw toApiError(parsed, res.status, text)\n return parsed as T\n } finally {\n composed.cleanup()\n }\n }\n\n private buildUrl(path: string): string {\n if (!path.startsWith('/')) {\n throw new TypeError(`crawlbrulee SDK: path must start with '/' (received '${path}')`)\n }\n return `${this.baseUrl}${path}`\n }\n\n private buildHeaders(args: SendArgs): Record<string, string> {\n const headers: Record<string, string> = {\n accept: 'application/json',\n 'user-agent': USER_AGENT,\n authorization: `Bearer ${this.apiKey}`,\n }\n if (args.body !== undefined) headers['content-type'] = 'application/json'\n return headers\n }\n\n /**\n * Build a single `AbortSignal` that fires when either the caller-supplied\n * signal aborts OR the per-request timeout elapses. The returned `cleanup`\n * callback MUST be invoked on every exit path so we don't leak timers or\n * dead listeners on long-lived caller signals.\n */\n private composeSignal(\n callerSignal: AbortSignal | undefined,\n overrideTimeoutMs: number | undefined\n ): ComposedSignal {\n const timeoutMs = overrideTimeoutMs ?? this.timeoutMs\n const hasTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0\n\n if (!hasTimeout && !callerSignal) {\n return { signal: undefined, timedOut: () => false, cleanup: () => {} }\n }\n\n if (!hasTimeout) {\n return { signal: callerSignal, timedOut: () => false, cleanup: () => {} }\n }\n\n const controller = new AbortController()\n let didTimeout = false\n const timer = setTimeout(() => {\n didTimeout = true\n controller.abort(new Error('request_timeout'))\n }, timeoutMs)\n\n let onCallerAbort: (() => void) | undefined\n if (callerSignal) {\n if (callerSignal.aborted) {\n clearTimeout(timer)\n controller.abort(callerSignal.reason)\n } else {\n onCallerAbort = () => {\n clearTimeout(timer)\n controller.abort(callerSignal.reason)\n }\n callerSignal.addEventListener('abort', onCallerAbort, { once: true })\n }\n }\n\n const cleanup = () => {\n clearTimeout(timer)\n if (onCallerAbort && callerSignal) {\n callerSignal.removeEventListener('abort', onCallerAbort)\n }\n }\n\n return { signal: controller.signal, timedOut: () => didTimeout, cleanup }\n }\n}\n\nfunction stripTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, '')\n}\n\nfunction isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === 'AbortError'\n}\n\nfunction abortOrNetworkError(cause: unknown, timedOut: boolean, timeoutMs: number): TransportError {\n if (isAbortError(cause)) {\n if (timedOut) {\n return new TransportError(`Request timed out after ${timeoutMs}ms.`, {\n errorName: 'request_timeout',\n cause,\n })\n }\n return new TransportError('Request aborted by caller.', {\n errorName: 'client_closed_request',\n cause,\n })\n }\n return new TransportError(formatNetworkErrorMessage(cause), { cause })\n}\n\nfunction formatNetworkErrorMessage(cause: unknown): string {\n if (cause instanceof Error) {\n return `Network error: ${cause.message}`\n }\n return 'Network error: unknown failure while sending the request.'\n}\n\nfunction parseJsonOrThrow(text: string, status: number): unknown {\n if (text === '') return {}\n try {\n return JSON.parse(text)\n } catch (cause: unknown) {\n const preview = text.length > 200 ? `${text.slice(0, 200)}…` : text\n throw new TransportError(`Unexpected non-JSON response (status ${status}): ${preview}`, {\n status,\n cause,\n })\n }\n}\n\nfunction toApiError(parsed: unknown, status: number, rawText: string): CrawlbruleeError {\n if (isApiErrorResponse(parsed)) {\n return createApiError(parsed, status)\n }\n const preview = rawText.length > 200 ? `${rawText.slice(0, 200)}…` : rawText\n return new TransportError(`HTTP ${status}: ${preview || '(empty body)'}`, { status })\n}\n\nfunction isApiErrorResponse(value: unknown): value is ApiErrorResponse {\n if (value === null || typeof value !== 'object') return false\n const v = value as Record<string, unknown>\n return typeof v.name === 'string' && typeof v.message === 'string'\n}\n","import { ENV_API_KEY } from './config.js'\nimport { CrawlbruleeError } from './errors.js'\nimport { HttpClient, type RequestOptions } from './http.js'\nimport type {\n AsyncJobStatusResponse,\n AsyncScrapeRequest,\n AsyncScrapeResponse,\n MapRequest,\n MapResponse,\n ScrapeCompleteWebhook,\n ScrapeRequest,\n ScrapeResponse,\n UsageResponse,\n WhoamiResponse,\n} from './types/index.js'\n\n/** Options accepted by the {@link Crawlbrulee} constructor. */\nexport interface CrawlbruleeOptions {\n /**\n * API key sent as `Authorization: Bearer <key>`. Required — to read from the\n * environment instead, use {@link Crawlbrulee.fromEnv}. Leading and trailing\n * whitespace is stripped; an empty / whitespace-only value is rejected.\n */\n apiKey: string\n /**\n * Override the base URL the SDK targets. Defaults to the production host\n * ({@link DEFAULT_BASE_URL}). Intended for local development and staging\n * (e.g. `https://api.<staging-domain>`) — production callers should\n * leave it unset. Trailing slashes are stripped.\n */\n baseUrl?: string\n /**\n * Per-request timeout in milliseconds. Defaults to `0` (no timeout). Set to a\n * positive number to abort slow requests; a per-call `timeoutMs` override\n * takes precedence. The timeout covers the WHOLE request, including the\n * response body read.\n */\n timeoutMs?: number\n}\n\n/**\n * Options accepted by {@link Crawlbrulee.waitForScrape}.\n *\n * Note: `timeoutMs` here is the OVERALL wait budget across all polls — not the\n * per-HTTP-request timeout. The per-poll HTTP timeout is whatever the client\n * was constructed with; if you want to bound each individual poll, construct\n * the client with `timeoutMs` set.\n */\nexport interface WaitForScrapeOptions extends Omit<RequestOptions, 'timeoutMs'> {\n /** Time between status polls in milliseconds. Default `2000`. */\n intervalMs?: number\n /**\n * Maximum total time to wait before giving up, in milliseconds. Default\n * `300_000` (5 minutes). Pass `0` to wait indefinitely.\n */\n timeoutMs?: number\n}\n\n/**\n * Official client for the crawlbrulee API.\n *\n * @example\n * ```ts\n * import { Crawlbrulee } from '@crawlbrulee/sdk'\n *\n * const crawlbrulee = new Crawlbrulee({ apiKey: 'cwbl_…' })\n * // or read CRAWLBRULEE_API_KEY from the environment:\n * const crawlbrulee = Crawlbrulee.fromEnv()\n *\n * const page = await crawlbrulee.scrape({\n * url: 'https://example.com',\n * extract: { markdown: true, links: true },\n * })\n * console.log(page.markdown)\n * ```\n */\nexport class Crawlbrulee {\n /** Resolved base URL — trailing slash already stripped. */\n readonly baseUrl: string\n /** Underlying HTTP layer. Exposed for advanced use cases (custom endpoints). */\n readonly http: HttpClient\n\n constructor(options: CrawlbruleeOptions) {\n const apiKey = options.apiKey?.trim()\n if (!apiKey) {\n throw new CrawlbruleeError(\n `Missing API key. Pass { apiKey } to Crawlbrulee or call Crawlbrulee.fromEnv() to read ${ENV_API_KEY}.`,\n { status: 0, errorName: null }\n )\n }\n this.http = new HttpClient({ apiKey, baseUrl: options.baseUrl, timeoutMs: options.timeoutMs })\n this.baseUrl = this.http.baseUrl\n }\n\n /**\n * Build a {@link Crawlbrulee} reading the API key from\n * `process.env.CRAWLBRULEE_API_KEY`. Throws if the variable is unset, empty,\n * or whitespace.\n *\n * Any other constructor option can be passed via `overrides`.\n *\n * @example\n * ```ts\n * const crawlbrulee = Crawlbrulee.fromEnv()\n * const crawlbrulee = Crawlbrulee.fromEnv({ timeoutMs: 30_000 })\n * ```\n */\n static fromEnv(overrides: Omit<CrawlbruleeOptions, 'apiKey'> = {}): Crawlbrulee {\n const apiKey = readEnv(ENV_API_KEY)\n if (!apiKey) {\n throw new CrawlbruleeError(\n `${ENV_API_KEY} is not set. Export it in your shell, or pass apiKey to new Crawlbrulee({ apiKey }).`,\n { status: 0, errorName: null }\n )\n }\n return new Crawlbrulee({ ...overrides, apiKey })\n }\n\n // ------------------------------------------------------------------\n // Scraping\n // ------------------------------------------------------------------\n\n /**\n * Scrape a URL synchronously and return the extracted content.\n *\n * The request blocks until the scrape is finished. For long-running jobs\n * (heavy JS rendering, screenshots of long pages) prefer\n * {@link Crawlbrulee.scrapeAsync} so the connection isn't held open.\n *\n * Any page the site really served is returned, whatever its status: a 404,\n * 410, 401 or 503 page resolves normally, with the site's status in\n * `page_status_code` — it does not throw. Check that field when the page's\n * status matters to you. The call throws when we could not return the page,\n * for example `TargetUnreachableError` when the site could not be reached,\n * `AntibotBlockedError`, or `PageTooLargeError`.\n *\n * @param request — body for `POST /api/scrape`.\n * @param options — per-call timeout and abort signal.\n */\n scrape(request: ScrapeRequest, options?: RequestOptions): Promise<ScrapeResponse> {\n return this.http.post<ScrapeResponse>('/api/scrape', request, options)\n }\n\n /**\n * Submit an asynchronous scrape job and return its `job_id`. Poll the job\n * with {@link Crawlbrulee.getScrapeStatus} or wait for completion with\n * {@link Crawlbrulee.waitForScrape}.\n *\n * Pass an optional `webhook` to have the API deliver a signed\n * `scrape.complete` `POST` to your endpoint when the job finishes (see\n * {@link AsyncScrapeWebhook}). This field is async-only.\n */\n scrapeAsync(request: AsyncScrapeRequest, options?: RequestOptions): Promise<AsyncScrapeResponse> {\n return this.http.post<AsyncScrapeResponse>('/api/scrape/async', request, options)\n }\n\n /** Look up the current status of an async scrape job. */\n getScrapeStatus(jobId: string, options?: RequestOptions): Promise<AsyncJobStatusResponse> {\n assertNonEmptyJobId(jobId)\n return this.http.get<AsyncJobStatusResponse>(\n `/api/scrape/status/${encodeURIComponent(jobId)}`,\n options\n )\n }\n\n /**\n * Fetch the result of a completed async scrape job. Throws if the job is\n * still pending/running — call {@link Crawlbrulee.getScrapeStatus}\n * first, or use {@link Crawlbrulee.waitForScrape} to poll-then-fetch.\n *\n * Like {@link Crawlbrulee.scrape}, a 404 (or any other) page the site served\n * is a completed job: the result carries the site's status in\n * `page_status_code`.\n */\n getScrapeResult(jobId: string, options?: RequestOptions): Promise<ScrapeResponse> {\n assertNonEmptyJobId(jobId)\n return this.http.get<ScrapeResponse>(`/api/scrape/result/${encodeURIComponent(jobId)}`, options)\n }\n\n /**\n * Fetch the scrape result referenced by a `scrape.complete` webhook body.\n *\n * Always verify the webhook signature with `verifyWebhookSignature` before\n * acting on it; this method trusts the parsed body it is handed.\n *\n * Behavior by `data.status`:\n * - `success` — delegates to {@link Crawlbrulee.getScrapeResult} for the\n * webhook's `job_id` and returns the parsed result.\n * - `failed` — throws a {@link CrawlbruleeError} carrying `data.error`\n * (`errorName: 'job_failed'`); there is no result to fetch.\n * - `cancelled` — throws a {@link CrawlbruleeError}\n * (`errorName: 'client_closed_request'`).\n *\n * A non-`scrape.complete` envelope throws a {@link CrawlbruleeError}\n * defensively. Any HTTP error from the underlying fetch propagates as the\n * usual typed `CrawlbruleeError` subclass.\n */\n async fetchScrapeResultFromWebhook(\n webhook: ScrapeCompleteWebhook,\n options?: RequestOptions\n ): Promise<ScrapeResponse> {\n if (webhook?.event !== 'scrape.complete') {\n throw new CrawlbruleeError(\n `Expected a 'scrape.complete' webhook but received '${String(webhook?.event)}'.`,\n { status: 0, errorName: 'validation_error' }\n )\n }\n\n const { job_id: jobId, status, error } = webhook.data\n\n switch (status) {\n case 'success':\n return this.getScrapeResult(jobId, options)\n\n case 'failed':\n throw new CrawlbruleeError(error ?? `Async scrape job ${jobId} failed.`, {\n status: 0,\n errorName: 'job_failed',\n })\n\n case 'cancelled':\n throw new CrawlbruleeError(`Async scrape job ${jobId} was cancelled.`, {\n status: 0,\n errorName: 'client_closed_request',\n })\n\n default:\n throw new CrawlbruleeError(\n `Async scrape webhook for job ${jobId} carried an unexpected status '${String(status)}'.`,\n { status: 0, errorName: 'validation_error' }\n )\n }\n }\n\n /**\n * Poll an async scrape job until it reaches a terminal state, then return\n * the scrape result.\n *\n * Throws a {@link CrawlbruleeError} when:\n * - the job ends in `failed` (`errorName: 'job_failed'`),\n * - the server reports an unexpected status (`errorName: 'job_failed'`),\n * - the overall wait exceeds `timeoutMs` (`errorName: 'request_timeout'`),\n * - the caller's `signal` aborts (`errorName: 'client_closed_request'`).\n */\n async waitForScrape(jobId: string, options: WaitForScrapeOptions = {}): Promise<ScrapeResponse> {\n assertNonEmptyJobId(jobId)\n const intervalMs = options.intervalMs ?? 2000\n const timeoutMs = options.timeoutMs ?? 300_000\n const deadline = timeoutMs > 0 ? Date.now() + timeoutMs : Number.POSITIVE_INFINITY\n\n while (true) {\n throwIfAborted(options.signal)\n if (Date.now() >= deadline) {\n throw new CrawlbruleeError(\n `Timed out after ${timeoutMs}ms waiting for async scrape job ${jobId}.`,\n { status: 0, errorName: 'request_timeout' }\n )\n }\n\n const status = await this.getScrapeStatus(jobId, { signal: options.signal })\n\n switch (status.status) {\n case 'done':\n return this.getScrapeResult(jobId, { signal: options.signal })\n\n case 'failed':\n throw new CrawlbruleeError(status.error ?? `Async scrape job ${jobId} failed.`, {\n status: 0,\n errorName: 'job_failed',\n })\n\n case 'pending':\n case 'running':\n break\n\n default:\n throw new CrawlbruleeError(\n `Async scrape job ${jobId} returned unexpected status '${String(status.status)}'.`,\n { status: 0, errorName: 'job_failed' }\n )\n }\n\n await sleep(intervalMs, options.signal)\n }\n }\n\n // ------------------------------------------------------------------\n // Mapping\n // ------------------------------------------------------------------\n\n /**\n * Build (or return a cached) site link-map for a domain. Combines sitemap\n * discovery with the freshest cached homepage scrape when available.\n */\n map(request: MapRequest, options?: RequestOptions): Promise<MapResponse> {\n return this.http.post<MapResponse>('/api/map', request, options)\n }\n\n // ------------------------------------------------------------------\n // Account\n // ------------------------------------------------------------------\n\n /**\n * Return the current billing-cycle usage: total/used/available credits,\n * used quota percentage, max concurrency, and when the cycle resets.\n */\n usage(options?: RequestOptions): Promise<UsageResponse> {\n return this.http.get<UsageResponse>('/api/usage', options)\n }\n\n /**\n * Return the organization name and identifying details of the API token\n * used to authenticate this request. Useful for confirming which key is in\n * use before performing destructive operations.\n */\n whoami(options?: RequestOptions): Promise<WhoamiResponse> {\n return this.http.get<WhoamiResponse>('/api/whoami', options)\n }\n}\n\n/**\n * Defensive read of `process.env[name]`. Guards both the absence of `process`\n * (browser / edge runtimes) and Deno's permission throw on env access without\n * `--allow-env`.\n */\nfunction readEnv(name: string): string | undefined {\n try {\n if (typeof process === 'undefined' || !process.env) return undefined\n const v = process.env[name]\n return typeof v === 'string' && v.trim().length > 0 ? v.trim() : undefined\n } catch {\n return undefined\n }\n}\n\nfunction assertNonEmptyJobId(jobId: string): void {\n if (typeof jobId !== 'string' || jobId.trim().length === 0) {\n throw new CrawlbruleeError('jobId must be a non-empty string.', {\n status: 0,\n errorName: null,\n })\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw new CrawlbruleeError('Request aborted by caller.', {\n status: 0,\n errorName: 'client_closed_request',\n cause: signal.reason,\n })\n }\n}\n\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer)\n reject(\n new CrawlbruleeError('Request aborted by caller.', {\n status: 0,\n errorName: 'client_closed_request',\n cause: signal?.reason,\n })\n )\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n if (signal) {\n if (signal.aborted) {\n clearTimeout(timer)\n onAbort()\n return\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n}\n","/**\n * Verification for async scrape completion webhooks.\n *\n * {@link verifyWebhookSignature} validates the signature crawlbrulee attaches to\n * every webhook delivery. It is a standalone, network-free helper built on Web\n * Crypto (`globalThis.crypto.subtle`) so it runs unchanged on Node.js 22+,\n * browsers, Bun, Deno, and edge runtimes — it never touches `node:crypto`.\n */\n\n/** HTTP header carrying the primary webhook signature (always present). */\nexport const WEBHOOK_SIGNATURE_HEADER = 'X-Cwbl-Signature'\n\n/**\n * HTTP header carrying a signature produced with the previous signing secret.\n * Present only during a signing-secret rotation grace window.\n */\nexport const WEBHOOK_SIGNATURE_ROTATED_HEADER = 'X-Cwbl-Signature-Rotated'\n\n/** HTTP header carrying the unique event id, useful for delivery de-duplication. */\nexport const WEBHOOK_EVENT_ID_HEADER = 'X-Cwbl-Event-Id'\n\n/** Default replay-protection window (seconds) applied to the signed timestamp. */\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300\n\n/** Which signature header satisfied verification. */\nexport type WebhookSignatureSource = 'primary' | 'rotated'\n\n/**\n * Why a webhook signature failed to verify.\n *\n * - `missing_signature` — neither the primary nor the rotated header was present.\n * - `malformed_signature` — a header was present but not in the expected\n * `t=<unix_seconds>,v1=<64_hex>` format.\n * - `timestamp_out_of_tolerance` — the signed timestamp drifted further from now\n * than `toleranceSeconds` allows (replay protection).\n * - `signature_mismatch` — a well-formed, in-tolerance signature did not match\n * the one computed from the payload and secret.\n */\nexport type WebhookVerificationFailureReason =\n | 'missing_signature'\n | 'malformed_signature'\n | 'timestamp_out_of_tolerance'\n | 'signature_mismatch'\n\n/** Result of {@link verifyWebhookSignature}. Verification failure is returned, not thrown. */\nexport type WebhookVerificationResult =\n | { verified: true; signedWith: WebhookSignatureSource }\n | { verified: false; reason: WebhookVerificationFailureReason }\n\n/** Options for {@link verifyWebhookSignature}. */\nexport interface VerifyWebhookSignatureOptions {\n /**\n * The raw request body, exactly as received. Pass the bytes/string the server\n * signed — do NOT re-serialize parsed JSON, or the signature will not match.\n */\n payload: string | Uint8Array\n /**\n * The request headers. Accepts a fetch `Headers` instance or a plain object\n * (Express/Node give lowercased keys, values possibly arrays). Lookup is\n * case-insensitive.\n */\n headers: Headers | Record<string, string | string[] | undefined>\n /** The current signing secret (`whsec_…`). */\n secret: string\n /**\n * Replay-protection window in seconds. Defaults to\n * {@link DEFAULT_WEBHOOK_TOLERANCE_SECONDS} (300). Pass `0` (or any falsy\n * value) to disable the timestamp check entirely.\n */\n toleranceSeconds?: number\n}\n\nconst SIGNATURE_FORMAT = /^t=(\\d+),v1=([0-9a-f]{64})$/\n\ninterface ParsedSignature {\n timestamp: number\n signature: string\n}\n\n/**\n * Verify a crawlbrulee webhook signature against the primary and rotated\n * headers.\n *\n * The signing scheme matches the backend:\n * - the signed payload is `` `${t}.${rawBody}` `` where `t` is the unix-seconds\n * integer from the header and `rawBody` is the raw request body,\n * - the signature is `HMAC-SHA256(secret, signedPayload)` as lowercase hex,\n * - the header value is `t=<unix_seconds>,v1=<64_hex>`.\n *\n * The supplied `secret` is tried against the primary header first, then the\n * rotated header (which the API emits during a signing-secret rotation grace\n * window). Whichever matches wins, and the result reports which header it was.\n *\n * This NEVER throws on a verification failure — failures are normal control\n * flow and are returned as `{ verified: false, reason }`.\n *\n * @example\n * ```ts\n * const result = await verifyWebhookSignature({\n * payload: rawBody,\n * headers: req.headers,\n * secret: process.env.CRAWLBRULEE_WEBHOOK_SECRET!,\n * })\n * if (!result.verified) return res.status(400).end()\n * ```\n */\nexport async function verifyWebhookSignature(\n options: VerifyWebhookSignatureOptions\n): Promise<WebhookVerificationResult> {\n const { payload, headers, secret } = options\n const toleranceSeconds = options.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS\n\n const primaryHeader = getHeader(headers, WEBHOOK_SIGNATURE_HEADER)\n const rotatedHeader = getHeader(headers, WEBHOOK_SIGNATURE_ROTATED_HEADER)\n\n if (primaryHeader === undefined && rotatedHeader === undefined) {\n return { verified: false, reason: 'missing_signature' }\n }\n\n const nowSeconds = Math.floor(Date.now() / 1000)\n const body = toBytes(payload)\n const key = await importHmacKey(secret)\n\n // Track the \"best\" failure reason so the result is informative: a real\n // mismatch should win over a malformed sibling header. Order from least to\n // most specific.\n let failure: WebhookVerificationFailureReason = 'malformed_signature'\n\n for (const source of ['primary', 'rotated'] as const) {\n const raw = source === 'primary' ? primaryHeader : rotatedHeader\n if (raw === undefined) continue\n\n const parsed = parseSignatureHeader(raw)\n if (!parsed) {\n // A malformed header can't verify; keep looking at the other one.\n continue\n }\n\n if (toleranceSeconds && Math.abs(nowSeconds - parsed.timestamp) > toleranceSeconds) {\n failure = mostSpecificFailure(failure, 'timestamp_out_of_tolerance')\n continue\n }\n\n const expected = await computeSignatureHex(key, parsed.timestamp, body)\n if (constantTimeEqualHex(expected, parsed.signature)) {\n return { verified: true, signedWith: source }\n }\n\n failure = mostSpecificFailure(failure, 'signature_mismatch')\n }\n\n return { verified: false, reason: failure }\n}\n\n/**\n * Rank verification failures so the returned reason reflects the most\n * actionable problem encountered across the two headers.\n */\nfunction mostSpecificFailure(\n current: WebhookVerificationFailureReason,\n candidate: WebhookVerificationFailureReason\n): WebhookVerificationFailureReason {\n const rank: Record<WebhookVerificationFailureReason, number> = {\n missing_signature: 0,\n malformed_signature: 1,\n timestamp_out_of_tolerance: 2,\n signature_mismatch: 3,\n }\n return rank[candidate] > rank[current] ? candidate : current\n}\n\n/** Case-insensitive header lookup over `Headers` or a plain object. */\nfunction getHeader(\n headers: Headers | Record<string, string | string[] | undefined>,\n name: string\n): string | undefined {\n if (typeof Headers !== 'undefined' && headers instanceof Headers) {\n return headers.get(name) ?? undefined\n }\n const target = name.toLowerCase()\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() !== target) continue\n const value = (headers as Record<string, string | string[] | undefined>)[key]\n if (Array.isArray(value)) return value[0]\n return value ?? undefined\n }\n return undefined\n}\n\nfunction parseSignatureHeader(value: string): ParsedSignature | null {\n const match = SIGNATURE_FORMAT.exec(value.trim())\n if (!match) return null\n const timestamp = Number(match[1])\n if (!Number.isSafeInteger(timestamp)) return null\n return { timestamp, signature: match[2]! }\n}\n\nfunction toBytes(payload: string | Uint8Array): Uint8Array {\n return typeof payload === 'string' ? new TextEncoder().encode(payload) : payload\n}\n\n/**\n * Web Crypto types, derived from the runtime global so we don't have to pull in\n * the DOM `lib` (the SDK compiles against `lib: ES2022` + `@types/node`).\n */\ntype SubtleCryptoLike = typeof globalThis.crypto.subtle\ntype CryptoKeyLike = Awaited<ReturnType<SubtleCryptoLike['importKey']>>\n\nfunction importHmacKey(secret: string): Promise<CryptoKeyLike> {\n return getSubtle().importKey(\n 'raw',\n new TextEncoder().encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign']\n )\n}\n\nasync function computeSignatureHex(\n key: CryptoKeyLike,\n timestamp: number,\n body: Uint8Array\n): Promise<string> {\n const prefix = new TextEncoder().encode(`${timestamp}.`)\n const message = new Uint8Array(prefix.length + body.length)\n message.set(prefix, 0)\n message.set(body, prefix.length)\n const digest = await getSubtle().sign('HMAC', key, message)\n return toHex(new Uint8Array(digest))\n}\n\nfunction toHex(bytes: Uint8Array): string {\n let hex = ''\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, '0')\n }\n return hex\n}\n\n/**\n * Length-checked, constant-time comparison of two lowercase hex strings. Folds\n * every byte into an accumulator with XOR — never early-returns on the first\n * mismatch — so timing does not leak how much of the signature matched.\n */\nfunction constantTimeEqualHex(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n }\n return diff === 0\n}\n\nfunction getSubtle(): SubtleCryptoLike {\n const subtle = globalThis.crypto?.subtle\n if (!subtle) {\n throw new Error(\n 'Web Crypto (globalThis.crypto.subtle) is not available in this runtime. crawlbrulee webhook verification requires Node.js 22+, Bun, Deno, or a modern browser/edge runtime.'\n )\n }\n return subtle\n}\n"],"mappings":";;;;;;AAKA,MAAa,mBAAmB;;AAGhC,MAAa,6BAA6B;;AAG1C,MAAa,cAAc;;AAG3B,MAAa,aAAa;;;;;;;;;;;;;;;;;;;;;ACW1B,IAAa,mBAAb,cAAsC,MAAM;;CAE1C,AAAS;;CAET,AAAS;;CAET,AAAS;;CAET,AAAS;CAET,YACE,SACA,SAOA;EACA,MAAM,SAAS,QAAQ,UAAU,SAAY,EAAE,OAAO,QAAQ,MAAM,IAAI,MAAS;EACjF,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,YAAY,QAAQ;EACzB,KAAK,UAAU,QAAQ;EACvB,KAAK,WAAW,QAAQ;CAC1B;AACF;;;;;;;;;;;AAYA,IAAa,sBAAb,cAAyC,iBAAiB;CACxD,YACE,SACA,SACA;EACA,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;;;;;;AAOA,IAAa,sBAAb,cAAyC,iBAAiB;CACxD,YACE,SACA,SACA;EACA,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;;;;;;;;AASA,IAAa,wBAAb,cAA2C,iBAAiB;CAC1D,YACE,SACA,SACA;EACA,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;;;;;;;;AASA,IAAa,oBAAb,cAAuC,iBAAiB;CACtD,YACE,SACA,SACA;EACA,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;;;;;AAkBA,IAAa,yBAAb,cAA4C,iBAAiB;CAC3D,YACE,SACA,SACA;EACA,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;;;;;;;AAQA,IAAa,mCAAb,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AI,MACR,6KACF;CAEF,OAAO;AACT"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/config.ts","../src/errors.ts","../src/instrumentation.ts","../src/http.ts","../src/client.ts","../src/webhooks.ts"],"sourcesContent":["/**\n * Production base URL of the crawlbrulee API. Used by default when the caller\n * doesn't pass a `baseUrl` to {@link Crawlbrulee}. Local development and\n * staging callers point at their own host via that option.\n */\nexport const DEFAULT_BASE_URL = 'https://api.crawlbrulee.com'\n\n/** Default request timeout when the caller doesn't specify one (0 disables the timeout). */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 0\n\n/** Environment variable read by `Crawlbrulee.fromEnv()` to source the API key. */\nexport const ENV_API_KEY = 'CRAWLBRULEE_API_KEY'\n\n/** Identifies the SDK in the `User-Agent` header. Kept in one place for easy bumping. */\nexport const USER_AGENT = '@crawlbrulee/sdk/1.3.0 (node)'\n","import type {\n ApiErrorDetails,\n ApiErrorName,\n ApiErrorResponse,\n RateLimitErrorDetails,\n UsageAllocationErrorDetails,\n} from './types/common.js'\n\n/**\n * Base error class for every failure raised by the SDK.\n *\n * Two kinds of failures end up here:\n *\n * 1. **API errors** — the server returned a non-2xx response with a well-formed\n * JSON body. In that case `status`, `errorName` and (sometimes) `details`\n * are populated.\n * 2. **Transport errors** — the request never produced a structured response\n * (network failure, abort, timeout, non-JSON body, etc.). In that case\n * `status` may be `0` and `errorName` is one of the synthetic transport\n * names (`request_timeout`, `client_closed_request`) or `null`.\n *\n * Typed subclasses are exported for the most common cases. To branch on more\n * specific server-side errors, switch on `err.errorName` or use the\n * {@link isCrawlbruleeError} helper.\n */\nexport class CrawlbruleeError extends Error {\n /** HTTP status code; `0` for transport-level failures with no response. */\n readonly status: number\n /** The `name` field from the API error body, or `null` for transport errors. */\n readonly errorName: ApiErrorName | null\n /** Structured detail block from the API error body, if any. */\n readonly details?: ApiErrorDetails\n /** The original parsed error body, when one was received. */\n readonly response?: ApiErrorResponse\n\n constructor(\n message: string,\n options: {\n status: number\n errorName: ApiErrorName | null\n details?: ApiErrorDetails\n response?: ApiErrorResponse\n cause?: unknown\n }\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined)\n this.name = 'CrawlbruleeError'\n this.status = options.status\n this.errorName = options.errorName\n this.details = options.details\n this.response = options.response\n }\n}\n\n/**\n * Raised when the API rejects your credentials — a missing, invalid, or\n * unauthorized API key (`invalid_credentials`, `access_denied`).\n *\n * Not every 403 is a key problem: a 403 carrying `antibot_blocked` is the\n * *target site* blocking us and raises {@link AntibotBlockedError} instead.\n * A 403 carrying `zero_data_retention_not_enabled` raises\n * {@link ZeroDataRetentionNotEnabledError}. Only an unrecognized 403 name falls\n * back to this class.\n */\nexport class AuthenticationError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'AuthenticationError'\n }\n}\n\n/**\n * Raised when the target site's anti-bot protection blocked the request\n * (HTTP 403, `antibot_blocked`). Not an API-key problem — retrying the same\n * tier rarely helps; try a higher proxy tier or skip the site.\n */\nexport class AntibotBlockedError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'AntibotBlockedError'\n }\n}\n\n/**\n * Raised when the target site redirected the request in a loop, or through\n * more hops than the API follows (HTTP 422, `too_many_redirects`). Like\n * {@link AntibotBlockedError} this is the target's doing — not a key problem\n * and not a bad request — so it is neither an `AuthenticationError` nor a\n * `ValidationError`. Retrying rarely helps. Returned by both `scrape` and `map`.\n */\nexport class TooManyRedirectsError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'TooManyRedirectsError'\n }\n}\n\n/**\n * Raised when the page's HTML was too large to process (HTTP 422,\n * `page_too_large`). Like {@link TooManyRedirectsError} this is about the page,\n * not your request — so it is neither an `AuthenticationError` nor a\n * `ValidationError`. It is terminal: the same URL fails the same way, so do not\n * retry it. Returned by `scrape`.\n */\nexport class PageTooLargeError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'PageTooLargeError'\n }\n}\n\n/**\n * Raised when we could not reach the target site at all (HTTP 502,\n * `target_unreachable`) — for example the site did not answer in time or its\n * TLS certificate was not valid. We never got a page, so there is nothing to\n * return and you are not charged. The message is always \"Could not reach the\n * target site.\" and there are no `details`.\n *\n * This is about the site, not your key or your request, so it is neither an\n * `AuthenticationError` nor a `ValidationError`. It is also not our own\n * outage ({@link ServiceUnavailableError}). Retrying later may help, since\n * the site may come back. The SDK does not retry for you.\n *\n * Not the same as a page with an error status: when the site answers with a\n * 404 or 503 page, the scrape succeeds and the site's status is in\n * `page_status_code`. Returned by both `scrape` and `map`.\n */\nexport class TargetUnreachableError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'TargetUnreachableError'\n }\n}\n\n/**\n * Raised when you send `zero_data_retention: true` but the option is not\n * enabled for your organization (HTTP 403, `zero_data_retention_not_enabled`).\n * The request is not billed. Not an API-key problem, so it is not an\n * {@link AuthenticationError}. See https://crawlbrulee.com/docs/zero-data-retention.\n */\nexport class ZeroDataRetentionNotEnabledError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'ZeroDataRetentionNotEnabledError'\n }\n}\n\n/**\n * Raised for HTTP 429 responses. When the server included a `retry_after_ms`\n * hint in `details` it is surfaced directly on the instance.\n *\n * `errorName` is always the literal `'too_many_requests'` — the SDK normalizes\n * this even when the server returns a 429 with a different `name` field. The\n * original body is still available on `response`.\n */\nexport class RateLimitError extends CrawlbruleeError {\n override readonly errorName: 'too_many_requests'\n /** Suggested delay (ms) before retrying, when the server provided one. */\n readonly retryAfterMs?: number\n /** Which rate limit was tripped (e.g. `org`, `ip`), when provided. */\n readonly limitedBy?: string\n\n constructor(\n message: string,\n options: {\n status: number\n details?: RateLimitErrorDetails\n response?: ApiErrorResponse\n }\n ) {\n super(message, { ...options, errorName: 'too_many_requests', details: options.details })\n this.name = 'RateLimitError'\n this.errorName = 'too_many_requests'\n this.retryAfterMs = options.details?.retry_after_ms\n this.limitedBy = options.details?.limited_by\n }\n}\n\n/**\n * Raised when the API rejects a request because the org's plan limits would\n * be exceeded (credit limit, concurrency cap, overage hard cap, etc.).\n *\n * `errorName` is always the literal `'usage_allocation_error'`.\n */\nexport class UsageAllocationError extends CrawlbruleeError {\n override readonly errorName: 'usage_allocation_error'\n /** Specific reason the allocation was denied. */\n readonly reason: UsageAllocationErrorDetails['reason']\n /** Current usage / limit snapshot at the time of the rejection. */\n readonly usage?: UsageAllocationErrorDetails['details']\n\n constructor(\n message: string,\n options: {\n status: number\n details: UsageAllocationErrorDetails\n response?: ApiErrorResponse\n }\n ) {\n super(message, { ...options, errorName: 'usage_allocation_error' })\n this.name = 'UsageAllocationError'\n this.errorName = 'usage_allocation_error'\n this.reason = options.details.reason\n this.usage = options.details.details\n }\n}\n\n/** Raised for 4xx responses caused by an invalid request shape or arguments. */\nexport class ValidationError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'ValidationError'\n }\n}\n\n/**\n * Raised for 404 responses from the crawlbrulee api — something on our side\n * was not found, for example an unknown or expired async job ID.\n *\n * It never means the target page was not found. When the site you scrape\n * answers with a 404 page, the scrape succeeds and returns that page with\n * `page_status_code: 404`.\n */\nexport class NotFoundError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Raised for 503 responses — the API could not serve the request right now\n * (a transient infrastructure failure, not a problem with your request).\n *\n * This is **retryable**: back off and try again. In particular it is not an\n * authentication failure, so it is never a reason to rotate your API key —\n * a genuinely bad or expired key still comes back as a 401\n * (`invalid_credentials`) and raises {@link AuthenticationError}.\n */\nexport class ServiceUnavailableError extends CrawlbruleeError {\n constructor(\n message: string,\n options: { status: number; errorName: ApiErrorName; response?: ApiErrorResponse }\n ) {\n super(message, options)\n this.name = 'ServiceUnavailableError'\n }\n}\n\n/**\n * Raised when a request cannot be sent or no structured response is parsed.\n *\n * The `errorName` discriminates the cause:\n * - `'request_timeout'` — the per-request timeout fired.\n * - `'client_closed_request'` — the caller's `AbortSignal` fired.\n * - `null` — generic transport failure (network error, non-JSON body, etc.).\n */\nexport class TransportError extends CrawlbruleeError {\n constructor(\n message: string,\n options: {\n status?: number\n errorName?: 'request_timeout' | 'client_closed_request' | null\n cause?: unknown\n } = {}\n ) {\n super(message, {\n status: options.status ?? 0,\n errorName: options.errorName ?? null,\n cause: options.cause,\n })\n this.name = 'TransportError'\n }\n}\n\n/** Narrow `unknown` to the SDK's base error type. */\nexport function isCrawlbruleeError(err: unknown): err is CrawlbruleeError {\n return err instanceof CrawlbruleeError\n}\n\n/**\n * Map an API error body + HTTP status to the most specific error class.\n *\n * Dispatch is **name-first**: the body's `name` field is the most reliable\n * signal of what went wrong. Status code is used only as a fallback when the\n * name is unrecognized (e.g. a CDN-synthesized error). This avoids\n * miscategorizing things like a 403 with `name: 'not_found'` as an auth error.\n *\n * Internal — used by the HTTP layer.\n */\nexport function createApiError(body: ApiErrorResponse, status: number): CrawlbruleeError {\n const { name, message, details } = body\n const response = body\n\n switch (name) {\n case 'too_many_requests':\n return new RateLimitError(message, {\n status,\n details: details?.error_name === 'too_many_requests' ? details : undefined,\n response,\n })\n\n case 'usage_allocation_error': {\n // Without a structured details block we still want a typed error — fall\n // back to a synthetic `internal_error` reason so callers can branch.\n const usageDetails: UsageAllocationErrorDetails =\n details?.error_name === 'usage_allocation_error'\n ? details\n : { error_name: 'usage_allocation_error', reason: 'internal_error' }\n return new UsageAllocationError(message, { status, details: usageDetails, response })\n }\n\n case 'antibot_blocked':\n return new AntibotBlockedError(message, { status, errorName: name, response })\n\n case 'too_many_redirects':\n return new TooManyRedirectsError(message, { status, errorName: name, response })\n\n case 'page_too_large':\n return new PageTooLargeError(message, { status, errorName: name, response })\n\n case 'target_unreachable':\n return new TargetUnreachableError(message, { status, errorName: name, response })\n\n case 'zero_data_retention_not_enabled':\n return new ZeroDataRetentionNotEnabledError(message, { status, errorName: name, response })\n\n case 'invalid_credentials':\n case 'access_denied':\n return new AuthenticationError(message, { status, errorName: name, response })\n\n case 'not_found':\n return new NotFoundError(message, { status, errorName: name, response })\n\n case 'service_unavailable':\n return new ServiceUnavailableError(message, { status, errorName: name, response })\n\n case 'validation_error':\n case 'invalid_url':\n case 'url_too_long':\n case 'unsupported_url_schema':\n case 'url_credentials_not_supported':\n case 'blocked_url':\n case 'unsupported_content':\n case 'unsupported_screenshot_output':\n return new ValidationError(message, { status, errorName: name, response })\n }\n\n // Name was not specific enough — fall back to status-based heuristics, but\n // never override what the name said. A 429 with an unrecognized name still\n // promotes to RateLimitError (the class invariant normalizes errorName).\n if (status === 429) {\n return new RateLimitError(message, { status, response })\n }\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { status, errorName: name, response })\n }\n if (status === 404) {\n return new NotFoundError(message, { status, errorName: name, response })\n }\n if (status === 503) {\n return new ServiceUnavailableError(message, { status, errorName: name, response })\n }\n\n return new CrawlbruleeError(message, { status, errorName: name, details, response })\n}\n","import { DEFAULT_BASE_URL } from './config.js'\nimport { CrawlbruleeError } from './errors.js'\n\n/** Function shape compatible with the global `fetch`. */\nexport type FetchLike = typeof fetch\n\n/**\n * Centralized factory for the low-level dependencies the SDK injects into its\n * HTTP layer. Production code resolves these to the runtime's global `fetch`\n * and the burned-in production base URL; tests stub this module to swap in\n * mocks and alternate hosts.\n *\n * This is internal — it is not exported from the package's public entry. Tests\n * import it from `src/instrumentation.js` directly and use `vi.spyOn` to\n * substitute behavior.\n */\nexport const CwblInstrumentation = {\n /**\n * Resolve the `fetch` implementation the SDK should use. Throws a\n * {@link CrawlbruleeError} if the runtime does not expose a global `fetch`.\n */\n getFetch(): FetchLike {\n const g = globalThis as { fetch?: FetchLike }\n if (typeof g.fetch !== 'function') {\n throw new CrawlbruleeError(\n 'No global fetch is available in this runtime. crawlbrulee requires Node.js 22+, Bun, Deno, or a modern browser/edge runtime.',\n { status: 0, errorName: null }\n )\n }\n return g.fetch.bind(globalThis)\n },\n\n /**\n * Resolve the base URL the SDK should target. Returns the production host by\n * default; tests stub this to point at a mock origin.\n */\n getBaseUrl(): string {\n return DEFAULT_BASE_URL\n },\n}\n","import { DEFAULT_REQUEST_TIMEOUT_MS, USER_AGENT } from './config.js'\nimport { TransportError, createApiError, type CrawlbruleeError } from './errors.js'\nimport { CwblInstrumentation, type FetchLike } from './instrumentation.js'\nimport type { ApiErrorResponse } from './types/common.js'\n\n/** HTTP methods used by the SDK. */\nexport type HttpMethod = 'GET' | 'POST'\n\n/** Options the SDK accepts at construction time for the HTTP layer. */\nexport interface HttpClientOptions {\n /** API key sent as `Authorization: Bearer <key>`. */\n apiKey: string\n /**\n * Override the base URL. Trailing slashes are stripped. Falls back to\n * {@link CwblInstrumentation.getBaseUrl} (which resolves to the production\n * host) when unset.\n */\n baseUrl?: string\n /**\n * Per-request timeout in milliseconds. Pass `0` (or omit) to disable the\n * timeout entirely.\n */\n timeoutMs?: number\n}\n\n/** Per-call overrides accepted on every resource method. */\nexport interface RequestOptions {\n /** Abort the request when this signal fires. Composable with the timeout. */\n signal?: AbortSignal\n /**\n * Override the constructor-level `timeoutMs` for this call. Pass `0` to\n * disable the timeout for this call.\n */\n timeoutMs?: number\n}\n\ninterface SendArgs extends RequestOptions {\n method: HttpMethod\n path: string\n body?: unknown\n}\n\ninterface ComposedSignal {\n signal: AbortSignal | undefined\n /** Returns `true` if the abort was triggered by the per-request timeout. */\n timedOut: () => boolean\n /** Releases the timer and any listeners attached to the caller's signal. */\n cleanup: () => void\n}\n\n/**\n * Minimal `fetch`-based HTTP layer used by {@link Crawlbrulee}. Handles:\n *\n * - URL composition (joining `baseUrl` and path safely).\n * - JSON serialization and parsing.\n * - The `Authorization: Bearer …` header.\n * - Composing the caller's `AbortSignal` with an internal timeout signal. The\n * timeout covers the WHOLE request, including the response body read — not\n * just the time-to-headers.\n * - Mapping non-2xx responses to typed `CrawlbruleeError` subclasses via\n * {@link createApiError}.\n *\n * The base URL and `fetch` implementation are sourced from\n * {@link CwblInstrumentation} at construction time so tests can stub the\n * module.\n */\nexport class HttpClient {\n readonly baseUrl: string\n private readonly apiKey: string\n private readonly fetch: FetchLike\n private readonly timeoutMs: number\n\n constructor(options: HttpClientOptions) {\n this.baseUrl = stripTrailingSlash(options.baseUrl ?? CwblInstrumentation.getBaseUrl())\n this.apiKey = options.apiKey\n this.fetch = CwblInstrumentation.getFetch()\n this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS\n }\n\n /** Send a `GET` request and parse the response as `T`. */\n get<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.send<T>({ method: 'GET', path, ...options })\n }\n\n /** Send a `POST` request with a JSON body and parse the response as `T`. */\n post<T>(path: string, body: unknown, options?: RequestOptions): Promise<T> {\n return this.send<T>({ method: 'POST', path, body, ...options })\n }\n\n private async send<T>(args: SendArgs): Promise<T> {\n const url = this.buildUrl(args.path)\n const headers = this.buildHeaders(args)\n const body = args.body === undefined ? undefined : JSON.stringify(args.body)\n const composed = this.composeSignal(args.signal, args.timeoutMs)\n\n try {\n let res: Response\n try {\n res = await this.fetch(url, {\n method: args.method,\n headers,\n body,\n signal: composed.signal,\n })\n } catch (cause: unknown) {\n throw abortOrNetworkError(cause, composed.timedOut(), args.timeoutMs ?? this.timeoutMs)\n }\n\n let text: string\n try {\n text = await res.text()\n } catch (cause: unknown) {\n if (isAbortError(cause)) {\n throw abortOrNetworkError(cause, composed.timedOut(), args.timeoutMs ?? this.timeoutMs)\n }\n throw new TransportError(`Failed to read response body (status ${res.status}).`, {\n status: res.status,\n cause,\n })\n }\n\n const parsed = parseJsonOrThrow(text, res.status)\n if (!res.ok) throw toApiError(parsed, res.status, text)\n return parsed as T\n } finally {\n composed.cleanup()\n }\n }\n\n private buildUrl(path: string): string {\n if (!path.startsWith('/')) {\n throw new TypeError(`crawlbrulee SDK: path must start with '/' (received '${path}')`)\n }\n return `${this.baseUrl}${path}`\n }\n\n private buildHeaders(args: SendArgs): Record<string, string> {\n const headers: Record<string, string> = {\n accept: 'application/json',\n 'user-agent': USER_AGENT,\n authorization: `Bearer ${this.apiKey}`,\n }\n if (args.body !== undefined) headers['content-type'] = 'application/json'\n return headers\n }\n\n /**\n * Build a single `AbortSignal` that fires when either the caller-supplied\n * signal aborts OR the per-request timeout elapses. The returned `cleanup`\n * callback MUST be invoked on every exit path so we don't leak timers or\n * dead listeners on long-lived caller signals.\n */\n private composeSignal(\n callerSignal: AbortSignal | undefined,\n overrideTimeoutMs: number | undefined\n ): ComposedSignal {\n const timeoutMs = overrideTimeoutMs ?? this.timeoutMs\n const hasTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0\n\n if (!hasTimeout && !callerSignal) {\n return { signal: undefined, timedOut: () => false, cleanup: () => {} }\n }\n\n if (!hasTimeout) {\n return { signal: callerSignal, timedOut: () => false, cleanup: () => {} }\n }\n\n const controller = new AbortController()\n let didTimeout = false\n const timer = setTimeout(() => {\n didTimeout = true\n controller.abort(new Error('request_timeout'))\n }, timeoutMs)\n\n let onCallerAbort: (() => void) | undefined\n if (callerSignal) {\n if (callerSignal.aborted) {\n clearTimeout(timer)\n controller.abort(callerSignal.reason)\n } else {\n onCallerAbort = () => {\n clearTimeout(timer)\n controller.abort(callerSignal.reason)\n }\n callerSignal.addEventListener('abort', onCallerAbort, { once: true })\n }\n }\n\n const cleanup = () => {\n clearTimeout(timer)\n if (onCallerAbort && callerSignal) {\n callerSignal.removeEventListener('abort', onCallerAbort)\n }\n }\n\n return { signal: controller.signal, timedOut: () => didTimeout, cleanup }\n }\n}\n\nfunction stripTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, '')\n}\n\nfunction isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === 'AbortError'\n}\n\nfunction abortOrNetworkError(cause: unknown, timedOut: boolean, timeoutMs: number): TransportError {\n if (isAbortError(cause)) {\n if (timedOut) {\n return new TransportError(`Request timed out after ${timeoutMs}ms.`, {\n errorName: 'request_timeout',\n cause,\n })\n }\n return new TransportError('Request aborted by caller.', {\n errorName: 'client_closed_request',\n cause,\n })\n }\n return new TransportError(formatNetworkErrorMessage(cause), { cause })\n}\n\nfunction formatNetworkErrorMessage(cause: unknown): string {\n if (cause instanceof Error) {\n return `Network error: ${cause.message}`\n }\n return 'Network error: unknown failure while sending the request.'\n}\n\nfunction parseJsonOrThrow(text: string, status: number): unknown {\n if (text === '') return {}\n try {\n return JSON.parse(text)\n } catch (cause: unknown) {\n const preview = text.length > 200 ? `${text.slice(0, 200)}…` : text\n throw new TransportError(`Unexpected non-JSON response (status ${status}): ${preview}`, {\n status,\n cause,\n })\n }\n}\n\nfunction toApiError(parsed: unknown, status: number, rawText: string): CrawlbruleeError {\n if (isApiErrorResponse(parsed)) {\n return createApiError(parsed, status)\n }\n const preview = rawText.length > 200 ? `${rawText.slice(0, 200)}…` : rawText\n return new TransportError(`HTTP ${status}: ${preview || '(empty body)'}`, { status })\n}\n\nfunction isApiErrorResponse(value: unknown): value is ApiErrorResponse {\n if (value === null || typeof value !== 'object') return false\n const v = value as Record<string, unknown>\n return typeof v.name === 'string' && typeof v.message === 'string'\n}\n","import { ENV_API_KEY } from './config.js'\nimport { CrawlbruleeError } from './errors.js'\nimport { HttpClient, type RequestOptions } from './http.js'\nimport type {\n AsyncJobStatusResponse,\n AsyncScrapeRequest,\n AsyncScrapeResponse,\n MapRequest,\n MapResponse,\n ScrapeCompleteWebhook,\n ScrapeRequest,\n ScrapeResponse,\n UsageResponse,\n WhoamiResponse,\n} from './types/index.js'\n\n/** Options accepted by the {@link Crawlbrulee} constructor. */\nexport interface CrawlbruleeOptions {\n /**\n * API key sent as `Authorization: Bearer <key>`. Required — to read from the\n * environment instead, use {@link Crawlbrulee.fromEnv}. Leading and trailing\n * whitespace is stripped; an empty / whitespace-only value is rejected.\n */\n apiKey: string\n /**\n * Override the base URL the SDK targets. Defaults to the production host\n * ({@link DEFAULT_BASE_URL}). Intended for local development and staging\n * (e.g. `https://api.<staging-domain>`) — production callers should\n * leave it unset. Trailing slashes are stripped.\n */\n baseUrl?: string\n /**\n * Per-request timeout in milliseconds. Defaults to `0` (no timeout). Set to a\n * positive number to abort slow requests; a per-call `timeoutMs` override\n * takes precedence. The timeout covers the WHOLE request, including the\n * response body read.\n */\n timeoutMs?: number\n}\n\n/**\n * Options accepted by {@link Crawlbrulee.waitForScrape}.\n *\n * Note: `timeoutMs` here is the OVERALL wait budget across all polls — not the\n * per-HTTP-request timeout. The per-poll HTTP timeout is whatever the client\n * was constructed with; if you want to bound each individual poll, construct\n * the client with `timeoutMs` set.\n */\nexport interface WaitForScrapeOptions extends Omit<RequestOptions, 'timeoutMs'> {\n /** Time between status polls in milliseconds. Default `2000`. */\n intervalMs?: number\n /**\n * Maximum total time to wait before giving up, in milliseconds. Default\n * `300_000` (5 minutes). Pass `0` to wait indefinitely.\n */\n timeoutMs?: number\n}\n\n/**\n * Official client for the crawlbrulee API.\n *\n * @example\n * ```ts\n * import { Crawlbrulee } from '@crawlbrulee/sdk'\n *\n * const crawlbrulee = new Crawlbrulee({ apiKey: 'cwbl_…' })\n * // or read CRAWLBRULEE_API_KEY from the environment:\n * const crawlbrulee = Crawlbrulee.fromEnv()\n *\n * const page = await crawlbrulee.scrape({\n * url: 'https://example.com',\n * extract: { markdown: true, links: true },\n * })\n * console.log(page.markdown)\n * ```\n */\nexport class Crawlbrulee {\n /** Resolved base URL — trailing slash already stripped. */\n readonly baseUrl: string\n /** Underlying HTTP layer. Exposed for advanced use cases (custom endpoints). */\n readonly http: HttpClient\n\n constructor(options: CrawlbruleeOptions) {\n const apiKey = options.apiKey?.trim()\n if (!apiKey) {\n throw new CrawlbruleeError(\n `Missing API key. Pass { apiKey } to Crawlbrulee or call Crawlbrulee.fromEnv() to read ${ENV_API_KEY}.`,\n { status: 0, errorName: null }\n )\n }\n this.http = new HttpClient({ apiKey, baseUrl: options.baseUrl, timeoutMs: options.timeoutMs })\n this.baseUrl = this.http.baseUrl\n }\n\n /**\n * Build a {@link Crawlbrulee} reading the API key from\n * `process.env.CRAWLBRULEE_API_KEY`. Throws if the variable is unset, empty,\n * or whitespace.\n *\n * Any other constructor option can be passed via `overrides`.\n *\n * @example\n * ```ts\n * const crawlbrulee = Crawlbrulee.fromEnv()\n * const crawlbrulee = Crawlbrulee.fromEnv({ timeoutMs: 30_000 })\n * ```\n */\n static fromEnv(overrides: Omit<CrawlbruleeOptions, 'apiKey'> = {}): Crawlbrulee {\n const apiKey = readEnv(ENV_API_KEY)\n if (!apiKey) {\n throw new CrawlbruleeError(\n `${ENV_API_KEY} is not set. Export it in your shell, or pass apiKey to new Crawlbrulee({ apiKey }).`,\n { status: 0, errorName: null }\n )\n }\n return new Crawlbrulee({ ...overrides, apiKey })\n }\n\n // ------------------------------------------------------------------\n // Scraping\n // ------------------------------------------------------------------\n\n /**\n * Scrape a URL synchronously and return the extracted content.\n *\n * The request blocks until the scrape is finished. For long-running jobs\n * (heavy JS rendering, screenshots of long pages) prefer\n * {@link Crawlbrulee.scrapeAsync} so the connection isn't held open.\n *\n * Any page the site really served is returned, whatever its status: a 404,\n * 410, 401 or 503 page resolves normally, with the site's status in\n * `page_status_code` — it does not throw. Check that field when the page's\n * status matters to you. The call throws when we could not return the page,\n * for example `TargetUnreachableError` when the site could not be reached,\n * `AntibotBlockedError`, or `PageTooLargeError`.\n *\n * @param request — body for `POST /api/scrape`.\n * @param options — per-call timeout and abort signal.\n */\n scrape(request: ScrapeRequest, options?: RequestOptions): Promise<ScrapeResponse> {\n return this.http.post<ScrapeResponse>('/api/scrape', request, options)\n }\n\n /**\n * Submit an asynchronous scrape job and return its `job_id`. Poll the job\n * with {@link Crawlbrulee.getScrapeStatus} or wait for completion with\n * {@link Crawlbrulee.waitForScrape}.\n *\n * Pass an optional `webhook` to have the API deliver a signed\n * `scrape.complete` `POST` to your endpoint when the job finishes (see\n * {@link AsyncScrapeWebhook}). This field is async-only.\n */\n scrapeAsync(request: AsyncScrapeRequest, options?: RequestOptions): Promise<AsyncScrapeResponse> {\n return this.http.post<AsyncScrapeResponse>('/api/scrape/async', request, options)\n }\n\n /** Look up the current status of an async scrape job. */\n getScrapeStatus(jobId: string, options?: RequestOptions): Promise<AsyncJobStatusResponse> {\n assertNonEmptyJobId(jobId)\n return this.http.get<AsyncJobStatusResponse>(\n `/api/scrape/status/${encodeURIComponent(jobId)}`,\n options\n )\n }\n\n /**\n * Fetch the result of a completed async scrape job. Throws if the job is\n * still pending/running — call {@link Crawlbrulee.getScrapeStatus}\n * first, or use {@link Crawlbrulee.waitForScrape} to poll-then-fetch.\n *\n * Like {@link Crawlbrulee.scrape}, a 404 (or any other) page the site served\n * is a completed job: the result carries the site's status in\n * `page_status_code`.\n */\n getScrapeResult(jobId: string, options?: RequestOptions): Promise<ScrapeResponse> {\n assertNonEmptyJobId(jobId)\n return this.http.get<ScrapeResponse>(`/api/scrape/result/${encodeURIComponent(jobId)}`, options)\n }\n\n /**\n * Fetch the scrape result referenced by a `scrape.complete` webhook body.\n *\n * Always verify the webhook signature with `verifyWebhookSignature` before\n * acting on it; this method trusts the parsed body it is handed.\n *\n * Behavior by `data.status`:\n * - `success` — delegates to {@link Crawlbrulee.getScrapeResult} for the\n * webhook's `job_id` and returns the parsed result.\n * - `failed` — throws a {@link CrawlbruleeError} carrying `data.error`\n * (`errorName: 'job_failed'`); there is no result to fetch.\n * - `cancelled` — throws a {@link CrawlbruleeError}\n * (`errorName: 'client_closed_request'`).\n *\n * A non-`scrape.complete` envelope throws a {@link CrawlbruleeError}\n * defensively. Any HTTP error from the underlying fetch propagates as the\n * usual typed `CrawlbruleeError` subclass.\n */\n async fetchScrapeResultFromWebhook(\n webhook: ScrapeCompleteWebhook,\n options?: RequestOptions\n ): Promise<ScrapeResponse> {\n if (webhook?.event !== 'scrape.complete') {\n throw new CrawlbruleeError(\n `Expected a 'scrape.complete' webhook but received '${String(webhook?.event)}'.`,\n { status: 0, errorName: 'validation_error' }\n )\n }\n\n const { job_id: jobId, status, error } = webhook.data\n\n switch (status) {\n case 'success':\n return this.getScrapeResult(jobId, options)\n\n case 'failed':\n throw new CrawlbruleeError(error ?? `Async scrape job ${jobId} failed.`, {\n status: 0,\n errorName: 'job_failed',\n })\n\n case 'cancelled':\n throw new CrawlbruleeError(`Async scrape job ${jobId} was cancelled.`, {\n status: 0,\n errorName: 'client_closed_request',\n })\n\n default:\n throw new CrawlbruleeError(\n `Async scrape webhook for job ${jobId} carried an unexpected status '${String(status)}'.`,\n { status: 0, errorName: 'validation_error' }\n )\n }\n }\n\n /**\n * Poll an async scrape job until it reaches a terminal state, then return\n * the scrape result.\n *\n * Throws a {@link CrawlbruleeError} when:\n * - the job ends in `failed` (`errorName: 'job_failed'`),\n * - the server reports an unexpected status (`errorName: 'job_failed'`),\n * - the overall wait exceeds `timeoutMs` (`errorName: 'request_timeout'`),\n * - the caller's `signal` aborts (`errorName: 'client_closed_request'`).\n */\n async waitForScrape(jobId: string, options: WaitForScrapeOptions = {}): Promise<ScrapeResponse> {\n assertNonEmptyJobId(jobId)\n const intervalMs = options.intervalMs ?? 2000\n const timeoutMs = options.timeoutMs ?? 300_000\n const deadline = timeoutMs > 0 ? Date.now() + timeoutMs : Number.POSITIVE_INFINITY\n\n while (true) {\n throwIfAborted(options.signal)\n if (Date.now() >= deadline) {\n throw new CrawlbruleeError(\n `Timed out after ${timeoutMs}ms waiting for async scrape job ${jobId}.`,\n { status: 0, errorName: 'request_timeout' }\n )\n }\n\n const status = await this.getScrapeStatus(jobId, { signal: options.signal })\n\n switch (status.status) {\n case 'done':\n return this.getScrapeResult(jobId, { signal: options.signal })\n\n case 'failed':\n throw new CrawlbruleeError(status.error ?? `Async scrape job ${jobId} failed.`, {\n status: 0,\n errorName: 'job_failed',\n })\n\n case 'pending':\n case 'running':\n break\n\n default:\n throw new CrawlbruleeError(\n `Async scrape job ${jobId} returned unexpected status '${String(status.status)}'.`,\n { status: 0, errorName: 'job_failed' }\n )\n }\n\n await sleep(intervalMs, options.signal)\n }\n }\n\n // ------------------------------------------------------------------\n // Mapping\n // ------------------------------------------------------------------\n\n /**\n * Build (or return a cached) site link-map for a domain. Combines sitemap\n * discovery with the freshest cached homepage scrape when available.\n */\n map(request: MapRequest, options?: RequestOptions): Promise<MapResponse> {\n return this.http.post<MapResponse>('/api/map', request, options)\n }\n\n // ------------------------------------------------------------------\n // Account\n // ------------------------------------------------------------------\n\n /**\n * Return the current billing-cycle usage: total/used/available credits,\n * used quota percentage, max concurrency, and when the cycle resets.\n */\n usage(options?: RequestOptions): Promise<UsageResponse> {\n return this.http.get<UsageResponse>('/api/usage', options)\n }\n\n /**\n * Return the organization name and identifying details of the API token\n * used to authenticate this request. Useful for confirming which key is in\n * use before performing destructive operations.\n */\n whoami(options?: RequestOptions): Promise<WhoamiResponse> {\n return this.http.get<WhoamiResponse>('/api/whoami', options)\n }\n}\n\n/**\n * Defensive read of `process.env[name]`. Guards both the absence of `process`\n * (browser / edge runtimes) and Deno's permission throw on env access without\n * `--allow-env`.\n */\nfunction readEnv(name: string): string | undefined {\n try {\n if (typeof process === 'undefined' || !process.env) return undefined\n const v = process.env[name]\n return typeof v === 'string' && v.trim().length > 0 ? v.trim() : undefined\n } catch {\n return undefined\n }\n}\n\nfunction assertNonEmptyJobId(jobId: string): void {\n if (typeof jobId !== 'string' || jobId.trim().length === 0) {\n throw new CrawlbruleeError('jobId must be a non-empty string.', {\n status: 0,\n errorName: null,\n })\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw new CrawlbruleeError('Request aborted by caller.', {\n status: 0,\n errorName: 'client_closed_request',\n cause: signal.reason,\n })\n }\n}\n\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer)\n reject(\n new CrawlbruleeError('Request aborted by caller.', {\n status: 0,\n errorName: 'client_closed_request',\n cause: signal?.reason,\n })\n )\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n if (signal) {\n if (signal.aborted) {\n clearTimeout(timer)\n onAbort()\n return\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n}\n","/**\n * Verification for async scrape completion webhooks.\n *\n * {@link verifyWebhookSignature} validates the signature crawlbrulee attaches to\n * every webhook delivery. It is a standalone, network-free helper built on Web\n * Crypto (`globalThis.crypto.subtle`) so it runs unchanged on Node.js 22+,\n * browsers, Bun, Deno, and edge runtimes — it never touches `node:crypto`.\n */\n\n/** HTTP header carrying the primary webhook signature (always present). */\nexport const WEBHOOK_SIGNATURE_HEADER = 'X-Cwbl-Signature'\n\n/**\n * HTTP header carrying a signature produced with the previous signing secret.\n * Present only during a signing-secret rotation grace window.\n */\nexport const WEBHOOK_SIGNATURE_ROTATED_HEADER = 'X-Cwbl-Signature-Rotated'\n\n/** HTTP header carrying the unique event id, useful for delivery de-duplication. */\nexport const WEBHOOK_EVENT_ID_HEADER = 'X-Cwbl-Event-Id'\n\n/** Default replay-protection window (seconds) applied to the signed timestamp. */\nexport const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300\n\n/** Which signature header satisfied verification. */\nexport type WebhookSignatureSource = 'primary' | 'rotated'\n\n/**\n * Why a webhook signature failed to verify.\n *\n * - `missing_signature` — neither the primary nor the rotated header was present.\n * - `malformed_signature` — a header was present but not in the expected\n * `t=<unix_seconds>,v1=<64_hex>` format.\n * - `timestamp_out_of_tolerance` — the signed timestamp drifted further from now\n * than `toleranceSeconds` allows (replay protection).\n * - `signature_mismatch` — a well-formed, in-tolerance signature did not match\n * the one computed from the payload and secret.\n */\nexport type WebhookVerificationFailureReason =\n | 'missing_signature'\n | 'malformed_signature'\n | 'timestamp_out_of_tolerance'\n | 'signature_mismatch'\n\n/** Result of {@link verifyWebhookSignature}. Verification failure is returned, not thrown. */\nexport type WebhookVerificationResult =\n | { verified: true; signedWith: WebhookSignatureSource }\n | { verified: false; reason: WebhookVerificationFailureReason }\n\n/** Options for {@link verifyWebhookSignature}. */\nexport interface VerifyWebhookSignatureOptions {\n /**\n * The raw request body, exactly as received. Pass the bytes/string the server\n * signed — do NOT re-serialize parsed JSON, or the signature will not match.\n */\n payload: string | Uint8Array\n /**\n * The request headers. Accepts a fetch `Headers` instance or a plain object\n * (Express/Node give lowercased keys, values possibly arrays). Lookup is\n * case-insensitive.\n */\n headers: Headers | Record<string, string | string[] | undefined>\n /** The current signing secret (`whsec_…`). */\n secret: string\n /**\n * Replay-protection window in seconds. Defaults to\n * {@link DEFAULT_WEBHOOK_TOLERANCE_SECONDS} (300). Pass `0` (or any falsy\n * value) to disable the timestamp check entirely.\n */\n toleranceSeconds?: number\n}\n\nconst SIGNATURE_FORMAT = /^t=(\\d+),v1=([0-9a-f]{64})$/\n\ninterface ParsedSignature {\n timestamp: number\n signature: string\n}\n\n/**\n * Verify a crawlbrulee webhook signature against the primary and rotated\n * headers.\n *\n * The signing scheme matches the backend:\n * - the signed payload is `` `${t}.${rawBody}` `` where `t` is the unix-seconds\n * integer from the header and `rawBody` is the raw request body,\n * - the signature is `HMAC-SHA256(secret, signedPayload)` as lowercase hex,\n * - the header value is `t=<unix_seconds>,v1=<64_hex>`.\n *\n * The supplied `secret` is tried against the primary header first, then the\n * rotated header (which the API emits during a signing-secret rotation grace\n * window). Whichever matches wins, and the result reports which header it was.\n *\n * This NEVER throws on a verification failure — failures are normal control\n * flow and are returned as `{ verified: false, reason }`.\n *\n * @example\n * ```ts\n * const result = await verifyWebhookSignature({\n * payload: rawBody,\n * headers: req.headers,\n * secret: process.env.CRAWLBRULEE_WEBHOOK_SECRET!,\n * })\n * if (!result.verified) return res.status(400).end()\n * ```\n */\nexport async function verifyWebhookSignature(\n options: VerifyWebhookSignatureOptions\n): Promise<WebhookVerificationResult> {\n const { payload, headers, secret } = options\n const toleranceSeconds = options.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS\n\n const primaryHeader = getHeader(headers, WEBHOOK_SIGNATURE_HEADER)\n const rotatedHeader = getHeader(headers, WEBHOOK_SIGNATURE_ROTATED_HEADER)\n\n if (primaryHeader === undefined && rotatedHeader === undefined) {\n return { verified: false, reason: 'missing_signature' }\n }\n\n const nowSeconds = Math.floor(Date.now() / 1000)\n const body = toBytes(payload)\n const key = await importHmacKey(secret)\n\n // Track the \"best\" failure reason so the result is informative: a real\n // mismatch should win over a malformed sibling header. Order from least to\n // most specific.\n let failure: WebhookVerificationFailureReason = 'malformed_signature'\n\n for (const source of ['primary', 'rotated'] as const) {\n const raw = source === 'primary' ? primaryHeader : rotatedHeader\n if (raw === undefined) continue\n\n const parsed = parseSignatureHeader(raw)\n if (!parsed) {\n // A malformed header can't verify; keep looking at the other one.\n continue\n }\n\n if (toleranceSeconds && Math.abs(nowSeconds - parsed.timestamp) > toleranceSeconds) {\n failure = mostSpecificFailure(failure, 'timestamp_out_of_tolerance')\n continue\n }\n\n const expected = await computeSignatureHex(key, parsed.timestamp, body)\n if (constantTimeEqualHex(expected, parsed.signature)) {\n return { verified: true, signedWith: source }\n }\n\n failure = mostSpecificFailure(failure, 'signature_mismatch')\n }\n\n return { verified: false, reason: failure }\n}\n\n/**\n * Rank verification failures so the returned reason reflects the most\n * actionable problem encountered across the two headers.\n */\nfunction mostSpecificFailure(\n current: WebhookVerificationFailureReason,\n candidate: WebhookVerificationFailureReason\n): WebhookVerificationFailureReason {\n const rank: Record<WebhookVerificationFailureReason, number> = {\n missing_signature: 0,\n malformed_signature: 1,\n timestamp_out_of_tolerance: 2,\n signature_mismatch: 3,\n }\n return rank[candidate] > rank[current] ? candidate : current\n}\n\n/** Case-insensitive header lookup over `Headers` or a plain object. */\nfunction getHeader(\n headers: Headers | Record<string, string | string[] | undefined>,\n name: string\n): string | undefined {\n if (typeof Headers !== 'undefined' && headers instanceof Headers) {\n return headers.get(name) ?? undefined\n }\n const target = name.toLowerCase()\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() !== target) continue\n const value = (headers as Record<string, string | string[] | undefined>)[key]\n if (Array.isArray(value)) return value[0]\n return value ?? undefined\n }\n return undefined\n}\n\nfunction parseSignatureHeader(value: string): ParsedSignature | null {\n const match = SIGNATURE_FORMAT.exec(value.trim())\n if (!match) return null\n const timestamp = Number(match[1])\n if (!Number.isSafeInteger(timestamp)) return null\n return { timestamp, signature: match[2]! }\n}\n\nfunction toBytes(payload: string | Uint8Array): Uint8Array {\n return typeof payload === 'string' ? new TextEncoder().encode(payload) : payload\n}\n\n/**\n * Web Crypto types, derived from the runtime global so we don't have to pull in\n * the DOM `lib` (the SDK compiles against `lib: ES2022` + `@types/node`).\n */\ntype SubtleCryptoLike = typeof globalThis.crypto.subtle\ntype CryptoKeyLike = Awaited<ReturnType<SubtleCryptoLike['importKey']>>\n\nfunction importHmacKey(secret: string): Promise<CryptoKeyLike> {\n return getSubtle().importKey(\n 'raw',\n new TextEncoder().encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign']\n )\n}\n\nasync function computeSignatureHex(\n key: CryptoKeyLike,\n timestamp: number,\n body: Uint8Array\n): Promise<string> {\n const prefix = new TextEncoder().encode(`${timestamp}.`)\n const message = new Uint8Array(prefix.length + body.length)\n message.set(prefix, 0)\n message.set(body, prefix.length)\n const digest = await getSubtle().sign('HMAC', key, message)\n return toHex(new Uint8Array(digest))\n}\n\nfunction toHex(bytes: Uint8Array): string {\n let hex = ''\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, '0')\n }\n return hex\n}\n\n/**\n * Length-checked, constant-time comparison of two lowercase hex strings. Folds\n * every byte into an accumulator with XOR — never early-returns on the first\n * mismatch — so timing does not leak how much of the signature matched.\n */\nfunction constantTimeEqualHex(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n }\n return diff === 0\n}\n\nfunction getSubtle(): SubtleCryptoLike {\n const subtle = globalThis.crypto?.subtle\n if (!subtle) {\n throw new Error(\n 'Web Crypto (globalThis.crypto.subtle) is not available in this runtime. crawlbrulee webhook verification requires Node.js 22+, Bun, Deno, or a modern browser/edge runtime.'\n )\n }\n return subtle\n}\n"],"mappings":";;;;;;AAKA,MAAa,mBAAmB;;AAGhC,MAAa,6BAA6B;;AAG1C,MAAa,cAAc;;AAG3B,MAAa,aAAa;;;;;;;;;;;;;;;;;;;;;ACW1B,IAAa,mBAAb,cAAsC,MAAM;;CAE1C,AAAS;;CAET,AAAS;;CAET,AAAS;;CAET,AAAS;CAET,YACE,SACA,SAOA;EACA,MAAM,SAAS,QAAQ,UAAU,SAAY,EAAE,OAAO,QAAQ,MAAM,IAAI,MAAS;EACjF,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,YAAY,QAAQ;EACzB,KAAK,UAAU,QAAQ;EACvB,KAAK,WAAW,QAAQ;CAC1B;AACF;;;;;;;;;;;AAYA,IAAa,sBAAb,cAAyC,iBAAiB;CACxD,YACE,SACA,SACA;EACA,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;;;;;;AAOA,IAAa,sBAAb,cAAyC,iBAAiB;CACxD,YACE,SACA,SACA;EACA,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;;;;;;;;AASA,IAAa,wBAAb,cAA2C,iBAAiB;CAC1D,YACE,SACA,SACA;EACA,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;;;;;;;;AASA,IAAa,oBAAb,cAAuC,iBAAiB;CACtD,YACE,SACA,SACA;EACA,MAA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,IAAI,GAAG,IAAI,EAAE,QAAQ,KAC5B,QAAQ,EAAE,WAAW,CAAC,IAAI,EAAE,WAAW,CAAC;CAE1C,OAAO,SAAS;AAClB;AAEA,SAAS,YAA8B;CACrC,MAAM,SAAS,WAAW,QAAQ;CAClC,IAAI,CAAC,QACH,MAAM,IAAI,MACR,6KACF;CAEF,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crawlbrulee/sdk",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
4
4
  "description": "official js/ts sdk for crawlbrulee — EU-native web scraping for AI agents & developers. any url to clean markdown, screenshots, metadata and links.",
5
5
  "keywords": [
6
6
  "crawlbrulee",