firecrawl 1.29.3 → 3.0.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.
Files changed (47) hide show
  1. package/.env.example +4 -2
  2. package/LICENSE +0 -0
  3. package/README.md +85 -78
  4. package/audit-ci.jsonc +4 -0
  5. package/dist/chunk-JFWW4BWA.js +85 -0
  6. package/dist/index.cjs +964 -39
  7. package/dist/index.d.cts +529 -11
  8. package/dist/index.d.ts +529 -11
  9. package/dist/index.js +952 -27
  10. package/dist/package-KYZ3HXR5.js +4 -0
  11. package/dump.rdb +0 -0
  12. package/jest.config.js +0 -0
  13. package/package.json +6 -6
  14. package/src/__tests__/e2e/v2/batch.test.ts +74 -0
  15. package/src/__tests__/e2e/v2/crawl.test.ts +182 -0
  16. package/src/__tests__/e2e/v2/extract.test.ts +70 -0
  17. package/src/__tests__/e2e/v2/map.test.ts +55 -0
  18. package/src/__tests__/e2e/v2/scrape.test.ts +130 -0
  19. package/src/__tests__/e2e/v2/search.test.ts +247 -0
  20. package/src/__tests__/e2e/v2/usage.test.ts +36 -0
  21. package/src/__tests__/e2e/v2/utils/idmux.ts +58 -0
  22. package/src/__tests__/e2e/v2/watcher.test.ts +96 -0
  23. package/src/__tests__/unit/v2/errorHandler.test.ts +19 -0
  24. package/src/__tests__/unit/v2/scrape.unit.test.ts +11 -0
  25. package/src/__tests__/unit/v2/validation.test.ts +59 -0
  26. package/src/index.backup.ts +2146 -0
  27. package/src/index.ts +27 -2134
  28. package/src/v1/index.ts +2158 -0
  29. package/src/v2/client.ts +281 -0
  30. package/src/v2/methods/batch.ts +131 -0
  31. package/src/v2/methods/crawl.ts +160 -0
  32. package/src/v2/methods/extract.ts +86 -0
  33. package/src/v2/methods/map.ts +37 -0
  34. package/src/v2/methods/scrape.ts +26 -0
  35. package/src/v2/methods/search.ts +69 -0
  36. package/src/v2/methods/usage.ts +39 -0
  37. package/src/v2/types.ts +308 -0
  38. package/src/v2/utils/errorHandler.ts +18 -0
  39. package/src/v2/utils/getVersion.ts +14 -0
  40. package/src/v2/utils/httpClient.ts +99 -0
  41. package/src/v2/utils/validation.ts +50 -0
  42. package/src/v2/watcher.ts +159 -0
  43. package/tsconfig.json +2 -1
  44. package/tsup.config.ts +0 -0
  45. package/dist/package-Z6F7JDXI.js +0 -111
  46. /package/src/__tests__/{v1/e2e_withAuth → e2e/v1}/index.test.ts +0 -0
  47. /package/src/__tests__/{v1/unit → unit/v1}/monitor-job-status-retry.test.ts +0 -0
@@ -0,0 +1,2158 @@
1
+ import axios, { type AxiosResponse, type AxiosRequestHeaders, AxiosError } from "axios";
2
+ import * as zt from "zod";
3
+ import { zodToJsonSchema } from "zod-to-json-schema";
4
+ import { TypedEventTarget } from "typescript-event-target";
5
+
6
+ /**
7
+ * Configuration interface for FirecrawlApp.
8
+ * @param apiKey - Optional API key for authentication.
9
+ * @param apiUrl - Optional base URL of the API; defaults to 'https://api.firecrawl.dev'.
10
+ */
11
+ export interface FirecrawlAppConfig {
12
+ apiKey?: string | null;
13
+ apiUrl?: string | null;
14
+ }
15
+
16
+ /**
17
+ * Metadata for a Firecrawl document.
18
+ * Includes various optional properties for document metadata.
19
+ */
20
+ export interface FirecrawlDocumentMetadata {
21
+ title?: string;
22
+ description?: string;
23
+ language?: string;
24
+ keywords?: string;
25
+ robots?: string;
26
+ ogTitle?: string;
27
+ ogDescription?: string;
28
+ ogUrl?: string;
29
+ ogImage?: string;
30
+ ogAudio?: string;
31
+ ogDeterminer?: string;
32
+ ogLocale?: string;
33
+ ogLocaleAlternate?: string[];
34
+ ogSiteName?: string;
35
+ ogVideo?: string;
36
+ dctermsCreated?: string;
37
+ dcDateCreated?: string;
38
+ dcDate?: string;
39
+ dctermsType?: string;
40
+ dcType?: string;
41
+ dctermsAudience?: string;
42
+ dctermsSubject?: string;
43
+ dcSubject?: string;
44
+ dcDescription?: string;
45
+ dctermsKeywords?: string;
46
+ modifiedTime?: string;
47
+ publishedTime?: string;
48
+ articleTag?: string;
49
+ articleSection?: string;
50
+ sourceURL?: string;
51
+ statusCode?: number;
52
+ error?: string;
53
+ proxyUsed?: "basic" | "stealth";
54
+ cacheState?: "miss" | "hit";
55
+ cachedAt?: string;
56
+ [key: string]: any; // Allows for additional metadata properties not explicitly defined.
57
+ }
58
+
59
+ /**
60
+ * Document interface for Firecrawl.
61
+ * Represents a document retrieved or processed by Firecrawl.
62
+ */
63
+ export interface FirecrawlDocument<T = any, ActionsSchema extends (ActionsResult | never) = never> {
64
+ url?: string;
65
+ markdown?: string;
66
+ html?: string;
67
+ rawHtml?: string;
68
+ links?: string[];
69
+ extract?: T;
70
+ json?: T;
71
+ screenshot?: string;
72
+ metadata?: FirecrawlDocumentMetadata;
73
+ actions: ActionsSchema;
74
+ changeTracking?: {
75
+ previousScrapeAt: string | null;
76
+ changeStatus: "new" | "same" | "changed" | "removed";
77
+ visibility: "visible" | "hidden";
78
+ diff?: {
79
+ text: string;
80
+ json: {
81
+ files: Array<{
82
+ from: string | null;
83
+ to: string | null;
84
+ chunks: Array<{
85
+ content: string;
86
+ changes: Array<{
87
+ type: string;
88
+ normal?: boolean;
89
+ ln?: number;
90
+ ln1?: number;
91
+ ln2?: number;
92
+ content: string;
93
+ }>;
94
+ }>;
95
+ }>;
96
+ };
97
+ };
98
+ json?: any;
99
+ };
100
+ // v1 search only
101
+ title?: string;
102
+ description?: string;
103
+ }
104
+
105
+ /**
106
+ * Parameters for scraping operations.
107
+ * Defines the options and configurations available for scraping web content.
108
+ */
109
+ export interface CrawlScrapeOptions {
110
+ formats?: ("markdown" | "html" | "rawHtml" | "content" | "links" | "screenshot" | "screenshot@fullPage" | "extract" | "json" | "changeTracking")[];
111
+ headers?: Record<string, string>;
112
+ includeTags?: string[];
113
+ excludeTags?: string[];
114
+ onlyMainContent?: boolean;
115
+ waitFor?: number;
116
+ timeout?: number;
117
+ location?: {
118
+ country?: string;
119
+ languages?: string[];
120
+ };
121
+ mobile?: boolean;
122
+ skipTlsVerification?: boolean;
123
+ removeBase64Images?: boolean;
124
+ blockAds?: boolean;
125
+ proxy?: "basic" | "stealth" | "auto";
126
+ storeInCache?: boolean;
127
+ maxAge?: number;
128
+ parsePDF?: boolean;
129
+ }
130
+
131
+ export type Action = {
132
+ type: "wait",
133
+ milliseconds?: number,
134
+ selector?: string,
135
+ } | {
136
+ type: "click",
137
+ selector: string,
138
+ all?: boolean,
139
+ } | {
140
+ type: "screenshot",
141
+ fullPage?: boolean,
142
+ quality?: number,
143
+ } | {
144
+ type: "write",
145
+ text: string,
146
+ } | {
147
+ type: "press",
148
+ key: string,
149
+ } | {
150
+ type: "scroll",
151
+ direction?: "up" | "down",
152
+ selector?: string,
153
+ } | {
154
+ type: "scrape",
155
+ } | {
156
+ type: "executeJavascript",
157
+ script: string,
158
+ };
159
+
160
+ export interface ScrapeParams<LLMSchema extends zt.ZodSchema = any, ActionsSchema extends (Action[] | undefined) = undefined> extends CrawlScrapeOptions {
161
+ extract?: {
162
+ prompt?: string;
163
+ schema?: LLMSchema;
164
+ systemPrompt?: string;
165
+ };
166
+ jsonOptions?:{
167
+ prompt?: string;
168
+ schema?: LLMSchema;
169
+ systemPrompt?: string;
170
+ }
171
+ changeTrackingOptions?: {
172
+ prompt?: string;
173
+ schema?: any;
174
+ modes?: ("json" | "git-diff")[];
175
+ tag?: string | null;
176
+ }
177
+ actions?: ActionsSchema;
178
+ agent?: AgentOptions;
179
+ zeroDataRetention?: boolean;
180
+ }
181
+
182
+ export interface ActionsResult {
183
+ screenshots: string[];
184
+ scrapes: ({
185
+ url: string;
186
+ html: string;
187
+ })[];
188
+ javascriptReturns: {
189
+ type: string;
190
+ value: unknown
191
+ }[];
192
+ }
193
+
194
+ /**
195
+ * Response interface for scraping operations.
196
+ * Defines the structure of the response received after a scraping operation.
197
+ */
198
+ export interface ScrapeResponse<LLMResult = any, ActionsSchema extends (ActionsResult | never) = never> extends FirecrawlDocument<LLMResult, ActionsSchema> {
199
+ success: true;
200
+ warning?: string;
201
+ error?: string;
202
+ }
203
+
204
+ /**
205
+ * Parameters for crawling operations.
206
+ * Includes options for both scraping and mapping during a crawl.
207
+ */
208
+ export interface CrawlParams {
209
+ includePaths?: string[];
210
+ excludePaths?: string[];
211
+ maxDepth?: number;
212
+ maxDiscoveryDepth?: number;
213
+ limit?: number;
214
+ allowBackwardLinks?: boolean;
215
+ crawlEntireDomain?: boolean;
216
+ allowExternalLinks?: boolean;
217
+ ignoreSitemap?: boolean;
218
+ scrapeOptions?: CrawlScrapeOptions;
219
+ webhook?: string | {
220
+ url: string;
221
+ headers?: Record<string, string>;
222
+ metadata?: Record<string, string>;
223
+ events?: ["completed", "failed", "page", "started"][number][];
224
+ };
225
+ deduplicateSimilarURLs?: boolean;
226
+ ignoreQueryParameters?: boolean;
227
+ regexOnFullURL?: boolean;
228
+ /**
229
+ * Delay in seconds between scrapes. This helps respect website rate limits.
230
+ * If not provided, the crawler may use the robots.txt crawl delay if available.
231
+ */
232
+ delay?: number;
233
+ allowSubdomains?: boolean;
234
+ maxConcurrency?: number;
235
+ zeroDataRetention?: boolean;
236
+ }
237
+
238
+ /**
239
+ * Response interface for crawling operations.
240
+ * Defines the structure of the response received after initiating a crawl.
241
+ */
242
+ export interface CrawlResponse {
243
+ id?: string;
244
+ url?: string;
245
+ success: true;
246
+ error?: string;
247
+ }
248
+
249
+ /**
250
+ * Response interface for batch scrape operations.
251
+ * Defines the structure of the response received after initiating a crawl.
252
+ */
253
+ export interface BatchScrapeResponse {
254
+ id?: string;
255
+ url?: string;
256
+ success: true;
257
+ error?: string;
258
+ invalidURLs?: string[];
259
+ }
260
+
261
+ /**
262
+ * Response interface for job status checks.
263
+ * Provides detailed status of a crawl job including progress and results.
264
+ */
265
+ export interface CrawlStatusResponse {
266
+ success: true;
267
+ status: "scraping" | "completed" | "failed" | "cancelled";
268
+ completed: number;
269
+ total: number;
270
+ creditsUsed: number;
271
+ expiresAt: Date;
272
+ next?: string;
273
+ data: FirecrawlDocument<undefined>[];
274
+ };
275
+
276
+ /**
277
+ * Response interface for batch scrape job status checks.
278
+ * Provides detailed status of a batch scrape job including progress and results.
279
+ */
280
+ export interface BatchScrapeStatusResponse {
281
+ success: true;
282
+ status: "scraping" | "completed" | "failed" | "cancelled";
283
+ completed: number;
284
+ total: number;
285
+ creditsUsed: number;
286
+ expiresAt: Date;
287
+ next?: string;
288
+ data: FirecrawlDocument<undefined>[];
289
+ };
290
+
291
+ /**
292
+ * Parameters for mapping operations.
293
+ * Defines options for mapping URLs during a crawl.
294
+ */
295
+ export interface MapParams {
296
+ search?: string;
297
+ ignoreSitemap?: boolean;
298
+ includeSubdomains?: boolean;
299
+ sitemapOnly?: boolean;
300
+ limit?: number;
301
+ timeout?: number;
302
+ useIndex?: boolean;
303
+ }
304
+
305
+ /**
306
+ * Response interface for mapping operations.
307
+ * Defines the structure of the response received after a mapping operation.
308
+ */
309
+ export interface MapResponse {
310
+ success: true;
311
+ links?: string[];
312
+ error?: string;
313
+ }
314
+
315
+ /**
316
+ * Parameters for extracting information from URLs.
317
+ * Defines options for extracting information from URLs.
318
+ */
319
+ export interface AgentOptions {
320
+ model?: string;
321
+ prompt?: string;
322
+ sessionId?: string;
323
+ }
324
+
325
+ /**
326
+ * Parameters for extracting information from URLs.
327
+ * Defines options for extracting information from URLs.
328
+ */
329
+ export interface AgentOptionsExtract {
330
+ model?: string;
331
+ sessionId?: string;
332
+ }
333
+
334
+ export interface ExtractParams<LLMSchema extends zt.ZodSchema = any> {
335
+ prompt?: string;
336
+ schema?: LLMSchema | object;
337
+ systemPrompt?: string;
338
+ allowExternalLinks?: boolean;
339
+ enableWebSearch?: boolean;
340
+ includeSubdomains?: boolean;
341
+ origin?: string;
342
+ showSources?: boolean;
343
+ scrapeOptions?: CrawlScrapeOptions;
344
+ agent?: AgentOptionsExtract;
345
+ }
346
+
347
+ /**
348
+ * Response interface for extracting information from URLs.
349
+ * Defines the structure of the response received after extracting information from URLs.
350
+ */
351
+ export interface ExtractResponse<LLMSchema extends zt.ZodSchema = any> {
352
+ success: boolean;
353
+ data: LLMSchema;
354
+ error?: string;
355
+ warning?: string;
356
+ sources?: string[];
357
+ }
358
+
359
+ /**
360
+ * Error response interface.
361
+ * Defines the structure of the response received when an error occurs.
362
+ */
363
+ export interface ErrorResponse {
364
+ success: false;
365
+ error: string;
366
+ }
367
+
368
+ /**
369
+ * Custom error class for Firecrawl.
370
+ * Extends the built-in Error class to include a status code.
371
+ */
372
+ export class FirecrawlError extends Error {
373
+ statusCode: number;
374
+ details?: any;
375
+ constructor(message: string, statusCode: number, details?: any) {
376
+ super(message);
377
+ this.statusCode = statusCode;
378
+ this.details = details;
379
+ }
380
+ }
381
+
382
+ /**
383
+ * Parameters for search operations.
384
+ * Defines options for searching and scraping search results.
385
+ */
386
+ export interface SearchParams {
387
+ limit?: number;
388
+ tbs?: string;
389
+ filter?: string;
390
+ lang?: string;
391
+ country?: string;
392
+ location?: string;
393
+ origin?: string;
394
+ timeout?: number;
395
+ scrapeOptions?: ScrapeParams;
396
+ }
397
+
398
+ /**
399
+ * Response interface for search operations.
400
+ * Defines the structure of the response received after a search operation.
401
+ */
402
+ export interface SearchResponse {
403
+ success: boolean;
404
+ data: FirecrawlDocument<undefined>[];
405
+ warning?: string;
406
+ error?: string;
407
+ }
408
+
409
+ /**
410
+ * Response interface for crawl/batch scrape error monitoring.
411
+ */
412
+ export interface CrawlErrorsResponse {
413
+ /**
414
+ * Scrapes that errored out + error details
415
+ */
416
+ errors: {
417
+ id: string,
418
+ timestamp?: string,
419
+ url: string,
420
+ code?: string,
421
+ error: string,
422
+ }[];
423
+
424
+ /**
425
+ * URLs blocked by robots.txt
426
+ */
427
+ robotsBlocked: string[];
428
+ };
429
+
430
+ /**
431
+ * Parameters for deep research operations.
432
+ * Defines options for conducting deep research on a query.
433
+ */
434
+ export interface DeepResearchParams<LLMSchema extends zt.ZodSchema = any> {
435
+ /**
436
+ * Maximum depth of research iterations (1-10)
437
+ * @default 7
438
+ */
439
+ maxDepth?: number;
440
+ /**
441
+ * Time limit in seconds (30-300)
442
+ * @default 270
443
+ */
444
+ timeLimit?: number;
445
+ /**
446
+ * Maximum number of URLs to analyze (1-1000)
447
+ * @default 20
448
+ */
449
+ maxUrls?: number;
450
+ /**
451
+ * The prompt to use for the final analysis
452
+ */
453
+ analysisPrompt?: string;
454
+ /**
455
+ * The system prompt to use for the research agent
456
+ */
457
+ systemPrompt?: string;
458
+ /**
459
+ * The formats to use for the final analysis
460
+ */
461
+ formats?: ("markdown" | "json")[];
462
+ /**
463
+ * The JSON options to use for the final analysis
464
+ */
465
+ jsonOptions?:{
466
+ prompt?: string;
467
+ schema?: LLMSchema;
468
+ systemPrompt?: string;
469
+ };
470
+ /**
471
+ * Experimental flag for streaming steps
472
+ */
473
+ // __experimental_streamSteps?: boolean;
474
+ }
475
+
476
+ /**
477
+ * Response interface for deep research operations.
478
+ */
479
+ export interface DeepResearchResponse {
480
+ success: boolean;
481
+ id: string;
482
+ }
483
+
484
+ /**
485
+ * Status response interface for deep research operations.
486
+ */
487
+ export interface DeepResearchStatusResponse {
488
+ success: boolean;
489
+ data: {
490
+ finalAnalysis: string;
491
+ activities: Array<{
492
+ type: string;
493
+ status: string;
494
+ message: string;
495
+ timestamp: string;
496
+ depth: number;
497
+ }>;
498
+ sources: Array<{
499
+ url: string;
500
+ title: string;
501
+ description: string;
502
+ }>;
503
+ };
504
+ status: "processing" | "completed" | "failed";
505
+ error?: string;
506
+ expiresAt: string;
507
+ currentDepth: number;
508
+ maxDepth: number;
509
+ activities: Array<{
510
+ type: string;
511
+ status: string;
512
+ message: string;
513
+ timestamp: string;
514
+ depth: number;
515
+ }>;
516
+ sources: Array<{
517
+ url: string;
518
+ title: string;
519
+ description: string;
520
+ }>;
521
+ summaries: string[];
522
+ }
523
+
524
+ /**
525
+ * Parameters for LLMs.txt generation operations.
526
+ */
527
+ export interface GenerateLLMsTextParams {
528
+ /**
529
+ * Maximum number of URLs to process (1-100)
530
+ * @default 10
531
+ */
532
+ maxUrls?: number;
533
+ /**
534
+ * Whether to show the full LLMs-full.txt in the response
535
+ * @default false
536
+ */
537
+ showFullText?: boolean;
538
+ /**
539
+ * Whether to use cached content if available
540
+ * @default true
541
+ */
542
+ cache?: boolean;
543
+ /**
544
+ * Experimental flag for streaming
545
+ */
546
+ __experimental_stream?: boolean;
547
+ }
548
+
549
+ /**
550
+ * Response interface for LLMs.txt generation operations.
551
+ */
552
+ export interface GenerateLLMsTextResponse {
553
+ success: boolean;
554
+ id: string;
555
+ }
556
+
557
+ /**
558
+ * Status response interface for LLMs.txt generation operations.
559
+ */
560
+ export interface GenerateLLMsTextStatusResponse {
561
+ success: boolean;
562
+ data: {
563
+ llmstxt: string;
564
+ llmsfulltxt?: string;
565
+ };
566
+ status: "processing" | "completed" | "failed";
567
+ error?: string;
568
+ expiresAt: string;
569
+ }
570
+
571
+ /**
572
+ * Main class for interacting with the Firecrawl API.
573
+ * Provides methods for scraping, searching, crawling, and mapping web content.
574
+ */
575
+ export default class FirecrawlApp {
576
+ public apiKey: string;
577
+ public apiUrl: string;
578
+ public version: string = "1.25.1";
579
+
580
+ private isCloudService(url: string): boolean {
581
+ return url.includes('api.firecrawl.dev');
582
+ }
583
+
584
+ private async getVersion(): Promise<string> {
585
+ try {
586
+ // Prefer env-provided version when available (works well in test runners)
587
+ if (typeof process !== 'undefined' && process.env && process.env.npm_package_version) {
588
+ return process.env.npm_package_version as string;
589
+ }
590
+ const packageJson = await import('../../package.json', { assert: { type: 'json' } });
591
+ return packageJson.default.version;
592
+ } catch (error) {
593
+ // Suppress noisy logs under test environments
594
+ const isTest = typeof process !== 'undefined' && (
595
+ process.env.JEST_WORKER_ID != null || process.env.NODE_ENV === 'test'
596
+ );
597
+ if (!isTest) {
598
+ // eslint-disable-next-line no-console
599
+ console.error("Error getting version:", error);
600
+ }
601
+ return "1.25.1";
602
+ }
603
+ }
604
+
605
+ private async init() {
606
+ this.version = await this.getVersion();
607
+ }
608
+
609
+ /**
610
+ * Initializes a new instance of the FirecrawlApp class.
611
+ * @param config - Configuration options for the FirecrawlApp instance.
612
+ */
613
+ constructor({ apiKey = null, apiUrl = null }: FirecrawlAppConfig) {
614
+ const baseUrl = apiUrl || "https://api.firecrawl.dev";
615
+
616
+ if (this.isCloudService(baseUrl) && typeof apiKey !== "string") {
617
+ throw new FirecrawlError("No API key provided", 401);
618
+ }
619
+
620
+ this.apiKey = apiKey || '';
621
+ this.apiUrl = baseUrl;
622
+ this.init();
623
+ }
624
+
625
+ /**
626
+ * Scrapes a URL using the Firecrawl API.
627
+ * @param url - The URL to scrape.
628
+ * @param params - Additional parameters for the scrape request.
629
+ * @returns The response from the scrape operation.
630
+ */
631
+ async scrapeUrl<T extends zt.ZodSchema, ActionsSchema extends (Action[] | undefined) = undefined>(
632
+ url: string,
633
+ params?: ScrapeParams<T, ActionsSchema>
634
+ ): Promise<ScrapeResponse<zt.infer<T>, ActionsSchema extends Action[] ? ActionsResult : never> | ErrorResponse> {
635
+ const headers: AxiosRequestHeaders = {
636
+ "Content-Type": "application/json",
637
+ Authorization: `Bearer ${this.apiKey}`,
638
+ } as AxiosRequestHeaders;
639
+ let jsonData: any = { url, ...params, origin: `js-sdk@${this.version}` };
640
+ if (jsonData?.extract?.schema) {
641
+ let schema = jsonData.extract.schema;
642
+
643
+ // Try parsing the schema as a Zod schema
644
+ try {
645
+ schema = zodToJsonSchema(schema);
646
+ } catch (error) {
647
+
648
+ }
649
+ jsonData = {
650
+ ...jsonData,
651
+ extract: {
652
+ ...jsonData.extract,
653
+ schema: schema,
654
+ },
655
+ };
656
+ }
657
+
658
+ if (jsonData?.jsonOptions?.schema) {
659
+ let schema = jsonData.jsonOptions.schema;
660
+ // Try parsing the schema as a Zod schema
661
+ try {
662
+ schema = zodToJsonSchema(schema);
663
+ } catch (error) {
664
+
665
+ }
666
+ jsonData = {
667
+ ...jsonData,
668
+ jsonOptions: {
669
+ ...jsonData.jsonOptions,
670
+ schema: schema,
671
+ },
672
+ };
673
+ }
674
+ try {
675
+ const response: AxiosResponse = await axios.post(
676
+ this.apiUrl + `/v1/scrape`,
677
+ jsonData,
678
+ { headers, timeout: params?.timeout !== undefined ? (params.timeout + 5000) : undefined },
679
+ );
680
+ if (response.status === 200) {
681
+ const responseData = response.data;
682
+ if (responseData.success) {
683
+ return {
684
+ success: true,
685
+ warning: responseData.warning,
686
+ error: responseData.error,
687
+ ...responseData.data
688
+ };
689
+ } else {
690
+ throw new FirecrawlError(`Failed to scrape URL. Error: ${responseData.error}`, response.status);
691
+ }
692
+ } else {
693
+ this.handleError(response, "scrape URL");
694
+ }
695
+ } catch (error: any) {
696
+ this.handleError(error.response, "scrape URL");
697
+ }
698
+ return { success: false, error: "Internal server error." };
699
+ }
700
+
701
+ /**
702
+ * Searches using the Firecrawl API and optionally scrapes the results.
703
+ * @param query - The search query string.
704
+ * @param params - Optional parameters for the search request.
705
+ * @returns The response from the search operation.
706
+ */
707
+ async search(query: string, params?: SearchParams | Record<string, any>): Promise<SearchResponse> {
708
+ const headers: AxiosRequestHeaders = {
709
+ "Content-Type": "application/json",
710
+ Authorization: `Bearer ${this.apiKey}`,
711
+ } as AxiosRequestHeaders;
712
+
713
+ let jsonData: any = {
714
+ query,
715
+ limit: params?.limit ?? 5,
716
+ tbs: params?.tbs,
717
+ filter: params?.filter,
718
+ lang: params?.lang ?? "en",
719
+ country: params?.country ?? "us",
720
+ location: params?.location,
721
+ origin: `js-sdk@${this.version}`,
722
+ timeout: params?.timeout ?? 60000,
723
+ scrapeOptions: params?.scrapeOptions ?? { formats: [] },
724
+ };
725
+
726
+ if (jsonData?.scrapeOptions?.extract?.schema) {
727
+ let schema = jsonData.scrapeOptions.extract.schema;
728
+
729
+ // Try parsing the schema as a Zod schema
730
+ try {
731
+ schema = zodToJsonSchema(schema);
732
+ } catch (error) {
733
+
734
+ }
735
+ jsonData = {
736
+ ...jsonData,
737
+ scrapeOptions: {
738
+ ...jsonData.scrapeOptions,
739
+ extract: {
740
+ ...jsonData.scrapeOptions.extract,
741
+ schema: schema,
742
+ },
743
+ },
744
+ };
745
+ }
746
+
747
+ try {
748
+ const response: AxiosResponse = await this.postRequest(
749
+ this.apiUrl + `/v1/search`,
750
+ jsonData,
751
+ headers
752
+ );
753
+
754
+ if (response.status === 200) {
755
+ const responseData = response.data;
756
+ if (responseData.success) {
757
+ return {
758
+ success: true,
759
+ data: responseData.data as FirecrawlDocument<any>[],
760
+ warning: responseData.warning,
761
+ };
762
+ } else {
763
+ throw new FirecrawlError(`Failed to search. Error: ${responseData.error}`, response.status);
764
+ }
765
+ } else {
766
+ this.handleError(response, "search");
767
+ }
768
+ } catch (error: any) {
769
+ if (error.response?.data?.error) {
770
+ throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`, error.response.status);
771
+ } else {
772
+ throw new FirecrawlError(error.message, 500);
773
+ }
774
+ }
775
+ return { success: false, error: "Internal server error.", data: [] };
776
+ }
777
+
778
+ /**
779
+ * Initiates a crawl job for a URL using the Firecrawl API.
780
+ * @param url - The URL to crawl.
781
+ * @param params - Additional parameters for the crawl request.
782
+ * @param pollInterval - Time in seconds for job status checks.
783
+ * @param idempotencyKey - Optional idempotency key for the request.
784
+ * @returns The response from the crawl operation.
785
+ */
786
+ async crawlUrl(
787
+ url: string,
788
+ params?: CrawlParams,
789
+ pollInterval: number = 2,
790
+ idempotencyKey?: string
791
+ ): Promise<CrawlStatusResponse | ErrorResponse> {
792
+ const headers = this.prepareHeaders(idempotencyKey);
793
+ let jsonData: any = { url, ...params, origin: `js-sdk@${this.version}` };
794
+ try {
795
+ const response: AxiosResponse = await this.postRequest(
796
+ this.apiUrl + `/v1/crawl`,
797
+ jsonData,
798
+ headers
799
+ );
800
+ if (response.status === 200) {
801
+ const id: string = response.data.id;
802
+ return this.monitorJobStatus(id, headers, pollInterval);
803
+ } else {
804
+ this.handleError(response, "start crawl job");
805
+ }
806
+ } catch (error: any) {
807
+ if (error.response?.data?.error) {
808
+ throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`, error.response.status);
809
+ } else {
810
+ throw new FirecrawlError(error.message, 500);
811
+ }
812
+ }
813
+ return { success: false, error: "Internal server error." };
814
+ }
815
+
816
+ async asyncCrawlUrl(
817
+ url: string,
818
+ params?: CrawlParams,
819
+ idempotencyKey?: string
820
+ ): Promise<CrawlResponse | ErrorResponse> {
821
+ const headers = this.prepareHeaders(idempotencyKey);
822
+ let jsonData: any = { url, ...params, origin: `js-sdk@${this.version}` };
823
+ try {
824
+ const response: AxiosResponse = await this.postRequest(
825
+ this.apiUrl + `/v1/crawl`,
826
+ jsonData,
827
+ headers
828
+ );
829
+ if (response.status === 200) {
830
+ return response.data;
831
+ } else {
832
+ this.handleError(response, "start crawl job");
833
+ }
834
+ } catch (error: any) {
835
+ if (error.response?.data?.error) {
836
+ throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`, error.response.status);
837
+ } else {
838
+ throw new FirecrawlError(error.message, 500);
839
+ }
840
+ }
841
+ return { success: false, error: "Internal server error." };
842
+ }
843
+
844
+ /**
845
+ * Checks the status of a crawl job using the Firecrawl API.
846
+ * @param id - The ID of the crawl operation.
847
+ * @param getAllData - Paginate through all the pages of documents, returning the full list of all documents. (default: `false`)
848
+ * @param nextURL - The `next` URL from the previous crawl status. Only required if you're not manually increasing `skip`. Only used when `getAllData = false`.
849
+ * @param skip - How many entries to skip to paginate. Only required if you're not providing `nextURL`. Only used when `getAllData = false`.
850
+ * @param limit - How many entries to return. Only used when `getAllData = false`.
851
+ * @returns The response containing the job status.
852
+ */
853
+ async checkCrawlStatus(id?: string, getAllData = false, nextURL?: string, skip?: number, limit?: number): Promise<CrawlStatusResponse | ErrorResponse> {
854
+ if (!id) {
855
+ throw new FirecrawlError("No crawl ID provided", 400);
856
+ }
857
+
858
+ const headers: AxiosRequestHeaders = this.prepareHeaders();
859
+ const targetURL = new URL(nextURL ?? `${this.apiUrl}/v1/crawl/${id}`);
860
+ if (skip !== undefined) {
861
+ targetURL.searchParams.set("skip", skip.toString());
862
+ }
863
+ if (limit !== undefined) {
864
+ targetURL.searchParams.set("limit", limit.toString());
865
+ }
866
+
867
+ try {
868
+ const response: AxiosResponse = await this.getRequest(
869
+ targetURL.href,
870
+ headers
871
+ );
872
+ if (response.status === 200) {
873
+ let allData = response.data.data;
874
+ if (getAllData && response.data.status === "completed") {
875
+ let statusData = response.data
876
+ if ("data" in statusData) {
877
+ let data = statusData.data;
878
+ while (typeof statusData === 'object' && 'next' in statusData) {
879
+ if (data.length === 0) {
880
+ break
881
+ }
882
+ statusData = (await this.getRequest(statusData.next, headers)).data;
883
+ data = data.concat(statusData.data);
884
+ }
885
+ allData = data;
886
+ }
887
+ }
888
+
889
+ let resp: CrawlStatusResponse | ErrorResponse = {
890
+ success: response.data.success,
891
+ status: response.data.status,
892
+ total: response.data.total,
893
+ completed: response.data.completed,
894
+ creditsUsed: response.data.creditsUsed,
895
+ next: getAllData ? undefined : response.data.next,
896
+ expiresAt: new Date(response.data.expiresAt),
897
+ data: allData
898
+ }
899
+
900
+ if (!response.data.success && response.data.error) {
901
+ resp = {
902
+ ...resp,
903
+ success: false,
904
+ error: response.data.error
905
+ } as ErrorResponse;
906
+ }
907
+
908
+ if (response.data.next) {
909
+ (resp as CrawlStatusResponse).next = response.data.next;
910
+ }
911
+
912
+ return resp;
913
+ } else {
914
+ this.handleError(response, "check crawl status");
915
+ }
916
+ } catch (error: any) {
917
+ throw new FirecrawlError(error.message, 500);
918
+ }
919
+ return { success: false, error: "Internal server error." };
920
+ }
921
+
922
+ /**
923
+ * Returns information about crawl errors.
924
+ * @param id - The ID of the crawl operation.
925
+ * @returns Information about crawl errors.
926
+ */
927
+ async checkCrawlErrors(id: string): Promise<CrawlErrorsResponse | ErrorResponse> {
928
+ const headers = this.prepareHeaders();
929
+ try {
930
+ const response: AxiosResponse = await this.deleteRequest(
931
+ `${this.apiUrl}/v1/crawl/${id}/errors`,
932
+ headers
933
+ );
934
+ if (response.status === 200) {
935
+ return response.data;
936
+ } else {
937
+ this.handleError(response, "check crawl errors");
938
+ }
939
+ } catch (error: any) {
940
+ throw new FirecrawlError(error.message, 500);
941
+ }
942
+ return { success: false, error: "Internal server error." };
943
+ }
944
+
945
+ /**
946
+ * Cancels a crawl job using the Firecrawl API.
947
+ * @param id - The ID of the crawl operation.
948
+ * @returns The response from the cancel crawl operation.
949
+ */
950
+ async cancelCrawl(id: string): Promise<ErrorResponse> {
951
+ const headers = this.prepareHeaders();
952
+ try {
953
+ const response: AxiosResponse = await this.deleteRequest(
954
+ `${this.apiUrl}/v1/crawl/${id}`,
955
+ headers
956
+ );
957
+ if (response.status === 200) {
958
+ return response.data;
959
+ } else {
960
+ this.handleError(response, "cancel crawl job");
961
+ }
962
+ } catch (error: any) {
963
+ throw new FirecrawlError(error.message, 500);
964
+ }
965
+ return { success: false, error: "Internal server error." };
966
+ }
967
+
968
+ /**
969
+ * Initiates a crawl job and returns a CrawlWatcher to monitor the job via WebSocket.
970
+ * @param url - The URL to crawl.
971
+ * @param params - Additional parameters for the crawl request.
972
+ * @param idempotencyKey - Optional idempotency key for the request.
973
+ * @returns A CrawlWatcher instance to monitor the crawl job.
974
+ */
975
+ async crawlUrlAndWatch(
976
+ url: string,
977
+ params?: CrawlParams,
978
+ idempotencyKey?: string,
979
+ ) {
980
+ const crawl = await this.asyncCrawlUrl(url, params, idempotencyKey);
981
+
982
+ if (crawl.success && crawl.id) {
983
+ const id = crawl.id;
984
+ return new CrawlWatcher(id, this);
985
+ }
986
+
987
+ throw new FirecrawlError("Crawl job failed to start", 400);
988
+ }
989
+
990
+ /**
991
+ * Maps a URL using the Firecrawl API.
992
+ * @param url - The URL to map.
993
+ * @param params - Additional parameters for the map request.
994
+ * @returns The response from the map operation.
995
+ */
996
+ async mapUrl(url: string, params?: MapParams): Promise<MapResponse | ErrorResponse> {
997
+ const headers = this.prepareHeaders();
998
+ let jsonData: any = { url, ...params, origin: `js-sdk@${this.version}` };
999
+
1000
+ try {
1001
+ const response: AxiosResponse = await this.postRequest(
1002
+ this.apiUrl + `/v1/map`,
1003
+ jsonData,
1004
+ headers
1005
+ );
1006
+ if (response.status === 200) {
1007
+ return response.data as MapResponse;
1008
+ } else {
1009
+ this.handleError(response, "map");
1010
+ }
1011
+ } catch (error: any) {
1012
+ throw new FirecrawlError(error.message, 500);
1013
+ }
1014
+ return { success: false, error: "Internal server error." };
1015
+ }
1016
+
1017
+ /**
1018
+ * Initiates a batch scrape job for multiple URLs using the Firecrawl API.
1019
+ * @param url - The URLs to scrape.
1020
+ * @param params - Additional parameters for the scrape request.
1021
+ * @param pollInterval - Time in seconds for job status checks.
1022
+ * @param idempotencyKey - Optional idempotency key for the request.
1023
+ * @param webhook - Optional webhook for the batch scrape.
1024
+ * @param ignoreInvalidURLs - Optional flag to ignore invalid URLs.
1025
+ * @returns The response from the crawl operation.
1026
+ */
1027
+ async batchScrapeUrls(
1028
+ urls: string[],
1029
+ params?: ScrapeParams,
1030
+ pollInterval: number = 2,
1031
+ idempotencyKey?: string,
1032
+ webhook?: CrawlParams["webhook"],
1033
+ ignoreInvalidURLs?: boolean,
1034
+ maxConcurrency?: number,
1035
+ ): Promise<BatchScrapeStatusResponse | ErrorResponse> {
1036
+ const headers = this.prepareHeaders(idempotencyKey);
1037
+ let jsonData: any = { urls, webhook, ignoreInvalidURLs, maxConcurrency, ...params, origin: `js-sdk@${this.version}` };
1038
+ if (jsonData?.extract?.schema) {
1039
+ let schema = jsonData.extract.schema;
1040
+
1041
+ // Try parsing the schema as a Zod schema
1042
+ try {
1043
+ schema = zodToJsonSchema(schema);
1044
+ } catch (error) {
1045
+
1046
+ }
1047
+ jsonData = {
1048
+ ...jsonData,
1049
+ extract: {
1050
+ ...jsonData.extract,
1051
+ schema: schema,
1052
+ },
1053
+ };
1054
+ }
1055
+ if (jsonData?.jsonOptions?.schema) {
1056
+ let schema = jsonData.jsonOptions.schema;
1057
+
1058
+ // Try parsing the schema as a Zod schema
1059
+ try {
1060
+ schema = zodToJsonSchema(schema);
1061
+ } catch (error) {
1062
+
1063
+ }
1064
+ jsonData = {
1065
+ ...jsonData,
1066
+ jsonOptions: {
1067
+ ...jsonData.jsonOptions,
1068
+ schema: schema,
1069
+ },
1070
+ };
1071
+ }
1072
+ try {
1073
+ const response: AxiosResponse = await this.postRequest(
1074
+ this.apiUrl + `/v1/batch/scrape`,
1075
+ jsonData,
1076
+ headers
1077
+ );
1078
+ if (response.status === 200) {
1079
+ const id: string = response.data.id;
1080
+ return this.monitorJobStatus(id, headers, pollInterval);
1081
+ } else {
1082
+ this.handleError(response, "start batch scrape job");
1083
+ }
1084
+ } catch (error: any) {
1085
+ if (error.response?.data?.error) {
1086
+ throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`, error.response.status);
1087
+ } else {
1088
+ throw new FirecrawlError(error.message, 500);
1089
+ }
1090
+ }
1091
+ return { success: false, error: "Internal server error." };
1092
+ }
1093
+
1094
+ async asyncBatchScrapeUrls(
1095
+ urls: string[],
1096
+ params?: ScrapeParams,
1097
+ idempotencyKey?: string,
1098
+ webhook?: CrawlParams["webhook"],
1099
+ ignoreInvalidURLs?: boolean,
1100
+ ): Promise<BatchScrapeResponse | ErrorResponse> {
1101
+ const headers = this.prepareHeaders(idempotencyKey);
1102
+ let jsonData: any = { urls, webhook, ignoreInvalidURLs, ...params, origin: `js-sdk@${this.version}` };
1103
+ try {
1104
+ const response: AxiosResponse = await this.postRequest(
1105
+ this.apiUrl + `/v1/batch/scrape`,
1106
+ jsonData,
1107
+ headers
1108
+ );
1109
+ if (response.status === 200) {
1110
+ return response.data;
1111
+ } else {
1112
+ this.handleError(response, "start batch scrape job");
1113
+ }
1114
+ } catch (error: any) {
1115
+ if (error.response?.data?.error) {
1116
+ throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`, error.response.status);
1117
+ } else {
1118
+ throw new FirecrawlError(error.message, 500);
1119
+ }
1120
+ }
1121
+ return { success: false, error: "Internal server error." };
1122
+ }
1123
+
1124
+ /**
1125
+ * Initiates a batch scrape job and returns a CrawlWatcher to monitor the job via WebSocket.
1126
+ * @param urls - The URL to scrape.
1127
+ * @param params - Additional parameters for the scrape request.
1128
+ * @param idempotencyKey - Optional idempotency key for the request.
1129
+ * @returns A CrawlWatcher instance to monitor the crawl job.
1130
+ */
1131
+ async batchScrapeUrlsAndWatch(
1132
+ urls: string[],
1133
+ params?: ScrapeParams,
1134
+ idempotencyKey?: string,
1135
+ webhook?: CrawlParams["webhook"],
1136
+ ignoreInvalidURLs?: boolean,
1137
+ ) {
1138
+ const crawl = await this.asyncBatchScrapeUrls(urls, params, idempotencyKey, webhook, ignoreInvalidURLs);
1139
+
1140
+ if (crawl.success && crawl.id) {
1141
+ const id = crawl.id;
1142
+ return new CrawlWatcher(id, this);
1143
+ }
1144
+
1145
+ throw new FirecrawlError("Batch scrape job failed to start", 400);
1146
+ }
1147
+
1148
+ /**
1149
+ * Checks the status of a batch scrape job using the Firecrawl API.
1150
+ * @param id - The ID of the batch scrape operation.
1151
+ * @param getAllData - Paginate through all the pages of documents, returning the full list of all documents. (default: `false`)
1152
+ * @param nextURL - The `next` URL from the previous batch scrape status. Only required if you're not manually increasing `skip`. Only used when `getAllData = false`.
1153
+ * @param skip - How many entries to skip to paginate. Only used when `getAllData = false`.
1154
+ * @param limit - How many entries to return. Only used when `getAllData = false`.
1155
+ * @returns The response containing the job status.
1156
+ */
1157
+ async checkBatchScrapeStatus(id?: string, getAllData = false, nextURL?: string, skip?: number, limit?: number): Promise<BatchScrapeStatusResponse | ErrorResponse> {
1158
+ if (!id) {
1159
+ throw new FirecrawlError("No batch scrape ID provided", 400);
1160
+ }
1161
+
1162
+ const headers: AxiosRequestHeaders = this.prepareHeaders();
1163
+ const targetURL = new URL(nextURL ?? `${this.apiUrl}/v1/batch/scrape/${id}`);
1164
+ if (skip !== undefined) {
1165
+ targetURL.searchParams.set("skip", skip.toString());
1166
+ }
1167
+ if (limit !== undefined) {
1168
+ targetURL.searchParams.set("limit", limit.toString());
1169
+ }
1170
+
1171
+ try {
1172
+ const response: AxiosResponse = await this.getRequest(
1173
+ targetURL.href,
1174
+ headers
1175
+ );
1176
+ if (response.status === 200) {
1177
+ let allData = response.data.data;
1178
+ if (getAllData && response.data.status === "completed") {
1179
+ let statusData = response.data
1180
+ if ("data" in statusData) {
1181
+ let data = statusData.data;
1182
+ while (typeof statusData === 'object' && 'next' in statusData) {
1183
+ if (data.length === 0) {
1184
+ break
1185
+ }
1186
+ statusData = (await this.getRequest(statusData.next, headers)).data;
1187
+ data = data.concat(statusData.data);
1188
+ }
1189
+ allData = data;
1190
+ }
1191
+ }
1192
+
1193
+ let resp: BatchScrapeStatusResponse | ErrorResponse = {
1194
+ success: response.data.success,
1195
+ status: response.data.status,
1196
+ total: response.data.total,
1197
+ completed: response.data.completed,
1198
+ creditsUsed: response.data.creditsUsed,
1199
+ next: getAllData ? undefined : response.data.next,
1200
+ expiresAt: new Date(response.data.expiresAt),
1201
+ data: allData
1202
+ }
1203
+
1204
+ if (!response.data.success && response.data.error) {
1205
+ resp = {
1206
+ ...resp,
1207
+ success: false,
1208
+ error: response.data.error
1209
+ } as ErrorResponse;
1210
+ }
1211
+
1212
+ if (response.data.next) {
1213
+ (resp as BatchScrapeStatusResponse).next = response.data.next;
1214
+ }
1215
+
1216
+ return resp;
1217
+ } else {
1218
+ this.handleError(response, "check batch scrape status");
1219
+ }
1220
+ } catch (error: any) {
1221
+ throw new FirecrawlError(error.message, 500);
1222
+ }
1223
+ return { success: false, error: "Internal server error." };
1224
+ }
1225
+
1226
+ /**
1227
+ * Returns information about batch scrape errors.
1228
+ * @param id - The ID of the batch scrape operation.
1229
+ * @returns Information about batch scrape errors.
1230
+ */
1231
+ async checkBatchScrapeErrors(id: string): Promise<CrawlErrorsResponse | ErrorResponse> {
1232
+ const headers = this.prepareHeaders();
1233
+ try {
1234
+ const response: AxiosResponse = await this.deleteRequest(
1235
+ `${this.apiUrl}/v1/batch/scrape/${id}/errors`,
1236
+ headers
1237
+ );
1238
+ if (response.status === 200) {
1239
+ return response.data;
1240
+ } else {
1241
+ this.handleError(response, "check batch scrape errors");
1242
+ }
1243
+ } catch (error: any) {
1244
+ throw new FirecrawlError(error.message, 500);
1245
+ }
1246
+ return { success: false, error: "Internal server error." };
1247
+ }
1248
+
1249
+ /**
1250
+ * Extracts information from URLs using the Firecrawl API.
1251
+ * Currently in Beta. Expect breaking changes on future minor versions.
1252
+ * @param urls - The URLs to extract information from. Optional if using other methods for data extraction.
1253
+ * @param params - Additional parameters for the extract request.
1254
+ * @returns The response from the extract operation.
1255
+ */
1256
+ async extract<T extends zt.ZodSchema = any>(urls?: string[], params?: ExtractParams<T>): Promise<ExtractResponse<zt.infer<T>> | ErrorResponse> {
1257
+ const headers = this.prepareHeaders();
1258
+
1259
+ let jsonData: { urls?: string[] } & ExtractParams<T> = { urls: urls, ...params };
1260
+ let jsonSchema: any;
1261
+ try {
1262
+ if (!params?.schema) {
1263
+ jsonSchema = undefined;
1264
+ } else {
1265
+ try {
1266
+ jsonSchema = zodToJsonSchema(params.schema as zt.ZodType);
1267
+ } catch (_) {
1268
+ jsonSchema = params.schema;
1269
+ }
1270
+ }
1271
+ } catch (error: any) {
1272
+ throw new FirecrawlError("Invalid schema. Schema must be either a valid Zod schema or JSON schema object.", 400);
1273
+ }
1274
+
1275
+ try {
1276
+ const response: AxiosResponse = await this.postRequest(
1277
+ this.apiUrl + `/v1/extract`,
1278
+ { ...jsonData, schema: jsonSchema, origin: `js-sdk@${this.version}` },
1279
+ headers
1280
+ );
1281
+
1282
+ if (response.status === 200) {
1283
+ const jobId = response.data.id;
1284
+ let extractStatus;
1285
+ do {
1286
+ const statusResponse: AxiosResponse = await this.getRequest(
1287
+ `${this.apiUrl}/v1/extract/${jobId}`,
1288
+ headers
1289
+ );
1290
+ extractStatus = statusResponse.data;
1291
+ if (extractStatus.status === "completed") {
1292
+ if (extractStatus.success) {
1293
+ return {
1294
+ success: true,
1295
+ data: extractStatus.data,
1296
+ warning: extractStatus.warning,
1297
+ error: extractStatus.error,
1298
+ sources: extractStatus?.sources || undefined,
1299
+ };
1300
+ } else {
1301
+ throw new FirecrawlError(`Failed to extract data. Error: ${extractStatus.error}`, statusResponse.status);
1302
+ }
1303
+ } else if (extractStatus.status === "failed" || extractStatus.status === "cancelled") {
1304
+ throw new FirecrawlError(`Extract job ${extractStatus.status}. Error: ${extractStatus.error}`, statusResponse.status);
1305
+ }
1306
+ await new Promise(resolve => setTimeout(resolve, 1000)); // Polling interval
1307
+ } while (extractStatus.status !== "completed");
1308
+ } else {
1309
+ this.handleError(response, "extract");
1310
+ }
1311
+ } catch (error: any) {
1312
+ throw new FirecrawlError(error.message, 500, error.response?.data?.details);
1313
+ }
1314
+ return { success: false, error: "Internal server error."};
1315
+ }
1316
+
1317
+ /**
1318
+ * Initiates an asynchronous extract job for a URL using the Firecrawl API.
1319
+ * @param url - The URL to extract data from.
1320
+ * @param params - Additional parameters for the extract request.
1321
+ * @param idempotencyKey - Optional idempotency key for the request.
1322
+ * @returns The response from the extract operation.
1323
+ */
1324
+ async asyncExtract(
1325
+ urls: string[],
1326
+ params?: ExtractParams,
1327
+ idempotencyKey?: string
1328
+ ): Promise<ExtractResponse | ErrorResponse> {
1329
+ const headers = this.prepareHeaders(idempotencyKey);
1330
+ let jsonData: any = { urls, ...params };
1331
+ let jsonSchema: any;
1332
+
1333
+ try {
1334
+ if (!params?.schema) {
1335
+ jsonSchema = undefined;
1336
+ } else {
1337
+ try {
1338
+ jsonSchema = zodToJsonSchema(params.schema as zt.ZodType);
1339
+ } catch (_) {
1340
+ jsonSchema = params.schema;
1341
+ }
1342
+ }
1343
+ } catch (error: any) {
1344
+ throw new FirecrawlError("Invalid schema. Schema must be either a valid Zod schema or JSON schema object.", 400);
1345
+ }
1346
+
1347
+ try {
1348
+ const response: AxiosResponse = await this.postRequest(
1349
+ this.apiUrl + `/v1/extract`,
1350
+ { ...jsonData, schema: jsonSchema, origin: `js-sdk@${this.version}` },
1351
+ headers
1352
+ );
1353
+
1354
+ if (response.status === 200) {
1355
+ return response.data;
1356
+ } else {
1357
+ this.handleError(response, "start extract job");
1358
+ }
1359
+ } catch (error: any) {
1360
+ throw new FirecrawlError(error.message, 500, error.response?.data?.details);
1361
+ }
1362
+ return { success: false, error: "Internal server error." };
1363
+ }
1364
+
1365
+ /**
1366
+ * Retrieves the status of an extract job.
1367
+ * @param jobId - The ID of the extract job.
1368
+ * @returns The status of the extract job.
1369
+ */
1370
+ async getExtractStatus(jobId: string): Promise<any> {
1371
+ try {
1372
+ const response: AxiosResponse = await this.getRequest(
1373
+ `${this.apiUrl}/v1/extract/${jobId}`,
1374
+ this.prepareHeaders()
1375
+ );
1376
+
1377
+ if (response.status === 200) {
1378
+ return response.data;
1379
+ } else {
1380
+ this.handleError(response, "get extract status");
1381
+ }
1382
+ } catch (error: any) {
1383
+ throw new FirecrawlError(error.message, 500);
1384
+ }
1385
+ }
1386
+
1387
+ /**
1388
+ * Prepares the headers for an API request.
1389
+ * @param idempotencyKey - Optional key to ensure idempotency.
1390
+ * @returns The prepared headers.
1391
+ */
1392
+ prepareHeaders(idempotencyKey?: string): AxiosRequestHeaders {
1393
+ return {
1394
+ "Content-Type": "application/json",
1395
+ Authorization: `Bearer ${this.apiKey}`,
1396
+ ...(idempotencyKey ? { "x-idempotency-key": idempotencyKey } : {}),
1397
+ } as AxiosRequestHeaders & { "x-idempotency-key"?: string };
1398
+ }
1399
+
1400
+ /**
1401
+ * Sends a POST request to the specified URL.
1402
+ * @param url - The URL to send the request to.
1403
+ * @param data - The data to send in the request.
1404
+ * @param headers - The headers for the request.
1405
+ * @returns The response from the POST request.
1406
+ */
1407
+ postRequest(
1408
+ url: string,
1409
+ data: any,
1410
+ headers: AxiosRequestHeaders
1411
+ ): Promise<AxiosResponse> {
1412
+ return axios.post(url, data, { headers, timeout: (data?.timeout ? (data.timeout + 5000) : undefined) });
1413
+ }
1414
+
1415
+ /**
1416
+ * Sends a GET request to the specified URL.
1417
+ * @param url - The URL to send the request to.
1418
+ * @param headers - The headers for the request.
1419
+ * @returns The response from the GET request.
1420
+ */
1421
+ async getRequest(
1422
+ url: string,
1423
+ headers: AxiosRequestHeaders
1424
+ ): Promise<AxiosResponse> {
1425
+ try {
1426
+ return await axios.get(url, { headers });
1427
+ } catch (error) {
1428
+ if (error instanceof AxiosError && error.response) {
1429
+ return error.response as AxiosResponse;
1430
+ } else {
1431
+ throw error;
1432
+ }
1433
+ }
1434
+ }
1435
+
1436
+ /**
1437
+ * Sends a DELETE request to the specified URL.
1438
+ * @param url - The URL to send the request to.
1439
+ * @param headers - The headers for the request.
1440
+ * @returns The response from the DELETE request.
1441
+ */
1442
+ async deleteRequest(
1443
+ url: string,
1444
+ headers: AxiosRequestHeaders
1445
+ ): Promise<AxiosResponse> {
1446
+ try {
1447
+ return await axios.delete(url, { headers });
1448
+ } catch (error) {
1449
+ if (error instanceof AxiosError && error.response) {
1450
+ return error.response as AxiosResponse;
1451
+ } else {
1452
+ throw error;
1453
+ }
1454
+ }
1455
+ }
1456
+
1457
+ /**
1458
+ * Monitors the status of a crawl job until completion or failure.
1459
+ * @param id - The ID of the crawl operation.
1460
+ * @param headers - The headers for the request.
1461
+ * @param checkInterval - Interval in seconds for job status checks.
1462
+ * @param checkUrl - Optional URL to check the status (used for v1 API)
1463
+ * @returns The final job status or data.
1464
+ */
1465
+ async monitorJobStatus(
1466
+ id: string,
1467
+ headers: AxiosRequestHeaders,
1468
+ checkInterval: number
1469
+ ): Promise<CrawlStatusResponse | ErrorResponse> {
1470
+ let failedTries = 0;
1471
+ let networkRetries = 0;
1472
+ const maxNetworkRetries = 3;
1473
+
1474
+ while (true) {
1475
+ try {
1476
+ let statusResponse: AxiosResponse = await this.getRequest(
1477
+ `${this.apiUrl}/v1/crawl/${id}`,
1478
+ headers
1479
+ );
1480
+
1481
+ if (statusResponse.status === 200) {
1482
+ failedTries = 0;
1483
+ networkRetries = 0;
1484
+ let statusData = statusResponse.data;
1485
+
1486
+ if (statusData.status === "completed") {
1487
+ if ("data" in statusData) {
1488
+ let data = statusData.data;
1489
+ while (typeof statusData === 'object' && 'next' in statusData) {
1490
+ if (data.length === 0) {
1491
+ break
1492
+ }
1493
+ statusResponse = await this.getRequest(statusData.next, headers);
1494
+ statusData = statusResponse.data;
1495
+ data = data.concat(statusData.data);
1496
+ }
1497
+ statusData.data = data;
1498
+ return statusData;
1499
+ } else {
1500
+ throw new FirecrawlError("Crawl job completed but no data was returned", 500);
1501
+ }
1502
+ } else if (
1503
+ ["active", "paused", "pending", "queued", "waiting", "scraping"].includes(statusData.status)
1504
+ ) {
1505
+ checkInterval = Math.max(checkInterval, 2);
1506
+ await new Promise((resolve) =>
1507
+ setTimeout(resolve, checkInterval * 1000)
1508
+ );
1509
+ } else {
1510
+ throw new FirecrawlError(
1511
+ `Crawl job failed or was stopped. Status: ${statusData.status}`,
1512
+ 500
1513
+ );
1514
+ }
1515
+ } else {
1516
+ failedTries++;
1517
+ if (failedTries >= 3) {
1518
+ this.handleError(statusResponse, "check crawl status");
1519
+ }
1520
+ }
1521
+ } catch (error: any) {
1522
+ if (this.isRetryableError(error) && networkRetries < maxNetworkRetries) {
1523
+ networkRetries++;
1524
+ const backoffDelay = Math.min(1000 * Math.pow(2, networkRetries - 1), 10000);
1525
+
1526
+ await new Promise((resolve) => setTimeout(resolve, backoffDelay));
1527
+ continue;
1528
+ }
1529
+
1530
+ throw new FirecrawlError(error, 500);
1531
+ }
1532
+ }
1533
+ }
1534
+
1535
+ /**
1536
+ * Determines if an error is retryable (transient network error)
1537
+ * @param error - The error to check
1538
+ * @returns True if the error should be retried
1539
+ */
1540
+ private isRetryableError(error: any): boolean {
1541
+ if (error instanceof AxiosError) {
1542
+ if (!error.response) {
1543
+ const code = error.code;
1544
+ const message = error.message?.toLowerCase() || '';
1545
+
1546
+ return (
1547
+ code === 'ECONNRESET' ||
1548
+ code === 'ETIMEDOUT' ||
1549
+ code === 'ENOTFOUND' ||
1550
+ code === 'ECONNREFUSED' ||
1551
+ message.includes('socket hang up') ||
1552
+ message.includes('network error') ||
1553
+ message.includes('timeout')
1554
+ );
1555
+ }
1556
+
1557
+ if (error.response?.status === 408 || error.response?.status === 504) {
1558
+ return true;
1559
+ }
1560
+ }
1561
+
1562
+ if (error && typeof error === 'object') {
1563
+ const code = error.code;
1564
+ const message = error.message?.toLowerCase() || '';
1565
+
1566
+ if (code === 'ECONNRESET' ||
1567
+ code === 'ETIMEDOUT' ||
1568
+ code === 'ENOTFOUND' ||
1569
+ code === 'ECONNREFUSED' ||
1570
+ message.includes('socket hang up') ||
1571
+ message.includes('network error') ||
1572
+ message.includes('timeout')) {
1573
+ return true;
1574
+ }
1575
+
1576
+ if (error.response?.status === 408 || error.response?.status === 504) {
1577
+ return true;
1578
+ }
1579
+ }
1580
+
1581
+ return false;
1582
+ }
1583
+
1584
+ /**
1585
+ * Handles errors from API responses.
1586
+ * @param {AxiosResponse} response - The response from the API.
1587
+ * @param {string} action - The action being performed when the error occurred.
1588
+ */
1589
+ handleError(response: AxiosResponse, action: string): void {
1590
+ if (!response) {
1591
+ throw new FirecrawlError(
1592
+ `No response received while trying to ${action}. This may be a network error or the server is unreachable.`,
1593
+ 0
1594
+ );
1595
+ }
1596
+
1597
+ if ([400, 402, 403, 408, 409, 500].includes(response.status)) {
1598
+ const errorMessage: string =
1599
+ response.data.error || "Unknown error occurred";
1600
+ const details = response.data.details ? ` - ${JSON.stringify(response.data.details)}` : '';
1601
+ throw new FirecrawlError(
1602
+ `Failed to ${action}. Status code: ${response.status}. Error: ${errorMessage}${details}`,
1603
+ response.status,
1604
+ response?.data?.details
1605
+ );
1606
+ } else {
1607
+ throw new FirecrawlError(
1608
+ `Unexpected error occurred while trying to ${action}. Status code: ${response.status}`,
1609
+ response.status
1610
+ );
1611
+ }
1612
+ }
1613
+
1614
+ /**
1615
+ * Initiates a deep research operation on a given query and polls until completion.
1616
+ * @param query - The query to research.
1617
+ * @param params - Parameters for the deep research operation.
1618
+ * @param onActivity - Optional callback to receive activity updates in real-time.
1619
+ * @param onSource - Optional callback to receive source updates in real-time.
1620
+ * @returns The final research results.
1621
+ */
1622
+ async deepResearch(
1623
+ query: string,
1624
+ params: DeepResearchParams<zt.ZodSchema>,
1625
+ onActivity?: (activity: {
1626
+ type: string;
1627
+ status: string;
1628
+ message: string;
1629
+ timestamp: string;
1630
+ depth: number;
1631
+ }) => void,
1632
+ onSource?: (source: {
1633
+ url: string;
1634
+ title?: string;
1635
+ description?: string;
1636
+ icon?: string;
1637
+ }) => void
1638
+ ): Promise<DeepResearchStatusResponse | ErrorResponse> {
1639
+ try {
1640
+ const response = await this.asyncDeepResearch(query, params);
1641
+
1642
+ if (!response.success || 'error' in response) {
1643
+ return { success: false, error: 'error' in response ? response.error : 'Unknown error' };
1644
+ }
1645
+
1646
+ if (!response.id) {
1647
+ throw new FirecrawlError(`Failed to start research. No job ID returned.`, 500);
1648
+ }
1649
+
1650
+ const jobId = response.id;
1651
+ let researchStatus;
1652
+ let lastActivityCount = 0;
1653
+ let lastSourceCount = 0;
1654
+
1655
+ while (true) {
1656
+ researchStatus = await this.checkDeepResearchStatus(jobId);
1657
+
1658
+ if ('error' in researchStatus && !researchStatus.success) {
1659
+ return researchStatus;
1660
+ }
1661
+
1662
+ // Stream new activities through the callback if provided
1663
+ if (onActivity && researchStatus.activities) {
1664
+ const newActivities = researchStatus.activities.slice(lastActivityCount);
1665
+ for (const activity of newActivities) {
1666
+ onActivity(activity);
1667
+ }
1668
+ lastActivityCount = researchStatus.activities.length;
1669
+ }
1670
+
1671
+ // Stream new sources through the callback if provided
1672
+ if (onSource && researchStatus.sources) {
1673
+ const newSources = researchStatus.sources.slice(lastSourceCount);
1674
+ for (const source of newSources) {
1675
+ onSource(source);
1676
+ }
1677
+ lastSourceCount = researchStatus.sources.length;
1678
+ }
1679
+
1680
+ if (researchStatus.status === "completed") {
1681
+ return researchStatus;
1682
+ }
1683
+
1684
+ if (researchStatus.status === "failed") {
1685
+ throw new FirecrawlError(
1686
+ `Research job ${researchStatus.status}. Error: ${researchStatus.error}`,
1687
+ 500
1688
+ );
1689
+ }
1690
+
1691
+ if (researchStatus.status !== "processing") {
1692
+ break;
1693
+ }
1694
+
1695
+ await new Promise(resolve => setTimeout(resolve, 2000));
1696
+ }
1697
+
1698
+ return { success: false, error: "Research job terminated unexpectedly" };
1699
+ } catch (error: any) {
1700
+ throw new FirecrawlError(error.message, 500, error.response?.data?.details);
1701
+ }
1702
+ }
1703
+
1704
+ /**
1705
+ * Initiates a deep research operation on a given query without polling.
1706
+ * @param params - Parameters for the deep research operation.
1707
+ * @returns The response containing the research job ID.
1708
+ */
1709
+ async asyncDeepResearch(query: string, params: DeepResearchParams<zt.ZodSchema>): Promise<DeepResearchResponse | ErrorResponse> {
1710
+ const headers = this.prepareHeaders();
1711
+ let jsonData: any = { query, ...params, origin: `js-sdk@${this.version}` };
1712
+
1713
+ if (jsonData?.jsonOptions?.schema) {
1714
+ let schema = jsonData.jsonOptions.schema;
1715
+ // Try parsing the schema as a Zod schema
1716
+ try {
1717
+ schema = zodToJsonSchema(schema);
1718
+ } catch (error) {
1719
+ // Ignore error if schema can't be parsed as Zod
1720
+ }
1721
+ jsonData = {
1722
+ ...jsonData,
1723
+ jsonOptions: {
1724
+ ...jsonData.jsonOptions,
1725
+ schema: schema,
1726
+ },
1727
+ };
1728
+ }
1729
+
1730
+ try {
1731
+ const response: AxiosResponse = await this.postRequest(
1732
+ `${this.apiUrl}/v1/deep-research`,
1733
+ jsonData,
1734
+ headers
1735
+ );
1736
+
1737
+ if (response.status === 200) {
1738
+ return response.data;
1739
+ } else {
1740
+ this.handleError(response, "start deep research");
1741
+ }
1742
+ } catch (error: any) {
1743
+ if (error.response?.data?.error) {
1744
+ throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`, error.response.status);
1745
+ } else {
1746
+ throw new FirecrawlError(error.message, 500);
1747
+ }
1748
+ }
1749
+ return { success: false, error: "Internal server error." };
1750
+ }
1751
+
1752
+ /**
1753
+ * Checks the status of a deep research operation.
1754
+ * @param id - The ID of the deep research operation.
1755
+ * @returns The current status and results of the research operation.
1756
+ */
1757
+ async checkDeepResearchStatus(id: string): Promise<DeepResearchStatusResponse | ErrorResponse> {
1758
+ const headers = this.prepareHeaders();
1759
+ try {
1760
+ const response: AxiosResponse = await this.getRequest(
1761
+ `${this.apiUrl}/v1/deep-research/${id}`,
1762
+ headers
1763
+ );
1764
+
1765
+ if (response.status === 200) {
1766
+ return response.data;
1767
+ } else if (response.status === 404) {
1768
+ throw new FirecrawlError("Deep research job not found", 404);
1769
+ } else {
1770
+ this.handleError(response, "check deep research status");
1771
+ }
1772
+ } catch (error: any) {
1773
+ if (error.response?.data?.error) {
1774
+ throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`, error.response.status);
1775
+ } else {
1776
+ throw new FirecrawlError(error.message, 500);
1777
+ }
1778
+ }
1779
+ return { success: false, error: "Internal server error." };
1780
+ }
1781
+
1782
+ /**
1783
+ * @deprecated Use deepResearch() instead
1784
+ * Initiates a deep research operation on a given topic and polls until completion.
1785
+ * @param topic - The topic to research.
1786
+ * @param params - Parameters for the deep research operation.
1787
+ * @param onActivity - Optional callback to receive activity updates in real-time.
1788
+ * @returns The final research results.
1789
+ */
1790
+ async __deepResearch(
1791
+ topic: string,
1792
+ params: DeepResearchParams,
1793
+ onActivity?: (activity: {
1794
+ type: string;
1795
+ status: string;
1796
+ message: string;
1797
+ timestamp: string;
1798
+ depth: number;
1799
+ }) => void
1800
+ ): Promise<DeepResearchStatusResponse | ErrorResponse> {
1801
+ try {
1802
+ const response = await this.__asyncDeepResearch(topic, params);
1803
+
1804
+ if (!response.success || 'error' in response) {
1805
+ return { success: false, error: 'error' in response ? response.error : 'Unknown error' };
1806
+ }
1807
+
1808
+ if (!response.id) {
1809
+ throw new FirecrawlError(`Failed to start research. No job ID returned.`, 500);
1810
+ }
1811
+
1812
+ const jobId = response.id;
1813
+ let researchStatus;
1814
+ let lastActivityCount = 0;
1815
+
1816
+ while (true) {
1817
+ researchStatus = await this.__checkDeepResearchStatus(jobId);
1818
+
1819
+ if ('error' in researchStatus && !researchStatus.success) {
1820
+ return researchStatus;
1821
+ }
1822
+
1823
+ // Stream new activities through the callback if provided
1824
+ if (onActivity && researchStatus.activities) {
1825
+ const newActivities = researchStatus.activities.slice(lastActivityCount);
1826
+ for (const activity of newActivities) {
1827
+ onActivity(activity);
1828
+ }
1829
+ lastActivityCount = researchStatus.activities.length;
1830
+ }
1831
+
1832
+ if (researchStatus.status === "completed") {
1833
+ return researchStatus;
1834
+ }
1835
+
1836
+ if (researchStatus.status === "failed") {
1837
+ throw new FirecrawlError(
1838
+ `Research job ${researchStatus.status}. Error: ${researchStatus.error}`,
1839
+ 500
1840
+ );
1841
+ }
1842
+
1843
+ if (researchStatus.status !== "processing") {
1844
+ break;
1845
+ }
1846
+
1847
+ await new Promise(resolve => setTimeout(resolve, 2000));
1848
+ }
1849
+
1850
+ return { success: false, error: "Research job terminated unexpectedly" };
1851
+ } catch (error: any) {
1852
+ throw new FirecrawlError(error.message, 500, error.response?.data?.details);
1853
+ }
1854
+ }
1855
+
1856
+ /**
1857
+ * @deprecated Use asyncDeepResearch() instead
1858
+ * Initiates a deep research operation on a given topic without polling.
1859
+ * @param params - Parameters for the deep research operation.
1860
+ * @returns The response containing the research job ID.
1861
+ */
1862
+ async __asyncDeepResearch(topic: string, params: DeepResearchParams): Promise<DeepResearchResponse | ErrorResponse> {
1863
+ const headers = this.prepareHeaders();
1864
+ try {
1865
+ let jsonData: any = { topic, ...params, origin: `js-sdk@${this.version}` };
1866
+ const response: AxiosResponse = await this.postRequest(
1867
+ `${this.apiUrl}/v1/deep-research`,
1868
+ jsonData,
1869
+ headers
1870
+ );
1871
+
1872
+ if (response.status === 200) {
1873
+ return response.data;
1874
+ } else {
1875
+ this.handleError(response, "start deep research");
1876
+ }
1877
+ } catch (error: any) {
1878
+ if (error.response?.data?.error) {
1879
+ throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`, error.response.status);
1880
+ } else {
1881
+ throw new FirecrawlError(error.message, 500);
1882
+ }
1883
+ }
1884
+ return { success: false, error: "Internal server error." };
1885
+ }
1886
+
1887
+ /**
1888
+ * @deprecated Use checkDeepResearchStatus() instead
1889
+ * Checks the status of a deep research operation.
1890
+ * @param id - The ID of the deep research operation.
1891
+ * @returns The current status and results of the research operation.
1892
+ */
1893
+ async __checkDeepResearchStatus(id: string): Promise<DeepResearchStatusResponse | ErrorResponse> {
1894
+ const headers = this.prepareHeaders();
1895
+ try {
1896
+ const response: AxiosResponse = await this.getRequest(
1897
+ `${this.apiUrl}/v1/deep-research/${id}`,
1898
+ headers
1899
+ );
1900
+
1901
+ if (response.status === 200) {
1902
+ return response.data;
1903
+ } else if (response.status === 404) {
1904
+ throw new FirecrawlError("Deep research job not found", 404);
1905
+ } else {
1906
+ this.handleError(response, "check deep research status");
1907
+ }
1908
+ } catch (error: any) {
1909
+ if (error.response?.data?.error) {
1910
+ throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`, error.response.status);
1911
+ } else {
1912
+ throw new FirecrawlError(error.message, 500);
1913
+ }
1914
+ }
1915
+ return { success: false, error: "Internal server error." };
1916
+ }
1917
+
1918
+ /**
1919
+ * Generates LLMs.txt for a given URL and polls until completion.
1920
+ * @param url - The URL to generate LLMs.txt from.
1921
+ * @param params - Parameters for the LLMs.txt generation operation.
1922
+ * @returns The final generation results.
1923
+ */
1924
+ async generateLLMsText(url: string, params?: GenerateLLMsTextParams): Promise<GenerateLLMsTextStatusResponse | ErrorResponse> {
1925
+ try {
1926
+ const response = await this.asyncGenerateLLMsText(url, params);
1927
+
1928
+ if (!response.success || 'error' in response) {
1929
+ return { success: false, error: 'error' in response ? response.error : 'Unknown error' };
1930
+ }
1931
+
1932
+ if (!response.id) {
1933
+ throw new FirecrawlError(`Failed to start LLMs.txt generation. No job ID returned.`, 500);
1934
+ }
1935
+
1936
+ const jobId = response.id;
1937
+ let generationStatus;
1938
+
1939
+ while (true) {
1940
+ generationStatus = await this.checkGenerateLLMsTextStatus(jobId);
1941
+
1942
+ if ('error' in generationStatus && !generationStatus.success) {
1943
+ return generationStatus;
1944
+ }
1945
+
1946
+ if (generationStatus.status === "completed") {
1947
+ return generationStatus;
1948
+ }
1949
+
1950
+ if (generationStatus.status === "failed") {
1951
+ throw new FirecrawlError(
1952
+ `LLMs.txt generation job ${generationStatus.status}. Error: ${generationStatus.error}`,
1953
+ 500
1954
+ );
1955
+ }
1956
+
1957
+ if (generationStatus.status !== "processing") {
1958
+ break;
1959
+ }
1960
+
1961
+ await new Promise(resolve => setTimeout(resolve, 2000));
1962
+ }
1963
+
1964
+ return { success: false, error: "LLMs.txt generation job terminated unexpectedly" };
1965
+ } catch (error: any) {
1966
+ throw new FirecrawlError(error.message, 500, error.response?.data?.details);
1967
+ }
1968
+ }
1969
+
1970
+ /**
1971
+ * Initiates a LLMs.txt generation operation without polling.
1972
+ * @param url - The URL to generate LLMs.txt from.
1973
+ * @param params - Parameters for the LLMs.txt generation operation.
1974
+ * @returns The response containing the generation job ID.
1975
+ */
1976
+ async asyncGenerateLLMsText(url: string, params?: GenerateLLMsTextParams): Promise<GenerateLLMsTextResponse | ErrorResponse> {
1977
+ const headers = this.prepareHeaders();
1978
+ let jsonData: any = { url, ...params, origin: `js-sdk@${this.version}` };
1979
+ try {
1980
+ const response: AxiosResponse = await this.postRequest(
1981
+ `${this.apiUrl}/v1/llmstxt`,
1982
+ jsonData,
1983
+ headers
1984
+ );
1985
+
1986
+ if (response.status === 200) {
1987
+ return response.data;
1988
+ } else {
1989
+ this.handleError(response, "start LLMs.txt generation");
1990
+ }
1991
+ } catch (error: any) {
1992
+ if (error.response?.data?.error) {
1993
+ throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`, error.response.status);
1994
+ } else {
1995
+ throw new FirecrawlError(error.message, 500);
1996
+ }
1997
+ }
1998
+ return { success: false, error: "Internal server error." };
1999
+ }
2000
+
2001
+ /**
2002
+ * Checks the status of a LLMs.txt generation operation.
2003
+ * @param id - The ID of the LLMs.txt generation operation.
2004
+ * @returns The current status and results of the generation operation.
2005
+ */
2006
+ async checkGenerateLLMsTextStatus(id: string): Promise<GenerateLLMsTextStatusResponse | ErrorResponse> {
2007
+ const headers = this.prepareHeaders();
2008
+ try {
2009
+ const response: AxiosResponse = await this.getRequest(
2010
+ `${this.apiUrl}/v1/llmstxt/${id}`,
2011
+ headers
2012
+ );
2013
+
2014
+ if (response.status === 200) {
2015
+ return response.data;
2016
+ } else if (response.status === 404) {
2017
+ throw new FirecrawlError("LLMs.txt generation job not found", 404);
2018
+ } else {
2019
+ this.handleError(response, "check LLMs.txt generation status");
2020
+ }
2021
+ } catch (error: any) {
2022
+ if (error.response?.data?.error) {
2023
+ throw new FirecrawlError(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`, error.response.status);
2024
+ } else {
2025
+ throw new FirecrawlError(error.message, 500);
2026
+ }
2027
+ }
2028
+ return { success: false, error: "Internal server error." };
2029
+ }
2030
+ }
2031
+
2032
+ interface CrawlWatcherEvents {
2033
+ document: CustomEvent<FirecrawlDocument<undefined>>,
2034
+ done: CustomEvent<{
2035
+ status: CrawlStatusResponse["status"];
2036
+ data: FirecrawlDocument<undefined>[];
2037
+ }>,
2038
+ error: CustomEvent<{
2039
+ status: CrawlStatusResponse["status"],
2040
+ data: FirecrawlDocument<undefined>[],
2041
+ error: string,
2042
+ }>,
2043
+ }
2044
+
2045
+ export class CrawlWatcher extends TypedEventTarget<CrawlWatcherEvents> {
2046
+ private ws: WebSocket;
2047
+ public data: FirecrawlDocument<undefined>[];
2048
+ public status: CrawlStatusResponse["status"];
2049
+ public id: string;
2050
+
2051
+ constructor(id: string, app: FirecrawlApp) {
2052
+ super();
2053
+ this.id = id;
2054
+ // replace `http` with `ws` (`http://` -> `ws://` and `https://` -> `wss://`)
2055
+ const wsUrl = app.apiUrl.replace(/^http/, "ws");
2056
+ this.ws = new WebSocket(`${wsUrl}/v1/crawl/${id}`, app.apiKey);
2057
+ this.status = "scraping";
2058
+ this.data = [];
2059
+
2060
+ type ErrorMessage = {
2061
+ type: "error",
2062
+ error: string,
2063
+ }
2064
+
2065
+ type CatchupMessage = {
2066
+ type: "catchup",
2067
+ data: CrawlStatusResponse,
2068
+ }
2069
+
2070
+ type DocumentMessage = {
2071
+ type: "document",
2072
+ data: FirecrawlDocument<undefined>,
2073
+ }
2074
+
2075
+ type DoneMessage = { type: "done" }
2076
+
2077
+ type Message = ErrorMessage | CatchupMessage | DoneMessage | DocumentMessage;
2078
+
2079
+ const messageHandler = (msg: Message) => {
2080
+ if (msg.type === "done") {
2081
+ this.status = "completed";
2082
+ this.dispatchTypedEvent("done", new CustomEvent("done", {
2083
+ detail: {
2084
+ status: this.status,
2085
+ data: this.data,
2086
+ id: this.id,
2087
+ },
2088
+ }));
2089
+ } else if (msg.type === "error") {
2090
+ this.status = "failed";
2091
+ this.dispatchTypedEvent("error", new CustomEvent("error", {
2092
+ detail: {
2093
+ status: this.status,
2094
+ data: this.data,
2095
+ error: msg.error,
2096
+ id: this.id,
2097
+ },
2098
+ }));
2099
+ } else if (msg.type === "catchup") {
2100
+ this.status = msg.data.status;
2101
+ this.data.push(...(msg.data.data ?? []));
2102
+ for (const doc of this.data) {
2103
+ this.dispatchTypedEvent("document", new CustomEvent("document", {
2104
+ detail: {
2105
+ ...doc,
2106
+ id: this.id,
2107
+ },
2108
+ }));
2109
+ }
2110
+ } else if (msg.type === "document") {
2111
+ this.dispatchTypedEvent("document", new CustomEvent("document", {
2112
+ detail: {
2113
+ ...msg.data,
2114
+ id: this.id,
2115
+ },
2116
+ }));
2117
+ }
2118
+ }
2119
+
2120
+ this.ws.onmessage = ((ev: MessageEvent) => {
2121
+ if (typeof ev.data !== "string") {
2122
+ this.ws.close();
2123
+ return;
2124
+ }
2125
+ try {
2126
+ const msg = JSON.parse(ev.data) as Message;
2127
+ messageHandler(msg);
2128
+ } catch (error) {
2129
+ console.error("Error on message", error);
2130
+ }
2131
+ }).bind(this);
2132
+
2133
+ this.ws.onclose = ((ev: CloseEvent) => {
2134
+ try {
2135
+ const msg = JSON.parse(ev.reason) as Message;
2136
+ messageHandler(msg);
2137
+ } catch (error) {
2138
+ console.error("Error on close", error);
2139
+ }
2140
+ }).bind(this);
2141
+
2142
+ this.ws.onerror = ((_: Event) => {
2143
+ this.status = "failed"
2144
+ this.dispatchTypedEvent("error", new CustomEvent("error", {
2145
+ detail: {
2146
+ status: this.status,
2147
+ data: this.data,
2148
+ error: "WebSocket error",
2149
+ id: this.id,
2150
+ },
2151
+ }));
2152
+ }).bind(this);
2153
+ }
2154
+
2155
+ close() {
2156
+ this.ws.close();
2157
+ }
2158
+ }