scrapfly-sdk 0.7.2 → 0.9.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 (75) hide show
  1. package/esm/browserconfig.d.ts +59 -0
  2. package/esm/browserconfig.d.ts.map +1 -0
  3. package/esm/browserconfig.js +207 -0
  4. package/esm/client.d.ts +193 -1
  5. package/esm/client.d.ts.map +1 -1
  6. package/esm/client.js +786 -5
  7. package/esm/crawl.d.ts +118 -0
  8. package/esm/crawl.d.ts.map +1 -0
  9. package/esm/crawl.js +230 -0
  10. package/esm/crawlerconfig.d.ts +119 -0
  11. package/esm/crawlerconfig.d.ts.map +1 -0
  12. package/esm/crawlerconfig.js +398 -0
  13. package/esm/crawlerresult.d.ts +253 -0
  14. package/esm/crawlerresult.d.ts.map +1 -0
  15. package/esm/crawlerresult.js +327 -0
  16. package/esm/errors.d.ts +4 -0
  17. package/esm/errors.d.ts.map +1 -1
  18. package/esm/errors.js +6 -0
  19. package/esm/extractionconfig.d.ts +2 -0
  20. package/esm/extractionconfig.d.ts.map +1 -1
  21. package/esm/extractionconfig.js +10 -0
  22. package/esm/main.d.ts +8 -1
  23. package/esm/main.d.ts.map +1 -1
  24. package/esm/main.js +6 -1
  25. package/esm/polyfill.d.ts +2 -0
  26. package/esm/polyfill.d.ts.map +1 -1
  27. package/esm/polyfill.js +12 -0
  28. package/esm/scrapeconfig.d.ts +27 -0
  29. package/esm/scrapeconfig.d.ts.map +1 -1
  30. package/esm/scrapeconfig.js +44 -1
  31. package/esm/screenshotconfig.d.ts +2 -2
  32. package/esm/screenshotconfig.d.ts.map +1 -1
  33. package/esm/utils.d.ts.map +1 -1
  34. package/esm/utils.js +16 -2
  35. package/esm/webhookserver.d.ts +1 -0
  36. package/esm/webhookserver.d.ts.map +1 -1
  37. package/esm/webhookserver.js +1 -0
  38. package/package.json +1 -1
  39. package/script/browserconfig.d.ts +59 -0
  40. package/script/browserconfig.d.ts.map +1 -0
  41. package/script/browserconfig.js +211 -0
  42. package/script/client.d.ts +193 -1
  43. package/script/client.d.ts.map +1 -1
  44. package/script/client.js +785 -4
  45. package/script/crawl.d.ts +118 -0
  46. package/script/crawl.d.ts.map +1 -0
  47. package/script/crawl.js +257 -0
  48. package/script/crawlerconfig.d.ts +119 -0
  49. package/script/crawlerconfig.d.ts.map +1 -0
  50. package/script/crawlerconfig.js +402 -0
  51. package/script/crawlerresult.d.ts +253 -0
  52. package/script/crawlerresult.d.ts.map +1 -0
  53. package/script/crawlerresult.js +335 -0
  54. package/script/errors.d.ts +4 -0
  55. package/script/errors.d.ts.map +1 -1
  56. package/script/errors.js +9 -1
  57. package/script/extractionconfig.d.ts +2 -0
  58. package/script/extractionconfig.d.ts.map +1 -1
  59. package/script/extractionconfig.js +10 -0
  60. package/script/main.d.ts +8 -1
  61. package/script/main.d.ts.map +1 -1
  62. package/script/main.js +17 -1
  63. package/script/polyfill.d.ts +2 -0
  64. package/script/polyfill.d.ts.map +1 -1
  65. package/script/polyfill.js +14 -1
  66. package/script/scrapeconfig.d.ts +27 -0
  67. package/script/scrapeconfig.d.ts.map +1 -1
  68. package/script/scrapeconfig.js +44 -1
  69. package/script/screenshotconfig.d.ts +2 -2
  70. package/script/screenshotconfig.d.ts.map +1 -1
  71. package/script/utils.d.ts.map +1 -1
  72. package/script/utils.js +16 -2
  73. package/script/webhookserver.d.ts +1 -0
  74. package/script/webhookserver.d.ts.map +1 -1
  75. package/script/webhookserver.js +2 -1
package/script/client.js CHANGED
@@ -28,8 +28,10 @@ const deps_js_1 = require("./deps.js");
28
28
  const polyfill_js_1 = require("./polyfill.js");
29
29
  const utils_js_1 = require("./utils.js");
30
30
  const errors = __importStar(require("./errors.js"));
31
+ const browserconfig_js_1 = require("./browserconfig.js");
31
32
  const result_js_1 = require("./result.js");
32
33
  const logger_js_1 = require("./logger.js");
