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(api): run browser and interact sessions from a chosen country (#5029)
Gergő Móricz8d6275001633
diff --git a/.github/workflows/test-server.yml b/.github/workflows/test-server.ymlindex c89a157ba..f143e9816 100644--- a/.github/workflows/test-server.yml+++ b/.github/workflows/test-server.yml@@ -254,6 +254,11 @@ jobs:run: pnpm exec vitest run src/controllers/v2/__tests__/browser-delete.test.ts --reporter=defaultworking-directory: apps/api+ - name: Run browser options regression tests+ if: matrix.engine == 'fetch' && matrix.proxy == 'no-proxy' && matrix.nuq == 'postgres'+ run: pnpm exec vitest run src/lib/browser-options.test.ts --reporter=default+ working-directory: apps/api+- name: Run search safe filter regression testsif: matrix.engine == 'fetch' && matrix.proxy == 'no-proxy' && matrix.nuq == 'postgres'run: >-diff --git a/apps/api/src/__tests__/snips/v2/browser-location.test.ts b/apps/api/src/__tests__/snips/v2/browser-location.test.tsnew file mode 100644index 000000000..f77a66566--- /dev/null+++ b/apps/api/src/__tests__/snips/v2/browser-location.test.ts@@ -0,0 +1,37 @@+import { config } from "../../../config";+import { itIf } from "../lib";+import { browserCreateRaw, idmux, Identity } from "./lib";++describe("POST /v2/interact location", () => {+ let identity: Identity;++ beforeAll(async () => {+ identity = await idmux({ name: "browser-location", credits: 100 });+ });++ it.each(["zz", "us-generic", "us-whitelist"])(+ "rejects %s as a country",+ async country => {+ const res = await browserCreateRaw({ location: { country } }, identity);+ expect(res.statusCode).toBe(400);+ expect(res.body.success).toBe(false);+ },+ );++ it("rejects languages, which a browser session cannot apply", async () => {+ const res = await browserCreateRaw(+ { location: { country: "DE", languages: ["de-DE"] } },+ identity,+ );+ expect(res.statusCode).toBe(400);+ });++ // Without Hangar a valid request stops at the 503 after validation.+ itIf(!config.HANGAR_URL)("accepts an ISO country", async () => {+ const res = await browserCreateRaw(+ { location: { country: "GB" } },+ identity,+ );+ expect(res.statusCode).toBe(503);+ });+});diff --git a/apps/api/src/__tests__/snips/v2/lib.ts b/apps/api/src/__tests__/snips/v2/lib.tsindex a9ed8a6fc..e03081ae9 100644--- a/apps/api/src/__tests__/snips/v2/lib.ts+++ b/apps/api/src/__tests__/snips/v2/lib.ts@@ -351,6 +351,7 @@ export async function browserCreateRaw(recordSession?: boolean;streamWebView?: boolean;profile?: { name: string; saveChanges?: boolean };+ location?: Record<string, unknown>;},identity: Identity,) {diff --git a/apps/api/src/controllers/v2/browser.ts b/apps/api/src/controllers/v2/browser.tsindex 51f762892..04ce0b630 100644--- a/apps/api/src/controllers/v2/browser.ts+++ b/apps/api/src/controllers/v2/browser.ts@@ -13,6 +13,7 @@ import { z } from "zod";import { config } from "../../config";import { RequestWithAuth } from "./types";import { integrationSchema } from "../../utils/integration";+import { countries } from "../../lib/validate-country";import { isAgentInteropSecretValid } from "../../lib/agent-interop";import {getBrowserSession,@@ -51,6 +52,17 @@ export const browserCreateRequestSchema = z.object({saveChanges: z.boolean().default(true),}).optional(),+ location: z+ .strictObject({+ country: z+ .string()+ .refine(+ value => Object.keys(countries).includes(value.toUpperCase()),+ "Invalid country code. Use a valid ISO 3166-1 alpha-2 country code.",+ )+ .transform(value => value.toLowerCase()),+ })+ .optional(),__agentInterop: z.object({auth: z.string(),diff --git a/apps/api/src/lib/browser-lifecycle.ts b/apps/api/src/lib/browser-lifecycle.tsindex 2b4cd1673..9ed1bf4be 100644--- a/apps/api/src/lib/browser-lifecycle.ts+++ b/apps/api/src/lib/browser-lifecycle.ts@@ -1,5 +1,6 @@import { z } from "zod";import { recordRequestCredits } from "./request-credits-store";+import type { BrowserOptions } from "./browser-options";import { upsertBrowserProfile } from "./browser-sessions";import { v7 as uuidv7 } from "uuid";import { config } from "../config";@@ -118,14 +119,12 @@ export function invalidAgentInteropError(export async function createBrowserSession(req: RequestWithAuth<any, any, any>,- options: {+ options: BrowserOptions & {ttl: number;activityTtl: number;streamWebView: boolean;recordSession: boolean;zeroDataRetention?: boolean;- blockAds: boolean;- profile?: { name: string; saveChanges: boolean };scrapeId?: string;shouldBill?: boolean;requestId?: string;diff --git a/apps/api/src/lib/browser-options.test.ts b/apps/api/src/lib/browser-options.test.tsindex f5848aa1d..512be6732 100644--- a/apps/api/src/lib/browser-options.test.ts+++ b/apps/api/src/lib/browser-options.test.ts@@ -1,4 +1,33 @@-import { hangarBrowserOptions } from "./browser-options";+import { vi } from "vitest";++vi.mock("../config", () => ({ config: { HANGAR_URL: "http://hangar.test" } }));++import {+ type BrowserOptions,+ browserOptionsFromScrape,+ hangarBrowserOptions,+ isBrowserOptions,+} from "./browser-options";+import { createHangarBrowser } from "./hangar";++async function hangarCreateBody(options: BrowserOptions) {+ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) =>+ Response.json({+ id: "br_1",+ status: "running",+ cdp_url: "wss://hangar.test/cdp",+ }),+ );+ vi.stubGlobal("fetch", fetchMock);+ await createHangarBrowser("key", "team", {+ ...options,+ ttl: 600,+ activityTtl: 300,+ streamWebView: true,+ recordSession: false,+ });+ return JSON.parse(fetchMock.mock.calls[0][1].body as string);+}describe("hangarBrowserOptions", () => {it("maps blockAds to Hangar's uBlock extension", () => {@@ -10,3 +39,91 @@ describe("hangarBrowserOptions", () => {});});});++describe("Hangar create body", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ const fromScrape = (+ options: Parameters<typeof browserOptionsFromScrape>[0],+ ) => hangarCreateBody(browserOptionsFromScrape(options));++ it("selects a proxy in the scrape's location country", async () => {+ const body = await fromScrape({+ location: { country: "gb" },+ proxy: "auto",+ });+ expect(body.proxy).toEqual({ country: "gb", type: "basic" });+ });++ it("lowercases the scrape's country", async () => {+ const body = await fromScrape({ location: { country: "GB" } });+ expect(body.proxy).toEqual({ country: "gb", type: "basic" });+ });++ it("sends no proxy for a scrape without a location", async () => {+ const body = await fromScrape({ proxy: "auto" });+ expect(body).not.toHaveProperty("proxy");+ });++ it.each(["us-generic", "us-whitelist"])(+ "sends no proxy for a scrape located in %s",+ async country => {+ const body = await fromScrape({ location: { country } });+ expect(body).not.toHaveProperty("proxy");+ },+ );++ it.each(["stealth", "enhanced"] as const)(+ "uses the mobile pool for a %s scrape",+ async proxy => {+ expect(+ (await fromScrape({ location: { country: "de" }, proxy })).proxy,+ ).toEqual({ country: "de", type: "mobile" });+ expect((await fromScrape({ proxy })).proxy).toEqual({ type: "mobile" });+ },+ );++ it("selects a basic proxy in a /v2/browser session's country", async () => {+ const body = await hangarCreateBody({+ blockAds: true,+ location: { country: "jp" },+ });+ expect(body.proxy).toEqual({ country: "jp", type: "basic" });+ });++ it("sends no proxy for a /v2/browser session without a location", async () => {+ const body = await hangarCreateBody({ blockAds: true });+ expect(body).not.toHaveProperty("proxy");+ });+});++describe("isBrowserOptions", () => {+ it("accepts options persisted before location and proxy were stored", () => {+ expect(isBrowserOptions({ blockAds: true })).toBe(true);+ expect(+ isBrowserOptions({+ blockAds: false,+ profile: { name: "default", saveChanges: true },+ }),+ ).toBe(true);+ });++ it("accepts options built from a located scrape", () => {+ expect(+ isBrowserOptions(+ browserOptionsFromScrape({+ location: { country: "gb" },+ proxy: "stealth",+ }),+ ),+ ).toBe(true);+ });++ it("rejects malformed location or proxy", () => {+ expect(isBrowserOptions({ blockAds: true, location: "gb" })).toBe(false);+ expect(isBrowserOptions({ blockAds: true, location: {} })).toBe(false);+ expect(isBrowserOptions({ blockAds: true, proxy: "auto" })).toBe(false);+ });+});diff --git a/apps/api/src/lib/browser-options.ts b/apps/api/src/lib/browser-options.tsindex b0f43d6ab..4d0f2cd1c 100644--- a/apps/api/src/lib/browser-options.ts+++ b/apps/api/src/lib/browser-options.ts@@ -6,28 +6,48 @@export type BrowserOptions = {blockAds: boolean;profile?: { name: string; saveChanges: boolean };+ /** `country` is a lowercase ISO 3166-1 alpha-2 code. */+ location?: { country: string };+ proxy?: "basic" | "stealth";};export function browserOptionsFromScrape(options: {blockAds?: boolean;profile?: { name: string; saveChanges: boolean };+ location?: { country: string };+ proxy?: "basic" | "stealth" | "enhanced" | "auto";}): BrowserOptions {+ const country = options.location?.country.toLowerCase();return {blockAds: options.blockAds ?? true,...(options.profile ? { profile: options.profile } : {}),+ // us-generic and us-whitelist are not countries; they keep the default US egress.+ ...(country && /^[a-z]{2}$/.test(country) ? { location: { country } } : {}),+ proxy:+ options.proxy === "stealth" || options.proxy === "enhanced"+ ? "stealth"+ : "basic",};}export function isBrowserOptions(value: unknown): value is BrowserOptions {if (!value || typeof value !== "object") return false;- const { blockAds, profile } = value as Record<string, unknown>;+ const { blockAds, profile, location, proxy } = value as Record<+ string,+ unknown+ >;return (typeof blockAds === "boolean" &&(profile === undefined ||(typeof profile === "object" &&profile !== null &&typeof (profile as any).name === "string" &&- typeof (profile as any).saveChanges === "boolean"))+ typeof (profile as any).saveChanges === "boolean")) &&+ (location === undefined ||+ (typeof location === "object" &&+ location !== null &&+ typeof (location as any).country === "string")) &&+ (proxy === undefined || proxy === "basic" || proxy === "stealth"));}@@ -44,5 +64,15 @@ export function hangarBrowserOptions(options: BrowserOptions) {},}: {}),+ // Scrape's stealth proxy is Hangar's mobile pool. Omitted fields keep+ // Hangar's defaults: country "us", type "basic".+ ...(options.location || options.proxy === "stealth"+ ? {+ proxy: {+ ...(options.location ? { country: options.location.country } : {}),+ type: options.proxy === "stealth" ? "mobile" : "basic",+ },+ }+ : {}),};}diff --git a/apps/elixir-sdk/lib/firecrawl.ex b/apps/elixir-sdk/lib/firecrawl.exindex 18c7d3c18..aa73270d3 100644--- a/apps/elixir-sdk/lib/firecrawl.ex+++ b/apps/elixir-sdk/lib/firecrawl.ex@@ -928,12 +928,13 @@ defmodule Firecrawl do@create_browser_session_schema NimbleOptions.new!([activity_ttl: [type: :integer, doc: "Time in seconds before the session is destroyed due to inactivity"],block_ads: [type: :boolean, doc: "Enable ad and cookie popup blocking, as in scrape. Sessions started from a scrape with interact use the scrape's blockAds."],+ location: [type: :keyword_list, keys: [country: [type: :string, required: true]], doc: "Country the session browses from (default US). Sessions started from a scrape with interact use the scrape's location."],profile: [type: :keyword_list, doc: "Enable persistent storage across interact sessions. Data saved in one session can be loaded in a later session using the same name."],stream_web_view: [type: :boolean, doc: "Whether to stream a live view of the browser"],ttl: [type: :integer, doc: "Total time-to-live in seconds for the interact session"]])- @create_browser_session_key_mapping %{activity_ttl: "activityTtl", block_ads: "blockAds", profile: "profile", stream_web_view: "streamWebView", ttl: "ttl"}+ @create_browser_session_key_mapping %{activity_ttl: "activityTtl", block_ads: "blockAds", location: {"location", %{country: "country"}}, profile: "profile", stream_web_view: "streamWebView", ttl: "ttl"}@doc """Create an interact sessiondiff --git a/apps/elixir-sdk/openapi.json b/apps/elixir-sdk/openapi.jsonindex 59efd2484..db3ddac15 100644--- a/apps/elixir-sdk/openapi.json+++ b/apps/elixir-sdk/openapi.json@@ -5129,6 +5129,20 @@"required": ["name"]+ },+ "location": {+ "type": "object",+ "description": "Country the session browses from (default US). Sessions started from a scrape with interact use the scrape's location.",+ "properties": {+ "country": {+ "type": "string",+ "description": "ISO 3166-1 alpha-2 country code, such as GB."+ }+ },+ "required": [+ "country"+ ],+ "additionalProperties": false}}}diff --git a/apps/elixir-sdk/test/firecrawl_test.exs b/apps/elixir-sdk/test/firecrawl_test.exsindex 66b2e174a..59440f7a8 100644--- a/apps/elixir-sdk/test/firecrawl_test.exs+++ b/apps/elixir-sdk/test/firecrawl_test.exs@@ -835,6 +835,43 @@ defmodule FirecrawlTest doend)end+ test "create_browser_session sends location only when set" do+ parent = self()++ adapter = fn request ->+ send(parent, {:request, request})++ resp = Req.Response.new(+ status: 200,+ headers: %{"content-type" => ["application/json"]},+ body: Jason.encode!(%{"success" => true, "id" => "session-1"})+ )++ {request, resp}+ end++ sent_body = fn params ->+ assert {:ok, %Req.Response{status: 200}} =+ Firecrawl.create_browser_session(params, api_key: "test-key", adapter: adapter)++ assert_receive {:request, request}++ cond do+ is_binary(request.body) -> Jason.decode!(request.body)+ is_map(request.body) -> request.body+ true -> request.options[:json]+ end+ end++ assert sent_body.(location: [country: "GB"])["location"] == %{"country" => "GB"}+ refute Map.has_key?(sent_body.(ttl: 60), "location")+ end++ test "create_browser_session rejects a location without a country" do+ assert {:error, %NimbleOptions.ValidationError{}} =+ Firecrawl.create_browser_session([location: []], api_key: "test-key")+ end+test "audit_metadata rejects unsupported fields" doassert_raise NimbleOptions.ValidationError, fn ->Firecrawl.scrape_and_extract_from_url!(diff --git a/apps/go-sdk/browser_test.go b/apps/go-sdk/browser_test.gonew file mode 100644index 000000000..729dd9936--- /dev/null+++ b/apps/go-sdk/browser_test.go@@ -0,0 +1,73 @@+package firecrawl++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "reflect"+ "testing"++ "github.com/firecrawl/firecrawl/apps/go-sdk/option"+)++func browserTestClient(t *testing.T, captured chan<- capturedRequest) *Client {+ t.Helper()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ captured <- captureRequest(r)+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"success":true,"id":"session-1"}`))+ }))+ t.Cleanup(server.Close)++ client, err := NewClient(+ option.WithAPIKey("fc-test"),+ option.WithAPIURL(server.URL),+ )+ if err != nil {+ t.Fatalf("NewClient: %v", err)+ }+ return client+}++func TestBrowserSendsLocation(t *testing.T) {+ captured := make(chan capturedRequest, 1)+ client := browserTestClient(t, captured)++ if _, err := client.Browser(context.Background(), &BrowserOptions{+ Location: &BrowserLocation{Country: "GB"},+ }); err != nil {+ t.Fatalf("Browser: %v", err)+ }++ req := <-captured+ if req.path != "/v2/browser" {+ t.Fatalf("path = %q, want /v2/browser", req.path)+ }+ var body map[string]any+ if err := json.Unmarshal([]byte(req.body), &body); err != nil {+ t.Fatalf("decode body: %v", err)+ }+ want := map[string]any{"location": map[string]any{"country": "GB"}}+ if !reflect.DeepEqual(body, want) {+ t.Fatalf("body = %v, want %v", body, want)+ }+}++func TestBrowserOmitsLocationWhenUnset(t *testing.T) {+ captured := make(chan capturedRequest, 1)+ client := browserTestClient(t, captured)++ if _, err := client.Browser(context.Background(), &BrowserOptions{TTL: Int(60)}); err != nil {+ t.Fatalf("Browser: %v", err)+ }++ var body map[string]any+ if err := json.Unmarshal([]byte((<-captured).body), &body); err != nil {+ t.Fatalf("decode body: %v", err)+ }+ if _, ok := body["location"]; ok {+ t.Fatalf("body has location: %v", body)+ }+}diff --git a/apps/go-sdk/firecrawl.go b/apps/go-sdk/firecrawl.goindex 8c9e50044..edbe92a09 100644--- a/apps/go-sdk/firecrawl.go+++ b/apps/go-sdk/firecrawl.go@@ -905,6 +905,9 @@ func (c *Client) Browser(ctx context.Context, opts *BrowserOptions) (*BrowserCreif opts.StreamWebView != nil {body["streamWebView"] = *opts.StreamWebView}+ if opts.Location != nil {+ body["location"] = opts.Location+ }}raw, err := c.http.post(ctx, "/v2/browser", body, nil)@@ -1142,6 +1145,14 @@ type BrowserOptions struct {TTL *intActivityTTL *intStreamWebView *bool+ // Location sets the country the session browses from (default US).+ Location *BrowserLocation+}++// BrowserLocation selects a browser session's country.+type BrowserLocation struct {+ // Country is an ISO 3166-1 alpha-2 code, such as "GB".+ Country string `json:"country"`}// BrowserExecuteParams holds optional parameters for browser code execution.diff --git a/apps/java-sdk/src/main/java/com/firecrawl/client/FirecrawlClient.java b/apps/java-sdk/src/main/java/com/firecrawl/client/FirecrawlClient.javaindex c6646097d..487e9f2c8 100644--- a/apps/java-sdk/src/main/java/com/firecrawl/client/FirecrawlClient.java+++ b/apps/java-sdk/src/main/java/com/firecrawl/client/FirecrawlClient.java@@ -821,10 +821,26 @@ public class FirecrawlClient {* @return the browser session details*/public BrowserCreateResponse browser(Integer ttl, Integer activityTtl, Boolean streamWebView) {+ return browser(ttl, activityTtl, streamWebView, null);+ }++ /**+ * Creates a new browser session that browses from a given country.+ *+ * @param ttl total session lifetime in seconds (30-3600), or null for default+ * @param activityTtl idle timeout in seconds (10-3600), or null for default+ * @param streamWebView whether to enable live view streaming, or null for default+ * @param country ISO 3166-1 alpha-2 country code such as "GB", sent as+ * {@code location.country}, or null for default (US)+ * @return the browser session details+ */+ public BrowserCreateResponse browser(Integer ttl, Integer activityTtl, Boolean streamWebView,+ String country) {Map<String, Object> body = new LinkedHashMap<>();if (ttl != null) body.put("ttl", ttl);if (activityTtl != null) body.put("activityTtl", activityTtl);if (streamWebView != null) body.put("streamWebView", streamWebView);+ if (country != null) body.put("location", Map.of("country", country));return http.post("/v2/browser", body, BrowserCreateResponse.class);}@@ -1195,7 +1211,22 @@ public class FirecrawlClient {*/public CompletableFuture<BrowserCreateResponse> browserAsync(Integer ttl, Integer activityTtl,Boolean streamWebView) {- return CompletableFuture.supplyAsync(() -> browser(ttl, activityTtl, streamWebView), asyncExecutor);+ return browserAsync(ttl, activityTtl, streamWebView, null);+ }++ /**+ * Asynchronously creates a new browser session that browses from a given country.+ *+ * @param ttl total session lifetime in seconds, or null for default+ * @param activityTtl idle timeout in seconds, or null for default+ * @param streamWebView whether to enable live view streaming, or null for default+ * @param country ISO 3166-1 alpha-2 country code, or null for default (US)+ * @return a CompletableFuture that resolves to the BrowserCreateResponse+ */+ public CompletableFuture<BrowserCreateResponse> browserAsync(Integer ttl, Integer activityTtl,+ Boolean streamWebView, String country) {+ return CompletableFuture.supplyAsync(() -> browser(ttl, activityTtl, streamWebView, country),+ asyncExecutor);}/**diff --git a/apps/java-sdk/src/test/java/com/firecrawl/BrowserLocationMockTest.java b/apps/java-sdk/src/test/java/com/firecrawl/BrowserLocationMockTest.javanew file mode 100644index 000000000..42cfa5b2e--- /dev/null+++ b/apps/java-sdk/src/test/java/com/firecrawl/BrowserLocationMockTest.java@@ -0,0 +1,72 @@+package com.firecrawl;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.firecrawl.client.FirecrawlClient;+import com.sun.net.httpserver.HttpServer;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.io.IOException;+import java.io.OutputStream;+import java.net.InetSocketAddress;+import java.nio.charset.StandardCharsets;+import java.util.concurrent.atomic.AtomicReference;++import static org.junit.jupiter.api.Assertions.*;++/**+ * POST /v2/browser location tests against a local mock HTTP server.+ */+class BrowserLocationMockTest {++ private HttpServer server;+ private FirecrawlClient client;+ private final AtomicReference<String> lastPath = new AtomicReference<>();+ private final AtomicReference<String> lastBody = new AtomicReference<>();++ @BeforeEach+ void setup() throws IOException {+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);+ server.createContext("/", exchange -> {+ lastPath.set(exchange.getRequestURI().getPath());+ lastBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));+ byte[] bytes = "{\"success\":true,\"id\":\"session-1\"}".getBytes(StandardCharsets.UTF_8);+ exchange.getResponseHeaders().set("Content-Type", "application/json");+ exchange.sendResponseHeaders(200, bytes.length);+ try (OutputStream os = exchange.getResponseBody()) {+ os.write(bytes);+ }+ });+ server.start();+ client = FirecrawlClient.builder()+ .apiKey("fc-test-key")+ .apiUrl("http://127.0.0.1:" + server.getAddress().getPort())+ .maxRetries(0)+ .build();+ }++ @AfterEach+ void teardown() {+ server.stop(0);+ }++ @Test+ void testBrowserSendsLocation() throws IOException {+ client.browser(null, null, null, "GB");++ assertEquals("/v2/browser", lastPath.get());+ JsonNode body = new ObjectMapper().readTree(lastBody.get());+ assertEquals("GB", body.path("location").path("country").asText());+ }++ @Test+ void testBrowserOmitsLocationWhenUnset() throws IOException {+ client.browser(60, null, null);++ JsonNode body = new ObjectMapper().readTree(lastBody.get());+ assertEquals(60, body.path("ttl").asInt());+ assertFalse(body.has("location"));+ }+}diff --git a/apps/js-sdk/firecrawl/src/__tests__/unit/v2/browser.unit.test.ts b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/browser.unit.test.tsnew file mode 100644index 000000000..8e7f7d208--- /dev/null+++ b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/browser.unit.test.ts@@ -0,0 +1,28 @@+import { describe, test, expect, vi } from "vitest";+import { browser } from "../../../v2/methods/browser";++describe("JS SDK v2 browser", () => {+ test("sends location when creating a session", async () => {+ const post = vi.fn(async () => ({+ status: 200,+ data: { success: true, id: "session-1" },+ }));++ await browser({ post } as any, { location: { country: "GB" } });++ expect(post).toHaveBeenCalledWith("/v2/browser", {+ location: { country: "GB" },+ });+ });++ test("omits location by default", async () => {+ const post = vi.fn(async () => ({+ status: 200,+ data: { success: true, id: "session-1" },+ }));++ await browser({ post } as any);++ expect(post).toHaveBeenCalledWith("/v2/browser", {});+ });+});diff --git a/apps/js-sdk/firecrawl/src/v2/client.ts b/apps/js-sdk/firecrawl/src/v2/client.tsindex 694fe04e0..41d3f1da9 100644--- a/apps/js-sdk/firecrawl/src/v2/client.ts+++ b/apps/js-sdk/firecrawl/src/v2/client.ts@@ -644,7 +644,7 @@ export class FirecrawlClient {// Browser/*** Create a new browser session.- * @param args Session options (ttl, activityTtl, streamWebView, blockAds, profile).+ * @param args Session options (ttl, activityTtl, streamWebView, blockAds, profile, location).* @returns Session id, CDP URL, live view URL, and expiration time.*/async browser(diff --git a/apps/js-sdk/firecrawl/src/v2/methods/browser.ts b/apps/js-sdk/firecrawl/src/v2/methods/browser.tsindex fa24a8e90..678ff9bb6 100644--- a/apps/js-sdk/firecrawl/src/v2/methods/browser.ts+++ b/apps/js-sdk/firecrawl/src/v2/methods/browser.ts@@ -22,6 +22,8 @@ export async function browser(name: string;saveChanges?: boolean;};+ /** Country the session browses from, as an ISO 3166-1 alpha-2 code (default US). */+ location?: { country: string };integration?: string;origin?: string;} = {},@@ -32,6 +34,7 @@ export async function browser(if (args.streamWebView != null) body.streamWebView = args.streamWebView;if (args.blockAds != null) body.blockAds = args.blockAds;if (args.profile != null) body.profile = args.profile;+ if (args.location != null) body.location = args.location;if (args.integration != null) body.integration = args.integration;if (args.origin) body.origin = args.origin;diff --git a/apps/php-sdk/src/Client/FirecrawlClient.php b/apps/php-sdk/src/Client/FirecrawlClient.phpindex 833501897..9ec9dec7a 100644--- a/apps/php-sdk/src/Client/FirecrawlClient.php+++ b/apps/php-sdk/src/Client/FirecrawlClient.php@@ -706,12 +706,14 @@ final class FirecrawlClient* Create a new browser session.** @param array<string, string>|null $profile+ * @param array{country: string}|null $location Country the session browses from, e.g. ['country' => 'GB'] (default US)*/public function browser(?int $ttl = null,?int $activityTtl = null,?bool $streamWebView = null,?array $profile = null,+ ?array $location = null,): BrowserCreateResponse {$body = [];if ($ttl !== null) {@@ -726,6 +728,9 @@ final class FirecrawlClientif ($profile !== null) {$body['profile'] = $profile;}+ if ($location !== null) {+ $body['location'] = $location;+ }return BrowserCreateResponse::fromArray($this->http->post('/v2/browser', $body));}diff --git a/apps/php-sdk/src/Laravel/Facades/Firecrawl.php b/apps/php-sdk/src/Laravel/Facades/Firecrawl.phpindex 49f77d549..a409fd079 100644--- a/apps/php-sdk/src/Laravel/Facades/Firecrawl.php+++ b/apps/php-sdk/src/Laravel/Facades/Firecrawl.php@@ -41,7 +41,7 @@ use Illuminate\Support\Facades\Facade;* @method static AgentStatusResponse agent(AgentOptions $options, int $pollIntervalSec = 2, int $timeoutSec = 300)* @method static array<string, mixed> cancelAgent(string $jobId)* @method static AgentListResponse listAgents(?int $before = null)- * @method static BrowserCreateResponse browser(?int $ttl = null, ?int $activityTtl = null, ?bool $streamWebView = null)+ * @method static BrowserCreateResponse browser(?int $ttl = null, ?int $activityTtl = null, ?bool $streamWebView = null, array<string, string>|null $profile = null, array{country: string}|null $location = null)* @method static BrowserExecuteResponse browserExecute(string $sessionId, string $code, string $language = 'bash', ?int $timeout = null)* @method static BrowserDeleteResponse deleteBrowser(string $sessionId)* @method static BrowserListResponse listBrowsers(?string $status = null)diff --git a/apps/php-sdk/tests/Unit/BrowserTest.php b/apps/php-sdk/tests/Unit/BrowserTest.phpnew file mode 100644index 000000000..6abbdff02--- /dev/null+++ b/apps/php-sdk/tests/Unit/BrowserTest.php@@ -0,0 +1,29 @@+<?php++declare(strict_types=1);++use GuzzleHttp\Psr7\Response;++it('sends the browser location option in the request body', function (): void {+ $history = new ArrayObject();+ $client = fakeFirecrawlClient([+ new Response(200, [], json_encode(['success' => true, 'id' => 'session-1'])),+ ], $history);++ $client->browser(location: ['country' => 'GB']);++ $request = $history[0]['request'];+ expect($request->getUri()->getPath())->toBe('/v2/browser');+ expect(json_decode((string) $request->getBody(), true))->toBe(['location' => ['country' => 'GB']]);+});++it('omits the browser location option when it is unset', function (): void {+ $history = new ArrayObject();+ $client = fakeFirecrawlClient([+ new Response(200, [], json_encode(['success' => true, 'id' => 'session-1'])),+ ], $history);++ $client->browser(ttl: 60);++ expect(json_decode((string) $history[0]['request']->getBody(), true))->toBe(['ttl' => 60]);+});diff --git a/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_browser_request_preparation.py b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_browser_request_preparation.pynew file mode 100644index 000000000..66a54a7f5--- /dev/null+++ b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_browser_request_preparation.py@@ -0,0 +1,44 @@+import pytest+from firecrawl.v2.methods.browser import browser+from firecrawl.v2.methods.aio import browser as async_browser+++class _FakeResponse:+ ok = True+ status_code = 200++ def json(self):+ return {"success": True, "id": "session-1"}+++class _FakeClient:+ def __init__(self):+ self.last_post = None++ def post(self, endpoint, payload):+ self.last_post = (endpoint, payload)+ return _FakeResponse()+++class _FakeAsyncClient(_FakeClient):+ async def post(self, endpoint, payload):+ return super().post(endpoint, payload)+++def test_browser_sends_location():+ client = _FakeClient()+ browser(client, location={"country": "GB"})+ assert client.last_post == ("/v2/browser", {"location": {"country": "GB"}})+++def test_browser_omits_location_by_default():+ client = _FakeClient()+ browser(client)+ assert client.last_post == ("/v2/browser", {})+++async def test_async_browser_sends_location():+ client = _FakeAsyncClient()+ await async_browser.browser(client, location={"country": "GB"})+ assert client.last_post == ("/v2/browser", {"location": {"country": "GB"}})diff --git a/apps/python-sdk/firecrawl/v2/client.py b/apps/python-sdk/firecrawl/v2/client.pyindex 8af7917dc..3bc02800a 100644--- a/apps/python-sdk/firecrawl/v2/client.py+++ b/apps/python-sdk/firecrawl/v2/client.py@@ -1757,6 +1757,7 @@ class FirecrawlClient:stream_web_view: Optional[bool] = None,block_ads: Optional[bool] = None,profile: Optional[Dict[str, Any]] = None,+ location: Optional[Dict[str, str]] = None,):"""Create a new browser session.@@ -1767,6 +1768,8 @@ class FirecrawlClient:block_ads: Block ads, trackers and cookie notices (default ``True``)profile: Profile config with ``name`` (str) andoptional ``save_changes`` (bool, default ``True``)+ location: ``{"country": "GB"}`` to browse from that country+ (ISO 3166-1 alpha-2, default US)Returns:BrowserCreateResponse with session id and CDP URL@@ -1778,6 +1781,7 @@ class FirecrawlClient:stream_web_view=stream_web_view,block_ads=block_ads,profile=profile,+ location=location,)def browser_execute(diff --git a/apps/python-sdk/firecrawl/v2/client_async.py b/apps/python-sdk/firecrawl/v2/client_async.pyindex 7547c2480..31baa1986 100644--- a/apps/python-sdk/firecrawl/v2/client_async.py+++ b/apps/python-sdk/firecrawl/v2/client_async.py@@ -1018,6 +1018,7 @@ class AsyncFirecrawlClient:stream_web_view: Optional[bool] = None,block_ads: Optional[bool] = None,profile: Optional[Dict[str, Any]] = None,+ location: Optional[Dict[str, str]] = None,):"""Create a new browser session.@@ -1028,6 +1029,8 @@ class AsyncFirecrawlClient:block_ads: Block ads, trackers and cookie notices (default ``True``)profile: Profile config with ``name`` (str) andoptional ``save_changes`` (bool, default ``True``)+ location: ``{"country": "GB"}`` to browse from that country+ (ISO 3166-1 alpha-2, default US)Returns:BrowserCreateResponse with session id and CDP URL@@ -1039,6 +1042,7 @@ class AsyncFirecrawlClient:stream_web_view=stream_web_view,block_ads=block_ads,profile=profile,+ location=location,)async def browser_execute(diff --git a/apps/python-sdk/firecrawl/v2/methods/aio/browser.py b/apps/python-sdk/firecrawl/v2/methods/aio/browser.pyindex 6883e264f..48181e025 100644--- a/apps/python-sdk/firecrawl/v2/methods/aio/browser.py+++ b/apps/python-sdk/firecrawl/v2/methods/aio/browser.py@@ -59,6 +59,7 @@ async def browser(stream_web_view: Optional[bool] = None,block_ads: Optional[bool] = None,profile: Optional[Dict[str, Any]] = None,+ location: Optional[Dict[str, str]] = None,) -> BrowserCreateResponse:"""Create a new browser session.@@ -70,6 +71,8 @@ async def browser(block_ads: Block ads, trackers and cookie notices (default ``True``)profile: Profile config with ``name`` (str) andoptional ``save_changes`` (bool, default ``True``)+ location: ``{"country": "GB"}`` to browse from that country+ (ISO 3166-1 alpha-2, default US)Returns:BrowserCreateResponse with session id and CDP URL@@ -88,6 +91,8 @@ async def browser("name": profile["name"],"saveChanges": profile.get("save_changes", True),}+ if location is not None:+ body["location"] = {"country": location["country"]}resp = await client.post("/v2/browser", body)payload = _normalize_browser_create_response(resp.json())diff --git a/apps/python-sdk/firecrawl/v2/methods/browser.py b/apps/python-sdk/firecrawl/v2/methods/browser.pyindex 78a79dbfe..fa90e3a87 100644--- a/apps/python-sdk/firecrawl/v2/methods/browser.py+++ b/apps/python-sdk/firecrawl/v2/methods/browser.py@@ -60,6 +60,7 @@ def browser(stream_web_view: Optional[bool] = None,block_ads: Optional[bool] = None,profile: Optional[Dict[str, Any]] = None,+ location: Optional[Dict[str, str]] = None,) -> BrowserCreateResponse:"""Create a new browser session.@@ -71,6 +72,8 @@ def browser(block_ads: Block ads, trackers and cookie notices (default ``True``)profile: Profile config with ``name`` (str) andoptional ``save_changes`` (bool, default ``True``)+ location: ``{"country": "GB"}`` to browse from that country+ (ISO 3166-1 alpha-2, default US)Returns:BrowserCreateResponse with session id and CDP URL@@ -89,6 +92,8 @@ def browser("name": profile["name"],"saveChanges": profile.get("save_changes", True),}+ if location is not None:+ body["location"] = {"country": location["country"]}resp = client.post("/v2/browser", body)if not resp.ok: