scrapfly-sdk 0.10.0 → 0.10.2

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.
package/esm/batch.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Streaming multipart/mixed parser for POST /scrape/batch.
3
+ *
4
+ * The API emits one part per scrape as each completes. This module
5
+ * reads the response body as a ReadableStream and yields
6
+ * `(headers, body)` pairs as each part lands.
7
+ *
8
+ * No external dependencies — uses Web Streams (native in Node 18+
9
+ * and all modern browsers).
10
+ */
11
+ export interface BatchPart {
12
+ headers: Record<string, string>;
13
+ body: Uint8Array;
14
+ }
15
+ /**
16
+ * Async iterator over multipart/mixed parts from a fetch Response.
17
+ *
18
+ * Yields one `BatchPart` per multipart section as it arrives on the
19
+ * wire. Throws if the response Content-Type is not multipart/mixed
20
+ * or the boundary is missing.
21
+ */
22
+ export declare function iterBatchParts(response: Response): AsyncGenerator<BatchPart>;
23
+ /**
24
+ * Decode a part body according to its content-type header. Supports
25
+ * both application/json (default) and application/msgpack.
26
+ */
27
+ export declare function decodePartBody<T = unknown>(part: BatchPart): T;
28
+ /**
29
+ * Synthesize a native fetch `Response` from a proxified batch part.
30
+ * The part body is the raw upstream bytes and the part carries:
31
+ * * `Content-Type` — the upstream's content-type
32
+ * * `X-Scrapfly-Scrape-Status` — the upstream's HTTP status
33
+ * * `X-Scrapfly-Upstream-<Name>` — upstream response headers
34
+ * * `X-Scrapfly-Log-Uuid`, `X-Scrapfly-Content-Format` — scrapfly metadata
35
+ *
36
+ * We return a Response with those values restored so the caller
37
+ * gets the same shape as a single proxified scrape.
38
+ */
39
+ export declare function buildProxifiedResponseFromPart(part: BatchPart): Response;
40
+ //# sourceMappingURL=batch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch.d.ts","sourceRoot":"","sources":["../src/batch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AA0CH,MAAM,WAAW,SAAS;IACxB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,IAAI,EAAE,UAAU,CAAC;CAClB;AAED;;;;;;GAMG;AACH,wBAAuB,cAAc,CAAC,QAAQ,EAAE,QAAQ,GAAG,cAAc,CAAC,SAAS,CAAC,CAwHnF;AAoBD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,CAAC,GAAG,OAAO,EAAE,IAAI,EAAE,SAAS,GAAG,CAAC,CAS9D;AAOD;;;;;;;;;;GAUG;AACH,wBAAgB,8BAA8B,CAAC,IAAI,EAAE,SAAS,GAAG,QAAQ,CAiCxE"}
package/esm/batch.js ADDED
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Streaming multipart/mixed parser for POST /scrape/batch.
3
+ *
4
+ * The API emits one part per scrape as each completes. This module
5
+ * reads the response body as a ReadableStream and yields
6
+ * `(headers, body)` pairs as each part lands.
7
+ *
8
+ * No external dependencies — uses Web Streams (native in Node 18+
9
+ * and all modern browsers).
10
+ */
11
+ const CR = 0x0d;
12
+ const LF = 0x0a;
13
+ const CRLF = new Uint8Array([CR, LF]);
14
+ const DOUBLE_CRLF = new Uint8Array([CR, LF, CR, LF]);
15
+ function indexOf(buf, needle, start = 0) {
16
+ if (needle.length === 0)
17
+ return start;
18
+ const last = buf.length - needle.length;
19
+ outer: for (let i = start; i <= last; i++) {
20
+ for (let j = 0; j < needle.length; j++) {
21
+ if (buf[i + j] !== needle[j])
22
+ continue outer;
23
+ }
24
+ return i;
25
+ }
26
+ return -1;
27
+ }
28
+ function concat(a, b) {
29
+ const out = new Uint8Array(a.length + b.length);
30
+ out.set(a, 0);
31
+ out.set(b, a.length);
32
+ return out;
33
+ }
34
+ function parseContentType(value) {
35
+ const semi = value.indexOf(';');
36
+ if (semi < 0)
37
+ return { mime: value.trim().toLowerCase(), params: {} };
38
+ const mime = value.slice(0, semi).trim().toLowerCase();
39
+ const params = {};
40
+ for (const piece of value.slice(semi + 1).split(';')) {
41
+ const eq = piece.indexOf('=');
42
+ if (eq < 0)
43
+ continue;
44
+ const k = piece.slice(0, eq).trim().toLowerCase();
45
+ let v = piece.slice(eq + 1).trim();
46
+ if (v.startsWith('"') && v.endsWith('"'))
47
+ v = v.slice(1, -1);
48
+ params[k] = v;
49
+ }
50
+ return { mime, params };
51
+ }
52
+ /**
53
+ * Async iterator over multipart/mixed parts from a fetch Response.
54
+ *
55
+ * Yields one `BatchPart` per multipart section as it arrives on the
56
+ * wire. Throws if the response Content-Type is not multipart/mixed
57
+ * or the boundary is missing.
58
+ */
59
+ export async function* iterBatchParts(response) {
60
+ const ct = response.headers.get('content-type') ?? '';
61
+ const { mime, params } = parseContentType(ct);
62
+ if (mime !== 'multipart/mixed') {
63
+ throw new Error(`scrapeBatch: expected Content-Type multipart/mixed, got ${JSON.stringify(ct)}`);
64
+ }
65
+ const boundaryStr = params['boundary'];
66
+ if (!boundaryStr) {
67
+ throw new Error(`scrapeBatch: Content-Type multipart/mixed is missing boundary parameter: ${JSON.stringify(ct)}`);
68
+ }
69
+ if (!response.body) {
70
+ throw new Error('scrapeBatch: response has no body stream');
71
+ }
72
+ const boundary = new TextEncoder().encode('--' + boundaryStr);
73
+ const nextBoundarySep = new TextEncoder().encode('\r\n--' + boundaryStr);
74
+ const reader = response.body.getReader();
75
+ let buf = new Uint8Array(0);
76
+ let eof = false;
77
+ let pastPrefix = false;
78
+ const pump = async () => {
79
+ if (eof)
80
+ return false;
81
+ const { done, value } = await reader.read();
82
+ if (done) {
83
+ eof = true;
84
+ return false;
85
+ }
86
+ if (value && value.length > 0) {
87
+ buf = concat(buf, value);
88
+ return true;
89
+ }
90
+ return false;
91
+ };
92
+ const readUntil = async (needle) => {
93
+ while (true) {
94
+ const idx = indexOf(buf, needle);
95
+ if (idx !== -1) {
96
+ const out = buf.subarray(0, idx);
97
+ buf = buf.subarray(idx + needle.length);
98
+ return out;
99
+ }
100
+ if (eof) {
101
+ const out = buf;
102
+ buf = new Uint8Array(0);
103
+ return out;
104
+ }
105
+ if (!(await pump())) {
106
+ const out = buf;
107
+ buf = new Uint8Array(0);
108
+ return out;
109
+ }
110
+ }
111
+ };
112
+ const readExact = async (n) => {
113
+ while (buf.length < n && !eof) {
114
+ await pump();
115
+ }
116
+ const out = buf.subarray(0, Math.min(n, buf.length));
117
+ buf = buf.subarray(out.length);
118
+ return out;
119
+ };
120
+ while (true) {
121
+ if (!pastPrefix) {
122
+ await readUntil(boundary);
123
+ pastPrefix = true;
124
+ }
125
+ // After each --boundary, expect CRLF (more parts) or `--` (terminator).
126
+ // RFC 2046 mandates CRLF; any server deviating from that is broken —
127
+ // return cleanly rather than try to guess.
128
+ const suffix = await readExact(2);
129
+ if (suffix.length < 2)
130
+ return;
131
+ if (suffix[0] === 0x2d && suffix[1] === 0x2d) {
132
+ // Final boundary marker "--"
133
+ return;
134
+ }
135
+ if (!(suffix[0] === CR && suffix[1] === LF)) {
136
+ return;
137
+ }
138
+ // Read headers up to blank line (CRLF CRLF).
139
+ const headerBlock = await readUntil(DOUBLE_CRLF);
140
+ const headers = {};
141
+ for (const lineBytes of splitByCRLF(headerBlock)) {
142
+ const line = new TextDecoder('utf-8').decode(lineBytes);
143
+ const colon = line.indexOf(':');
144
+ if (colon <= 0)
145
+ continue;
146
+ headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
147
+ }
148
+ // Body framing: prefer Content-Length (server always emits it).
149
+ // When Content-Length is known, yield the part IMMEDIATELY after
150
+ // reading the body bytes — don't wait for the next boundary
151
+ // separator to arrive. Otherwise the caller is blocked until
152
+ // part N+1 starts streaming, which defeats the whole point of
153
+ // per-part streaming (especially when scrape N+1 is a slow one).
154
+ let body;
155
+ const cl = headers['content-length'];
156
+ let readSeparatorAfterYield = false;
157
+ if (cl && /^\d+$/.test(cl)) {
158
+ body = await readExact(parseInt(cl, 10));
159
+ readSeparatorAfterYield = true;
160
+ }
161
+ else {
162
+ body = await readUntil(nextBoundarySep);
163
+ }
164
+ yield { headers, body };
165
+ // With Content-Length framing, the "\r\n--<boundary>" separator
166
+ // follows the body but is not part of it. Consume it now — any
167
+ // blocking that happens here blocks the NEXT iteration, not this
168
+ // part's delivery.
169
+ if (readSeparatorAfterYield) {
170
+ await readUntil(nextBoundarySep);
171
+ }
172
+ }
173
+ }
174
+ function splitByCRLF(buf) {
175
+ const out = [];
176
+ let start = 0;
177
+ for (let i = 0; i < buf.length - 1; i++) {
178
+ if (buf[i] === CR && buf[i + 1] === LF) {
179
+ out.push(buf.subarray(start, i));
180
+ start = i + 2;
181
+ i++;
182
+ }
183
+ }
184
+ if (start < buf.length)
185
+ out.push(buf.subarray(start));
186
+ return out;
187
+ }
188
+ // msgpack decoder. The module is npm:@msgpack/msgpack — dnt rewrites
189
+ // this to a regular npm import in the published package.
190
+ import { decode as msgpackDecode } from '@msgpack/msgpack';
191
+ /**
192
+ * Decode a part body according to its content-type header. Supports
193
+ * both application/json (default) and application/msgpack.
194
+ */
195
+ export function decodePartBody(part) {
196
+ const ct = part.headers['content-type'] ?? 'application/json';
197
+ if (ct.startsWith('application/json')) {
198
+ return JSON.parse(new TextDecoder('utf-8').decode(part.body));
199
+ }
200
+ if (ct.startsWith('application/msgpack') || ct.startsWith('application/x-msgpack')) {
201
+ return msgpackDecode(part.body);
202
+ }
203
+ throw new Error(`scrapeBatch: unsupported part Content-Type: ${ct}`);
204
+ }
205
+ // Header prefix used by the server to forward upstream response
206
+ // headers on proxified batch parts (avoids collision with the
207
+ // multipart envelope's own headers).
208
+ const UPSTREAM_PREFIX = 'x-scrapfly-upstream-';
209
+ /**
210
+ * Synthesize a native fetch `Response` from a proxified batch part.
211
+ * The part body is the raw upstream bytes and the part carries:
212
+ * * `Content-Type` — the upstream's content-type
213
+ * * `X-Scrapfly-Scrape-Status` — the upstream's HTTP status
214
+ * * `X-Scrapfly-Upstream-<Name>` — upstream response headers
215
+ * * `X-Scrapfly-Log-Uuid`, `X-Scrapfly-Content-Format` — scrapfly metadata
216
+ *
217
+ * We return a Response with those values restored so the caller
218
+ * gets the same shape as a single proxified scrape.
219
+ */
220
+ export function buildProxifiedResponseFromPart(part) {
221
+ const statusHeader = part.headers['x-scrapfly-scrape-status'];
222
+ const status = statusHeader ? parseInt(statusHeader, 10) || 200 : 200;
223
+ const headers = new Headers();
224
+ for (const [key, value] of Object.entries(part.headers)) {
225
+ const lower = key.toLowerCase();
226
+ if (lower === 'content-type') {
227
+ headers.set('Content-Type', value);
228
+ }
229
+ else if (lower.startsWith(UPSTREAM_PREFIX)) {
230
+ headers.set(key.slice(UPSTREAM_PREFIX.length), value);
231
+ }
232
+ else if (lower.startsWith('x-scrapfly-')) {
233
+ headers.set(key, value);
234
+ }
235
+ }
236
+ // Normalize X-Scrapfly-Log-Uuid → X-Scrapfly-Log for parity with
237
+ // the single-scrape proxified response headers.
238
+ if (!headers.has('X-Scrapfly-Log') && headers.has('X-Scrapfly-Log-Uuid')) {
239
+ headers.set('X-Scrapfly-Log', headers.get('X-Scrapfly-Log-Uuid') ?? '');
240
+ }
241
+ // Wrap the Uint8Array in an ArrayBuffer so fetch Response accepts
242
+ // it (Node's fetch is picky about BodyInit).
243
+ // Copy into a fresh ArrayBuffer to avoid SharedArrayBuffer edge
244
+ // cases when the underlying bytes came from a larger buffer.
245
+ const bodyBuffer = new Uint8Array(part.body.length);
246
+ bodyBuffer.set(part.body);
247
+ return new Response(bodyBuffer, {
248
+ status,
249
+ headers,
250
+ });
251
+ }
@@ -28,6 +28,7 @@ export type BrowserConfigOptions = {
28
28
  unblock?: boolean;
29
29
  unblock_timeout?: number;
30
30
  browser_brand?: string;
31
+ enable_mcp?: boolean;
31
32
  };
