scrapfly-sdk 0.11.1 → 0.12.1

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 (101) hide show
  1. package/README.md +72 -5
  2. package/esm/browserconfig.d.ts +57 -9
  3. package/esm/browserconfig.d.ts.map +1 -1
  4. package/esm/browserconfig.js +63 -5
  5. package/esm/browserdownloads.d.ts +70 -0
  6. package/esm/browserdownloads.d.ts.map +1 -0
  7. package/esm/browserdownloads.js +215 -0
  8. package/esm/client.d.ts +224 -8
  9. package/esm/client.d.ts.map +1 -1
  10. package/esm/client.js +646 -62
  11. package/esm/crawl.d.ts +83 -1
  12. package/esm/crawl.d.ts.map +1 -1
  13. package/esm/crawl.js +73 -0
  14. package/esm/crawlerconfig.d.ts +54 -3
  15. package/esm/crawlerconfig.d.ts.map +1 -1
  16. package/esm/crawlerconfig.js +96 -2
  17. package/esm/crawlerresult.d.ts +374 -2
  18. package/esm/crawlerresult.d.ts.map +1 -1
  19. package/esm/crawlerresult.js +367 -1
  20. package/esm/errors.d.ts +12 -0
  21. package/esm/errors.d.ts.map +1 -1
  22. package/esm/errors.js +11 -0
  23. package/esm/main.d.ts +12 -7
  24. package/esm/main.d.ts.map +1 -1
  25. package/esm/main.js +10 -5
  26. package/esm/monitoringconfig.d.ts +2 -2
  27. package/esm/result.d.ts +11 -1
  28. package/esm/result.d.ts.map +1 -1
  29. package/esm/result.js +14 -5
  30. package/esm/scrapeconfig.d.ts +65 -1
  31. package/esm/scrapeconfig.d.ts.map +1 -1
  32. package/esm/scrapeconfig.js +88 -4
  33. package/esm/screenshotconfig.d.ts +9 -1
  34. package/esm/screenshotconfig.d.ts.map +1 -1
  35. package/esm/screenshotconfig.js +12 -1
  36. package/esm/types.d.ts +128 -0
  37. package/esm/types.d.ts.map +1 -1
  38. package/esm/types.js +22 -1
  39. package/esm/utils.d.ts.map +1 -1
  40. package/esm/utils.js +16 -2
  41. package/esm/webhookserver.d.ts +33 -15
  42. package/esm/webhookserver.d.ts.map +1 -1
  43. package/esm/webhookserver.js +197 -38
  44. package/package.json +1 -1
  45. package/script/browserconfig.d.ts +57 -9
  46. package/script/browserconfig.d.ts.map +1 -1
  47. package/script/browserconfig.js +63 -5
  48. package/script/browserdownloads.d.ts +70 -0
  49. package/script/browserdownloads.d.ts.map +1 -0
  50. package/script/browserdownloads.js +221 -0
  51. package/script/client.d.ts +224 -8
  52. package/script/client.d.ts.map +1 -1
  53. package/script/client.js +645 -61
  54. package/script/crawl.d.ts +83 -1
  55. package/script/crawl.d.ts.map +1 -1
  56. package/script/crawl.js +73 -0
  57. package/script/crawlerconfig.d.ts +54 -3
  58. package/script/crawlerconfig.d.ts.map +1 -1
  59. package/script/crawlerconfig.js +97 -3
  60. package/script/crawlerresult.d.ts +374 -2
  61. package/script/crawlerresult.d.ts.map +1 -1
  62. package/script/crawlerresult.js +374 -2
  63. package/script/errors.d.ts +12 -0
  64. package/script/errors.d.ts.map +1 -1
  65. package/script/errors.js +12 -1
  66. package/script/main.d.ts +12 -7
  67. package/script/main.d.ts.map +1 -1
  68. package/script/main.js +20 -4
  69. package/script/monitoringconfig.d.ts +2 -2
  70. package/script/result.d.ts +11 -1
  71. package/script/result.d.ts.map +1 -1
  72. package/script/result.js +14 -5
  73. package/script/scrapeconfig.d.ts +65 -1
  74. package/script/scrapeconfig.d.ts.map +1 -1
  75. package/script/scrapeconfig.js +88 -4
  76. package/script/screenshotconfig.d.ts +9 -1
  77. package/script/screenshotconfig.d.ts.map +1 -1
  78. package/script/screenshotconfig.js +12 -1
  79. package/script/types.d.ts +128 -0
  80. package/script/types.d.ts.map +1 -1
  81. package/script/types.js +23 -0
  82. package/script/utils.d.ts.map +1 -1
  83. package/script/utils.js +16 -2
  84. package/script/webhookserver.d.ts +33 -15
  85. package/script/webhookserver.d.ts.map +1 -1
  86. package/script/webhookserver.js +197 -38
  87. package/src/browserconfig.ts +74 -8
  88. package/src/browserdownloads.ts +266 -0
  89. package/src/client.ts +796 -65
  90. package/src/crawl.ts +106 -0
  91. package/src/crawlerconfig.ts +128 -5
  92. package/src/crawlerresult.ts +607 -3
  93. package/src/errors.ts +12 -0
  94. package/src/main.ts +55 -5
  95. package/src/monitoringconfig.ts +2 -2
  96. package/src/result.ts +17 -5
  97. package/src/scrapeconfig.ts +92 -3
  98. package/src/screenshotconfig.ts +14 -1
  99. package/src/types.ts +159 -1
  100. package/src/utils.ts +16 -2
  101. package/src/webhookserver.ts +235 -39
package/script/client.js CHANGED
@@ -31,9 +31,21 @@ const errors = __importStar(require("./errors.js"));
31
31
  const browserconfig_js_1 = require("./browserconfig.js");
32
32
  const result_js_1 = require("./result.js");
33
33
  const logger_js_1 = require("./logger.js");
34
+ const crawlerconfig_js_1 = require("./crawlerconfig.js");
34
35
  const crawlerresult_js_1 = require("./crawlerresult.js");
