stagehand 4.5.0a0.dev1707__tar.gz → 4.5.0a0.dev1708__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/PKG-INFO +1 -1
  2. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/pyproject.toml +1 -1
  3. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_extension/service-worker.js +87 -376
  4. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_generated/protocol_version.py +1 -1
  5. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/README.md +0 -0
  6. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/__init__.py +0 -0
  7. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_extension/blank.html +0 -0
  8. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_extension/content-script.js +0 -0
  9. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_extension/manifest.json +0 -0
  10. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_extension/offscreen/service-worker-heartbeat.html +0 -0
  11. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_extension/offscreen/service-worker-heartbeat.js +0 -0
  12. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_extension/wake-service-worker.html +0 -0
  13. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_extension/wake-service-worker.js +0 -0
  14. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_generated/__init__.py +0 -0
  15. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_generated/input_types.py +0 -0
  16. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_generated/models.py +0 -0
  17. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_sdk_identity.py +0 -0
  18. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/_validation.py +0 -0
  19. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/browser.py +0 -0
  20. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/browser_clipboard.py +0 -0
  21. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/browser_context.py +0 -0
  22. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/browserbase_connection.py +0 -0
  23. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/browserbase_rpc.py +0 -0
  24. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/browserbase_services.py +0 -0
  25. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/browserbase_session.py +0 -0
  26. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/browserbase_transport.py +0 -0
  27. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/cdp_client.py +0 -0
  28. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/client_models.py +0 -0
  29. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/client_types.py +0 -0
  30. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/extension_assets.py +0 -0
  31. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/file_upload.py +0 -0
  32. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/locator.py +0 -0
  33. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/page.py +0 -0
  34. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/py.typed +0 -0
  35. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/response.py +0 -0
  36. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/rpc_client.py +0 -0
  37. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/stagehand.py +0 -0
  38. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/timeouts.py +0 -0
  39. {stagehand-4.5.0a0.dev1707 → stagehand-4.5.0a0.dev1708}/src/stagehand/webmcp.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stagehand
3
- Version: 4.5.0a0.dev1707
3
+ Version: 4.5.0a0.dev1708
4
4
  Summary: Browserbase's SDK for building browser agents
5
5
  Keywords: ai,agent,ai-agent,browser,browser-agent,browser-automation,computer-use,headless,playwright,cdp,llm,automation,web-scraping,testing
6
6
  Author: Browserbase
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "stagehand"
3
- version = "4.5.0a0.dev1707"
3
+ version = "4.5.0a0.dev1708"
4
4
  description = "Browserbase's SDK for building browser agents"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -9206,7 +9206,7 @@ function isRecord$2(value) {
9206
9206
  }
