@mendable/firecrawl 1.2.2 → 1.18.0

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.
@@ -1,346 +0,0 @@
1
- import axios from "axios";
2
- import { zodToJsonSchema } from "zod-to-json-schema";
3
- import { WebSocket } from "isows";
4
- import { TypedEventTarget } from "typescript-event-target";
5
- /**
6
- * Main class for interacting with the Firecrawl API.
7
- * Provides methods for scraping, searching, crawling, and mapping web content.
8
- */
9
- export default class FirecrawlApp {
10
- /**
11
- * Initializes a new instance of the FirecrawlApp class.
12
- * @param config - Configuration options for the FirecrawlApp instance.
13
- */
14
- constructor({ apiKey = null, apiUrl = null }) {
15
- this.apiKey = apiKey || "";
16
- this.apiUrl = apiUrl || "https://api.firecrawl.dev";
17
- }
18
- /**
19
- * Scrapes a URL using the Firecrawl API.
20
- * @param url - The URL to scrape.
21
- * @param params - Additional parameters for the scrape request.
22
- * @returns The response from the scrape operation.
23
- */
24
- async scrapeUrl(url, params) {
25
- const headers = {
26
- "Content-Type": "application/json",
27
- Authorization: `Bearer ${this.apiKey}`,
28
- };
29
- let jsonData = { url, ...params };
30
- if (jsonData?.extract?.schema) {
31
- let schema = jsonData.extract.schema;
32
- // Try parsing the schema as a Zod schema
33
- try {
34
- schema = zodToJsonSchema(schema);
35
- }
36
- catch (error) {
37
- }
38
- jsonData = {
39
- ...jsonData,
40
- extract: {
41
- ...jsonData.extract,
42
- schema: schema,
43
- },
44
- };
45
- }
46
- try {
47
- const response = await axios.post(this.apiUrl + `/v1/scrape`, jsonData, { headers });
48
- if (response.status === 200) {
49
- const responseData = response.data;
50
- if (responseData.success) {
51
- return {
52
- success: true,
53
- warning: responseData.warning,
54
- error: responseData.error,
55
- ...responseData.data
56
- };
57
- }
58
- else {
59
- throw new Error(`Failed to scrape URL. Error: ${responseData.error}`);
60
- }
61
- }
62
- else {
63
- this.handleError(response, "scrape URL");
64
- }
65
- }
66
- catch (error) {
67
- throw new Error(error.message);
68
- }
69
- return { success: false, error: "Internal server error." };
70
- }
71
- /**
72
- * This method is intended to search for a query using the Firecrawl API. However, it is not supported in version 1 of the API.
73
- * @param query - The search query string.
74
- * @param params - Additional parameters for the search.
75
- * @returns Throws an error advising to use version 0 of the API.
76
- */
77
- async search(query, params) {
78
- throw new Error("Search is not supported in v1, please update FirecrawlApp() initialization to use v0.");
79
- }
80
- /**
81
- * Initiates a crawl job for a URL using the Firecrawl API.
82
- * @param url - The URL to crawl.
83
- * @param params - Additional parameters for the crawl request.
84
- * @param pollInterval - Time in seconds for job status checks.
85
- * @param idempotencyKey - Optional idempotency key for the request.
86
- * @returns The response from the crawl operation.
87
- */
88
- async crawlUrl(url, params, pollInterval = 2, idempotencyKey) {
89
- const headers = this.prepareHeaders(idempotencyKey);
90
- let jsonData = { url, ...params };
91
- try {
92
- const response = await this.postRequest(this.apiUrl + `/v1/crawl`, jsonData, headers);
93
- if (response.status === 200) {
94
- const id = response.data.id;
95
- return this.monitorJobStatus(id, headers, pollInterval);
96
- }
97
- else {
98
- this.handleError(response, "start crawl job");
99
- }
100
- }
101
- catch (error) {
102
- if (error.response?.data?.error) {
103
- throw new Error(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`);
104
- }
105
- else {
106
- throw new Error(error.message);
107
- }
108
- }
109
- return { success: false, error: "Internal server error." };
110
- }
111
- async asyncCrawlUrl(url, params, idempotencyKey) {
112
- const headers = this.prepareHeaders(idempotencyKey);
113
- let jsonData = { url, ...params };
114
- try {
115
- const response = await this.postRequest(this.apiUrl + `/v1/crawl`, jsonData, headers);
116
- if (response.status === 200) {
117
- return response.data;
118
- }
119
- else {
120
- this.handleError(response, "start crawl job");
121
- }
122
- }
123
- catch (error) {
124
- if (error.response?.data?.error) {
125
- throw new Error(`Request failed with status code ${error.response.status}. Error: ${error.response.data.error} ${error.response.data.details ? ` - ${JSON.stringify(error.response.data.details)}` : ''}`);
126
- }
127
- else {
128
- throw new Error(error.message);
129
- }
130
- }
131
- return { success: false, error: "Internal server error." };
132
- }
133
- /**
134
- * Checks the status of a crawl job using the Firecrawl API.
135
- * @param id - The ID of the crawl operation.
136
- * @returns The response containing the job status.
137
- */
138
- async checkCrawlStatus(id) {
139
- if (!id) {
140
- throw new Error("No crawl ID provided");
141
- }
142
- const headers = this.prepareHeaders();
143
- try {
144
- const response = await this.getRequest(`${this.apiUrl}/v1/crawl/${id}`, headers);
145
- if (response.status === 200) {
146
- return ({
147
- success: true,
148
- status: response.data.status,
149
- total: response.data.total,
150
- completed: response.data.completed,
151
- creditsUsed: response.data.creditsUsed,
152
- expiresAt: new Date(response.data.expiresAt),
153
- next: response.data.next,
154
- data: response.data.data,
155
- error: response.data.error
156
- });
157
- }
158
- else {
159
- this.handleError(response, "check crawl status");
160
- }
161
- }
162
- catch (error) {
163
- throw new Error(error.message);
164
- }
165
- return { success: false, error: "Internal server error." };
166
- }
167
- async crawlUrlAndWatch(url, params, idempotencyKey) {
168
- const crawl = await this.asyncCrawlUrl(url, params, idempotencyKey);
169
- if (crawl.success && crawl.id) {
170
- const id = crawl.id;
171
- return new CrawlWatcher(id, this);
172
- }
173
- throw new Error("Crawl job failed to start");
174
- }
175
- async mapUrl(url, params) {
176
- const headers = this.prepareHeaders();
177
- let jsonData = { url, ...params };
178
- try {
179
- const response = await this.postRequest(this.apiUrl + `/v1/map`, jsonData, headers);
180
- if (response.status === 200) {
181
- return response.data;
182
- }
183
- else {
184
- this.handleError(response, "map");
185
- }
186
- }
187
- catch (error) {
188
- throw new Error(error.message);
189
- }
190
- return { success: false, error: "Internal server error." };
191
- }
192
- /**
193
- * Prepares the headers for an API request.
194
- * @param idempotencyKey - Optional key to ensure idempotency.
195
- * @returns The prepared headers.
196
- */
197
- prepareHeaders(idempotencyKey) {
198
- return {
199
- "Content-Type": "application/json",
200
- Authorization: `Bearer ${this.apiKey}`,
201
- ...(idempotencyKey ? { "x-idempotency-key": idempotencyKey } : {}),
202
- };
203
- }
204
- /**
205
- * Sends a POST request to the specified URL.
206
- * @param url - The URL to send the request to.
207
- * @param data - The data to send in the request.
208
- * @param headers - The headers for the request.
209
- * @returns The response from the POST request.
210
- */
211
- postRequest(url, data, headers) {
212
- return axios.post(url, data, { headers });
213
- }
214
- /**
215
- * Sends a GET request to the specified URL.
216
- * @param url - The URL to send the request to.
217
- * @param headers - The headers for the request.
218
- * @returns The response from the GET request.
219
- */
220
- getRequest(url, headers) {
221
- return axios.get(url, { headers });
222
- }
223
- /**
224
- * Monitors the status of a crawl job until completion or failure.
225
- * @param id - The ID of the crawl operation.
226
- * @param headers - The headers for the request.
227
- * @param checkInterval - Interval in seconds for job status checks.
228
- * @param checkUrl - Optional URL to check the status (used for v1 API)
229
- * @returns The final job status or data.
230
- */
231
- async monitorJobStatus(id, headers, checkInterval) {
232
- while (true) {
233
- let statusResponse = await this.getRequest(`${this.apiUrl}/v1/crawl/${id}`, headers);
234
- if (statusResponse.status === 200) {
235
- let statusData = statusResponse.data;
236
- if (statusData.status === "completed") {
237
- if ("data" in statusData) {
238
- let data = statusData.data;
239
- while ('next' in statusData) {
240
- statusResponse = await this.getRequest(statusData.next, headers);
241
- statusData = statusResponse.data;
242
- data = data.concat(statusData.data);
243
- }
244
- statusData.data = data;
245
- return statusData;
246
- }
247
- else {
248
- throw new Error("Crawl job completed but no data was returned");
249
- }
250
- }
251
- else if (["active", "paused", "pending", "queued", "waiting", "scraping"].includes(statusData.status)) {
252
- checkInterval = Math.max(checkInterval, 2);
253
- await new Promise((resolve) => setTimeout(resolve, checkInterval * 1000));
254
- }
255
- else {
256
- throw new Error(`Crawl job failed or was stopped. Status: ${statusData.status}`);
257
- }
258
- }
259
- else {
260
- this.handleError(statusResponse, "check crawl status");
261
- }
262
- }
263
- }
264
- /**
265
- * Handles errors from API responses.
266
- * @param {AxiosResponse} response - The response from the API.
267
- * @param {string} action - The action being performed when the error occurred.
268
- */
269
- handleError(response, action) {
270
- if ([402, 408, 409, 500].includes(response.status)) {
271
- const errorMessage = response.data.error || "Unknown error occurred";
272
- throw new Error(`Failed to ${action}. Status code: ${response.status}. Error: ${errorMessage}`);
273
- }
274
- else {
275
- throw new Error(`Unexpected error occurred while trying to ${action}. Status code: ${response.status}`);
276
- }
277
- }
278
- }
279
- export class CrawlWatcher extends TypedEventTarget {
280
- constructor(id, app) {
281
- super();
282
- this.ws = new WebSocket(`${app.apiUrl}/v1/crawl/${id}`, app.apiKey);
283
- this.status = "scraping";
284
- this.data = [];
285
- const messageHandler = (msg) => {
286
- if (msg.type === "done") {
287
- this.status = "completed";
288
- this.dispatchTypedEvent("done", new CustomEvent("done", {
289
- detail: {
290
- status: this.status,
291
- data: this.data,
292
- },
293
- }));
294
- }
295
- else if (msg.type === "error") {
296
- this.status = "failed";
297
- this.dispatchTypedEvent("error", new CustomEvent("error", {
298
- detail: {
299
- status: this.status,
300
- data: this.data,
301
- error: msg.error,
302
- },
303
- }));
304
- }
305
- else if (msg.type === "catchup") {
306
- this.status = msg.data.status;
307
- this.data.push(...(msg.data.data ?? []));
308
- for (const doc of this.data) {
309
- this.dispatchTypedEvent("document", new CustomEvent("document", {
310
- detail: doc,
311
- }));
312
- }
313
- }
314
- else if (msg.type === "document") {
315
- this.dispatchTypedEvent("document", new CustomEvent("document", {
316
- detail: msg.data,
317
- }));
318
- }
319
- };
320
- this.ws.onmessage = ((ev) => {
321
- if (typeof ev.data !== "string") {
322
- this.ws.close();
323
- return;
324
- }
325
- const msg = JSON.parse(ev.data);
326
- messageHandler(msg);
327
- }).bind(this);
328
- this.ws.onclose = ((ev) => {
329
- const msg = JSON.parse(ev.reason);
330
- messageHandler(msg);
331
- }).bind(this);
332
- this.ws.onerror = ((_) => {
333
- this.status = "failed";
334
- this.dispatchTypedEvent("error", new CustomEvent("error", {
335
- detail: {
336
- status: this.status,
337
- data: this.data,
338
- error: "WebSocket error",
339
- },
340
- }));
341
- }).bind(this);
342
- }
343
- close() {
344
- this.ws.close();
345
- }
346
- }
@@ -1 +0,0 @@
1
- {"type": "module"}
package/types/index.d.ts DELETED
@@ -1,260 +0,0 @@
1
- import { AxiosResponse, AxiosRequestHeaders } from "axios";
2
- import { z } from "zod";
3
- import { TypedEventTarget } from "typescript-event-target";
4
- /**
5
- * Configuration interface for FirecrawlApp.
6
- * @param apiKey - Optional API key for authentication.
7
- * @param apiUrl - Optional base URL of the API; defaults to 'https://api.firecrawl.dev'.
8
- */
9
- export interface FirecrawlAppConfig {
10
- apiKey?: string | null;
11
- apiUrl?: string | null;
12
- }
13
- /**
14
- * Metadata for a Firecrawl document.
15
- * Includes various optional properties for document metadata.
16
- */
17
- export interface FirecrawlDocumentMetadata {
18
- title?: string;
19
- description?: string;
20
- language?: string;
21
- keywords?: string;
22
- robots?: string;
23
- ogTitle?: string;
24
- ogDescription?: string;
25
- ogUrl?: string;
26
- ogImage?: string;
27
- ogAudio?: string;
28
- ogDeterminer?: string;
29
- ogLocale?: string;
30
- ogLocaleAlternate?: string[];
31
- ogSiteName?: string;
32
- ogVideo?: string;
33
- dctermsCreated?: string;
34
- dcDateCreated?: string;
35
- dcDate?: string;
36
- dctermsType?: string;
37
- dcType?: string;
38
- dctermsAudience?: string;
39
- dctermsSubject?: string;
40
- dcSubject?: string;
41
- dcDescription?: string;
42
- dctermsKeywords?: string;
43
- modifiedTime?: string;
44
- publishedTime?: string;
45
- articleTag?: string;
46
- articleSection?: string;
47
- sourceURL?: string;
48
- statusCode?: number;
49
- error?: string;
50
- [key: string]: any;
51
- }
52
- /**
53
- * Document interface for Firecrawl.
54
- * Represents a document retrieved or processed by Firecrawl.
55
- */
56
- export interface FirecrawlDocument {
57
- url?: string;
58
- markdown?: string;
59
- html?: string;
60
- rawHtml?: string;
61
- links?: string[];
62
- extract?: Record<any, any>;
63
- screenshot?: string;
64
- metadata?: FirecrawlDocumentMetadata;
65
- }
66
- /**
67
- * Parameters for scraping operations.
68
- * Defines the options and configurations available for scraping web content.
69
- */
70
- export interface ScrapeParams {
71
- formats: ("markdown" | "html" | "rawHtml" | "content" | "links" | "screenshot" | "extract" | "full@scrennshot")[];
72
- headers?: Record<string, string>;
73
- includeTags?: string[];
74
- excludeTags?: string[];
75
- onlyMainContent?: boolean;
76
- extract?: {
77
- prompt?: string;
78
- schema?: z.ZodSchema | any;
79
- systemPrompt?: string;
80
- };
81
- waitFor?: number;
82
- timeout?: number;
83
- }
84
- /**
85
- * Response interface for scraping operations.
86
- * Defines the structure of the response received after a scraping operation.
87
- */
88
- export interface ScrapeResponse extends FirecrawlDocument {
89
- success: true;
90
- warning?: string;
91
- error?: string;
92
- }
93
- /**
94
- * Parameters for crawling operations.
95
- * Includes options for both scraping and mapping during a crawl.
96
- */
97
- export interface CrawlParams {
98
- includePaths?: string[];
99
- excludePaths?: string[];
100
- maxDepth?: number;
101
- limit?: number;
102
- allowBackwardLinks?: boolean;
103
- allowExternalLinks?: boolean;
104
- ignoreSitemap?: boolean;
105
- scrapeOptions?: ScrapeParams;
106
- webhook?: string;
107
- }
108
- /**
109
- * Response interface for crawling operations.
110
- * Defines the structure of the response received after initiating a crawl.
111
- */
112
- export interface CrawlResponse {
113
- id?: string;
114
- url?: string;
115
- success: true;
116
- error?: string;
117
- }
118
- /**
119
- * Response interface for job status checks.
120
- * Provides detailed status of a crawl job including progress and results.
121
- */
122
- export interface CrawlStatusResponse {
123
- success: true;
124
- total: number;
125
- completed: number;
126
- creditsUsed: number;
127
- expiresAt: Date;
128
- status: "scraping" | "completed" | "failed";
129
- next: string;
130
- data?: FirecrawlDocument[];
131
- error?: string;
132
- }
133
- /**
134
- * Parameters for mapping operations.
135
- * Defines options for mapping URLs during a crawl.
136
- */
137
- export interface MapParams {
138
- search?: string;
139
- ignoreSitemap?: boolean;
140
- includeSubdomains?: boolean;
141
- limit?: number;
142
- }
143
- /**
144
- * Response interface for mapping operations.
145
- * Defines the structure of the response received after a mapping operation.
146
- */
147
- export interface MapResponse {
148
- success: true;
149
- links?: string[];
150
- error?: string;
151
- }
152
- /**
153
- * Error response interface.
154
- * Defines the structure of the response received when an error occurs.
155
- */
156
- export interface ErrorResponse {
157
- success: false;
158
- error: string;
159
- }
160
- /**
161
- * Main class for interacting with the Firecrawl API.
162
- * Provides methods for scraping, searching, crawling, and mapping web content.
163
- */
164
- export default class FirecrawlApp {
165
- apiKey: string;
166
- apiUrl: string;
167
- /**
168
- * Initializes a new instance of the FirecrawlApp class.
169
- * @param config - Configuration options for the FirecrawlApp instance.
170
- */
171
- constructor({ apiKey, apiUrl }: FirecrawlAppConfig);
172
- /**
173
- * Scrapes a URL using the Firecrawl API.
174
- * @param url - The URL to scrape.
175
- * @param params - Additional parameters for the scrape request.
176
- * @returns The response from the scrape operation.
177
- */
178
- scrapeUrl(url: string, params?: ScrapeParams): Promise<ScrapeResponse | ErrorResponse>;
179
- /**
180
- * This method is intended to search for a query using the Firecrawl API. However, it is not supported in version 1 of the API.
181
- * @param query - The search query string.
182
- * @param params - Additional parameters for the search.
183
- * @returns Throws an error advising to use version 0 of the API.
184
- */
185
- search(query: string, params?: any): Promise<any>;
186
- /**
187
- * Initiates a crawl job for a URL using the Firecrawl API.
188
- * @param url - The URL to crawl.
189
- * @param params - Additional parameters for the crawl request.
190
- * @param pollInterval - Time in seconds for job status checks.
191
- * @param idempotencyKey - Optional idempotency key for the request.
192
- * @returns The response from the crawl operation.
193
- */
194
- crawlUrl(url: string, params?: CrawlParams, pollInterval?: number, idempotencyKey?: string): Promise<CrawlStatusResponse | ErrorResponse>;
195
- asyncCrawlUrl(url: string, params?: CrawlParams, idempotencyKey?: string): Promise<CrawlResponse | ErrorResponse>;
196
- /**
197
- * Checks the status of a crawl job using the Firecrawl API.
198
- * @param id - The ID of the crawl operation.
199
- * @returns The response containing the job status.
200
- */
201
- checkCrawlStatus(id?: string): Promise<CrawlStatusResponse | ErrorResponse>;
202
- crawlUrlAndWatch(url: string, params?: CrawlParams, idempotencyKey?: string): Promise<CrawlWatcher>;
203
- mapUrl(url: string, params?: MapParams): Promise<MapResponse | ErrorResponse>;
204
- /**
205
- * Prepares the headers for an API request.
206
- * @param idempotencyKey - Optional key to ensure idempotency.
207
- * @returns The prepared headers.
208
- */
209
- prepareHeaders(idempotencyKey?: string): AxiosRequestHeaders;
210
- /**
211
- * Sends a POST request to the specified URL.
212
- * @param url - The URL to send the request to.
213
- * @param data - The data to send in the request.
214
- * @param headers - The headers for the request.
215
- * @returns The response from the POST request.
216
- */
217
- postRequest(url: string, data: any, headers: AxiosRequestHeaders): Promise<AxiosResponse>;
218
- /**
219
- * Sends a GET request to the specified URL.
220
- * @param url - The URL to send the request to.
221
- * @param headers - The headers for the request.
222
- * @returns The response from the GET request.
223
- */
224
- getRequest(url: string, headers: AxiosRequestHeaders): Promise<AxiosResponse>;
225
- /**
226
- * Monitors the status of a crawl job until completion or failure.
227
- * @param id - The ID of the crawl operation.
228
- * @param headers - The headers for the request.
229
- * @param checkInterval - Interval in seconds for job status checks.
230
- * @param checkUrl - Optional URL to check the status (used for v1 API)
231
- * @returns The final job status or data.
232
- */
233
- monitorJobStatus(id: string, headers: AxiosRequestHeaders, checkInterval: number): Promise<CrawlStatusResponse>;
234
- /**
235
- * Handles errors from API responses.
236
- * @param {AxiosResponse} response - The response from the API.
237
- * @param {string} action - The action being performed when the error occurred.
238
- */
239
- handleError(response: AxiosResponse, action: string): void;
240
- }
241
- interface CrawlWatcherEvents {
242
- document: CustomEvent<FirecrawlDocument>;
243
- done: CustomEvent<{
244
- status: CrawlStatusResponse["status"];
245
- data: FirecrawlDocument[];
246
- }>;
247
- error: CustomEvent<{
248
- status: CrawlStatusResponse["status"];
249
- data: FirecrawlDocument[];
250
- error: string;
251
- }>;
252
- }
253
- export declare class CrawlWatcher extends TypedEventTarget<CrawlWatcherEvents> {
254
- private ws;
255
- data: FirecrawlDocument[];
256
- status: CrawlStatusResponse["status"];
257
- constructor(id: string, app: FirecrawlApp);
258
- close(): void;
259
- }
260
- export {};