32
33
  export declare class BrowserConfig {
33
34
  proxy_pool?: string;
@@ -50,6 +51,7 @@ export declare class BrowserConfig {
50
51
  unblock?: boolean;
51
52
  unblock_timeout?: number;
52
53
  browser_brand?: string;
54
+ enable_mcp?: boolean;
53
55
  constructor(options?: BrowserConfigOptions);
54
56
  /**
55
57
  * Generate the WebSocket URL for a Cloud Browser session.
@@ -1 +1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,UAAU,CAAC,EAAE,OAAO,CAAC;gBAET,OAAO,GAAE,oBAAyB;IA2B9C;;OAEG;IACH,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM;CA6BpD"}
@@ -131,6 +131,12 @@ export class BrowserConfig {
131
131
  writable: true,
132
132
  value: void 0
133
133
  });
134
+ Object.defineProperty(this, "enable_mcp", {
135
+ enumerable: true,
136
+ configurable: true,
137
+ writable: true,
138
+ value: void 0
139
+ });
134
140
  if (options.timeout !== undefined && options.timeout > 1800) {
135
141
  throw new Error('timeout cannot exceed 1800 seconds (30 minutes)');
136
142
  }
@@ -154,6 +160,7 @@ export class BrowserConfig {
154
160
  this.unblock = options.unblock;
155
161
  this.unblock_timeout = options.unblock_timeout;
156
162
  this.browser_brand = options.browser_brand;
163
+ this.enable_mcp = options.enable_mcp;
157
164
  }
158
165
  /**
159
166
  * Generate the WebSocket URL for a Cloud Browser session.
@@ -201,6 +208,8 @@ export class BrowserConfig {
201
208
  params.set('unblock_timeout', String(this.unblock_timeout));
202
209
  if (this.browser_brand !== undefined)
203
210
  params.set('browser_brand', this.browser_brand);
211
+ if (this.enable_mcp !== undefined)
212
+ params.set('enable_mcp', String(this.enable_mcp));
204
213
  const baseHost = host || 'wss://browser.scrapfly.io';
205
214
  return `${baseHost}?${params.toString()}`;
206
215
  }
package/esm/client.d.ts CHANGED
@@ -4,7 +4,7 @@ import type { ScrapeConfig } from './scrapeconfig.js';
4
4
  import type { ScreenshotConfig } from './screenshotconfig.js';
5
5
  import type { ExtractionConfig } from './extractionconfig.js';
6
6
  import { BrowserConfig } from './browserconfig.js';
7
- import { type AccountData, ExtractionResult, ScrapeResult, ScreenshotResult } from './result.js';
7
+ import { type AccountData, type ClassifyOptions, type ClassifyResult, ExtractionResult, ScrapeResult, ScreenshotResult } from './result.js';
8
8
  import type { Rec } from './types.js';
9
9
  import type { CrawlerConfig, CrawlerContentFormat } from './crawlerconfig.js';
10
10
  import { CrawlerArtifact, type CrawlerArtifactType, CrawlerContents, CrawlerStatus, CrawlerUrls } from './crawlerresult.js';
@@ -39,6 +39,15 @@ export declare class ScrapflyClient {
39
39
  * Retrieve Scrapfly account details
40
40
  */
41
41
  account(): Promise<AccountData>;
42
+ /**
43
+ * Classify an already-fetched HTTP response for anti-bot blocking.
44
+ *
45
+ * Runs the same anti-bot detection pipeline used by live Scrapfly
46
+ * scrapes against a response you already have (from your own proxy,
47
+ * cache, etc). 1 API credit per call. See
48
+ * https://scrapfly.io/docs/scrape-api/classify for the full contract.
49
+ */
50
+ classify(options: ClassifyOptions): Promise<ClassifyResult>;
42
51
  private monitoringRequest;
43
52
  private buildMetricsParams;
44
53
  private buildTargetParams;
@@ -74,6 +83,25 @@ export declare class ScrapflyClient {
74
83
  @param concurrencyLimit: if not set it will be taken from your account info
75
84
  */
76
85
  concurrentScrape(configs: ScrapeConfig[], concurrencyLimit?: number): AsyncGenerator<ScrapeResult | Error | undefined, void, undefined>;
86
+ /**
87
+ * Issue a single batch request against POST /scrape/batch and
88
+ * stream results back as each scrape completes.
89
+ *
90
+ * Yields `[correlation_id, resultOrError]` tuples. Results arrive
91
+ * OUT OF ORDER — whichever scrape finishes first is yielded first.
92
+ * Every ScrapeConfig MUST carry a unique `correlation_id`; missing
93
+ * or duplicate values are caught client-side before the batch is
94
+ * sent (so callers fail fast on misconfiguration).
95
+ *
96
+ * Usage:
97
+ * for await (const [id, result] of client.scrapeBatch(configs)) {
98
+ * if (result instanceof errors.ScrapflyError) { ... }
99
+ * else { ... }
100
+ * }
101
+ */
102
+ scrapeBatch(configs: ScrapeConfig[], options?: {
103
+ format?: 'json' | 'msgpack';
104
+ }): AsyncGenerator<[string, ScrapeResult | Response | errors.ScrapflyError], void, undefined>;
77
105
  /**
78
106
  * Save screenshot response to a file
79
107
  */
@@ -212,10 +240,12 @@ export declare class ScrapflyClient {
212
240
  headers?: Record<string, string>;
213
241
  body?: string;
214
242
  method?: string;
243
+ enable_mcp?: boolean;
215
244
  }): Promise<{
216
245
  ws_url: string;
217
246
  session_id: string;
218
247
  run_id: string;
248
+ mcp_endpoint?: string;
219
249
  }>;
220
250
  /**
221
251
  * Stop a Cloud Browser session.
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AACtC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,KAAK,WAAW,EAAE,gBAAgB,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEjG,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,KAAK,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC9E,OAAO,EAAE,eAAe,EAAE,KAAK,mBAAmB,EAAE,eAAe,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAC5H,OAAO,EAEL,KAAK,6BAA6B,EAClC,KAAK,wBAAwB,EAC7B,KAAK,8BAA8B,EACpC,MAAM,uBAAuB,CAAC;AAE/B,qBAAa,cAAc;IAClB,IAAI,SAA6B;IACjC,kBAAkB,SAA+B;IACjD,sBAAsB,SAAiC;IAC9D,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,gBAAgB,CAAS;IACjC,OAAO,CAAC,mBAAmB,CAAS;IACpC,KAAK,oBAAc;gBAEP,OAAO,EAAE;QAAE,GAAG,EAAE,MAAM,CA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 * Classify an already-fetched HTTP response for anti-bot blocking.
235
+ *
236
+ * Runs the same anti-bot detection pipeline used by live Scrapfly
237
+ * scrapes against a response you already have (from your own proxy,
238
+ * cache, etc). 1 API credit per call. See
239
+ * https://scrapfly.io/docs/scrape-api/classify for the full contract.
240
+ */
241
+ async classify(options) {
242
+ if (!options || !options.url) {
243
+ throw new errors.ScrapflyError('classify: url is required');
244
+ }
245
+ if (typeof options.statusCode !== 'number' ||
246
+ options.statusCode < 100 ||
247
+ options.statusCode > 599) {
248
+ throw new errors.ScrapflyError('classify: status_code must be a valid HTTP status in [100, 599]');
249
+ }
250
+ const body = {
251
+ url: options.url,
252
+ status_code: options.statusCode,
253
+ method: options.method ?? 'GET',
254
+ };
255
+ if (options.headers && Object.keys(options.headers).length > 0) {
256
+ const hdrs = {};
257
+ for (const [k, v] of Object.entries(options.headers)) {
258
+ hdrs[String(k)] = String(v);
259
+ }
260
+ body.headers = hdrs;
261
+ }
262
+ if (options.body !== undefined && options.body !== null) {
263
+ body.body = options.body;
264
+ }
265
+ const url = new URL(this.HOST + '/classify');
266
+ url.search = new URLSearchParams({ key: this.key }).toString();
267
+ const response = await this.fetch({
268
+ url: url.toString(),
269
+ method: 'POST',
270
+ headers: {
271
+ 'user-agent': this.ua,
272
+ 'accept-encoding': 'gzip, deflate, br',
273
+ accept: 'application/json',
274
+ 'content-type': 'application/json',
275
+ },
276
+ body: JSON.stringify(body),
277
+ });
278
+ const data = (await response.json());
279
+ if (response.status >= 400 || 'error_id' in data) {
280
+ if (response.status == 401) {
281
+ throw new errors.BadApiKeyError(JSON.stringify(data));
282
+ }
283
+ throw new errors.ApiHttpClientError(JSON.stringify(data));
284
+ }
285
+ return {
286
+ blocked: Boolean(data.blocked),
287
+ antibot: (data.antibot ?? null),
288
+ cost: Number(data.cost ?? 0),
289
+ };
290
+ }
233
291
  // ── Monitoring API (Enterprise+ plan only) ──────────────────────
234
292
  // The Monitoring API exposes per-product aggregates and per-target
235
293
  // timeseries. Web Scraping / Screenshot / Extraction / Crawler share
@@ -498,6 +556,130 @@ export class ScrapflyClient {
498
556
  yield resultOrError;
499
557
  }
500
558
  }
559
+ /**
560
+ * Issue a single batch request against POST /scrape/batch and
561
+ * stream results back as each scrape completes.
562
+ *
563
+ * Yields `[correlation_id, resultOrError]` tuples. Results arrive
564
+ * OUT OF ORDER — whichever scrape finishes first is yielded first.
565
+ * Every ScrapeConfig MUST carry a unique `correlation_id`; missing
566
+ * or duplicate values are caught client-side before the batch is
567
+ * sent (so callers fail fast on misconfiguration).
568
+ *
569
+ * Usage:
570
+ * for await (const [id, result] of client.scrapeBatch(configs)) {
571
+ * if (result instanceof errors.ScrapflyError) { ... }
572
+ * else { ... }
573
+ * }
574
+ */
575
+ async *scrapeBatch(configs, options = {}) {
576
+ const wireFormat = options.format ?? 'json';
577
+ const acceptHeader = wireFormat === 'msgpack' ? 'application/msgpack' : 'application/json';
578
+ // Lazy-load the parser to avoid pulling Web Streams polyfills
579
+ // into the module graph for users who never call scrapeBatch.
580
+ const { iterBatchParts, decodePartBody, buildProxifiedResponseFromPart } = await import('./batch.js');
581
+ if (!configs || configs.length === 0) {
582
+ throw new errors.ScrapflyError('scrapeBatch: configs list is empty');
583
+ }
584
+ if (configs.length > 100) {
585
+ throw new errors.ScrapflyError(`scrapeBatch: max 100 configs per batch (got ${configs.length})`);
586
+ }
587
+ const seen = new Map();
588
+ const configByCorrelation = new Map();
589
+ const bodyConfigs = [];
590
+ for (let i = 0; i < configs.length; i++) {
591
+ const cfg = configs[i];
592
+ const correlationId = cfg.correlation_id;
593
+ if (!correlationId) {
594
+ throw new errors.ScrapflyError(`scrapeBatch: configs[${i}] is missing correlation_id (required for matching streamed parts)`);
595
+ }
596
+ if (seen.has(correlationId)) {
597
+ throw new errors.ScrapflyError(`scrapeBatch: correlation_id ${JSON.stringify(correlationId)} reused by configs[${seen.get(correlationId)}] and configs[${i}]`);
598
+ }
599
+ seen.set(correlationId, i);
600
+ configByCorrelation.set(correlationId, cfg);
601
+ // Reuse toApiParams to guarantee wire parity with /scrape.
602
+ // Drop `key` (batch key is in the URL).
603
+ const params = cfg.toApiParams({ key: this.key });
604
+ delete params.key;
605
+ bodyConfigs.push(params);
606
+ }
607
+ const url = new URL(this.HOST + '/scrape/batch');
608
+ url.search = new URLSearchParams({ key: this.key }).toString();
609
+ const response = await this.fetch({
610
+ url: url.toString(),
611
+ method: 'POST',
612
+ headers: {
613
+ 'user-agent': this.ua,
614
+ 'content-type': 'application/json',
615
+ // gzip is universally supported in fetch runtimes; skip zstd
616
+ // for streaming compatibility (Node < 22 / browsers don't
617
+ // auto-decompress zstd yet).
618
+ 'accept-encoding': 'gzip',
619
+ accept: acceptHeader,
620
+ },
621
+ body: JSON.stringify({ configs: bodyConfigs }),
622
+ });
623
+ if (response.status !== 200) {
624
+ const body = await response.text();
625
+ let parsed;
626
+ try {
627
+ parsed = JSON.parse(body);
628
+ }
629
+ catch {
630
+ parsed = { message: body, code: 'ERR::API::INTERNAL_ERROR' };
631
+ }
632
+ throw new errors.ApiHttpServerError(`scrapeBatch: ${parsed.code ?? 'error'} (HTTP ${response.status}): ${parsed.message ?? body}`);
633
+ }
634
+ for await (const part of iterBatchParts(response)) {
635
+ const correlationId = part.headers['x-scrapfly-correlation-id'] ?? '';
636
+ // Proxified-response parts: the part body is the raw upstream
637
+ // bytes, not a JSON envelope. Surface a native fetch Response
638
+ // so callers get the same shape as a single proxified scrape
639
+ // (which returns Response from .scrape()).
640
+ if (part.headers['x-scrapfly-proxified'] === 'true') {
641
+ try {
642
+ const proxResponse = buildProxifiedResponseFromPart(part);
643
+ yield [correlationId, proxResponse];
644
+ }
645
+ catch (proxErr) {
646
+ yield [
647
+ correlationId,
648
+ new errors.ScrapflyError(`scrapeBatch: failed to build proxified response for correlation_id=${JSON.stringify(correlationId)}: ${proxErr}`),
649
+ ];
650
+ }
651
+ continue;
652
+ }
653
+ let parsed;
654
+ try {
655
+ parsed = decodePartBody(part);
656
+ }
657
+ catch (decodeErr) {
658
+ yield [
659
+ correlationId,
660
+ new errors.ScrapflyError(`scrapeBatch: failed to decode part for correlation_id=${JSON.stringify(correlationId)}: ${decodeErr}`),
661
+ ];
662
+ continue;
663
+ }
664
+ try {
665
+ const result = new ScrapeResult({
666
+ config: parsed.config,
667
+ context: parsed.context,
668
+ result: parsed.result,
669
+ uuid: parsed.uuid,
670
+ });
671
+ yield [correlationId, result];
672
+ }
673
+ catch (resultErr) {
674
+ yield [
675
+ correlationId,
676
+ resultErr instanceof errors.ScrapflyError
677
+ ? resultErr
678
+ : new errors.ScrapflyError(`scrapeBatch: ${resultErr}`),
679
+ ];
680
+ }
681
+ }
682
+ }
501
683
  /**
502
684
  * Save screenshot response to a file
503
685
  */
@@ -1034,6 +1216,8 @@ export class ScrapflyClient {
1034
1216
  jsonBody.body = options.body;
1035
1217
  if (options.method)
1036
1218
  jsonBody.method = options.method;
1219
+ if (options.enable_mcp !== undefined)
1220
+ jsonBody.enable_mcp = options.enable_mcp;
1037
1221
  const url = new URL(this.cloudBrowserApiHost + '/unblock');
1038
1222
  url.searchParams.set('key', this.key);
1039
1223
  const response = await this.fetch({
package/esm/main.d.ts CHANGED
@@ -6,7 +6,7 @@ export { BrowserConfig, ProxyPool, OperatingSystem } from './browserconfig.js';
6
6
  export type { BrowserConfigOptions } from './browserconfig.js';
7
7
  export * as errors from './errors.js';
8
8
  export { ExtractionResult, ScrapeResult, ScreenshotResult } from './result.js';
9
- export type { AccountData, ConfigData, ContextData, ResultData, ScreenshotMetadata } from './result.js';
9
+ export type { AccountData, ClassifyOptions, ClassifyResult, ConfigData, ContextData, ResultData, ScreenshotMetadata } from './result.js';
10
10
  export { CrawlerConfig } from './crawlerconfig.js';
11
11
  export type { CrawlerConfigOptions, CrawlerContentFormat, CrawlerWebhookEventName } from './crawlerconfig.js';
12
12
  export { Crawl } from './crawl.js';
package/esm/main.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"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