35
36
  const monitoringconfig_js_1 = require("./monitoringconfig.js");
36
37
  const schedule_js_1 = require("./schedule.js");
38
+ /** ERR::<RESOURCE>::* → error-class taxonomy. */
39
+ const RESOURCE_TO_ERROR = {
40
+ SCRAPE: errors.ScrapflyScrapeError,
41
+ WEBHOOK: errors.ScrapflyWebhookError,
42
+ PROXY: errors.ScrapflyProxyError,
43
+ SCHEDULE: errors.ScrapflyScheduleError,
44
+ ASP: errors.ScrapflyAspError,
45
+ SESSION: errors.ScrapflySessionError,
46
+ THROTTLE: errors.ScrapflyThrottleError,
47
+ CRAWLER: errors.ScrapflyCrawlerError,
48
+ };
37
49
  /**
38
50
  * Main entry point for the Scrapfly SDK.
39
51
  *
@@ -148,21 +160,9 @@ class ScrapflyClient {
148
160
  case 429:
149
161
  return new errors.TooManyRequests(message, args);
150
162
  }
151
- switch (args.resource) {
152
- case 'SCRAPE':
153
- return new errors.ScrapflyScrapeError(message, args);
154
- case 'WEBHOOK':
155
- return new errors.ScrapflyWebhookError(message, args);
156
- case 'PROXY':
157
- return new errors.ScrapflyProxyError(message, args);
158
- case 'SCHEDULE':
159
- return new errors.ScrapflyScheduleError(message, args);
160
- case 'ASP':
161
- return new errors.ScrapflyAspError(message, args);
162
- case 'SESSION':
163
- return new errors.ScrapflySessionError(message, args);
164
- case 'CRAWLER':
165
- return new errors.ScrapflyCrawlerError(message, args);
163
+ const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
164
+ if (ResourceError) {
165
+ return new ResourceError(message, args);
166
166
  }
167
167
  if (args.resource) {
168
168
  return new errors.ApiHttpClientError(message, args);
@@ -177,25 +177,48 @@ class ScrapflyClient {
177
177
  return new errors.UpstreamHttpServerError(message, args);
178
178
  }
179
179
  }
180
- switch (args.resource) {
181
- case 'SCRAPE':
182
- return new errors.ScrapflyScrapeError(message, args);
183
- case 'WEBHOOK':
184
- return new errors.ScrapflyWebhookError(message, args);
185
- case 'PROXY':
186
- return new errors.ScrapflyProxyError(message, args);
187
- case 'SCHEDULE':
188
- return new errors.ScrapflyScheduleError(message, args);
189
- case 'ASP':
190
- return new errors.ScrapflyAspError(message, args);
191
- case 'SESSION':
192
- return new errors.ScrapflySessionError(message, args);
193
- case 'CRAWLER':
194
- return new errors.ScrapflyCrawlerError(message, args);
180
+ const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
181
+ if (ResourceError) {
182
+ return new ResourceError(message, args);
195
183
  }
196
184
  }
197
185
  return new errors.ScrapflyError(message, args);
198
186
  }
187
+ /** Build the typed per-part error for an API-generated batch error body. */
188
+ batchApiErrorPartToError(parsed, partHeaders) {
189
+ const code = typeof parsed.code === 'string' ? parsed.code : '';
190
+ const message = String(parsed.message ?? parsed.reason ?? 'API error');
191
+ const httpStatusCode = typeof parsed.http_code === 'number'
192
+ ? parsed.http_code
193
+ : parseInt(partHeaders['x-scrapfly-scrape-status'] ?? '500', 10) || 500;
194
+ const isRetryable = parsed.retryable === true;
195
+ let documentationUrl;
196
+ if (parsed.links && typeof parsed.links === 'object' && !Array.isArray(parsed.links)) {
197
+ const values = Object.values(parsed.links);
198
+ if (values.length)
199
+ documentationUrl = values[0];
200
+ }
201
+ const args = {
202
+ code,
203
+ http_status_code: httpStatusCode,
204
+ is_retryable: isRetryable,
205
+ resource: code ? code.split('::')[1] : null,
206
+ documentation_url: documentationUrl,
207
+ };
208
+ const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
209
+ if (ResourceError) {
210
+ return new ResourceError(message, args);
211
+ }
212
+ switch (httpStatusCode) {
213
+ case 401:
214
+ return new errors.BadApiKeyError(message, args);
215
+ case 429:
216
+ return new errors.TooManyRequests(message, args);
217
+ }
218
+ return httpStatusCode >= 500
219
+ ? new errors.ApiHttpServerError(message, args)
220
+ : new errors.ApiHttpClientError(message, args);
221
+ }
199
222
  /**
200
223
  * Handle clob and blob large objects
201
224
  */
