scrapfly-sdk 0.10.4 → 0.10.6
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.map +1 -1
- package/esm/batch.js +6 -0
- package/esm/browserconfig.d.ts +80 -1
- package/esm/browserconfig.d.ts.map +1 -1
- package/esm/browserconfig.js +54 -1
- package/esm/client.d.ts +65 -0
- package/esm/client.d.ts.map +1 -1
- package/esm/client.js +157 -5
- package/esm/crawl.d.ts +4 -0
- package/esm/crawl.d.ts.map +1 -1
- package/esm/crawl.js +4 -0
- package/esm/crawlerresult.d.ts +7 -0
- package/esm/crawlerresult.d.ts.map +1 -1
- package/esm/errors.d.ts +43 -0
- package/esm/errors.d.ts.map +1 -1
- package/esm/errors.js +43 -16
- package/esm/extractionconfig.d.ts +54 -9
- package/esm/extractionconfig.d.ts.map +1 -1
- package/esm/extractionconfig.js +37 -13
- package/esm/logger.d.ts +1 -0
- package/esm/logger.d.ts.map +1 -1
- package/esm/logger.js +1 -0
- package/esm/main.d.ts +29 -0
- package/esm/main.d.ts.map +1 -1
- package/esm/main.js +28 -0
- package/esm/monitoringconfig.d.ts +48 -11
- package/esm/monitoringconfig.d.ts.map +1 -1
- package/esm/monitoringconfig.js +14 -0
- package/esm/result.d.ts +2 -0
- package/esm/result.d.ts.map +1 -1
- package/esm/schedule.d.ts +93 -0
- package/esm/schedule.d.ts.map +1 -0
- package/esm/schedule.js +40 -0
- package/esm/scrapeconfig.d.ts +10 -8
- package/esm/scrapeconfig.d.ts.map +1 -1
- package/esm/scrapeconfig.js +10 -8
- package/esm/screenshotconfig.d.ts +59 -26
- package/esm/screenshotconfig.d.ts.map +1 -1
- package/esm/screenshotconfig.js +38 -26
- package/esm/webhookserver.d.ts +28 -0
- package/esm/webhookserver.d.ts.map +1 -1
- package/esm/webhookserver.js +34 -3
- package/package.json +1 -1
- package/script/batch.d.ts.map +1 -1
- package/script/batch.js +6 -0
- package/script/browserconfig.d.ts +80 -1
- package/script/browserconfig.d.ts.map +1 -1
- package/script/browserconfig.js +54 -1
- package/script/client.d.ts +65 -0
- package/script/client.d.ts.map +1 -1
- package/script/client.js +157 -5
- package/script/crawl.d.ts +4 -0
- package/script/crawl.d.ts.map +1 -1
- package/script/crawl.js +4 -0
- package/script/crawlerresult.d.ts +7 -0
- package/script/crawlerresult.d.ts.map +1 -1
- package/script/errors.d.ts +43 -0
- package/script/errors.d.ts.map +1 -1
- package/script/errors.js +43 -16
- package/script/extractionconfig.d.ts +54 -9
- package/script/extractionconfig.d.ts.map +1 -1
- package/script/extractionconfig.js +37 -13
- package/script/logger.d.ts +1 -0
- package/script/logger.d.ts.map +1 -1
- package/script/logger.js +1 -0
- package/script/main.d.ts +29 -0
- package/script/main.d.ts.map +1 -1
- package/script/main.js +30 -1
- package/script/monitoringconfig.d.ts +48 -11
- package/script/monitoringconfig.d.ts.map +1 -1
- package/script/monitoringconfig.js +14 -0
- package/script/result.d.ts +2 -0
- package/script/result.d.ts.map +1 -1
- package/script/schedule.d.ts +93 -0
- package/script/schedule.d.ts.map +1 -0
- package/script/schedule.js +44 -0
- package/script/scrapeconfig.d.ts +10 -8
- package/script/scrapeconfig.d.ts.map +1 -1
- package/script/scrapeconfig.js +10 -8
- package/script/screenshotconfig.d.ts +59 -26
- package/script/screenshotconfig.d.ts.map +1 -1
- package/script/screenshotconfig.js +38 -26
- package/script/webhookserver.d.ts +28 -0
- package/script/webhookserver.d.ts.map +1 -1
- package/script/webhookserver.js +34 -3
- package/src/batch.ts +7 -1
- package/src/browserconfig.ts +82 -1
- package/src/client.ts +227 -7
- package/src/crawl.ts +4 -0
- package/src/crawlerresult.ts +7 -0
- package/src/errors.ts +43 -16
- package/src/extractionconfig.ts +58 -16
- package/src/logger.ts +2 -0
- package/src/main.ts +37 -0
- package/src/monitoringconfig.ts +49 -11
- package/src/result.ts +2 -0
- package/src/schedule.ts +101 -0
- package/src/scrapeconfig.ts +10 -8
- package/src/screenshotconfig.ts +59 -26
- package/src/webhookserver.ts +34 -3
package/src/browserconfig.ts
CHANGED
|
@@ -1,61 +1,134 @@
|
|
|
1
|
+
/** Proxy pool to use for the Cloud Browser session. */
|
|
1
2
|
export enum ProxyPool {
|
|
3
|
+
/** Datacenter proxies — fast and cheap; best for non-protected targets. */
|
|
2
4
|
DATACENTER = 'datacenter',
|
|
5
|
+
/** Residential proxies — real ISP IPs; required by most anti-bot protections. */
|
|
3
6
|
RESIDENTIAL = 'residential',
|
|
4
7
|
}
|
|
5
8
|
|
|
9
|
+
/** Operating system to emulate for the Cloud Browser session fingerprint. */
|
|
6
10
|
export enum OperatingSystem {
|
|
11
|
+
/** Emulate a Linux browser fingerprint. */
|
|
7
12
|
LINUX = 'linux',
|
|
13
|
+
/** Emulate a Windows browser fingerprint. */
|
|
8
14
|
WINDOWS = 'windows',
|
|
15
|
+
/** Emulate a macOS browser fingerprint. */
|
|
9
16
|
MACOS = 'macos',
|
|
10
17
|
}
|
|
11
18
|
|
|
19
|
+
/**
|
|
20
|
+
* User-facing options accepted by {@link BrowserConfig}. All fields are
|
|
21
|
+
* optional; any field left undefined falls back to the Scrapfly Cloud
|
|
22
|
+
* Browser defaults.
|
|
23
|
+
*/
|
|
12
24
|
export type BrowserConfigOptions = {
|
|
25
|
+
/** Proxy pool to route the session through. */
|
|
13
26
|
proxy_pool?: ProxyPool | string;
|
|
27
|
+
/** Operating system fingerprint to emulate. */
|
|
14
28
|
os?: OperatingSystem | string;
|
|
29
|
+
/** Session ID for sticky sessions (IP + cookies reused across scrapes). */
|
|
15
30
|
session?: string;
|
|
31
|
+
/** ISO country code for geo-targeting. */
|
|
16
32
|
country?: string;
|
|
33
|
+
/** Close the browser automatically when the connection drops. */
|
|
17
34
|
auto_close?: boolean;
|
|
35
|
+
/** Session timeout in seconds (max 1800 = 30 minutes). */
|
|
18
36
|
timeout?: number;
|
|
37
|
+
/** Enable debug trace for the session. */
|
|
19
38
|
debug?: boolean;
|
|
39
|
+
/** Browser extensions to load (by ID). */
|
|
20
40
|
extensions?: string[];
|
|
41
|
+
/** Block image requests to speed up navigation. */
|
|
21
42
|
block_images?: boolean;
|
|
43
|
+
/** Block stylesheet requests. */
|
|
22
44
|
block_styles?: boolean;
|
|
45
|
+
/** Block font requests. */
|
|
23
46
|
block_fonts?: boolean;
|
|
47
|
+
/** Block media (video/audio) requests. */
|
|
24
48
|
block_media?: boolean;
|
|
49
|
+
/** Capture a screenshot at session end. */
|
|
25
50
|
screenshot?: boolean;
|
|
51
|
+
/** Viewport resolution, formatted as "widthxheight" (e.g. "1920x1080"). */
|
|
26
52
|
resolution?: string;
|
|
53
|
+
/** URL to navigate to after session start. */
|
|
27
54
|
target_url?: string;
|
|
55
|
+
/** Reuse cached responses where possible. */
|
|
28
56
|
cache?: boolean;
|
|
57
|
+
/** Apply Scrapfly's abuse blacklist. */
|
|
29
58
|
blacklist?: boolean;
|
|
59
|
+
/** Enable anti-scraping-protection bypass. */
|
|
30
60
|
unblock?: boolean;
|
|
61
|
+
/** Timeout in seconds for the unblock step. */
|
|
31
62
|
unblock_timeout?: number;
|
|
63
|
+
/** Browser brand to emulate (e.g. "chrome", "firefox"). */
|
|
32
64
|
browser_brand?: string;
|
|
65
|
+
/** Enable the MCP (Model Context Protocol) bridge. */
|
|
33
66
|
enable_mcp?: boolean;
|
|
67
|
+
/**
|
|
68
|
+
* Arm Scrapium's built-in captcha detector + solver on the first page attach.
|
|
69
|
+
* Turnstile, DataDome slider, reCAPTCHA, GeeTest, PerimeterX hold, and
|
|
70
|
+
* puzzle captchas are handled automatically — no extra CDP calls from the
|
|
71
|
+
* client. Billed per solve; failures cost nothing.
|
|
72
|
+
* See https://scrapfly.io/docs/cloud-browser-api/captcha-solver
|
|
73
|
+
*/
|
|
74
|
+
solve_captcha?: boolean;
|
|
34
75
|
};
|
|
35
76
|
|
|
77
|
+
/**
|
|
78
|
+
* Configuration for a Scrapfly Cloud Browser session. Builds the
|
|
79
|
+
* WebSocket URL that clients such as Puppeteer or Playwright can
|
|
80
|
+
* connect to via CDP.
|
|
81
|
+
*/
|
|
36
82
|
export class BrowserConfig {
|
|
83
|
+
/** See {@link BrowserConfigOptions.proxy_pool}. */
|
|
37
84
|
proxy_pool?: string;
|
|
85
|
+
/** See {@link BrowserConfigOptions.os}. */
|
|
38
86
|
os?: string;
|
|
87
|
+
/** See {@link BrowserConfigOptions.session}. */
|
|
39
88
|
session?: string;
|
|
89
|
+
/** See {@link BrowserConfigOptions.country}. */
|
|
40
90
|
country?: string;
|
|
91
|
+
/** See {@link BrowserConfigOptions.auto_close}. */
|
|
41
92
|
auto_close?: boolean;
|
|
93
|
+
/** See {@link BrowserConfigOptions.timeout}. */
|
|
42
94
|
timeout?: number;
|
|
95
|
+
/** See {@link BrowserConfigOptions.debug}. */
|
|
43
96
|
debug?: boolean;
|
|
97
|
+
/** See {@link BrowserConfigOptions.extensions}. */
|
|
44
98
|
extensions?: string[];
|
|
99
|
+
/** See {@link BrowserConfigOptions.block_images}. */
|
|
45
100
|
block_images?: boolean;
|
|
101
|
+
/** See {@link BrowserConfigOptions.block_styles}. */
|
|
46
102
|
block_styles?: boolean;
|
|
103
|
+
/** See {@link BrowserConfigOptions.block_fonts}. */
|
|
47
104
|
block_fonts?: boolean;
|
|
105
|
+
/** See {@link BrowserConfigOptions.block_media}. */
|
|
48
106
|
block_media?: boolean;
|
|
107
|
+
/** See {@link BrowserConfigOptions.screenshot}. */
|
|
49
108
|
screenshot?: boolean;
|
|
109
|
+
/** See {@link BrowserConfigOptions.resolution}. */
|
|
50
110
|
resolution?: string;
|
|
111
|
+
/** See {@link BrowserConfigOptions.target_url}. */
|
|
51
112
|
target_url?: string;
|
|
113
|
+
/** See {@link BrowserConfigOptions.cache}. */
|
|
52
114
|
cache?: boolean;
|
|
115
|
+
/** See {@link BrowserConfigOptions.blacklist}. */
|
|
53
116
|
blacklist?: boolean;
|
|
117
|
+
/** See {@link BrowserConfigOptions.unblock}. */
|
|
54
118
|
unblock?: boolean;
|
|
119
|
+
/** See {@link BrowserConfigOptions.unblock_timeout}. */
|
|
55
120
|
unblock_timeout?: number;
|
|
121
|
+
/** See {@link BrowserConfigOptions.browser_brand}. */
|
|
56
122
|
browser_brand?: string;
|
|
123
|
+
/** See {@link BrowserConfigOptions.enable_mcp}. */
|
|
57
124
|
enable_mcp?: boolean;
|
|
125
|
+
/** See {@link BrowserConfigOptions.solve_captcha}. */
|
|
126
|
+
solve_captcha?: boolean;
|
|
58
127
|
|
|
128
|
+
/**
|
|
129
|
+
* @param options Session options. See {@link BrowserConfigOptions}.
|
|
130
|
+
* @throws `Error` if `timeout` exceeds the upper bound of 1800 seconds.
|
|
131
|
+
*/
|
|
59
132
|
constructor(options: BrowserConfigOptions = {}) {
|
|
60
133
|
if (options.timeout !== undefined && options.timeout > 1800) {
|
|
61
134
|
throw new Error('timeout cannot exceed 1800 seconds (30 minutes)');
|
|
@@ -81,10 +154,17 @@ export class BrowserConfig {
|
|
|
81
154
|
this.unblock_timeout = options.unblock_timeout;
|
|
82
155
|
this.browser_brand = options.browser_brand;
|
|
83
156
|
this.enable_mcp = options.enable_mcp;
|
|
157
|
+
this.solve_captcha = options.solve_captcha;
|
|
84
158
|
}
|
|
85
159
|
|
|
86
160
|
/**
|
|
87
|
-
*
|
|
161
|
+
* Build the WebSocket URL clients use to connect to the Cloud Browser
|
|
162
|
+
* session (compatible with Puppeteer `browserWSEndpoint` and the
|
|
163
|
+
* Playwright `connectOverCDP` API).
|
|
164
|
+
*
|
|
165
|
+
* @param apiKey Scrapfly API key.
|
|
166
|
+
* @param host Optional override for the Cloud Browser host (defaults to `wss://browser.scrapfly.io`).
|
|
167
|
+
* @returns A fully-qualified `wss://…` URL with all options encoded as query parameters.
|
|
88
168
|
*/
|
|
89
169
|
websocketUrl(apiKey: string, host?: string): string {
|
|
90
170
|
const params = new URLSearchParams();
|
|
@@ -111,6 +191,7 @@ export class BrowserConfig {
|
|
|
111
191
|
if (this.unblock_timeout !== undefined) params.set('unblock_timeout', String(this.unblock_timeout));
|
|
112
192
|
if (this.browser_brand !== undefined) params.set('browser_brand', this.browser_brand);
|
|
113
193
|
if (this.enable_mcp !== undefined) params.set('enable_mcp', String(this.enable_mcp));
|
|
194
|
+
if (this.solve_captcha !== undefined) params.set('solve_captcha', String(this.solve_captcha));
|
|
114
195
|
|
|
115
196
|
const baseHost = host || 'wss://browser.scrapfly.io';
|
|
116
197
|
return `${baseHost}?${params.toString()}`;
|
package/src/client.ts
CHANGED
|
@@ -17,17 +17,43 @@ import {
|
|
|
17
17
|
type MonitoringMetricsOptions,
|
|
18
18
|
type MonitoringTargetMetricsOptions,
|
|
19
19
|
} from './monitoringconfig.js';
|
|
20
|
-
|
|
20
|
+
import {
|
|
21
|
+
ScheduleAPIError,
|
|
22
|
+
type CreateScheduleRequest,
|
|
23
|
+
type ListSchedulesOptions,
|
|
24
|
+
type Schedule,
|
|
25
|
+
type UpdateScheduleRequest,
|
|
26
|
+
} from './schedule.js';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Main entry point for the Scrapfly SDK.
|
|
30
|
+
*
|
|
31
|
+
* A single `ScrapflyClient` can be used to call every Scrapfly API
|
|
32
|
+
* (scrape, screenshot, extraction, crawler, monitoring, cloud browser).
|
|
33
|
+
* It is safe to share one instance across concurrent calls.
|
|
34
|
+
*/
|
|
21
35
|
export class ScrapflyClient {
|
|
36
|
+
/** Base URL of the Scrapfly REST API. */
|
|
22
37
|
public HOST = 'https://api.scrapfly.io';
|
|
38
|
+
/** Default Cloud Browser WebSocket host. */
|
|
23
39
|
public CLOUD_BROWSER_HOST = 'wss://browser.scrapfly.io';
|
|
40
|
+
/** Default Cloud Browser REST host (derived from the WS host). */
|
|
24
41
|
public CLOUD_BROWSER_API_HOST = 'https://browser.scrapfly.io';
|
|
25
42
|
private key: string;
|
|
26
43
|
private ua: string;
|
|
27
44
|
private cloudBrowserHost: string;
|
|
28
45
|
private cloudBrowserApiHost: string;
|
|
29
|
-
fetch
|
|
46
|
+
/** `fetch` implementation used by the client. Override for custom retries/tracing. */
|
|
47
|
+
fetch: typeof fetchRetry = fetchRetry;
|
|
30
48
|
|
|
49
|
+
/**
|
|
50
|
+
* Create a Scrapfly client.
|
|
51
|
+
*
|
|
52
|
+
* @param options.key Scrapfly API key.
|
|
53
|
+
* @param options.host Optional override for the REST API host.
|
|
54
|
+
* @param options.cloudBrowserHost Optional override for the Cloud Browser WS host.
|
|
55
|
+
* @throws {@link errors.BadApiKeyError} if `options.key` is not a non-empty string.
|
|
56
|
+
*/
|
|
31
57
|
constructor(options: { key: string; host?: string; cloudBrowserHost?: string }) {
|
|
32
58
|
if (typeof options.key !== 'string' || options.key.trim() === '') {
|
|
33
59
|
throw new errors.BadApiKeyError('Invalid key. Key must be a non-empty string');
|
|
@@ -284,6 +310,7 @@ export class ScrapflyClient {
|
|
|
284
310
|
// Cloud Browser is session-based and exposes a distinct shape.
|
|
285
311
|
// See https://scrapfly.io/docs/monitoring#api
|
|
286
312
|
|
|
313
|
+
/** Dispatch an HTTP GET against a Monitoring API path with the given query params, parsing errors. */
|
|
287
314
|
private async monitoringRequest(path: string, params: Rec<string>): Promise<Rec<any>> {
|
|
288
315
|
const url = new URL(this.HOST + path);
|
|
289
316
|
url.search = new URLSearchParams(params).toString();
|
|
@@ -306,6 +333,7 @@ export class ScrapflyClient {
|
|
|
306
333
|
return data;
|
|
307
334
|
}
|
|
308
335
|
|
|
336
|
+
/** Build the query string for a request-based Monitoring API metrics endpoint. */
|
|
309
337
|
private buildMetricsParams(options: MonitoringMetricsOptions): Rec<string> {
|
|
310
338
|
const params: Rec<string> = {
|
|
311
339
|
key: this.key,
|
|
@@ -319,6 +347,7 @@ export class ScrapflyClient {
|
|
|
319
347
|
return params;
|
|
320
348
|
}
|
|
321
349
|
|
|
350
|
+
/** Build the query string for a per-target Monitoring API endpoint. */
|
|
322
351
|
private buildTargetParams(options: MonitoringTargetMetricsOptions): Rec<string> {
|
|
323
352
|
if ((options.start && !options.end) || (!options.start && options.end)) {
|
|
324
353
|
throw new Error('You must provide both start and end date');
|
|
@@ -340,55 +369,61 @@ export class ScrapflyClient {
|
|
|
340
369
|
return params;
|
|
341
370
|
}
|
|
342
371
|
|
|
343
|
-
|
|
372
|
+
/** Fetch Web Scraping API monitoring metrics (aggregate). */
|
|
344
373
|
async getMonitoringMetrics(options: MonitoringMetricsOptions = {}): Promise<Rec<any>> {
|
|
345
374
|
return this.monitoringRequest('/scrape/monitoring/metrics', this.buildMetricsParams(options));
|
|
346
375
|
}
|
|
347
376
|
|
|
377
|
+
/** Fetch Web Scraping API monitoring metrics for a single target domain. */
|
|
348
378
|
async getMonitoringTargetMetrics(options: MonitoringTargetMetricsOptions): Promise<Rec<any>> {
|
|
349
379
|
return this.monitoringRequest('/scrape/monitoring/metrics/target', this.buildTargetParams(options));
|
|
350
380
|
}
|
|
351
381
|
|
|
352
|
-
|
|
382
|
+
/** Fetch Screenshot API monitoring metrics (aggregate). */
|
|
353
383
|
async getScreenshotMonitoringMetrics(options: MonitoringMetricsOptions = {}): Promise<Rec<any>> {
|
|
354
384
|
return this.monitoringRequest('/screenshot/monitoring/metrics', this.buildMetricsParams(options));
|
|
355
385
|
}
|
|
356
386
|
|
|
387
|
+
/** Fetch Screenshot API monitoring metrics for a single target domain. */
|
|
357
388
|
async getScreenshotMonitoringTargetMetrics(options: MonitoringTargetMetricsOptions): Promise<Rec<any>> {
|
|
358
389
|
return this.monitoringRequest('/screenshot/monitoring/metrics/target', this.buildTargetParams(options));
|
|
359
390
|
}
|
|
360
391
|
|
|
361
|
-
|
|
392
|
+
/** Fetch Extraction API monitoring metrics (aggregate). */
|
|
362
393
|
async getExtractionMonitoringMetrics(options: MonitoringMetricsOptions = {}): Promise<Rec<any>> {
|
|
363
394
|
return this.monitoringRequest('/extraction/monitoring/metrics', this.buildMetricsParams(options));
|
|
364
395
|
}
|
|
365
396
|
|
|
397
|
+
/** Fetch Extraction API monitoring metrics for a single target domain. */
|
|
366
398
|
async getExtractionMonitoringTargetMetrics(options: MonitoringTargetMetricsOptions): Promise<Rec<any>> {
|
|
367
399
|
return this.monitoringRequest('/extraction/monitoring/metrics/target', this.buildTargetParams(options));
|
|
368
400
|
}
|
|
369
401
|
|
|
370
|
-
|
|
402
|
+
/** Fetch Crawler API monitoring metrics (aggregate). */
|
|
371
403
|
async getCrawlerMonitoringMetrics(options: MonitoringMetricsOptions = {}): Promise<Rec<any>> {
|
|
372
404
|
return this.monitoringRequest('/crawl/monitoring/metrics', this.buildMetricsParams(options));
|
|
373
405
|
}
|
|
374
406
|
|
|
407
|
+
/** Fetch Crawler API monitoring metrics for a single target domain. */
|
|
375
408
|
async getCrawlerMonitoringTargetMetrics(options: MonitoringTargetMetricsOptions): Promise<Rec<any>> {
|
|
376
409
|
return this.monitoringRequest('/crawl/monitoring/metrics/target', this.buildTargetParams(options));
|
|
377
410
|
}
|
|
378
411
|
|
|
379
|
-
|
|
412
|
+
/** Fetch Cloud Browser monitoring metrics (session-based aggregate). */
|
|
380
413
|
async getBrowserMonitoringMetrics(
|
|
381
414
|
options: CloudBrowserMonitoringOptions = {},
|
|
382
415
|
): Promise<Rec<any>> {
|
|
383
416
|
return this.monitoringRequest('/browser/monitoring/metrics', this.buildBrowserParams(options));
|
|
384
417
|
}
|
|
385
418
|
|
|
419
|
+
/** Fetch Cloud Browser monitoring timeseries (per-minute session usage). */
|
|
386
420
|
async getBrowserMonitoringTimeseries(
|
|
387
421
|
options: CloudBrowserMonitoringOptions = {},
|
|
388
422
|
): Promise<Rec<any>> {
|
|
389
423
|
return this.monitoringRequest('/browser/monitoring/metrics/timeseries', this.buildBrowserParams(options));
|
|
390
424
|
}
|
|
391
425
|
|
|
426
|
+
/** Build the query string for the session-based Cloud Browser Monitoring endpoints. */
|
|
392
427
|
private buildBrowserParams(options: CloudBrowserMonitoringOptions): Rec<string> {
|
|
393
428
|
if ((options.start && !options.end) || (!options.start && options.end)) {
|
|
394
429
|
throw new Error('You must provide both start and end date');
|
|
@@ -1294,6 +1329,7 @@ export class ScrapflyClient {
|
|
|
1294
1329
|
body?: string;
|
|
1295
1330
|
method?: string;
|
|
1296
1331
|
enable_mcp?: boolean;
|
|
1332
|
+
solve_captcha?: boolean;
|
|
1297
1333
|
}): Promise<{ ws_url: string; session_id: string; run_id: string; mcp_endpoint?: string }> {
|
|
1298
1334
|
const proxyPoolMap: Record<string, string> = {
|
|
1299
1335
|
datacenter: 'public_datacenter_pool',
|
|
@@ -1310,6 +1346,7 @@ export class ScrapflyClient {
|
|
|
1310
1346
|
if (options.body) jsonBody.body = options.body;
|
|
1311
1347
|
if (options.method) jsonBody.method = options.method;
|
|
1312
1348
|
if (options.enable_mcp !== undefined) jsonBody.enable_mcp = options.enable_mcp;
|
|
1349
|
+
if (options.solve_captcha !== undefined) jsonBody.solve_captcha = options.solve_captcha;
|
|
1313
1350
|
|
|
1314
1351
|
const url = new URL(this.cloudBrowserApiHost + '/unblock');
|
|
1315
1352
|
url.searchParams.set('key', this.key);
|
|
@@ -1527,6 +1564,189 @@ export class ScrapflyClient {
|
|
|
1527
1564
|
}
|
|
1528
1565
|
return await response.json() as { sessions: any[]; total: number };
|
|
1529
1566
|
}
|
|
1567
|
+
|
|
1568
|
+
// -------------------------------------------------------------------------
|
|
1569
|
+
// Public schedule endpoints — /scrape/schedules, /screenshot/schedules,
|
|
1570
|
+
// /crawl/schedules, /schedules. The kind-specific config is supplied to the
|
|
1571
|
+
// matching `create*Schedule` method; the cross-kind list/get/update/delete/
|
|
1572
|
+
// pause/resume/execute methods work regardless of kind.
|
|
1573
|
+
// -------------------------------------------------------------------------
|
|
1574
|
+
|
|
1575
|
+
/** Create a Web Scraping API schedule. `scrape_config` is the same shape
|
|
1576
|
+
* accepted by `/scrape` (e.g. `{ url, render_js, asp, ... }`). */
|
|
1577
|
+
async createScrapeSchedule(
|
|
1578
|
+
scrapeConfig: Record<string, unknown>,
|
|
1579
|
+
request: CreateScheduleRequest,
|
|
1580
|
+
): Promise<Schedule> {
|
|
1581
|
+
return await this.scheduleRequest(
|
|
1582
|
+
'POST',
|
|
1583
|
+
'/scrape/schedules',
|
|
1584
|
+
undefined,
|
|
1585
|
+
this.buildCreateBody('scrape_config', scrapeConfig, request),
|
|
1586
|
+
) as Schedule;
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
/** Create a Screenshot API schedule. */
|
|
1590
|
+
async createScreenshotSchedule(
|
|
1591
|
+
screenshotConfig: Record<string, unknown>,
|
|
1592
|
+
request: CreateScheduleRequest,
|
|
1593
|
+
): Promise<Schedule> {
|
|
1594
|
+
return await this.scheduleRequest(
|
|
1595
|
+
'POST',
|
|
1596
|
+
'/screenshot/schedules',
|
|
1597
|
+
undefined,
|
|
1598
|
+
this.buildCreateBody('screenshot_config', screenshotConfig, request),
|
|
1599
|
+
) as Schedule;
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
/** Create a Crawler API schedule. */
|
|
1603
|
+
async createCrawlerSchedule(
|
|
1604
|
+
crawlerConfig: Record<string, unknown>,
|
|
1605
|
+
request: CreateScheduleRequest,
|
|
1606
|
+
): Promise<Schedule> {
|
|
1607
|
+
return await this.scheduleRequest(
|
|
1608
|
+
'POST',
|
|
1609
|
+
'/crawl/schedules',
|
|
1610
|
+
undefined,
|
|
1611
|
+
this.buildCreateBody('crawler_config', crawlerConfig, request),
|
|
1612
|
+
) as Schedule;
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
/** Return a schedule by id. Works across all kinds. */
|
|
1616
|
+
async getSchedule(id: string): Promise<Schedule> {
|
|
1617
|
+
return await this.scheduleRequest('GET', `/schedules/${encodeURIComponent(id)}`) as Schedule;
|
|
1618
|
+
}
|
|
1619
|
+
|
|
1620
|
+
/** List every schedule on the account, optionally filtered by kind/status. */
|
|
1621
|
+
async listSchedules(opts?: ListSchedulesOptions): Promise<Schedule[]> {
|
|
1622
|
+
return await this.scheduleRequest(
|
|
1623
|
+
'GET',
|
|
1624
|
+
'/schedules',
|
|
1625
|
+
opts as Record<string, string | undefined> | undefined,
|
|
1626
|
+
) as Schedule[];
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
async listScrapeSchedules(opts?: { status?: string }): Promise<Schedule[]> {
|
|
1630
|
+
return await this.scheduleRequest('GET', '/scrape/schedules', opts) as Schedule[];
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
async listScreenshotSchedules(opts?: { status?: string }): Promise<Schedule[]> {
|
|
1634
|
+
return await this.scheduleRequest('GET', '/screenshot/schedules', opts) as Schedule[];
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
async listCrawlerSchedules(opts?: { status?: string }): Promise<Schedule[]> {
|
|
1638
|
+
return await this.scheduleRequest('GET', '/crawl/schedules', opts) as Schedule[];
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
/** Patch an active schedule. Only fields set in `request` change. */
|
|
1642
|
+
async updateSchedule(id: string, request: UpdateScheduleRequest): Promise<Schedule> {
|
|
1643
|
+
return await this.scheduleRequest(
|
|
1644
|
+
'PATCH',
|
|
1645
|
+
`/schedules/${encodeURIComponent(id)}`,
|
|
1646
|
+
undefined,
|
|
1647
|
+
request as Record<string, unknown>,
|
|
1648
|
+
) as Schedule;
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
/** Cancel a schedule. Cancellation is terminal (returns no body). */
|
|
1652
|
+
async cancelSchedule(id: string): Promise<void> {
|
|
1653
|
+
await this.scheduleRequest('DELETE', `/schedules/${encodeURIComponent(id)}`);
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
async pauseSchedule(id: string): Promise<Schedule> {
|
|
1657
|
+
return await this.scheduleRequest(
|
|
1658
|
+
'POST',
|
|
1659
|
+
`/schedules/${encodeURIComponent(id)}/pause`,
|
|
1660
|
+
) as Schedule;
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
async resumeSchedule(id: string): Promise<Schedule> {
|
|
1664
|
+
return await this.scheduleRequest(
|
|
1665
|
+
'POST',
|
|
1666
|
+
`/schedules/${encodeURIComponent(id)}/resume`,
|
|
1667
|
+
) as Schedule;
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
/** Fire a schedule immediately, regardless of next_scheduled_date. */
|
|
1671
|
+
async executeSchedule(id: string): Promise<Schedule> {
|
|
1672
|
+
return await this.scheduleRequest(
|
|
1673
|
+
'POST',
|
|
1674
|
+
`/schedules/${encodeURIComponent(id)}/execute`,
|
|
1675
|
+
) as Schedule;
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
private buildCreateBody(
|
|
1679
|
+
configKey: string,
|
|
1680
|
+
config: Record<string, unknown>,
|
|
1681
|
+
request: CreateScheduleRequest,
|
|
1682
|
+
): Record<string, unknown> {
|
|
1683
|
+
const body: Record<string, unknown> = {
|
|
1684
|
+
[configKey]: config,
|
|
1685
|
+
webhook_name: request.webhook_name,
|
|
1686
|
+
allow_concurrency: request.allow_concurrency ?? false,
|
|
1687
|
+
retry_on_failure: request.retry_on_failure ?? false,
|
|
1688
|
+
};
|
|
1689
|
+
if (request.recurrence) body.recurrence = request.recurrence;
|
|
1690
|
+
if (request.scheduled_date) body.scheduled_date = request.scheduled_date;
|
|
1691
|
+
if (typeof request.max_retries === 'number') body.max_retries = request.max_retries;
|
|
1692
|
+
if (request.notes) body.notes = request.notes;
|
|
1693
|
+
return body;
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
private async scheduleRequest(
|
|
1697
|
+
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
|
|
1698
|
+
path: string,
|
|
1699
|
+
query?: Record<string, string | undefined>,
|
|
1700
|
+
body?: Record<string, unknown>,
|
|
1701
|
+
): Promise<unknown> {
|
|
1702
|
+
const url = new URL(this.HOST + path);
|
|
1703
|
+
const params = new URLSearchParams();
|
|
1704
|
+
params.set('key', this.key);
|
|
1705
|
+
if (query) {
|
|
1706
|
+
for (const [k, v] of Object.entries(query)) {
|
|
1707
|
+
if (v !== undefined && v !== '') params.set(k, v);
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
url.search = params.toString();
|
|
1711
|
+
|
|
1712
|
+
const init: { url: string; method: string; headers: Record<string, string>; body?: string } = {
|
|
1713
|
+
url: url.toString(),
|
|
1714
|
+
method,
|
|
1715
|
+
headers: {
|
|
1716
|
+
'user-agent': this.ua,
|
|
1717
|
+
accept: 'application/json',
|
|
1718
|
+
},
|
|
1719
|
+
};
|
|
1720
|
+
if (body !== undefined) {
|
|
1721
|
+
init.body = JSON.stringify(body);
|
|
1722
|
+
init.headers['content-type'] = 'application/json';
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
const response = await this.fetch(init as any);
|
|
1726
|
+
|
|
1727
|
+
if (response.status === 204) return undefined;
|
|
1728
|
+
if (!response.ok) {
|
|
1729
|
+
let envelope: { error?: string; message?: string; reason?: string; details?: unknown } = {};
|
|
1730
|
+
try {
|
|
1731
|
+
envelope = await response.json() as typeof envelope;
|
|
1732
|
+
} catch {
|
|
1733
|
+
// body wasn't JSON; fall through with the empty envelope
|
|
1734
|
+
}
|
|
1735
|
+
const code = envelope.error ?? 'ERR::SCHEDULER::BACKEND_ERROR';
|
|
1736
|
+
let message = envelope.message ?? '';
|
|
1737
|
+
if (envelope.reason) {
|
|
1738
|
+
message = message ? `${message} (${envelope.reason})` : envelope.reason;
|
|
1739
|
+
}
|
|
1740
|
+
if (!message) message = `HTTP ${response.status}`;
|
|
1741
|
+
throw new ScheduleAPIError({
|
|
1742
|
+
code,
|
|
1743
|
+
message,
|
|
1744
|
+
httpStatusCode: response.status,
|
|
1745
|
+
details: envelope.details,
|
|
1746
|
+
});
|
|
1747
|
+
}
|
|
1748
|
+
return await response.json();
|
|
1749
|
+
}
|
|
1530
1750
|
}
|
|
1531
1751
|
|
|
1532
1752
|
// ---------------------------------------------------------------------------
|
package/src/crawl.ts
CHANGED
|
@@ -46,6 +46,10 @@ export class Crawl {
|
|
|
46
46
|
private _status?: CrawlerStatus;
|
|
47
47
|
private readonly _artifactCache: Map<CrawlerArtifactType, CrawlerArtifact> = new Map();
|
|
48
48
|
|
|
49
|
+
/**
|
|
50
|
+
* @param client Configured {@link ScrapflyClient} that performs the HTTP calls.
|
|
51
|
+
* @param config Crawler configuration to submit on {@link Crawl.start}.
|
|
52
|
+
*/
|
|
49
53
|
constructor(private readonly client: ScrapflyClient, private readonly config: CrawlerConfig) {}
|
|
50
54
|
|
|
51
55
|
/** The crawler UUID returned by the API after `start()`, or undefined before. */
|
package/src/crawlerresult.ts
CHANGED
|
@@ -82,12 +82,19 @@ export type CrawlerStopReason =
|
|
|
82
82
|
* `duration` is always a number (0 when nothing has happened yet).
|
|
83
83
|
*/
|
|
84
84
|
export interface CrawlerState {
|
|
85
|
+
/** Number of URLs the crawler has fetched. */
|
|
85
86
|
urls_visited: number;
|
|
87
|
+
/** Number of URLs from which content or links were extracted. */
|
|
86
88
|
urls_extracted: number;
|
|
89
|
+
/** Number of URLs that failed to fetch. */
|
|
87
90
|
urls_failed: number;
|
|
91
|
+
/** Number of URLs skipped (filtered out, duplicate, limit hit, ...). */
|
|
88
92
|
urls_skipped: number;
|
|
93
|
+
/** Number of URLs queued for future fetch. */
|
|
89
94
|
urls_to_crawl: number;
|
|
95
|
+
/** API credits consumed so far. */
|
|
90
96
|
api_credit_used: number;
|
|
97
|
+
/** Elapsed time in seconds since the crawl started (0 while PENDING). */
|
|
91
98
|
duration: number;
|
|
92
99
|
/** `null` until the crawler stops. */
|
|
93
100
|
stop_reason: CrawlerStopReason | null;
|
package/src/errors.ts
CHANGED
|
@@ -1,55 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base class for every error thrown by the Scrapfly SDK.
|
|
3
|
+
*
|
|
4
|
+
* Concrete subclasses distinguish config-level, HTTP-level, and
|
|
5
|
+
* API-specific failures so callers can catch the exact category they
|
|
6
|
+
* care about without string-matching on error messages.
|
|
7
|
+
*/
|
|
1
8
|
export class ScrapflyError extends Error {
|
|
9
|
+
/** Extra context carried alongside the error message (response body, request params, etc.). */
|
|
2
10
|
args: Record<string, any>;
|
|
3
11
|
|
|
12
|
+
/**
|
|
13
|
+
* @param message Human-readable description of the failure.
|
|
14
|
+
* @param args Optional structured context to attach to the error.
|
|
15
|
+
*/
|
|
4
16
|
constructor(message: string, args: Record<string, any> = {}) {
|
|
5
17
|
super(message);
|
|
6
18
|
this.args = args;
|
|
7
19
|
}
|
|
8
20
|
}
|
|
9
21
|
|
|
10
|
-
|
|
22
|
+
/** Raised when a ScrapeConfig is constructed with invalid parameters. */
|
|
11
23
|
export class ScrapeConfigError extends ScrapflyError {}
|
|
12
|
-
|
|
24
|
+
/** Raised when a ScreenshotConfig is constructed with invalid parameters. */
|
|
13
25
|
export class ScreenshotConfigError extends ScrapflyError {}
|
|
14
|
-
|
|
26
|
+
/** Raised when an ExtractionConfig is constructed with invalid parameters. */
|
|
15
27
|
export class ExtractionConfigError extends ScrapflyError {}
|
|
16
|
-
|
|
28
|
+
/** Raised when a CrawlerConfig is constructed with invalid parameters. */
|
|
17
29
|
export class CrawlerConfigError extends ScrapflyError {}
|
|
18
30
|
|
|
19
|
-
|
|
31
|
+
/** Raised when scrape parameters cannot be encoded into a request. */
|
|
20
32
|
export class EncodeError extends ScrapflyError {}
|
|
33
|
+
/** Raised when a response carries an unexpected or unsupported Content-Type. */
|
|
21
34
|
export class ContentTypeError extends ScrapflyError {}
|
|
22
35
|
|
|
23
|
-
|
|
36
|
+
/** Base error for every HTTP-level failure surfaced by the SDK. */
|
|
24
37
|
export class HttpError extends ScrapflyError {}
|
|
38
|
+
/** Raised when the upstream target returned an error to Scrapfly. */
|
|
25
39
|
export class UpstreamHttpError extends HttpError {}
|
|
40
|
+
/** Raised when the upstream target returned a 4xx client error. */
|
|
26
41
|
export class UpstreamHttpClientError extends UpstreamHttpError {}
|
|
42
|
+
/** Raised when the upstream target returned a 5xx server error. */
|
|
27
43
|
export class UpstreamHttpServerError extends UpstreamHttpClientError {}
|
|
28
44
|
|
|
45
|
+
/** Raised when the Scrapfly API itself returned a 4xx client error. */
|
|
29
46
|
export class ApiHttpClientError extends HttpError {}
|
|
30
|
-
|
|
47
|
+
/** Raised when the API key provided to the client is missing, invalid, or revoked. */
|
|
31
48
|
export class BadApiKeyError extends ApiHttpClientError {}
|
|
32
49
|
|
|
50
|
+
/** Raised when the request is rate-limited (HTTP 429). */
|
|
33
51
|
export class TooManyRequests extends HttpError {}
|
|
52
|
+
/** Raised when the Scrapfly API returned a 5xx server error. */
|
|
34
53
|
export class ApiHttpServerError extends HttpError {}
|
|
54
|
+
/** Raised when a scrape call fails for a reason not captured by a more specific subclass. */
|
|
35
55
|
export class ScrapflyScrapeError extends HttpError {}
|
|
36
|
-
|
|
56
|
+
/** Raised when proxy settings do not match an available proxy (invalid pool, unsupported country, ...). */
|
|
37
57
|
export class ScrapflyProxyError extends HttpError {}
|
|
58
|
+
/** Raised when the request is throttled by Scrapfly (e.g. burst limits). */
|
|
38
59
|
export class ScrapflyThrottleError extends HttpError {}
|
|
39
|
-
|
|
60
|
+
/** Raised when Scrapfly failed to bypass anti-scraping protection on the target. */
|
|
40
61
|
export class ScrapflyAspError extends HttpError {}
|
|
62
|
+
/** Raised when a scheduled scrape cannot be created or fulfilled. */
|
|
41
63
|
export class ScrapflyScheduleError extends HttpError {}
|
|
42
|
-
|
|
64
|
+
/** Raised when a webhook is invalid or cannot be delivered (e.g. full queue). */
|
|
43
65
|
export class ScrapflyWebhookError extends HttpError {}
|
|
44
|
-
|
|
66
|
+
/** Raised when a session is accessed concurrently in a way that violates session semantics. */
|
|
45
67
|
export class ScrapflySessionError extends HttpError {}
|
|
46
|
-
|
|
68
|
+
/** Raised when concurrent requests exceed the account's concurrency limit. */
|
|
47
69
|
export class TooManyConcurrentRequests extends HttpError {}
|
|
48
|
-
|
|
70
|
+
/** Raised when the account is out of scrape credits. */
|
|
49
71
|
export class QuotaLimitReached extends HttpError {}
|
|
50
|
-
|
|
72
|
+
/** Raised for screenshot-API-specific failures. */
|
|
51
73
|
export class ScreenshotApiError extends ApiHttpClientError {}
|
|
52
|
-
|
|
74
|
+
/** Raised for extraction-API-specific failures. */
|
|
53
75
|
export class ExtractionApiError extends ApiHttpClientError {}
|
|
54
|
-
|
|
76
|
+
/**
|
|
77
|
+
* Raised for crawler-API-specific failures.
|
|
78
|
+
*
|
|
79
|
+
* Covers crawler job lifecycle errors such as ALREADY_STARTED,
|
|
80
|
+
* NOT_STARTED, FAILED, CANCELLED, TIMEOUT, etc.
|
|
81
|
+
*/
|
|
55
82
|
export class ScrapflyCrawlerError extends HttpError {}
|