9207
9207
  var package_default$1 = {
9208
9208
  name: "@browserbasehq/stagehand-protocol",
9209
- version: "3.2.0-alpha-82827a219512f0399cb159720a63f7d271d21480",
9209
+ version: "3.2.0-alpha-cdf5ddce87a10fa240c0c220095d4a95f4526295",
9210
9210
  "private": true,
9211
9211
  type: "module",
9212
9212
  exports: {
@@ -13541,7 +13541,7 @@ function createContextController(runtime) {
13541
13541
  };
13542
13542
  }
13543
13543
  //#endregion
13544
- //#region ../sdk-ts/src/browserClipboard.ts
13544
+ //#region ../shared/browser-api/src/browserClipboard.ts
13545
13545
  var BrowserClipboard = class {
13546
13546
  constructor(rpcClient) {
13547
13547
  this.rpcClient = rpcClient;
@@ -13575,7 +13575,45 @@ function clipboardTarget(options) {
13575
13575
  return options?.page ? { pageId: options.page.pageId } : {};
13576
13576
  }
13577
13577
  //#endregion
13578
- //#region ../sdk-ts/src/base64.ts
13578
+ //#region ../shared/browser-api/src/platform.ts
13579
+ /** Browser implementation and default for command clients without filesystem access. */
13580
+ var browserPlatform = {
13581
+ async readInputFile() {
13582
+ throw new TypeError("setInputFiles(): file paths are only supported in Node.js; use a file payload instead");
13583
+ },
13584
+ async readTextFile(_path, caller) {
13585
+ throw new TypeError(`${caller}: path is only supported in Node.js; use content or a function instead`);
13586
+ },
13587
+ async writeCaptureFile(_path, _bytes, method) {
13588
+ throw new TypeError(`page.${method}(): path is only supported in Node.js; omit path to receive ${method === "pdf" ? "PDF" : "screenshot"} bytes`);
13589
+ },
13590
+ emitWarning(message, code) {
13591
+ console.warn(`[${code}] ${message}`);
13592
+ },
13593
+ encodeBase64,
13594
+ utf8ByteLengthExceeds: utf8ByteLengthExceeds$1
13595
+ };
13596
+ function utf8ByteLengthExceeds$1(value, limit) {
13597
+ let byteLength = 0;
13598
+ for (let index = 0; index < value.length; index++) {
13599
+ const codeUnit = value.charCodeAt(index);
13600
+ if (codeUnit <= 127) byteLength += 1;
13601
+ else if (codeUnit <= 2047) byteLength += 2;
13602
+ else if (codeUnit >= 55296 && codeUnit <= 56319 && index + 1 < value.length && value.charCodeAt(index + 1) >= 56320 && value.charCodeAt(index + 1) <= 57343) {
13603
+ byteLength += 4;
13604
+ index += 1;
13605
+ } else byteLength += 3;
13606
+ if (byteLength > limit) return true;
13607
+ }
13608
+ return false;
13609
+ }
13610
+ function encodeBase64(bytes) {
13611
+ let binary = "";
13612
+ for (const byte of bytes) binary += String.fromCharCode(byte);
13613
+ return btoa(binary);
13614
+ }
13615
+ //#endregion
13616
+ //#region ../shared/browser-api/src/base64.ts
13579
13617
  var BASE64_PATTERN = /^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/;
13580
13618
  function decodeBase64(value, source) {
13581
13619
  if (value.length % 4 !== 0 || !BASE64_PATTERN.test(value)) throw new Error(`${source} returned invalid base64`);
@@ -13590,172 +13628,33 @@ function decodeBase64(value, source) {
13590
13628
  for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
13591
13629
  return bytes;
13592
13630
  }
13593
- //#endregion
13594
- //#region \0vite/preload-helper.js
13595
- var scriptRel = /* @__PURE__ */ (function detectScriptRel() {
13596
- const relList = typeof document !== "undefined" && document.createElement("link").relList;
13597
- return relList && relList.supports && relList.supports("modulepreload") ? "modulepreload" : "preload";
13598
- })();
13599
- var assetsURL = function(dep) {
13600
- return "/" + dep;
13601
- };
13602
- var seen = {};
13603
- var __vitePreload = function preload(baseModule, deps, importerUrl) {
13604
- let promise = Promise.resolve();
13605
- if (deps && deps.length > 0) {
13606
- const links = document.getElementsByTagName("link");
13607
- const cspNonceMeta = document.querySelector("meta[property=csp-nonce]");
13608
- const cspNonce = cspNonceMeta?.nonce || cspNonceMeta?.getAttribute("nonce");
13609
- function allSettled(promises) {
13610
- return Promise.all(promises.map((p) => Promise.resolve(p).then((value) => ({
13611
- status: "fulfilled",
13612
- value
13613
- }), (reason) => ({
13614
- status: "rejected",
13615
- reason
13616
- }))));
13617
- }
13618
- function importMetaResolve(specifier) {
13619
- if (import.meta.resolve) return import.meta.resolve(specifier);
13620
- return new URL(
13621
- specifier,
13622
- /** #__KEEP__ */
13623
- import.meta.url
13624
- ).href;
13625
- }
13626
- promise = allSettled(deps.map((dep) => {
13627
- dep = assetsURL(dep, importerUrl);
13628
- dep = importMetaResolve(dep);
13629
- if (dep in seen) return;
13630
- seen[dep] = true;
13631
- const isCss = dep.endsWith(".css");
13632
- for (let i = links.length - 1; i >= 0; i--) {
13633
- const link = links[i];
13634
- if (link.href === dep && (!isCss || link.rel === "stylesheet")) return;
13635
- }
13636
- const link = document.createElement("link");
13637
- link.rel = isCss ? "stylesheet" : scriptRel;
13638
- if (!isCss) link.as = "script";
13639
- link.crossOrigin = "";
13640
- link.href = dep;
13641
- if (cspNonce) link.setAttribute("nonce", cspNonce);
13642
- document.head.appendChild(link);
13643
- if (isCss) return new Promise((res, rej) => {
13644
- link.addEventListener("load", res);
13645
- link.addEventListener("error", () => rej(/* @__PURE__ */ new Error(`Unable to preload CSS for ${dep}`)));
13646
- });
13647
- }));
13648
- }
13649
- function handlePreloadError(err) {
13650
- const e = new Event("vite:preloadError", { cancelable: true });
13651
- e.payload = err;
13652
- window.dispatchEvent(e);
13653
- if (!e.defaultPrevented) throw err;
13654
- }
13655
- return promise.then((res) => {
13656
- for (const item of res || []) {
13657
- if (item.status !== "rejected") continue;
13658
- handlePreloadError(item.reason);
13659
- }
13660
- return baseModule().catch(handlePreloadError);
13661
- });
13662
- };
13663
- //#endregion
13664
- //#region ../sdk-ts/src/fileUpload.ts
13665
- var MAX_INPUT_FILE_BYTES = 50 * 1024 * 1024;
13666
- async function normalizeFileInput(files) {
13631
+ async function normalizeFileInput(files, platform = browserPlatform) {
13667
13632
  const entries = Array.isArray(files) ? files : [files];
13668
13633
  const payloads = [];
13669
- for (const entry of entries) payloads.push(await normalizeFile(entry));
13634
+ for (const entry of entries) payloads.push(await normalizeFile(entry, platform));
13670
13635
  return payloads;
13671
13636
  }
13672
- async function normalizeFile(file) {
13673
- if (typeof file === "string") {
13674
- const fsModuleName = "node:fs/promises";
13675
- const pathModuleName = "node:path";
13676
- const [fs, path] = await Promise.all([__vitePreload(() => import(
13677
- /* @vite-ignore */
13678
- fsModuleName
13679
- ), []), __vitePreload(() => import(
13680
- /* @vite-ignore */
13681
- pathModuleName
13682
- ), [])]).catch(() => {
13683
- throw new TypeError("setInputFiles(): file paths are only supported in Node.js; use a file payload instead");
13684
- });
13685
- const absolutePath = path.resolve(file);
13686
- const handle = await fs.open(absolutePath, "r").catch(() => {
13687
- throw new TypeError("setInputFiles(): could not read file");
13688
- });
13689
- try {
13690
- const fileStat = await handle.stat().catch(() => {
13691
- throw new TypeError("setInputFiles(): could not read file");
13692
- });
13693
- if (!fileStat.isFile()) throw new TypeError("setInputFiles(): expected a file");
13694
- if (fileStat.size > MAX_INPUT_FILE_BYTES) throw new RangeError(`setInputFiles(): file is larger than the 50 MiB upload limit`);
13695
- const chunks = [];
13696
- let bytesRead = 0;
13697
- try {
13698
- for await (const chunk of handle.createReadStream({
13699
- autoClose: false,
13700
- end: MAX_INPUT_FILE_BYTES,
13701
- start: 0
13702
- })) {
13703
- const bytes = Buffer.from(chunk);
13704
- chunks.push(bytes);
13705
- bytesRead += bytes.byteLength;
13706
- }
13707
- } catch {
13708
- throw new TypeError("setInputFiles(): could not read file");
13709
- }
13710
- if (bytesRead > MAX_INPUT_FILE_BYTES) throw new RangeError(`setInputFiles(): file is larger than the 50 MiB upload limit`);
13711
- const lastModified = Math.trunc(fileStat.mtimeMs);
13712
- return {
13713
- name: path.basename(absolutePath),
13714
- data: Buffer.concat(chunks, bytesRead).toString("base64"),
13715
- ...lastModified < 0 ? {} : { lastModified }
13716
- };
13717
- } finally {
13718
- await handle.close().catch(() => {});
13719
- }
13720
- }
13637
+ async function normalizeFile(file, platform) {
13638
+ if (typeof file === "string") return platform.readInputFile(file);
13721
13639
  if (!file.name) throw new TypeError("setInputFiles(): file payload name cannot be empty");
13640
+ let bytes;
13722
13641
  if (typeof file.buffer === "string") {
13723
- const nodeBuffer = globalThis.Buffer;
13724
- if (nodeBuffer ? nodeBuffer.byteLength(file.buffer, "utf8") > MAX_INPUT_FILE_BYTES : utf8ByteLengthExceeds$1(file.buffer, MAX_INPUT_FILE_BYTES)) throw new RangeError(`setInputFiles(): file is larger than the 50 MiB upload limit`);
13725
- }
13726
- const bytes = typeof file.buffer === "string" ? new TextEncoder().encode(file.buffer) : file.buffer instanceof ArrayBuffer ? new Uint8Array(file.buffer) : file.buffer;
13727
- if (bytes.byteLength > MAX_INPUT_FILE_BYTES) throw new RangeError(`setInputFiles(): file is larger than the 50 MiB upload limit`);
13642
+ if (platform.utf8ByteLengthExceeds(file.buffer, 52428800)) throw new RangeError(`setInputFiles(): file is larger than the 50 MiB upload limit`);
13643
+ bytes = new TextEncoder().encode(file.buffer);
13644
+ } else if (ArrayBuffer.isView(file.buffer) && Object.prototype.toString.call(file.buffer) === "[object Uint8Array]") bytes = file.buffer;
13645
+ else if (Object.prototype.toString.call(file.buffer) === "[object ArrayBuffer]") bytes = new Uint8Array(file.buffer);
13646
+ else throw new TypeError("setInputFiles(): buffer must be a string, Uint8Array, or ArrayBuffer");
13647
+ if (bytes.byteLength > 52428800) throw new RangeError(`setInputFiles(): file is larger than the 50 MiB upload limit`);
13728
13648
  if (file.lastModified !== void 0 && (!Number.isInteger(file.lastModified) || file.lastModified < 0)) throw new RangeError("setInputFiles(): lastModified must be a non-negative integer");
13729
13649
  return {
13730
13650
  name: file.name,
13731
13651
  ...file.mimeType ? { mimeType: file.mimeType } : {},
13732
- data: encodeBase64(bytes),
13652
+ data: platform.encodeBase64(bytes),
13733
13653
  ...file.lastModified === void 0 ? {} : { lastModified: file.lastModified }
13734
13654
  };
13735
13655
  }
13736
- function utf8ByteLengthExceeds$1(value, limit) {
13737
- let byteLength = 0;
13738
- for (let index = 0; index < value.length; index++) {
13739
- const codeUnit = value.charCodeAt(index);
13740
- if (codeUnit <= 127) byteLength += 1;
13741
- else if (codeUnit <= 2047) byteLength += 2;
13742
- else if (codeUnit >= 55296 && codeUnit <= 56319 && index + 1 < value.length && value.charCodeAt(index + 1) >= 56320 && value.charCodeAt(index + 1) <= 57343) {
13743
- byteLength += 4;
13744
- index += 1;
13745
- } else byteLength += 3;
13746
- if (byteLength > limit) return true;
13747
- }
13748
- return false;
13749
- }
13750
- function encodeBase64(bytes) {
13751
- const nodeBuffer = globalThis.Buffer;
13752
- if (nodeBuffer) return nodeBuffer.from(bytes).toString("base64");
13753
- let binary = "";
13754
- for (const byte of bytes) binary += String.fromCharCode(byte);
13755
- return btoa(binary);
13756
- }
13757
13656
  //#endregion
13758
- //#region ../sdk-ts/src/locator.ts
13657
+ //#region ../shared/browser-api/src/locator.ts
13759
13658
  var Locator$1 = class Locator$1 {
13760
13659
  constructor(rpcClient, descriptor) {
13761
13660
  this.rpcClient = rpcClient;
@@ -13864,7 +13763,7 @@ var Locator$1 = class Locator$1 {
13864
13763
  async setInputFiles(files, options) {
13865
13764
  await this.rpcClient.send(StagehandMethods.locatorSetInputFiles, {
13866
13765
  ...this.descriptor,
13867
- files: await normalizeFileInput(files),
13766
+ files: await normalizeFileInput(files, this.rpcClient.platform),
13868
13767
  ...options ? { options } : {}
13869
13768
  });
13870
13769
  }
@@ -13881,7 +13780,7 @@ var Locator$1 = class Locator$1 {
13881
13780
  }
13882
13781
  };
13883
13782
  //#endregion
13884
- //#region ../sdk-ts/src/pageScripts.ts
13783
+ //#region ../shared/browser-api/src/pageScripts.ts
13885
13784
  function normalizeEvaluationExpression(expression, arg, caller = "page.evaluate") {
13886
13785
  if (typeof expression === "string") return expression;
13887
13786
  return `(${expression.toString()})(${serializeArgument(arg, caller)})`;
@@ -13895,7 +13794,7 @@ function parsedArgument(arg, caller) {
13895
13794
  if (arg === void 0) return "undefined";
13896
13795
  return `JSON.parse(${JSON.stringify(serializeArgument(arg, caller))})`;
13897
13796
  }
13898
- async function normalizeInitScriptSource$1(script, arg, caller = "page.addInitScript") {
13797
+ async function normalizeInitScriptSource$1(script, arg, caller = "page.addInitScript", platform = browserPlatform) {
13899
13798
  if (typeof script === "function") return `(${script.toString()})(${serializeArgument(arg, caller)})`;
13900
13799
  if (arg !== void 0) throw new TypeError(`${caller}: 'arg' is only supported when passing a function.`);
13901
13800
  if (typeof script === "string") return script;
@@ -13904,15 +13803,7 @@ async function normalizeInitScriptSource$1(script, arg, caller = "page.addInitSc
13904
13803
  if (hasContent === (typeof script.path === "string" && script.path.trim().length > 0)) throw new TypeError(`${caller}: provide an object with exactly one of path or content.`);
13905
13804
  if (hasContent) return script.content;
13906
13805
  const filePath = script.path;
13907
- const moduleName = "node:fs/promises";
13908
- const { readFile } = await __vitePreload(async () => {
13909
- const { readFile } = await import(
13910
- /* @vite-ignore */
13911
- moduleName
13912
- );
13913
- return { readFile };
13914
- }, []);
13915
- return `${await readFile(filePath, "utf8")}\n//# sourceURL=${filePath.replace(/\n/g, "")}`;
13806
+ return `${await platform.readTextFile(filePath, caller)}\n//# sourceURL=${filePath.replace(/\n/g, "")}`;
13916
13807
  }
13917
13808
  function serializeArgument(arg, caller) {
13918
13809
  if (arg === void 0) return "undefined";
@@ -13922,7 +13813,7 @@ function serializeArgument(arg, caller) {
13922
13813
  return serialized;
13923
13814
  }
13924
13815
  //#endregion
13925
- //#region ../sdk-ts/src/response.ts
13816
+ //#region ../shared/browser-api/src/response.ts
13926
13817
  var Response$2 = class {
13927
13818
  #rpcClient;
13928
13819
  #descriptor;
@@ -13988,7 +13879,7 @@ var Response$2 = class {
13988
13879
  }
13989
13880
  };
13990
13881
  //#endregion
13991
- //#region ../sdk-ts/src/webmcp.ts
13882
+ //#region ../shared/browser-api/src/webmcp.ts
13992
13883
  var WebMCPTool = class {
13993
13884
  #rpcClient;
13994
13885
  #pageId;
@@ -14042,7 +13933,7 @@ var WebMCPInvocation = class {
14042
13933
  }
14043
13934
  };
14044
13935
  //#endregion
14045
- //#region ../sdk-ts/src/page.ts
13936
+ //#region ../shared/browser-api/src/page.ts
14046
13937
  var CDPSubscription = class {
14047
13938
  constructor(rpcClient, subscriptionId, removeLocalListener, onDisposed) {
14048
13939
  this.rpcClient = rpcClient;
@@ -14163,7 +14054,7 @@ var Page$1 = class {
14163
14054
  })).value;
14164
14055
  }
14165
14056
  async addInitScript(script, arg) {
14166
- const source = await normalizeInitScriptSource$1(script, arg);
14057
+ const source = await normalizeInitScriptSource$1(script, arg, "page.addInitScript", this.rpcClient.platform);
14167
14058
  await this.rpcClient.send(StagehandMethods.pageAddInitScript, {
14168
14059
  pageId: this.pageId,
14169
14060
  source
@@ -14192,14 +14083,15 @@ var Page$1 = class {
14192
14083
  });
14193
14084
  }
14194
14085
  async subscribe(event, deliver) {
14086
+ const platform = this.rpcClient.platform ?? browserPlatform;
14195
14087
  const subscriptionId = crypto.randomUUID();
14196
14088
  const removeNotificationListener = this.rpcClient.onNotification((notification) => {
14197
14089
  if (notification.method !== StagehandNotifications.pageCDPEvent.name && notification.method !== StagehandNotifications.pageEvent.name || notification.params.subscriptionId !== subscriptionId) return;
14198
14090
  try {
14199
14091
  const result = deliver(notification);
14200
- if (result && typeof result === "object" && "then" in result) Promise.resolve(result).catch(reportPageEventListenerError);
14092
+ if (result && typeof result === "object" && "then" in result) Promise.resolve(result).catch((error) => reportPageEventListenerError(error, platform));
14201
14093
  } catch (error) {
14202
- reportPageEventListenerError(error);
14094
+ reportPageEventListenerError(error, platform);
14203
14095
  }
14204
14096
  });
14205
14097
  let subscription;
@@ -14218,7 +14110,7 @@ var Page$1 = class {
14218
14110
  await this.rpcClient.send(StagehandMethods.pageOff, { subscriptionId });
14219
14111
  this.eventSubscriptions.delete(subscription);
14220
14112
  } catch (cleanupError) {
14221
- process.emitWarning(cleanupError instanceof Error ? cleanupError.message : String(cleanupError), { code: "STAGEHAND_PAGE_SUBSCRIPTION_CLEANUP_ERROR" });
14113
+ platform.emitWarning(cleanupError instanceof Error ? cleanupError.message : String(cleanupError), "STAGEHAND_PAGE_SUBSCRIPTION_CLEANUP_ERROR");
14222
14114
  }
14223
14115
  throw error;
14224
14116
  }
@@ -14273,14 +14165,14 @@ var Page$1 = class {
14273
14165
  ...screenshotOptions,
14274
14166
  ...mask ? { mask: mask.map((locator) => locator.descriptor) } : {}
14275
14167
  }
14276
- })).data, "screenshot", path);
14168
+ })).data, "screenshot", path, this.rpcClient.platform);
14277
14169
  }
14278
14170
  async pdf(options) {
14279
14171
  const { path, ...pdfOptions } = options ?? {};
14280
14172
  return await decodeCaptureResult((await this.rpcClient.send(StagehandMethods.pagePDF, {
14281
14173
  pageId: this.pageId,
14282
14174
  options: pdfOptions
14283
- })).data, "pdf", path);
14175
+ })).data, "pdf", path, this.rpcClient.platform);
14284
14176
  }
