// Code mode in a page: headless Chrome (atlibs docs/browser.mjs) compiles in a Web Worker and runs the // code on the page's own atlibs engine (createPluginContext: a Worker per event, the memory cap). import assert from "node:assert/strict"; import { fileURLToPath } from "node:url"; import { test } from "node:test"; import { CHROME, browse } from "../../atlibs/docs/browser.mjs"; const root = fileURLToPath(new URL("../..", import.meta.url)); // atlibs and atlibs-code-mode side by side const nm = "/atlibs-code-mode/node_modules"; // what a page that uses code mode puts in its import map: asc, its two dependencies and atlibs const imports = { "assemblyscript/asc": `${nm}/assemblyscript/dist/asc.js`, assemblyscript: `${nm}/assemblyscript/dist/assemblyscript.js`, binaryen: `${nm}/binaryen/index.js`, long: `${nm}/long/index.js`, "@publicdomainrelay/atlibs/": "/atlibs/javascript/src/" }; const index = ``; test("a page compiles and runs AssemblyScript through the MCP server", { skip: !CHROME && "no Chrome (set CHROME)", timeout: 120000 }, async () => { const out = await browse(async ({ open, evaluate }) => { await open("/"); return evaluate(`(async () => { const { codeMode } = await import("/atlibs-code-mode/js/index.js"); const { createPluginContext } = await import("@publicdomainrelay/atlibs/plugin-context/index.js"); const mcp = codeMode({ ctx: createPluginContext({ id: "code-mode-test", wasmTimeoutMs: 1000 }) }); const call = async (code) => JSON.parse((await mcp.message({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "run_assemblyscript", arguments: { code, input: { n: 20 } } } })).result.content[0].text); return { ok: await call('export function main(run: Run): void { print("in a page"); run.finish(Json.number(run.input.get("n").num + 22)); }'), loop: await call("export function main(run: Run): void { while (true) {} }"), }; })()`); }, { root, index }); assert.deepEqual(out.ok, { stdout: "in a page\n", result: 42 }); assert.match(out.loop.error, /^WASM_TIMEOUT/); });