Skip to content

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.

Embed help docs at build time to fix empty help() in production

0x06fda2a43f3d0
diff --git a/package/ego-browser/scripts/build.mjs b/package/ego-browser/scripts/build.mjs
index 6cc3056..0d88025 100644
--- a/package/ego-browser/scripts/build.mjs
+++ b/package/ego-browser/scripts/build.mjs
@@ -1,4 +1,13 @@
-import { chmod, cp, mkdir, open, readdir, rm } from "node:fs/promises";
+import {
+ chmod,
+ cp,
+ mkdir,
+ open,
+ readFile,
+ readdir,
+ rm,
+ writeFile,
+} from "node:fs/promises";
import { builtinModules } from "node:module";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -8,6 +17,10 @@ import { rollup } from "rollup";
import resolve from "@rollup/plugin-node-resolve";
import typescript from "@rollup/plugin-typescript";
+import { extractHelpDocs } from "./extract-help-docs.mjs";
+
+const HELP_DOCS_PLACEHOLDER = '"__EGO_EMBEDDED_HELP_DOCS__"';
+
const root = dirname(dirname(fileURLToPath(import.meta.url)));
const repoRoot = dirname(dirname(root));
const distDir = join(root, "dist");
@@ -39,7 +52,7 @@ try {
platform: "node",
format: "esm",
target: "node22",
- logLevel: "info"
+ logLevel: "info",
};
await build({
@@ -49,7 +62,7 @@ try {
outbase: ".",
bundle: false,
sourcemap: false,
- absWorkingDir: root
+ absWorkingDir: root,
});
const rollupConfig = {
@@ -62,15 +75,17 @@ try {
compilerOptions: {
noEmit: false,
declaration: false,
- removeComments: false
- }
- })
- ]
+ removeComments: false,
+ },
+ }),
+ ],
};
const bundle = await rollup(rollupConfig);
await bundle.write({ file: bundledCli, format: "esm", sourcemap: false });
await bundle.close();
+ await embedHelpDocs(bundledCli, join(distDir, "src", "help-runtime.js"));
+
await cp(skillSourceDir, bundledSkillDir, { recursive: true });
await chmod(bundledCli, 0o755);
} finally {
@@ -78,10 +93,35 @@ try {
await rm(buildLock, { force: true });
}
+async function embedHelpDocs(...files) {
+ // The docs are extracted from the emitted bundle (it carries every helper's
+ // JSDoc with comments preserved) and injected into each build artifact that
+ // ships help-runtime, replacing the placeholder string constant. Doing this
+ // at build time means the runtime never has to read its own source. See
+ // GitHub issue #84.
+ const bundleSource = await readFile(files[0], "utf-8");
+ const docs = extractHelpDocs(bundleSource);
+ if (docs.length === 0) {
+ throw new Error("embedHelpDocs: extracted 0 helper docs from the bundle");
+ }
+ const injected = JSON.stringify(JSON.stringify(docs));
+ for (const file of files) {
+ const source = await readFile(file, "utf-8");
+ if (!source.includes(HELP_DOCS_PLACEHOLDER)) {
+ throw new Error(`embedHelpDocs: placeholder not found in ${file}`);
+ }
+ // Use a replacer function so `$` sequences in the JSON are inserted literally.
+ await writeFile(
+ file,
+ source.replace(HELP_DOCS_PLACEHOLDER, () => injected),
+ );
+ }
+}
+
async function tsEntryPoints(dirs) {
const files = [];
for (const dir of dirs) {
- files.push(...await collectTsFiles(join(root, dir), dir));
+ files.push(...(await collectTsFiles(join(root, dir), dir)));
}
return files.sort();
}
@@ -93,7 +133,7 @@ async function collectTsFiles(absDir, relativeDir) {
const relativePath = `${relativeDir}/${entry.name}`;
const absPath = join(absDir, entry.name);
if (entry.isDirectory()) {
- files.push(...await collectTsFiles(absPath, relativePath));
+ files.push(...(await collectTsFiles(absPath, relativePath)));
} else if (entry.isFile() && entry.name.endsWith(".ts")) {
files.push(relativePath);
}
diff --git a/package/ego-browser/scripts/extract-help-docs.mjs b/package/ego-browser/scripts/extract-help-docs.mjs
new file mode 100644
index 0000000..0f769e9
--- /dev/null
+++ b/package/ego-browser/scripts/extract-help-docs.mjs
@@ -0,0 +1,206 @@
+import { parse } from "acorn";
+
+// Build-time helper-doc extraction.
+//
+// Historically this ran at runtime inside help-runtime.ts by reading the
+// module's own source (fileURLToPath(import.meta.url) + readFileSync). That
+// only works when the SDK is loaded from a real file. In the shipped browser
+// the SDK is loaded from a compiled .pak resource whose import.meta.url is
+// "ego://services/node/resources/index.js", so fileURLToPath throws and the
+// docs map was permanently empty. The extraction now happens at build time
+// against the emitted bundle and the result is embedded as data, so the
+// runtime never touches its own source. See GitHub issue #84.
+
+/**
+ * Parse bundled JS source and return the helper docs used by help()/formatHelp().
+ * @param {string} source Bundled JavaScript with comments preserved.
+ * @returns {Array<{name: string, signature: string, description: string | null, params: Array<object>, returns: string | null, async: boolean}>}
+ */
+export function extractHelpDocs(source) {
+ const docs = new Map();
+
+ const comments = [];
+ const ast = parse(source, {
+ ecmaVersion: "latest",
+ sourceType: "module",
+ onComment: comments,
+ locations: true,
+ });
+
+ const commentsByEndLine = new Map();
+ for (const c of comments) {
+ if (c.type === "Block") {
+ commentsByEndLine.set(c.loc.end.line, c);
+ }
+ }
+
+ walkFunctions(ast, (node) => {
+ const name = extractFunctionName(node);
+ if (!name) return;
+
+ const startLine = node.loc.start.line;
+ const jsDoc = commentsByEndLine.get(startLine - 1);
+ const parsed = jsDoc ? parseJSDoc(jsDoc.value) : null;
+
+ const params = extractParams(node, parsed);
+ const isAsync = node.async === true;
+ const paramSig = params
+ .map((p) => {
+ const rest = p.rest ? "..." : "";
+ const opt = p.optional ? "?" : "";
+ return `${rest}${p.name}${opt}`;
+ })
+ .join(", ");
+ const retStr = parsed?.returns || (isAsync ? "Promise<...>" : null);
+ const signature = `${name}(${paramSig})${retStr ? ` → ${retStr}` : ""}`;
+
+ docs.set(name, {
+ name,
+ signature,
+ description: parsed?.description || null,
+ params,
+ returns: retStr,
+ async: isAsync,
+ });
+ });
+
+ walkAliases(ast, (name, target) => {
+ const existing = docs.get(target);
+ if (existing && !docs.has(name)) {
+ docs.set(name, { ...existing, name });
+ }
+ });
+
+ return [...docs.values()];
+}
+
+function walkFunctions(node, visitor) {
+ if (!node || typeof node !== "object") return;
+ if (
+ node.type === "FunctionDeclaration" ||
+ node.type === "FunctionExpression"
+ ) {
+ visitor(node);
+ }
+ for (const key of Object.keys(node)) {
+ if (key === "type" || key === "loc" || key === "start" || key === "end")
+ continue;
+ const child = node[key];
+ if (Array.isArray(child)) {
+ for (const item of child) {
+ if (item && typeof item.type === "string") walkFunctions(item, visitor);
+ }
+ } else if (child && typeof child.type === "string") {
+ walkFunctions(child, visitor);
+ }
+ }
+}
+
+function walkAliases(node, visitor) {
+ if (!node || typeof node !== "object") return;
+ if (node.type === "VariableDeclaration") {
+ for (const decl of node.declarations || []) {
+ if (decl.id?.type === "Identifier" && decl.init?.type === "Identifier") {
+ visitor(decl.id.name, decl.init.name);
+ }
+ }
+ }
+ for (const key of Object.keys(node)) {
+ if (key === "type" || key === "loc" || key === "start" || key === "end")
+ continue;
+ const child = node[key];
+ if (Array.isArray(child)) {
+ for (const item of child) {
+ if (item && typeof item.type === "string") walkAliases(item, visitor);
+ }
+ } else if (child && typeof child.type === "string") {
+ walkAliases(child, visitor);
+ }
+ }
+}
+
+function extractFunctionName(node) {
+ if (node.id?.name) return node.id.name;
+ return null;
+}
+
+function extractParams(node, jsdoc) {
+ return (node.params || []).map((p) => {
+ const info = resolveParam(p);
+ const jsdocParam = jsdoc?.params.find((jp) => jp.name === info.name);
+ return {
+ ...info,
+ type: jsdocParam?.type || null,
+ description: jsdocParam?.description || null,
+ };
+ });
+}
+
+function parseJSDoc(raw) {
+ const lines = raw.split("\n").map((l) => l.replace(/^\s*\*\s?/, "").trim());
+ const descLines = [];
+ const params = [];
+ let returns = null;
+
+ for (const line of lines) {
+ const paramMatch = line.match(
+ /^@param\s+(?:\{([^}]*)\}\s+)?(\[?\w+\]?)(?:(?:\s+[-–—]\s*|\s+)(.+))?\s*$/,
+ );
+ if (paramMatch) {
+ const name = paramMatch[2].replace(/^\[|\]$/g, "");
+ params.push({
+ name,
+ type: paramMatch[1] || null,
+ description: paramMatch[3] || null,
+ });
+ continue;
+ }
+ const returnsMatch = line.match(/^@returns?\s+(?:\{([^}]*)\}\s*)?(.*)/);
+ if (returnsMatch) {
+ returns = returnsMatch[1] || returnsMatch[2] || null;
+ continue;
+ }
+ if (line.startsWith("@")) continue;
+ if (line) descLines.push(line);
+ }
+
+ return {
+ description: descLines.join(" ").trim() || null,
+ params,
+ returns,
+ };
+}
+
+function resolveParam(node) {
+ if (node.type === "RestElement") {
+ const inner = resolveParam(node.argument);
+ return { ...inner, rest: true, optional: true };
+ }
+ if (node.type === "AssignmentPattern") {
+ const inner = resolveParam(node.left);
+ const defStr = nodeToString(node.right);
+ return { ...inner, optional: true, default: defStr };
+ }
+ if (node.type === "Identifier") {
+ return { name: node.name, optional: false, rest: false, default: null };
+ }
+ if (node.type === "ObjectPattern") {
+ const props = (node.properties || [])
+ .map((p) => p.key?.name || "?")
+ .join(", ");
+ return { name: `{${props}}`, optional: false, rest: false, default: null };
+ }
+ if (node.type === "ArrayPattern") {
+ return { name: "[...]", optional: false, rest: false, default: null };
+ }
+ return { name: "?", optional: false, rest: false, default: null };
+}
+
+function nodeToString(node) {
+ if (!node) return "?";
+ if (node.type === "Literal") return JSON.stringify(node.value);
+ if (node.type === "ObjectExpression") return "{}";
+ if (node.type === "ArrayExpression") return "[]";
+ if (node.type === "Identifier") return node.name;
+ return "...";
+}
diff --git a/package/ego-browser/src/help-runtime.test.mjs b/package/ego-browser/src/help-runtime.test.mjs
new file mode 100644
index 0000000..f852955
--- /dev/null
+++ b/package/ego-browser/src/help-runtime.test.mjs
@@ -0,0 +1,39 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { help, formatHelp } from "../dist/src/help-runtime.js";
+
+// Regression test for GitHub issue #84: the runtime used to build its docs map
+// by reading its own source, which produced an empty map whenever the SDK was
+// not loaded from a real file (the shipped .pak resource). Docs are now
+// embedded at build time, so these assertions exercise the injected data.
+
+test("help(name) returns the embedded doc instead of an empty result", () => {
+ const doc = help({ click: () => {} }, "click");
+ assert.equal(typeof doc, "object");
+ assert.equal(doc.name, "click");
+ assert.ok(
+ doc.description && doc.description.length > 0,
+ `expected a non-empty description, got: ${JSON.stringify(doc)}`,
+ );
+});
+
+test("help() lists the helpers present in the context", () => {
+ const list = help({ click: () => {}, waitFor: () => {} });
+ assert.ok(Array.isArray(list));
+ assert.ok(list.length > 0, "expected embedded docs to be non-empty");
+ assert.ok(list.some((d) => d.name === "click"));
+});
+
+test("help(unknown) reports the unknown helper", () => {
+ assert.equal(
+ help({}, "definitelyNotAHelper"),
+ "Unknown helper: definitelyNotAHelper",
+ );
+});
+
+test("formatHelp renders the signature for an embedded doc", () => {
+ const doc = help({ click: () => {} }, "click");
+ const text = formatHelp(doc);
+ assert.ok(text.includes("click("), `expected signature in:\n${text}`);
+});
diff --git a/package/ego-browser/src/help-runtime.ts b/package/ego-browser/src/help-runtime.ts
index d64ebd1..769bf20 100644
--- a/package/ego-browser/src/help-runtime.ts
+++ b/package/ego-browser/src/help-runtime.ts
@@ -1,7 +1,3 @@
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { parse } from "acorn";
-
type ParamInfo = {
name: string;
type: string | null;
@@ -20,9 +16,21 @@ type HelperDoc = {
async: boolean;
};
+// Helper docs are extracted from the bundle at build time and injected here by
+// scripts/build.mjs, which replaces the placeholder below with a JSON string.
+// The runtime must never introspect its own source: in the shipped browser the
+// SDK is loaded from a compiled .pak resource whose import.meta.url is
+// "ego://services/node/resources/index.js", which is not a readable file, so
+// the previous readFileSync(fileURLToPath(import.meta.url)) approach silently
+// produced an empty docs map. See GitHub issue #84.
+const EMBEDDED_DOCS_JSON = "__EGO_EMBEDDED_HELP_DOCS__";
+
let cache: Map<string, HelperDoc> | null = null;
-export function help(helpers: Record<string, unknown>, ...names: string[]): HelperDoc | HelperDoc[] | string {
+export function help(
+ helpers: Record<string, unknown>,
+ ...names: string[]
+): HelperDoc | HelperDoc[] | string {
const docs = getDocsMap();
if (names.length === 0) {
const all = [...docs.values()].filter((d) => d.name in helpers);
@@ -33,7 +41,17 @@ export function help(helpers: Record<string, unknown>, ...names: string[]): Help
if (!doc) return `Unknown helper: ${names[0]}`;
return doc;
}
- return names.map((n) => docs.get(n) || { name: n, signature: n, description: null, params: [], returns: null, async: false });
+ return names.map(
+ (n) =>
+ docs.get(n) || {
+ name: n,
+ signature: n,
+ description: null,
+ params: [],
+ returns: null,
+ async: false,
+ },
+ );
}
export function formatHelp(doc: HelperDoc): string {
@@ -46,7 +64,9 @@ export function formatHelp(doc: HelperDoc): string {
const type = p.type ? `: ${p.type}` : "";
const desc = p.description ? ` — ${p.description}` : "";
const def = p.default ? ` (default: ${p.default})` : "";
- lines.push(`@param ${p.rest ? "..." : ""}${p.name}${opt}${type}${desc}${def}`);
+ lines.push(
+ `@param ${p.rest ? "..." : ""}${p.name}${opt}${type}${desc}${def}`,
+ );
}
if (doc.returns) {
lines.push(`@returns ${doc.returns}`);
@@ -59,196 +79,19 @@ export function formatHelp(doc: HelperDoc): string {
function getDocsMap(): Map<string, HelperDoc> {
if (cache) return cache;
cache = new Map();
- const source = readSelf();
- if (!source) return cache;
-
- const comments: any[] = [];
- let ast: any;
- try {
- ast = parse(source, {
- ecmaVersion: "latest",
- sourceType: "module",
- onComment: comments,
- locations: true
- });
- } catch {
- return cache;
+ for (const doc of parseEmbeddedDocs(EMBEDDED_DOCS_JSON)) {
+ cache.set(doc.name, doc);
}
-
- const commentsByEndLine = new Map<number, any>();
- for (const c of comments) {
- if (c.type === "Block") {
- commentsByEndLine.set(c.loc.end.line, c);
- }
- }
-
- walkFunctions(ast, (node: any) => {
- const name = extractFunctionName(node);
- if (!name) return;
-
- const startLine = node.loc.start.line;
- const jsDoc = commentsByEndLine.get(startLine - 1);
- const parsed = jsDoc ? parseJSDoc(jsDoc.value) : null;
-
- const params = extractParams(node, parsed);
- const isAsync = node.async === true;
- const paramSig = params.map((p) => {
- const rest = p.rest ? "..." : "";
- const opt = p.optional ? "?" : "";
- return `${rest}${p.name}${opt}`;
- }).join(", ");
- const retStr = parsed?.returns || (isAsync ? "Promise<...>" : null);
- const signature = `${name}(${paramSig})${retStr ? ` → ${retStr}` : ""}`;
-
- cache!.set(name, {
- name,
- signature,
- description: parsed?.description || null,
- params,
- returns: retStr,
- async: isAsync
- });
- });
-
- walkAliases(ast, (name: string, target: string) => {
- const existing = cache!.get(target);
- if (existing && !cache!.has(name)) {
- cache!.set(name, { ...existing, name });
- }
- });
-
return cache;
}
-function readSelf(): string | null {
+function parseEmbeddedDocs(raw: string): HelperDoc[] {
+ // If the build injection did not run (e.g. importing raw TypeScript), `raw`
+ // is still the placeholder and JSON.parse throws; there are simply no docs.
try {
- const selfPath = fileURLToPath(import.meta.url);
- return readFileSync(selfPath, "utf-8");
+ const parsed = JSON.parse(raw);
+ return Array.isArray(parsed) ? parsed : [];
} catch {
- return null;
- }
-}
-
-function walkFunctions(node: any, visitor: (node: any) => void) {
- if (!node || typeof node !== "object") return;
- if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression") {
- visitor(node);
- }
- for (const key of Object.keys(node)) {
- if (key === "type" || key === "loc" || key === "start" || key === "end") continue;
- const child = node[key];
- if (Array.isArray(child)) {
- for (const item of child) {
- if (item && typeof item.type === "string") walkFunctions(item, visitor);
- }
- } else if (child && typeof child.type === "string") {
- walkFunctions(child, visitor);
- }
+ return [];
}
}
-
-function walkAliases(node: any, visitor: (name: string, target: string) => void) {
- if (!node || typeof node !== "object") return;
- if (node.type === "VariableDeclaration") {
- for (const decl of node.declarations || []) {
- if (decl.id?.type === "Identifier" && decl.init?.type === "Identifier") {
- visitor(decl.id.name, decl.init.name);
- }
- }
- }
- for (const key of Object.keys(node)) {
- if (key === "type" || key === "loc" || key === "start" || key === "end") continue;
- const child = node[key];
- if (Array.isArray(child)) {
- for (const item of child) {
- if (item && typeof item.type === "string") walkAliases(item, visitor);
- }
- } else if (child && typeof child.type === "string") {
- walkAliases(child, visitor);
- }
- }
-}
-
-function extractFunctionName(node: any): string | null {
- if (node.id?.name) return node.id.name;
- return null;
-}
-
-function extractParams(node: any, jsdoc: ParsedJSDoc | null): ParamInfo[] {
- return (node.params || []).map((p: any) => {
- const info = resolveParam(p);
- const jsdocParam = jsdoc?.params.find((jp) => jp.name === info.name);
- return {
- ...info,
- type: jsdocParam?.type || null,
- description: jsdocParam?.description || null
- };
- });
-}
-
-type ParsedJSDoc = {
- description: string | null;
- params: Array<{ name: string; type: string | null; description: string | null }>;
- returns: string | null;
-};
-
-function parseJSDoc(raw: string): ParsedJSDoc {
- const lines = raw.split("\n").map((l) => l.replace(/^\s*\*\s?/, "").trim());
- const descLines: string[] = [];
- const params: ParsedJSDoc["params"] = [];
- let returns: string | null = null;
-
- for (const line of lines) {
- const paramMatch = line.match(/^@param\s+(?:\{([^}]*)\}\s+)?(\[?\w+\]?)(?:(?:\s+[-–—]\s*|\s+)(.+))?\s*$/);
- if (paramMatch) {
- const name = paramMatch[2].replace(/^\[|\]$/g, "");
- params.push({ name, type: paramMatch[1] || null, description: paramMatch[3] || null });
- continue;
- }
- const returnsMatch = line.match(/^@returns?\s+(?:\{([^}]*)\}\s*)?(.*)/);
- if (returnsMatch) {
- returns = returnsMatch[1] || returnsMatch[2] || null;
- continue;
- }
- if (line.startsWith("@")) continue;
- if (line) descLines.push(line);
- }
-
- return {
- description: descLines.join(" ").trim() || null,
- params,
- returns
- };
-}
-
-function resolveParam(node: any): { name: string; optional: boolean; rest: boolean; default: string | null } {
- if (node.type === "RestElement") {
- const inner = resolveParam(node.argument);
- return { ...inner, rest: true, optional: true };
- }
- if (node.type === "AssignmentPattern") {
- const inner = resolveParam(node.left);
- const defStr = nodeToString(node.right);
- return { ...inner, optional: true, default: defStr };
- }
- if (node.type === "Identifier") {
- return { name: node.name, optional: false, rest: false, default: null };
- }
- if (node.type === "ObjectPattern") {
- const props = (node.properties || []).map((p: any) => p.key?.name || "?").join(", ");
- return { name: `{${props}}`, optional: false, rest: false, default: null };
- }
- if (node.type === "ArrayPattern") {
- return { name: "[...]", optional: false, rest: false, default: null };
- }
- return { name: "?", optional: false, rest: false, default: null };
-}
-
-function nodeToString(node: any): string {
- if (!node) return "?";
- if (node.type === "Literal") return JSON.stringify(node.value);
- if (node.type === "ObjectExpression") return "{}";
- if (node.type === "ArrayExpression") return "[]";
- if (node.type === "Identifier") return node.name;
- return "...";
-}