// A function a page carries by its SOURCE TEXT reaches nothing outside itself. // // Three places send a module function into a browser as text: `embedFn` // (chrome-posts.mjs: the posts' and the feed's planners), shoot-page.mjs's // `pageExpression`, and every `page.evaluate(fn)` (playwright sends // `fn.toString()`). The text is the function's body as it is in the running // process -- and in a built umtool that is the bundler's: every module-scope // name (an import, a constant, a helper) is minified, and the page has nothing // called that. 11 Nov: `postsCues` called `settleFirstFrame`, the built app's // posts preview threw `ReferenceError: h is not defined`, and no unit test saw // it, because here the name is its own. // // So: each embedded function's text is parsed alone and every name it does not // declare itself must be a global of the language (or, for a page function, // of the DOM). And the sources are scanned, so a function embedded tomorrow is // held to it too -- or the scan fails and says to list it here. // // Run: node --test umtool/report-to-video/embedded-source.test.mjs import { test } from "node:test"; import assert from "node:assert/strict"; import { readdirSync, readFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import ts from "typescript"; import { embedFn, postsCues, postsPlan } from "./chrome-posts.mjs"; import { settleFirstFrame } from "./cue-start.mjs"; import { browserShoot, markCrop, matchWith, normaliseWithMap, pageExpression } from "./shoot-page.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); /** The language's own. */ const ES = ["Array", "Boolean", "Infinity", "JSON", "Map", "Math", "NaN", "Number", "Object", "Set", "String", "isFinite", "parseFloat", "parseInt"]; /** What a page has besides. */ const DOM = ["document", "getComputedStyle", "window"]; /** * Every function sent to a page by name: module -> its functions, and whether * they run on a document (`dom`) or are pure. `embedFn` and `page.evaluate` * arguments found in the sources must all be here (the scan below). */ const EMBEDDED = { "chrome-posts.mjs": { fns: ["postsPlan"] }, "cue-start.mjs": { fns: ["settleFirstFrame"] }, "chrome-feed.mjs": { fns: ["feedCues", "feedShotRoom", "feedShotLone", "feedShotWhole"] }, "post-clock.mjs": { dom: true, fns: ["mountClock", "setClockState", "measureClockPlace"] }, "read-follow.mjs": { dom: true, fns: ["measureFollow", "applyFollowState"] }, "post-link-visit.mjs": { dom: true, fns: ["applyVisitState"] }, "post-join.mjs": { dom: true, fns: ["applyJoinState"] }, "post-branch-map.mjs": { dom: true, fns: ["applyMapState"] }, "post-caption.mjs": { dom: true, fns: ["mountCaptions", "measureCaptionWords", "setCaptionState"] }, "post-slam.mjs": { dom: true, fns: ["mountSlams", "setSlamState"] }, "post-progress.mjs": { dom: true, fns: ["mountProgress", "measureProgressPlace", "setProgressState"] }, // shoot-page.mjs's pageExpression carries these as expressions: each its own body alone (its helpers handed in). "shoot-page.mjs": { dom: true, extra: ["CSS"], fns: ["normaliseWithMap", "matchWith", "markCrop", "browserShoot"] }, }; const LISTED = new Set(Object.values(EMBEDDED).flatMap((m) => m.fns)); /** * The names an expression's text uses and does not declare, by the compiler's * own name resolution with no library at all (so `Math` is one of them). */ function freeNames(expr) { const file = "/embedded.ts"; const sf = ts.createSourceFile(file, `const __embedded = (${expr});\nexport {};\n`, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS); const host = { getSourceFile: (f) => (f === file ? sf : undefined), getDefaultLibFileName: () => "lib.d.ts", writeFile() {}, getCurrentDirectory: () => "/", getCanonicalFileName: (f) => f, useCaseSensitiveFileNames: () => true, getNewLine: () => "\n", fileExists: (f) => f === file, readFile: () => undefined, }; const program = ts.createProgram([file], { noLib: true, noEmit: true, types: [], target: ts.ScriptTarget.ES2022 }, host); assert.deepEqual(program.getSyntacticDiagnostics(sf).map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n")), [], "the text parses"); const names = new Set(); for (const d of program.getSemanticDiagnostics(sf)) { const m = /^Cannot find name '([^']+)'/.exec(ts.flattenDiagnosticMessageText(d.messageText, "\n")); if (m) names.add(m[1]); } return [...names].sort(); } const outside = (expr, allowed) => freeNames(expr).filter((n) => !allowed.includes(n)); test("freeNames: a name the text does not declare is found; its parameters, locals and own name are not", () => { assert.deepEqual(freeNames("function f(a, { b = 1 }) { const c = a + b; return f(c) + outer + Math.max(1, helper(a)); }"), ["Math", "helper", "outer"]); assert.deepEqual(freeNames("(a) => { for (const k of Object.keys(a)) if (typeof gone === 'undefined') return k; }"), ["Object", "gone"]); // What the bundler makes of a module function that calls an import. assert.deepEqual(outside("function d(a){return{cues:h(a)}}", ES), ["h"]); }); for (const [mod, { fns, dom, extra = [] }] of Object.entries(EMBEDDED)) { test(`${mod}: ${fns.join(", ")} -- nothing outside the function's own body but ${dom ? "the language's and the DOM's" : "the language's"} globals`, async () => { const m = await import(`./${mod}`); for (const name of fns) { assert.equal(typeof m[name], "function", `${mod} exports ${name}`); assert.deepEqual(outside(m[name].toString(), [...(dom ? [...ES, ...DOM] : ES), ...extra]), [], `${name} is sent to a page as its source text: a module-scope name in it is minified in a built umtool and undefined in the page -- hand it in as a parameter`); } }); } test("shoot-page: the expression it sends declares every function it calls", () => { assert.deepEqual(outside(pageExpression({ quote: "q" }), [...ES, ...DOM, "CSS"]), []); }); test("shoot-page: the expression works when the bundler has renamed every function -- nothing is called by its own name", () => { // What a built umtool's functions look like: the same bodies under other names (the module's own names are gone). const renamed = (fn, as) => fn.toString().replace(/^function\s+[A-Za-z_$][\w$]*\s*\(/, `function ${as}(`); const minified = pageExpression({ quote: "q" }) .replace(normaliseWithMap.toString(), renamed(normaliseWithMap, "a")) .replace(matchWith.toString(), renamed(matchWith, "b")) .replace(markCrop.toString(), renamed(markCrop, "c")) .replace(browserShoot.toString(), renamed(browserShoot, "d")); assert.ok(!/\bfunction (normaliseWithMap|matchWith|markCrop|browserShoot)\(/.test(minified), "every name replaced"); assert.deepEqual(outside(minified, [...ES, ...DOM, "CSS"]), []); // The renamed helpers still match through the page's own names. const h = new Function(`return { normaliseWithMap: (${renamed(normaliseWithMap, "a")}), matchWith: (${renamed(matchWith, "b")}) };`)(); const m = h.matchWith(h.normaliseWithMap, ["He said \u201cno\u201d ", "today."], 'said "no" today', null); assert.equal(m.ok, true); assert.deepEqual([m.start, m.end], [{ segment: 0, offset: 3 }, { segment: 1, offset: 5 }]); }); test("the posts' page: its planner runs on its text alone, under names no module has, and is the module's plan", () => { // The page's own lines, in a scope with nothing of this module in it. const run = new Function("args", `${embedFn("settleFirstFrame", settleFirstFrame)}\n${embedFn("postsPlan", postsPlan)}\nreturn postsPlan(args, settleFirstFrame);`); const args = { posts: [{ id: "a", appear: 0, out: [8, 8.5] }, { id: "b", appear: 3, out: [8, 8.5] }, { id: "c", appear: 5, out: [8, 8.5] }], heights: [300, 300, 300], pans: [0, 120, 0], column: 700, }; const plan = run(structuredClone(args)); assert.deepEqual(plan, postsCues(structuredClone(args))); assert.ok(plan.cues.length > 6); // The first card's entrance starts at the cut's first instant and is a real move: it stays a cue. assert.ok(plan.cues.some((c) => c.k === "c0" && c.at === 0)); }); /** Every call in a source file, with its callee's last name. */ function callsIn(file) { const sf = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS); const out = []; const walk = (node) => { if (ts.isCallExpression(node)) { const callee = ts.isPropertyAccessExpression(node.expression) ? node.expression.name.text : ts.isIdentifier(node.expression) ? node.expression.text : null; if (callee) out.push({ callee, node, sf }); } ts.forEachChild(node, walk); }; walk(sf); return out; } const SOURCES = [HERE, path.join(HERE, "modules")] .flatMap((dir) => readdirSync(dir).filter((f) => f.endsWith(".mjs") && !f.endsWith(".test.mjs")).map((f) => path.join(dir, f))); test("the scan: every function a source embeds (embedFn, page.evaluate) is listed above, and an inline one is self-contained", () => { let embeds = 0; let evaluates = 0; for (const file of SOURCES) { const rel = path.relative(HERE, file); for (const { callee, node, sf } of callsIn(file)) { const at = () => `${rel}:${sf.getLineAndCharacterOfPosition(node.getStart()).line + 1}`; if (callee === "embedFn" && node.arguments.length === 2) { const fn = node.arguments[1]; assert.ok(ts.isIdentifier(fn), `${at()}: embedFn takes a module function by name`); assert.ok(LISTED.has(fn.text), `${at()}: ${fn.text} is embedded in a page -- list it in EMBEDDED (embedded-source.test.mjs)`); embeds += 1; } if (callee === "evaluate" && node.arguments.length) { const fn = node.arguments[0]; evaluates += 1; if (ts.isIdentifier(fn)) { assert.ok(LISTED.has(fn.text), `${at()}: ${fn.text} is sent to a page -- list it in EMBEDDED (embedded-source.test.mjs)`); } else if (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) { assert.deepEqual(outside(fn.getText(sf), [...ES, ...DOM]), [], `${at()}: the function sent to the page uses a name from outside itself`); } else { // Text built here: a literal, or shoot-page's expression (its own test above). const text = fn.getText(sf); assert.ok(ts.isStringLiteralLike(fn) || /^pageExpression\(/.test(text), `${at()}: page.evaluate(${text.slice(0, 40)}) -- neither a function nor a known expression`); } } } } // The scan found what is there today (a regex that stopped matching would pass on nothing). assert.ok(embeds >= 5, `embedFn calls found: ${embeds}`); assert.ok(evaluates >= 40, `page.evaluate calls found: ${evaluates}`); });