scrapfly-sdk 0.10.2 → 0.10.4

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 (100) hide show
  1. package/esm/batch.d.ts.map +1 -1
  2. package/esm/batch.js +4 -0
  3. package/esm/client.d.ts.map +1 -1
  4. package/esm/client.js +17 -8
  5. package/package.json +1 -1
  6. package/script/batch.d.ts.map +1 -1
  7. package/script/batch.js +4 -0
  8. package/script/client.d.ts.map +1 -1
  9. package/script/client.js +17 -8
  10. package/src/_dnt.shims.ts +64 -0
  11. package/src/batch.ts +272 -0
  12. package/src/browserconfig.ts +118 -0
  13. package/src/client.ts +1609 -0
  14. package/src/crawl.ts +251 -0
  15. package/src/crawlerconfig.ts +363 -0
  16. package/src/crawlerresult.ts +471 -0
  17. package/src/deps/jsr.io/@std/path/1.0.1/_common/assert_path.ts +10 -0
  18. package/src/deps/jsr.io/@std/path/1.0.1/_common/basename.ts +53 -0
  19. package/src/deps/jsr.io/@std/path/1.0.1/_common/common.ts +26 -0
  20. package/src/deps/jsr.io/@std/path/1.0.1/_common/constants.ts +49 -0
  21. package/src/deps/jsr.io/@std/path/1.0.1/_common/dirname.ts +9 -0
  22. package/src/deps/jsr.io/@std/path/1.0.1/_common/format.ts +25 -0
  23. package/src/deps/jsr.io/@std/path/1.0.1/_common/from_file_url.ts +10 -0
  24. package/src/deps/jsr.io/@std/path/1.0.1/_common/glob_to_reg_exp.ts +290 -0
  25. package/src/deps/jsr.io/@std/path/1.0.1/_common/normalize.ts +9 -0
  26. package/src/deps/jsr.io/@std/path/1.0.1/_common/normalize_string.ts +74 -0
  27. package/src/deps/jsr.io/@std/path/1.0.1/_common/relative.ts +10 -0
  28. package/src/deps/jsr.io/@std/path/1.0.1/_common/strip_trailing_separators.ts +25 -0
  29. package/src/deps/jsr.io/@std/path/1.0.1/_common/to_file_url.ts +17 -0
  30. package/src/deps/jsr.io/@std/path/1.0.1/_os.ts +31 -0
  31. package/src/deps/jsr.io/@std/path/1.0.1/basename.ts +35 -0
  32. package/src/deps/jsr.io/@std/path/1.0.1/common.ts +35 -0
  33. package/src/deps/jsr.io/@std/path/1.0.1/constants.ts +18 -0
  34. package/src/deps/jsr.io/@std/path/1.0.1/dirname.ts +28 -0
  35. package/src/deps/jsr.io/@std/path/1.0.1/extname.ts +27 -0
  36. package/src/deps/jsr.io/@std/path/1.0.1/format.ts +30 -0
  37. package/src/deps/jsr.io/@std/path/1.0.1/from_file_url.ts +30 -0
  38. package/src/deps/jsr.io/@std/path/1.0.1/glob_to_regexp.ts +94 -0
  39. package/src/deps/jsr.io/@std/path/1.0.1/is_absolute.ts +30 -0
  40. package/src/deps/jsr.io/@std/path/1.0.1/is_glob.ts +49 -0
  41. package/src/deps/jsr.io/@std/path/1.0.1/join.ts +28 -0
  42. package/src/deps/jsr.io/@std/path/1.0.1/join_globs.ts +42 -0
  43. package/src/deps/jsr.io/@std/path/1.0.1/mod.ts +55 -0
  44. package/src/deps/jsr.io/@std/path/1.0.1/normalize.ts +31 -0
  45. package/src/deps/jsr.io/@std/path/1.0.1/normalize_glob.ts +45 -0
  46. package/src/deps/jsr.io/@std/path/1.0.1/parse.ts +44 -0
  47. package/src/deps/jsr.io/@std/path/1.0.1/posix/_util.ts +10 -0
  48. package/src/deps/jsr.io/@std/path/1.0.1/posix/basename.ts +39 -0
  49. package/src/deps/jsr.io/@std/path/1.0.1/posix/constants.ts +15 -0
  50. package/src/deps/jsr.io/@std/path/1.0.1/posix/dirname.ts +55 -0
  51. package/src/deps/jsr.io/@std/path/1.0.1/posix/extname.ts +73 -0
  52. package/src/deps/jsr.io/@std/path/1.0.1/posix/format.ts +31 -0
  53. package/src/deps/jsr.io/@std/path/1.0.1/posix/from_file_url.ts +25 -0
  54. package/src/deps/jsr.io/@std/path/1.0.1/posix/glob_to_regexp.ts +94 -0
  55. package/src/deps/jsr.io/@std/path/1.0.1/posix/is_absolute.ts +25 -0
  56. package/src/deps/jsr.io/@std/path/1.0.1/posix/join.ts +27 -0
  57. package/src/deps/jsr.io/@std/path/1.0.1/posix/join_globs.ts +44 -0
  58. package/src/deps/jsr.io/@std/path/1.0.1/posix/normalize.ts +41 -0
  59. package/src/deps/jsr.io/@std/path/1.0.1/posix/normalize_glob.ts +42 -0
  60. package/src/deps/jsr.io/@std/path/1.0.1/posix/parse.ts +121 -0
  61. package/src/deps/jsr.io/@std/path/1.0.1/posix/relative.ts +103 -0
  62. package/src/deps/jsr.io/@std/path/1.0.1/posix/resolve.ts +69 -0
  63. package/src/deps/jsr.io/@std/path/1.0.1/posix/to_file_url.ts +32 -0
  64. package/src/deps/jsr.io/@std/path/1.0.1/posix/to_namespaced_path.ts +21 -0
  65. package/src/deps/jsr.io/@std/path/1.0.1/relative.ts +32 -0
  66. package/src/deps/jsr.io/@std/path/1.0.1/resolve.ts +32 -0
  67. package/src/deps/jsr.io/@std/path/1.0.1/to_file_url.ts +30 -0
  68. package/src/deps/jsr.io/@std/path/1.0.1/to_namespaced_path.ts +31 -0
  69. package/src/deps/jsr.io/@std/path/1.0.1/types.ts +40 -0
  70. package/src/deps/jsr.io/@std/path/1.0.1/windows/_util.ts +28 -0
  71. package/src/deps/jsr.io/@std/path/1.0.1/windows/basename.ts +48 -0
  72. package/src/deps/jsr.io/@std/path/1.0.1/windows/constants.ts +15 -0
  73. package/src/deps/jsr.io/@std/path/1.0.1/windows/dirname.ts +114 -0
  74. package/src/deps/jsr.io/@std/path/1.0.1/windows/extname.ts +86 -0
  75. package/src/deps/jsr.io/@std/path/1.0.1/windows/format.ts +31 -0
  76. package/src/deps/jsr.io/@std/path/1.0.1/windows/from_file_url.ts +34 -0
  77. package/src/deps/jsr.io/@std/path/1.0.1/windows/glob_to_regexp.ts +92 -0
  78. package/src/deps/jsr.io/@std/path/1.0.1/windows/is_absolute.ts +40 -0
  79. package/src/deps/jsr.io/@std/path/1.0.1/windows/join.ts +72 -0
  80. package/src/deps/jsr.io/@std/path/1.0.1/windows/join_globs.ts +45 -0
  81. package/src/deps/jsr.io/@std/path/1.0.1/windows/normalize.ts +132 -0
  82. package/src/deps/jsr.io/@std/path/1.0.1/windows/normalize_glob.ts +42 -0
  83. package/src/deps/jsr.io/@std/path/1.0.1/windows/parse.ts +184 -0
  84. package/src/deps/jsr.io/@std/path/1.0.1/windows/relative.ts +128 -0
  85. package/src/deps/jsr.io/@std/path/1.0.1/windows/resolve.ts +174 -0
  86. package/src/deps/jsr.io/@std/path/1.0.1/windows/to_file_url.ts +38 -0
  87. package/src/deps/jsr.io/@std/path/1.0.1/windows/to_namespaced_path.ts +60 -0
  88. package/src/deps.ts +4 -0
  89. package/src/errors.ts +55 -0
  90. package/src/extractionconfig.ts +175 -0
  91. package/src/logger.ts +51 -0
  92. package/src/main.ts +61 -0
  93. package/src/monitoringconfig.ts +50 -0
  94. package/src/polyfill.ts +37 -0
  95. package/src/result.ts +338 -0
  96. package/src/scrapeconfig.ts +448 -0
  97. package/src/screenshotconfig.ts +204 -0
  98. package/src/types.ts +2 -0
  99. package/src/utils.ts +86 -0
  100. package/src/webhookserver.ts +66 -0
