scrapfly-sdk 0.11.0 → 0.12.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.
Files changed (68) hide show
  1. package/README.md +36 -3
  2. package/esm/browserconfig.d.ts +37 -5
  3. package/esm/browserconfig.d.ts.map +1 -1
  4. package/esm/browserconfig.js +51 -3
  5. package/esm/client.d.ts +124 -9
  6. package/esm/client.d.ts.map +1 -1
  7. package/esm/client.js +346 -50
  8. package/esm/crawl.d.ts +58 -1
  9. package/esm/crawl.d.ts.map +1 -1
  10. package/esm/crawl.js +55 -0
  11. package/esm/crawlerconfig.d.ts +41 -3
  12. package/esm/crawlerconfig.d.ts.map +1 -1
  13. package/esm/crawlerconfig.js +93 -2
  14. package/esm/crawlerresult.d.ts +335 -2
  15. package/esm/crawlerresult.d.ts.map +1 -1
  16. package/esm/crawlerresult.js +367 -1
  17. package/esm/errors.d.ts +12 -0
  18. package/esm/errors.d.ts.map +1 -1
  19. package/esm/errors.js +11 -0
  20. package/esm/main.d.ts +4 -4
  21. package/esm/main.d.ts.map +1 -1
  22. package/esm/main.js +3 -3
  23. package/esm/scrapeconfig.d.ts +36 -0
  24. package/esm/scrapeconfig.d.ts.map +1 -1
  25. package/esm/scrapeconfig.js +44 -2
  26. package/esm/types.d.ts.map +1 -1
  27. package/esm/webhookserver.d.ts +33 -15
  28. package/esm/webhookserver.d.ts.map +1 -1
  29. package/esm/webhookserver.js +197 -38
  30. package/package.json +1 -1
  31. package/script/browserconfig.d.ts +37 -5
  32. package/script/browserconfig.d.ts.map +1 -1
  33. package/script/browserconfig.js +51 -3
  34. package/script/client.d.ts +124 -9
  35. package/script/client.d.ts.map +1 -1
  36. package/script/client.js +345 -49
  37. package/script/crawl.d.ts +58 -1
  38. package/script/crawl.d.ts.map +1 -1
  39. package/script/crawl.js +55 -0
  40. package/script/crawlerconfig.d.ts +41 -3
  41. package/script/crawlerconfig.d.ts.map +1 -1
  42. package/script/crawlerconfig.js +94 -3
  43. package/script/crawlerresult.d.ts +335 -2
  44. package/script/crawlerresult.d.ts.map +1 -1
  45. package/script/crawlerresult.js +374 -2
  46. package/script/errors.d.ts +12 -0
  47. package/script/errors.d.ts.map +1 -1
  48. package/script/errors.js +12 -1
  49. package/script/main.d.ts +4 -4
  50. package/script/main.d.ts.map +1 -1
  51. package/script/main.js +9 -2
  52. package/script/scrapeconfig.d.ts +36 -0
  53. package/script/scrapeconfig.d.ts.map +1 -1
  54. package/script/scrapeconfig.js +44 -2
  55. package/script/types.d.ts.map +1 -1
  56. package/script/webhookserver.d.ts +33 -15
  57. package/script/webhookserver.d.ts.map +1 -1
  58. package/script/webhookserver.js +197 -38
  59. package/src/browserconfig.ts +52 -4
  60. package/src/client.ts +413 -51
  61. package/src/crawl.ts +74 -0
  62. package/src/crawlerconfig.ts +115 -5
  63. package/src/crawlerresult.ts +566 -3
  64. package/src/errors.ts +12 -0
  65. package/src/main.ts +25 -2
  66. package/src/scrapeconfig.ts +54 -2
  67. package/src/types.ts +0 -1
  68. package/src/webhookserver.ts +235 -39
package/esm/client.js CHANGED
@@ -5,9 +5,21 @@ import * as errors from './errors.js';
5
5
  import { BrowserConfig } from './browserconfig.js';
6
6
  import { ExtractionResult, ScrapeResult, ScreenshotResult } from './result.js';
7
7
  import { log } from './logger.js';
8
- import { CrawlerArtifact, CrawlerContents, CrawlerStatus, CrawlerUrls } from './crawlerresult.js';
8
+ import { REFRESH_MAX_INTERVAL, REFRESH_MIN_INTERVAL } from './crawlerconfig.js';
9
+ import { CrawlerArtifact, CrawlerContents, CrawlerSearchResponse, CrawlerStatus, CrawlerUrls, parseCrawlerPromptStream, parseCrawlerRefreshState, } from './crawlerresult.js';
9
10
  import { formatMonitoringDate, } from './monitoringconfig.js';