@@ -203,8 +226,7 @@ class ScrapflyClient {
203
226
  let response;
204
227
  try {
205
228
  const url = new URL(result.content);
206
- const params = { key: this.key };
207
- url.search = new URLSearchParams(params).toString();
229
+ url.searchParams.set('key', this.key);
208
230
  response = await this.fetch({
209
231
  url: url.toString(),
210
232
  method: 'GET',
@@ -219,6 +241,20 @@ class ScrapflyClient {
219
241
  logger_js_1.log.error('error', e);
220
242
  throw e;
221
243
  }
244
+ if (!response.ok) {
245
+ const body = await response.text();
246
+ let parsed = null;
247
+ try {
248
+ parsed = JSON.parse(body);
249
+ }
250
+ catch {
251
+ // Not an API error: a proxy's page, say.
252
+ }
253
+ const envelope = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
254
+ ? parsed
255
+ : { message: body.slice(0, 500) || response.statusText };
256
+ throw this.batchApiErrorPartToError(envelope, { 'x-scrapfly-scrape-status': String(response.status) });
257
+ }
222
258
  let content;
223
259
  if (format === 'clob') {
224
260
  content = await response.text();
@@ -237,7 +273,8 @@ class ScrapflyClient {
237
273
  handleResponse(response, result) {
238
274
  // success
239
275
  logger_js_1.log.debug('scrape log url: ', result.result.log_url);
240
- if (result.result.status === 'DONE' && result.result.success === true) {
276
+ // QUEUED: a scrape with a webhook, delivered to it later.
277
+ if (result.result.status === 'QUEUED' || (result.result.status === 'DONE' && result.result.success === true)) {
241
278
  return result;
242
279
  }
243
280
  // something went wrong
@@ -657,6 +694,12 @@ class ScrapflyClient {
657
694
  // Drop `key` (batch key is in the URL).
658
695
  const params = cfg.toApiParams({ key: this.key });
659
696
  delete params.key;
697
+ // What a single scrape sends as the request itself: the API reads
698
+ // both keys of a batch entry and runs a GET without them.
699
+ params.method = cfg.method;
700
+ if (cfg.body !== undefined) {
701
+ params.body = cfg.body;
702
+ }
660
703
  bodyConfigs.push(params);
661
704
  }
662
705
  const url = new URL(this.HOST + '/scrape/batch');
@@ -716,12 +759,26 @@ class ScrapflyClient {
716
759
  ];
717
760
  continue;
718
761
  }
762
+ // API-generated error parts carry status >= 400 and an error body
763
+ // instead of the scrape envelope — surface them as typed errors.
764
+ const partStatus = parseInt(part.headers['x-scrapfly-scrape-status'] ?? '0', 10) || 0;
765
+ if (partStatus >= 400 &&
766
+ parsed &&
767
+ typeof parsed === 'object' &&
768
+ !Array.isArray(parsed) &&
769
+ !('result' in parsed) &&
770
+ !('config' in parsed)) {
771
+ yield [correlationId, this.batchApiErrorPartToError(parsed, part.headers)];
772
+ continue;
773
+ }
719
774
  try {
775
+ // A config with a webhook is answered by its enqueue ack, the scrape's answer under `result`.
776
+ const envelope = parsed.enqueued === true && parsed.result ? parsed.result : parsed;
720
777
  const result = new result_js_1.ScrapeResult({
721
- config: parsed.config,
722
- context: parsed.context,
723
- result: parsed.result,
724
- uuid: parsed.uuid,
778
+ config: envelope.config,
779
+ context: envelope.context,
780
+ result: envelope.result,
781
+ uuid: envelope.uuid,
725
782
  });
726
783
  yield [correlationId, result];
727
784
  }
@@ -739,7 +796,7 @@ class ScrapflyClient {
739
796
  * Save screenshot response to a file
740
797
  */
741
798
  async saveScreenshot(result, name, savePath) {
742
- if (!result.image) {
799
+ if (!result.image || result.image.byteLength === 0) {
743
800
  throw new Error('Screenshot binary does not exist');
744
801
  }
745
802
  const extension_name = result.metadata.extension_name;
@@ -759,23 +816,39 @@ class ScrapflyClient {
759
816
  * Turn scrapfly screenshot API response to ScreenshotResult or raise one of ScrapflyError
760
817
  */
761
818
  async handleScreenshotResponse(response) {
762
- // A Response body can only be consumed once. If the server returned
763
- // JSON, parse it up front and reuse it on the error path — re-reading
764
- // would yield "body stream already read" and mask the real error.
765
- const isJson = response.headers.get('content-type') === 'application/json';
766
- let jsonData = null;
767
- if (isJson) {
768
- jsonData = (await response.json());
769
- if (jsonData.http_code == 401 || response.status == 401) {
770
- throw new errors.BadApiKeyError(JSON.stringify(jsonData));
819
+ // A JSON answer is never an image: an error, or the 201 of a screenshot with a webhook.
820
+ // A Response body can only be consumed once, so it is read as text and parsed from that.
821
+ const isJson = (response.headers.get('content-type') ?? '').startsWith('application/json');
822
+ if (isJson || response.status === 201) {
823
+ const text = await response.text();
824
+ let jsonData = null;
825
+ try {
826
+ const parsed = JSON.parse(text);
827
+ if (parsed !== null && typeof parsed === 'object') {
828
+ jsonData = parsed;
829
+ }
771
830
  }
772
- if ('error_id' in jsonData) {
773
- throw new errors.ScreenshotApiError(JSON.stringify(jsonData));
831
+ catch {
832
+ jsonData = null;
833
+ }
834
+ const message = jsonData ? JSON.stringify(jsonData) : text || `API returned status ${response.status}`;
835
+ if (response.status == 401 || jsonData?.http_code == 401) {
836
+ throw new errors.BadApiKeyError(message);
774
837
  }
838
+ if (jsonData) {
839
+ if ('error_id' in jsonData) {
840
+ throw new errors.ScreenshotApiError(JSON.stringify(jsonData));
841
+ }
842
+ // 201: a screenshot with a webhook, delivered to it later.
843
+ const job = jsonData.job_uuid;
844
+ if (response.status === 201 && jsonData.webhook_enqueued === true && typeof job === 'string' && job !== '') {
845
+ return new result_js_1.ScreenshotResult(response, new ArrayBuffer(0), job);
846
+ }
847
+ }
848
+ throw new errors.ScreenshotApiError(message);
775
849
  }
776
850
  if (!response.ok) {
777
- const body = jsonData ?? (await response.text());
778
- throw new errors.ScreenshotApiError(typeof body === 'string' ? body : JSON.stringify(body));
851
+ throw new errors.ScreenshotApiError((await response.text()) || `API returned status ${response.status}`);
779
852
  }
780
853
  const data = await response.arrayBuffer();
781
854
  const result = new result_js_1.ScreenshotResult(response, data);
@@ -877,7 +950,8 @@ class ScrapflyClient {
877
950
  throwCrawlerError(response, data) {
878
951
  const httpCode = data.http_code ?? response.status;
879
952
  const code = (data.code ?? '');
880
- const message = data.message ?? JSON.stringify(data);
953
+ // The engine relays its own failures as `{error, code}`.
954
+ const message = data.message ?? (typeof data.error === 'string' ? data.error : JSON.stringify(data));
881
955
  if (httpCode === 401) {
882
956
  throw new errors.BadApiKeyError(message, { http_status_code: httpCode, code, api_response: data });
883
957
  }
@@ -916,7 +990,7 @@ class ScrapflyClient {
916
990
  if (urlList !== undefined) {
917
991
  // Strip url_list from the JSON config — the URLs go through the
918
992
  // 'urls' multipart part instead, which the API gateway streams
919
- // straight through to the scrape engine.
993
+ // straight through to the scraping backend.
920
994
  delete params.url_list;
921
995
  const form = new FormData();
922
996
  const configBlob = new Blob([JSON.stringify(params)], { type: 'application/json' });
@@ -1283,6 +1357,319 @@ class ScrapflyClient {
1283
1357
  }
1284
1358
  return response.ok;
1285
1359
  }
1360
+ /**
1361
+ * Run one refresh of an existing crawl immediately, without waiting for the
1362
+ * next scheduled period.
1363
+ *
1364
+ * `POST /crawl/{uuid}/refresh` re-scrapes the crawl's own URLs in place:
1365
+ * same `crawler_uuid`, same artifacts, same search index. Only pages whose
1366
+ * content actually changed are re-indexed and pages that disappeared are
1367
+ * dropped, so everything already pointing at this crawl keeps working.
1368
+ *
1369
+ * A refresh bills the pages it re-scrapes, exactly like the original crawl.
1370
+ * What unchanged pages save is the embedding and the index write.
1371
+ *
1372
+ * The call returns as soon as the run is accepted; poll `crawlStatus` or
1373
+ * `crawlRefreshHistory` for the outcome. Do not retry it blindly: a retry
1374
+ * starts a second re-scrape of the whole site.
1375
+ */
1376
+ async crawlRefreshNow(uuid) {
1377
+ if (!uuid) {
1378
+ throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
1379
+ }
1380
+ let response;
1381
+ try {
1382
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh`);
1383
+ url.search = new URLSearchParams({ key: this.key }).toString();
1384
+ // One attempt: the server may have accepted the billable refresh even
1385
+ // when its response is lost or replaced by a gateway error.
1386
+ response = await this.fetch({
1387
+ url: url.toString(),
1388
+ method: 'POST',
1389
+ headers: {
1390
+ 'user-agent': this.ua,
1391
+ 'accept-encoding': 'gzip, deflate, br',
1392
+ accept: 'application/json',
1393
+ },
1394
+ }, 1);
1395
+ }
1396
+ catch (e) {
1397
+ logger_js_1.log.error('error', e);
1398
+ throw e;
1399
+ }
1400
+ const data = (await response.json());
1401
+ if ('error_id' in data || data.http_code !== undefined) {
1402
+ this.throwCrawlerError(response, data);
1403
+ }
1404
+ return (0, crawlerresult_js_1.parseCrawlerRefreshState)(data);
1405
+ }
1406
+ /**
1407
+ * Change the refresh schedule of an existing crawl.
1408
+ *
1409
+ * `PATCH /crawl/{uuid}/refresh` — only the fields passed are changed, so
1410
+ * turning a crawl off keeps its interval for when it is turned back on.
1411
+ *
1412
+ * Turning refresh on for a crawl started without it is allowed: the crawl
1413
+ * already holds the URL index a refresh walks.
1414
+ */
1415
+ async crawlRefreshSettings(uuid, settings) {
1416
+ if (!uuid) {
1417
+ throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
1418
+ }
1419
+ if (settings?.enabled === undefined && settings?.interval_seconds === undefined) {
1420
+ throw new errors.ScrapflyCrawlerError('pass at least one of enabled, interval_seconds');
1421
+ }
1422
+ if (settings.interval_seconds !== undefined &&
1423
+ (settings.interval_seconds < crawlerconfig_js_1.REFRESH_MIN_INTERVAL || settings.interval_seconds > crawlerconfig_js_1.REFRESH_MAX_INTERVAL)) {
1424
+ throw new errors.ScrapflyCrawlerError(`interval_seconds must be between ${crawlerconfig_js_1.REFRESH_MIN_INTERVAL} and ${crawlerconfig_js_1.REFRESH_MAX_INTERVAL} seconds`);
1425
+ }
1426
+ // Wire keys are the ones POST /crawl already takes, so a crawl body and a
1427
+ // later PATCH name the same things. The enabled/interval_seconds spelling
1428
+ // belongs to the state block this call answers with, not to its request;
1429
+ // the API decodes the body with unknown fields rejected.
1430
+ const payload = {};
1431
+ if (settings.enabled !== undefined)
1432
+ payload.refresh = settings.enabled;
1433
+ if (settings.interval_seconds !== undefined)
1434
+ payload.refresh_interval = settings.interval_seconds;
1435
+ let response;
1436
+ try {
1437
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh`);
1438
+ url.search = new URLSearchParams({ key: this.key }).toString();
1439
+ response = await this.fetch({
1440
+ url: url.toString(),
1441
+ method: 'PATCH',
1442
+ headers: {
1443
+ 'user-agent': this.ua,
1444
+ 'content-type': 'application/json',
1445
+ 'accept-encoding': 'gzip, deflate, br',
1446
+ accept: 'application/json',
1447
+ },
1448
+ body: JSON.stringify(payload),
1449
+ });
1450
+ }
1451
+ catch (e) {
1452
+ logger_js_1.log.error('error', e);
1453
+ throw e;
1454
+ }
1455
+ const data = (await response.json());
1456
+ if ('error_id' in data || data.http_code !== undefined) {
1457
+ this.throwCrawlerError(response, data);
1458
+ }
1459
+ return (0, crawlerresult_js_1.parseCrawlerRefreshState)(data);
1460
+ }
1461
+ /**
1462
+ * Read a crawl's refresh timeline, newest last.
1463
+ *
1464
+ * `GET /crawl/{uuid}/refresh/history` — the server keeps the 50 most recent
1465
+ * runs; older rows are trimmed rather than paged, because the timeline
1466
+ * exists to show recent activity.
1467
+ */
1468
+ async crawlRefreshHistory(uuid, opts) {
1469
+ if (!uuid) {
1470
+ throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
1471
+ }
1472
+ let response;
1473
+ try {
1474
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh/history`);
1475
+ const params = { key: this.key };
1476
+ if (opts?.limit !== undefined)
1477
+ params.limit = String(opts.limit);
1478
+ url.search = new URLSearchParams(params).toString();
1479
+ response = await this.fetch({
1480
+ url: url.toString(),
1481
+ method: 'GET',
1482
+ headers: {
1483
+ 'user-agent': this.ua,
1484
+ 'accept-encoding': 'gzip, deflate, br',
1485
+ accept: 'application/json',
1486
+ },
1487
+ });
1488
+ }
1489
+ catch (e) {
1490
+ logger_js_1.log.error('error', e);
1491
+ throw e;
1492
+ }
1493
+ const data = (await response.json());
1494
+ if ('error_id' in data || data.http_code !== undefined) {
1495
+ this.throwCrawlerError(response, data);
1496
+ }
1497
+ return (0, crawlerresult_js_1.parseCrawlerRefreshState)(data).history ?? [];
1498
+ }
1499
+ /**
1500
+ * Search across the search indexes of one or more crawls.
1501
+ *
1502
+ * `POST /crawl/search`: the collection endpoint is the real API and
1503
+ * {@link crawl.Crawl.search} is sugar over a one-element list so the two
1504
+ * cannot drift.
1505
+ *
1506
+ * Only crawls started with `search: true` whose index reached `READY` or
1507
+ * `PARTIAL` contribute. The rest come back in `skipped` with a reason and
1508
+ * never fail the call, so inspect `skipped` before concluding a crawl had
1509
+ * no match.
1510
+ */
1511
+ async crawlSearch(crawlIds, query, opts) {
1512
+ if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
1513
+ throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
1514
+ }
1515
+ if (!query) {
1516
+ throw new errors.ScrapflyCrawlerError('query must be a non-empty string');
1517
+ }
1518
+ const payload = { query, crawl_ids: crawlIds };
1519
+ if (opts?.limit !== undefined)
1520
+ payload.limit = opts.limit;
1521
+ if (opts?.mode !== undefined)
1522
+ payload.mode = opts.mode;
1523
+ if (opts?.filters !== undefined)
1524
+ payload.filters = opts.filters;
1525
+ if (opts?.cursor !== undefined)
1526
+ payload.cursor = opts.cursor;
1527
+ let response;
1528
+ try {
1529
+ const url = new URL(`${this.HOST}/crawl/search`);
1530
+ url.search = new URLSearchParams({ key: this.key }).toString();
1531
+ response = await this.fetch({
1532
+ url: url.toString(),
1533
+ method: 'POST',
1534
+ headers: {
1535
+ 'user-agent': this.ua,
1536
+ 'content-type': 'application/json',
1537
+ 'accept-encoding': 'gzip, deflate, br',
1538
+ accept: 'application/json',
1539
+ },
1540
+ body: JSON.stringify(payload),
1541
+ });
1542
+ }
1543
+ catch (e) {
1544
+ logger_js_1.log.error('error', e);
1545
+ throw e;
1546
+ }
1547
+ const data = (await response.json());
1548
+ if ('error_id' in data || data.http_code !== undefined) {
1549
+ this.throwCrawlerError(response, data);
1550
+ }
1551
+ return new crawlerresult_js_1.CrawlerSearchResponse(data);
1552
+ }
1553
+ /**
1554
+ * Ask a question answered from the content of one or more crawls, streaming
1555
+ * the answer as it is generated.
1556
+ *
1557
+ * `POST /crawl/prompt`: the collection endpoint is the real API and
1558
+ * {@link crawl.Crawl.prompt} is sugar over a one-element list.
1559
+ *
1560
+ * Yields `source` frames, then `token` frames, then one `done`. An
1561
+ * `event: error` frame is thrown as `ScrapflyCrawlerError` rather than
1562
+ * yielded, and can arrive after tokens were already yielded because
1563
+ * generation fails mid-stream.
1564
+ *
1565
+ * Consume with `for await`; abandoning the iterator early cancels the body.
1566
+ *
1567
+ * Do not consume this with `EventSource`: it reconnects on close and would
1568
+ * silently re-run the whole fan-out and generation.
1569
+ */
1570
+ async *crawlPrompt(crawlIds, prompt, opts) {
1571
+ if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
1572
+ throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
1573
+ }
1574
+ if (!prompt) {
1575
+ throw new errors.ScrapflyCrawlerError('prompt must be a non-empty string');
1576
+ }
1577
+ const generation = { stream: true };
1578
+ if (opts?.model !== undefined)
1579
+ generation.model = opts.model;
1580
+ const payload = { prompt, crawl_ids: crawlIds, generation };
1581
+ if (opts?.search !== undefined)
1582
+ payload.search = opts.search;
1583
+ const url = new URL(`${this.HOST}/crawl/prompt`);
1584
+ url.search = new URLSearchParams({ key: this.key }).toString();
1585
+ // One attempt only: the request runs a fan-out and a generation, both
1586
+ // billable, so a retry doubles the bill.
1587
+ const response = await this.fetch({
1588
+ url: url.toString(),
1589
+ method: 'POST',
1590
+ headers: {
1591
+ 'user-agent': this.ua,
1592
+ 'content-type': 'application/json',
1593
+ accept: 'text/event-stream',
1594
+ },
1595
+ body: JSON.stringify(payload),
1596
+ }, 1);
1597
+ if (!response.ok) {
1598
+ const data = (await response.json().catch(() => ({})));
1599
+ this.throwCrawlerError(response, data);
1600
+ }
1601
+ if (response.body === null) {
1602
+ throw new errors.ScrapflyCrawlerError('prompt response carried no body');
1603
+ }
1604
+ yield* (0, crawlerresult_js_1.parseCrawlerPromptStream)(response.body);
1605
+ }
1606
+ /**
1607
+ * Ask a question answered from the content of one or more crawls, and get
1608
+ * the whole answer in one object once generation completes.
1609
+ *
1610
+ * `POST /crawl/prompt` with `generation.stream: false`: the same facts as
1611
+ * the frames of {@link crawlPrompt}. {@link crawl.Crawl.promptAnswer} is
1612
+ * sugar over a one-element list.
1613
+ */
1614
+ async crawlPromptAnswer(crawlIds, prompt, opts) {
1615
+ if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
1616
+ throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
1617
+ }
1618
+ if (!prompt) {
1619
+ throw new errors.ScrapflyCrawlerError('prompt must be a non-empty string');
1620
+ }
1621
+ const generation = { stream: false };
1622
+ if (opts?.model !== undefined)
1623
+ generation.model = opts.model;
1624
+ const payload = { prompt, crawl_ids: crawlIds, generation };
1625
+ if (opts?.search !== undefined)
1626
+ payload.search = opts.search;
1627
+ return (await this.postCrawlerJson('/crawl/prompt', payload));
1628
+ }
1629
+ /**
1630
+ * Extract a structured object from the content of one or more crawls.
1631
+ *
1632
+ * `POST /crawl/extract` retrieves like {@link crawlPromptAnswer} and answers
1633
+ * with `data` shaped by `schema`, a JSON Schema handed to the model as its
1634
+ * response schema. There is no streaming variant. {@link crawl.Crawl.extract}
1635
+ * is sugar over a one-element list.
1636
+ */
1637
+ async crawlExtract(crawlIds, prompt, schema, opts) {
1638
+ if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
1639
+ throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
1640
+ }
1641
+ if (!prompt) {
1642
+ throw new errors.ScrapflyCrawlerError('prompt must be a non-empty string');
1643
+ }
1644
+ if (typeof schema !== 'object' || schema === null || Array.isArray(schema) || Object.keys(schema).length === 0) {
1645
+ throw new errors.ScrapflyCrawlerError('schema must be a non-empty JSON Schema object');
1646
+ }
1647
+ const payload = { prompt, crawl_ids: crawlIds, schema };
1648
+ if (opts?.search !== undefined)
1649
+ payload.search = opts.search;
1650
+ return (await this.postCrawlerJson('/crawl/extract', payload));
1651
+ }
1652
+ /** POST a JSON body to a crawler endpoint that generates, once, and return its JSON answer. */
1653
+ async postCrawlerJson(path, payload) {
1654
+ const url = new URL(`${this.HOST}${path}`);
1655
+ url.search = new URLSearchParams({ key: this.key }).toString();
1656
+ // One attempt only: a retry re-runs the fan-out and the generation.
1657
+ const response = await this.fetch({
1658
+ url: url.toString(),
1659
+ method: 'POST',
1660
+ headers: {
1661
+ 'user-agent': this.ua,
1662
+ 'content-type': 'application/json',
1663
+ accept: 'application/json',
1664
+ },
1665
+ body: JSON.stringify(payload),
1666
+ }, 1);
1667
+ if (!response.ok) {
1668
+ const data = (await response.json().catch(() => ({})));
1669
+ this.throwCrawlerError(response, data);
1670
+ }
1671
+ return (await response.json());
1672
+ }
1286
1673
  // --- Cloud Browser ---
1287
1674
  /**
1288
1675
  * Get the WebSocket URL for a Cloud Browser session.
@@ -1297,18 +1684,29 @@ class ScrapflyClient {
1297
1684
  }
1298
1685
  /**
1299
1686
  * Return the deterministic project salt for this client's api_key. Matches
1300
- * the `X-Browser-Project-Salt` response header returned on a successful
1301
- * Cloud Browser WebSocket upgrade.
1687
+ * the `X-Browser-Project-Salt` response header returned on VNC-enabled
1688
+ * Cloud Browser upgrades, where the salt is also the VNC password prefix.
1302
1689
  */
1303
1690
  async cloudBrowserProjectSalt() {
1304
1691
  return browserconfig_js_1.BrowserConfig.projectSalt(this.key);
1305
1692
  }
1693
+ /**
1694
+ * Return the password a native VNC client must type to attach to a session
1695
+ * created with `config`: `<projectSalt>-<vnc_password>`.
1696
+ *
1697
+ * Copy this value into your VNC client when connecting to the TCP endpoint
1698
+ * (port 5901). The WebSocket endpoint `/run/<run_id>/vnc` takes the raw
1699
+ * `vnc_password` instead.
1700
+ */
1701
+ async cloudBrowserVncPassword(config) {
1702
+ return config.vncClientPassword(this.key);
1703
+ }
1306
1704
  /**
1307
1705
  * Call the Cloud Browser Unblock API.
1308
1706
  *
1309
1707
  * Unblock always uses a residential proxy (no proxy pool selection) and
1310
1708
  * always performs a GET — the endpoint's purpose is to harvest cookies /
1311
- * clearance tokens via an ASP-bypass navigation, not to proxy arbitrary
1709
+ * clearance tokens via an Unblocker navigation, not to proxy arbitrary
1312
1710
  * HTTP requests.
1313
1711
  */
1314
1712
  async cloudBrowserUnblock(options) {
@@ -1461,12 +1859,12 @@ class ScrapflyClient {
1461
1859
  return await response.json();
1462
1860
  }
1463
1861
  // ----- Cloud Browser Credential Vault -------------------------------------
1464
- // Server contract documented at apps/scrapfly/api/scrapfly-api/pkg/vault/.
1862
+ // Server contract documented in the Vault API reference.
1465
1863
  //
1466
1864
  // SECURITY: the vault key is the customer-held secret that decrypts every
1467
1865
  // item in the vault. The server emits it ONCE on POST /vault and POST
1468
1866
  // /vault/{id}/rotate; never log it, never include it in error messages,
1469
- // never put it in a breadcrumb. See agent_secret_tokenization_boundary.md.
1867
+ // never put it in a breadcrumb, and never echo it back to a caller.
1470
1868
  /**
1471
1869
  * Create a new Cloud Browser Credential Vault. The response contains a
1472
1870
  * one-time `key` that the caller MUST save locally — the server cannot
@@ -1705,6 +2103,183 @@ class ScrapflyClient {
1705
2103
  message: typeof body.message === 'string' ? body.message : '',
1706
2104
  };
1707
2105
  }
2106
+ // ----- Vault ↔ linked secret manager (1Password) ---------------------------
2107
+ // A linked vault mirrors an upstream secret manager instead of holding
2108
+ // operator-entered items. The provider's service-account token is sealed
2109
+ // under the vault key like any other secret, so every endpoint that carries
2110
+ // a token also carries X-Vault-Key: the server verifies the key BEFORE
2111
+ // sealing, because a well-formed wrong key would link the vault and leave a
2112
+ // token every later sync fails to open.
2113
+ /**
2114
+ * Link a vault to a secret manager. The token is sealed under `vaultKey`, so
2115
+ * the key is mandatory here. The vault must not already be linked and must
2116
+ * hold no rows owned by a previous service (the server answers 409).
2117
+ */
2118
+ async cloudBrowserVaultServiceLink(vaultId, vaultKey, link) {
2119
+ if (!link.token) {
2120
+ throw new Error('cloudBrowserVaultServiceLink: token is required when linking a service');
2121
+ }
2122
+ // Same rule as the server's linked_service_data validation; caught here so a
2123
+ // malformed link does not cost a round trip.
2124
+ if (!link.linked_service_data?.vault_id && !link.linked_service_data?.vault_name) {
2125
+ throw new Error('cloudBrowserVaultServiceLink: linked_service_data requires vault_id or vault_name');
2126
+ }
2127
+ const url = new URL(this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service');
2128
+ url.searchParams.set('key', this.key);
2129
+ const response = await this.fetch({
2130
+ url: url.toString(),
2131
+ method: 'POST',
2132
+ headers: {
2133
+ 'content-type': 'application/json',
2134
+ 'user-agent': this.ua,
2135
+ 'X-Vault-Key': vaultKey,
2136
+ },
2137
+ body: JSON.stringify({
2138
+ linked_service: link.linked_service,
2139
+ token: link.token,
2140
+ linked_service_data: link.linked_service_data,
2141
+ }),
2142
+ });
2143
+ if (!response.ok) {
2144
+ throw new Error(`Vault service link failed: ${response.status} ${await response.text()}`);
2145
+ }
2146
+ return await response.json();
2147
+ }
2148
+ /**
2149
+ * Update a link: edit the non-secret selection rules, rotate the token, or
2150
+ * both. `vaultKey` is required only when `token` is supplied, mirroring
2151
+ * `cloudBrowserVaultItemUpdate`; a config-only edit needs no key.
2152
+ *
2153
+ * A token rotation also clears the server's one-hour auth back-off, so a link
2154
+ * broken by a dead token syncs again on the next round.
2155
+ */
2156
+ async cloudBrowserVaultServiceUpdate(vaultId, opts) {
2157
+ if (opts.token !== undefined && opts.token !== '' && (opts.vaultKey === undefined || opts.vaultKey === '')) {
2158
+ throw new Error('cloudBrowserVaultServiceUpdate: vaultKey is required when rotating the service token');
2159
+ }
2160
+ const url = new URL(this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service');
2161
+ url.searchParams.set('key', this.key);
2162
+ const body = {};
2163
+ if (opts.token !== undefined)
2164
+ body.token = opts.token;
2165
+ if (opts.linked_service_data !== undefined)
2166
+ body.linked_service_data = opts.linked_service_data;
2167
+ const headers = {
2168
+ 'content-type': 'application/json',
2169
+ 'user-agent': this.ua,
2170
+ };
2171
+ if (opts.vaultKey !== undefined && opts.vaultKey !== '') {
2172
+ headers['X-Vault-Key'] = opts.vaultKey;
2173
+ }
2174
+ const response = await this.fetch({
2175
+ url: url.toString(),
2176
+ method: 'PATCH',
2177
+ headers,
2178
+ body: JSON.stringify(body),
2179
+ });
2180
+ if (!response.ok) {
2181
+ throw new Error(`Vault service update failed: ${response.status} ${await response.text()}`);
2182
+ }
2183
+ return await response.json();
2184
+ }
2185
+ /**
2186
+ * Unlink the provider. `keepItems` governs only the mirrored rows — kept as
2187
+ * plain manual items, or deleted — while the sealed token is removed either
2188
+ * way, so no vault key is needed.
2189
+ *
2190
+ * Dropping the rows is irreversible, so the default is to keep them and the
2191
+ * flag always goes on the wire explicitly rather than relying on a default at
2192
+ * either end.
2193
+ */
2194
+ async cloudBrowserVaultServiceUnlink(vaultId, opts = {}) {
2195
+ const url = new URL(this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service');
2196
+ url.searchParams.set('key', this.key);
2197
+ url.searchParams.set('keep_items', (opts.keepItems ?? true) ? 'true' : 'false');
2198
+ const response = await this.fetch({
2199
+ url: url.toString(),
2200
+ method: 'DELETE',
2201
+ headers: { 'user-agent': this.ua },
2202
+ });
2203
+ if (!response.ok) {
2204
+ throw new Error(`Vault service unlink failed: ${response.status} ${await response.text()}`);
2205
+ }
2206
+ const body = await response.json();
2207
+ return {
2208
+ success: body.success !== undefined ? Boolean(body.success) : true,
2209
+ message: typeof body.message === 'string' ? body.message : '',
2210
+ };
2211
+ }
2212
+ /**
2213
+ * Force a reconcile against the provider now, bypassing the sync TTL and the
2214
+ * back-off a failed round leaves behind. Requires the vault key: the server
2215
+ * opens the sealed token with it and re-seals every mirrored row.
2216
+ *
2217
+ * The server budget is 25s; the SDK pins no per-call timeout, so the runtime's
2218
+ * own fetch default applies.
2219
+ */
2220
+ async cloudBrowserVaultServiceSync(vaultId, vaultKey) {
2221
+ const url = new URL(this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service/sync');
2222
+ url.searchParams.set('key', this.key);
2223
+ const response = await this.fetch({
2224
+ url: url.toString(),
2225
+ method: 'POST',
2226
+ headers: {
2227
+ 'user-agent': this.ua,
2228
+ 'X-Vault-Key': vaultKey,
2229
+ },
2230
+ });
2231
+ if (!response.ok) {
2232
+ throw new Error(`Vault service sync failed: ${response.status} ${await response.text()}`);
2233
+ }
2234
+ return await response.json();
2235
+ }
2236
+ /**
2237
+ * Probe the provider: proves a token is live and lists the upstream vaults it
2238
+ * can read. Writes nothing, so it never moves the vault's sync state.
2239
+ *
2240
+ * With no `token` the sealed token of an existing link is probed (the vault
2241
+ * key opens it). Passing an unsaved `token` instead enumerates the upstream
2242
+ * vaults BEFORE a link exists, which is how a caller picks `vault_id`.
2243
+ *
2244
+ * `linkedService` stays optional and undefaulted here: this is the one endpoint
2245
+ * whose empty discriminator the server itself resolves to 1Password, and a
2246
+ * client-side default would send a field the bodyless stored-token path must
2247
+ * not carry.
2248
+ *
2249
+ * The server budget is 10s; the SDK pins no per-call timeout, so the runtime's
2250
+ * own fetch default applies.
2251
+ */
2252
+ async cloudBrowserVaultServiceTest(vaultId, vaultKey, opts = {}) {
2253
+ const url = new URL(this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service/test');
2254
+ url.searchParams.set('key', this.key);
2255
+ const headers = {
2256
+ 'user-agent': this.ua,
2257
+ 'X-Vault-Key': vaultKey,
2258
+ };
2259
+ // A bodyless request is what selects the stored-token path server-side, so
2260
+ // send a body only when the caller supplied something to probe with.
2261
+ let body;
2262
+ if (opts.token !== undefined || opts.linkedService !== undefined) {
2263
+ const payload = {};
2264
+ if (opts.linkedService !== undefined)
2265
+ payload.linked_service = opts.linkedService;
2266
+ if (opts.token !== undefined)
2267
+ payload.token = opts.token;
2268
+ body = JSON.stringify(payload);
2269
+ headers['content-type'] = 'application/json';
2270
+ }
2271
+ const response = await this.fetch({
2272
+ url: url.toString(),
2273
+ method: 'POST',
2274
+ headers,
2275
+ body,
2276
+ });
2277
+ if (!response.ok) {
2278
+ throw new Error(`Vault service test failed: ${response.status} ${await response.text()}`);
2279
+ }
2280
+ const json = await response.json();
2281
+ return { ...json, vaults_visible: json.vaults_visible ?? [] };
2282
+ }
1708
2283
  /**
1709
2284
  * Download a debug session recording video.
1710
2285
  * Returns the video as an ArrayBuffer (stream from server).
@@ -1785,7 +2360,12 @@ class ScrapflyClient {
1785
2360
  // pause/resume/execute methods work regardless of kind.
1786
2361
  // -------------------------------------------------------------------------
1787
2362
  /** Create a Web Scraping API schedule. `scrape_config` is the same shape
1788
- * accepted by `/scrape` (e.g. `{ url, render_js, asp, ... }`). */
2363
+ * accepted by `/scrape` (e.g. `{ url, render_js, asp, ... }`). This dict is
2364
+ * forwarded to the API verbatim, so its keys are wire keys, not the SDK
2365
+ * option names. The anti-bot bypass may be spelled either way here: the API
2366
+ * folds `unblocker` into `asp` on the STORED config, with the same precedence
2367
+ * the SDK uses (a supplied `asp` wins; `unblocker` is read only when `asp` is
2368
+ * absent, `null` or `""`), so both names reach the replayed scrape. */
1789
2369
  async createScrapeSchedule(scrapeConfig, request) {
1790
2370
  return await this.scheduleRequest('POST', '/scrape/schedules', undefined, this.buildCreateBody('scrape_config', scrapeConfig, request));
1791
2371
  }
@@ -1793,7 +2373,11 @@ class ScrapflyClient {
1793
2373
  async createScreenshotSchedule(screenshotConfig, request) {
1794
2374
  return await this.scheduleRequest('POST', '/screenshot/schedules', undefined, this.buildCreateBody('screenshot_config', screenshotConfig, request));
1795
2375
  }
1796
- /** Create a Crawler API schedule. */
2376
+ /** Create a Crawler API schedule. `crawler_config` is forwarded verbatim and
2377
+ * its keys are wire keys, not the SDK option names. As with
2378
+ * `createScrapeSchedule`, the anti-bot bypass may be spelled `asp` or
2379
+ * `unblocker`: the API folds the alias into `asp` on the stored config before
2380
+ * it is ever replayed. */
1797
2381
  async createCrawlerSchedule(crawlerConfig, request) {
1798
2382
  return await this.scheduleRequest('POST', '/crawl/schedules', undefined, this.buildCreateBody('crawler_config', crawlerConfig, request));
1799
2383
  }
@@ -1801,7 +2385,7 @@ class ScrapflyClient {
1801
2385
  async getSchedule(id) {
1802
2386
  return await this.scheduleRequest('GET', `/schedules/${encodeURIComponent(id)}`);
1803
2387
  }
1804
- /** List every schedule on the account, optionally filtered by kind/status. */
2388
+ /** List the schedules of the API key's project and environment, optionally filtered by kind/status. */
1805
2389
  async listSchedules(opts) {
1806
2390
  return await this.scheduleRequest('GET', '/schedules', opts);
1807
2391
  }