34
+ const crawlerresult_js_1 = require("./crawlerresult.js");
33
35
  class ScrapflyClient {
34
36
  constructor(options) {
35
37
  Object.defineProperty(this, "HOST", {
@@ -38,6 +40,18 @@ class ScrapflyClient {
38
40
  writable: true,
39
41
  value: 'https://api.scrapfly.io'
40
42
  });
43
+ Object.defineProperty(this, "CLOUD_BROWSER_HOST", {
44
+ enumerable: true,
45
+ configurable: true,
46
+ writable: true,
47
+ value: 'wss://browser.scrapfly.io'
48
+ });
49
+ Object.defineProperty(this, "CLOUD_BROWSER_API_HOST", {
50
+ enumerable: true,
51
+ configurable: true,
52
+ writable: true,
53
+ value: 'https://browser.scrapfly.io'
54
+ });
41
55
  Object.defineProperty(this, "key", {
42
56
  enumerable: true,
43
57
  configurable: true,
@@ -50,6 +64,18 @@ class ScrapflyClient {
50
64
  writable: true,
51
65
  value: void 0
52
66
  });
67
+ Object.defineProperty(this, "cloudBrowserHost", {
68
+ enumerable: true,
69
+ configurable: true,
70
+ writable: true,
71
+ value: void 0
72
+ });
73
+ Object.defineProperty(this, "cloudBrowserApiHost", {
74
+ enumerable: true,
75
+ configurable: true,
76
+ writable: true,
77
+ value: void 0
78
+ });
53
79
  Object.defineProperty(this, "fetch", {
54
80
  enumerable: true,
55
81
  configurable: true,
@@ -60,7 +86,15 @@ class ScrapflyClient {
60
86
  throw new errors.BadApiKeyError('Invalid key. Key must be a non-empty string');
61
87
  }
62
88
  this.key = options.key;
89
+ if (options.host) {
90
+ // Trim trailing slash so callers can pass either form
91
+ this.HOST = options.host.replace(/\/+$/, '');
92
+ }
63
93
  this.ua = 'Typescript Scrapfly SDK';
94
+ this.cloudBrowserHost = options.cloudBrowserHost || this.CLOUD_BROWSER_HOST;
95
+ this.cloudBrowserApiHost = options.cloudBrowserHost
96
+ ? options.cloudBrowserHost.replace('wss://', 'https://')
97
+ : this.CLOUD_BROWSER_API_HOST;
64
98
  }
65
99
  /**
66
100
  * Raise appropriate error for given response and scrape result
@@ -68,12 +102,18 @@ class ScrapflyClient {
68
102
  errResult(response, result) {
69
103
  const error = result.result.error;
70
104
  const message = error?.message ?? '';
105
+ // When success=false the authoritative error code lives in result.result.error.code
106
+ // (e.g. "ERR::SCRAPE::BAD_UPSTREAM_RESPONSE"). result.result.status is only "DONE"
107
+ // or a job-level error and does not carry the upstream-failure code.
108
+ const effectiveCode = (result.result.success === false && error?.code)
109
+ ? error.code
110
+ : result.result.status;
71
111
  const args = {
72
- code: result.result.status,
112
+ code: effectiveCode,
73
113
  http_status_code: result.result.status_code,
74
114
  is_retryable: error?.retryable ?? false,
75
115
  api_response: result,
76
- resource: result.result.status ? result.result.status.split('::')[1] : null,
116
+ resource: effectiveCode ? effectiveCode.split('::')[1] : null,
77
117
  retry_delay: error?.retryable ? 5 : response.headers.get('X-Retry') ?? 5,
78
118
  retry_times: 3,
79
119
  documentation_url: error?.doc_url ?? 'https://scrapfly.io/docs/scrape-api/errors#api',
@@ -100,6 +140,8 @@ class ScrapflyClient {
100
140
  return new errors.ScrapflyAspError(message, args);
101
141
  case 'SESSION':
102
142
  return new errors.ScrapflySessionError(message, args);
143
+ case 'CRAWLER':
144
+ return new errors.ScrapflyCrawlerError(message, args);
103
145
  }
104
146
  if (args.resource) {
105
147
  return new errors.ApiHttpClientError(message, args);
@@ -127,6 +169,8 @@ class ScrapflyClient {
127
169
  return new errors.ScrapflyAspError(message, args);
128
170
  case 'SESSION':
129
171
  return new errors.ScrapflySessionError(message, args);
172
+ case 'CRAWLER':
173
+ return new errors.ScrapflyCrawlerError(message, args);
130
174
  }
131
175
  }
132
176
  return new errors.ScrapflyError(message, args);
@@ -237,9 +281,66 @@ class ScrapflyClient {
237
281
  }
238
282
  catch (e) {
239
283
  logger_js_1.log.error('error', e);
240
- e.scrapeConfig = config;
284
+ // Attach the scrape config to the thrown error for debuggability.
285
+ // The error is typed as `unknown` since TypeScript 4.4 strict catch
286
+ // clause variables, so we narrow to a mutable object before tagging.
287
+ if (e !== null && typeof e === 'object') {
288
+ e.scrapeConfig = config;
289
+ }
241
290
  throw e;
242
291
  }
292
+ // Proxified mode: the API returns the raw upstream response (target's
293
+ // status, headers, body) instead of the JSON envelope. Return the raw
294
+ // fetch Response so callers can drive it like any HTTP response.
295
+ //
296
+ // DO NOT throw on non-2xx: the response status is the UPSTREAM target's
297
+ // status, not a Scrapfly system error. A 503 from the target is a
298
+ // legitimate proxified response, not an API failure.
299
+ //
300
+ // Callers inspect:
301
+ // response.status — the upstream status
302
+ // response.headers.get("x-scrapfly-reject-code") — Scrapfly error (if any)
303
+ // response.headers.get("x-scrapfly-api-cost") — credits charged
304
+ if (config.proxified_response === true) {
305
+ // Error restoration: if X-Scrapfly-Reject-Code is present, the
306
+ // scrape failed. Reconstruct a typed error from the headers so
307
+ // callers get the same error interface as non-proxified mode.
308
+ const rejectCode = response.headers.get('x-scrapfly-reject-code');
309
+ if (rejectCode) {
310
+ const rejectDesc = response.headers.get('x-scrapfly-reject-description') ?? '';
311
+ const rejectRetryable = response.headers.get('x-scrapfly-reject-retryable') === 'true';
312
+ const retryAfter = rejectRetryable ? parseInt(response.headers.get('retry-after') ?? '0', 10) : 0;
313
+ const err = new errors.ApiHttpClientError(`Proxified scrape error: ${rejectCode} — ${rejectDesc}`);
314
+ err.code = rejectCode;
315
+ err.httpStatusCode = response.status;
316
+ err.retryable = rejectRetryable;
317
+ err.retryAfter = retryAfter;
318
+ err.response = response;
319
+ throw err;
320
+ }
321
+ return response;
322
+ }
323
+ // HEAD responses have no body per HTTP spec — the API returns headers
324
+ // only. Build a ScrapeResult from the HTTP response headers and the
325
+ // local config, mirroring the Python SDK's HEAD handler.
326
+ if (config.method === 'HEAD') {
327
+ const responseHeaders = {};
328
+ response.headers.forEach((v, k) => { responseHeaders[k] = v; });
329
+ return this.handleResponse(response, new result_js_1.ScrapeResult({
330
+ config: config.toApiParams({ key: this.key }),
331
+ context: {},
332
+ result: {
333
+ status_code: response.status,
334
+ content: '',
335
+ format: 'text',
336
+ success: response.status >= 200 && response.status < 300,
337
+ status: 'DONE',
338
+ response_headers: responseHeaders,
339
+ request_headers: {},
340
+ },
341
+ uuid: '',
342
+ }));
343
+ }
243
344
  const data = await response.json();
244
345
  if ('error_id' in data || Object.keys(data).length === 0) {
245
346
  if (data.http_code == 401 || response.status == 401) {
@@ -401,7 +502,7 @@ class ScrapflyClient {
401
502
  let response;
402
503
  try {
403
504
  const url = new URL(this.HOST + '/extraction');
404
- const params = await config.toApiParams({ key: this.key });
505
+ const params = config.toApiParams({ key: this.key });
405
506
  url.search = new URLSearchParams(params).toString();
406
507
  const headers = {
407
508
  'user-agent': this.ua,
@@ -426,5 +527,685 @@ class ScrapflyClient {
426
527
  const result = await this.handleExtractionResponse(response);
427
528
  return result;
428
529
  }
530
+ // ---------------------------------------------------------------------------
531
+ // Crawler API
532
+ // ---------------------------------------------------------------------------
533
+ /**
534
+ * Throw a typed error for a crawler JSON error envelope.
535
+ *
536
+ * The crawler endpoints (status, urls, contents, artifact, cancel) return either
537
+ * a clean JSON body on success or an error envelope `{error_id, http_code, message, ...}`.
538
+ * Use this to map the envelope to one of `BadApiKeyError` / `ScrapflyCrawlerError` /
539
+ * `ApiHttpClientError`.
540
+ */
541
+ throwCrawlerError(response, data) {
542
+ const httpCode = data.http_code ?? response.status;
543
+ const code = (data.code ?? '');
544
+ const message = data.message ?? JSON.stringify(data);
545
+ if (httpCode === 401) {
546
+ throw new errors.BadApiKeyError(message, { http_status_code: httpCode, code, api_response: data });
547
+ }
548
+ if (httpCode === 429) {
549
+ throw new errors.TooManyRequests(message, { http_status_code: httpCode, code, api_response: data });
550
+ }
551
+ // Any ERR::CRAWLER::* code → typed crawler error
552
+ if (typeof code === 'string' && code.includes('::CRAWLER::')) {
553
+ throw new errors.ScrapflyCrawlerError(message, { http_status_code: httpCode, code, api_response: data });
554
+ }
555
+ throw new errors.ApiHttpClientError(message, { http_status_code: httpCode, code, api_response: data });
556
+ }
557
+ /**
558
+ * Schedule a new crawler job.
559
+ *
560
+ * `POST /crawl` — returns `{crawler_uuid, status}` on success. On failure throws
561
+ * `ScrapflyCrawlerError`, `BadApiKeyError`, or `ApiHttpClientError`.
562
+ */
563
+ async crawl(config) {
564
+ logger_js_1.log.debug('crawling', { url: config.url });
565
+ let response;
566
+ try {
567
+ const url = new URL(this.HOST + '/crawl');
568
+ url.search = new URLSearchParams({ key: this.key }).toString();
569
+ response = await this.fetch({
570
+ url: url.toString(),
571
+ method: 'POST',
572
+ headers: {
573
+ 'user-agent': this.ua,
574
+ 'content-type': 'application/json',
575
+ 'accept-encoding': 'gzip, deflate, br',
576
+ accept: 'application/json',
577
+ },
578
+ body: JSON.stringify(config.toApiParams()),
579
+ });
580
+ }
581
+ catch (e) {
582
+ logger_js_1.log.error('error', e);
583
+ throw e;
584
+ }
585
+ const data = (await response.json());
586
+ if ('error_id' in data || data.http_code !== undefined) {
587
+ this.throwCrawlerError(response, data);
588
+ }
589
+ if (typeof data.uuid !== 'string' && typeof data.crawler_uuid !== 'string') {
590
+ throw new errors.ApiHttpClientError(`Crawler API returned no uuid: ${JSON.stringify(data).slice(0, 500)}`);
591
+ }
592
+ return {
593
+ crawler_uuid: (data.crawler_uuid ?? data.uuid),
594
+ status: (data.status ?? 'PENDING'),
595
+ };
596
+ }
597
+ /**
598
+ * Get the current status of a crawler job.
599
+ *
600
+ * `GET /crawl/{uuid}/status`
601
+ */
602
+ async crawlStatus(uuid) {
603
+ let response;
604
+ try {
605
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/status`);
606
+ url.search = new URLSearchParams({ key: this.key }).toString();
607
+ response = await this.fetch({
608
+ url: url.toString(),
609
+ method: 'GET',
610
+ headers: {
611
+ 'user-agent': this.ua,
612
+ 'accept-encoding': 'gzip, deflate, br',
613
+ accept: 'application/json',
614
+ },
615
+ });
616
+ }
617
+ catch (e) {
618
+ logger_js_1.log.error('error', e);
619
+ throw e;
620
+ }
621
+ const data = (await response.json());
622
+ if ('error_id' in data || data.http_code !== undefined) {
623
+ this.throwCrawlerError(response, data);
624
+ }
625
+ return new crawlerresult_js_1.CrawlerStatus(data);
626
+ }
627
+ /**
628
+ * List crawled URLs for a job, optionally filtered by status and paginated.
629
+ *
630
+ * `GET /crawl/{uuid}/urls?status=<filter>&page=<n>&per_page=<n>`
631
+ *
632
+ * The server streams the response as `text/plain` — one record per line.
633
+ * JSON is intentionally NOT used here because this endpoint is expected to
634
+ * scale to millions of URLs per job, and materialising that as JSON would
635
+ * be prohibitively expensive on both the server and the client. See
636
+ * {@link CrawlerUrls.fromText} for the exact line format.
637
+ *
638
+ * Pagination: the wire protocol carries no global `total`. Request further
639
+ * pages by incrementing `page` until a response contains no records.
640
+ */
641
+ async crawlUrls(uuid, opts) {
642
+ const statusHint = opts?.status ?? 'visited';
643
+ const page = opts?.page ?? 1;
644
+ const perPage = opts?.per_page ?? 100;
645
+ let response;
646
+ try {
647
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/urls`);
648
+ const params = { key: this.key };
649
+ if (opts?.status)
650
+ params.status = opts.status;
651
+ if (opts?.page !== undefined)
652
+ params.page = String(opts.page);
653
+ if (opts?.per_page !== undefined)
654
+ params.per_page = String(opts.per_page);
655
+ url.search = new URLSearchParams(params).toString();
656
+ response = await this.fetch({
657
+ url: url.toString(),
658
+ method: 'GET',
659
+ headers: {
660
+ 'user-agent': this.ua,
661
+ 'accept-encoding': 'gzip, deflate, br',
662
+ // text/plain is the canonical format; we also accept JSON because
663
+ // error envelopes come back as JSON regardless of the success type.
664
+ accept: 'text/plain, application/json',
665
+ },
666
+ });
667
+ }
668
+ catch (e) {
669
+ logger_js_1.log.error('error', e);
670
+ throw e;
671
+ }
672
+ // Error envelopes are always JSON, even for text endpoints. Detect by
673
+ // content-type before consuming the body as text.
674
+ const ct = response.headers.get('content-type') ?? '';
675
+ if (ct.includes('application/json')) {
676
+ const data = (await response.json());
677
+ if ('error_id' in data || data.http_code !== undefined) {
678
+ this.throwCrawlerError(response, data);
679
+ }
680
+ // Unexpected: the server sent JSON on a success response for the text
681
+ // endpoint. Surface this as a client error so users see the mismatch
682
+ // instead of getting silent empty results.
683
+ throw new errors.ApiHttpClientError(`crawlUrls expected text/plain, got JSON: ${JSON.stringify(data).slice(0, 500)}`);
684
+ }
685
+ const body = await response.text();
686
+ return crawlerresult_js_1.CrawlerUrls.fromText(body, statusHint, page, perPage);
687
+ }
688
+ /**
689
+ * Get crawled content from a crawler job.
690
+ *
691
+ * Two modes:
692
+ *
693
+ * 1. **JSON mode** (default, `plain` omitted or false): returns a {@link CrawlerContents}
694
+ * with a `contents` map (URL → format → content) and pagination links. Useful for
695
+ * bulk retrieval. Honors `limit` (max 50, default 10) and `offset`.
696
+ *
697
+ * 2. **Plain mode** (`plain: true`): returns the raw content for a single URL/format
698
+ * as a `string`, with content-type matching the format. Requires `url`. Useful for
699
+ * piping markdown/text directly. **New in this SDK** (not in Python SDK as of 0.8.27).
700
+ *
701
+ * `GET /crawl/{uuid}/contents`
702
+ */
703
+ async crawlContents(uuid, opts) {
704
+ if (opts.plain && !opts.url) {
705
+ throw new errors.CrawlerConfigError('plain=true requires a single `url` argument');
706
+ }
707
+ let response;
708
+ try {
709
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/contents`);
710
+ // Note: the server query param is `formats` (plural), not `format`. The
711
+ // public docs say `format` but the actual server only accepts `formats`.
712
+ // We expose `format` (singular) as the SDK option since that's what users
713
+ // expect from the docs, and translate it here.
714
+ const params = { key: this.key, formats: opts.format };
715
+ if (opts.url)
716
+ params.url = opts.url;
717
+ if (opts.plain)
718
+ params.plain = 'true';
719
+ if (opts.limit !== undefined)
720
+ params.limit = String(opts.limit);
721
+ if (opts.offset !== undefined)
722
+ params.offset = String(opts.offset);
723
+ url.search = new URLSearchParams(params).toString();
724
+ response = await this.fetch({
725
+ url: url.toString(),
726
+ method: 'GET',
727
+ headers: {
728
+ 'user-agent': this.ua,
729
+ 'accept-encoding': 'gzip, deflate, br',
730
+ // In plain mode the server returns the raw content with a format-matching
731
+ // content-type (text/markdown, text/html, etc.); accept anything.
732
+ accept: opts.plain ? '*/*' : 'application/json',
733
+ },
734
+ });
735
+ }
736
+ catch (e) {
737
+ logger_js_1.log.error('error', e);
738
+ throw e;
739
+ }
740
+ if (opts.plain) {
741
+ // Plain mode: server returns raw text. Error envelopes still come back as JSON,
742
+ // so detect that by content-type before reading the body as text.
743
+ const ct = response.headers.get('content-type') ?? '';
744
+ if (ct.includes('application/json')) {
745
+ const data = (await response.json());
746
+ if ('error_id' in data || data.http_code !== undefined) {
747
+ this.throwCrawlerError(response, data);
748
+ }
749
+ // JSON came back without an error envelope — caller asked for plain but server
750
+ // returned JSON anyway (e.g. format=json). Stringify so the return type is stable.
751
+ return JSON.stringify(data);
752
+ }
753
+ return await response.text();
754
+ }
755
+ const data = (await response.json());
756
+ if ('error_id' in data || data.http_code !== undefined) {
757
+ this.throwCrawlerError(response, data);
758
+ }
759
+ return new crawlerresult_js_1.CrawlerContents(data);
760
+ }
761
+ /**
762
+ * Batch-retrieve crawled content for up to 100 URLs in one round-trip.
763
+ *
764
+ * `POST /crawl/{uuid}/contents/batch`
765
+ *
766
+ * The request body is a newline-separated list of URLs (`text/plain`). The response
767
+ * is a `multipart/related` (RFC 2387) document with one part per found URL. Each
768
+ * part has `Content-Type` (matching the format) and `Content-Location` (the URL).
769
+ *
770
+ * Returns a map of `url → format → content`. Formats not requested for a given URL
771
+ * are simply absent from its inner map.
772
+ */
773
+ async crawlContentsBatch(uuid, urls, formats) {
774
+ if (urls.length === 0) {
775
+ throw new errors.CrawlerConfigError('crawlContentsBatch requires at least one url');
776
+ }
777
+ if (urls.length > 100) {
778
+ throw new errors.CrawlerConfigError('crawlContentsBatch is limited to 100 urls per request');
779
+ }
780
+ if (formats.length === 0) {
781
+ throw new errors.CrawlerConfigError('crawlContentsBatch requires at least one format');
782
+ }
783
+ let response;
784
+ try {
785
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/contents/batch`);
786
+ url.search = new URLSearchParams({ key: this.key, formats: formats.join(',') }).toString();
787
+ response = await this.fetch({
788
+ url: url.toString(),
789
+ method: 'POST',
790
+ headers: {
791
+ 'user-agent': this.ua,
792
+ 'content-type': 'text/plain',
793
+ 'accept-encoding': 'gzip, deflate, br',
794
+ accept: 'multipart/related, application/json',
795
+ },
796
+ body: urls.join('\n'),
797
+ });
798
+ }
799
+ catch (e) {
800
+ logger_js_1.log.error('error', e);
801
+ throw e;
802
+ }
803
+ const ct = response.headers.get('content-type') ?? '';
804
+ if (ct.includes('application/json')) {
805
+ // Error envelope
806
+ const data = (await response.json());
807
+ if ('error_id' in data || data.http_code !== undefined) {
808
+ this.throwCrawlerError(response, data);
809
+ }
810
+ throw new errors.ApiHttpClientError(`crawlContentsBatch expected multipart/related, got JSON: ${JSON.stringify(data).slice(0, 500)}`);
811
+ }
812
+ const text = await response.text();
813
+ return parseMultipartRelated(text, ct, formats);
814
+ }
815
+ /**
816
+ * Download a crawler job's WARC or HAR artifact as raw bytes.
817
+ *
818
+ * `GET /crawl/{uuid}/artifact?type=warc|har`
819
+ *
820
+ * The SDK does NOT bundle WARC/HAR parsers — use a dedicated library (e.g. `warcio`
821
+ * on npm) to walk the records. The returned {@link CrawlerArtifact} provides a
822
+ * `save(path)` helper for the common case of writing the artifact to disk.
823
+ */
824
+ async crawlArtifact(uuid, type = 'warc') {
825
+ let response;
826
+ try {
827
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/artifact`);
828
+ url.search = new URLSearchParams({ key: this.key, type }).toString();
829
+ response = await this.fetch({
830
+ url: url.toString(),
831
+ method: 'GET',
832
+ headers: {
833
+ 'user-agent': this.ua,
834
+ // Accept the artifact's binary content type plus JSON for error envelopes
835
+ accept: type === 'har' ? 'application/json, application/octet-stream' : 'application/gzip, application/octet-stream',
836
+ },
837
+ });
838
+ }
839
+ catch (e) {
840
+ logger_js_1.log.error('error', e);
841
+ throw e;
842
+ }
843
+ // Error envelope check (server returns JSON on errors regardless of artifact type)
844
+ const ct = response.headers.get('content-type') ?? '';
845
+ if (ct.includes('application/json') && type !== 'har') {
846
+ // For warc, JSON responses are always errors. For har, JSON IS the artifact —
847
+ // we need to peek at the body to distinguish.
848
+ const data = (await response.json());
849
+ if ('error_id' in data || data.http_code !== undefined) {
850
+ this.throwCrawlerError(response, data);
851
+ }
852
+ // Should not reach here for warc; treat as unexpected JSON.
853
+ throw new errors.ApiHttpClientError(`crawlArtifact(${type}) expected binary, got JSON: ${JSON.stringify(data).slice(0, 500)}`);
854
+ }
855
+ const buf = new Uint8Array(await response.arrayBuffer());
856
+ // For HAR, the body IS JSON — but we still need to detect error envelopes
857
+ // (which set http_code or error_id at the top level of the JSON object).
858
+ if (type === 'har') {
859
+ try {
860
+ const text = new TextDecoder().decode(buf);
861
+ const parsed = JSON.parse(text);
862
+ if ('error_id' in parsed || parsed.http_code !== undefined) {
863
+ this.throwCrawlerError(response, parsed);
864
+ }
865
+ }
866
+ catch (e) {
867
+ // If JSON parse fails, the body is not an error envelope — treat as raw HAR bytes.
868
+ if (e instanceof errors.ScrapflyError)
869
+ throw e;
870
+ }
871
+ }
872
+ return new crawlerresult_js_1.CrawlerArtifact(type, buf);
873
+ }
874
+ /**
875
+ * Cancel a running crawler job.
876
+ *
877
+ * `POST /crawl/{uuid}/cancel` — returns `true` on success. The endpoint
878
+ * is idempotent: cancelling a crawl that has already finished is a no-op
879
+ * and still returns success.
880
+ *
881
+ * Note: earlier versions of this SDK called `DELETE /crawl/{uuid}`, which
882
+ * is not a valid public route — that path silently 404'd against the
883
+ * public API. Fixed in 0.8.0 to use the correct documented endpoint.
884
+ */
885
+ async crawlCancel(uuid) {
886
+ let response;
887
+ try {
888
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/cancel`);
889
+ url.search = new URLSearchParams({ key: this.key }).toString();
890
+ response = await this.fetch({
891
+ url: url.toString(),
892
+ method: 'POST',
893
+ headers: {
894
+ 'user-agent': this.ua,
895
+ 'accept-encoding': 'gzip, deflate, br',
896
+ accept: 'application/json',
897
+ },
898
+ });
899
+ }
900
+ catch (e) {
901
+ logger_js_1.log.error('error', e);
902
+ throw e;
903
+ }
904
+ // Empty body or JSON
905
+ const ct = response.headers.get('content-type') ?? '';
906
+ if (ct.includes('application/json')) {
907
+ const data = (await response.json());
908
+ if ('error_id' in data || data.http_code !== undefined) {
909
+ this.throwCrawlerError(response, data);
910
+ }
911
+ }
912
+ return response.ok;
913
+ }
914
+ // --- Cloud Browser ---
915
+ /**
916
+ * Get the WebSocket URL for a Cloud Browser session.
917
+ */
918
+ cloudBrowser(config) {
919
+ const browserConfig = config || new browserconfig_js_1.BrowserConfig();
920
+ return browserConfig.websocketUrl(this.key, this.cloudBrowserHost);
921
+ }
922
+ /**
923
+ * Call the Cloud Browser Unblock API.
924
+ */
925
+ async cloudBrowserUnblock(options) {
926
+ const proxyPoolMap = {
927
+ datacenter: 'public_datacenter_pool',
928
+ residential: 'public_residential_pool',
929
+ };
930
+ const jsonBody = { url: options.url };
931
+ if (options.proxy_pool)
932
+ jsonBody.proxy_pool = proxyPoolMap[options.proxy_pool] || options.proxy_pool;
933
+ if (options.country)
934
+ jsonBody.country = options.country;
935
+ if (options.os)
936
+ jsonBody.os = options.os;
937
+ if (options.timeout)
938
+ jsonBody.timeout = options.timeout;
939
+ if (options.browser_timeout)
940
+ jsonBody.browser_timeout = options.browser_timeout;
941
+ if (options.headers)
942
+ jsonBody.headers = options.headers;
943
+ if (options.body)
944
+ jsonBody.body = options.body;
945
+ if (options.method)
946
+ jsonBody.method = options.method;
947
+ const url = new URL(this.cloudBrowserApiHost + '/unblock');
948
+ url.searchParams.set('key', this.key);
949
+ const response = await this.fetch({
950
+ url: url.toString(),
951
+ method: 'POST',
952
+ headers: {
953
+ 'content-type': 'application/json',
954
+ 'user-agent': this.ua,
955
+ },
956
+ body: JSON.stringify(jsonBody),
957
+ });
958
+ if (!response.ok) {
959
+ throw new Error(`Unblock failed: ${response.status} ${await response.text()}`);
960
+ }
961
+ return await response.json();
962
+ }
963
+ /**
964
+ * Stop a Cloud Browser session.
965
+ */
966
+ async cloudBrowserSessionStop(sessionId) {
967
+ const url = new URL(this.cloudBrowserApiHost + '/session/' + sessionId + '/stop');
968
+ url.searchParams.set('key', this.key);
969
+ const response = await this.fetch({
970
+ url: url.toString(),
971
+ method: 'POST',
972
+ headers: { 'user-agent': this.ua },
973
+ });
974
+ if (!response.ok) {
975
+ throw new Error(`Session stop failed: ${response.status} ${await response.text()}`);
976
+ }
977
+ }
978
+ /**
979
+ * List all browser extensions.
980
+ */
981
+ async cloudBrowserExtensionList() {
982
+ const url = new URL(this.cloudBrowserApiHost + '/extension');
983
+ url.searchParams.set('key', this.key);
984
+ const response = await this.fetch({
985
+ url: url.toString(),
986
+ method: 'GET',
987
+ headers: { 'user-agent': this.ua },
988
+ });
989
+ if (!response.ok) {
990
+ throw new Error(`Extension list failed: ${response.status} ${await response.text()}`);
991
+ }
992
+ return await response.json();
993
+ }
994
+ /**
995
+ * Delete a browser extension.
996
+ */
997
+ async cloudBrowserExtensionDelete(extensionId) {
998
+ const url = new URL(this.cloudBrowserApiHost + '/extension/' + extensionId);
999
+ url.searchParams.set('key', this.key);
1000
+ const response = await this.fetch({
1001
+ url: url.toString(),
1002
+ method: 'DELETE',
1003
+ headers: { 'user-agent': this.ua },
1004
+ });
1005
+ if (!response.ok) {
1006
+ throw new Error(`Extension delete failed: ${response.status} ${await response.text()}`);
1007
+ }
1008
+ return await response.json();
1009
+ }
1010
+ /**
1011
+ * Get details of a specific browser extension.
1012
+ */
1013
+ async cloudBrowserExtensionGet(extensionId) {
1014
+ const url = new URL(this.cloudBrowserApiHost + '/extension/' + extensionId);
1015
+ url.searchParams.set('key', this.key);
1016
+ const response = await this.fetch({
1017
+ url: url.toString(),
1018
+ method: 'GET',
1019
+ headers: { 'user-agent': this.ua },
1020
+ });
1021
+ if (!response.ok) {
1022
+ throw new Error(`Extension get failed: ${response.status} ${await response.text()}`);
1023
+ }
1024
+ return await response.json();
1025
+ }
1026
+ /**
1027
+ * Upload a browser extension from a local file (.zip or .crx).
1028
+ * Pass a file path — the file is read and sent as multipart/form-data.
1029
+ */
1030
+ async cloudBrowserExtensionUpload(filePath) {
1031
+ const fileBytes = (0, polyfill_js_1.readFileSync)(filePath);
1032
+ const fileName = filePath.split('/').pop() || filePath.split('\\').pop() || 'extension.zip';
1033
+ const boundary = '----ScrapflyBoundary' + Date.now();
1034
+ const encoder = new TextEncoder();
1035
+ const header = encoder.encode(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${fileName}"\r\nContent-Type: application/octet-stream\r\n\r\n`);
1036
+ const footer = encoder.encode(`\r\n--${boundary}--\r\n`);
1037
+ const body = new Uint8Array(header.length + fileBytes.length + footer.length);
1038
+ body.set(header, 0);
1039
+ body.set(fileBytes, header.length);
1040
+ body.set(footer, header.length + fileBytes.length);
1041
+ const url = new URL(this.cloudBrowserApiHost + '/extension');
1042
+ url.searchParams.set('key', this.key);
1043
+ const response = await this.fetch({
1044
+ url: url.toString(),
1045
+ method: 'POST',
1046
+ headers: {
1047
+ 'content-type': `multipart/form-data; boundary=${boundary}`,
1048
+ 'user-agent': this.ua,
1049
+ },
1050
+ body: body,
1051
+ });
1052
+ if (!response.ok) {
1053
+ throw new Error(`Extension upload failed: ${response.status} ${await response.text()}`);
1054
+ }
1055
+ return await response.json();
1056
+ }
1057
+ /**
1058
+ * Install a browser extension from a URL (.crx file).
1059
+ * URL-based extensions auto-update on each browser session start.
1060
+ */
1061
+ async cloudBrowserExtensionUploadFromUrl(extensionUrl) {
1062
+ const url = new URL(this.cloudBrowserApiHost + '/extension');
1063
+ url.searchParams.set('key', this.key);
1064
+ const response = await this.fetch({
1065
+ url: url.toString(),
1066
+ method: 'POST',
1067
+ headers: {
1068
+ 'content-type': 'application/json',
1069
+ 'user-agent': this.ua,
1070
+ },
1071
+ body: JSON.stringify({ extension_url: extensionUrl }),
1072
+ });
1073
+ if (!response.ok) {
1074
+ throw new Error(`Extension upload from URL failed: ${response.status} ${await response.text()}`);
1075
+ }
1076
+ return await response.json();
1077
+ }
1078
+ /**
1079
+ * Download a debug session recording video.
1080
+ * Returns the video as an ArrayBuffer (stream from server).
1081
+ */
1082
+ async cloudBrowserVideo(runId) {
1083
+ const url = new URL(this.cloudBrowserApiHost + '/run/' + runId + '/video');
1084
+ url.searchParams.set('key', this.key);
1085
+ const response = await this.fetch({
1086
+ url: url.toString(),
1087
+ method: 'GET',
1088
+ headers: { 'user-agent': this.ua },
1089
+ });
1090
+ if (!response.ok) {
1091
+ throw new Error(`Video download failed: ${response.status} ${await response.text()}`);
1092
+ }
1093
+ const filename = runId + '.webm';
1094
+ return { data: await response.arrayBuffer(), filename };
1095
+ }
1096
+ /**
1097
+ * Get playback info for a debug session recording.
1098
+ */
1099
+ async cloudBrowserPlayback(runId) {
1100
+ const url = new URL(this.cloudBrowserApiHost + '/run/' + runId + '/playback');
1101
+ url.searchParams.set('key', this.key);
1102
+ const response = await this.fetch({
1103
+ url: url.toString(),
1104
+ method: 'GET',
1105
+ headers: { 'user-agent': this.ua },
1106
+ });
1107
+ if (!response.ok) {
1108
+ throw new Error(`Playback get failed: ${response.status} ${await response.text()}`);
1109
+ }
1110
+ return await response.json();
1111
+ }
1112
+ /**
1113
+ * List all running Cloud Browser sessions.
1114
+ */
1115
+ async cloudBrowserSessions() {
1116
+ const url = new URL(this.cloudBrowserApiHost + '/sessions');
1117
+ url.searchParams.set('key', this.key);
1118
+ const response = await this.fetch({
1119
+ url: url.toString(),
1120
+ method: 'GET',
1121
+ headers: { 'user-agent': this.ua },
1122
+ });
1123
+ if (!response.ok) {
1124
+ throw new Error(`Sessions list failed: ${response.status} ${await response.text()}`);
1125
+ }
1126
+ return await response.json();
1127
+ }
429
1128
  }
430
1129
  exports.ScrapflyClient = ScrapflyClient;
1130
+ // ---------------------------------------------------------------------------
1131
+ // multipart/related parser
1132
+ // ---------------------------------------------------------------------------
1133
+ //
1134
+ // Tiny inline parser for the response of `POST /crawl/{uuid}/contents/batch`.
1135
+ // Avoids pulling in a multipart npm dep so the SDK stays dependency-free.
1136
+ //
1137
+ // Each part has at minimum a `Content-Location: <url>` header and a body. The
1138
+ // `Content-Type` may also be set, indicating the format. We map URL → format → body
1139
+ // using the `formats` argument as the inferred-format fallback when the part has
1140
+ // no `Content-Type`.
1141
+ function parseMultipartRelated(body, contentType, formats) {
1142
+ const boundaryMatch = contentType.match(/boundary=(?:"([^"]+)"|([^;\s]+))/);
1143
+ if (!boundaryMatch) {
1144
+ throw new errors.ApiHttpClientError(`crawlContentsBatch: response has no multipart boundary in content-type "${contentType}"`);
1145
+ }
1146
+ const boundary = boundaryMatch[1] ?? boundaryMatch[2];
1147
+ const delimiter = `--${boundary}`;
1148
+ const result = {};
1149
+ // Split on the delimiter; first segment is the preamble (ignored), last is the
1150
+ // closing `--` (also ignored).
1151
+ const segments = body.split(delimiter);
1152
+ for (let i = 1; i < segments.length; i++) {
1153
+ let segment = segments[i];
1154
+ // Strip leading CRLF after the boundary
1155
+ if (segment.startsWith('\r\n'))
1156
+ segment = segment.slice(2);
1157
+ else if (segment.startsWith('\n'))
1158
+ segment = segment.slice(1);
1159
+ // The closing boundary is `--{boundary}--`; segment starts with `--` then EOL
1160
+ if (segment.startsWith('--'))
1161
+ break;
1162
+ // Trim trailing CRLF before the next boundary
1163
+ if (segment.endsWith('\r\n'))
1164
+ segment = segment.slice(0, -2);
1165
+ else if (segment.endsWith('\n'))
1166
+ segment = segment.slice(0, -1);
1167
+ // Header/body split: first blank line
1168
+ const headerEnd = segment.indexOf('\r\n\r\n');
1169
+ const altHeaderEnd = headerEnd === -1 ? segment.indexOf('\n\n') : headerEnd;
1170
+ if (altHeaderEnd === -1)
1171
+ continue;
1172
+ const headersRaw = segment.slice(0, altHeaderEnd);
1173
+ const partBody = segment.slice(altHeaderEnd + (headerEnd === -1 ? 2 : 4));
1174
+ // Parse headers
1175
+ let url;
1176
+ let format;
1177
+ for (const line of headersRaw.split(/\r?\n/)) {
1178
+ const colon = line.indexOf(':');
1179
+ if (colon === -1)
1180
+ continue;
1181
+ const name = line.slice(0, colon).trim().toLowerCase();
1182
+ const value = line.slice(colon + 1).trim();
1183
+ if (name === 'content-location')
1184
+ url = value;
1185
+ else if (name === 'content-type')
1186
+ format = inferFormatFromContentType(value);
1187
+ }
1188
+ if (!url)
1189
+ continue;
1190
+ if (!format) {
1191
+ // Fall back to the first requested format if the part has no content-type
1192
+ format = formats[0];
1193
+ }
1194
+ if (!result[url])
1195
+ result[url] = {};
1196
+ result[url][format] = partBody;
1197
+ }
1198
+ return result;
1199
+ }
1200
+ function inferFormatFromContentType(ct) {
1201
+ const lc = ct.toLowerCase().split(';')[0].trim();
1202
+ if (lc === 'text/html')
1203
+ return 'html';
1204
+ if (lc === 'text/markdown')
1205
+ return 'markdown';
1206
+ if (lc === 'text/plain')
1207
+ return 'text';
1208
+ if (lc === 'application/json')
1209
+ return 'json';
1210
+ return undefined;
1211
+ }