10
11
  import { ScheduleAPIError, } from './schedule.js';
12
+ /** ERR::<RESOURCE>::* → error-class taxonomy. */
13
+ const RESOURCE_TO_ERROR = {
14
+ SCRAPE: errors.ScrapflyScrapeError,
15
+ WEBHOOK: errors.ScrapflyWebhookError,
16
+ PROXY: errors.ScrapflyProxyError,
17
+ SCHEDULE: errors.ScrapflyScheduleError,
18
+ ASP: errors.ScrapflyAspError,
19
+ SESSION: errors.ScrapflySessionError,
20
+ THROTTLE: errors.ScrapflyThrottleError,
21
+ CRAWLER: errors.ScrapflyCrawlerError,
22
+ };
11
23
  /**
12
24
  * Main entry point for the Scrapfly SDK.
13
25
  *
@@ -122,21 +134,9 @@ export class ScrapflyClient {
122
134
  case 429:
123
135
  return new errors.TooManyRequests(message, args);
124
136
  }
125
- switch (args.resource) {
126
- case 'SCRAPE':
127
- return new errors.ScrapflyScrapeError(message, args);
128
- case 'WEBHOOK':
129
- return new errors.ScrapflyWebhookError(message, args);
130
- case 'PROXY':
131
- return new errors.ScrapflyProxyError(message, args);
132
- case 'SCHEDULE':
133
- return new errors.ScrapflyScheduleError(message, args);
134
- case 'ASP':
135
- return new errors.ScrapflyAspError(message, args);
136
- case 'SESSION':
137
- return new errors.ScrapflySessionError(message, args);
138
- case 'CRAWLER':
139
- return new errors.ScrapflyCrawlerError(message, args);
137
+ const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
138
+ if (ResourceError) {
139
+ return new ResourceError(message, args);
140
140
  }
141
141
  if (args.resource) {
142
142
  return new errors.ApiHttpClientError(message, args);
@@ -151,25 +151,48 @@ export class ScrapflyClient {
151
151
  return new errors.UpstreamHttpServerError(message, args);
152
152
  }
153
153
  }
154
- switch (args.resource) {
155
- case 'SCRAPE':
156
- return new errors.ScrapflyScrapeError(message, args);
157
- case 'WEBHOOK':
158
- return new errors.ScrapflyWebhookError(message, args);
159
- case 'PROXY':
160
- return new errors.ScrapflyProxyError(message, args);
161
- case 'SCHEDULE':
162
- return new errors.ScrapflyScheduleError(message, args);
163
- case 'ASP':
164
- return new errors.ScrapflyAspError(message, args);
165
- case 'SESSION':
166
- return new errors.ScrapflySessionError(message, args);
167
- case 'CRAWLER':
168
- return new errors.ScrapflyCrawlerError(message, args);
154
+ const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
155
+ if (ResourceError) {
156
+ return new ResourceError(message, args);
169
157
  }
170
158
  }
171
159
  return new errors.ScrapflyError(message, args);
172
160
  }
161
+ /** Build the typed per-part error for an API-generated batch error body. */
162
+ batchApiErrorPartToError(parsed, partHeaders) {
163
+ const code = typeof parsed.code === 'string' ? parsed.code : '';
164
+ const message = String(parsed.message ?? parsed.reason ?? 'API error');
165
+ const httpStatusCode = typeof parsed.http_code === 'number'
166
+ ? parsed.http_code
167
+ : parseInt(partHeaders['x-scrapfly-scrape-status'] ?? '500', 10) || 500;
168
+ const isRetryable = parsed.retryable === true;
169
+ let documentationUrl;
170
+ if (parsed.links && typeof parsed.links === 'object' && !Array.isArray(parsed.links)) {
171
+ const values = Object.values(parsed.links);
172
+ if (values.length)
173
+ documentationUrl = values[0];
174
+ }
175
+ const args = {
176
+ code,
177
+ http_status_code: httpStatusCode,
178
+ is_retryable: isRetryable,
179
+ resource: code ? code.split('::')[1] : null,
180
+ documentation_url: documentationUrl,
181
+ };
182
+ const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
183
+ if (ResourceError) {
184
+ return new ResourceError(message, args);
185
+ }
186
+ switch (httpStatusCode) {
187
+ case 401:
188
+ return new errors.BadApiKeyError(message, args);
189
+ case 429:
190
+ return new errors.TooManyRequests(message, args);
191
+ }
192
+ return httpStatusCode >= 500
193
+ ? new errors.ApiHttpServerError(message, args)
194
+ : new errors.ApiHttpClientError(message, args);
195
+ }
173
196
  /**
174
197
  * Handle clob and blob large objects
175
198
  */
