scrapebadger 0.78.0 → 0.80.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/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
- import { createHmac, timingSafeEqual } from 'crypto';
2
1
  import { EventEmitter } from 'events';
3
2
  import WebSocket from 'ws';
3
+ import { createHmac, timingSafeEqual } from 'crypto';
4
4
 
5
5
  // src/internal/version.ts
6
- var SDK_VERSION = "0.77.0";
6
+ var SDK_VERSION = "0.80.0";
7
7
 
8
8
  // src/internal/exceptions.ts
9
9
  var ScrapeBadgerError = class _ScrapeBadgerError extends Error {
@@ -161,6 +161,21 @@ var WebSocketStreamError = class _WebSocketStreamError extends ScrapeBadgerError
161
161
 
162
162
  // src/internal/client.ts
163
163
  var RETRYABLE_STATUS_CODES = [500, 502, 503, 504];
164
+ var NOT_SENT_CODES = /* @__PURE__ */ new Set([
165
+ "ECONNREFUSED",
166
+ "ENOTFOUND",
167
+ "EAI_AGAIN",
168
+ "EHOSTUNREACH",
169
+ "ENETUNREACH",
170
+ "UND_ERR_CONNECT_TIMEOUT"
171
+ ]);
172
+ function failedBeforeSend(error) {
173
+ const cause = error?.cause;
174
+ if (!cause) return false;
175
+ if (typeof cause.code === "string") return NOT_SENT_CODES.has(cause.code);
176
+ return Array.isArray(cause.errors) && cause.errors.length > 0 && cause.errors.every((e) => NOT_SENT_CODES.has(String(e?.code)));
177
+ }
178
+ var finalErrors = /* @__PURE__ */ new WeakSet();
164
179
  var BaseClient = class _BaseClient {
165
180
  config;
166
181
  constructor(config) {
@@ -212,11 +227,41 @@ var BaseClient = class _BaseClient {
212
227
  async requestWithHeaders(path, options = {}) {
213
228
  return this.requestRaw(path, options);
214
229
  }
230
+ /**
231
+ * Make an HTTP request and return its status, headers and body undigested:
232
+ * the body is JSON-decoded when the response is JSON, otherwise text (the
233
+ * normal path turns a non-JSON, non-HTML body into `{ detail }`). Error
234
+ * statuses still throw the matching typed error.
235
+ */
236
+ async requestResponse(path, options = {}) {
237
+ const { data } = await this.requestRaw(path, options, async (response) => {
238
+ if (!response.ok) {
239
+ try {
240
+ await this.handleResponse(response);
241
+ } catch (error) {
242
+ if (response.headers.get("Idempotent-Replayed")?.trim().toLowerCase() === "true") {
243
+ finalErrors.add(error);
244
+ }
245
+ throw error;
246
+ }
247
+ }
248
+ const text = await response.text();
249
+ let body = text;
250
+ if (response.headers.get("content-type")?.toLowerCase().includes("json")) {
251
+ try {
252
+ body = JSON.parse(text);
253
+ } catch {
254
+ }
255
+ }
256
+ return { status: response.status, headers: response.headers, body };
257
+ });
258
+ return data;
259
+ }
215
260
  /**
216
261
  * Internal method that builds the request and executes it, returning data and rate limit info.
217
262
  */
218
- async requestRaw(path, options = {}) {
219
- const { method = "GET", params, body, headers = {} } = options;
263
+ async requestRaw(path, options = {}, decode) {
264
+ const { method = "GET", params, body, headers = {}, timeoutMs, maxRetries, retry } = options;
220
265
  const url = new URL(path, this.config.baseUrl);
221
266
  if (params) {
222
267
  for (const [key, value] of Object.entries(params)) {
@@ -239,17 +284,24 @@ var BaseClient = class _BaseClient {
239
284
  if (body && method !== "GET") {
240
285
  fetchOptions.body = JSON.stringify(body);
241
286
  }
242
- return this.executeWithRetry(url.toString(), fetchOptions);
287
+ return this.executeWithRetry(url.toString(), fetchOptions, {
288
+ decode,
289
+ timeoutMs,
290
+ maxRetries,
291
+ retry
292
+ });
243
293
  }
244
294
  /**
245
295
  * Execute request with exponential backoff retry logic.
246
296
  */
247
- async executeWithRetry(url, options) {
297
+ async executeWithRetry(url, options, policy = {}) {
248
298
  let lastError;
249
- for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {
299
+ const maxRetries = policy.maxRetries ?? this.config.maxRetries;
300
+ const decode = policy.decode ?? ((response) => this.handleResponse(response));
301
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
250
302
  let retryAfterMs = 0;
251
303
  try {
252
- const httpResponse = await this.fetchWithTimeout(url, options);
304
+ const httpResponse = await this.fetchWithTimeout(url, options, policy.timeoutMs);
253
305
  const retryAfter = httpResponse.headers.get("Retry-After")?.trim();
254
306
  if (retryAfter) {
255
307
  let requestedDelay = 0;
@@ -268,21 +320,20 @@ var BaseClient = class _BaseClient {
268
320
  retryAfterMs = requestedDelay;
269
321
  }
270
322
  }
271
- const data = await this.handleResponse(httpResponse);
323
+ const data = await decode(httpResponse);
272
324
  const rateLimit = this.parseRateLimitHeaders(httpResponse.headers);
273
325
  return { data, rateLimit, status: httpResponse.status, headers: httpResponse.headers };
274
326
  } catch (error) {
275
327
  lastError = error;
276
- if (!_BaseClient.isRetryable(error)) {
328
+ if (!_BaseClient.isRetryable(error, policy.retry ?? "all")) {
277
329
  throw error;
278
330
  }
279
- if (attempt === this.config.maxRetries) {
331
+ if (attempt === maxRetries) {
280
332
  break;
281
333
  }
282
334
  const delay = Math.max(this.config.retryDelay * Math.pow(2, attempt), retryAfterMs);
283
335
  const delaySec = Math.round(delay / 1e3);
284
336
  const attemptNum = attempt + 1;
285
- const maxRetries = this.config.maxRetries;
286
337
  if (error instanceof RateLimitError) {
287
338
  console.warn(
288
339
  `\x1B[33m\u26A0 ScrapeBadger: 429 Rate Limited \u2014 retrying in ${delaySec}s (attempt ${attemptNum}/${maxRetries})\x1B[0m`
@@ -333,9 +384,9 @@ var BaseClient = class _BaseClient {
333
384
  /**
334
385
  * Fetch with timeout support.
335
386
  */
336
- async fetchWithTimeout(url, options) {
387
+ async fetchWithTimeout(url, options, timeoutMs = this.config.timeout) {
337
388
  const controller = new AbortController();
338
- const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
389
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
339
390
  try {
340
391
  const response = await fetch(url, {
341
392
  ...options,
@@ -344,10 +395,7 @@ var BaseClient = class _BaseClient {
344
395
  return response;
345
396
  } catch (error) {
346
397
  if (error instanceof Error && error.name === "AbortError") {
347
- throw new TimeoutError(
348
- `Request timed out after ${this.config.timeout}ms`,
349
- this.config.timeout
350
- );
398
+ throw new TimeoutError(`Request timed out after ${timeoutMs}ms`, timeoutMs);
351
399
  }
352
400
  throw error;
353
401
  } finally {
@@ -383,7 +431,7 @@ var BaseClient = class _BaseClient {
383
431
  if (errorData.error === "ip_not_allowed") {
384
432
  throw new IPNotAllowedError(message, errorData.client_ip ?? null);
385
433
  }
386
- if (errorData.error === "insufficient_scope") {
434
+ if (errorData.error === "insufficient_scope" || errorData.error === "full_access_required") {
387
435
  throw new PermissionDeniedError(
388
436
  message,
389
437
  errorData.required_scope,
@@ -426,16 +474,24 @@ var BaseClient = class _BaseClient {
426
474
  *
427
475
  * Retryable: transient server failures (500/502/503/504), request timeouts,
428
476
  * rate limits, and raw network faults thrown by `fetch` itself. Everything
429
- * else — auth, validation, not-found, conflict — is final.
477
+ * else — auth, validation, not-found, conflict — is final, and so is a
478
+ * replayed result. `mode` narrows this further (see `RequestOptions.retry`).
430
479
  */
431
- static isRetryable(error) {
480
+ static isRetryable(error, mode) {
481
+ if (typeof error === "object" && error !== null && finalErrors.has(error)) {
482
+ return false;
483
+ }
484
+ const networkFault = !(error instanceof ScrapeBadgerError);
485
+ if (mode === "connect") {
486
+ return networkFault && failedBeforeSend(error);
487
+ }
432
488
  if (error instanceof ServerError) {
433
- return RETRYABLE_STATUS_CODES.includes(error.statusCode);
489
+ return mode === "all" && RETRYABLE_STATUS_CODES.includes(error.statusCode);
434
490
  }
435
- if (error instanceof RateLimitError || error instanceof TimeoutError) {
436
- return true;
491
+ if (error instanceof RateLimitError) {
492
+ return mode === "all";
437
493
  }
438
- return !(error instanceof ScrapeBadgerError);
494
+ return error instanceof TimeoutError || networkFault;
439
495
  }
440
496
  /**
441
497
  * Sleep for a given duration.
@@ -1817,6 +1873,48 @@ var GeoClient = class {
1817
1873
  return createPaginatedResponse(response.data ?? []);
1818
1874
  }
1819
1875
  };
1876
+ var DEFAULT_TOLERANCE_S = 300;
1877
+ var SIGNATURE_RE = /^sha256=([0-9a-fA-F]{64})$/;
1878
+ function rawBytes(rawBody, fn) {
1879
+ if (typeof rawBody === "string") return Buffer.from(rawBody, "utf-8");
1880
+ if (rawBody instanceof Uint8Array) {
1881
+ return Buffer.from(rawBody.buffer, rawBody.byteOffset, rawBody.byteLength);
1882
+ }
1883
+ if (rawBody instanceof ArrayBuffer) return Buffer.from(rawBody);
1884
+ throw new TypeError(
1885
+ `${fn} needs the raw request body (a string or Buffer) exactly as received, not a parsed object: read it with express.raw({ type: "application/json" }) or equivalent.`
1886
+ );
1887
+ }
1888
+ function verifyWebhookSignature(secret, rawBody, signature, options = {}) {
1889
+ const body = rawBytes(rawBody, "verifyWebhookSignature");
1890
+ if (!secret || typeof signature !== "string") return false;
1891
+ const match = SIGNATURE_RE.exec(signature.trim());
1892
+ if (!match?.[1]) return false;
1893
+ const expected = createHmac("sha256", secret).update(body).digest();
1894
+ if (!timingSafeEqual(expected, Buffer.from(match[1], "hex"))) return false;
1895
+ const { sentAt, toleranceS = DEFAULT_TOLERANCE_S } = options;
1896
+ if (sentAt === void 0 || sentAt === null) return true;
1897
+ const sentAtS = typeof sentAt === "number" ? sentAt : Number(sentAt.trim() || Number.NaN);
1898
+ return Math.abs(Date.now() / 1e3 - sentAtS) <= toleranceS;
1899
+ }
1900
+ function parseWebhookEvent(rawBody) {
1901
+ const text = typeof rawBody === "string" ? rawBody : rawBytes(rawBody, "parseWebhookEvent").toString("utf-8");
1902
+ let parsed;
1903
+ try {
1904
+ parsed = JSON.parse(text);
1905
+ } catch (error) {
1906
+ throw new SyntaxError(`Webhook body is not JSON: ${error.message}`);
1907
+ }
1908
+ const event = parsed;
1909
+ if (typeof event !== "object" || event === null || Array.isArray(event) || typeof event.event !== "string" || typeof event.request_id !== "string") {
1910
+ throw new TypeError(
1911
+ "Not a ScrapeBadger webhook event: expected a JSON object with string `event` and `request_id`."
1912
+ );
1913
+ }
1914
+ return event;
1915
+ }
1916
+
1917
+ // src/twitter/stream.ts
1820
1918
  var MIN_RECONNECT_DELAY_SECONDS = 5;
1821
1919
  function wsUrlFromBase(baseUrl) {
1822
1920
  if (baseUrl.startsWith("https://")) {
@@ -2495,19 +2593,6 @@ var StreamClient = class {
2495
2593
  }
2496
2594
  }
2497
2595
  };
2498
- function verifyWebhookSignature(secret, body, signatureHeader) {
2499
- if (!signatureHeader.startsWith("sha256=")) {
2500
- return false;
2501
- }
2502
- const expectedHex = signatureHeader.slice("sha256=".length);
2503
- const bodyBuffer = typeof body === "string" ? Buffer.from(body, "utf-8") : body;
2504
- const actualHex = createHmac("sha256", secret).update(bodyBuffer).digest("hex");
2505
- try {
2506
- return timingSafeEqual(Buffer.from(expectedHex, "hex"), Buffer.from(actualHex, "hex"));
2507
- } catch {
2508
- return false;
2509
- }
2510
- }
2511
2596
 
2512
2597
  // src/twitter/spaces.ts
2513
2598
  var SpacesClient = class {
@@ -3839,6 +3924,38 @@ var GooglePlayClient = class {
3839
3924
  }
3840
3925
  };
3841
3926
 
3927
+ // src/grok/client.ts
3928
+ var GrokClient = class {
3929
+ client;
3930
+ constructor(client) {
3931
+ this.client = client;
3932
+ }
3933
+ /** Ask Grok a question. Generated from the OpenAPI spec; returns the raw response object. */
3934
+ async askGrokAQuestion(params = {}) {
3935
+ return this.client.request("/v1/grok/ask", { params });
3936
+ }
3937
+ /** Ask Grok a question (POST). Generated from the OpenAPI spec; returns the raw response object. */
3938
+ async askGrokAQuestionPost(body, params = {}) {
3939
+ return this.client.request("/v1/grok/ask", { method: "POST", params, body });
3940
+ }
3941
+ /** Measure brand visibility in Grok. Generated from the OpenAPI spec; returns the raw response object. */
3942
+ async measureBrandVisibilityInGrok(params = {}) {
3943
+ return this.client.request("/v1/grok/brand-visibility", { params });
3944
+ }
3945
+ /** Measure brand visibility in Grok (POST). Generated from the OpenAPI spec; returns the raw response object. */
3946
+ async measureBrandVisibilityInGrokPost(body, params = {}) {
3947
+ return this.client.request("/v1/grok/brand-visibility", { method: "POST", params, body });
3948
+ }
3949
+ /** Get a Grok conversation. Generated from the OpenAPI spec; returns the raw response object. */
3950
+ async getAGrokConversation(conversationId, params = {}) {
3951
+ return this.client.request(`/v1/grok/conversations/${conversationId}`, { params });
3952
+ }
3953
+ /** List Grok assistant modes. Generated from the OpenAPI spec; returns the raw response object. */
3954
+ async listGrokAssistantModes(params = {}) {
3955
+ return this.client.request("/v1/grok/models", { params });
3956
+ }
3957
+ };
3958
+
3842
3959
  // src/idealista/client.ts
3843
3960
  var IdealistaClient = class {
3844
3961
  client;
@@ -5027,12 +5144,65 @@ var RedfinClient = class {
5027
5144
  // --- END generated by sdk/codegen/facade ---
5028
5145
  };
5029
5146
 
5147
+ // src/rufus/client.ts
5148
+ var RufusClient = class {
5149
+ client;
5150
+ constructor(client) {
5151
+ this.client = client;
5152
+ }
5153
+ /** Ask Amazon Rufus a question. Generated from the OpenAPI spec; returns the raw response object. */
5154
+ async askAmazonRufusAQuestion(params = {}) {
5155
+ return this.client.request("/v1/rufus/ask", { params });
5156
+ }
5157
+ /** Ask Amazon Rufus a question (POST). Generated from the OpenAPI spec; returns the raw response object. */
5158
+ async askAmazonRufusAQuestionPost(body, params = {}) {
5159
+ return this.client.request("/v1/rufus/ask", { method: "POST", params, body });
5160
+ }
5161
+ /** List Amazon Rufus models. Generated from the OpenAPI spec; returns the raw response object. */
5162
+ async listAmazonRufusModels(params = {}) {
5163
+ return this.client.request("/v1/rufus/models", { params });
5164
+ }
5165
+ };
5166
+
5030
5167
  // src/account/client.ts
5031
5168
  var AccountClient = class {
5032
- client;
5033
5169
  constructor(client) {
5034
5170
  this.client = client;
5035
5171
  }
5172
+ /**
5173
+ * The secret that signs this account's async-request and batch webhooks,
5174
+ * created on first use. Free. Needs a full-access API key.
5175
+ *
5176
+ * @throws PermissionDeniedError - 403 `full_access_required`: a key limited to some APIs.
5177
+ */
5178
+ async webhookSecret() {
5179
+ return this.client.request("/v1/account/webhook-secret");
5180
+ }
5181
+ /**
5182
+ * Replace the webhook signing secret. Deliveries that start from now on are
5183
+ * signed with the new one; retries of a delivery already under way keep the
5184
+ * old one. Free. Needs a full-access API key.
5185
+ *
5186
+ * @throws PermissionDeniedError - 403 `full_access_required`: a key limited to some APIs.
5187
+ */
5188
+ async rotateWebhookSecret() {
5189
+ return this.client.request("/v1/account/webhook-secret/rotate", {
5190
+ method: "POST"
5191
+ });
5192
+ }
5193
+ /**
5194
+ * The account's webhook deliveries of the last 24 hours, newest first.
5195
+ * Free. Needs a full-access API key.
5196
+ *
5197
+ * @param options - `limit` (API default 50, max 200).
5198
+ * @throws PermissionDeniedError - 403 `full_access_required`: a key limited to some APIs.
5199
+ */
5200
+ async webhookDeliveries(options = {}) {
5201
+ return this.client.request("/v1/account/webhook-deliveries", {
5202
+ params: { limit: options.limit }
5203
+ });
5204
+ }
5205
+ // --- BEGIN generated by sdk/codegen/facade — do not edit ---
5036
5206
  /** Get account info. Generated from the OpenAPI spec; returns the raw response object. */
5037
5207
  async getAccountInfo(params = {}) {
5038
5208
  return this.client.request("/v1/account/me", { params });
@@ -5049,7 +5219,208 @@ var AccountClient = class {
5049
5219
  body
5050
5220
  });
5051
5221
  }
5222
+ // --- END generated by sdk/codegen/facade ---
5223
+ };
5224
+
5225
+ // src/requests/client.ts
5226
+ var DEFAULT_WAIT_S = 25;
5227
+ var MAX_WAIT_S = 120;
5228
+ var DEFAULT_POLL_S = 5;
5229
+ var MIN_POLL_MS = 250;
5230
+ var DEFAULT_WAIT_TIMEOUT_MS = 6e5;
5231
+ var WAIT_POLL_RETRIES = 2;
5232
+ var WaitTimeoutError = class _WaitTimeoutError extends TimeoutError {
5233
+ /** The request that is still running. */
5234
+ requestId;
5235
+ constructor(requestId, timeoutMs) {
5236
+ super(
5237
+ `Request ${requestId} still running after ${timeoutMs}ms. It keeps running: poll it again with requests.get() or requests.wait(); do not re-submit it.`,
5238
+ timeoutMs
5239
+ );
5240
+ this.name = "WaitTimeoutError";
5241
+ this.requestId = requestId;
5242
+ Object.setPrototypeOf(this, _WaitTimeoutError.prototype);
5243
+ }
5244
+ };
5245
+ var RequestsClient = class {
5246
+ constructor(client) {
5247
+ this.client = client;
5248
+ }
5249
+ /**
5250
+ * Submit any API call asynchronously.
5251
+ *
5252
+ * Sends `Prefer: respond-async[, wait=N]`, plus `X-Callback-URL` and
5253
+ * `Idempotency-Key` when given. A call that finishes within `wait` comes
5254
+ * back completed; otherwise the API answers 202 and this returns a running
5255
+ * request to {@link get} or {@link wait} for (or to expect a webhook for).
5256
+ *
5257
+ * Without an `idempotencyKey`, a submit is retried only when the connection
5258
+ * failed before anything was sent. A timeout, a network fault, a 429 or a
5259
+ * 5xx is thrown: the call may already be running, and a second submit would
5260
+ * run and bill it again. With a key, the usual retries are safe (a retry
5261
+ * answers the existing call), except that a replayed error is never retried.
5262
+ *
5263
+ * @param path - API path, e.g. "/v1/perplexity/ask" (the "/v1" prefix is optional).
5264
+ * @param options - `method`, `params`, `body`, `callbackUrl`, `wait`, `idempotencyKey`.
5265
+ * @returns The running request (202) or the completed call.
5266
+ * @throws ScrapeBadgerError - A refusal before anything ran (400 `invalid_callback_url`,
5267
+ * `async_not_supported`, `invalid_idempotency_key`; 401; 402; 429), or the call's own
5268
+ * error when it completed within `wait`, as the matching subclass.
5269
+ * @throws ConflictError - 409 `idempotency_key_reused`: the key was used for a different call.
5270
+ */
5271
+ async submit(path, options = {}) {
5272
+ const { method = "GET", params, body, callbackUrl, wait, idempotencyKey } = options;
5273
+ if (wait !== void 0 && (!Number.isFinite(wait) || wait < 0)) {
5274
+ throw new RangeError(`wait must be a number of seconds (0-${MAX_WAIT_S}), got ${wait}`);
5275
+ }
5276
+ const waitS = wait !== void 0 ? Math.floor(wait) : callbackUrl ? 0 : void 0;
5277
+ const headers = {
5278
+ Prefer: waitS === void 0 ? "respond-async" : `respond-async, wait=${waitS}`
5279
+ };
5280
+ if (callbackUrl !== void 0) headers["X-Callback-URL"] = callbackUrl;
5281
+ if (idempotencyKey !== void 0) headers["Idempotency-Key"] = idempotencyKey;
5282
+ const query = {};
5283
+ for (const [key, value] of Object.entries(params ?? {})) {
5284
+ if (value !== null && value !== void 0) query[key] = value;
5285
+ }
5286
+ const effectiveWaitS = Math.min(waitS ?? DEFAULT_WAIT_S, MAX_WAIT_S);
5287
+ const timeoutMs = Math.max(this.client.config.timeout, (effectiveWaitS + 15) * 1e3);
5288
+ const response = await this.client.requestResponse(apiPath(path), {
5289
+ method,
5290
+ params: query,
5291
+ body,
5292
+ headers,
5293
+ timeoutMs,
5294
+ retry: idempotencyKey !== void 0 ? "all" : "connect"
5295
+ });
5296
+ return toAsyncRequest(response);
5297
+ }
5298
+ /**
5299
+ * Poll an async request once. Free.
5300
+ *
5301
+ * @param requestId - `request_id` from the 202 response (or `AsyncRequest.requestId`).
5302
+ * @returns `status: "running"` while in progress; once completed, the original status,
5303
+ * headers and body.
5304
+ * @throws NotFoundError - Unknown or expired request (results are kept about 15 minutes;
5305
+ * one that never completed was not billed).
5306
+ * @throws ScrapeBadgerError - The original call finished with an error status (as the
5307
+ * matching subclass).
5308
+ */
5309
+ async get(requestId) {
5310
+ return this.poll(requestId);
5311
+ }
5312
+ /**
5313
+ * Poll an async request until it completes, pausing as long as the API's
5314
+ * `Retry-After` says between polls. Free. An error status is thrown at
5315
+ * once, never retried: a stored result answers the same every time.
5316
+ *
5317
+ * @param requestId - `request_id` of the running request.
5318
+ * @param options - `timeoutMs` (default 600000, ten minutes).
5319
+ * @returns The completed request.
5320
+ * @throws WaitTimeoutError - Still running at the deadline (it keeps running; poll it again).
5321
+ * @throws NotFoundError - Unknown or expired request.
5322
+ * @throws ScrapeBadgerError - The original call finished with an error status.
5323
+ */
5324
+ async wait(requestId, options = {}) {
5325
+ const timeoutMs = options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
5326
+ const deadline = Date.now() + timeoutMs;
5327
+ const maxRetries = Math.min(this.client.config.maxRetries, WAIT_POLL_RETRIES);
5328
+ for (; ; ) {
5329
+ const state = await this.poll(requestId, { maxRetries, retry: "transport" });
5330
+ if (state.status === "completed") return state;
5331
+ const remainingMs = deadline - Date.now();
5332
+ if (remainingMs <= 0) throw new WaitTimeoutError(requestId, timeoutMs);
5333
+ const suggestedMs = (state.retryAfterSeconds ?? DEFAULT_POLL_S) * 1e3;
5334
+ await sleep2(Math.min(Math.max(suggestedMs, MIN_POLL_MS), remainingMs));
5335
+ }
5336
+ }
5337
+ /**
5338
+ * Webhook delivery state of a call submitted with a `callbackUrl`. Free.
5339
+ *
5340
+ * @param requestId - `request_id` of the call.
5341
+ * @throws NotFoundError - 404 `callback_not_found`: no such request, or it had no callback.
5342
+ */
5343
+ async callbackStatus(requestId) {
5344
+ return this.client.request(
5345
+ `/v1/requests/${encodeURIComponent(requestId)}/callback`
5346
+ );
5347
+ }
5348
+ /**
5349
+ * Submit up to 100 GET reads as async requests in one call. Submitting is free.
5350
+ *
5351
+ * Each item runs under this key with the same auth, credit check, rate limit
5352
+ * and price as if sent alone; at most 10 of a batch run at a time.
5353
+ *
5354
+ * @example
5355
+ * ```typescript
5356
+ * const sub = await client.requests.batch(
5357
+ * prompts.map((prompt) => ({ path: "/v1/chatgpt/ask", query: { prompt } })),
5358
+ * { callbackUrl: "https://example.com/hook" }
5359
+ * );
5360
+ * const ids = sub.requests.filter((r) => r.accepted).map((r) => r.request_id);
5361
+ * ```
5362
+ *
5363
+ * @param items - `{ path: "/v1/...", query: {...} }` (method defaults to GET).
5364
+ * @param options - `callbackUrl` for one signed webhook per item.
5365
+ * @returns A request_id (or the refusal) for every item.
5366
+ */
5367
+ async batch(items, options = {}) {
5368
+ return this.client.request("/v1/batch", {
5369
+ method: "POST",
5370
+ body: { requests: items, callback_url: options.callbackUrl }
5371
+ });
5372
+ }
5373
+ async poll(requestId, options = {}) {
5374
+ const response = await this.client.requestResponse(
5375
+ `/v1/requests/${encodeURIComponent(requestId)}`,
5376
+ options
5377
+ );
5378
+ return toAsyncRequest(response, requestId);
5379
+ }
5052
5380
  };
5381
+ function apiPath(path) {
5382
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//") || path.startsWith("\\")) {
5383
+ throw new TypeError(`path must be an API path such as "/v1/perplexity/ask", not a URL`);
5384
+ }
5385
+ const bare = path.replace(/^\/+/, "");
5386
+ return bare === "v1" || bare.startsWith("v1/") ? `/${bare}` : `/v1/${bare}`;
5387
+ }
5388
+ function toAsyncRequest(response, requestId) {
5389
+ const { status, headers, body } = response;
5390
+ const accepted = status === 202 && typeof body === "object" && body !== null ? body : null;
5391
+ const running = status === 202 && (requestId !== void 0 || typeof accepted?.request_id === "string");
5392
+ const headerMap = {};
5393
+ headers.forEach((value, name) => {
5394
+ headerMap[name.toLowerCase()] = value;
5395
+ });
5396
+ const credits = headers.get("X-Credits-Used");
5397
+ return {
5398
+ requestId: requestId ?? (typeof accepted?.request_id === "string" ? accepted.request_id : null) ?? headers.get("X-Request-ID") ?? "",
5399
+ status: running ? "running" : "completed",
5400
+ running,
5401
+ retryAfterSeconds: running ? retryAfterSeconds(headers, accepted?.retry_after_seconds) : null,
5402
+ statusCode: status,
5403
+ headers: headerMap,
5404
+ body,
5405
+ replayed: headers.get("Idempotent-Replayed")?.trim().toLowerCase() === "true",
5406
+ creditsUsed: credits && /^\d+$/.test(credits) ? Number(credits) : null,
5407
+ resultId: null,
5408
+ // deprecated: the API no longer sends X-Result-ID
5409
+ data: body
5410
+ };
5411
+ }
5412
+ function retryAfterSeconds(headers, fromBody) {
5413
+ const header = headers.get("Retry-After")?.trim();
5414
+ if (header) {
5415
+ if (/^\d+$/.test(header)) return Number(header);
5416
+ const at = Date.parse(header);
5417
+ if (!Number.isNaN(at)) return Math.max(0, Math.ceil((at - Date.now()) / 1e3));
5418
+ }
5419
+ return typeof fromBody === "number" && Number.isFinite(fromBody) && fromBody >= 0 ? fromBody : null;
5420
+ }
5421
+ function sleep2(ms) {
5422
+ return new Promise((resolve) => setTimeout(resolve, ms));
5423
+ }
5053
5424
 
5054
5425
  // src/agent/client.ts
5055
5426
  var AgentClient = class {
@@ -5139,62 +5510,6 @@ var ResultsClient = class {
5139
5510
  });
5140
5511
  }
5141
5512
  };
5142
- var RequestsClient = class {
5143
- constructor(client) {
5144
- this.client = client;
5145
- }
5146
- /**
5147
- * Poll an async request. Free.
5148
- *
5149
- * @param requestId - `request_id` from the 202 response.
5150
- * @returns `running: true` while in progress; once done, `data` is the original body.
5151
- * @throws NotFoundError - Unknown or expired request (one that never completed was not billed).
5152
- * @throws ScrapeBadgerError - The original call finished with an error status (as the matching subclass).
5153
- */
5154
- async get(requestId) {
5155
- const { data, status, headers } = await this.client.requestWithHeaders(
5156
- `/v1/requests/${encodeURIComponent(requestId)}`
5157
- );
5158
- const running = status === 202;
5159
- const retryAfter = running ? data?.retry_after_seconds : void 0;
5160
- const credits = headers?.get("X-Credits-Used");
5161
- return {
5162
- requestId,
5163
- running,
5164
- status: status ?? 200,
5165
- retryAfterSeconds: retryAfter ?? null,
5166
- resultId: null,
5167
- // deprecated: the API no longer sends X-Result-ID
5168
- creditsUsed: credits && /^\d+$/.test(credits) ? Number(credits) : null,
5169
- data
5170
- };
5171
- }
5172
- /**
5173
- * Submit up to 100 GET reads as async requests in one call. Submitting is free.
5174
- *
5175
- * Each item runs under this key with the same auth, credit check, rate limit
5176
- * and price as if sent alone; at most 10 of a batch run at a time.
5177
- *
5178
- * @example
5179
- * ```typescript
5180
- * const sub = await client.requests.batch(
5181
- * prompts.map((prompt) => ({ path: "/v1/chatgpt/ask", query: { prompt } })),
5182
- * { callbackUrl: "https://example.com/hook" }
5183
- * );
5184
- * const ids = sub.requests.filter((r) => r.accepted).map((r) => r.request_id);
5185
- * ```
5186
- *
5187
- * @param items - `{ path: "/v1/...", query: {...} }` (method defaults to GET).
5188
- * @param options - `callbackUrl` for one signed webhook per item.
5189
- * @returns A request_id (or the refusal) for every item.
5190
- */
5191
- async batch(items, options = {}) {
5192
- return this.client.request("/v1/batch", {
5193
- method: "POST",
5194
- body: { requests: items, callback_url: options.callbackUrl }
5195
- });
5196
- }
5197
- };
5198
5513
 
5199
5514
  // src/airbnb/client.ts
5200
5515
  var AirbnbClient = class {
@@ -10771,6 +11086,8 @@ var ScrapeBadger = class {
10771
11086
  google;
10772
11087
  /** Google_Play API client. (Generated from the OpenAPI spec.) */
10773
11088
  google_play;
11089
+ /** Grok API client. (Generated from the OpenAPI spec.) */
11090
+ grok;
10774
11091
  /** Idealista API client. (Generated from the OpenAPI spec.) */
10775
11092
  idealista;
10776
11093
  /** Reddit scraper API client */
@@ -10787,8 +11104,10 @@ var ScrapeBadger = class {
10787
11104
  instagram;
10788
11105
  /** Redfin scraper API client — search, property, agent, autocomplete, markets (redfin.com, US) */
10789
11106
  redfin;
11107
+ /** Rufus API client. (Generated from the OpenAPI spec.) */
11108
+ rufus;
10790
11109
  /** Amazon scraper API client — 14 endpoints */
10791
- /** Account API client. (Generated from the OpenAPI spec.) */
11110
+ /** Account info, the webhook signing secret and the webhook delivery log. Free. */
10792
11111
  account;
10793
11112
  /** Quote a call before making it, and report bugs or send feedback. Free. */
10794
11113
  agent;
@@ -10797,7 +11116,11 @@ var ScrapeBadger = class {
10797
11116
  * 410 Gone since 2026-11-09); see `ResultsClient.get`.
10798
11117
  */
10799
11118
  results;
10800
- /** Poll a call made with `Prefer: respond-async`. Free. */
11119
+ /**
11120
+ * Async requests: submit any call (optionally with a webhook and an
11121
+ * idempotency key), poll it, wait for it, check its webhook delivery.
11122
+ * Polling is free; the call is billed once, when it completes.
11123
+ */
10801
11124
  requests;
10802
11125
  /** Airbnb API client. (Generated from the OpenAPI spec.) */
10803
11126
  airbnb;
@@ -10911,6 +11234,7 @@ var ScrapeBadger = class {
10911
11234
  this.vinted = new VintedClient(this.baseClient);
10912
11235
  this.google = new GoogleClient(this.baseClient);
10913
11236
  this.google_play = new GooglePlayClient(this.baseClient);
11237
+ this.grok = new GrokClient(this.baseClient);
10914
11238
  this.idealista = new IdealistaClient(this.baseClient);
10915
11239
  this.reddit = new RedditClient(this.baseClient);
10916
11240
  this.apartments = new ApartmentsClient(this.baseClient);
@@ -10919,6 +11243,7 @@ var ScrapeBadger = class {
10919
11243
  this.autoscout24 = new Autoscout24Client(this.baseClient);
10920
11244
  this.instagram = new InstagramClient(this.baseClient);
10921
11245
  this.redfin = new RedfinClient(this.baseClient);
11246
+ this.rufus = new RufusClient(this.baseClient);
10922
11247
  this.account = new AccountClient(this.baseClient);
10923
11248
  this.agent = new AgentClient(this.baseClient);
10924
11249
  this.results = new ResultsClient(this.baseClient);
@@ -10963,6 +11288,6 @@ var ScrapeBadger = class {
10963
11288
  }
10964
11289
  };
10965
11290
 
10966
- export { AccountRestrictedError, AgentClient, AmazonClient, ListingsClient as AmazonListingsClient, ProductsClient2 as AmazonProductsClient, ReferenceClient2 as AmazonReferenceClient, SearchClient5 as AmazonSearchClient, SellersClient as AmazonSellersClient, ApartmentsClient, AuthenticationError, BaiduClient, BingClient, MediaClient3 as BingMediaClient, NewsClient2 as BingNewsClient, ReferenceClient8 as BingReferenceClient, SearchClient11 as BingSearchClient, BlockedError, AskClient as ChatGPTAskClient, BrandClient as ChatGPTBrandClient, ChatGPTClient, ReferenceClient16 as ChatGPTReferenceClient, CommunitiesClient, ConflictError, DepopClient, DuckDuckGoClient, MediaClient2 as DuckDuckGoMediaClient, ReferenceClient7 as DuckDuckGoReferenceClient, SearchClient10 as DuckDuckGoSearchClient, CategoriesClient as EbayCategoriesClient, EbayClient, ItemsClient2 as EbayItemsClient, ReferenceClient5 as EbayReferenceClient, SearchClient8 as EbaySearchClient, SellersClient2 as EbaySellersClient, AskClient2 as GeminiAskClient, BrandClient2 as GeminiBrandClient, GeminiClient, GeoClient, AdsClient as GoogleAdsClient, AiModeClient as GoogleAiModeClient, AutocompleteClient as GoogleAutocompleteClient, GoogleClient, FinanceClient as GoogleFinanceClient, FlightsClient as GoogleFlightsClient, HotelsClient as GoogleHotelsClient, ImagesClient as GoogleImagesClient, JobsClient as GoogleJobsClient, LensClient as GoogleLensClient, MapsClient as GoogleMapsClient, NewsClient as GoogleNewsClient, PatentsClient as GooglePatentsClient, ProductsClient as GoogleProductsClient, ScholarClient as GoogleScholarClient, SearchClient2 as GoogleSearchClient, ShoppingClient as GoogleShoppingClient, ShortsClient as GoogleShortsClient, TrendsClient2 as GoogleTrendsClient, VideosClient as GoogleVideosClient, GumtreeClient, IPNotAllowedError, ImmobiliareClient, AudioClient as InstagramAudioClient, InstagramClient, HashtagsClient as InstagramHashtagsClient, LocationsClient as InstagramLocationsClient, MediaClient as InstagramMediaClient, SearchClient4 as InstagramSearchClient, UsersClient4 as InstagramUsersClient, InsufficientCreditsError, AdsClient3 as LeboncoinAdsClient, LeboncoinClient, ReferenceClient13 as LeboncoinReferenceClient, SearchClient17 as LeboncoinSearchClient, SellersClient4 as LeboncoinSellersClient, LinkedInClient, ListsClient, BrokersClient as LoopNetBrokersClient, LoopNetClient, ListingsClient2 as LoopNetListingsClient, ReferenceClient15 as LoopNetReferenceClient, SearchClient19 as LoopNetSearchClient, NaverClient, ContentClient as NaverContentClient, PlacesClient as NaverPlacesClient, ProductsClient5 as NaverProductsClient, ReviewsClient2 as NaverReviewsClient, SearchClient12 as NaverSearchClient, ShoppingClient2 as NaverShoppingClient, ShoppingLiveClient as NaverShoppingLiveClient, StoresClient2 as NaverStoresClient, NotFoundError, PermissionDeniedError, RateLimitError, RealtorClient, PropertiesClient as RealtorPropertiesClient, ReferenceClient12 as RealtorReferenceClient, SearchClient16 as RealtorSearchClient, RedditClient, PostsClient as RedditPostsClient, SearchClient3 as RedditSearchClient, SubredditsClient as RedditSubredditsClient, UsersClient3 as RedditUsersClient, RedfinClient, RequestsClient, ResultsClient, ScrapeBadger, ScrapeBadgerError, ServerError, ShopeeClient, ProductsClient3 as ShopeeProductsClient, ReferenceClient3 as ShopeeReferenceClient, ReviewsClient as ShopeeReviewsClient, SearchClient6 as ShopeeSearchClient, SpacesClient, StreamClient, AdsClient2 as TikTokAdsClient, TikTokClient, HashtagsClient2 as TikTokHashtagsClient, MusicClient as TikTokMusicClient, ReferenceClient4 as TikTokReferenceClient, SearchClient7 as TikTokSearchClient, TrendingClient as TikTokTrendingClient, UsersClient5 as TikTokUsersClient, VideosClient2 as TikTokVideosClient, TimeoutError, TrendsClient, TweetsClient, TwitterClient, UsersClient, ValidationError, VintedClient, ItemsClient as VintedItemsClient, ReferenceClient as VintedReferenceClient, SearchClient as VintedSearchClient, UsersClient2 as VintedUsersClient, WallapopClient, WalmartClient, ProductsClient4 as WalmartProductsClient, ReferenceClient6 as WalmartReferenceClient, SearchClient9 as WalmartSearchClient, SellersClient3 as WalmartSellersClient, StoresClient as WalmartStoresClient, WebClient, WebSocketStreamError, YahooClient, MediaClient4 as YahooMediaClient, NewsClient3 as YahooNewsClient, ReferenceClient9 as YahooReferenceClient, SearchClient13 as YahooSearchClient, YandexClient, ImagesClient2 as YandexImagesClient, ReferenceClient10 as YandexReferenceClient, SearchClient14 as YandexSearchClient, ChannelsClient as YoutubeChannelsClient, YoutubeClient, CommunityClient as YoutubeCommunityClient, MusicClient2 as YoutubeMusicClient, PlaylistsClient as YoutubePlaylistsClient, ReferenceClient11 as YoutubeReferenceClient, SearchClient15 as YoutubeSearchClient, ShortsClient2 as YoutubeShortsClient, TrendingClient2 as YoutubeTrendingClient, VideosClient3 as YoutubeVideosClient, AgentClient2 as ZillowAgentClient, ZillowClient, PropertiesClient2 as ZillowPropertiesClient, ReferenceClient14 as ZillowReferenceClient, SearchClient18 as ZillowSearchClient, collectAll, verifyWebhookSignature };
11291
+ export { AccountRestrictedError, AgentClient, AmazonClient, ListingsClient as AmazonListingsClient, ProductsClient2 as AmazonProductsClient, ReferenceClient2 as AmazonReferenceClient, SearchClient5 as AmazonSearchClient, SellersClient as AmazonSellersClient, ApartmentsClient, AuthenticationError, BaiduClient, BingClient, MediaClient3 as BingMediaClient, NewsClient2 as BingNewsClient, ReferenceClient8 as BingReferenceClient, SearchClient11 as BingSearchClient, BlockedError, AskClient as ChatGPTAskClient, BrandClient as ChatGPTBrandClient, ChatGPTClient, ReferenceClient16 as ChatGPTReferenceClient, CommunitiesClient, ConflictError, DepopClient, DuckDuckGoClient, MediaClient2 as DuckDuckGoMediaClient, ReferenceClient7 as DuckDuckGoReferenceClient, SearchClient10 as DuckDuckGoSearchClient, CategoriesClient as EbayCategoriesClient, EbayClient, ItemsClient2 as EbayItemsClient, ReferenceClient5 as EbayReferenceClient, SearchClient8 as EbaySearchClient, SellersClient2 as EbaySellersClient, AskClient2 as GeminiAskClient, BrandClient2 as GeminiBrandClient, GeminiClient, GeoClient, AdsClient as GoogleAdsClient, AiModeClient as GoogleAiModeClient, AutocompleteClient as GoogleAutocompleteClient, GoogleClient, FinanceClient as GoogleFinanceClient, FlightsClient as GoogleFlightsClient, HotelsClient as GoogleHotelsClient, ImagesClient as GoogleImagesClient, JobsClient as GoogleJobsClient, LensClient as GoogleLensClient, MapsClient as GoogleMapsClient, NewsClient as GoogleNewsClient, PatentsClient as GooglePatentsClient, ProductsClient as GoogleProductsClient, ScholarClient as GoogleScholarClient, SearchClient2 as GoogleSearchClient, ShoppingClient as GoogleShoppingClient, ShortsClient as GoogleShortsClient, TrendsClient2 as GoogleTrendsClient, VideosClient as GoogleVideosClient, GumtreeClient, IPNotAllowedError, ImmobiliareClient, AudioClient as InstagramAudioClient, InstagramClient, HashtagsClient as InstagramHashtagsClient, LocationsClient as InstagramLocationsClient, MediaClient as InstagramMediaClient, SearchClient4 as InstagramSearchClient, UsersClient4 as InstagramUsersClient, InsufficientCreditsError, AdsClient3 as LeboncoinAdsClient, LeboncoinClient, ReferenceClient13 as LeboncoinReferenceClient, SearchClient17 as LeboncoinSearchClient, SellersClient4 as LeboncoinSellersClient, LinkedInClient, ListsClient, BrokersClient as LoopNetBrokersClient, LoopNetClient, ListingsClient2 as LoopNetListingsClient, ReferenceClient15 as LoopNetReferenceClient, SearchClient19 as LoopNetSearchClient, NaverClient, ContentClient as NaverContentClient, PlacesClient as NaverPlacesClient, ProductsClient5 as NaverProductsClient, ReviewsClient2 as NaverReviewsClient, SearchClient12 as NaverSearchClient, ShoppingClient2 as NaverShoppingClient, ShoppingLiveClient as NaverShoppingLiveClient, StoresClient2 as NaverStoresClient, NotFoundError, PermissionDeniedError, RateLimitError, RealtorClient, PropertiesClient as RealtorPropertiesClient, ReferenceClient12 as RealtorReferenceClient, SearchClient16 as RealtorSearchClient, RedditClient, PostsClient as RedditPostsClient, SearchClient3 as RedditSearchClient, SubredditsClient as RedditSubredditsClient, UsersClient3 as RedditUsersClient, RedfinClient, RequestsClient, ResultsClient, ScrapeBadger, ScrapeBadgerError, ServerError, ShopeeClient, ProductsClient3 as ShopeeProductsClient, ReferenceClient3 as ShopeeReferenceClient, ReviewsClient as ShopeeReviewsClient, SearchClient6 as ShopeeSearchClient, SpacesClient, StreamClient, AdsClient2 as TikTokAdsClient, TikTokClient, HashtagsClient2 as TikTokHashtagsClient, MusicClient as TikTokMusicClient, ReferenceClient4 as TikTokReferenceClient, SearchClient7 as TikTokSearchClient, TrendingClient as TikTokTrendingClient, UsersClient5 as TikTokUsersClient, VideosClient2 as TikTokVideosClient, TimeoutError, TrendsClient, TweetsClient, TwitterClient, UsersClient, ValidationError, VintedClient, ItemsClient as VintedItemsClient, ReferenceClient as VintedReferenceClient, SearchClient as VintedSearchClient, UsersClient2 as VintedUsersClient, WaitTimeoutError, WallapopClient, WalmartClient, ProductsClient4 as WalmartProductsClient, ReferenceClient6 as WalmartReferenceClient, SearchClient9 as WalmartSearchClient, SellersClient3 as WalmartSellersClient, StoresClient as WalmartStoresClient, WebClient, WebSocketStreamError, YahooClient, MediaClient4 as YahooMediaClient, NewsClient3 as YahooNewsClient, ReferenceClient9 as YahooReferenceClient, SearchClient13 as YahooSearchClient, YandexClient, ImagesClient2 as YandexImagesClient, ReferenceClient10 as YandexReferenceClient, SearchClient14 as YandexSearchClient, ChannelsClient as YoutubeChannelsClient, YoutubeClient, CommunityClient as YoutubeCommunityClient, MusicClient2 as YoutubeMusicClient, PlaylistsClient as YoutubePlaylistsClient, ReferenceClient11 as YoutubeReferenceClient, SearchClient15 as YoutubeSearchClient, ShortsClient2 as YoutubeShortsClient, TrendingClient2 as YoutubeTrendingClient, VideosClient3 as YoutubeVideosClient, AgentClient2 as ZillowAgentClient, ZillowClient, PropertiesClient2 as ZillowPropertiesClient, ReferenceClient14 as ZillowReferenceClient, SearchClient18 as ZillowSearchClient, collectAll, parseWebhookEvent, verifyWebhookSignature };
10967
11292
  //# sourceMappingURL=index.mjs.map
10968
11293
  //# sourceMappingURL=index.mjs.map