14285
14177
  async snapshot(options) {
14286
14178
  return await this.rpcClient.send(StagehandMethods.pageSnapshot, {
@@ -14311,25 +14203,16 @@ var Page$1 = class {
14311
14203
  });
14312
14204
  }
14313
14205
  };
14314
- async function decodeCaptureResult(data, method, path) {
14206
+ async function decodeCaptureResult(data, method, path, platform = browserPlatform) {
14315
14207
  const bytes = decodeBase64(data, `page.${method}`);
14316
- if (path !== void 0) {
14317
- const moduleName = "node:fs/promises";
14318
- const { writeFile } = await __vitePreload(() => import(
14319
- /* @vite-ignore */
14320
- moduleName
14321
- ), []).catch(() => {
14322
- throw new TypeError(`page.${method}(): path is only supported in Node.js; omit path to receive ${method === "pdf" ? "PDF" : "screenshot"} bytes`);
14323
- });
14324
- await writeFile(path, bytes);
14325
- }
14208
+ if (path !== void 0) await platform.writeCaptureFile(path, bytes, method);
14326
14209
  return bytes;
14327
14210
  }
14328
- function reportPageEventListenerError(error) {
14329
- process.emitWarning(error instanceof Error ? error.message : String(error), { code: "STAGEHAND_PAGE_EVENT_LISTENER_ERROR" });
14211
+ function reportPageEventListenerError(error, platform) {
14212
+ platform.emitWarning(error instanceof Error ? error.message : String(error), "STAGEHAND_PAGE_EVENT_LISTENER_ERROR");
14330
14213
  }
14331
14214
  //#endregion
14332
- //#region ../sdk-ts/src/browserContext.ts
14215
+ //#region ../shared/browser-api/src/browserContext.ts
14333
14216
  var BrowserContext$1 = class {
14334
14217
  constructor(rpcClient, closeBrowser) {
14335
14218
  this.rpcClient = rpcClient;
@@ -14359,7 +14242,7 @@ var BrowserContext$1 = class {
14359
14242
  await this.closeBrowser();
14360
14243
  }
14361
14244
  async addInitScript(script, arg) {
14362
- const source = await normalizeInitScriptSource$1(script, arg, "context.addInitScript");
14245
+ const source = await normalizeInitScriptSource$1(script, arg, "context.addInitScript", this.rpcClient.platform);
14363
14246
  await this.rpcClient.send(StagehandMethods.contextAddInitScript, { source });
14364
14247
  }
14365
14248
  async setExtraHTTPHeaders(headers) {
@@ -14397,170 +14280,11 @@ function serializeCookieFilter(filter) {
14397
14280
  };
14398
14281
  }
14399
14282
  //#endregion
14400
- //#region ../sdk-ts/src/browser/index.ts
14401
- var browserHandleInternals = /* @__PURE__ */ new WeakMap();
14402
- function isStagehandBrowser(value) {
14403
- return typeof value === "object" && value !== null && browserHandleInternals.has(value);
14404
- }
14405
- strictObject({
14406
- args: array(string()).optional(),
14407
- executablePath: string().optional(),
14408
- port: number$1().optional(),
14409
- userDataDir: string().optional(),
14410
- preserveUserDataDir: boolean().optional(),
14411
- headless: boolean().optional(),
14412
- devtools: boolean().optional(),
14413
- chromiumSandbox: boolean().optional(),
14414
- ignoreDefaultArgs: union([boolean(), array(string())]).optional(),
14415
- proxy: strictObject({
14416
- server: string(),
14417
- bypass: string().optional(),
14418
- username: string().optional(),
14419
- password: string().optional()
14420
- }).optional(),
14421
- locale: string().optional(),
14422
- viewport: strictObject({
14423
- width: number$1(),
14424
- height: number$1()
14425
- }).optional(),
14426
- deviceScaleFactor: number$1().optional(),
14427
- hasTouch: boolean().optional(),
14428
- ignoreHTTPSErrors: boolean().optional(),
14429
- downloadsPath: string().optional(),
14430
- acceptDownloads: boolean().optional(),
14431
- keepAlive: boolean().optional()
14432
- }).meta({ id: "LocalBrowserLaunchOptions" });
14433
- var CDPHeadersSchema = preprocess((value) => {
14434
- try {
14435
- if (typeof value !== "object" || value === null || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return null;
14436
- const entries = Object.entries(value);
14437
- if (!entries.every(([name, content]) => name.length > 0 && !/[^!#$%&'*+\-.^_`|~0-9A-Za-z]/.test(name) && typeof content === "string" && !/[^\t\x20-\x7e]/.test(content) && content === content.replace(/^[ \t]+|[ \t]+$/g, ""))) return null;
14438
- return Object.fromEntries(entries);
14439
- } catch {
14440
- return null;
14441
- }
14442
- }, record(string(), string(), { error: "headers must map valid HTTP header names to ASCII string values without leading or trailing spaces or tabs" }));
14443
- strictObject({
14444
- cdpUrl: string().min(1),
14445
- /** Headers for client-side CDP discovery and WebSocket connections. */
14446
- headers: CDPHeadersSchema.optional(),
14447
- extensionId: string().optional(),
14448
- /**
14449
- * Browser-level CDP WebSocket URL dialed by the extension inside Chrome.
14450
- * Defaults to the client's URL. Set this when the client connects through
14451
- * a gateway the extension cannot or should not use.
14452
- */
14453
- extensionCdpUrl: url({
14454
- protocol: /^wss?$/,
14455
- hostname: /.+/
14456
- }).refine((value) => {
14457
- try {
14458
- return new URL(value).port !== "0";
14459
- } catch {
14460
- return false;
14461
- }
14462
- }, { message: "Port must be between 1 and 65535" }).optional()
14463
- }).meta({ id: "LocalBrowserConnectOptions" });
14464
- var DEFAULT_BROWSERBASE_URL = "https://api.browserbase.com";
14465
- var BrowserbaseClientOptionsSchema = strictObject({
14466
- timeout: int().nonnegative().optional(),
14467
- maxRetries: int().nonnegative().optional(),
14468
- defaultHeaders: record(string(), string().nullable().optional()).optional(),
14469
- defaultQuery: record(string(), string().optional()).optional(),
14470
- fetch: custom((value) => typeof value === "function", { message: "fetch must be a function" }).optional()
14471
- });
14472
- looseObject({
14473
- apiKey: string().min(1),
14474
- baseUrl: url().default(DEFAULT_BROWSERBASE_URL),
14475
- clientOptions: BrowserbaseClientOptionsSchema.optional(),
14476
- apiUrl: never().optional(),
14477
- type: never().optional()
14478
- }).meta({ id: "BrowserbaseLaunchOptions" });
14479
- strictObject({
14480
- apiKey: string().min(1),
14481
- baseUrl: url().default(DEFAULT_BROWSERBASE_URL),
14482
- clientOptions: BrowserbaseClientOptionsSchema.optional(),
14483
- sessionId: string().min(1),
14484
- extensionId: string().optional()
14485
- }).meta({ id: "BrowserbaseConnectOptions" });
14486
- var BrowserbaseCredentialsShape = {
14487
- apiKey: string().min(1),
14488
- baseUrl: url().default(DEFAULT_BROWSERBASE_URL)
14489
- };
14490
- strictObject({
14491
- ...BrowserbaseCredentialsShape,
14492
- query: string().min(1).max(200),
14493
- numResults: int().min(1).max(25).optional()
14494
- }).meta({ id: "BrowserbaseSearchOptions" });
14495
- strictObject({
14496
- ...BrowserbaseCredentialsShape,
14497
- url: url(),
14498
- allowInsecureSsl: boolean().optional(),
14499
- allowRedirects: boolean().optional(),
14500
- format: _enum([
14501
- "raw",
14502
- "json",
14503
- "markdown"
14504
- ]).optional(),
14505
- proxies: boolean().optional(),
14506
- schema: record(string(), unknown()).optional()
14507
- }).refine(({ format, schema }) => schema === void 0 || format === "json", {
14508
- message: "schema is only valid when format is \"json\"",
14509
- path: ["schema"]
14510
- }).refine(({ format, schema }) => format !== "json" || schema !== void 0, {
14511
- message: "schema is required when format is \"json\"",
14512
- path: ["schema"]
14513
- }).meta({ id: "BrowserbaseFetchOptions" });
14514
- object({
14515
- query: string(),
14516
- requestId: string(),
14517
- results: array(object({
14518
- id: string(),
14519
- title: string(),
14520
- url: string(),
14521
- author: string().nullish(),
14522
- favicon: string().nullish(),
14523
- image: string().nullish(),
14524
- publishedDate: string().nullish()
14525
- }))
14526
- }).meta({ id: "BrowserbaseSearchResult" });
14527
- object({
14528
- id: string(),
14529
- content: union([string(), record(string(), unknown())]),
14530
- contentType: string(),
14531
- encoding: string(),
14532
- headers: record(string(), string()),
14533
- statusCode: number$1().int()
14534
- }).meta({ id: "BrowserbaseFetchResult" });
14535
- object({
14536
- id: string(),
14537
- connectUrl: string()
14538
- }).meta({ id: "BrowserbaseSessionCreateResult" });
14539
- object({
14540
- id: string(),
14541
- connectUrl: string().optional(),
14542
- region: BrowserbaseRegionSchema.optional()
14543
- }).meta({ id: "BrowserbaseSessionRetrieveResult" });
14544
- strictObject({
14545
- sessionId: string().trim().min(1),
14546
- cdpUrl: string().trim().min(1),
14547
- region: BrowserbaseRegionSchema.optional()
14548
- }).meta({ id: "BrowserbaseSessionConnection" });
14549
- WebMCPToolsOptionsSchema$1.partial();
14550
- WebMCPInvokeOptionsSchema$1.partial();
14551
- /** An LLM callback implemented locally by the SDK consumer. It never crosses the wire. */
14552
- var ClientLLMSchema = strictObject({ generate: _function({
14553
- input: [LLMGenerateParamsSchema],
14554
- output: promise(LLMGenerateResultSchema)
14555
- }) }).meta({ id: "ClientLLM" });
14556
- var StagehandClientLogLevelSchema = union([StagehandLogLevelSchema, literal("off")]).meta({ id: "StagehandClientLogLevel" });
14557
- var StagehandClientLogFormatSchema = _enum(["pretty", "json"]).meta({ id: "StagehandClientLogFormat" });
14558
- var StagehandClientOnLogSchema = custom((value) => typeof value === "function", "onLog must be a function").meta({ id: "StagehandClientOnLog" });
14559
- var StagehandClientLoggingConfigSchema = strictObject({
14560
- level: StagehandClientLogLevelSchema.default("info"),
14561
- format: StagehandClientLogFormatSchema.default("pretty"),
14562
- onLog: StagehandClientOnLogSchema.optional()
14563
- }).meta({ id: "StagehandClientLoggingConfig" });
14283
+ //#region ../shared/browser-api/src/schemas.ts
14284
+ /**
14285
+ * Browser API operation schemas shared by the TS SDK and extension callback batches. They extend
14286
+ * wire schemas with local Page and Locator instances and client-facing option defaults.
14287
+ */
14564
14288
  var StagehandClientActOptionsSchema = ActOptionsSchema.extend({
14565
14289
  locator: _instanceof(Locator$1).optional(),
14566
14290
  ignoreLocators: array(_instanceof(Locator$1)).optional(),
@@ -14576,26 +14300,10 @@ var StagehandClientExtractOptionsSchema = ExtractOptionsSchema.extend({
14576
14300
  ignoreLocators: array(_instanceof(Locator$1)).optional(),
14577
14301
  page: _instanceof(Page$1).optional()
14578
14302
  }).meta({ id: "StagehandClientExtractOptions" });
14579
- var StagehandClientCreateConfigSchema = strictObject(StagehandInitParamsSchema.shape).omit({
14580
- browserbase: true,
14581
- protocolVersion: true,
14582
- clientInfo: true,
14583
- browserCdpUrl: true,
14584
- logLevel: true,
14585
- browser: true
14586
- }).extend({
14587
- apiKey: string().min(1).optional().meta({ description: "Browserbase API key. A Browserbase browser uses the key supplied to its launch/connect factory; this option does not override that key." }),
14588
- apiUrl: url({ protocol: /^https?$/ }).refine((value) => !value.includes("?") && !value.includes("#"), "Stagehand apiUrl must not include a query string or fragment").refine((value) => !new URL(value).pathname.replace(/\/+$/, "").endsWith("/v1"), { message: "Stagehand apiUrl must be a service origin without /v1" }).optional().meta({ description: "Stagehand API base URL override for managed services such as Model Gateway and server-side caching" }),
14589
- model: union([ModelConfigSchema, ClientLLMSchema]).optional(),
14590
- logging: StagehandClientLoggingConfigSchema.default({
14591
- level: "info",
14592
- format: "pretty"
14593
- })
14594
- }).strict().meta({ id: "StagehandClientCreateConfig" });
14595
- var StagehandBrowserSchema = custom(isStagehandBrowser, "browser must be created by localBrowser or browserbase").meta({ id: "StagehandBrowser" });
14596
- StagehandClientCreateConfigSchema.extend({ browser: StagehandBrowserSchema }).meta({ id: "StagehandCreateOptions" });
14303
+ WebMCPToolsOptionsSchema$1.partial();
14304
+ WebMCPInvokeOptionsSchema$1.partial();
14597
14305
  //#endregion
14598
- //#region ../sdk-ts/src/clientLocatorOptions.ts
14306
+ //#region ../shared/browser-api/src/clientLocatorOptions.ts
14599
14307
  function serializeClientLocator(locator, pageId, method) {
14600
14308
  if (locator.descriptor.pageId !== pageId) throw new TypeError(`${method}(): locator must belong to the target page`);
14601
14309
  const { selector, nth } = locator.descriptor;
@@ -14615,11 +14323,13 @@ function serializeClientLocatorOptions(method, pageId, options) {
14615
14323
  //#endregion
14616
14324
  //#region callbackBatch.ts
14617
14325
  var InProcessCommandClient = class {
14618
- #nextRequestId = 1;
14326
+ #nextRequestId;
14619
14327
  constructor(router, signal, traceContext) {
14620
14328
  this.router = router;
14621
14329
  this.signal = signal;
14622
14330
  this.traceContext = traceContext;
14331
+ this.platform = browserPlatform;
14332
+ this.#nextRequestId = 1;
14623
14333
  }
14624
14334
  async send(method, params) {
14625
14335
  this.throwIfAborted();
@@ -66135,7 +65845,7 @@ var WebTracerProvider = class extends BasicTracerProvider {
66135
65845
  };
66136
65846
  var package_default = {
66137
65847
  name: "@browserbasehq/stagehand-extension",
66138
- version: "1.4.0-alpha-82827a219512f0399cb159720a63f7d271d21480",
65848
+ version: "1.4.0-alpha-cdf5ddce87a10fa240c0c220095d4a95f4526295",
66139
65849
  "private": true,
66140
65850
  type: "module",
66141
65851
  scripts: {
@@ -66163,6 +65873,7 @@ var package_default = {
66163
65873
  "zustand": "catalog:"
66164
65874
  },
66165
65875
  devDependencies: {
65876
+ "@browserbasehq/stagehand-browser-api": "workspace:*",
66166
65877
  "@browserbasehq/stagehand-protocol": "workspace:*",
66167
65878
  "@types/chrome": "catalog:",
66168
65879
  "@types/node": "catalog:",
@@ -1,4 +1,4 @@
1
1
  """Generated from packages/protocol/package.json. Do not edit."""
2
2
 
3
3
  PROTOCOL_SEMVER_PATTERN = '^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\\+([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$'
4
- STAGEHAND_PROTOCOL_VERSION = '3.2.0-alpha-82827a219512f0399cb159720a63f7d271d21480'
4
+ STAGEHAND_PROTOCOL_VERSION = '3.2.0-alpha-cdf5ddce87a10fa240c0c220095d4a95f4526295'