@@ -690,6 +713,18 @@ export class ScrapflyClient {
690
713
  ];
691
714
  continue;
692
715
  }
716
+ // API-generated error parts carry status >= 400 and an error body
717
+ // instead of the scrape envelope — surface them as typed errors.
718
+ const partStatus = parseInt(part.headers['x-scrapfly-scrape-status'] ?? '0', 10) || 0;
719
+ if (partStatus >= 400 &&
720
+ parsed &&
721
+ typeof parsed === 'object' &&
722
+ !Array.isArray(parsed) &&
723
+ !('result' in parsed) &&
724
+ !('config' in parsed)) {
725
+ yield [correlationId, this.batchApiErrorPartToError(parsed, part.headers)];
726
+ continue;
727
+ }
693
728
  try {
694
729
  const result = new ScrapeResult({
695
730
  config: parsed.config,
@@ -890,7 +925,7 @@ export class ScrapflyClient {
890
925
  if (urlList !== undefined) {
891
926
  // Strip url_list from the JSON config — the URLs go through the
892
927
  // 'urls' multipart part instead, which the API gateway streams
893
- // straight through to the scrape engine.
928
+ // straight through to the scraping backend.
894
929
  delete params.url_list;
895
930
  const form = new FormData();
896
931
  const configBlob = new Blob([JSON.stringify(params)], { type: 'application/json' });
@@ -1257,6 +1292,252 @@ export class ScrapflyClient {
1257
1292
  }
1258
1293
  return response.ok;
1259
1294
  }
1295
+ /**
1296
+ * Run one refresh of an existing crawl immediately, without waiting for the
1297
+ * next scheduled period.
1298
+ *
1299
+ * `POST /crawl/{uuid}/refresh` re-scrapes the crawl's own URLs in place:
1300
+ * same `crawler_uuid`, same artifacts, same search index. Only pages whose
1301
+ * content actually changed are re-indexed and pages that disappeared are
1302
+ * dropped, so everything already pointing at this crawl keeps working.
1303
+ *
1304
+ * A refresh bills the pages it re-scrapes, exactly like the original crawl.
1305
+ * What unchanged pages save is the embedding and the index write.
1306
+ *
1307
+ * The call returns as soon as the run is accepted; poll `crawlStatus` or
1308
+ * `crawlRefreshHistory` for the outcome. Do not retry it blindly: a retry
1309
+ * starts a second re-scrape of the whole site.
1310
+ */
1311
+ async crawlRefreshNow(uuid) {
1312
+ if (!uuid) {
1313
+ throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
1314
+ }
1315
+ let response;
1316
+ try {
1317
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh`);
1318
+ url.search = new URLSearchParams({ key: this.key }).toString();
1319
+ // One attempt: the server may have accepted the billable refresh even
1320
+ // when its response is lost or replaced by a gateway error.
1321
+ response = await this.fetch({
1322
+ url: url.toString(),
1323
+ method: 'POST',
1324
+ headers: {
1325
+ 'user-agent': this.ua,
1326
+ 'accept-encoding': 'gzip, deflate, br',
1327
+ accept: 'application/json',
1328
+ },
1329
+ }, 1);
1330
+ }
1331
+ catch (e) {
1332
+ log.error('error', e);
1333
+ throw e;
1334
+ }
1335
+ const data = (await response.json());
1336
+ if ('error_id' in data || data.http_code !== undefined) {
1337
+ this.throwCrawlerError(response, data);
1338
+ }
1339
+ return parseCrawlerRefreshState(data);
1340
+ }
1341
+ /**
1342
+ * Change the refresh schedule of an existing crawl.
1343
+ *
1344
+ * `PATCH /crawl/{uuid}/refresh` — only the fields passed are changed, so
1345
+ * turning a crawl off keeps its interval for when it is turned back on.
1346
+ *
1347
+ * Turning refresh on for a crawl started without it is allowed: the crawl
1348
+ * already holds the URL index a refresh walks.
1349
+ */
1350
+ async crawlRefreshSettings(uuid, settings) {
1351
+ if (!uuid) {
1352
+ throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
1353
+ }
1354
+ if (settings?.enabled === undefined && settings?.interval_seconds === undefined) {
1355
+ throw new errors.ScrapflyCrawlerError('pass at least one of enabled, interval_seconds');
1356
+ }
1357
+ if (settings.interval_seconds !== undefined &&
1358
+ (settings.interval_seconds < REFRESH_MIN_INTERVAL || settings.interval_seconds > REFRESH_MAX_INTERVAL)) {
1359
+ throw new errors.ScrapflyCrawlerError(`interval_seconds must be between ${REFRESH_MIN_INTERVAL} and ${REFRESH_MAX_INTERVAL} seconds`);
1360
+ }
1361
+ // Wire keys are the ones POST /crawl already takes, so a crawl body and a
1362
+ // later PATCH name the same things. The enabled/interval_seconds spelling
1363
+ // belongs to the state block this call answers with, not to its request;
1364
+ // the API decodes the body with unknown fields rejected.
1365
+ const payload = {};
1366
+ if (settings.enabled !== undefined)
1367
+ payload.refresh = settings.enabled;
1368
+ if (settings.interval_seconds !== undefined)
1369
+ payload.refresh_interval = settings.interval_seconds;
1370
+ let response;
1371
+ try {
1372
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh`);
1373
+ url.search = new URLSearchParams({ key: this.key }).toString();
1374
+ response = await this.fetch({
1375
+ url: url.toString(),
1376
+ method: 'PATCH',
1377
+ headers: {
1378
+ 'user-agent': this.ua,
1379
+ 'content-type': 'application/json',
1380
+ 'accept-encoding': 'gzip, deflate, br',
1381
+ accept: 'application/json',
1382
+ },
1383
+ body: JSON.stringify(payload),
1384
+ });
1385
+ }
1386
+ catch (e) {
1387
+ log.error('error', e);
1388
+ throw e;
1389
+ }
1390
+ const data = (await response.json());
1391
+ if ('error_id' in data || data.http_code !== undefined) {
1392
+ this.throwCrawlerError(response, data);
1393
+ }
1394
+ return parseCrawlerRefreshState(data);
1395
+ }
1396
+ /**
1397
+ * Read a crawl's refresh timeline, newest last.
1398
+ *
1399
+ * `GET /crawl/{uuid}/refresh/history` — the server keeps the 50 most recent
1400
+ * runs; older rows are trimmed rather than paged, because the timeline
1401
+ * exists to show recent activity.
1402
+ */
1403
+ async crawlRefreshHistory(uuid, opts) {
1404
+ if (!uuid) {
1405
+ throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
1406
+ }
1407
+ let response;
1408
+ try {
1409
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh/history`);
1410
+ const params = { key: this.key };
1411
+ if (opts?.limit !== undefined)
1412
+ params.limit = String(opts.limit);
1413
+ url.search = new URLSearchParams(params).toString();
1414
+ response = await this.fetch({
1415
+ url: url.toString(),
1416
+ method: 'GET',
1417
+ headers: {
1418
+ 'user-agent': this.ua,
1419
+ 'accept-encoding': 'gzip, deflate, br',
1420
+ accept: 'application/json',
1421
+ },
1422
+ });
1423
+ }
1424
+ catch (e) {
1425
+ log.error('error', e);
1426
+ throw e;
1427
+ }
1428
+ const data = (await response.json());
1429
+ if ('error_id' in data || data.http_code !== undefined) {
1430
+ this.throwCrawlerError(response, data);
1431
+ }
1432
+ return parseCrawlerRefreshState(data).history ?? [];
1433
+ }
1434
+ /**
1435
+ * Search across the search indexes of one or more crawls.
1436
+ *
1437
+ * `POST /crawl/search`: the collection endpoint is the real API and
1438
+ * {@link crawl.Crawl.search} is sugar over a one-element list so the two
1439
+ * cannot drift.
1440
+ *
1441
+ * Only crawls started with `search: true` whose index reached `READY` or
1442
+ * `PARTIAL` contribute. The rest come back in `skipped` with a reason and
1443
+ * never fail the call, so inspect `skipped` before concluding a crawl had
1444
+ * no match.
1445
+ */
1446
+ async crawlSearch(crawlIds, query, opts) {
1447
+ if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
1448
+ throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
1449
+ }
1450
+ if (!query) {
1451
+ throw new errors.ScrapflyCrawlerError('query must be a non-empty string');
1452
+ }
1453
+ const payload = { query, crawl_ids: crawlIds };
1454
+ if (opts?.limit !== undefined)
1455
+ payload.limit = opts.limit;
1456
+ if (opts?.mode !== undefined)
1457
+ payload.mode = opts.mode;
1458
+ if (opts?.filters !== undefined)
1459
+ payload.filters = opts.filters;
1460
+ if (opts?.cursor !== undefined)
1461
+ payload.cursor = opts.cursor;
1462
+ let response;
1463
+ try {
1464
+ const url = new URL(`${this.HOST}/crawl/search`);
1465
+ url.search = new URLSearchParams({ key: this.key }).toString();
1466
+ response = await this.fetch({
1467
+ url: url.toString(),
1468
+ method: 'POST',
1469
+ headers: {
1470
+ 'user-agent': this.ua,
1471
+ 'content-type': 'application/json',
1472
+ 'accept-encoding': 'gzip, deflate, br',
1473
+ accept: 'application/json',
1474
+ },
1475
+ body: JSON.stringify(payload),
1476
+ });
1477
+ }
1478
+ catch (e) {
1479
+ log.error('error', e);
1480
+ throw e;
1481
+ }
1482
+ const data = (await response.json());
1483
+ if ('error_id' in data || data.http_code !== undefined) {
1484
+ this.throwCrawlerError(response, data);
1485
+ }
1486
+ return new CrawlerSearchResponse(data);
1487
+ }
1488
+ /**
1489
+ * Ask a question answered from the content of one or more crawls, streaming
1490
+ * the answer as it is generated.
1491
+ *
1492
+ * `POST /crawl/prompt`: the collection endpoint is the real API and
1493
+ * {@link crawl.Crawl.prompt} is sugar over a one-element list.
1494
+ *
1495
+ * Yields `source` frames, then `token` frames, then one `done`. An
1496
+ * `event: error` frame is thrown as `ScrapflyCrawlerError` rather than
1497
+ * yielded, and can arrive after tokens were already yielded because
1498
+ * generation fails mid-stream.
1499
+ *
1500
+ * Consume with `for await`; abandoning the iterator early cancels the body.
1501
+ *
1502
+ * Do not consume this with `EventSource`: it reconnects on close and would
1503
+ * silently re-run the whole fan-out and generation.
1504
+ */
1505
+ async *crawlPrompt(crawlIds, prompt, opts) {
1506
+ if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
1507
+ throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
1508
+ }
1509
+ if (!prompt) {
1510
+ throw new errors.ScrapflyCrawlerError('prompt must be a non-empty string');
1511
+ }
1512
+ const generation = { stream: true };
1513
+ if (opts?.model !== undefined)
1514
+ generation.model = opts.model;
1515
+ const payload = { prompt, crawl_ids: crawlIds, generation };
1516
+ if (opts?.search !== undefined)
1517
+ payload.search = opts.search;
1518
+ const url = new URL(`${this.HOST}/crawl/prompt`);
1519
+ url.search = new URLSearchParams({ key: this.key }).toString();
1520
+ // One attempt only: the request runs a fan-out and a generation, both
1521
+ // billable, so a retry doubles the bill.
1522
+ const response = await this.fetch({
1523
+ url: url.toString(),
1524
+ method: 'POST',
1525
+ headers: {
1526
+ 'user-agent': this.ua,
1527
+ 'content-type': 'application/json',
1528
+ accept: 'text/event-stream',
1529
+ },
1530
+ body: JSON.stringify(payload),
1531
+ }, 1);
1532
+ if (!response.ok) {
1533
+ const data = (await response.json().catch(() => ({})));
1534
+ this.throwCrawlerError(response, data);
1535
+ }
1536
+ if (response.body === null) {
1537
+ throw new errors.ScrapflyCrawlerError('prompt response carried no body');
1538
+ }
1539
+ yield* parseCrawlerPromptStream(response.body);
1540
+ }
1260
1541
  // --- Cloud Browser ---
1261
1542
  /**
1262
1543
  * Get the WebSocket URL for a Cloud Browser session.
@@ -1271,39 +1552,45 @@ export class ScrapflyClient {
1271
1552
  }
1272
1553
  /**
1273
1554
  * Return the deterministic project salt for this client's api_key. Matches
1274
- * the `X-Browser-Project-Salt` response header returned on a successful
1275
- * Cloud Browser WebSocket upgrade.
1555
+ * the `X-Browser-Project-Salt` response header returned on VNC-enabled
1556
+ * Cloud Browser upgrades, where the salt is also the VNC password prefix.
1276
1557
  */
1277
1558
  async cloudBrowserProjectSalt() {
1278
1559
  return BrowserConfig.projectSalt(this.key);
1279
1560
  }
1561
+ /**
1562
+ * Return the password a native VNC client must type to attach to a session
1563
+ * created with `config`: `<projectSalt>-<vnc_password>`.
1564
+ *
1565
+ * Copy this value into your VNC client when connecting to the TCP endpoint
1566
+ * (port 5901). The WebSocket endpoint `/run/<run_id>/vnc` takes the raw
1567
+ * `vnc_password` instead.
1568
+ */
1569
+ async cloudBrowserVncPassword(config) {
1570
+ return config.vncClientPassword(this.key);
1571
+ }
1280
1572
  /**
1281
1573
  * Call the Cloud Browser Unblock API.
1574
+ *
1575
+ * Unblock always uses a residential proxy (no proxy pool selection) and
1576
+ * always performs a GET — the endpoint's purpose is to harvest cookies /
1577
+ * clearance tokens via an ASP-bypass navigation, not to proxy arbitrary
1578
+ * HTTP requests.
1282
1579
  */
1283
1580
  async cloudBrowserUnblock(options) {
1284
- const proxyPoolMap = {
1285
- datacenter: 'public_datacenter_pool',
1286
- residential: 'public_residential_pool',
1287
- };
1288
1581
  const jsonBody = { url: options.url };
1289
- if (options.proxy_pool)
1290
- jsonBody.proxy_pool = proxyPoolMap[options.proxy_pool] || options.proxy_pool;
1291
1582
  if (options.country)
1292
1583
  jsonBody.country = options.country;
1293
1584
  if (options.os)
1294
1585
  jsonBody.os = options.os;
1295
1586
  if (options.browser_brand)
1296
1587
  jsonBody.browser_brand = options.browser_brand;
1588
+ if (options.session)
1589
+ jsonBody.session = options.session;
1297
1590
  if (options.timeout)
1298
1591
  jsonBody.timeout = options.timeout;
1299
1592
  if (options.browser_timeout)
1300
1593
  jsonBody.browser_timeout = options.browser_timeout;
1301
- if (options.headers)
1302
- jsonBody.headers = options.headers;
1303
- if (options.body)
1304
- jsonBody.body = options.body;
1305
- if (options.method)
1306
- jsonBody.method = options.method;
1307
1594
  if (options.enable_mcp !== undefined)
1308
1595
  jsonBody.enable_mcp = options.enable_mcp;
1309
1596
  if (options.debug !== undefined)
@@ -1440,12 +1727,12 @@ export class ScrapflyClient {
1440
1727
  return await response.json();
1441
1728
  }
1442
1729
  // ----- Cloud Browser Credential Vault -------------------------------------
1443
- // Server contract documented at apps/scrapfly/api/scrapfly-api/pkg/vault/.
1730
+ // Server contract documented in the Vault API reference.
1444
1731
  //
1445
1732
  // SECURITY: the vault key is the customer-held secret that decrypts every
1446
1733
  // item in the vault. The server emits it ONCE on POST /vault and POST
1447
1734
  // /vault/{id}/rotate; never log it, never include it in error messages,
1448
- // never put it in a breadcrumb. See agent_secret_tokenization_boundary.md.
1735
+ // never put it in a breadcrumb, and never echo it back to a caller.
1449
1736
  /**
1450
1737
  * Create a new Cloud Browser Credential Vault. The response contains a
1451
1738
  * one-time `key` that the caller MUST save locally — the server cannot
@@ -1764,7 +2051,12 @@ export class ScrapflyClient {
1764
2051
  // pause/resume/execute methods work regardless of kind.
1765
2052
  // -------------------------------------------------------------------------
1766
2053
  /** Create a Web Scraping API schedule. `scrape_config` is the same shape
1767
- * accepted by `/scrape` (e.g. `{ url, render_js, asp, ... }`). */
2054
+ * accepted by `/scrape` (e.g. `{ url, render_js, asp, ... }`). This dict is
2055
+ * forwarded to the API verbatim, so its keys are wire keys, not the SDK
2056
+ * option names. The anti-bot bypass may be spelled either way here: the API
2057
+ * folds `unblocker` into `asp` on the STORED config, with the same precedence
2058
+ * the SDK uses (a supplied `asp` wins; `unblocker` is read only when `asp` is
2059
+ * absent, `null` or `""`), so both names reach the replayed scrape. */
1768
2060
  async createScrapeSchedule(scrapeConfig, request) {
1769
2061
  return await this.scheduleRequest('POST', '/scrape/schedules', undefined, this.buildCreateBody('scrape_config', scrapeConfig, request));
1770
2062
  }
@@ -1772,7 +2064,11 @@ export class ScrapflyClient {
1772
2064
  async createScreenshotSchedule(screenshotConfig, request) {
1773
2065
  return await this.scheduleRequest('POST', '/screenshot/schedules', undefined, this.buildCreateBody('screenshot_config', screenshotConfig, request));
1774
2066
  }
1775
- /** Create a Crawler API schedule. */
2067
+ /** Create a Crawler API schedule. `crawler_config` is forwarded verbatim and
2068
+ * its keys are wire keys, not the SDK option names. As with
2069
+ * `createScrapeSchedule`, the anti-bot bypass may be spelled `asp` or
2070
+ * `unblocker`: the API folds the alias into `asp` on the stored config before
2071
+ * it is ever replayed. */
1776
2072
  async createCrawlerSchedule(crawlerConfig, request) {
1777
2073
  return await this.scheduleRequest('POST', '/crawl/schedules', undefined, this.buildCreateBody('crawler_config', crawlerConfig, request));
1778
2074
  }
package/esm/crawl.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ScrapflyClient } from './client.js';
2
2
  import type { CrawlerConfig, CrawlerContentFormat } from './crawlerconfig.js';
3
- import type { CrawlerArtifact, CrawlerStatus, CrawlerUrls } from './crawlerresult.js';
3
+ import type { CrawlerArtifact, CrawlerPromptEvent, CrawlerRefreshEntry, CrawlerRefreshState, CrawlerSearchMode, CrawlerSearchResponse, CrawlerStatus, CrawlerUrls } from './crawlerresult.js';
4
4
  /**
5
5
  * High-level fluent wrapper around a single crawler job lifecycle.
6
6
  *
@@ -96,6 +96,63 @@ export declare class Crawl {
96
96
  page?: number;
97
97
  per_page?: number;
98
98
  }): Promise<CrawlerUrls>;
99
+ /**
100
+ * Search this crawl's index.
101
+ *
102
+ * Sugar over `client.crawlSearch([uuid], ...)`. The cross-crawl call is the
103
+ * real endpoint; both share its implementation so single and multi-crawl
104
+ * search cannot drift.
105
+ *
106
+ * Requires the crawl to have been started with `search: true` and its index
107
+ * to have reached `READY`/`PARTIAL`; poll `CrawlerStatus.search` or
108
+ * subscribe to the `crawler_search_ready` webhook. An index that is not
109
+ * ready yet is reported in the response's `skipped` list, not as an error.
110
+ */
111
+ search(query: string, opts?: {
112
+ limit?: number;
113
+ mode?: CrawlerSearchMode;
114
+ filters?: Record<string, any>;
115
+ cursor?: string;
116
+ }): Promise<CrawlerSearchResponse>;
117
+ /**
118
+ * Ask a question answered from this crawl's content.
119
+ *
120
+ * Sugar over `client.crawlPrompt([uuid], ...)`; yields the same frames.
121
+ */
122
+ prompt(prompt: string, opts?: {
123
+ search?: {
124
+ limit?: number;
125
+ mode?: CrawlerSearchMode;
126
+ filters?: Record<string, any>;
127
+ };
128
+ model?: string;
129
+ }): AsyncGenerator<CrawlerPromptEvent, void, undefined>;
130
+ /**
131
+ * Re-scrape this crawl's URLs in place, right now.
132
+ *
133
+ * Sugar over `client.crawlRefreshNow(uuid)`. The crawl keeps its uuid, its
134
+ * artifacts and its search index; only pages whose content changed are
135
+ * re-indexed and pages that disappeared are dropped.
136
+ */
137
+ refreshNow(): Promise<CrawlerRefreshState>;
138
+ /**
139
+ * Change this crawl's refresh schedule.
140
+ *
141
+ * Sugar over `client.crawlRefreshSettings(uuid, ...)`; only what is passed
142
+ * is changed.
143
+ */
144
+ refreshSettings(settings: {
145
+ enabled?: boolean;
146
+ interval_seconds?: number;
147
+ }): Promise<CrawlerRefreshState>;
148
+ /**
149
+ * Read this crawl's refresh timeline, newest last.
150
+ *
151
+ * Sugar over `client.crawlRefreshHistory(uuid, ...)`.
152
+ */
153
+ refreshHistory(opts?: {
154
+ limit?: number;
155
+ }): Promise<CrawlerRefreshEntry[]>;
99
156
  /**
100
157
  * Read raw content for a single crawled URL using `plain=true` mode.
101
158
  *
@@ -1 +1 @@
1
- {"version":3,"file":"crawl.d.ts","sourceRoot":"","sources":["../src/crawl.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,KAAK,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC9E,OAAO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,CAAC,kBAAkB,EAAE,IAAI,EAAE,SAAS,CAAC;IAKtD;;;;;;OAMG;IACG,UAAU,IAAI,OAAO,CAAC,mBAAmB,CAAC;IAKhD;;;;;OAKG;IACG,eAAe,CAAC,QAAQ,EAAE;QAAE,OAAO,CAAC,EAAE,OAAO,CAAC;QAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAK/G;;;;OAIG;IACG,cAAc,CAAC,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,mBAAmB,EAAE,CAAC;IAK/E;;;;;;OAMG;IACG,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,GAAE,oBAA6B,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAetF;;;;OAIG;IACG,SAAS,CACb,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,GAAE,oBAAoB,EAAa,GACzC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAKlD;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,eAAe,CAAC;IAStC;;OAEG;IACG,GAAG,IAAI,OAAO,CAAC,eAAe,CAAC;CAQtC"}
package/esm/crawl.js CHANGED
@@ -176,6 +176,61 @@ export class Crawl {
176
176
  const uuid = this.requireUuid();
177
177
  return await this.client.crawlUrls(uuid, opts);
178
178
  }
179
+ /**
180
+ * Search this crawl's index.
181
+ *
182
+ * Sugar over `client.crawlSearch([uuid], ...)`. The cross-crawl call is the
183
+ * real endpoint; both share its implementation so single and multi-crawl
184
+ * search cannot drift.
185
+ *
186
+ * Requires the crawl to have been started with `search: true` and its index
187
+ * to have reached `READY`/`PARTIAL`; poll `CrawlerStatus.search` or
188
+ * subscribe to the `crawler_search_ready` webhook. An index that is not
189
+ * ready yet is reported in the response's `skipped` list, not as an error.
190
+ */
191
+ async search(query, opts) {
192
+ const uuid = this.requireUuid();
193
+ return await this.client.crawlSearch([uuid], query, opts);
194
+ }
195
+ /**
196
+ * Ask a question answered from this crawl's content.
197
+ *
198
+ * Sugar over `client.crawlPrompt([uuid], ...)`; yields the same frames.
199
+ */
200
+ prompt(prompt, opts) {
201
+ const uuid = this.requireUuid();
202
+ return this.client.crawlPrompt([uuid], prompt, opts);
203
+ }
204
+ /**
205
+ * Re-scrape this crawl's URLs in place, right now.
206
+ *
207
+ * Sugar over `client.crawlRefreshNow(uuid)`. The crawl keeps its uuid, its
208
+ * artifacts and its search index; only pages whose content changed are
209
+ * re-indexed and pages that disappeared are dropped.
210
+ */
211
+ async refreshNow() {
212
+ const uuid = this.requireUuid();
213
+ return await this.client.crawlRefreshNow(uuid);
214
+ }
215
+ /**
216
+ * Change this crawl's refresh schedule.
217
+ *
218
+ * Sugar over `client.crawlRefreshSettings(uuid, ...)`; only what is passed
219
+ * is changed.
220
+ */
221
+ async refreshSettings(settings) {
222
+ const uuid = this.requireUuid();
223
+ return await this.client.crawlRefreshSettings(uuid, settings);
224
+ }
225
+ /**
226
+ * Read this crawl's refresh timeline, newest last.
227
+ *
228
+ * Sugar over `client.crawlRefreshHistory(uuid, ...)`.
229
+ */
230
+ async refreshHistory(opts) {
231
+ const uuid = this.requireUuid();
232
+ return await this.client.crawlRefreshHistory(uuid, opts);
233
+ }
179
234
  /**
180
235
  * Read raw content for a single crawled URL using `plain=true` mode.
181
236
  *