package/src/client.ts ADDED
@@ -0,0 +1,1609 @@
1
+ import { path } from './deps.js';
2
+ import { mkdir, writeFile, readFileSync } from './polyfill.js';
3
+ import { fetchRetry } from './utils.js';
4
+ import * as errors from './errors.js';
5
+ import type { ScrapeConfig } from './scrapeconfig.js';
6
+ import type { ScreenshotConfig } from './screenshotconfig.js';
7
+ import type { ExtractionConfig } from './extractionconfig.js';
8
+ import { BrowserConfig } from './browserconfig.js';
9
+ import { type AccountData, type ClassifyOptions, type ClassifyResult, ExtractionResult, ScrapeResult, ScreenshotResult } from './result.js';
10
+ import { log } from './logger.js';
11
+ import type { Rec } from './types.js';
12
+ import type { CrawlerConfig, CrawlerContentFormat } from './crawlerconfig.js';
13
+ import { CrawlerArtifact, type CrawlerArtifactType, CrawlerContents, CrawlerStatus, CrawlerUrls } from './crawlerresult.js';
14
+ import {
15
+ formatMonitoringDate,
16
+ type CloudBrowserMonitoringOptions,
17
+ type MonitoringMetricsOptions,
18
+ type MonitoringTargetMetricsOptions,
19
+ } from './monitoringconfig.js';
20
+
21
+ export class ScrapflyClient {
22
+ public HOST = 'https://api.scrapfly.io';
23
+ public CLOUD_BROWSER_HOST = 'wss://browser.scrapfly.io';
24
+ public CLOUD_BROWSER_API_HOST = 'https://browser.scrapfly.io';
25
+ private key: string;
26
+ private ua: string;
27
+ private cloudBrowserHost: string;
28
+ private cloudBrowserApiHost: string;
29
+ fetch = fetchRetry;
30
+
31
+ constructor(options: { key: string; host?: string; cloudBrowserHost?: string }) {
32
+ if (typeof options.key !== 'string' || options.key.trim() === '') {
33
+ throw new errors.BadApiKeyError('Invalid key. Key must be a non-empty string');
34
+ }
35
+ this.key = options.key;
36
+ if (options.host) {
37
+ // Trim trailing slash so callers can pass either form
38
+ this.HOST = options.host.replace(/\/+$/, '');
39
+ }
40
+ this.ua = 'Typescript Scrapfly SDK';
41
+ this.cloudBrowserHost = options.cloudBrowserHost || this.CLOUD_BROWSER_HOST;
42
+ this.cloudBrowserApiHost = options.cloudBrowserHost
43
+ ? options.cloudBrowserHost.replace('wss://', 'https://')
44
+ : this.CLOUD_BROWSER_API_HOST;
45
+ }
46
+
47
+ /**
48
+ * Raise appropriate error for given response and scrape result
49
+ */
50
+ errResult(response: Response, result: ScrapeResult): errors.ScrapflyError {
51
+ const error = result.result.error;
52
+ const message = error?.message ?? '';
53
+ // When success=false the authoritative error code lives in result.result.error.code
54
+ // (e.g. "ERR::SCRAPE::BAD_UPSTREAM_RESPONSE"). result.result.status is only "DONE"
55
+ // or a job-level error and does not carry the upstream-failure code.
56
+ const effectiveCode = (result.result.success === false && error?.code)
57
+ ? error.code
58
+ : result.result.status;
59
+ const args = {
60
+ code: effectiveCode,
61
+ http_status_code: result.result.status_code,
62
+ is_retryable: error?.retryable ?? false,
63
+ api_response: result,
64
+ resource: effectiveCode ? effectiveCode.split('::')[1] : null,
65
+ retry_delay: error?.retryable ? 5 : response.headers.get('X-Retry') ?? 5,
66
+ retry_times: 3,
67
+ documentation_url: error?.doc_url ?? 'https://scrapfly.io/docs/scrape-api/errors#api',
68
+ };
69
+ if (result.result.success === true) {
70
+ switch (args.http_status_code) {
71
+ case 500:
72
+ return new errors.ApiHttpServerError(message, args);
73
+ case 401:
74
+ return new errors.BadApiKeyError(message, args);
75
+ case 429:
76
+ return new errors.TooManyRequests(message, args);
77
+ }
78
+ switch (args.resource) {
79
+ case 'SCRAPE':
80
+ return new errors.ScrapflyScrapeError(message, args);
81
+ case 'WEBHOOK':
82
+ return new errors.ScrapflyWebhookError(message, args);
83
+ case 'PROXY':
84
+ return new errors.ScrapflyProxyError(message, args);
85
+ case 'SCHEDULE':
86
+ return new errors.ScrapflyScheduleError(message, args);
87
+ case 'ASP':
88
+ return new errors.ScrapflyAspError(message, args);
89
+ case 'SESSION':
90
+ return new errors.ScrapflySessionError(message, args);
91
+ case 'CRAWLER':
92
+ return new errors.ScrapflyCrawlerError(message, args);
93
+ }
94
+ if (args.resource) {
95
+ return new errors.ApiHttpClientError(message, args);
96
+ }
97
+ } else {
98
+ if (args.code === 'ERR::SCRAPE::BAD_UPSTREAM_RESPONSE') {
99
+ if (args.http_status_code >= 400 && args.http_status_code < 500) {
100
+ return new errors.UpstreamHttpClientError(message, args);
101
+ }
102
+ if (args.http_status_code >= 500 && args.http_status_code < 600) {
103
+ return new errors.UpstreamHttpServerError(message, args);
104
+ }
105
+ }
106
+ switch (args.resource) {
107
+ case 'SCRAPE':
108
+ return new errors.ScrapflyScrapeError(message, args);
109
+ case 'WEBHOOK':
110
+ return new errors.ScrapflyWebhookError(message, args);
111
+ case 'PROXY':
112
+ return new errors.ScrapflyProxyError(message, args);
113
+ case 'SCHEDULE':
114
+ return new errors.ScrapflyScheduleError(message, args);
115
+ case 'ASP':
116
+ return new errors.ScrapflyAspError(message, args);
117
+ case 'SESSION':
118
+ return new errors.ScrapflySessionError(message, args);
119
+ case 'CRAWLER':
120
+ return new errors.ScrapflyCrawlerError(message, args);
121
+ }
122
+ }
123
+ return new errors.ScrapflyError(message, args);
124
+ }
125
+
126
+ /**
127
+ * Handle clob and blob large objects
128
+ */
129
+ async handleLargeObjects(result: any, format: 'clob' | 'blob'): Promise<ScrapeResult> {
130
+ let response: Response;
131
+
132
+ try {
133
+ const url = new URL(result.content);
134
+ const params = { key: this.key };
135
+ url.search = new URLSearchParams(params).toString();
136
+ response = await this.fetch({
137
+ url: url.toString(),
138
+ method: 'GET',
139
+ headers: {
140
+ 'user-agent': this.ua,
141
+ 'accept-encoding': 'gzip, deflate, br',
142
+ accept: 'application/json',
143
+ },
144
+ });
145
+ } catch (e) {
146
+ log.error('error', e);
147
+ throw e;
148
+ }
149
+
150
+ let content;
151
+
152
+ if (format === 'clob') {
153
+ content = await response.text();
154
+ result.format = 'text';
155
+ }
156
+
157
+ if (format === 'blob') {
158
+ content = new Uint8Array(await response.arrayBuffer());
159
+ result.format = 'binary';
160
+ }
161
+
162
+ result.content = content;
163
+ return result;
164
+ }
165
+
166
+ /**
167
+ * Turn scrapfly API response to ScrapeResult or raise one of ScrapflyError
168
+ */
169
+ handleResponse(response: Response, result: ScrapeResult): ScrapeResult {
170
+ // success
171
+ log.debug('scrape log url: ', result.result.log_url);
172
+ if (result.result.status === 'DONE' && result.result.success === true) {
173
+ return result;
174
+ }
175
+ // something went wrong
176
+ throw this.errResult(response, result);
177
+ }
178
+
179
+ /**
180
+ * Retrieve Scrapfly account details
181
+ */
182
+ async account(): Promise<AccountData> {
183
+ log.debug('retrieving account info');
184
+ let response: Response;
185
+ try {
186
+ const url = new URL(this.HOST + '/account');
187
+ const params = { key: this.key };
188
+ url.search = new URLSearchParams(params).toString();
189
+ response = await this.fetch({
190
+ url: url.toString(),
191
+ method: 'GET',
192
+ headers: {
193
+ 'user-agent': this.ua,
194
+ 'accept-encoding': 'gzip, deflate, br',
195
+ accept: 'application/json',
196
+ },
197
+ });
198
+ } catch (e) {
199
+ log.error('error', e);
200
+ throw e;
201
+ }
202
+ const data: Rec<any> = await response.json() as Rec<any>;
203
+ if ('error_id' in data || Object.keys(data).length === 0) {
204
+ if (data.http_code == 401 || response.status == 401) {
205
+ throw new errors.BadApiKeyError(JSON.stringify(data));
206
+ }
207
+ throw new errors.ApiHttpClientError(JSON.stringify(data));
208
+ }
209
+ return data as AccountData;
210
+ }
211
+
212
+ /**
213
+ * Classify an already-fetched HTTP response for anti-bot blocking.
214
+ *
215
+ * Runs the same anti-bot detection pipeline used by live Scrapfly
216
+ * scrapes against a response you already have (from your own proxy,
217
+ * cache, etc). 1 API credit per call. See
218
+ * https://scrapfly.io/docs/scrape-api/classify for the full contract.
219
+ */
220
+ async classify(options: ClassifyOptions): Promise<ClassifyResult> {
221
+ if (!options || !options.url) {
222
+ throw new errors.ScrapflyError('classify: url is required');
223
+ }
224
+ if (
225
+ typeof options.statusCode !== 'number' ||
226
+ options.statusCode < 100 ||
227
+ options.statusCode > 599
228
+ ) {
229
+ throw new errors.ScrapflyError(
230
+ 'classify: status_code must be a valid HTTP status in [100, 599]',
231
+ );
232
+ }
233
+
234
+ const body: Rec<unknown> = {
235
+ url: options.url,
236
+ status_code: options.statusCode,
237
+ method: options.method ?? 'GET',
238
+ };
239
+ if (options.headers && Object.keys(options.headers).length > 0) {
240
+ const hdrs: Rec<string> = {};
241
+ for (const [k, v] of Object.entries(options.headers)) {
242
+ hdrs[String(k)] = String(v);
243
+ }
244
+ body.headers = hdrs;
245
+ }
246
+ if (options.body !== undefined && options.body !== null) {
247
+ body.body = options.body;
248
+ }
249
+
250
+ const url = new URL(this.HOST + '/classify');
251
+ url.search = new URLSearchParams({ key: this.key }).toString();
252
+
253
+ const response = await this.fetch({
254
+ url: url.toString(),
255
+ method: 'POST',
256
+ headers: {
257
+ 'user-agent': this.ua,
258
+ 'accept-encoding': 'gzip, deflate, br',
259
+ accept: 'application/json',
260
+ 'content-type': 'application/json',
261
+ },
262
+ body: JSON.stringify(body),
263
+ });
264
+
265
+ const data = (await response.json()) as Rec<unknown>;
266
+ if (response.status >= 400 || 'error_id' in data) {
267
+ if (response.status == 401) {
268
+ throw new errors.BadApiKeyError(JSON.stringify(data));
269
+ }
270
+ throw new errors.ApiHttpClientError(JSON.stringify(data));
271
+ }
272
+
273
+ return {
274
+ blocked: Boolean(data.blocked),
275
+ antibot: (data.antibot ?? null) as string | null,
276
+ cost: Number(data.cost ?? 0),
277
+ };
278
+ }
279
+
280
+ // ── Monitoring API (Enterprise+ plan only) ──────────────────────
281
+ // The Monitoring API exposes per-product aggregates and per-target
282
+ // timeseries. Web Scraping / Screenshot / Extraction / Crawler share
283
+ // one shape (request-based) but live under different URL prefixes;
284
+ // Cloud Browser is session-based and exposes a distinct shape.
285
+ // See https://scrapfly.io/docs/monitoring#api
286
+
287
+ private async monitoringRequest(path: string, params: Rec<string>): Promise<Rec<any>> {
288
+ const url = new URL(this.HOST + path);
289
+ url.search = new URLSearchParams(params).toString();
290
+ const response = await this.fetch({
291
+ url: url.toString(),
292
+ method: 'GET',
293
+ headers: {
294
+ 'user-agent': this.ua,
295
+ 'accept-encoding': 'gzip, deflate, br',
296
+ accept: 'application/json',
297
+ },
298
+ });
299
+ const data: Rec<any> = (await response.json()) as Rec<any>;
300
+ if ('error_id' in data) {
301
+ if (data.http_code == 401 || response.status == 401) {
302
+ throw new errors.BadApiKeyError(JSON.stringify(data));
303
+ }
304
+ throw new errors.ApiHttpClientError(JSON.stringify(data));
305
+ }
306
+ return data;
307
+ }
308
+
309
+ private buildMetricsParams(options: MonitoringMetricsOptions): Rec<string> {
310
+ const params: Rec<string> = {
311
+ key: this.key,
312
+ format: options.format ?? 'structured',
313
+ };
314
+ if (options.period !== undefined) params.period = options.period;
315
+ if (options.aggregation !== undefined && options.aggregation.length > 0) {
316
+ params.aggregation = options.aggregation.join(',');
317
+ }
318
+ if (options.includeWebhook) params.include_webhook = 'true';
319
+ return params;
320
+ }
321
+
322
+ private buildTargetParams(options: MonitoringTargetMetricsOptions): Rec<string> {
323
+ if ((options.start && !options.end) || (!options.start && options.end)) {
324
+ throw new Error('You must provide both start and end date');
325
+ }
326
+ const params: Rec<string> = {
327
+ key: this.key,
328
+ domain: options.domain,
329
+ group_subdomain: String(options.groupSubdomain ?? false),
330
+ };
331
+ if (options.start && options.end) {
332
+ params.start = formatMonitoringDate(options.start);
333
+ params.end = formatMonitoringDate(options.end);
334
+ } else if (options.period !== undefined) {
335
+ params.period = options.period;
336
+ } else {
337
+ params.period = 'last24h';
338
+ }
339
+ if (options.includeWebhook) params.include_webhook = 'true';
340
+ return params;
341
+ }
342
+
343
+ // ── Web Scraping API (existing — kept for backward compat) ──────
344
+ async getMonitoringMetrics(options: MonitoringMetricsOptions = {}): Promise<Rec<any>> {
345
+ return this.monitoringRequest('/scrape/monitoring/metrics', this.buildMetricsParams(options));
346
+ }
347
+
348
+ async getMonitoringTargetMetrics(options: MonitoringTargetMetricsOptions): Promise<Rec<any>> {
349
+ return this.monitoringRequest('/scrape/monitoring/metrics/target', this.buildTargetParams(options));
350
+ }
351
+
352
+ // ── Screenshot API ───────────────────────────────────────────────
353
+ async getScreenshotMonitoringMetrics(options: MonitoringMetricsOptions = {}): Promise<Rec<any>> {
354
+ return this.monitoringRequest('/screenshot/monitoring/metrics', this.buildMetricsParams(options));
355
+ }
356
+
357
+ async getScreenshotMonitoringTargetMetrics(options: MonitoringTargetMetricsOptions): Promise<Rec<any>> {
358
+ return this.monitoringRequest('/screenshot/monitoring/metrics/target', this.buildTargetParams(options));
359
+ }
360
+
361
+ // ── Extraction API ───────────────────────────────────────────────
362
+ async getExtractionMonitoringMetrics(options: MonitoringMetricsOptions = {}): Promise<Rec<any>> {
363
+ return this.monitoringRequest('/extraction/monitoring/metrics', this.buildMetricsParams(options));
364
+ }
365
+
366
+ async getExtractionMonitoringTargetMetrics(options: MonitoringTargetMetricsOptions): Promise<Rec<any>> {
367
+ return this.monitoringRequest('/extraction/monitoring/metrics/target', this.buildTargetParams(options));
368
+ }
369
+
370
+ // ── Crawler API ──────────────────────────────────────────────────
371
+ async getCrawlerMonitoringMetrics(options: MonitoringMetricsOptions = {}): Promise<Rec<any>> {
372
+ return this.monitoringRequest('/crawl/monitoring/metrics', this.buildMetricsParams(options));
373
+ }
374
+
375
+ async getCrawlerMonitoringTargetMetrics(options: MonitoringTargetMetricsOptions): Promise<Rec<any>> {
376
+ return this.monitoringRequest('/crawl/monitoring/metrics/target', this.buildTargetParams(options));
377
+ }
378
+
379
+ // ── Cloud Browser API (session-based, distinct shape) ────────────
380
+ async getBrowserMonitoringMetrics(
381
+ options: CloudBrowserMonitoringOptions = {},
382
+ ): Promise<Rec<any>> {
383
+ return this.monitoringRequest('/browser/monitoring/metrics', this.buildBrowserParams(options));
384
+ }
385
+
386
+ async getBrowserMonitoringTimeseries(
387
+ options: CloudBrowserMonitoringOptions = {},
388
+ ): Promise<Rec<any>> {
389
+ return this.monitoringRequest('/browser/monitoring/metrics/timeseries', this.buildBrowserParams(options));
390
+ }
391
+
392
+ private buildBrowserParams(options: CloudBrowserMonitoringOptions): Rec<string> {
393
+ if ((options.start && !options.end) || (!options.start && options.end)) {
394
+ throw new Error('You must provide both start and end date');
395
+ }
396
+ const params: Rec<string> = { key: this.key };
397
+ if (options.start && options.end) {
398
+ params.start = formatMonitoringDate(options.start);
399
+ params.end = formatMonitoringDate(options.end);
400
+ } else if (options.period !== undefined) {
401
+ params.period = options.period;
402
+ }
403
+ if (options.proxyPool !== undefined) params.proxy_pool = options.proxyPool;
404
+ return params;
405
+ }
406
+
407
+ /**
408
+ * Issue a single scrape command from a given scrape configuration
409
+ */
410
+ async scrape(config: ScrapeConfig): Promise<ScrapeResult | Response> {
411
+ log.debug('scraping', { method: config.method, url: config.url });
412
+ let response;
413
+ try {
414
+ const url = new URL(this.HOST + '/scrape');
415
+ const params = config.toApiParams({ key: this.key });
416
+ url.search = new URLSearchParams(params).toString();
417
+ response = await this.fetch({
418
+ url: url.toString(),
419
+ method: config.method,
420
+ headers: {
421
+ 'user-agent': this.ua,
422
+ 'content-type': config.method === 'POST'
423
+ ? config.headers?.['content-type'] ?? 'application/json'
424
+ : 'application/json',
425
+ 'accept-encoding': 'gzip, deflate, br',
426
+ accept: 'application/json',
427
+ },
428
+ body: config.body,
429
+ });
430
+ } catch (e) {
431
+ log.error('error', e);
432
+ // Attach the scrape config to the thrown error for debuggability.
433
+ // The error is typed as `unknown` since TypeScript 4.4 strict catch
434
+ // clause variables, so we narrow to a mutable object before tagging.
435
+ if (e !== null && typeof e === 'object') {
436
+ (e as Record<string, unknown>).scrapeConfig = config;
437
+ }
438
+ throw e;
439
+ }
440
+ // Proxified mode: the API returns the raw upstream response (target's
441
+ // status, headers, body) instead of the JSON envelope. Return the raw
442
+ // fetch Response so callers can drive it like any HTTP response.
443
+ //
444
+ // DO NOT throw on non-2xx: the response status is the UPSTREAM target's
445
+ // status, not a Scrapfly system error. A 503 from the target is a
446
+ // legitimate proxified response, not an API failure.
447
+ //
448
+ // Callers inspect:
449
+ // response.status — the upstream status
450
+ // response.headers.get("x-scrapfly-reject-code") — Scrapfly error (if any)
451
+ // response.headers.get("x-scrapfly-api-cost") — credits charged
452
+ if (config.proxified_response === true) {
453
+ // Error restoration: if X-Scrapfly-Reject-Code is present, the
454
+ // scrape failed. Reconstruct a typed error from the headers so
455
+ // callers get the same error interface as non-proxified mode.
456
+ const rejectCode = response.headers.get('x-scrapfly-reject-code');
457
+ if (rejectCode) {
458
+ const rejectDesc = response.headers.get('x-scrapfly-reject-description') ?? '';
459
+ const rejectRetryable = response.headers.get('x-scrapfly-reject-retryable') === 'true';
460
+ const retryAfter = rejectRetryable ? parseInt(response.headers.get('retry-after') ?? '0', 10) : 0;
461
+ const err = new errors.ApiHttpClientError(
462
+ `Proxified scrape error: ${rejectCode} — ${rejectDesc}`
463
+ );
464
+ (err as any).code = rejectCode;
465
+ (err as any).httpStatusCode = response.status;
466
+ (err as any).retryable = rejectRetryable;
467
+ (err as any).retryAfter = retryAfter;
468
+ (err as any).response = response;
469
+ throw err;
470
+ }
471
+ return response;
472
+ }
473
+ // HEAD responses have no body per HTTP spec — the API returns headers
474
+ // only. Build a ScrapeResult from the HTTP response headers and the
475
+ // local config, mirroring the Python SDK's HEAD handler.
476
+ if (config.method === 'HEAD') {
477
+ const responseHeaders: Record<string, string> = {};
478
+ response.headers.forEach((v, k) => { responseHeaders[k] = v; });
479
+ return this.handleResponse(
480
+ response,
481
+ new ScrapeResult({
482
+ config: config.toApiParams({ key: this.key }) as any,
483
+ context: {} as any,
484
+ result: {
485
+ status_code: response.status,
486
+ content: '',
487
+ format: 'text',
488
+ success: response.status >= 200 && response.status < 300,
489
+ status: 'DONE',
490
+ response_headers: responseHeaders,
491
+ request_headers: {},
492
+ } as any,
493
+ uuid: '',
494
+ }),
495
+ );
496
+ }
497
+ const data: Rec<any> = await response.json() as Rec<any>;
498
+ if ('error_id' in data || Object.keys(data).length === 0) {
499
+ if (data.http_code == 401 || response.status == 401) {
500
+ throw new errors.BadApiKeyError(JSON.stringify(data));
501
+ }
502
+ throw new errors.ApiHttpClientError(JSON.stringify(data));
503
+ }
504
+
505
+ const content_format = data.result.format;
506
+ if (content_format === 'clob' || content_format === 'blob') {
507
+ data.result = await this.handleLargeObjects(data.result, content_format);
508
+ }
509
+
510
+ const result = this.handleResponse(
511
+ response,
512
+ new ScrapeResult({
513
+ config: data.config,
514
+ context: data.context,
515
+ result: data.result,
516
+ uuid: data.uuid,
517
+ }),
518
+ );
519
+ return result;
520
+ }
521
+
522
+ /**
523
+ Concurrently scrape multiple configs
524
+ This is a async generator call it like this:
525
+
526
+ const results = [];
527
+ const errors = [];
528
+ for await (const resultOrError of client.concurrentScrape(configs)) {
529
+ if (resultOrError instanceof Error) {
530
+ errors.push(resultOrError);
531
+ } else {
532
+ results.push(resultOrError);
533
+ }
534
+ }
535
+
536
+ @param concurrencyLimit: if not set it will be taken from your account info
537
+ */
538
+ async *concurrentScrape(
539
+ configs: ScrapeConfig[],
540
+ concurrencyLimit?: number,
541
+ ): AsyncGenerator<ScrapeResult | Error | undefined, void, undefined> {
542
+ if (concurrencyLimit === undefined) {
543
+ const account = await this.account();
544
+ concurrencyLimit = account.subscription.usage.scrape.concurrent_limit;
545
+ log.info(`concurrency not provided - setting it to ${concurrencyLimit} from account info`);
546
+ }
547
+ const activePromises = new Set<Promise<ScrapeResult | Error>>();
548
+ const configsIterator = configs[Symbol.iterator]();
549
+
550
+ // Helper function to start a new scrape and add it to activePromises
551
+ const startNewScrape = () => {
552
+ const { value: config, done } = configsIterator.next();
553
+ if (done) return; // No more configs
554
+
555
+ const promise = this.scrape(config).catch((error) => error); // Catch errors and return them
556
+ activePromises.add(promise);
557
+
558
+ promise.finally(() => {
559
+ activePromises.delete(promise);
560
+ // After each scrape, start a new one if there are remaining configs
561
+ startNewScrape();
562
+ });
563
+ };
564
+
565
+ // Initially start as many scrapes as the concurrency limit
566
+ for (let i = 0; i < concurrencyLimit; i++) {
567
+ startNewScrape();
568
+ }
569
+
570
+ // As each scrape finishes, yield the result or error and start a new one if there are remaining configs
571
+ while (activePromises.size > 0) {
572
+ log.debug(`concurrently scraping ${activePromises.size}/${configs.length}}`);
573
+ const resultOrError = await Promise.race(activePromises);
574
+ yield resultOrError;
575
+ }
576
+ }
577
+
578
+ /**
579
+ * Issue a single batch request against POST /scrape/batch and
580
+ * stream results back as each scrape completes.
581
+ *
582
+ * Yields `[correlation_id, resultOrError]` tuples. Results arrive
583
+ * OUT OF ORDER — whichever scrape finishes first is yielded first.
584
+ * Every ScrapeConfig MUST carry a unique `correlation_id`; missing
585
+ * or duplicate values are caught client-side before the batch is
586
+ * sent (so callers fail fast on misconfiguration).
587
+ *
588
+ * Usage:
589
+ * for await (const [id, result] of client.scrapeBatch(configs)) {
590
+ * if (result instanceof errors.ScrapflyError) { ... }
591
+ * else { ... }
592
+ * }
593
+ */
594
+ async *scrapeBatch(
595
+ configs: ScrapeConfig[],
596
+ options: { format?: 'json' | 'msgpack' } = {},
597
+ ): AsyncGenerator<[string, ScrapeResult | Response | errors.ScrapflyError], void, undefined> {
598
+ const wireFormat = options.format ?? 'json';
599
+ const acceptHeader =
600
+ wireFormat === 'msgpack' ? 'application/msgpack' : 'application/json';
601
+ // Lazy-load the parser to avoid pulling Web Streams polyfills
602
+ // into the module graph for users who never call scrapeBatch.
603
+ const { iterBatchParts, decodePartBody, buildProxifiedResponseFromPart } = await import('./batch.js');
604
+
605
+ if (!configs || configs.length === 0) {
606
+ throw new errors.ScrapflyError('scrapeBatch: configs list is empty');
607
+ }
608
+ if (configs.length > 100) {
609
+ throw new errors.ScrapflyError(
610
+ `scrapeBatch: max 100 configs per batch (got ${configs.length})`,
611
+ );
612
+ }
613
+
614
+ const seen = new Map<string, number>();
615
+ const configByCorrelation = new Map<string, ScrapeConfig>();
616
+ const bodyConfigs: Record<string, unknown>[] = [];
617
+
618
+ for (let i = 0; i < configs.length; i++) {
619
+ const cfg = configs[i];
620
+ const correlationId = (cfg as unknown as Record<string, string>).correlation_id;
621
+ if (!correlationId) {
622
+ throw new errors.ScrapflyError(
623
+ `scrapeBatch: configs[${i}] is missing correlation_id (required for matching streamed parts)`,
624
+ );
625
+ }
626
+ if (seen.has(correlationId)) {
627
+ throw new errors.ScrapflyError(
628
+ `scrapeBatch: correlation_id ${JSON.stringify(correlationId)} reused by configs[${seen.get(correlationId)}] and configs[${i}]`,
629
+ );
630
+ }
631
+ seen.set(correlationId, i);
632
+ configByCorrelation.set(correlationId, cfg);
633
+
634
+ // Reuse toApiParams to guarantee wire parity with /scrape.
635
+ // Drop `key` (batch key is in the URL).
636
+ const params = cfg.toApiParams({ key: this.key }) as Record<string, unknown>;
637
+ delete params.key;
638
+ bodyConfigs.push(params);
639
+ }
640
+
641
+ const url = new URL(this.HOST + '/scrape/batch');
642
+ url.search = new URLSearchParams({ key: this.key }).toString();
643
+
644
+ const response = await this.fetch({
645
+ url: url.toString(),
646
+ method: 'POST',
647
+ headers: {
648
+ 'user-agent': this.ua,
649
+ 'content-type': 'application/json',
650
+ // gzip is universally supported in fetch runtimes; skip zstd
651
+ // for streaming compatibility (Node < 22 / browsers don't
652
+ // auto-decompress zstd yet).
653
+ 'accept-encoding': 'gzip',
654
+ accept: acceptHeader,
655
+ },
656
+ body: JSON.stringify({ configs: bodyConfigs }),
657
+ });
658
+
659
+ if (response.status !== 200) {
660
+ const body = await response.text();
661
+ let parsed: Record<string, unknown>;
662
+ try {
663
+ parsed = JSON.parse(body);
664
+ } catch {
665
+ parsed = { message: body, code: 'ERR::API::INTERNAL_ERROR' };
666
+ }
667
+ throw new errors.ApiHttpServerError(
668
+ `scrapeBatch: ${parsed.code ?? 'error'} (HTTP ${response.status}): ${parsed.message ?? body}`,
669
+ );
670
+ }
671
+
672
+ for await (const part of iterBatchParts(response)) {
673
+ const correlationId = part.headers['x-scrapfly-correlation-id'] ?? '';
674
+
675
+ // Proxified-response parts: the part body is the raw upstream
676
+ // bytes, not a JSON envelope. Surface a native fetch Response
677
+ // so callers get the same shape as a single proxified scrape
678
+ // (which returns Response from .scrape()).
679
+ if (part.headers['x-scrapfly-proxified'] === 'true') {
680
+ try {
681
+ const proxResponse = buildProxifiedResponseFromPart(part);
682
+ yield [correlationId, proxResponse];
683
+ } catch (proxErr) {
684
+ yield [
685
+ correlationId,
686
+ new errors.ScrapflyError(
687
+ `scrapeBatch: failed to build proxified response for correlation_id=${JSON.stringify(correlationId)}: ${proxErr}`,
688
+ ),
689
+ ];
690
+ }
691
+ continue;
692
+ }
693
+
694
+ let parsed: Record<string, unknown>;
695
+ try {
696
+ parsed = decodePartBody(part);
697
+ } catch (decodeErr) {
698
+ yield [
699
+ correlationId,
700
+ new errors.ScrapflyError(
701
+ `scrapeBatch: failed to decode part for correlation_id=${JSON.stringify(correlationId)}: ${decodeErr}`,
702
+ ),
703
+ ];
704
+ continue;
705
+ }
706
+
707
+ try {
708
+ const result = new ScrapeResult({
709
+ config: (parsed as any).config,
710
+ context: (parsed as any).context,
711
+ result: (parsed as any).result,
712
+ uuid: (parsed as any).uuid,
713
+ });
714
+ yield [correlationId, result];
715
+ } catch (resultErr) {
716
+ yield [
717
+ correlationId,
718
+ resultErr instanceof errors.ScrapflyError
719
+ ? resultErr
720
+ : new errors.ScrapflyError(`scrapeBatch: ${resultErr}`),
721
+ ];
722
+ }
723
+ }
724
+ }
725
+
726
+ /**
727
+ * Save screenshot response to a file
728
+ */
729
+ async saveScreenshot(result: ScreenshotResult, name: string, savePath?: string): Promise<any> {
730
+ if (!result.image) {
731
+ throw new Error('Screenshot binary does not exist');
732
+ }
733
+
734
+ const extension_name = result.metadata.extension_name;
735
+ let file_path;
736
+
737
+ if (savePath) {
738
+ await mkdir(savePath, { recursive: true });
739
+ file_path = path.join(savePath, `${name}.${extension_name}`);
740
+ } else {
741
+ file_path = `${name}.${extension_name}`;
742
+ }
743
+
744
+ const content = new Uint8Array(result.image);
745
+
746
+ // Use Deno's write file method
747
+ await writeFile(file_path, content);
748
+ }
749
+
750
+ /**
751
+ * Turn scrapfly screenshot API response to ScreenshotResult or raise one of ScrapflyError
752
+ */
753
+ async handleScreenshotResponse(response: Response): Promise<ScreenshotResult> {
754
+ // A Response body can only be consumed once. If the server returned
755
+ // JSON, parse it up front and reuse it on the error path — re-reading
756
+ // would yield "body stream already read" and mask the real error.
757
+ const isJson = response.headers.get('content-type') === 'application/json';
758
+ let jsonData: Rec<any> | null = null;
759
+ if (isJson) {
760
+ jsonData = (await response.json()) as Rec<any>;
761
+ if (jsonData.http_code == 401 || response.status == 401) {
762
+ throw new errors.BadApiKeyError(JSON.stringify(jsonData));
763
+ }
764
+ if ('error_id' in jsonData) {
765
+ throw new errors.ScreenshotApiError(JSON.stringify(jsonData));
766
+ }
767
+ }
768
+ if (!response.ok) {
769
+ const body = jsonData ?? (await response.text());
770
+ throw new errors.ScreenshotApiError(
771
+ typeof body === 'string' ? body : JSON.stringify(body),
772
+ );
773
+ }
774
+ const data = await response.arrayBuffer();
775
+ const result = new ScreenshotResult(response, data);
776
+ return result;
777
+ }
778
+
779
+ /**
780
+ * Take a screenshot
781
+ */
782
+ async screenshot(config: ScreenshotConfig): Promise<ScreenshotResult> {
783
+ let response;
784
+ try {
785
+ const url = new URL(this.HOST + '/screenshot');
786
+ const params = config.toApiParams({ key: this.key });
787
+ url.search = new URLSearchParams(params).toString();
788
+ response = await this.fetch({
789
+ url: url.toString(),
790
+ method: 'GET',
791
+ headers: {
792
+ 'user-agent': this.ua,
793
+ 'accept-encoding': 'gzip, deflate, br',
794
+ accept: 'application/json',
795
+ },
796
+ });
797
+ } catch (e) {
798
+ log.error('error', e);
799
+ throw e;
800
+ }
801
+ const result = await this.handleScreenshotResponse(response);
802
+ return result;
803
+ }
804
+
805
+ /**
806
+ * Turn scrapfly Extraction API response to ExtractionResult or raise one of ScrapflyError
807
+ */
808
+ async handleExtractionResponse(response: Response): Promise<ExtractionResult> {
809
+ // Body can only be consumed once — reuse the parsed JSON on the
810
+ // error path instead of re-reading, which would fail with
811
+ // "body stream already read".
812
+ const data: Rec<any> = (await response.json()) as Rec<any>;
813
+ if ('error_id' in data) {
814
+ if (data.http_code == 401 || response.status == 401) {
815
+ throw new errors.BadApiKeyError(JSON.stringify(data));
816
+ }
817
+ throw new errors.ExtractionApiError(JSON.stringify(data));
818
+ }
819
+ if (!response.ok) {
820
+ throw new errors.ApiHttpClientError(JSON.stringify(data));
821
+ }
822
+ const result = new ExtractionResult({
823
+ data: data.data,
824
+ content_type: data.content_type,
825
+ });
826
+ return result;
827
+ }
828
+
829
+ /**
830
+ * Extract structured data from a web page
831
+ */
832
+ async extract(config: ExtractionConfig): Promise<ExtractionResult> {
833
+ log.debug('extacting data from', { content_type: config.content_type });
834
+ let response;
835
+ try {
836
+ const url = new URL(this.HOST + '/extraction');
837
+ const params = config.toApiParams({ key: this.key });
838
+ url.search = new URLSearchParams(params).toString();
839
+ const headers: Record<string, string> = {
840
+ 'user-agent': this.ua,
841
+ 'accept-encoding': 'gzip, deflate, br',
842
+ 'content-type': config.content_type,
843
+ 'accept': 'application/json',
844
+ };
845
+ if (config.document_compression_format && config.document_compression_format) {
846
+ headers['content-encoding'] = config.document_compression_format;
847
+ }
848
+ response = await this.fetch({
849
+ url: url.toString(),
850
+ method: 'POST',
851
+ headers: headers,
852
+ body: config.body,
853
+ });
854
+ } catch (e) {
855
+ log.error('error', e);
856
+ throw e;
857
+ }
858
+ const result = await this.handleExtractionResponse(response);
859
+ return result;
860
+ }
861
+
862
+ // ---------------------------------------------------------------------------
863
+ // Crawler API
864
+ // ---------------------------------------------------------------------------
865
+
866
+ /**
867
+ * Throw a typed error for a crawler JSON error envelope.
868
+ *
869
+ * The crawler endpoints (status, urls, contents, artifact, cancel) return either
870
+ * a clean JSON body on success or an error envelope `{error_id, http_code, message, ...}`.
871
+ * Use this to map the envelope to one of `BadApiKeyError` / `ScrapflyCrawlerError` /
872
+ * `ApiHttpClientError`.
873
+ */
874
+ private throwCrawlerError(response: Response, data: Rec<any>): never {
875
+ const httpCode = data.http_code ?? response.status;
876
+ const code = (data.code ?? '') as string;
877
+ const message = data.message ?? JSON.stringify(data);
878
+ if (httpCode === 401) {
879
+ throw new errors.BadApiKeyError(message, { http_status_code: httpCode, code, api_response: data });
880
+ }
881
+ if (httpCode === 429) {
882
+ throw new errors.TooManyRequests(message, { http_status_code: httpCode, code, api_response: data });
883
+ }
884
+ // Any ERR::CRAWLER::* code → typed crawler error
885
+ if (typeof code === 'string' && code.includes('::CRAWLER::')) {
886
+ throw new errors.ScrapflyCrawlerError(message, { http_status_code: httpCode, code, api_response: data });
887
+ }
888
+ throw new errors.ApiHttpClientError(message, { http_status_code: httpCode, code, api_response: data });
889
+ }
890
+
891
+ /**
892
+ * Schedule a new crawler job.
893
+ *
894
+ * `POST /crawl` — returns `{crawler_uuid, status}` on success. On failure throws
895
+ * `ScrapflyCrawlerError`, `BadApiKeyError`, or `ApiHttpClientError`.
896
+ */
897
+ async crawl(config: CrawlerConfig): Promise<{ crawler_uuid: string; status: string }> {
898
+ log.debug('crawling', { url: config.url });
899
+ let response: Response;
900
+ try {
901
+ const url = new URL(this.HOST + '/crawl');
902
+ url.search = new URLSearchParams({ key: this.key }).toString();
903
+ response = await this.fetch({
904
+ url: url.toString(),
905
+ method: 'POST',
906
+ headers: {
907
+ 'user-agent': this.ua,
908
+ 'content-type': 'application/json',
909
+ 'accept-encoding': 'gzip, deflate, br',
910
+ accept: 'application/json',
911
+ },
912
+ body: JSON.stringify(config.toApiParams()),
913
+ });
914
+ } catch (e) {
915
+ log.error('error', e);
916
+ throw e;
917
+ }
918
+ const data: Rec<any> = (await response.json()) as Rec<any>;
919
+ if ('error_id' in data || data.http_code !== undefined) {
920
+ this.throwCrawlerError(response, data);
921
+ }
922
+ if (typeof data.uuid !== 'string' && typeof data.crawler_uuid !== 'string') {
923
+ throw new errors.ApiHttpClientError(
924
+ `Crawler API returned no uuid: ${JSON.stringify(data).slice(0, 500)}`,
925
+ );
926
+ }
927
+ return {
928
+ crawler_uuid: (data.crawler_uuid ?? data.uuid) as string,
929
+ status: (data.status ?? 'PENDING') as string,
930
+ };
931
+ }
932
+
933
+ /**
934
+ * Get the current status of a crawler job.
935
+ *
936
+ * `GET /crawl/{uuid}/status`
937
+ */
938
+ async crawlStatus(uuid: string): Promise<CrawlerStatus> {
939
+ let response: Response;
940
+ try {
941
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/status`);
942
+ url.search = new URLSearchParams({ key: this.key }).toString();
943
+ response = await this.fetch({
944
+ url: url.toString(),
945
+ method: 'GET',
946
+ headers: {
947
+ 'user-agent': this.ua,
948
+ 'accept-encoding': 'gzip, deflate, br',
949
+ accept: 'application/json',
950
+ },
951
+ });
952
+ } catch (e) {
953
+ log.error('error', e);
954
+ throw e;
955
+ }
956
+ const data: Rec<any> = (await response.json()) as Rec<any>;
957
+ if ('error_id' in data || data.http_code !== undefined) {
958
+ this.throwCrawlerError(response, data);
959
+ }
960
+ return new CrawlerStatus(data);
961
+ }
962
+
963
+ /**
964
+ * List crawled URLs for a job, optionally filtered by status and paginated.
965
+ *
966
+ * `GET /crawl/{uuid}/urls?status=<filter>&page=<n>&per_page=<n>`
967
+ *
968
+ * The server streams the response as `text/plain` — one record per line.
969
+ * JSON is intentionally NOT used here because this endpoint is expected to
970
+ * scale to millions of URLs per job, and materialising that as JSON would
971
+ * be prohibitively expensive on both the server and the client. See
972
+ * {@link CrawlerUrls.fromText} for the exact line format.
973
+ *
974
+ * Pagination: the wire protocol carries no global `total`. Request further
975
+ * pages by incrementing `page` until a response contains no records.
976
+ */
977
+ async crawlUrls(
978
+ uuid: string,
979
+ opts?: { status?: 'visited' | 'pending' | 'failed' | 'skipped'; page?: number; per_page?: number },
980
+ ): Promise<CrawlerUrls> {
981
+ const statusHint = opts?.status ?? 'visited';
982
+ const page = opts?.page ?? 1;
983
+ const perPage = opts?.per_page ?? 100;
984
+
985
+ let response: Response;
986
+ try {
987
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/urls`);
988
+ const params: Record<string, string> = { key: this.key };
989
+ if (opts?.status) params.status = opts.status;
990
+ if (opts?.page !== undefined) params.page = String(opts.page);
991
+ if (opts?.per_page !== undefined) params.per_page = String(opts.per_page);
992
+ url.search = new URLSearchParams(params).toString();
993
+ response = await this.fetch({
994
+ url: url.toString(),
995
+ method: 'GET',
996
+ headers: {
997
+ 'user-agent': this.ua,
998
+ 'accept-encoding': 'gzip, deflate, br',
999
+ // text/plain is the canonical format; we also accept JSON because
1000
+ // error envelopes come back as JSON regardless of the success type.
1001
+ accept: 'text/plain, application/json',
1002
+ },
1003
+ });
1004
+ } catch (e) {
1005
+ log.error('error', e);
1006
+ throw e;
1007
+ }
1008
+
1009
+ // Error envelopes are always JSON, even for text endpoints. Detect by
1010
+ // content-type before consuming the body as text.
1011
+ const ct = response.headers.get('content-type') ?? '';
1012
+ if (ct.includes('application/json')) {
1013
+ const data: Rec<any> = (await response.json()) as Rec<any>;
1014
+ if ('error_id' in data || data.http_code !== undefined) {
1015
+ this.throwCrawlerError(response, data);
1016
+ }
1017
+ // Unexpected: the server sent JSON on a success response for the text
1018
+ // endpoint. Surface this as a client error so users see the mismatch
1019
+ // instead of getting silent empty results.
1020
+ throw new errors.ApiHttpClientError(
1021
+ `crawlUrls expected text/plain, got JSON: ${JSON.stringify(data).slice(0, 500)}`,
1022
+ );
1023
+ }
1024
+
1025
+ const body = await response.text();
1026
+ return CrawlerUrls.fromText(body, statusHint, page, perPage);
1027
+ }
1028
+
1029
+ /**
1030
+ * Get crawled content from a crawler job.
1031
+ *
1032
+ * Two modes:
1033
+ *
1034
+ * 1. **JSON mode** (default, `plain` omitted or false): returns a {@link CrawlerContents}
1035
+ * with a `contents` map (URL → format → content) and pagination links. Useful for
1036
+ * bulk retrieval. Honors `limit` (max 50, default 10) and `offset`.
1037
+ *
1038
+ * 2. **Plain mode** (`plain: true`): returns the raw content for a single URL/format
1039
+ * as a `string`, with content-type matching the format. Requires `url`. Useful for
1040
+ * piping markdown/text directly. **New in this SDK** (not in Python SDK as of 0.8.27).
1041
+ *
1042
+ * `GET /crawl/{uuid}/contents`
1043
+ */
1044
+ async crawlContents(
1045
+ uuid: string,
1046
+ opts: {
1047
+ format: CrawlerContentFormat;
1048
+ url?: string;
1049
+ plain?: boolean;
1050
+ limit?: number;
1051
+ offset?: number;
1052
+ },
1053
+ ): Promise<CrawlerContents | string> {
1054
+ if (opts.plain && !opts.url) {
1055
+ throw new errors.CrawlerConfigError('plain=true requires a single `url` argument');
1056
+ }
1057
+ let response: Response;
1058
+ try {
1059
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/contents`);
1060
+ // Note: the server query param is `formats` (plural), not `format`. The
1061
+ // public docs say `format` but the actual server only accepts `formats`.
1062
+ // We expose `format` (singular) as the SDK option since that's what users
1063
+ // expect from the docs, and translate it here.
1064
+ const params: Record<string, string> = { key: this.key, formats: opts.format };
1065
+ if (opts.url) params.url = opts.url;
1066
+ if (opts.plain) params.plain = 'true';
1067
+ if (opts.limit !== undefined) params.limit = String(opts.limit);
1068
+ if (opts.offset !== undefined) params.offset = String(opts.offset);
1069
+ url.search = new URLSearchParams(params).toString();
1070
+ response = await this.fetch({
1071
+ url: url.toString(),
1072
+ method: 'GET',
1073
+ headers: {
1074
+ 'user-agent': this.ua,
1075
+ 'accept-encoding': 'gzip, deflate, br',
1076
+ // In plain mode the server returns the raw content with a format-matching
1077
+ // content-type (text/markdown, text/html, etc.); accept anything.
1078
+ accept: opts.plain ? '*/*' : 'application/json',
1079
+ },
1080
+ });
1081
+ } catch (e) {
1082
+ log.error('error', e);
1083
+ throw e;
1084
+ }
1085
+
1086
+ if (opts.plain) {
1087
+ // Plain mode: server returns raw text. Error envelopes still come back as JSON,
1088
+ // so detect that by content-type before reading the body as text.
1089
+ const ct = response.headers.get('content-type') ?? '';
1090
+ if (ct.includes('application/json')) {
1091
+ const data: Rec<any> = (await response.json()) as Rec<any>;
1092
+ if ('error_id' in data || data.http_code !== undefined) {
1093
+ this.throwCrawlerError(response, data);
1094
+ }
1095
+ // JSON came back without an error envelope — caller asked for plain but server
1096
+ // returned JSON anyway (e.g. format=json). Stringify so the return type is stable.
1097
+ return JSON.stringify(data);
1098
+ }
1099
+ return await response.text();
1100
+ }
1101
+
1102
+ const data: Rec<any> = (await response.json()) as Rec<any>;
1103
+ if ('error_id' in data || data.http_code !== undefined) {
1104
+ this.throwCrawlerError(response, data);
1105
+ }
1106
+ return new CrawlerContents(data);
1107
+ }
1108
+
1109
+ /**
1110
+ * Batch-retrieve crawled content for up to 100 URLs in one round-trip.
1111
+ *
1112
+ * `POST /crawl/{uuid}/contents/batch`
1113
+ *
1114
+ * The request body is a newline-separated list of URLs (`text/plain`). The response
1115
+ * is a `multipart/related` (RFC 2387) document with one part per found URL. Each
1116
+ * part has `Content-Type` (matching the format) and `Content-Location` (the URL).
1117
+ *
1118
+ * Returns a map of `url → format → content`. Formats not requested for a given URL
1119
+ * are simply absent from its inner map.
1120
+ */
1121
+ async crawlContentsBatch(
1122
+ uuid: string,
1123
+ urls: string[],
1124
+ formats: CrawlerContentFormat[],
1125
+ ): Promise<Record<string, Record<string, string>>> {
1126
+ if (urls.length === 0) {
1127
+ throw new errors.CrawlerConfigError('crawlContentsBatch requires at least one url');
1128
+ }
1129
+ if (urls.length > 100) {
1130
+ throw new errors.CrawlerConfigError('crawlContentsBatch is limited to 100 urls per request');
1131
+ }
1132
+ if (formats.length === 0) {
1133
+ throw new errors.CrawlerConfigError('crawlContentsBatch requires at least one format');
1134
+ }
1135
+ let response: Response;
1136
+ try {
1137
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/contents/batch`);
1138
+ url.search = new URLSearchParams({ key: this.key, formats: formats.join(',') }).toString();
1139
+ response = await this.fetch({
1140
+ url: url.toString(),
1141
+ method: 'POST',
1142
+ headers: {
1143
+ 'user-agent': this.ua,
1144
+ 'content-type': 'text/plain',
1145
+ 'accept-encoding': 'gzip, deflate, br',
1146
+ accept: 'multipart/related, application/json',
1147
+ },
1148
+ body: urls.join('\n'),
1149
+ });
1150
+ } catch (e) {
1151
+ log.error('error', e);
1152
+ throw e;
1153
+ }
1154
+
1155
+ const ct = response.headers.get('content-type') ?? '';
1156
+ if (ct.includes('application/json')) {
1157
+ // Error envelope
1158
+ const data: Rec<any> = (await response.json()) as Rec<any>;
1159
+ if ('error_id' in data || data.http_code !== undefined) {
1160
+ this.throwCrawlerError(response, data);
1161
+ }
1162
+ throw new errors.ApiHttpClientError(
1163
+ `crawlContentsBatch expected multipart/related, got JSON: ${JSON.stringify(data).slice(0, 500)}`,
1164
+ );
1165
+ }
1166
+
1167
+ const text = await response.text();
1168
+ return parseMultipartRelated(text, ct, formats);
1169
+ }
1170
+
1171
+ /**
1172
+ * Download a crawler job's WARC or HAR artifact as raw bytes.
1173
+ *
1174
+ * `GET /crawl/{uuid}/artifact?type=warc|har`
1175
+ *
1176
+ * The SDK does NOT bundle WARC/HAR parsers — use a dedicated library (e.g. `warcio`
1177
+ * on npm) to walk the records. The returned {@link CrawlerArtifact} provides a
1178
+ * `save(path)` helper for the common case of writing the artifact to disk.
1179
+ */
1180
+ async crawlArtifact(uuid: string, type: CrawlerArtifactType = 'warc'): Promise<CrawlerArtifact> {
1181
+ let response: Response;
1182
+ try {
1183
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/artifact`);
1184
+ url.search = new URLSearchParams({ key: this.key, type }).toString();
1185
+ response = await this.fetch({
1186
+ url: url.toString(),
1187
+ method: 'GET',
1188
+ headers: {
1189
+ 'user-agent': this.ua,
1190
+ // Accept the artifact's binary content type plus JSON for error envelopes
1191
+ accept: type === 'har' ? 'application/json, application/octet-stream' : 'application/gzip, application/octet-stream',
1192
+ },
1193
+ });
1194
+ } catch (e) {
1195
+ log.error('error', e);
1196
+ throw e;
1197
+ }
1198
+
1199
+ // Error envelope check (server returns JSON on errors regardless of artifact type)
1200
+ const ct = response.headers.get('content-type') ?? '';
1201
+ if (ct.includes('application/json') && type !== 'har') {
1202
+ // For warc, JSON responses are always errors. For har, JSON IS the artifact —
1203
+ // we need to peek at the body to distinguish.
1204
+ const data: Rec<any> = (await response.json()) as Rec<any>;
1205
+ if ('error_id' in data || data.http_code !== undefined) {
1206
+ this.throwCrawlerError(response, data);
1207
+ }
1208
+ // Should not reach here for warc; treat as unexpected JSON.
1209
+ throw new errors.ApiHttpClientError(
1210
+ `crawlArtifact(${type}) expected binary, got JSON: ${JSON.stringify(data).slice(0, 500)}`,
1211
+ );
1212
+ }
1213
+
1214
+ const buf = new Uint8Array(await response.arrayBuffer());
1215
+
1216
+ // For HAR, the body IS JSON — but we still need to detect error envelopes
1217
+ // (which set http_code or error_id at the top level of the JSON object).
1218
+ if (type === 'har') {
1219
+ try {
1220
+ const text = new TextDecoder().decode(buf);
1221
+ const parsed = JSON.parse(text) as Rec<any>;
1222
+ if ('error_id' in parsed || parsed.http_code !== undefined) {
1223
+ this.throwCrawlerError(response, parsed);
1224
+ }
1225
+ } catch (e) {
1226
+ // If JSON parse fails, the body is not an error envelope — treat as raw HAR bytes.
1227
+ if (e instanceof errors.ScrapflyError) throw e;
1228
+ }
1229
+ }
1230
+
1231
+ return new CrawlerArtifact(type, buf);
1232
+ }
1233
+
1234
+ /**
1235
+ * Cancel a running crawler job.
1236
+ *
1237
+ * `POST /crawl/{uuid}/cancel` — returns `true` on success. The endpoint
1238
+ * is idempotent: cancelling a crawl that has already finished is a no-op
1239
+ * and still returns success.
1240
+ *
1241
+ * Note: earlier versions of this SDK called `DELETE /crawl/{uuid}`, which
1242
+ * is not a valid public route — that path silently 404'd against the
1243
+ * public API. Fixed in 0.8.0 to use the correct documented endpoint.
1244
+ */
1245
+ async crawlCancel(uuid: string): Promise<boolean> {
1246
+ let response: Response;
1247
+ try {
1248
+ const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/cancel`);
1249
+ url.search = new URLSearchParams({ key: this.key }).toString();
1250
+ response = await this.fetch({
1251
+ url: url.toString(),
1252
+ method: 'POST',
1253
+ headers: {
1254
+ 'user-agent': this.ua,
1255
+ 'accept-encoding': 'gzip, deflate, br',
1256
+ accept: 'application/json',
1257
+ },
1258
+ });
1259
+ } catch (e) {
1260
+ log.error('error', e);
1261
+ throw e;
1262
+ }
1263
+ // Empty body or JSON
1264
+ const ct = response.headers.get('content-type') ?? '';
1265
+ if (ct.includes('application/json')) {
1266
+ const data: Rec<any> = (await response.json()) as Rec<any>;
1267
+ if ('error_id' in data || data.http_code !== undefined) {
1268
+ this.throwCrawlerError(response, data);
1269
+ }
1270
+ }
1271
+ return response.ok;
1272
+ }
1273
+ // --- Cloud Browser ---
1274
+
1275
+ /**
1276
+ * Get the WebSocket URL for a Cloud Browser session.
1277
+ */
1278
+ cloudBrowser(config?: BrowserConfig): string {
1279
+ const browserConfig = config || new BrowserConfig();
1280
+ return browserConfig.websocketUrl(this.key, this.cloudBrowserHost);
1281
+ }
1282
+
1283
+ /**
1284
+ * Call the Cloud Browser Unblock API.
1285
+ */
1286
+ async cloudBrowserUnblock(options: {
1287
+ url: string;
1288
+ proxy_pool?: string;
1289
+ country?: string;
1290
+ os?: string;
1291
+ timeout?: number;
1292
+ browser_timeout?: number;
1293
+ headers?: Record<string, string>;
1294
+ body?: string;
1295
+ method?: string;
1296
+ enable_mcp?: boolean;
1297
+ }): Promise<{ ws_url: string; session_id: string; run_id: string; mcp_endpoint?: string }> {
1298
+ const proxyPoolMap: Record<string, string> = {
1299
+ datacenter: 'public_datacenter_pool',
1300
+ residential: 'public_residential_pool',
1301
+ };
1302
+
1303
+ const jsonBody: Record<string, unknown> = { url: options.url };
1304
+ if (options.proxy_pool) jsonBody.proxy_pool = proxyPoolMap[options.proxy_pool] || options.proxy_pool;
1305
+ if (options.country) jsonBody.country = options.country;
1306
+ if (options.os) jsonBody.os = options.os;
1307
+ if (options.timeout) jsonBody.timeout = options.timeout;
1308
+ if (options.browser_timeout) jsonBody.browser_timeout = options.browser_timeout;
1309
+ if (options.headers) jsonBody.headers = options.headers;
1310
+ if (options.body) jsonBody.body = options.body;
1311
+ if (options.method) jsonBody.method = options.method;
1312
+ if (options.enable_mcp !== undefined) jsonBody.enable_mcp = options.enable_mcp;
1313
+
1314
+ const url = new URL(this.cloudBrowserApiHost + '/unblock');
1315
+ url.searchParams.set('key', this.key);
1316
+
1317
+ const response = await this.fetch({
1318
+ url: url.toString(),
1319
+ method: 'POST',
1320
+ headers: {
1321
+ 'content-type': 'application/json',
1322
+ 'user-agent': this.ua,
1323
+ },
1324
+ body: JSON.stringify(jsonBody),
1325
+ });
1326
+
1327
+ if (!response.ok) {
1328
+ throw new Error(`Unblock failed: ${response.status} ${await response.text()}`);
1329
+ }
1330
+ return await response.json() as { ws_url: string; session_id: string; run_id: string };
1331
+ }
1332
+
1333
+ /**
1334
+ * Stop a Cloud Browser session.
1335
+ */
1336
+ async cloudBrowserSessionStop(sessionId: string): Promise<void> {
1337
+ const url = new URL(this.cloudBrowserApiHost + '/session/' + sessionId + '/stop');
1338
+ url.searchParams.set('key', this.key);
1339
+
1340
+ const response = await this.fetch({
1341
+ url: url.toString(),
1342
+ method: 'POST',
1343
+ headers: { 'user-agent': this.ua },
1344
+ });
1345
+
1346
+ if (!response.ok) {
1347
+ throw new Error(`Session stop failed: ${response.status} ${await response.text()}`);
1348
+ }
1349
+ }
1350
+
1351
+ /**
1352
+ * List all browser extensions.
1353
+ */
1354
+ async cloudBrowserExtensionList(): Promise<{ extensions: any[]; quota: { used: number; limit: number } }> {
1355
+ const url = new URL(this.cloudBrowserApiHost + '/extension');
1356
+ url.searchParams.set('key', this.key);
1357
+
1358
+ const response = await this.fetch({
1359
+ url: url.toString(),
1360
+ method: 'GET',
1361
+ headers: { 'user-agent': this.ua },
1362
+ });
1363
+
1364
+ if (!response.ok) {
1365
+ throw new Error(`Extension list failed: ${response.status} ${await response.text()}`);
1366
+ }
1367
+ return await response.json() as { extensions: any[]; quota: { used: number; limit: number } };
1368
+ }
1369
+
1370
+ /**
1371
+ * Delete a browser extension.
1372
+ */
1373
+ async cloudBrowserExtensionDelete(extensionId: string): Promise<{ success: boolean; message: string }> {
1374
+ const url = new URL(this.cloudBrowserApiHost + '/extension/' + extensionId);
1375
+ url.searchParams.set('key', this.key);
1376
+
1377
+ const response = await this.fetch({
1378
+ url: url.toString(),
1379
+ method: 'DELETE',
1380
+ headers: { 'user-agent': this.ua },
1381
+ });
1382
+
1383
+ if (!response.ok) {
1384
+ throw new Error(`Extension delete failed: ${response.status} ${await response.text()}`);
1385
+ }
1386
+ return await response.json() as { success: boolean; message: string };
1387
+ }
1388
+
1389
+ /**
1390
+ * Get details of a specific browser extension.
1391
+ */
1392
+ async cloudBrowserExtensionGet(extensionId: string): Promise<Record<string, any>> {
1393
+ const url = new URL(this.cloudBrowserApiHost + '/extension/' + extensionId);
1394
+ url.searchParams.set('key', this.key);
1395
+
1396
+ const response = await this.fetch({
1397
+ url: url.toString(),
1398
+ method: 'GET',
1399
+ headers: { 'user-agent': this.ua },
1400
+ });
1401
+
1402
+ if (!response.ok) {
1403
+ throw new Error(`Extension get failed: ${response.status} ${await response.text()}`);
1404
+ }
1405
+ return await response.json() as Record<string, any>;
1406
+ }
1407
+
1408
+ /**
1409
+ * Upload a browser extension from a local file (.zip or .crx).
1410
+ * Pass a file path — the file is read and sent as multipart/form-data.
1411
+ */
1412
+ async cloudBrowserExtensionUpload(filePath: string): Promise<{ extension: Record<string, any>; is_update: boolean }> {
1413
+ const fileBytes = readFileSync(filePath);
1414
+ const fileName = filePath.split('/').pop() || filePath.split('\\').pop() || 'extension.zip';
1415
+ const boundary = '----ScrapflyBoundary' + Date.now();
1416
+
1417
+ const encoder = new TextEncoder();
1418
+ const header = encoder.encode(
1419
+ `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${fileName}"\r\nContent-Type: application/octet-stream\r\n\r\n`
1420
+ );
1421
+ const footer = encoder.encode(`\r\n--${boundary}--\r\n`);
1422
+
1423
+ const body = new Uint8Array(header.length + fileBytes.length + footer.length);
1424
+ body.set(header, 0);
1425
+ body.set(fileBytes, header.length);
1426
+ body.set(footer, header.length + fileBytes.length);
1427
+
1428
+ const url = new URL(this.cloudBrowserApiHost + '/extension');
1429
+ url.searchParams.set('key', this.key);
1430
+
1431
+ const response = await this.fetch({
1432
+ url: url.toString(),
1433
+ method: 'POST',
1434
+ headers: {
1435
+ 'content-type': `multipart/form-data; boundary=${boundary}`,
1436
+ 'user-agent': this.ua,
1437
+ },
1438
+ body: body,
1439
+ });
1440
+
1441
+ if (!response.ok) {
1442
+ throw new Error(`Extension upload failed: ${response.status} ${await response.text()}`);
1443
+ }
1444
+ return await response.json() as { extension: Record<string, any>; is_update: boolean };
1445
+ }
1446
+
1447
+ /**
1448
+ * Install a browser extension from a URL (.crx file).
1449
+ * URL-based extensions auto-update on each browser session start.
1450
+ */
1451
+ async cloudBrowserExtensionUploadFromUrl(extensionUrl: string): Promise<{ extension: Record<string, any>; is_update: boolean }> {
1452
+ const url = new URL(this.cloudBrowserApiHost + '/extension');
1453
+ url.searchParams.set('key', this.key);
1454
+
1455
+ const response = await this.fetch({
1456
+ url: url.toString(),
1457
+ method: 'POST',
1458
+ headers: {
1459
+ 'content-type': 'application/json',
1460
+ 'user-agent': this.ua,
1461
+ },
1462
+ body: JSON.stringify({ extension_url: extensionUrl }),
1463
+ });
1464
+
1465
+ if (!response.ok) {
1466
+ throw new Error(`Extension upload from URL failed: ${response.status} ${await response.text()}`);
1467
+ }
1468
+ return await response.json() as { extension: Record<string, any>; is_update: boolean };
1469
+ }
1470
+
1471
+ /**
1472
+ * Download a debug session recording video.
1473
+ * Returns the video as an ArrayBuffer (stream from server).
1474
+ */
1475
+ async cloudBrowserVideo(runId: string): Promise<{ data: ArrayBuffer; filename: string }> {
1476
+ const url = new URL(this.cloudBrowserApiHost + '/run/' + runId + '/video');
1477
+ url.searchParams.set('key', this.key);
1478
+
1479
+ const response = await this.fetch({
1480
+ url: url.toString(),
1481
+ method: 'GET',
1482
+ headers: { 'user-agent': this.ua },
1483
+ });
1484
+
1485
+ if (!response.ok) {
1486
+ throw new Error(`Video download failed: ${response.status} ${await response.text()}`);
1487
+ }
1488
+
1489
+ const filename = runId + '.webm';
1490
+ return { data: await response.arrayBuffer(), filename };
1491
+ }
1492
+
1493
+ /**
1494
+ * Get playback info for a debug session recording.
1495
+ */
1496
+ async cloudBrowserPlayback(runId: string): Promise<Record<string, any>> {
1497
+ const url = new URL(this.cloudBrowserApiHost + '/run/' + runId + '/playback');
1498
+ url.searchParams.set('key', this.key);
1499
+
1500
+ const response = await this.fetch({
1501
+ url: url.toString(),
1502
+ method: 'GET',
1503
+ headers: { 'user-agent': this.ua },
1504
+ });
1505
+
1506
+ if (!response.ok) {
1507
+ throw new Error(`Playback get failed: ${response.status} ${await response.text()}`);
1508
+ }
1509
+ return await response.json() as Record<string, any>;
1510
+ }
1511
+
1512
+ /**
1513
+ * List all running Cloud Browser sessions.
1514
+ */
1515
+ async cloudBrowserSessions(): Promise<{ sessions: any[]; total: number }> {
1516
+ const url = new URL(this.cloudBrowserApiHost + '/sessions');
1517
+ url.searchParams.set('key', this.key);
1518
+
1519
+ const response = await this.fetch({
1520
+ url: url.toString(),
1521
+ method: 'GET',
1522
+ headers: { 'user-agent': this.ua },
1523
+ });
1524
+
1525
+ if (!response.ok) {
1526
+ throw new Error(`Sessions list failed: ${response.status} ${await response.text()}`);
1527
+ }
1528
+ return await response.json() as { sessions: any[]; total: number };
1529
+ }
1530
+ }
1531
+
1532
+ // ---------------------------------------------------------------------------
1533
+ // multipart/related parser
1534
+ // ---------------------------------------------------------------------------
1535
+ //
1536
+ // Tiny inline parser for the response of `POST /crawl/{uuid}/contents/batch`.
1537
+ // Avoids pulling in a multipart npm dep so the SDK stays dependency-free.
1538
+ //
1539
+ // Each part has at minimum a `Content-Location: <url>` header and a body. The
1540
+ // `Content-Type` may also be set, indicating the format. We map URL → format → body
1541
+ // using the `formats` argument as the inferred-format fallback when the part has
1542
+ // no `Content-Type`.
1543
+
1544
+ function parseMultipartRelated(
1545
+ body: string,
1546
+ contentType: string,
1547
+ formats: string[],
1548
+ ): Record<string, Record<string, string>> {
1549
+ const boundaryMatch = contentType.match(/boundary=(?:"([^"]+)"|([^;\s]+))/);
1550
+ if (!boundaryMatch) {
1551
+ throw new errors.ApiHttpClientError(
1552
+ `crawlContentsBatch: response has no multipart boundary in content-type "${contentType}"`,
1553
+ );
1554
+ }
1555
+ const boundary = boundaryMatch[1] ?? boundaryMatch[2];
1556
+ const delimiter = `--${boundary}`;
1557
+ const result: Record<string, Record<string, string>> = {};
1558
+
1559
+ // Split on the delimiter; first segment is the preamble (ignored), last is the
1560
+ // closing `--` (also ignored).
1561
+ const segments = body.split(delimiter);
1562
+ for (let i = 1; i < segments.length; i++) {
1563
+ let segment = segments[i];
1564
+ // Strip leading CRLF after the boundary
1565
+ if (segment.startsWith('\r\n')) segment = segment.slice(2);
1566
+ else if (segment.startsWith('\n')) segment = segment.slice(1);
1567
+ // The closing boundary is `--{boundary}--`; segment starts with `--` then EOL
1568
+ if (segment.startsWith('--')) break;
1569
+ // Trim trailing CRLF before the next boundary
1570
+ if (segment.endsWith('\r\n')) segment = segment.slice(0, -2);
1571
+ else if (segment.endsWith('\n')) segment = segment.slice(0, -1);
1572
+
1573
+ // Header/body split: first blank line
1574
+ const headerEnd = segment.indexOf('\r\n\r\n');
1575
+ const altHeaderEnd = headerEnd === -1 ? segment.indexOf('\n\n') : headerEnd;
1576
+ if (altHeaderEnd === -1) continue;
1577
+ const headersRaw = segment.slice(0, altHeaderEnd);
1578
+ const partBody = segment.slice(altHeaderEnd + (headerEnd === -1 ? 2 : 4));
1579
+
1580
+ // Parse headers
1581
+ let url: string | undefined;
1582
+ let format: string | undefined;
1583
+ for (const line of headersRaw.split(/\r?\n/)) {
1584
+ const colon = line.indexOf(':');
1585
+ if (colon === -1) continue;
1586
+ const name = line.slice(0, colon).trim().toLowerCase();
1587
+ const value = line.slice(colon + 1).trim();
1588
+ if (name === 'content-location') url = value;
1589
+ else if (name === 'content-type') format = inferFormatFromContentType(value);
1590
+ }
1591
+ if (!url) continue;
1592
+ if (!format) {
1593
+ // Fall back to the first requested format if the part has no content-type
1594
+ format = formats[0];
1595
+ }
1596
+ if (!result[url]) result[url] = {};
1597
+ result[url][format] = partBody;
1598
+ }
1599
+ return result;
1600
+ }
1601
+
1602
+ function inferFormatFromContentType(ct: string): string | undefined {
1603
+ const lc = ct.toLowerCase().split(';')[0].trim();
1604
+ if (lc === 'text/html') return 'html';
1605
+ if (lc === 'text/markdown') return 'markdown';
1606
+ if (lc === 'text/plain') return 'text';
1607
+ if (lc === 'application/json') return 'json';
1608
+ return undefined;
1609
+ }