Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit d0602d86a28087af31bccc4f3fc34d3f14733f0e
parent 3ae8cea8caf2e6d0f2adbbc75b6516e712dcb6fa
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 09:17:17 -0500

umtool: drift tracks speed, and shoot-page's page script is held to the embedded-function rule -- a picked read synthesized at another speed than it would be asked at now (castProject.mjs resolverFor: readSpeedOf over a thread read's own --speed, the item's own speed for his words, the preset's) is drift as a changed voice is (cast.mjs voiceDrift: a single take by its speed, a thread read by each part's; "kokoro:am_michael ×1.1" -> "×1.25" only where a speed is involved; Orpheus and converted reads never by speed); shoot-page.mjs pageExpression carries normaliseWithMap, matchWith (matchInSegments with its normaliser handed in) and markCrop as expressions under the page's own names and calls browserShoot as an expression with them handed in, so nothing is called by a name the bundler minifies; embedded-source.test.mjs lists the four and runs the expression with every function renamed

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Meditor/CHANGELOG.md | 2++
Mumtool/docs/knobs.md | 3+++
Mumtool/lib/report/castProject.mjs | 15+++++++++++----
Aumtool/lib/report/driftSpeed.test.mjs | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/cast.mjs | 31+++++++++++++++++++++++--------
Mumtool/report-to-video/embedded-source.test.mjs | 25++++++++++++++++++++++---
Mumtool/report-to-video/shoot-page.mjs | 34+++++++++++++++++++++++-----------
Mumtool/report-to-video/shoot-page.test.mjs | 10++++++----
8 files changed, 144 insertions(+), 30 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,8 @@ # Changelog ## [Unreleased] +- **umtool: a character's changed speed shows its reads as stale.** Changing a character's preset speed left every read made at the old speed looking current: drift compared voices only. A picked read synthesized at another speed than the one it would be asked at now (the item's own, else the preset's; a thread read keeps the `--speed` it was made with) is now listed as drift on the Voices page, in `umtool cast project` and in `umtool lint`, as "kokoro:am_michael ×1.1 → ×1.25", and `cast reread` re-reads it. Orpheus reads and converted recordings never drift by speed. +- **umtool: the quote shooter's page script no longer depends on its functions' names.** `shoot-page.mjs` sent its matcher into the page as function source and called the functions by name; in a built umtool those names are minified, which is how the posts preview failed with "h is not defined" last week. The helpers now travel as expressions under names of the page's own, and the embedded-source test holds each of them to its own body, including with every name changed. - **umtool: a thread read can use your recorded line.** `umtool posts narrate <p> <item> --take --thread` synthesized every part, so an operator's recorded (or recorded-and-converted) read of his own line could not sit in a thread read: the item then played his line alone and the post it answers went unread. `--post-take <n>` (the take's number as `--list` shows it) now makes his line that take, while the posts it answers, quotes and links are synthesized in their authors' voices around it. Each part of the new take says where it came from (a synthesized part its cached file and voice, the take's part its file and the take's id), the read records which take it used, and a re-read after a voice change names it again. A thread take, or a take whose file is gone, is refused. `--speed` on a thread read reaches every synthesized part (it has since the character presets landed; a test now holds it). - **umtool: an anonymous character is anonymous on screen too.** An anonymous character of a video ("Anon 1") went by its shown name only on umtool's own pages: the cut's post card still showed the author's name, handle and picture. Now the build and Play draw that author under the shown name wherever a card draws them -- the item's head, the strip, the posts it answers, quotes and links, a repost line, "Replying to", a thread read's and a scene's tiles, a side card, the vertical cut, the chapters -- with no handle, no verified badge and a neutral avatar (the shown name's initial on the card's muted colour). A mention of their handle in the words the card shows becomes `@Anon_1`, and a reply's captured thread shot that shows them is not drawn. A cut with no anonymous character renders exactly as before; a `narration/characters.json` the build cannot read now stops the build rather than show a real name. What a read says is unchanged. - **umtool: the Voices page proposes characters and you accept, change or reject each.** A new "proposed" section: **Propose characters** runs the same rule as `umtool cast assign` (no model is needed or asked), each proposal shows its voice, why it was chosen and the items it would be named on, and **Accept**, **Change** (another stock voice, the name, anonymous) and **Reject** each go through the same writer as the CLI. Accepting never touches a picked read: one in another voice is listed as drift, as before. diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -1488,6 +1488,9 @@ human-filtered voices". A character carries two, picked by how the read is made: the tts op's; absent: 1). Speed is the only parameter the tts op takes beside the voice (Orpheus's emotion is in the script, its `<sigh>` `<laugh>` tags; Orpheus has no speed and is asked none). It reaches a single take, the bench's Re-take and every part of a thread read; `--speed` on the command wins, then the item's own `narration.speed`. + A picked read synthesized at another speed than the one it would be asked at now is **drift**, as one in another + voice is (`umtool cast project <p>`, the Voices page, `umtool lint`: "kokoro:am_michael ×1.1 -> ×1.25"; a thread read + made with `--speed` keeps it as asked; Orpheus and a converted recording never drift by speed). - **`recorded`** -- a recording of them made their read: `convert` `{engine, voice, pitch, semitones}` (the target is ALWAYS a stock synthetic voice: validation refuses a file, a path or a recording, in the cast and in a project's own characters), `enhance` (cleaned first by the editor's voice-enhance; absent: yes), `trim` `{on, padMs}` (its diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs @@ -7,7 +7,7 @@ // // Plain ESM. import { postNarrationKnobs } from "umtool-report-to-video/post-narration"; -import { handleKey, resolvePieceVoice, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say"; +import { handleKey, readSpeedOf, resolvePieceVoice, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say"; import { castDrift, castPresetMap, characterForRead, characterOf, charactersOf, convertTargetOf, itemCharacterOf, itemPresetOf, narratorOf, projectCharactersOf, projectPresetMap, proposalsOf, recordedPresetOf, shownNameOf, speakerFor, takeReads, voiceDrift, ENGINE_WEIGHT, @@ -19,8 +19,11 @@ const str = (v) => (typeof v === "string" ? v : ""); /** * The voice a piece of a picked read would be said in NOW, as the read that made it would ask (its own --voice-for * and --voice kept: an override made on purpose): `(e, role, handle, take, read) => { engine, voice, from, speed?, - * character? }`. A read converted from a recording is compared with its character's convert target (the chain's: - * cast.mjs characterForRead), else not at all. `project` is the project's own characters (characters.json's document). + * character? }`. `speed` is the speed it would be asked at now, as the read would ask it (post-say.mjs readSpeedOf: the + * thread read's own --speed, else the item's own for his words, else the preset's; none for Orpheus or at 1) -- so a + * preset whose speed changed shows its reads as drift. A read converted from a recording is compared with its + * character's convert target (the chain's: cast.mjs characterForRead), else not at all. `project` is the project's + * own characters (characters.json's document). */ export function resolverFor({ map = {}, cast = null, project = null, render = {} }) { const castMap = castPresetMap(cast); @@ -33,10 +36,14 @@ export function resolverFor({ map = {}, cast = null, project = null, render = {} } const k = postNarrationKnobs(e, render); const tr = take?.read?.kind === "thread" ? take.read : null; - return resolvePieceVoice({ handle, role }, { + const v = resolvePieceVoice({ handle, role }, { map: layer, cast: castMap, item: itemPresetOf(e, { project, cast }), overrides: tr?.voiceFor ?? {}, voice: tr?.voice ?? null, self: e.handle ?? null, narrator: e.narration?.voice ?? k.voice, engine: e.narration?.engine ?? k.engine, }); + const own = role === "post" && handleKey(handle) === handleKey(e.handle) ? e.narration?.speed ?? null : null; + const speed = readSpeedOf({ flag: typeof tr?.speed === "number" ? tr.speed : null, preset: v.speed ?? null, own, engine: v.engine }); + const { speed: _preset, ...rest } = v; + return { ...rest, ...(speed !== null ? { speed } : {}) }; }; } diff --git a/umtool/lib/report/driftSpeed.test.mjs b/umtool/lib/report/driftSpeed.test.mjs @@ -0,0 +1,54 @@ +// DRIFT TRACKS SPEED (cast.mjs voiceDrift, castProject.mjs resolverFor): a picked read synthesized at another speed +// than its character's preset asks now is stale, as one in another voice is -- a single take by its `speed`, a thread +// read by each part's; the item's own speed and a thread read's own --speed answer before the preset; Orpheus (no +// speed) and a converted recording never drift by speed. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { projectCharacters, rereadPlan } from "./castProject.mjs"; + +const cast = (speed) => ({ + format: "umtool-cast", version: 2, + characters: [ + { id: "host", name: "Host", handles: ["host"], synthetic: { voice: "kokoro:am_michael", ...(speed ? { speed } : {}) } }, + { id: "guest", name: "Guest", handles: ["guest"], synthetic: { voice: "kokoro:bf_emma", speed: 0.9 } }, + { id: "orph", name: "Orph", handles: ["orph"], synthetic: { voice: "orpheus:zac" } }, + ], +}); +const single = (o = {}) => ({ file: "narration/posts/1/take-1.kokoro.wav", engine: "kokoro", voice: "am_michael", seconds: 2, script: "Hi.", ...o }); +const post = (id, handle, narration, o = {}) => ({ type: "post", id, handle, author: handle, text: "words", narration, ...o }); +const m = (...timeline) => ({ render: { postNarration: { engine: "kokoro", voice: "af_heart" } }, timeline }); +const driftOf = (manifest, c) => projectCharacters(manifest, { cast: c }).characters.flatMap((x) => x.drift); + +test("a single take at another speed than the preset now is drift; at the same, or 1 against none, it is not", () => { + const at11 = m(post("p1", "host", { takes: [single({ speed: 1.1 })], pick: 0 })); + assert.deepEqual(driftOf(at11, cast(1.1)), []); + const rows = driftOf(at11, cast(1.3)); + assert.deepEqual(rows.map((r) => [r.id, r.role, r.reads, r.want, r.from]), [["p1", "post", "kokoro:am_michael ×1.1", "kokoro:am_michael ×1.3", "cast"]]); + // A take with no speed against a preset that has one now: stale. None and 1 are one. + assert.equal(driftOf(m(post("p1", "host", { takes: [single()], pick: 0 })), cast(1.2)).length, 1); + assert.deepEqual(driftOf(m(post("p1", "host", { takes: [single({ speed: 1 })], pick: 0 })), cast(null)), []); + // A changed voice reads as before (no speed said where none is). + assert.deepEqual(driftOf(m(post("p1", "host", { takes: [single({ voice: "am_adam" })], pick: 0 })), cast(null)).map((r) => [r.reads, r.want]), [["kokoro:am_adam", "kokoro:am_michael"]]); + // The item's own speed answers before the preset (as a new take would be asked). + assert.deepEqual(driftOf(m(post("p1", "host", { speed: 1.1, takes: [single({ speed: 1.1 })], pick: 0 })), cast(1.3)), []); + // The re-read it asks for. + const plan = rereadPlan("p", at11, rows, ["host"]); + assert.deepEqual(plan.items.map((x) => x.argv), [["posts", "narrate", "p", "p1", "--take"]]); +}); + +test("a thread read's parts: each at its preset's speed now; the read's own --speed kept as asked; Orpheus never by speed", () => { + const parts = (hostSpeed, guestSpeed) => [ + { n: 1, role: "parent:0", voice: "bf_emma", engine: "kokoro", ...(guestSpeed ? { speed: guestSpeed } : {}), text: "q", file: "narration/parts-cache/a.wav", start: 0, seconds: 1 }, + { n: 2, role: "post", voice: "am_michael", engine: "kokoro", ...(hostSpeed ? { speed: hostSpeed } : {}), text: "a", file: "narration/parts-cache/b.wav", start: 1.8, seconds: 1 }, + ]; + const thread = (p, read = { kind: "thread", parents: "0" }) => ({ file: "narration/posts/1/take-2.kokoro-thread.wav", engine: "kokoro", voice: "bf_emma+am_michael", seconds: 3, script: "q\n\na", parts: p, read }); + const e = (t) => post("p1", "host", { takes: [t], pick: 0 }, { parents: [{ id: "9", handle: "guest", author: "Guest", text: "q" }] }); + assert.deepEqual(driftOf(m(e(thread(parts(1.1, 0.9)))), cast(1.1)), []); + const rows = driftOf(m(e(thread(parts(1.1, 0.9)))), cast(1.25)); + assert.deepEqual(rows.map((r) => [r.role, r.reads, r.want, r.thread]), [["post", "kokoro:am_michael ×1.1", "kokoro:am_michael ×1.25", true]]); + // A read made with --speed 1.4: that is how it was asked, kept -- no drift while its parts are at it. + assert.deepEqual(driftOf(m(e(thread(parts(1.4, 1.4), { kind: "thread", parents: "0", speed: 1.4 }))), cast(1.25)), []); + // Orpheus has no speed: never drift by one. + const orph = post("p2", "orph", { takes: [{ file: "narration/posts/2/take-1.orpheus.wav", engine: "orpheus", voice: "zac", seconds: 2, script: "x" }], pick: 0 }); + assert.deepEqual(driftOf(m(orph), cast(null)), []); +}); diff --git a/umtool/report-to-video/cast.mjs b/umtool/report-to-video/cast.mjs @@ -578,9 +578,10 @@ function playing(e) { } /** - * WHAT A PICKED TAKE READS EACH AUTHOR IN, pure: `[{ handle, role, engine, voice, kind }]` -- a thread read by its + * WHAT A PICKED TAKE READS EACH AUTHOR IN, pure: `[{ handle, role, engine, voice, kind, speed? }]` -- a thread read by its * parts (each part's role and voice; its engine, else the take's), a single read as his post; `kind` "tts", - * "recorded" (a person's own voice: `voice` is its label) or "converted" (a recording made a stock voice). + * "recorded" (a person's own voice: `voice` is its label) or "converted" (a recording made a stock voice). `speed`: the + * speed a synthesized read was asked at (a part's, a single take's), when it was asked one. */ export function takeReads(e, take = playing(e)) { if (!take) return []; @@ -608,23 +609,30 @@ export function takeReads(e, take = playing(e)) { seen.set(key, r ? { ...r, role: p.role, handle: handleOfRole(e, p.role) } : { handle: handleOfRole(e, p.role), role: p.role, engine: null, voice: p.voice, kind: "recorded" }); continue; } - seen.set(key, { handle: handleOfRole(e, p.role), role: p.role, engine: str(p.engine) || str(take.engine) || null, voice: p.voice, kind: "tts" }); + seen.set(key, { handle: handleOfRole(e, p.role), role: p.role, engine: str(p.engine) || str(take.engine) || null, voice: p.voice, kind: "tts", ...(typeof p.speed === "number" ? { speed: p.speed } : {}) }); } return [...seen.values()]; } - return [{ handle: str(e?.handle) || null, role: "post", engine: str(take.engine) || null, voice: str(take.voice), kind: "tts" }]; + return [{ handle: str(e?.handle) || null, role: "post", engine: str(take.engine) || null, voice: str(take.voice), kind: "tts", ...(typeof take.speed === "number" ? { speed: take.speed } : {}) }]; } /** Two voices the same (`{engine, voice}`; an engine unknown on either side compares by the voice). */ export const sameVoice = (a, b) => !!a && !!b && a.voice === b.voice && (!a.engine || !b.engine || a.engine === b.engine); +/** A speed as the drift compares it: none, or 1, is the voice's own. */ +const speedKey = (s) => (typeof s === "number" && Number.isFinite(s) && s !== 1 ? s : null); +/** Two speeds the same (none and 1 are one). */ +export const sameSpeed = (a, b) => speedKey(a) === speedKey(b); +/** A voice as a drift row says it: "kokoro:am_michael", with its speed when it has one ("kokoro:am_michael ×1.1"). */ +const driftSpec = (v, speed) => `${voiceSpecOf(v)}${speedKey(speed) !== null ? ` ×${speedKey(speed)}` : ""}`; /** Is a take a thread read (its parts in their authors' voices)? */ export const isThreadTake = (t) => t?.read?.kind === "thread" || /-thread\.wav$/.test(str(t?.file)) || (Array.isArray(t?.parts) && new Set(t.parts.map((p) => p?.voice).filter(Boolean)).size > 1); /** * EVERY PICKED READ IN ANOTHER VOICE THAN THE ONE IT WOULD BE READ IN NOW, pure: `[{ id, handle, role, reads, want, - * from, kind, thread }]` -- `resolve(e, role, handle, take, read)` says the voice now (`{ engine, voice, from }`, or - * null: nothing to compare). A recorded read (a person's own voice) is never one. + * from, kind, thread }]` -- `resolve(e, role, handle, take, read)` says the voice now (`{ engine, voice, from, speed? }`, + * or null: nothing to compare). A synthesized read AT ANOTHER SPEED than its preset's now is one too (its `reads` and + * `want` say the speeds: "kokoro:am_michael ×1.1"). A recorded read (a person's own voice) is never one. */ export function voiceDrift(manifest, resolve) { const rows = []; @@ -634,8 +642,15 @@ export function voiceDrift(manifest, resolve) { for (const r of takeReads(e, take)) { if (!r.handle || r.kind === "recorded") continue; const want = resolve(e, r.role, r.handle, take, r); - if (!want || sameVoice({ engine: r.engine, voice: r.voice }, want)) continue; - rows.push({ id: e.id, handle: handleKey(r.handle), role: r.role, reads: voiceSpecOf({ engine: r.engine, voice: r.voice }), want: voiceSpecOf(want), from: want.from ?? null, kind: r.kind, thread: isThreadTake(take) }); + // A converted read is compared by its voice alone (a recording has no tts speed). + const speedToo = r.kind === "tts"; + if (!want || (sameVoice({ engine: r.engine, voice: r.voice }, want) && (!speedToo || sameSpeed(r.speed, want.speed)))) continue; + const withSpeed = speedToo && (speedKey(r.speed) !== null || speedKey(want.speed) !== null); + rows.push({ + id: e.id, handle: handleKey(r.handle), role: r.role, + reads: withSpeed ? driftSpec({ engine: r.engine, voice: r.voice }, r.speed) : voiceSpecOf({ engine: r.engine, voice: r.voice }), + want: withSpeed ? driftSpec(want, want.speed) : voiceSpecOf(want), from: want.from ?? null, kind: r.kind, thread: isThreadTake(take), + }); } } return rows; diff --git a/umtool/report-to-video/embedded-source.test.mjs b/umtool/report-to-video/embedded-source.test.mjs @@ -26,7 +26,7 @@ import ts from "typescript"; import { embedFn, postsCues, postsPlan } from "./chrome-posts.mjs"; import { settleFirstFrame } from "./cue-start.mjs"; -import { pageExpression } from "./shoot-page.mjs"; +import { browserShoot, markCrop, matchWith, normaliseWithMap, pageExpression } from "./shoot-page.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -52,6 +52,8 @@ const EMBEDDED = { "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)); @@ -92,12 +94,12 @@ test("freeNames: a name the text does not declare is found; its parameters, loca assert.deepEqual(outside("function d(a){return{cues:h(a)}}", ES), ["h"]); }); -for (const [mod, { fns, dom }] of Object.entries(EMBEDDED)) { +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), [], + 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`); } }); @@ -107,6 +109,23 @@ 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);`); diff --git a/umtool/report-to-video/shoot-page.mjs b/umtool/report-to-video/shoot-page.mjs @@ -68,9 +68,12 @@ export const DEFAULTS = Object.freeze({ export const CROP_MODES = Object.freeze(["block", "mark"]); // --------------------------------------------------------------------------- -// The matcher. Pure, and SELF-CONTAINED: these two functions are also sent into -// the page as source text (see browserShoot), so neither may reference anything -// outside itself but the other by name and the language's own globals. +// The matcher. Pure, and SELF-CONTAINED: these functions are also sent into the +// page as source text (pageExpression), so none may reference anything outside +// its own body but the language's globals -- not even each other BY NAME: in a +// built umtool every module-scope name is minified, and the page has nothing +// called that (embedded-source.test.mjs, the EMBEDDED-FUNCTION RULE). What one +// needs of another is handed in as a parameter. // --------------------------------------------------------------------------- // `raw` normalised for matching, with `map[k]` = the index in `raw` of the @@ -112,17 +115,22 @@ export function normaliseWithMap(raw) { // `{ segment, offset }` in the RAW segment strings (`end` exclusive, and always // in the segment holding the match's last character), or `{ ok: false, reason }`. export function matchInSegments(segments, quote, context) { - const q = normaliseWithMap(String(quote ?? "")).text.trim(); + return matchWith(normaliseWithMap, segments, quote, context); +} + +/** matchInSegments with its normaliser handed in (`normalise`: normaliseWithMap) -- the form the page carries. */ +export function matchWith(normalise, segments, quote, context) { + const q = normalise(String(quote ?? "")).text.trim(); if (!q) return { ok: false, reason: "empty quote" }; const raw = segments.join(""); - const hay = normaliseWithMap(raw); + const hay = normalise(raw); let occurrences = 0; for (let i = hay.text.indexOf(q); i !== -1; i = hay.text.indexOf(q, i + 1)) occurrences++; let at; if (context != null && String(context).trim()) { - const c = normaliseWithMap(String(context)).text.trim(); + const c = normalise(String(context)).text.trim(); const ci = hay.text.indexOf(c); if (ci === -1) return { ok: false, reason: "context not found", occurrences }; at = hay.text.indexOf(q, ci); @@ -189,7 +197,8 @@ export function markCrop({ rects, lineHeight, content, contextLines, padding, do // the visible text, match, wrap the match in marks, measure what to shoot. // --------------------------------------------------------------------------- -function browserShoot(args) { +// `h`: the helpers it calls, handed in by pageExpression -- `{ normaliseWithMap, matchWith, markCrop }`. +export function browserShoot(args, h) { const { quote, context, color, padding, maxHeight, isolate, cropMode, contextLines } = args; const doc = document; const SKIP = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "TITLE", "HEAD", "SVG", "MATH", "IFRAME", "OBJECT", "SELECT", "TEXTAREA"]); @@ -244,7 +253,7 @@ function browserShoot(args) { for (let i = kids.length - 1; i >= 0; i--) stack.push(kids[i]); } - const m = matchInSegments(segs.map((s) => s.text), quote, context); + const m = h.matchWith(h.normaliseWithMap, segs.map((s) => s.text), quote, context); if (!m.ok) return m; const range = doc.createRange(); @@ -328,7 +337,7 @@ function browserShoot(args) { // computed style; 1.2 × the font size is what browsers use for most fonts. const ps = getComputedStyle(marks[0].parentElement); const lineHeight = parseFloat(ps.lineHeight) || parseFloat(ps.fontSize) * 1.2; - const mc = markCrop({ rects, lineHeight, content, contextLines, padding, docW, docH }); + const mc = h.markCrop({ rects, lineHeight, content, contextLines, padding, docW, docH }); crop = mc.crop; // Mask the padding above and below the lines with the block's own ground, // across its padding box: past that the ground is the page's, and the @@ -412,9 +421,12 @@ function browserShoot(args) { } // The expression handed to page.evaluate: the matcher and the walker as source, -// then a call. A string rather than a function so the helpers travel with it. +// then a call. A string rather than a function so the helpers travel with it -- +// each as an EXPRESSION under a name of the page's own (`h.…`), and the walker +// called as one: a function's own name in its source is whatever the bundler +// made it, so nothing here calls one by that name. export function pageExpression(args) { - return `(() => {\n${normaliseWithMap}\n${matchInSegments}\n${markCrop}\n${browserShoot}\nreturn browserShoot(${JSON.stringify(args)});\n})()`; + return `(() => {\nconst h = { normaliseWithMap: (${normaliseWithMap}), matchWith: (${matchWith}), markCrop: (${markCrop}) };\nreturn (${browserShoot})(${JSON.stringify(args)}, h);\n})()`; } // --------------------------------------------------------------------------- diff --git a/umtool/report-to-video/shoot-page.test.mjs b/umtool/report-to-video/shoot-page.test.mjs @@ -117,11 +117,13 @@ test("context picks the occurrence, and is itself required to be there", () => { test("the page expression carries the matcher with it", () => { const expr = pageExpression({ quote: "a \"b\"", context: null, color: "#ff0", padding: 4, maxHeight: 100 }); - assert.match(expr, /function normaliseWithMap/); - assert.match(expr, /function matchInSegments/); - assert.match(expr, /return browserShoot\(\{"quote":"a \\"b\\""/); + assert.match(expr, /normaliseWithMap: \(function normaliseWithMap/); + assert.match(expr, /matchWith: \(function matchWith/); + // The walker is called as the expression it is, its helpers handed in -- never by its own name. + assert.match(expr, /\}\)\(\{"quote":"a \\"b\\"".*\}, h\);\n\}\)\(\)$/s); + assert.doesNotMatch(expr, /return browserShoot\(/); // It parses as one expression. - assert.doesNotThrow(() => new Function(`return ${expr.replace(/return browserShoot\([^\n]*\);/, "return 0;")}`)); + assert.doesNotThrow(() => new Function(`return ${expr}`)); }); test("only file:// under the page's own directory is allowed", () => {