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
Restore evaluate compatibility for real-browser e2e
Tachikomac712d3fe5288
diff --git a/package/ego-browser/src/cdp-eval.test.mjs b/package/ego-browser/src/cdp-eval.test.mjsindex f933dd5..a8f4b7c 100644--- a/package/ego-browser/src/cdp-eval.test.mjs+++ b/package/ego-browser/src/cdp-eval.test.mjs@@ -2,6 +2,7 @@ import test from "node:test";import assert from "node:assert/strict";import {+ hasReturnStatement,decodeUnserializableJsValue,runtimeValue,evaluate,@@ -9,6 +10,26 @@ import {} from "../dist/src/cdp-eval.js";import { setOverrides } from "../dist/src/state.js";+/* ------------------------------------------------------------------ */+/* hasReturnStatement — the state-machine parser */+/* ------------------------------------------------------------------ */++test("hasReturnStatement detects a bare return", () => {+ assert.equal(hasReturnStatement("return 1"), true);+});++test("hasReturnStatement ignores return inside strings and comments", () => {+ assert.equal(hasReturnStatement("'return 1'"), false);+ assert.equal(hasReturnStatement('"return 1"'), false);+ assert.equal(hasReturnStatement("// return 1\n1 + 2"), false);+ assert.equal(hasReturnStatement("/* return 1 */ 1 + 2"), false);+});++test("hasReturnStatement does not match return as part of an identifier", () => {+ assert.equal(hasReturnStatement("const returned = 1; returned + 1"), false);+ assert.equal(hasReturnStatement("const returnCode = 1; returnCode"), false);+});+/* ------------------------------------------------------------------ *//* decodeUnserializableJsValue — special CDP value decoding *//* ------------------------------------------------------------------ */@@ -235,6 +256,26 @@ test("cdp tracks Network domain state on enable", async () => {/* evaluate() — Playwright-style pageFunction evaluation *//* ------------------------------------------------------------------ */+test("evaluate auto-wraps string expressions with top-level return", async () => {+ let capturedExpression;+ const restore = setOverrides({+ cdpOverride: async (method, params) => {+ if (method === "Runtime.evaluate") {+ capturedExpression = params.expression;+ return { result: { type: "number", value: 42 } };+ }+ return {};+ },+ });+ try {+ const result = await evaluate("return 42");+ assert.equal(result, 42);+ assert.equal(capturedExpression, "(function(){return 42})()");+ } finally {+ restore();+ }+});+test("evaluate passes plain expressions without IIFE wrapping", async () => {let capturedExpression;const restore = setOverrides({@@ -255,6 +296,25 @@ test("evaluate passes plain expressions without IIFE wrapping", async () => {}});+test("evaluate does not wrap string expressions that already start with paren", async () => {+ let capturedExpression;+ const restore = setOverrides({+ cdpOverride: async (method, params) => {+ if (method === "Runtime.evaluate") {+ capturedExpression = params.expression;+ return { result: { type: "number", value: 10 } };+ }+ return {};+ },+ });+ try {+ await evaluate("(function(){ return 10 })()");+ assert.equal(capturedExpression, "(function(){ return 10 })()");+ } finally {+ restore();+ }+});+test("evaluate passes function pageFunctions with an arg", async () => {let capturedExpression;const restore = setOverrides({@@ -289,10 +349,10 @@ test("evaluate rejects non-string/non-function input", async () => {);});-test("evaluate rejects string expressions with an arg", async () => {+test("evaluate rejects string expressions with non-string args", async () => {await assert.rejects(- () => evaluate("document.title", "!"),- /string form does not accept an arg/,+ () => evaluate("document.title", { suffix: "!" }),+ /string form only accepts a legacy target id/,);});@@ -323,3 +383,36 @@ test("evaluate propagates page exceptions", async () => {restore();}});++test("evaluate attaches to a target session when legacy target id is given", async () => {+ const calls = [];+ const restore = setOverrides({+ cdpOverride: async (method, params, sessionId) => {+ calls.push([method, params, sessionId]);+ if (method === "Target.attachToTarget") {+ return { sessionId: "sess-123" };+ }+ if (method === "Runtime.evaluate") {+ return { result: { type: "string", value: "iframe-result" } };+ }+ return {};+ },+ });+ try {+ const result = await evaluate("return document.title", "target-abc");+ assert.equal(result, "iframe-result");+ assert.deepEqual(calls[0], [+ "Target.attachToTarget",+ { targetId: "target-abc", flatten: true },+ undefined,+ ]);+ assert.equal(calls[1][0], "Runtime.evaluate");+ assert.equal(+ calls[1][1].expression,+ "(function(){return document.title})()",+ );+ assert.equal(calls[1][2], "sess-123");+ } finally {+ restore();+ }+});diff --git a/package/ego-browser/src/cdp-eval.ts b/package/ego-browser/src/cdp-eval.tsindex 890df03..09f7c27 100644--- a/package/ego-browser/src/cdp-eval.ts+++ b/package/ego-browser/src/cdp-eval.ts@@ -28,26 +28,40 @@ export async function cdp(method, params: any = {}, sessionId = undefined) {/*** Evaluate JavaScript in the current page, Playwright-style.* @param {string | Function} pageFunction JavaScript expression string or function called with arg.+ * String expressions with top-level return statements are auto-wrapped in an IIFE for compatibility.* @param {unknown} [arg] Optional serializable argument passed to function pageFunctions.+ * For legacy string expressions, a string second argument is treated as a target id to evaluate in.* @returns {Promise<any>} Runtime.evaluate return-by-value result.*/export async function evaluate(pageFunction, arg = undefined) {let expression;+ let sessionId;if (typeof pageFunction === "function") {expression = `(${pageFunction.toString()})(${serializedArg(arg)})`;} else if (typeof pageFunction === "string") {- if (arg !== undefined) {+ if (arg !== undefined && typeof arg !== "string") {throw new TypeError(- "page.evaluate string form does not accept an arg; pass a function pageFunction instead",+ "page.evaluate string form only accepts a legacy target id as its second argument; pass a function pageFunction to use args",);}expression = pageFunction;+ if (arg !== undefined) {+ sessionId = (+ await cdp("Target.attachToTarget", {+ targetId: arg,+ flatten: true,+ })+ ).sessionId;+ }} else {throw new TypeError(`page.evaluate expects a string expression or function pageFunction, got ${pageFunction === null ? "null" : typeof pageFunction}`,);}- return runtimeEvaluate(expression, undefined, true);+ if (hasReturnStatement(expression) && !expression.trim().startsWith("(")) {+ expression = `(function(){${expression}})()`;+ }+ return runtimeEvaluate(expression, sessionId, true);}async function runtimeEvaluate(@@ -140,6 +154,71 @@ function jsSnippet(expression, limit = 160) {return snippet.length > limit ? `${snippet.slice(0, limit - 3)}...` : snippet;}+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;+ }+ }+ return false;+}+function serializedArg(arg) {return arg === undefined ? "" : JSON.stringify(arg);}