The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
fix(ego-browser): only auto-wrap js() source with an outer return
Zhuowei Wang8d49bb411900
diff --git a/package/ego-browser/src/cdp-eval.test.mjs b/package/ego-browser/src/cdp-eval.test.mjsnew file mode 100644index 0000000..607d43e--- /dev/null+++ b/package/ego-browser/src/cdp-eval.test.mjs@@ -0,0 +1,98 @@+import test from "node:test";+import assert from "node:assert/strict";+import { runInNewContext } from "node:vm";++import { hasReturnStatement, js } from "../dist/src/cdp-eval.js";+import { setOverrides } from "../dist/src/state.js";++test("hasReturnStatement ignores returns inside nested functions", () => {+ for (const expression of [+ "[1, 2].map(x => { return x * 2; })",+ "function f() { return 1; } f()",+ "const f = function () { return 1; }; f()",+ "({ value() { return 1; } }).value()",+ "class C { value() { return 1; } } new C().value()",+ "`${(() => { return 1; })()}`",+ "(async () => { return 1; })()",+ ]) {+ assert.equal(hasReturnStatement(expression), false, expression);+ }+});++test("hasReturnStatement finds outer returns inside control flow", () => {+ for (const expression of [+ "return 1",+ "if (true) { return 1; }",+ "try { throw 1; } catch (error) { return error; }",+ "for (const n of [1]) { return n; }",+ "const f = () => { return 1; }; return f();",+ "(1 + 2); return 4;",+ ]) {+ assert.equal(hasReturnStatement(expression), true, expression);+ }+});++test("hasReturnStatement ignores return in regexes, strings, and identifiers", () => {+ for (const expression of [+ "/return/i.test('return')",+ "'return 1'",+ "// return 1\n2",+ "({ return: 1 }).return",+ "const returnCode = 1; returnCode",+ "const $return = 1; $return",+ ]) {+ assert.equal(hasReturnStatement(expression), false, expression);+ }+});++test("hasReturnStatement leaves invalid source for the browser to reject", () => {+ assert.equal(hasReturnStatement("return ("), false);+});++// Execute the emitted expression for real so a wrapper that drops the value+// cannot pass by way of a mock that answers unconditionally.+async function evaluateInVm(expression) {+ let emitted;+ const restore = setOverrides({+ cdpOverride: async (method, params) => {+ assert.equal(method, "Runtime.evaluate");+ emitted = params.expression;+ const value = await runInNewContext(params.expression);+ return {+ result:+ value === undefined+ ? { type: "undefined" }+ : { type: typeof value, value: structuredClone(value) },+ };+ },+ });+ try {+ return { value: await js(expression), emitted };+ } finally {+ restore();+ }+}++for (const [name, expression, expected] of [+ ["arrow callback", "[1, 2].map(x => { return x * 2; })", [2, 4]],+ ["function declaration", "function f() { return 3; } f()", 3],+ ["object method", "[1].map(({ value() { return 4; } }).value)", [4]],+ ["class method", "class C { value() { return 5; } } new C().value()", 5],+ ["regex literal", "/return/i.test('RETURN')", true],+ ["outer return", "return 42", 42],+ ["block return", "if (true) { return [2, 4]; }", [2, 4]],+ ["return after a parenthesized expression", "(1 + 2); return 4;", 4],+ ["return with a trailing line comment", "return 6 // done", 6],+ ["return after await", "const n = await Promise.resolve(7); return n;", 7],+]) {+ test(`js preserves the result of ${name}`, async () => {+ const { value } = await evaluateInVm(expression);+ assert.deepEqual(value, expected);+ });+}++test("js sends expressions without an outer return unchanged", async () => {+ const expression = "(async () => { return 1; })()";+ const { emitted } = await evaluateInVm(expression);+ assert.equal(emitted, expression);+});diff --git a/package/ego-browser/src/cdp-eval.ts b/package/ego-browser/src/cdp-eval.tsindex c543a6f..36c67e3 100644--- a/package/ego-browser/src/cdp-eval.ts+++ b/package/ego-browser/src/cdp-eval.ts@@ -1,3 +1,5 @@+import { parse } from "acorn";+import { browserCdp } from "./browser-runtime.js";import { state } from "./state.js";@@ -59,8 +61,10 @@ export async function js(expression, targetId = undefined) {.sessionId: undefined;let finalExpression = expression;- if (hasReturnStatement(expression) && !expression.trim().startsWith("(")) {- finalExpression = `(function(){${expression}})()`;+ if (hasReturnStatement(expression)) {+ // Newlines keep a trailing line comment from swallowing the closing+ // brace; async keeps top-level await valid inside the wrapper.+ finalExpression = `(async function(){\n${expression}\n})()`;}return runtimeEvaluate(finalExpression, sessionId, true);}@@ -152,67 +156,38 @@ function jsSnippet(expression, limit = 160) {return snippet.length > limit ? `${snippet.slice(0, limit - 3)}...` : snippet;}+/**+ * Whether the source has a `return` outside any nested function, meaning it+ * must be wrapped in a function before Runtime.evaluate accepts it.+ */export function hasReturnStatement(expression) {- let i = 0;- let stateName = "code";- let quote = "";- while (i < expression.length) {- const ch = expression[i];- const next = expression[i + 1] || "";- if (stateName === "code") {- if (ch === "'" || ch === '"' || ch === "`") {- stateName = "string";- quote = ch;- i += 1;- continue;- }- if (ch === "/" && next === "/") {- stateName = "line_comment";- i += 2;- continue;- }- if (ch === "/" && next === "*") {- stateName = "block_comment";- i += 2;- continue;- }- if (expression.startsWith("return", i)) {- const before = i > 0 ? expression[i - 1] : "";- const after = expression[i + 6] || "";- if (!/[A-Za-z0-9_]/.test(before) && !/[A-Za-z0-9_]/.test(after)) {- return true;- }- }- i += 1;- continue;- }- if (stateName === "line_comment") {- if (ch === "\n") {- stateName = "code";- }- i += 1;- continue;- }- if (stateName === "block_comment") {- if (ch === "*" && next === "/") {- stateName = "code";- i += 2;- continue;- }- i += 1;- continue;- }- if (stateName === "string") {- if (ch === "\\") {- i += 2;- continue;- }- if (ch === quote) {- stateName = "code";- quote = "";- }- i += 1;- }+ try {+ return containsOuterReturn(+ parse(expression, {+ ecmaVersion: "latest",+ allowReturnOutsideFunction: true,+ allowAwaitOutsideFunction: true,+ }),+ );+ } catch {+ // Leave invalid or unsupported syntax untouched for the browser to report.+ return false;+ }+}++function containsOuterReturn(node) {+ if (!node || typeof node !== "object") return false;+ if (node.type === "ReturnStatement") return true;+ if (+ node.type === "FunctionDeclaration" ||+ node.type === "FunctionExpression" ||+ node.type === "ArrowFunctionExpression"+ ) {+ return false;}- return false;+ return Object.values(node).some((child) =>+ Array.isArray(child)+ ? child.some(containsOuterReturn)+ : containsOuterReturn(child),+ );}