Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
feat(sdks): keep v1-style calls working on the v2 clients, with a one-time deprecation warning (#5223)
Erik Engervall8710c0125d47
diff --git a/apps/js-sdk/firecrawl/package.json b/apps/js-sdk/firecrawl/package.jsonindex ad8bae8dd..3e8ddccc7 100644--- a/apps/js-sdk/firecrawl/package.json+++ b/apps/js-sdk/firecrawl/package.json@@ -1,6 +1,6 @@{"name": "@mendable/firecrawl-js",- "version": "4.48.0",+ "version": "4.49.0","description": "JavaScript SDK for the Firecrawl API: web scraping, crawling, web search, and scientific literature search over a research paper index of PubMed, bioRxiv, medRxiv and arXiv abstracts","main": "dist/index.js","types": "dist/index.d.ts",diff --git a/apps/js-sdk/firecrawl/src/__tests__/unit/v2/v1-aliases.test.ts b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/v1-aliases.test.tsindex 3b52808a1..41b975a70 100644--- a/apps/js-sdk/firecrawl/src/__tests__/unit/v2/v1-aliases.test.ts+++ b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/v1-aliases.test.ts@@ -1,4 +1,5 @@-import { describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { AxiosAdapter } from "axios";import { FirecrawlClient } from "../../../v2/client";const ALIAS_MAP: Record<string, string> = {@@ -20,14 +21,98 @@ describe("V1 deprecated aliases", () => {apiUrl: "http://localhost:9",});+ afterEach(() => {+ vi.restoreAllMocks();+ });+for (const [alias, target] of Object.entries(ALIAS_MAP)) {- it(`${alias} delegates to ${target}`, async () => {+ it(`${alias} delegates to ${target} and adds success: true`, async () => {const spy = vi.spyOn(app, target as any).mockResolvedValue({ ok: true } as any);- await (app as any)[alias]("https://example.com");+ const result = await (app as any)[alias]("https://example.com");expect(spy).toHaveBeenCalled();- spy.mockRestore();+ expect(result).toEqual({ ok: true, success: true });});}++ it("scrapeUrl keeps the document fields beside success, as v1 did", async () => {+ vi.spyOn(app, "scrape").mockResolvedValue({ markdown: "# hi", metadata: { sourceURL: "https://example.com" } } as any);+ const result = await app.scrapeUrl("https://example.com", { formats: ["markdown"] });+ expect(app.scrape).toHaveBeenCalledWith("https://example.com", { formats: ["markdown"] });+ expect(result.success).toBe(true);+ expect(result.markdown).toBe("# hi");+ });++ it("crawlUrl and asyncCrawlUrl rename v1 crawl options to their v2 names", async () => {+ vi.spyOn(app, "crawl").mockResolvedValue({ status: "completed", data: [] } as any);+ vi.spyOn(app, "startCrawl").mockResolvedValue({ id: "job-1", url: "u" } as any);+ const v1Options = { limit: 2, maxDepth: 3, allowBackwardLinks: true, ignoreSitemap: true, scrapeOptions: { formats: ["markdown" as const] } };+ const expected = { limit: 2, maxDiscoveryDepth: 3, crawlEntireDomain: true, sitemap: "skip", scrapeOptions: { formats: ["markdown"] } };++ await app.crawlUrl("https://example.com", v1Options);+ await app.asyncCrawlUrl("https://example.com", v1Options);++ expect(app.crawl).toHaveBeenCalledWith("https://example.com", expected);+ expect(app.startCrawl).toHaveBeenCalledWith("https://example.com", expected);+ });++ it("v2 methods return results without success", async () => {+ const client = new FirecrawlClient({ apiKey: "fc-test", apiUrl: "http://localhost:9" });+ const adapter: AxiosAdapter = async config => ({+ data: { success: true, data: { markdown: "# hi" } },+ status: 200,+ statusText: "OK",+ headers: {},+ config,+ });+ (client as any).http.instance.defaults.adapter = adapter;+ const result = await client.scrape("https://example.com", { formats: ["markdown"] });+ expect(result).toEqual({ markdown: "# hi" });+ expect("success" in result).toBe(false);+ });+});++describe("V1 deprecation warning", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ async function freshClient() {+ vi.resetModules();+ const emitWarning = vi.spyOn(process, "emitWarning").mockImplementation(() => {});+ const { FirecrawlClient: FreshClient } = await import("../../../v2/client");+ const app = new FreshClient({ apiKey: "fc-test", apiUrl: "http://localhost:9" });+ const v1Warnings = () => emitWarning.mock.calls.filter(([, opts]) => (opts as any)?.code === "FIRECRAWL_V1_METHOD");+ return { app, v1Warnings };+ }++ it("is emitted once per process", async () => {+ const { app, v1Warnings } = await freshClient();+ vi.spyOn(app, "scrape").mockResolvedValue({ markdown: "# hi" } as any);+ vi.spyOn(app, "map").mockResolvedValue({ links: [] } as any);++ await app.scrapeUrl("https://example.com");+ await app.scrapeUrl("https://example.com");+ await app.mapUrl("https://example.com");++ expect(v1Warnings()).toHaveLength(1);+ expect((v1Warnings()[0]![1] as any).type).toBe("DeprecationWarning");+ });++ it("is not emitted by v2 methods", async () => {+ const { app, v1Warnings } = await freshClient();+ const adapter: AxiosAdapter = async config => ({+ data: { success: true, data: { markdown: "# hi" } },+ status: 200,+ statusText: "OK",+ headers: {},+ config,+ });+ (app as any).http.instance.defaults.adapter = adapter;++ await app.scrape("https://example.com", { formats: ["markdown"] });++ expect(v1Warnings()).toHaveLength(0);+ });});diff --git a/apps/js-sdk/firecrawl/src/v2/client.ts b/apps/js-sdk/firecrawl/src/v2/client.tsindex b9be6b349..9aba2bdc7 100644--- a/apps/js-sdk/firecrawl/src/v2/client.ts+++ b/apps/js-sdk/firecrawl/src/v2/client.ts@@ -104,6 +104,7 @@ import type {import { defaultOrigin } from "../utils/callerOrigin";import { getVersion } from "./utils/getVersion";import { Watcher } from "./watcher";+import { callV1, toV2CrawlOptions, type V1CrawlOptions, type V1Result } from "./utils/v1Compat";import type { WatcherOptions } from "./watcher";import * as zt from "zod";@@ -730,54 +731,54 @@ export class FirecrawlClient {return new Watcher(this.http, jobId, opts);}- /** @deprecated V1 compatibility alias for agent recovery. Prefer scrape(). */- async scrapeUrl(url: string, options?: ScrapeOptions): Promise<Document> {- return this.scrape(url, options);+ /** @deprecated v1 alias for scrape(); its result also carries v1's `success: true`. */+ async scrapeUrl(url: string, options?: ScrapeOptions): Promise<V1Result<Document>> {+ return callV1(() => this.scrape(url, options));}- /** @deprecated V1 compatibility alias for agent recovery. Prefer crawl(). */- async crawlUrl(url: string, req: CrawlOptions & { pollInterval?: number; timeout?: number; signal?: AbortSignal } = {}): Promise<CrawlJob> {- return this.crawl(url, req);+ /** @deprecated v1 alias for crawl(); its result also carries v1's `success: true`. */+ async crawlUrl(url: string, req: CrawlOptions & V1CrawlOptions & { pollInterval?: number; timeout?: number; signal?: AbortSignal } = {}): Promise<V1Result<CrawlJob>> {+ return callV1(() => this.crawl(url, toV2CrawlOptions(req)));}- /** @deprecated V1 compatibility alias for agent recovery. Prefer startCrawl(). */- async asyncCrawlUrl(url: string, req: CrawlOptions = {}): Promise<CrawlResponse> {- return this.startCrawl(url, req);+ /** @deprecated v1 alias for startCrawl(); its result also carries v1's `success: true`. */+ async asyncCrawlUrl(url: string, req: CrawlOptions & V1CrawlOptions = {}): Promise<V1Result<CrawlResponse>> {+ return callV1(() => this.startCrawl(url, toV2CrawlOptions(req)));}- /** @deprecated V1 compatibility alias for agent recovery. Prefer getCrawlStatus(). */- async checkCrawlStatus(jobId: string, pagination?: PaginationConfig): Promise<CrawlJob> {- return this.getCrawlStatus(jobId, pagination);+ /** @deprecated v1 alias for getCrawlStatus(); its result also carries v1's `success: true`. */+ async checkCrawlStatus(jobId: string, pagination?: PaginationConfig): Promise<V1Result<CrawlJob>> {+ return callV1(() => this.getCrawlStatus(jobId, pagination));}- /** @deprecated V1 compatibility alias for agent recovery. Prefer getCrawlErrors(). */- async checkCrawlErrors(crawlId: string): Promise<CrawlErrorsResponse> {- return this.getCrawlErrors(crawlId);+ /** @deprecated v1 alias for getCrawlErrors(); its result also carries v1's `success: true`. */+ async checkCrawlErrors(crawlId: string): Promise<V1Result<CrawlErrorsResponse>> {+ return callV1(() => this.getCrawlErrors(crawlId));}- /** @deprecated V1 compatibility alias for agent recovery. Prefer map(). */- async mapUrl(url: string, options?: MapOptions): Promise<MapData> {- return this.map(url, options);+ /** @deprecated v1 alias for map(); its result also carries v1's `success: true`. */+ async mapUrl(url: string, options?: MapOptions): Promise<V1Result<MapData>> {+ return callV1(() => this.map(url, options));}- /** @deprecated V1 compatibility alias for agent recovery. Prefer batchScrape(). */- async batchScrapeUrls(urls: string[], opts?: BatchScrapeOptions & { pollInterval?: number; timeout?: number }): Promise<BatchScrapeJob> {- return this.batchScrape(urls, opts);+ /** @deprecated v1 alias for batchScrape(); its result also carries v1's `success: true`. */+ async batchScrapeUrls(urls: string[], opts?: BatchScrapeOptions & { pollInterval?: number; timeout?: number }): Promise<V1Result<BatchScrapeJob>> {+ return callV1(() => this.batchScrape(urls, opts));}- /** @deprecated V1 compatibility alias for agent recovery. Prefer startBatchScrape(). */- async asyncBatchScrapeUrls(urls: string[], opts?: BatchScrapeOptions): Promise<BatchScrapeResponse> {- return this.startBatchScrape(urls, opts);+ /** @deprecated v1 alias for startBatchScrape(); its result also carries v1's `success: true`. */+ async asyncBatchScrapeUrls(urls: string[], opts?: BatchScrapeOptions): Promise<V1Result<BatchScrapeResponse>> {+ return callV1(() => this.startBatchScrape(urls, opts));}- /** @deprecated V1 compatibility alias for agent recovery. Prefer getBatchScrapeStatus(). */- async checkBatchScrapeStatus(jobId: string, pagination?: PaginationConfig): Promise<BatchScrapeJob> {- return this.getBatchScrapeStatus(jobId, pagination);+ /** @deprecated v1 alias for getBatchScrapeStatus(); its result also carries v1's `success: true`. */+ async checkBatchScrapeStatus(jobId: string, pagination?: PaginationConfig): Promise<V1Result<BatchScrapeJob>> {+ return callV1(() => this.getBatchScrapeStatus(jobId, pagination));}- /** @deprecated V1 compatibility alias for agent recovery. Prefer getBatchScrapeErrors(). */- async checkBatchScrapeErrors(jobId: string): Promise<CrawlErrorsResponse> {- return this.getBatchScrapeErrors(jobId);+ /** @deprecated v1 alias for getBatchScrapeErrors(); its result also carries v1's `success: true`. */+ async checkBatchScrapeErrors(jobId: string): Promise<V1Result<CrawlErrorsResponse>> {+ return callV1(() => this.getBatchScrapeErrors(jobId));}}diff --git a/apps/js-sdk/firecrawl/src/v2/utils/v1Compat.ts b/apps/js-sdk/firecrawl/src/v2/utils/v1Compat.tsnew file mode 100644index 000000000..5026a2533--- /dev/null+++ b/apps/js-sdk/firecrawl/src/v2/utils/v1Compat.ts@@ -0,0 +1,38 @@+let warned = false;++/** Emits the deprecation warning for v1-style method calls, once per process. */+export function warnV1Usage(): void {+ if (warned) return;+ warned = true;+ const message =+ "firecrawl: v1-style methods (scrapeUrl, crawlUrl, batchScrapeUrls, ...) are deprecated and mapped to the v2 API. " ++ "Use scrape(), crawl(), batchScrape() and the other v2 methods instead.";+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") {+ process.emitWarning(message, { type: "DeprecationWarning", code: "FIRECRAWL_V1_METHOD" });+ } else {+ console.warn(message);+ }+}++/** v1 crawl options that have a v2 equivalent. */+export type V1CrawlOptions = { maxDepth?: number; allowBackwardLinks?: boolean; ignoreSitemap?: boolean };++/** Renames v1 crawl options to their v2 names; v2 options given alongside win. */+export function toV2CrawlOptions<T extends object>(req: T & V1CrawlOptions): T {+ const { maxDepth, allowBackwardLinks, ignoreSitemap, ...rest } = req;+ return {+ ...(maxDepth != null && { maxDiscoveryDepth: maxDepth }),+ ...(allowBackwardLinks != null && { crawlEntireDomain: allowBackwardLinks }),+ ...(ignoreSitemap != null && { sitemap: ignoreSitemap ? "skip" : "include" }),+ ...rest,+ } as T;+}++/** A v2 result with the `success` flag v1 results carried. */+export type V1Result<T> = T & { success: true };++/** Warns once, then runs the v2 call and adds the v1 `success` flag to its result. */+export async function callV1<T extends object>(call: () => Promise<T>): Promise<V1Result<T>> {+ warnV1Usage();+ return { ...(await call()), success: true };+}diff --git a/apps/python-sdk/firecrawl/__init__.py b/apps/python-sdk/firecrawl/__init__.pyindex 205515139..059816501 100644--- a/apps/python-sdk/firecrawl/__init__.py+++ b/apps/python-sdk/firecrawl/__init__.py@@ -7,6 +7,7 @@ import loggingimport osfrom .client import Firecrawl, AsyncFirecrawl, FirecrawlApp, AsyncFirecrawlApp+from .v2.utils.v1_compat import ScrapeOptionsfrom .v2.watcher import Watcherfrom .v2.watcher_async import AsyncWatcherfrom .v2.types import (@@ -41,7 +42,7 @@ from .v1 import (V1ChangeTrackingOptions,)-__version__ = "4.52.1"+__version__ = "4.53.0"# Define the logger for the Firecrawl projectlogger: logging.Logger = logging.getLogger("firecrawl")@@ -101,6 +102,7 @@ __all__ = ['AsyncFirecrawl','FirecrawlApp','AsyncFirecrawlApp',+ 'ScrapeOptions','Watcher','AsyncWatcher','AuditMetadata',diff --git a/apps/python-sdk/firecrawl/__tests__/unit/v2/utils/test_v1_compat.py b/apps/python-sdk/firecrawl/__tests__/unit/v2/utils/test_v1_compat.pynew file mode 100644index 000000000..df59ce16d--- /dev/null+++ b/apps/python-sdk/firecrawl/__tests__/unit/v2/utils/test_v1_compat.py@@ -0,0 +1,170 @@+"""v1-style calls (params dicts, positional options, camelCase keys, dict reads) on the v2 client."""++import asyncio+import warnings+from unittest.mock import AsyncMock, patch++import pytest++from firecrawl import AsyncFirecrawl, Firecrawl, ScrapeOptions+from firecrawl.v2.methods import scrape as scrape_module+from firecrawl.v2.types import (+ BatchScrapeJob,+ BatchScrapeResponse,+ CrawlJob,+ Document,+ DocumentMetadata,+ ScrapeOptions as V2ScrapeOptions,+)+from firecrawl.v2.utils import v1_compat++[email protected](autouse=True)+def reset_warning():+ v1_compat._warned = False+ yield+ v1_compat._warned = False+++def client():+ return Firecrawl(api_key="fc-test", api_url="http://localhost:9")+++def _doc(markdown="# hi", url="https://example.com"):+ return Document(markdown=markdown, metadata=DocumentMetadata(url=url, source_url=url))+++def test_scrape_url_maps_params_dict(client):+ with patch.object(client._v2_client, "scrape", return_value=_doc()) as scrape:+ result = client.scrape_url("https://example.com", params={"formats": ["markdown", "html"], "onlyMainContent": True})+ scrape.assert_called_once_with("https://example.com", formats=["markdown", "html"], only_main_content=True)+ assert result["markdown"] == "# hi"+ assert result.markdown == "# hi"+ assert result["success"] is True and result.success is True+++def test_async_batch_scrape_urls_maps_positional_options(client):+ response = BatchScrapeResponse(id="job-1", url="https://api/x")+ with patch.object(client._v2_client, "start_batch_scrape", return_value=response) as start:+ job = client.async_batch_scrape_urls(["https://example.com"], {"formats": ["markdown", "links"], "onlyMainContent": True})+ start.assert_called_once_with(["https://example.com"], formats=["markdown", "links"], only_main_content=True)+ assert job["success"] is True+ assert job["id"] == "job-1"+ assert isinstance(job, BatchScrapeResponse)+ assert job.model_dump(exclude_none=True) == {"id": "job-1", "url": "https://api/x", "success": True}+++def test_crawl_url_renames_v1_options(client):+ job = CrawlJob(status="completed", completed=1, total=1, data=[_doc()])+ with patch.object(client._v2_client, "crawl", return_value=job) as crawl:+ result = client.crawl_url(+ "https://example.com",+ params={"limit": 1, "maxDepth": 2, "allowBackwardLinks": True, "scrapeOptions": {"formats": ["markdown"], "waitFor": 500}},+ )+ kwargs = crawl.call_args.kwargs+ assert kwargs["limit"] == 1+ assert kwargs["max_discovery_depth"] == 2+ assert kwargs["crawl_entire_domain"] is True+ assert isinstance(kwargs["scrape_options"], V2ScrapeOptions)+ assert kwargs["scrape_options"].wait_for == 500+ assert len(result["data"]) == 1+ assert result["data"][0]["markdown"] == "# hi"+ assert result["data"][0]["metadata"]["url"] == "https://example.com"+ assert result["creditsUsed"] == 0+++def test_crawl_url_accepts_2x_keyword_options(client):+ job = CrawlJob(status="completed", completed=0, total=0, data=[])+ with patch.object(client._v2_client, "crawl", return_value=job) as crawl:+ client.crawl_url(url="https://example.com", limit=2, max_depth=2, allow_backward_links=False, scrape_options=ScrapeOptions(formats=["markdown"]), poll_interval=5)+ kwargs = crawl.call_args.kwargs+ assert kwargs["max_discovery_depth"] == 2+ assert kwargs["crawl_entire_domain"] is False+ assert kwargs["poll_interval"] == 5+ assert "max_depth" not in kwargs and "allow_backward_links" not in kwargs+++def test_map_url_translates_sitemap_flags(client):+ with patch.object(client._v2_client, "map", return_value=None) as map_:+ client.map_url("https://example.com", params={"ignoreSitemap": True, "includeSubdomains": True})+ client.map_url("https://example.com", params={"sitemapOnly": True})+ client.map_url("https://example.com", params={"sitemapOnly": False, "limit": 5})+ assert map_.call_args_list[0].kwargs == {"sitemap": "skip", "include_subdomains": True}+ assert map_.call_args_list[1].kwargs == {"sitemap": "only"}+ assert map_.call_args_list[2].kwargs == {"limit": 5}+++def test_crawl_aliases_accept_and_drop_idempotency_key(client):+ job = CrawlJob(status="completed", completed=0, total=0, data=[])+ with patch.object(client._v2_client, "crawl", return_value=job) as crawl, patch.object(client._v2_client, "start_crawl", return_value=None) as start:+ client.crawl_url("https://example.com", params={"limit": 1}, idempotency_key="key-1")+ client.async_crawl_url("https://example.com", {"limit": 1}, idempotency_key="key-1")+ assert crawl.call_args.kwargs == {"limit": 1}+ assert start.call_args.kwargs == {"limit": 1}+++def test_status_alias_results_read_like_v1(client):+ status = BatchScrapeJob(status="completed", completed=1, total=1, data=[_doc()])+ with patch.object(client._v2_client, "get_batch_scrape_status", return_value=status):+ result = client.check_batch_scrape_status("job-1")+ assert result["status"] == "completed" and result["success"] is True+ assert {p["metadata"]["url"]: p["markdown"] for p in result["data"]} == {"https://example.com": "# hi"}+ assert result.get("missing", "fallback") == "fallback"+ with pytest.raises(KeyError):+ result["missing"]+++def test_scrape_options_accepts_camel_case():+ options = ScrapeOptions(formats=["html"], waitFor=1000, onlyMainContent=True, checkPromptInjection=True)+ assert isinstance(options, V2ScrapeOptions)+ assert options.wait_for == 1000+ assert options.only_main_content is True+ assert options.check_prompt_injection is True+++def test_scrape_options_snake_case_does_not_warn():+ with warnings.catch_warnings():+ warnings.simplefilter("error")+ options = ScrapeOptions(formats=["markdown"], only_main_content=True)+ assert options.only_main_content is True+++def test_warns_once_per_process(client):+ with patch.object(client._v2_client, "scrape", return_value=_doc()), patch.object(client._v2_client, "map", return_value=None):+ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ client.scrape_url("https://example.com", params={"formats": ["markdown"]})+ client.scrape_url("https://example.com")+ client.map_url("https://example.com")+ ScrapeOptions(waitFor=1)+ deprecations = [w for w in caught if issubclass(w.category, DeprecationWarning)]+ assert len(deprecations) == 1+ assert deprecations[0].filename == __file__+++def test_v2_methods_are_unchanged(client):+ with patch.object(scrape_module, "scrape", return_value=_doc()):+ with warnings.catch_warnings():+ warnings.simplefilter("error")+ doc = client.scrape("https://example.com", formats=["markdown"])+ assert type(doc) is Document+ assert "success" not in doc.model_dump()+ with pytest.raises(TypeError):+ doc["markdown"]+++def test_api_url_none_uses_default():+ assert Firecrawl(api_key="fc-test", api_url=None).api_url == "https://api.firecrawl.dev"+ assert AsyncFirecrawl(api_key="fc-test", api_url=None).api_url == "https://api.firecrawl.dev"+++def test_async_aliases_map_params():+ client = AsyncFirecrawl(api_key="fc-test", api_url="http://localhost:9")+ job = CrawlJob(status="completed", completed=1, total=1, data=[_doc()])+ with patch.object(client._v2_client, "crawl", new=AsyncMock(return_value=job)) as crawl:+ result = asyncio.run(client.crawl_url("https://example.com", params={"limit": 1, "scrapeOptions": {"formats": ["markdown"]}}))+ assert crawl.call_args.kwargs["url"] == "https://example.com"+ assert crawl.call_args.kwargs["limit"] == 1+ assert result["success"] is True+ assert result["data"][0]["markdown"] == "# hi"diff --git a/apps/python-sdk/firecrawl/client.py b/apps/python-sdk/firecrawl/client.pyindex e8e8f35c9..5833a85ba 100644--- a/apps/python-sdk/firecrawl/client.py+++ b/apps/python-sdk/firecrawl/client.py@@ -247,7 +247,7 @@ class Firecrawl:def __init__(self,api_key: str = None,- api_url: str = "https://api.firecrawl.dev",+ api_url: Optional[str] = "https://api.firecrawl.dev",timeout: float = None,max_retries: int = 3,backoff_factor: float = 0.5,@@ -257,7 +257,7 @@ class Firecrawl:Args:api_key: Firecrawl API key (or set ``FIRECRAWL_API_KEY``)- api_url: Base API URL (defaults to production)+ api_url: Base API URL (defaults to production, also when None)timeout: Default request timeout in seconds for all HTTP requestsmax_retries: Maximum number of retries for failed requests (default: 3)backoff_factor: Exponential backoff factor for retries (default: 0.5)@@ -267,6 +267,8 @@ class Firecrawl:creates the client; set FIRECRAWL_DISABLE_CALLER_ORIGIN=1 tokeep the plain default)"""+ if api_url is None:+ api_url = "https://api.firecrawl.dev"self.api_key = api_keyself.api_url = api_url@@ -406,12 +408,14 @@ class AsyncFirecrawl:def __init__(self,api_key: str = None,- api_url: str = "https://api.firecrawl.dev",+ api_url: Optional[str] = "https://api.firecrawl.dev",timeout: float = None,max_retries: int = 3,backoff_factor: float = 0.5,origin: str = None,):+ if api_url is None:+ api_url = "https://api.firecrawl.dev"self.api_key = api_keyself.api_url = api_urldiff --git a/apps/python-sdk/firecrawl/v2/client.py b/apps/python-sdk/firecrawl/v2/client.pyindex e7e3b2a76..95e9d981a 100644--- a/apps/python-sdk/firecrawl/v2/client.py+++ b/apps/python-sdk/firecrawl/v2/client.py@@ -64,6 +64,7 @@ from .types import ()from .utils.http_client import HttpClientfrom .utils.error_handler import FirecrawlError+from .utils.v1_compat import call_v1from .methods import scrape as scrape_modulefrom .methods import parse as parse_modulefrom .methods import crawl as crawl_module@@ -409,45 +410,45 @@ class FirecrawlClient:"""Deprecated alias for stop_interaction()."""return self.stop_interaction(job_id)- def scrape_url(self, url: str, **kwargs):- """V1 compatibility alias for agent recovery. Prefer scrape()."""- return self.scrape(url, **kwargs)+ def scrape_url(self, url: str, params: Optional[Dict[str, Any]] = None, **kwargs):+ """Deprecated v1 alias for scrape(); also takes v1 params and returns v1-readable results."""+ return call_v1(self.scrape, url, params=params, **kwargs)- def crawl_url(self, url: str, **kwargs):- """V1 compatibility alias for agent recovery. Prefer crawl()."""- return self.crawl(url, **kwargs)+ def crawl_url(self, url: str, params: Optional[Dict[str, Any]] = None, idempotency_key: Optional[str] = None, **kwargs):+ """Deprecated v1 alias for crawl(); also takes v1 params and returns v1-readable results. v2 crawls take no idempotency_key, so it is ignored."""+ return call_v1(self.crawl, url, params=params, **kwargs)- def map_url(self, url: str, **kwargs):- """V1 compatibility alias for agent recovery. Prefer map()."""- return self.map(url, **kwargs)+ def map_url(self, url: str, params: Optional[Dict[str, Any]] = None, **kwargs):+ """Deprecated v1 alias for map(); also takes v1 params and returns v1-readable results."""+ return call_v1(self.map, url, params=params, **kwargs)- def async_crawl_url(self, url: str, **kwargs):- """V1 compatibility alias for agent recovery. Prefer start_crawl()."""- return self.start_crawl(url, **kwargs)+ def async_crawl_url(self, url: str, params: Optional[Dict[str, Any]] = None, idempotency_key: Optional[str] = None, **kwargs):+ """Deprecated v1 alias for start_crawl(); also takes v1 params and returns v1-readable results. v2 crawls take no idempotency_key, so it is ignored."""+ return call_v1(self.start_crawl, url, params=params, **kwargs)def check_crawl_status(self, id: str, **kwargs):- """V1 compatibility alias for agent recovery. Prefer get_crawl_status()."""- return self.get_crawl_status(id, **kwargs)+ """Deprecated v1 alias for get_crawl_status(); returns v1-readable results."""+ return call_v1(self.get_crawl_status, id, **kwargs)def check_crawl_errors(self, id: str):- """V1 compatibility alias for agent recovery. Prefer get_crawl_errors()."""- return self.get_crawl_errors(id)+ """Deprecated v1 alias for get_crawl_errors(); returns v1-readable results."""+ return call_v1(self.get_crawl_errors, id)- def batch_scrape_urls(self, urls, **kwargs):- """V1 compatibility alias for agent recovery. Prefer batch_scrape()."""- return self.batch_scrape(urls, **kwargs)+ def batch_scrape_urls(self, urls, params: Optional[Dict[str, Any]] = None, **kwargs):+ """Deprecated v1 alias for batch_scrape(); also takes v1 params and returns v1-readable results."""+ return call_v1(self.batch_scrape, urls, params=params, **kwargs)- def async_batch_scrape_urls(self, urls, **kwargs):- """V1 compatibility alias for agent recovery. Prefer start_batch_scrape()."""- return self.start_batch_scrape(urls, **kwargs)+ def async_batch_scrape_urls(self, urls, params: Optional[Dict[str, Any]] = None, **kwargs):+ """Deprecated v1 alias for start_batch_scrape(); also takes v1 params and returns v1-readable results."""+ return call_v1(self.start_batch_scrape, urls, params=params, **kwargs)def check_batch_scrape_status(self, id: str, **kwargs):- """V1 compatibility alias for agent recovery. Prefer get_batch_scrape_status()."""- return self.get_batch_scrape_status(id, **kwargs)+ """Deprecated v1 alias for get_batch_scrape_status(); returns v1-readable results."""+ return call_v1(self.get_batch_scrape_status, id, **kwargs)def check_batch_scrape_errors(self, id: str):- """V1 compatibility alias for agent recovery. Prefer get_batch_scrape_errors()."""- return self.get_batch_scrape_errors(id)+ """Deprecated v1 alias for get_batch_scrape_errors(); returns v1-readable results."""+ return call_v1(self.get_batch_scrape_errors, id)def parse(self,diff --git a/apps/python-sdk/firecrawl/v2/client_async.py b/apps/python-sdk/firecrawl/v2/client_async.pyindex 31baa1986..96820a08e 100644--- a/apps/python-sdk/firecrawl/v2/client_async.py+++ b/apps/python-sdk/firecrawl/v2/client_async.py@@ -59,6 +59,7 @@ from .types import (from .utils.http_client import HttpClientfrom .utils.http_client_async import AsyncHttpClientfrom .utils.error_handler import CrawlJobTimeoutError+from .utils.v1_compat import acall_v1from .methods.aio import scrape as async_scrape # type: ignore[attr-defined]from .methods.aio import parse as async_parse # type: ignore[attr-defined]@@ -262,45 +263,45 @@ class AsyncFirecrawlClient:"""Deprecated alias for stop_interaction()."""return await self.stop_interaction(job_id)- async def scrape_url(self, url: str, **kwargs):- """V1 compatibility alias for agent recovery. Prefer scrape()."""- return await self.scrape(url, **kwargs)+ async def scrape_url(self, url: str, params: Optional[Dict[str, Any]] = None, **kwargs):+ """Deprecated v1 alias for scrape(); also takes v1 params and returns v1-readable results."""+ return await acall_v1(self.scrape, url, params=params, **kwargs)- async def crawl_url(self, url: str, **kwargs):- """V1 compatibility alias for agent recovery. Prefer crawl()."""- return await self.crawl(url=url, **kwargs)+ async def crawl_url(self, url: str, params: Optional[Dict[str, Any]] = None, idempotency_key: Optional[str] = None, **kwargs):+ """Deprecated v1 alias for crawl(); also takes v1 params and returns v1-readable results. v2 crawls take no idempotency_key, so it is ignored."""+ return await acall_v1(self.crawl, url=url, params=params, **kwargs)- async def map_url(self, url: str, **kwargs):- """V1 compatibility alias for agent recovery. Prefer map()."""- return await self.map(url, **kwargs)+ async def map_url(self, url: str, params: Optional[Dict[str, Any]] = None, **kwargs):+ """Deprecated v1 alias for map(); also takes v1 params and returns v1-readable results."""+ return await acall_v1(self.map, url, params=params, **kwargs)- async def async_crawl_url(self, url: str, **kwargs):- """V1 compatibility alias for agent recovery. Prefer start_crawl()."""- return await self.start_crawl(url, **kwargs)+ async def async_crawl_url(self, url: str, params: Optional[Dict[str, Any]] = None, idempotency_key: Optional[str] = None, **kwargs):+ """Deprecated v1 alias for start_crawl(); also takes v1 params and returns v1-readable results. v2 crawls take no idempotency_key, so it is ignored."""+ return await acall_v1(self.start_crawl, url, params=params, **kwargs)async def check_crawl_status(self, id: str, **kwargs):- """V1 compatibility alias for agent recovery. Prefer get_crawl_status()."""- return await self.get_crawl_status(id, **kwargs)+ """Deprecated v1 alias for get_crawl_status(); returns v1-readable results."""+ return await acall_v1(self.get_crawl_status, id, **kwargs)async def check_crawl_errors(self, id: str):- """V1 compatibility alias for agent recovery. Prefer get_crawl_errors()."""- return await self.get_crawl_errors(id)+ """Deprecated v1 alias for get_crawl_errors(); returns v1-readable results."""+ return await acall_v1(self.get_crawl_errors, id)- async def batch_scrape_urls(self, urls, **kwargs):- """V1 compatibility alias for agent recovery. Prefer batch_scrape()."""- return await self.batch_scrape(urls, **kwargs)+ async def batch_scrape_urls(self, urls, params: Optional[Dict[str, Any]] = None, **kwargs):+ """Deprecated v1 alias for batch_scrape(); also takes v1 params and returns v1-readable results."""+ return await acall_v1(self.batch_scrape, urls, params=params, **kwargs)- async def async_batch_scrape_urls(self, urls, **kwargs):- """V1 compatibility alias for agent recovery. Prefer start_batch_scrape()."""- return await self.start_batch_scrape(urls, **kwargs)+ async def async_batch_scrape_urls(self, urls, params: Optional[Dict[str, Any]] = None, **kwargs):+ """Deprecated v1 alias for start_batch_scrape(); also takes v1 params and returns v1-readable results."""+ return await acall_v1(self.start_batch_scrape, urls, params=params, **kwargs)async def check_batch_scrape_status(self, id: str, **kwargs):- """V1 compatibility alias for agent recovery. Prefer get_batch_scrape_status()."""- return await self.get_batch_scrape_status(id, **kwargs)+ """Deprecated v1 alias for get_batch_scrape_status(); returns v1-readable results."""+ return await acall_v1(self.get_batch_scrape_status, id, **kwargs)async def check_batch_scrape_errors(self, id: str):- """V1 compatibility alias for agent recovery. Prefer get_batch_scrape_errors()."""- return await self.get_batch_scrape_errors(id)+ """Deprecated v1 alias for get_batch_scrape_errors(); returns v1-readable results."""+ return await acall_v1(self.get_batch_scrape_errors, id)async def parse(self,diff --git a/apps/python-sdk/firecrawl/v2/utils/v1_compat.py b/apps/python-sdk/firecrawl/v2/utils/v1_compat.pynew file mode 100644index 000000000..7ef5c7412--- /dev/null+++ b/apps/python-sdk/firecrawl/v2/utils/v1_compat.py@@ -0,0 +1,124 @@+"""Maps v1-style SDK calls (v1 method names, ``params`` dicts, camelCase options) onto the v2 client."""++import re+import warnings+from functools import lru_cache+from typing import Any, Callable, Dict, Optional++from pydantic import BaseModel, computed_field, model_validator++from .. import types as v2_types+from ..types import ScrapeOptions as V2ScrapeOptions++_RENAMED_OPTIONS = {+ "max_depth": "max_discovery_depth",+ "allow_backward_links": "crawl_entire_domain",+}++_warned = False+++def warn_v1_usage() -> None:+ """Emit the v1-style call deprecation warning, once per process."""+ global _warned+ if _warned:+ return+ _warned = True+ warnings.warn(+ "firecrawl: v1-style calls (scrape_url, crawl_url, batch_scrape_urls, params=..., "+ "camelCase options) are deprecated and mapped to the v2 API. Use scrape(), crawl(), "+ "batch_scrape() and the other v2 methods with keyword arguments instead.",+ DeprecationWarning,+ stacklevel=4,+ )+++def _snake_case(key: str) -> str:+ return re.sub(r"(?<=[a-z0-9])([A-Z])", r"_\1", key).lower()+++class ScrapeOptions(V2ScrapeOptions):+ """v2 ScrapeOptions that also accepts the camelCase field names firecrawl-py 2.x used."""++ @model_validator(mode="before")+ @classmethod+ def _accept_camel_case(cls, data: Any) -> Any:+ if not isinstance(data, dict):+ return data+ known = set(cls.model_fields) | {f.alias for f in cls.model_fields.values() if f.alias}+ legacy = [key for key in data if key not in known and _snake_case(key) in cls.model_fields]+ if not legacy:+ return data+ warn_v1_usage()+ return {(_snake_case(key) if key in legacy else key): value for key, value in data.items()}+++ScrapeOptions.model_rebuild(_types_namespace=vars(v2_types))+++def to_v2_kwargs(params: Optional[Dict[str, Any]], kwargs: Dict[str, Any]) -> Dict[str, Any]:+ """Merge a v1 ``params`` dict into keyword arguments and rename v1 keys to their v2 names."""+ converted: Dict[str, Any] = {}+ for key, value in {**(params or {}), **kwargs}.items():+ name = _snake_case(key)+ name = _RENAMED_OPTIONS.get(name, name)+ if name == "ignore_sitemap":+ name, value = "sitemap", "skip" if value else "include"+ if name == "sitemap_only":+ if not value:+ continue+ name, value = "sitemap", "only"+ if name == "scrape_options" and isinstance(value, dict):+ value = ScrapeOptions(**value)+ converted[name] = value+ return converted+++def _success(self: Any) -> bool:+ return True+++class _V1Result:+ """Dict-style reads and a ``success`` field, as v1 results had."""++ def __getitem__(self, key: str) -> Any:+ name = _snake_case(key)+ cls = type(self)+ if name not in cls.model_fields and name not in cls.model_computed_fields and name not in (self.model_extra or {}):+ raise KeyError(key)+ return as_v1_result(getattr(self, name))++ def get(self, key: str, default: Any = None) -> Any:+ try:+ return self[key]+ except KeyError:+ return default+++@lru_cache(maxsize=None)+def _v1_result_class(cls: type) -> type:+ namespace: Dict[str, Any] = {"__module__": cls.__module__, "__qualname__": cls.__qualname__}+ if "success" not in cls.model_fields:+ namespace["success"] = computed_field(property(_success))+ return type(cls.__name__, (_V1Result, cls), namespace)+++def as_v1_result(value: Any) -> Any:+ """Return a v2 result that also reads like a v1 result; other values pass through."""+ if isinstance(value, list):+ return [as_v1_result(item) for item in value]+ if not isinstance(value, BaseModel) or isinstance(value, _V1Result):+ return value+ return _v1_result_class(type(value)).model_construct(_fields_set=value.model_fields_set, **dict(value))+++def call_v1(method: Callable[..., Any], *args: Any, params: Optional[Dict[str, Any]] = None, **kwargs: Any) -> Any:+ """Run a v2 method for a v1-style call."""+ warn_v1_usage()+ return as_v1_result(method(*args, **to_v2_kwargs(params, kwargs)))+++async def acall_v1(method: Callable[..., Any], *args: Any, params: Optional[Dict[str, Any]] = None, **kwargs: Any) -> Any:+ """Await a v2 async method for a v1-style call."""+ warn_v1_usage()+ return as_v1_result(await method(*args, **to_v2_kwargs(params, kwargs)))