Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support environments without ws by dynamically importing WebSocket module with error handling #997

Merged
merged 6 commits into from
Dec 23, 2024
21 changes: 20 additions & 1 deletion apps/js-sdk/firecrawl/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,24 @@
import axios, { type AxiosResponse, type AxiosRequestHeaders, AxiosError } from "axios";
import type * as zt from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
import { WebSocket } from "isows";

import type { WebSocket as IsowsWebSocket } from 'isows';
/**
* Dynamically imports the WebSocket class from 'isows'.
* If the import fails, WebSocket is set to null.
* This approach is used because some environments, such as Firebase Functions,
* might not support WebSocket natively.
*/
const WebSocket: typeof IsowsWebSocket | null = await (async () => {
try {
const module = await import('isows');
return module.WebSocket;
} catch (error) {
console.error("Failed to load 'isows' module:", error);
tomkosm marked this conversation as resolved.
Show resolved Hide resolved
return null;
}
})();

import { TypedEventTarget } from "typescript-event-target";

/**
Expand Down Expand Up @@ -938,6 +955,8 @@ export class CrawlWatcher extends TypedEventTarget<CrawlWatcherEvents> {

constructor(id: string, app: FirecrawlApp) {
super();
if(!WebSocket)
throw new FirecrawlError("WebSocket module failed to load. Your system might not support WebSocket.", 500);
this.ws = new WebSocket(`${app.apiUrl}/v1/crawl/${id}`, app.apiKey);
this.status = "scraping";
this.data = [];
Expand Down
Loading