scrapfly-sdk 0.10.3 → 0.10.5

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