scrapfly-sdk 0.10.3 → 0.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/package.json +1 -1
  2. package/src/_dnt.shims.ts +64 -0
  3. package/src/batch.ts +272 -0
  4. package/src/browserconfig.ts +118 -0
  5. package/src/client.ts +1609 -0
  6. package/src/crawl.ts +251 -0
  7. package/src/crawlerconfig.ts +363 -0
  8. package/src/crawlerresult.ts +471 -0
  9. package/src/deps/jsr.io/@std/path/1.0.1/_common/assert_path.ts +10 -0
  10. package/src/deps/jsr.io/@std/path/1.0.1/_common/basename.ts +53 -0
  11. package/src/deps/jsr.io/@std/path/1.0.1/_common/common.ts +26 -0
  12. package/src/deps/jsr.io/@std/path/1.0.1/_common/constants.ts +49 -0
  13. package/src/deps/jsr.io/@std/path/1.0.1/_common/dirname.ts +9 -0
  14. package/src/deps/jsr.io/@std/path/1.0.1/_common/format.ts +25 -0
  15. package/src/deps/jsr.io/@std/path/1.0.1/_common/from_file_url.ts +10 -0
  16. package/src/deps/jsr.io/@std/path/1.0.1/_common/glob_to_reg_exp.ts +290 -0
  17. package/src/deps/jsr.io/@std/path/1.0.1/_common/normalize.ts +9 -0
  18. package/src/deps/jsr.io/@std/path/1.0.1/_common/normalize_string.ts +74 -0
  19. package/src/deps/jsr.io/@std/path/1.0.1/_common/relative.ts +10 -0
  20. package/src/deps/jsr.io/@std/path/1.0.1/_common/strip_trailing_separators.ts +25 -0
  21. package/src/deps/jsr.io/@std/path/1.0.1/_common/to_file_url.ts +17 -0
  22. package/src/deps/jsr.io/@std/path/1.0.1/_os.ts +31 -0
  23. package/src/deps/jsr.io/@std/path/1.0.1/basename.ts +35 -0
  24. package/src/deps/jsr.io/@std/path/1.0.1/common.ts +35 -0
  25. package/src/deps/jsr.io/@std/path/1.0.1/constants.ts +18 -0
  26. package/src/deps/jsr.io/@std/path/1.0.1/dirname.ts +28 -0
  27. package/src/deps/jsr.io/@std/path/1.0.1/extname.ts +27 -0
  28. package/src/deps/jsr.io/@std/path/1.0.1/format.ts +30 -0
  29. package/src/deps/jsr.io/@std/path/1.0.1/from_file_url.ts +30 -0
  30. package/src/deps/jsr.io/@std/path/1.0.1/glob_to_regexp.ts +94 -0
  31. package/src/deps/jsr.io/@std/path/1.0.1/is_absolute.ts +30 -0
  32. package/src/deps/jsr.io/@std/path/1.0.1/is_glob.ts +49 -0
  33. package/src/deps/jsr.io/@std/path/1.0.1/join.ts +28 -0
  34. package/src/deps/jsr.io/@std/path/1.0.1/join_globs.ts +42 -0
  35. package/src/deps/jsr.io/@std/path/1.0.1/mod.ts +55 -0
  36. package/src/deps/jsr.io/@std/path/1.0.1/normalize.ts +31 -0
  37. package/src/deps/jsr.io/@std/path/1.0.1/normalize_glob.ts +45 -0
  38. package/src/deps/jsr.io/@std/path/1.0.1/parse.ts +44 -0
  39. package/src/deps/jsr.io/@std/path/1.0.1/posix/_util.ts +10 -0
  40. package/src/deps/jsr.io/@std/path/1.0.1/posix/basename.ts +39 -0
  41. package/src/deps/jsr.io/@std/path/1.0.1/posix/constants.ts +15 -0
  42. package/src/deps/jsr.io/@std/path/1.0.1/posix/dirname.ts +55 -0
  43. package/src/deps/jsr.io/@std/path/1.0.1/posix/extname.ts +73 -0
  44. package/src/deps/jsr.io/@std/path/1.0.1/posix/format.ts +31 -0
  45. package/src/deps/jsr.io/@std/path/1.0.1/posix/from_file_url.ts +25 -0
  46. package/src/deps/jsr.io/@std/path/1.0.1/posix/glob_to_regexp.ts +94 -0
  47. package/src/deps/jsr.io/@std/path/1.0.1/posix/is_absolute.ts +25 -0
  48. package/src/deps/jsr.io/@std/path/1.0.1/posix/join.ts +27 -0
  49. package/src/deps/jsr.io/@std/path/1.0.1/posix/join_globs.ts +44 -0
  50. package/src/deps/jsr.io/@std/path/1.0.1/posix/normalize.ts +41 -0
  51. package/src/deps/jsr.io/@std/path/1.0.1/posix/normalize_glob.ts +42 -0
  52. package/src/deps/jsr.io/@std/path/1.0.1/posix/parse.ts +121 -0
  53. package/src/deps/jsr.io/@std/path/1.0.1/posix/relative.ts +103 -0
  54. package/src/deps/jsr.io/@std/path/1.0.1/posix/resolve.ts +69 -0
  55. package/src/deps/jsr.io/@std/path/1.0.1/posix/to_file_url.ts +32 -0
  56. package/src/deps/jsr.io/@std/path/1.0.1/posix/to_namespaced_path.ts +21 -0
  57. package/src/deps/jsr.io/@std/path/1.0.1/relative.ts +32 -0
  58. package/src/deps/jsr.io/@std/path/1.0.1/resolve.ts +32 -0
  59. package/src/deps/jsr.io/@std/path/1.0.1/to_file_url.ts +30 -0
  60. package/src/deps/jsr.io/@std/path/1.0.1/to_namespaced_path.ts +31 -0
  61. package/src/deps/jsr.io/@std/path/1.0.1/types.ts +40 -0
  62. package/src/deps/jsr.io/@std/path/1.0.1/windows/_util.ts +28 -0
  63. package/src/deps/jsr.io/@std/path/1.0.1/windows/basename.ts +48 -0
  64. package/src/deps/jsr.io/@std/path/1.0.1/windows/constants.ts +15 -0
  65. package/src/deps/jsr.io/@std/path/1.0.1/windows/dirname.ts +114 -0
  66. package/src/deps/jsr.io/@std/path/1.0.1/windows/extname.ts +86 -0
  67. package/src/deps/jsr.io/@std/path/1.0.1/windows/format.ts +31 -0
  68. package/src/deps/jsr.io/@std/path/1.0.1/windows/from_file_url.ts +34 -0
  69. package/src/deps/jsr.io/@std/path/1.0.1/windows/glob_to_regexp.ts +92 -0
  70. package/src/deps/jsr.io/@std/path/1.0.1/windows/is_absolute.ts +40 -0
  71. package/src/deps/jsr.io/@std/path/1.0.1/windows/join.ts +72 -0
  72. package/src/deps/jsr.io/@std/path/1.0.1/windows/join_globs.ts +45 -0
  73. package/src/deps/jsr.io/@std/path/1.0.1/windows/normalize.ts +132 -0
  74. package/src/deps/jsr.io/@std/path/1.0.1/windows/normalize_glob.ts +42 -0
  75. package/src/deps/jsr.io/@std/path/1.0.1/windows/parse.ts +184 -0
  76. package/src/deps/jsr.io/@std/path/1.0.1/windows/relative.ts +128 -0
  77. package/src/deps/jsr.io/@std/path/1.0.1/windows/resolve.ts +174 -0
  78. package/src/deps/jsr.io/@std/path/1.0.1/windows/to_file_url.ts +38 -0
  79. package/src/deps/jsr.io/@std/path/1.0.1/windows/to_namespaced_path.ts +60 -0
  80. package/src/deps.ts +4 -0
  81. package/src/errors.ts +55 -0
  82. package/src/extractionconfig.ts +175 -0
  83. package/src/logger.ts +51 -0
  84. package/src/main.ts +61 -0
  85. package/src/monitoringconfig.ts +50 -0
  86. package/src/polyfill.ts +37 -0
  87. package/src/result.ts +338 -0
  88. package/src/scrapeconfig.ts +448 -0
  89. package/src/screenshotconfig.ts +204 -0
  90. package/src/types.ts +2 -0
  91. package/src/utils.ts +86 -0
  92. package/src/webhookserver.ts +66 -0
package/src/crawl.ts ADDED
@@ -0,0 +1,251 @@
1
+ import * as errors from './errors.js';
2
+ import { log } from './logger.js';
3
+ import type { ScrapflyClient } from './client.js';
4
+ import type { CrawlerConfig, CrawlerContentFormat } from './crawlerconfig.js';
5
+ import type {
6
+ CrawlerArtifact,
7
+ CrawlerArtifactType,
8
+ CrawlerContents,
9
+ CrawlerStatus,
10
+ CrawlerUrls,
11
+ } from './crawlerresult.js';
12
+
13
+ /**
14
+ * High-level fluent wrapper around a single crawler job lifecycle.
15
+ *
16
+ * Mirrors the Python SDK's `Crawl` class. Internally calls into `ScrapflyClient`'s
17
+ * lower-level crawler methods, but adds:
18
+ *
19
+ * - polling helpers (`wait()`)
20
+ * - per-instance caching of the most recent status and downloaded artifacts
21
+ * - convenience methods that pre-fill the crawler UUID
22
+ *
23
+ * Use this when you want a simple `start → wait → read` flow. Use the lower-level
24
+ * `client.crawl*` methods directly if you need finer control (e.g. polling at
25
+ * irregular intervals or reusing a status response across calls).
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * const crawl = new Crawl(client, new CrawlerConfig({
30
+ * url: 'https://web-scraping.dev/products',
31
+ * page_limit: 10,
32
+ * content_formats: ['markdown'],
33
+ * }));
34
+ *
35
+ * await crawl.start();
36
+ * await crawl.wait({ pollInterval: 2 });
37
+ *
38
+ * for (const entry of (await crawl.urls({ status: 'visited' })).urls) {
39
+ * const md = await crawl.read(entry.url, 'markdown');
40
+ * console.log(entry.url, md?.length);
41
+ * }
42
+ * ```
43
+ */
44
+ export class Crawl {
45
+ private _uuid?: string;
46
+ private _status?: CrawlerStatus;
47
+ private readonly _artifactCache: Map<CrawlerArtifactType, CrawlerArtifact> = new Map();
48
+
49
+ constructor(private readonly client: ScrapflyClient, private readonly config: CrawlerConfig) {}
50
+
51
+ /** The crawler UUID returned by the API after `start()`, or undefined before. */
52
+ get uuid(): string | undefined {
53
+ return this._uuid;
54
+ }
55
+
56
+ /** True once `start()` has been called and the crawler has a UUID. */
57
+ get started(): boolean {
58
+ return this._uuid !== undefined;
59
+ }
60
+
61
+ /**
62
+ * Schedule the crawl on the Scrapfly API.
63
+ *
64
+ * Returns `this` for chaining. Throws `ScrapflyCrawlerError` if `start()` has
65
+ * already been called on this instance.
66
+ */
67
+ async start(): Promise<this> {
68
+ if (this._uuid) {
69
+ throw new errors.ScrapflyCrawlerError('Crawl already started', { code: 'ALREADY_STARTED' });
70
+ }
71
+ const response = await this.client.crawl(this.config);
72
+ this._uuid = response.crawler_uuid;
73
+ log.debug('crawl started', { crawler_uuid: this._uuid });
74
+ return this;
75
+ }
76
+
77
+ private requireUuid(): string {
78
+ if (!this._uuid) {
79
+ throw new errors.ScrapflyCrawlerError(
80
+ 'Crawl has not been started yet. Call start() first.',
81
+ { code: 'NOT_STARTED' },
82
+ );
83
+ }
84
+ return this._uuid;
85
+ }
86
+
87
+ /**
88
+ * Fetch (or return cached) status for this crawl.
89
+ *
90
+ * @param refresh — when true (default), always re-query the API. When false,
91
+ * return the cached status from the previous call (or fetch fresh if none).
92
+ */
93
+ async status(refresh = true): Promise<CrawlerStatus> {
94
+ const uuid = this.requireUuid();
95
+ if (refresh || !this._status) {
96
+ this._status = await this.client.crawlStatus(uuid);
97
+ }
98
+ return this._status;
99
+ }
100
+
101
+ /**
102
+ * Block until the crawler reaches a terminal state, polling status periodically.
103
+ *
104
+ * Returns `this` for chaining when the job completes successfully. Throws
105
+ * `ScrapflyCrawlerError` if the job fails, is cancelled, or `maxWait` is exceeded.
106
+ *
107
+ * @param opts.pollInterval — seconds between polls (default 5)
108
+ * @param opts.maxWait — maximum total seconds to wait (default: no limit)
109
+ * @param opts.verbose — log progress on every poll
110
+ * @param opts.allowCancelled — when `true`, return normally if the crawler
111
+ * reaches CANCELLED instead of throwing. Useful for the cancel-then-wait
112
+ * pattern where the caller already triggered the cancellation. Defaults
113
+ * to `false`, preserving the prior throw-on-cancel behavior for callers
114
+ * that observe external interrupts.
115
+ */
116
+ async wait(opts?: {
117
+ pollInterval?: number;
118
+ maxWait?: number;
119
+ verbose?: boolean;
120
+ allowCancelled?: boolean;
121
+ }): Promise<this> {
122
+ const pollInterval = opts?.pollInterval ?? 5;
123
+ const maxWait = opts?.maxWait;
124
+ const verbose = opts?.verbose ?? false;
125
+ const allowCancelled = opts?.allowCancelled ?? false;
126
+ const start = Date.now();
127
+
128
+ while (true) {
129
+ const status = await this.status(true);
130
+ if (verbose) {
131
+ log.info(
132
+ `crawl ${this._uuid} status=${status.status} visited=${status.state.urls_visited}/${status.state.urls_extracted}`,
133
+ );
134
+ }
135
+ if (status.is_finished || status.status === 'CANCELLED') {
136
+ if (status.isFailed) {
137
+ throw new errors.ScrapflyCrawlerError(
138
+ `Crawl ${this._uuid} failed: ${status.state.stop_reason ?? 'unknown reason'}`,
139
+ { code: 'FAILED', stop_reason: status.state.stop_reason, status },
140
+ );
141
+ }
142
+ if (status.isCancelled) {
143
+ if (allowCancelled) {
144
+ if (verbose) {
145
+ log.info(`crawl ${this._uuid} was cancelled (allowCancelled=true)`);
146
+ }
147
+ return this;
148
+ }
149
+ throw new errors.ScrapflyCrawlerError(
150
+ `Crawl ${this._uuid} was cancelled (reason: ${status.state.stop_reason ?? 'unknown'})`,
151
+ { code: 'CANCELLED', stop_reason: status.state.stop_reason, status },
152
+ );
153
+ }
154
+ // status.isComplete
155
+ return this;
156
+ }
157
+
158
+ if (maxWait !== undefined) {
159
+ const elapsedSeconds = (Date.now() - start) / 1000;
160
+ if (elapsedSeconds + pollInterval > maxWait) {
161
+ throw new errors.ScrapflyCrawlerError(
162
+ `Timed out waiting for crawl ${this._uuid} after ${maxWait}s`,
163
+ { code: 'TIMEOUT', status },
164
+ );
165
+ }
166
+ }
167
+
168
+ await new Promise((resolve) => setTimeout(resolve, pollInterval * 1000));
169
+ }
170
+ }
171
+
172
+ /** Cancel the crawl. Returns `true` on success. */
173
+ async cancel(): Promise<boolean> {
174
+ const uuid = this.requireUuid();
175
+ return await this.client.crawlCancel(uuid);
176
+ }
177
+
178
+ /**
179
+ * List crawled URLs (paginated, optionally filtered by status).
180
+ *
181
+ * Convenience wrapper around `client.crawlUrls(uuid, opts)`. **New endpoint** —
182
+ * not available in the Python SDK as of 0.8.27.
183
+ */
184
+ async urls(opts?: {
185
+ status?: 'visited' | 'pending' | 'failed';
186
+ page?: number;
187
+ per_page?: number;
188
+ }): Promise<CrawlerUrls> {
189
+ const uuid = this.requireUuid();
190
+ return await this.client.crawlUrls(uuid, opts);
191
+ }
192
+
193
+ /**
194
+ * Read raw content for a single crawled URL using `plain=true` mode.
195
+ *
196
+ * Returns `null` if the URL has no content for that format. Throws
197
+ * `ScrapflyCrawlerError` for any non-404 error. **New mode** — not available in
198
+ * the Python SDK as of 0.8.27.
199
+ */
200
+ async read(url: string, format: CrawlerContentFormat = 'html'): Promise<string | null> {
201
+ const uuid = this.requireUuid();
202
+ try {
203
+ const result = await this.client.crawlContents(uuid, { url, format, plain: true });
204
+ // crawlContents in plain mode always returns string
205
+ return typeof result === 'string' ? result : JSON.stringify(result);
206
+ } catch (e) {
207
+ // Treat 404 as "no content for this URL" rather than re-throwing
208
+ if (e instanceof errors.ScrapflyError && (e.args?.http_status_code === 404)) {
209
+ return null;
210
+ }
211
+ throw e;
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Batch-read content for multiple URLs in one round-trip.
217
+ *
218
+ * Convenience wrapper around `client.crawlContentsBatch`. Limited to 100 URLs.
219
+ */
220
+ async readBatch(
221
+ urls: string[],
222
+ formats: CrawlerContentFormat[] = ['html'],
223
+ ): Promise<Record<string, Record<string, string>>> {
224
+ const uuid = this.requireUuid();
225
+ return await this.client.crawlContentsBatch(uuid, urls, formats);
226
+ }
227
+
228
+ /**
229
+ * Download the WARC artifact (cached after first call).
230
+ */
231
+ async warc(): Promise<CrawlerArtifact> {
232
+ const uuid = this.requireUuid();
233
+ const cached = this._artifactCache.get('warc');
234
+ if (cached) return cached;
235
+ const artifact = await this.client.crawlArtifact(uuid, 'warc');
236
+ this._artifactCache.set('warc', artifact);
237
+ return artifact;
238
+ }
239
+
240
+ /**
241
+ * Download the HAR artifact (cached after first call).
242
+ */
243
+ async har(): Promise<CrawlerArtifact> {
244
+ const uuid = this.requireUuid();
245
+ const cached = this._artifactCache.get('har');
246
+ if (cached) return cached;
247
+ const artifact = await this.client.crawlArtifact(uuid, 'har');
248
+ this._artifactCache.set('har', artifact);
249
+ return artifact;
250
+ }
251
+ }
@@ -0,0 +1,363 @@
1
+ import { CrawlerConfigError } from './errors.js';
2
+ import type { Rec } from './types.js';
3
+
4
+ /**
5
+ * Content formats supported by the Crawler API.
6
+ *
7
+ * - `html` — original HTML
8
+ * - `clean_html` — sanitized/cleaned HTML
9
+ * - `markdown` — LLM-ready markdown
10
+ * - `text` — plain-text extraction
11
+ * - `json` — parse as JSON (for API responses)
12
+ * - `extracted_data` — structured data from extraction rules
13
+ * - `page_metadata` — title, description, etc.
14
+ */
15
+ export type CrawlerContentFormat =
16
+ | 'html'
17
+ | 'clean_html'
18
+ | 'markdown'
19
+ | 'text'
20
+ | 'json'
21
+ | 'extracted_data'
22
+ | 'page_metadata';
23
+
24
+ const VALID_CONTENT_FORMATS: ReadonlySet<string> = new Set([
25
+ 'html',
26
+ 'clean_html',
27
+ 'markdown',
28
+ 'text',
29
+ 'json',
30
+ 'extracted_data',
31
+ 'page_metadata',
32
+ ]);
33
+
34
+ /**
35
+ * Webhook event names emitted by the crawler.
36
+ *
37
+ * Source of truth: `apps/scrapfly/scrape-engine/scrape_engine/scrape_engine/crawler/webhook_manager.py`
38
+ * lines 11-20. Verified to match the public docs and the JSON example payloads.
39
+ */
40
+ export type CrawlerWebhookEventName =
41
+ | 'crawler_started'
42
+ | 'crawler_url_visited'
43
+ | 'crawler_url_skipped'
44
+ | 'crawler_url_discovered'
45
+ | 'crawler_url_failed'
46
+ | 'crawler_stopped'
47
+ | 'crawler_cancelled'
48
+ | 'crawler_finished';
49
+
50
+ const VALID_WEBHOOK_EVENTS: ReadonlySet<string> = new Set([
51
+ 'crawler_started',
52
+ 'crawler_url_visited',
53
+ 'crawler_url_skipped',
54
+ 'crawler_url_discovered',
55
+ 'crawler_url_failed',
56
+ 'crawler_stopped',
57
+ 'crawler_cancelled',
58
+ 'crawler_finished',
59
+ ]);
60
+
61
+ /**
62
+ * Constructor options for {@link CrawlerConfig}.
63
+ *
64
+ * Every field except `url` is optional. Fields left unset are NOT sent to the API,
65
+ * which lets the server apply its documented defaults (e.g. `respect_robots_txt=true`).
66
+ */
67
+ export type CrawlerConfigOptions = {
68
+ url: string;
69
+
70
+ // Crawl limits
71
+ page_limit?: number;
72
+ max_depth?: number;
73
+ max_duration?: number;
74
+ max_api_credit?: number;
75
+
76
+ // Path filtering (mutually exclusive)
77
+ exclude_paths?: string[];
78
+ include_only_paths?: string[];
79
+
80
+ // Domain / subdomain restrictions
81
+ ignore_base_path_restriction?: boolean;
82
+ follow_external_links?: boolean;
83
+ allowed_external_domains?: string[];
84
+ follow_internal_subdomains?: boolean;
85
+ allowed_internal_subdomains?: string[];
86
+
87
+ // Request configuration
88
+ headers?: Rec<string>;
89
+ delay?: number;
90
+ user_agent?: string;
91
+ max_concurrency?: number;
92
+ rendering_delay?: number;
93
+
94
+ // Crawl strategy options
95
+ use_sitemaps?: boolean;
96
+ respect_robots_txt?: boolean;
97
+ ignore_no_follow?: boolean;
98
+
99
+ // Cache options
100
+ cache?: boolean;
101
+ cache_ttl?: number;
102
+ cache_clear?: boolean;
103
+
104
+ // Content extraction
105
+ content_formats?: CrawlerContentFormat[];
106
+ extraction_rules?: Rec<any>;
107
+
108
+ // Web scraping features
109
+ asp?: boolean;
110
+ proxy_pool?: string;
111
+ country?: string;
112
+
113
+ // Webhook integration
114
+ webhook_name?: string;
115
+ webhook_events?: CrawlerWebhookEventName[];
116
+ };
117
+
118
+ /**
119
+ * Configuration for a Scrapfly Crawler API job.
120
+ *
121
+ * Mirrors the documented `POST /crawl` request body field-for-field. Fields left
122
+ * unset are dropped from the serialized output so the server applies its own defaults.
123
+ *
124
+ * @example
125
+ * ```ts
126
+ * const config = new CrawlerConfig({
127
+ * url: 'https://web-scraping.dev/products',
128
+ * page_limit: 10,
129
+ * content_formats: ['markdown'],
130
+ * });
131
+ * ```
132
+ */
133
+ export class CrawlerConfig {
134
+ url: string;
135
+
136
+ page_limit?: number;
137
+ max_depth?: number;
138
+ max_duration?: number;
139
+ max_api_credit?: number;
140
+
141
+ exclude_paths?: string[];
142
+ include_only_paths?: string[];
143
+
144
+ ignore_base_path_restriction?: boolean;
145
+ follow_external_links?: boolean;
146
+ allowed_external_domains?: string[];
147
+ follow_internal_subdomains?: boolean;
148
+ allowed_internal_subdomains?: string[];
149
+
150
+ headers?: Rec<string>;
151
+ delay?: number;
152
+ user_agent?: string;
153
+ max_concurrency?: number;
154
+ rendering_delay?: number;
155
+
156
+ use_sitemaps?: boolean;
157
+ respect_robots_txt?: boolean;
158
+ ignore_no_follow?: boolean;
159
+
160
+ cache?: boolean;
161
+ cache_ttl?: number;
162
+ cache_clear?: boolean;
163
+
164
+ content_formats?: CrawlerContentFormat[];
165
+ extraction_rules?: Rec<any>;
166
+
167
+ asp?: boolean;
168
+ proxy_pool?: string;
169
+ country?: string;
170
+
171
+ webhook_name?: string;
172
+ webhook_events?: CrawlerWebhookEventName[];
173
+
174
+ constructor(options: CrawlerConfigOptions) {
175
+ this.validateOptions(options);
176
+
177
+ if (typeof options.url !== 'string' || options.url.trim() === '') {
178
+ throw new CrawlerConfigError('url is required and must be a non-empty string');
179
+ }
180
+ this.url = options.url;
181
+
182
+ // Mutually exclusive path filters
183
+ if (options.exclude_paths && options.include_only_paths) {
184
+ throw new CrawlerConfigError('exclude_paths and include_only_paths are mutually exclusive');
185
+ }
186
+
187
+ // Bounds checks (mirroring the public docs)
188
+ if (options.page_limit !== undefined && options.page_limit < 0) {
189
+ throw new CrawlerConfigError('page_limit must be >= 0 (0 = unlimited)');
190
+ }
191
+ if (options.max_depth !== undefined && options.max_depth < 0) {
192
+ throw new CrawlerConfigError('max_depth must be >= 0');
193
+ }
194
+ if (options.rendering_delay !== undefined && (options.rendering_delay < 0 || options.rendering_delay > 25000)) {
195
+ throw new CrawlerConfigError('rendering_delay must be between 0 and 25000 (ms)');
196
+ }
197
+ if (options.delay !== undefined && (options.delay < 0 || options.delay > 15000)) {
198
+ throw new CrawlerConfigError('delay must be between 0 and 15000 (ms)');
199
+ }
200
+ if (options.cache_ttl !== undefined && (options.cache_ttl < 0 || options.cache_ttl > 604800)) {
201
+ throw new CrawlerConfigError('cache_ttl must be between 0 and 604800 (seconds, max 7 days)');
202
+ }
203
+ if (options.max_duration !== undefined && (options.max_duration < 15 || options.max_duration > 10800)) {
204
+ throw new CrawlerConfigError('max_duration must be between 15 and 10800 (seconds)');
205
+ }
206
+ if (options.max_api_credit !== undefined && options.max_api_credit < 0) {
207
+ throw new CrawlerConfigError('max_api_credit must be >= 0 (0 = no limit)');
208
+ }
209
+ if (options.exclude_paths && options.exclude_paths.length > 100) {
210
+ throw new CrawlerConfigError('exclude_paths is limited to 100 entries');
211
+ }
212
+ if (options.include_only_paths && options.include_only_paths.length > 100) {
213
+ throw new CrawlerConfigError('include_only_paths is limited to 100 entries');
214
+ }
215
+ if (options.allowed_external_domains && options.allowed_external_domains.length > 250) {
216
+ throw new CrawlerConfigError('allowed_external_domains is limited to 250 entries');
217
+ }
218
+ if (options.allowed_internal_subdomains && options.allowed_internal_subdomains.length > 250) {
219
+ throw new CrawlerConfigError('allowed_internal_subdomains is limited to 250 entries');
220
+ }
221
+
222
+ // Validate content_formats values
223
+ if (options.content_formats) {
224
+ for (const fmt of options.content_formats) {
225
+ if (!VALID_CONTENT_FORMATS.has(fmt)) {
226
+ throw new CrawlerConfigError(`Invalid content_formats value: ${fmt}`);
227
+ }
228
+ }
229
+ }
230
+
231
+ // Validate webhook_events values
232
+ if (options.webhook_events) {
233
+ for (const ev of options.webhook_events) {
234
+ if (!VALID_WEBHOOK_EVENTS.has(ev)) {
235
+ throw new CrawlerConfigError(`Invalid webhook_events value: ${ev}`);
236
+ }
237
+ }
238
+ }
239
+
240
+ // Assign all the optional fields by reference
241
+ this.page_limit = options.page_limit;
242
+ this.max_depth = options.max_depth;
243
+ this.max_duration = options.max_duration;
244
+ this.max_api_credit = options.max_api_credit;
245
+ this.exclude_paths = options.exclude_paths;
246
+ this.include_only_paths = options.include_only_paths;
247
+ this.ignore_base_path_restriction = options.ignore_base_path_restriction;
248
+ this.follow_external_links = options.follow_external_links;
249
+ this.allowed_external_domains = options.allowed_external_domains;
250
+ this.follow_internal_subdomains = options.follow_internal_subdomains;
251
+ this.allowed_internal_subdomains = options.allowed_internal_subdomains;
252
+ this.headers = options.headers;
253
+ this.delay = options.delay;
254
+ this.user_agent = options.user_agent;
255
+ this.max_concurrency = options.max_concurrency;
256
+ this.rendering_delay = options.rendering_delay;
257
+ this.use_sitemaps = options.use_sitemaps;
258
+ this.respect_robots_txt = options.respect_robots_txt;
259
+ this.ignore_no_follow = options.ignore_no_follow;
260
+ this.cache = options.cache;
261
+ this.cache_ttl = options.cache_ttl;
262
+ this.cache_clear = options.cache_clear;
263
+ this.content_formats = options.content_formats;
264
+ this.extraction_rules = options.extraction_rules;
265
+ this.asp = options.asp;
266
+ this.proxy_pool = options.proxy_pool;
267
+ this.country = options.country;
268
+ this.webhook_name = options.webhook_name;
269
+ this.webhook_events = options.webhook_events;
270
+ }
271
+
272
+ private validateOptions(options: Partial<CrawlerConfigOptions>) {
273
+ const validKeys = new Set<string>([
274
+ 'url',
275
+ 'page_limit',
276
+ 'max_depth',
277
+ 'max_duration',
278
+ 'max_api_credit',
279
+ 'exclude_paths',
280
+ 'include_only_paths',
281
+ 'ignore_base_path_restriction',
282
+ 'follow_external_links',
283
+ 'allowed_external_domains',
284
+ 'follow_internal_subdomains',
285
+ 'allowed_internal_subdomains',
286
+ 'headers',
287
+ 'delay',
288
+ 'user_agent',
289
+ 'max_concurrency',
290
+ 'rendering_delay',
291
+ 'use_sitemaps',
292
+ 'respect_robots_txt',
293
+ 'ignore_no_follow',
294
+ 'cache',
295
+ 'cache_ttl',
296
+ 'cache_clear',
297
+ 'content_formats',
298
+ 'extraction_rules',
299
+ 'asp',
300
+ 'proxy_pool',
301
+ 'country',
302
+ 'webhook_name',
303
+ 'webhook_events',
304
+ ]);
305
+ for (const key in options) {
306
+ if (!validKeys.has(key)) {
307
+ throw new CrawlerConfigError(`Invalid option provided: ${key}`);
308
+ }
309
+ }
310
+ }
311
+
312
+ /**
313
+ * Serialize to a flat object suitable for `JSON.stringify()` as a `POST /crawl` body.
314
+ *
315
+ * Unlike `ScrapeConfig.toApiParams()`, the crawler API takes its config as a JSON
316
+ * **body**, not URL query parameters. The API key is therefore NOT included here —
317
+ * it's added to the URL by the client.
318
+ *
319
+ * Fields left undefined are dropped so the server applies its own documented
320
+ * defaults (e.g. `respect_robots_txt=true`).
321
+ */
322
+ toApiParams(): Rec<any> {
323
+ const params: Rec<any> = { url: this.url };
324
+ const fields: Array<keyof CrawlerConfig> = [
325
+ 'page_limit',
326
+ 'max_depth',
327
+ 'max_duration',
328
+ 'max_api_credit',
329
+ 'exclude_paths',
330
+ 'include_only_paths',
331
+ 'ignore_base_path_restriction',
332
+ 'follow_external_links',
333
+ 'allowed_external_domains',
334
+ 'follow_internal_subdomains',
335
+ 'allowed_internal_subdomains',
336
+ 'headers',
337
+ 'delay',
338
+ 'user_agent',
339
+ 'max_concurrency',
340
+ 'rendering_delay',
341
+ 'use_sitemaps',
342
+ 'respect_robots_txt',
343
+ 'ignore_no_follow',
344
+ 'cache',
345
+ 'cache_ttl',
346
+ 'cache_clear',
347
+ 'content_formats',
348
+ 'extraction_rules',
349
+ 'asp',
350
+ 'proxy_pool',
351
+ 'country',
352
+ 'webhook_name',
353
+ 'webhook_events',
354
+ ];
355
+ for (const key of fields) {
356
+ const v = (this as any)[key];
357
+ if (v !== undefined) {
358
+ params[key] = v;
359
+ }
360
+ }
361
+ return params;
362
+ }
363
+ }