// CHROME FRAME KEYS: what each frame of a cue-driven chrome page draws, as a // key, computed without a browser -- so a re-render captures only the frames // whose key is new and takes every other from a render already on disk. // // The deck and the fact-check stamps are each ONE page whose script is a dumb // interpreter of a cue list (chrome-deck.mjs explains why): `init` states // every element's properties at t = 0, and every cue is a GSAP fromTo whose // FROM is stated -- the value the cue before it on that element left. So what // a frame at time t draws is a pure function of // // - the page itself, less the cue list (its markup, styles, fonts, assets: // the STATIC part), and // - each element's property values at t: init's, the last finished cue's // `to`, or a running cue's value at its progress. // // A frame's key hashes both. The running values are computed the way GSAP // renders them: its own ease functions (the vendored gsap.min.js, run in a // sandbox), `from + (to - from) * ease(progress)`, rounded as its CSS plugin // rounds (four decimals) -- so two frames with one key set the very same CSS. // Times in the key are the cue's OWN (t - at), never the cut's: a moment the // cut moved (an insert, a longer intro) keys as it did, because the cue // times sit on the sub-frame grid (deck.mjs cueTime) and move exactly. // // The static part leaves out what only times the page or reaches a preview: // the cue list and init (keyed per frame), the window (a preview's window of // the cut keys each frame at its cut time: the same frame keys as the whole // cut's there), the cut's total and // the ids list (preview messages), and every `data-duration` (each the whole // page's; checked). Anything else in the page's data stays in. // // PER-MODULE CACHE RULES (release 39, the video modules). Each module's // `frameKeys` (modules/.mjs) is its model: the data fields left out of // the static part, its own eases, a window's offset -- and two rules that // keep the static part MINIMAL: // // - ASSETS BY CONTENT. A page names its assets by place (`qr03.png`, // `shot07.png`: first seen, first numbered), so a post inserted early // renumbered every one after it. The key reads each asset reference as // its content's hash: an asset is the same asset wherever it is filed. // - ITEMS. A page may hand over its items (`items`: each segment's text, // each pip, each feed card) -- markup a frame draws only while its GATE // is visible: a slot (`gate: [k, prop]`, the item's own opacity or // autoAlpha) that is not 0, or for the feed an event that has happened // (`event`). An item's markup, the assets it names and its slots' values // are in the key of a frame that shows it and of no other, so a changed // subtitle recaptures the frames its clip is on screen, and a clip or // post inserted later leaves the frames before it as they were. // // FRAME_KEY_VERSION 2 is these rules: a render keyed by version 1 is // captured once more, then reused as ever. // // Refused -- `null`, and the layer is rendered whole as before -- when the // page is not one this models: no data script, a `data-duration` that is not // the page's, a window not as long as its frames (or on the feed's page, or a // page with an offset of its own), a cue whose FROM is not what its element holds, two // cues running on one property at once, or a property value that is neither // a number nor a string. Conservative by construction: a frame is reused // only when everything this knows of it is the same. // // Plain node; every path is a parameter. import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; import vm from "node:vm"; import { GSAP_FILE } from "./chrome-deck.mjs"; import { feedCues } from "./chrome-feed.mjs"; import { MODULES } from "./modules/index.mjs"; /** Bumped when what a frame key covers changes: every frame is captured once more. */ export const FRAME_KEY_VERSION = 2; /** * The regions whose pages this models, and the data fields their key leaves * out of the static part: each module's own `frameKeys` (modules/.mjs), * by its region -- the shell's deck, the stamps, the feed (keyed by its * EVENTS: it plans its cues in the page), the finale (a window of the cut). */ export const FRAME_KEY_REGIONS = Object.freeze( Object.fromEntries(MODULES.filter((m) => m.region && m.frameKeys).map((m) => [m.region, m.frameKeys])), ); /** * How long after a feed event (a post in, the column hidden or shown) its * cues can still run, at most: FEED_MOTION's longest chain is under two * seconds. Checked per page (feedFrameKeys) against the plan itself. */ export const FEED_EVENT_CAP = 12; let gsapEase = null; /** GSAP's own ease, by name (the vendored file, in a sandbox, once). */ export function easeOf(name) { if (!gsapEase) { const sandbox = { console, setTimeout, clearTimeout }; sandbox.self = sandbox; vm.createContext(sandbox); vm.runInContext(readFileSync(GSAP_FILE, "utf8"), sandbox, { filename: "gsap.min.js" }); const g = sandbox.window?.gsap ?? sandbox.gsap; if (!g?.parseEase) throw new Error("frame keys: the vendored GSAP did not load"); const cache = new Map(); gsapEase = (n) => { if (!cache.has(n)) cache.set(n, g.parseEase(n)); return cache.get(n); }; } const f = gsapEase(name); if (typeof f !== "function") throw new Error(`frame keys: no ease ${name}`); return f; } /** GSAP's CSS rounding (CSSPlugin: four decimals). */ const gsapRound = (v) => Math.round(v * 10000) / 10000; const sha1 = (s) => createHash("sha1").update(s).digest(); /** The page's data script: its JSON, and the page with that JSON cut out. */ function splitData(html, id) { const open = `", from); if (to < 0) return null; let data; try { data = JSON.parse(html.slice(from, to)); } catch { return null; } return { data, before: html.slice(0, from), after: html.slice(to) }; } /** An asset reference in a page: `assets/`. */ const ASSET_REF = /assets\/([A-Za-z0-9._-]+)/g; /** * A page's text with every asset reference read as its content's hash * (`assets/#`), and the names it referenced. */ function byContent(text, hashOf) { const used = new Set(); const out = text.replace(ASSET_REF, (m, name) => { const h = hashOf.get(name); if (h === undefined) return m; used.add(name); return `assets/#${h}`; }); return { text: out, used }; } /** * The page split into its static part and its items: `{ data, page, items, * assets }`, `page` the static text (the data script less `omit`, every * item's markup out, every asset by content), `items` each `{ key, gate?, * event?, hash }` in page order, `assets` the static part's asset hashes. * null when the page is not modelled. */ function splitPage({ html, region, assets = [], fps, frames = null, items = null }) { const spec = FRAME_KEY_REGIONS[region]; if (!spec) return null; const parts = splitData(html, spec.data); if (!parts) return null; const { data } = parts; // A window of the cut ([from, from + dur], a preview's) keys each frame at // its CUT time, from + n / fps -- the page plays the cut's timeline there -- // so it is modelled when it is as long as its frames, on a page with no // offset of its own and no events. (The whole cut written as one -- a total // off the 4-decimal grid makes deckHtml "window" [0, r4(total)] -- is the identity.) if (data.window) { const w = data.window; if (!Number.isFinite(w.from) || !Number.isFinite(w.dur) || w.from < 0) return null; if (frames == null || Math.abs(w.dur - frames / fps) >= 1 / fps) return null; if (w.from !== 0 && (spec.events || spec.offset)) return null; } if (spec.events ? !(Array.isArray(data.posts) && Array.isArray(data.visibility) && data.grid > 0) : !data.init || !Array.isArray(data.cues)) return null; if (spec.offset && !Number.isFinite(data[spec.offset])) return null; // A page's own eases are modelled only as the page writes them. for (const e of Object.values(spec.eases ?? {})) if (!html.includes(e.page)) return null; // Every data-duration is the page's own (the root and its one clip). const durs = [...html.matchAll(/data-duration="([^"]*)"/g)].map((m) => m[1]); if (!durs.length || durs.some((d) => d !== durs[0])) return null; const starts = [...html.matchAll(/data-start="([^"]*)"/g)].map((m) => m[1]); if (starts.some((x) => x !== "0")) return null; const rest = Object.fromEntries(Object.entries(data).filter(([k]) => !spec.omit.includes(k))); let page = (parts.before + JSON.stringify(rest) + parts.after).replace(/data-duration="[^"]*"/g, 'data-duration=""'); const hashOf = new Map([...assets].map(([n, h]) => [String(n), String(h)])); // The items out of the page, each hashed with the assets it names. const itemOut = []; const itemAssets = new Set(); for (const it of items ?? []) { if (!it || typeof it.html !== "string" || !it.html) return null; const at = page.indexOf(it.html); if (at < 0) return null; // With the whitespace that joins it to what is before it: a page's items // are absolutely placed boxes, and the joins between them are not drawn // -- so a page of n items and one of n + 1 have the same static part. const lead = /\s*$/.exec(page.slice(0, at))[0].length; page = page.slice(0, at - lead) + page.slice(at + it.html.length); const { text, used } = byContent(it.html, hashOf); for (const n of used) itemAssets.add(n); itemOut.push({ key: it.key, at, ...(it.gate ? { gate: it.gate } : {}), ...(Number.isInteger(it.event) ? { event: it.event } : {}), hash: createHash("sha1").update(text).digest("hex"), }); } // In page order (each removal shifts what follows: the order of `at` as removed is not the page's). const ordered = items?.length ? orderItems(html, items, itemOut) : itemOut; const { text: staticText, used } = byContent(page, hashOf); // The static part's assets: every one it names, and every one no item names. const statics = [...hashOf.entries()].filter(([n]) => used.has(n) || !itemAssets.has(n)).map(([, h]) => h).sort(); return { data, page: staticText, items: ordered, assets: statics }; } /** The items in the order their markup stands in the page. */ function orderItems(html, items, out) { const pos = items.map((it) => html.indexOf(it.html)); return out.map((o, i) => ({ o, p: pos[i] })).sort((x, y) => x.p - y.p).map((x) => x.o); } /** * The static part's key: the page less what is keyed per frame (and less * its items), its assets by content, the frame rate and the renderer. null * when the page is not modelled. */ export function staticKey({ html, region, assets = [], fps, version, frames = null, items = null }) { const sp = splitPage({ html, region, assets, fps, frames, items }); if (!sp) return null; return createHash("sha256") .update(JSON.stringify({ v: FRAME_KEY_VERSION, region, page: sp.page, assets: sp.assets, fps, version, items: !!items?.length })) .digest("hex"); } const repr = (v) => (typeof v === "number" ? `n${gsapRound(v)}` : `s${JSON.stringify(v)}`); /** * Every frame's key, `frames` frames at `fps` (frame n at n / fps), or null * when the page is not modelled (see the top of the file). * * @returns {string[] | null} hex keys, frame 1 first */ export function frameKeys({ html, region, assets = [], fps, frames, version, items = null }) { const sk = staticKey({ html, region, assets, fps, version, frames, items }); if (!sk) return null; const sp = splitPage({ html, region, assets, fps, frames, items }); if (FRAME_KEY_REGIONS[region].events) return feedFrameKeys({ html, sk, fps, frames, items: sp.items }); const spec = FRAME_KEY_REGIONS[region]; const { data } = sp; const init = data.init; const cues = data.cues; const t0 = spec.offset ? Number(data[spec.offset]) : data.window ? Number(data.window.from) : 0; const ease = (name) => spec.eases?.[name]?.fn ?? easeOf(name); // Slots: one per (element, property), each with its cues in time order. const slots = new Map(); const slot = (k, p) => { const id = `${k}\u0000${p}`; let s = slots.get(id); if (!s) { s = { id, k, p, initial: init[k] && p in init[k] ? init[k][p] : undefined, cues: [] }; slots.set(id, s); } return s; }; for (const [k, props] of Object.entries(init)) for (const p of Object.keys(props)) slot(k, p); cues.forEach((c, n) => { if (!c || typeof c.k !== "string" || !(c.dur > 0) || !Number.isFinite(c.at)) throw new Error(`frame keys: cue ${n} is malformed`); for (const p of Object.keys(c.to ?? {})) slot(c.k, p).cues.push({ ...c, n }); }); // The model's checks: every FROM is what its element holds, no two cues // run on one property at once, every value a number or a string. const okValue = (v) => typeof v === "number" || typeof v === "string" || v === undefined; for (const s of slots.values()) { s.cues.sort((x, y) => x.at - y.at || x.n - y.n); let held = s.initial; let freeAt = -Infinity; for (const c of s.cues) { const from = c.from?.[s.p]; const to = c.to[s.p]; if (!okValue(from) || !okValue(to) || !okValue(held)) return null; // (Nothing held -- the CSS default -- takes the from the page states for it.) if (held !== undefined && from !== held) return null; if (c.at < freeAt - 1e-9) return null; held = to; freeAt = c.at + c.dur; } } // The value of a slot at time t, as GSAP draws it. const valueAt = (s, t) => { let cur = null; for (const c of s.cues) { if (c.at <= t + 1e-9) cur = c; else break; } if (!cur) return s.initial === undefined ? "u" : `i${repr(s.initial)}`; const from = cur.from?.[s.p]; const to = cur.to[s.p]; const end = cur.at + cur.dur; if (t >= end - 1e-9) return `e${repr(to)}`; const u = Math.max(0, (t - cur.at) / cur.dur); if (typeof from === "number" && typeof to === "number") { return `r${gsapRound(from + (to - from) * ease(cur.ease)(u))}`; } // A string that does not change (a transformOrigin restated) is that string. if (from === to) return `e${repr(to)}`; // A string in flight: the cue and its own clock, to the microsecond. return `x${JSON.stringify([from, to, cur.ease, cur.dur])}@${(t - cur.at).toFixed(6)}`; }; // The state's hash: XOR over the slots of each slot's (id, value) hash, // updated only where a value moves. Each slot's changes come from its own // cue boundaries (a step) or a running cue (every frame). // One accumulator for the page's own slots and one per item: an item's // slots (its key, or its key's children `.`) count only while // it is shown. const acc = Buffer.alloc(20); const itemList = sp.items; const itemAcc = itemList.map(() => Buffer.alloc(20)); const itemByKey = new Map(itemList.map((it, i) => [it.key, i])); const ownerOf = (k) => { if (itemByKey.has(k)) return itemByKey.get(k); const dot = k.indexOf("."); return dot > 0 && itemByKey.has(k.slice(0, dot)) ? itemByKey.get(k.slice(0, dot)) : -1; }; const owner = new Map(); for (const s of slots.values()) owner.set(s.id, ownerOf(s.k)); const xorInto = (buf, b) => { for (let i = 0; i < 20; i += 1) buf[i] ^= b[i]; }; const xor = (id, b) => { const o = owner.get(id); xorInto(o >= 0 ? itemAcc[o] : acc, b); }; const cur = new Map(); for (const s of slots.values()) { const v = valueAt(s, t0); cur.set(s.id, v); xor(s.id, sha1(`${s.id}\u0001${v}`)); } // An item's gate: hidden while its slot holds 0 (at rest, from init or a // finished cue); anything else -- a value, a cue running, a CSS default -- // is shown. const HIDDEN = new Set(["in0", "en0"]); const gateId = itemList.map((it) => (it.gate ? `${it.gate[0]}\u0000${it.gate[1]}` : null)); for (const id of gateId) if (id !== null && !slots.has(id)) return null; // Per frame, the slots that may move: those with a cue starting by it or running at it. const frameOf = (t) => Math.ceil((t - t0) * fps - 1e-6); const touch = new Map(); // frame -> slots const push = (f, s) => { if (f < 0 || f >= frames) return; let l = touch.get(f); if (!l) touch.set(f, (l = new Set())); l.add(s); }; for (const s of slots.values()) { for (const c of s.cues) { const f0 = Math.max(0, frameOf(c.at)); const f1 = Math.min(frames - 1, frameOf(c.at + c.dur)); for (let f = f0; f <= f1; f += 1) push(f, s); } } const out = new Array(frames); for (let f = 0; f < frames; f += 1) { const t = t0 + f / fps; for (const s of touch.get(f) ?? []) { const v = valueAt(s, t); const was = cur.get(s.id); if (v === was) continue; xor(s.id, sha1(`${s.id}\u0001${was}`)); xor(s.id, sha1(`${s.id}\u0001${v}`)); cur.set(s.id, v); } const h = createHash("sha1").update(sk).update(acc); for (let i = 0; i < itemList.length; i += 1) { const g = gateId[i]; if (g !== null && HIDDEN.has(cur.get(g))) continue; h.update(`\u0002${itemList[i].key}\u0003${itemList[i].hash}`).update(itemAcc[i]); } out[f] = h.digest("hex"); } return out; } /** * The feed's frame keys. Its cues are planned in the page from the heights * its cards measure, so they are not in it; but every cue time is an event's * time on the cue grid plus a FEED_MOTION constant (feedCues with `grid`), * and the plan is a function of the page's static part (which fixes the * heights) and those times. So a frame's key is the static part and, for * each event, how many grid steps ago it was -- "not yet" when it is to * come, "settled" once FEED_EVENT_CAP has passed. Refused (null) when the * page's plan, run here with the shortest and the tallest cards, has a cue * that runs past the cap after the event before it. */ function feedFrameKeys({ html, sk, fps, frames, items = [] }) { const { data } = splitData(html, FRAME_KEY_REGIONS.feed.data); const g = Number(data.grid); const per = g / fps; if (!Number.isInteger(per) || per <= 0) return null; const steps = (v) => Math.round(v * g); const events = []; data.posts.forEach((p, j) => { if (!Number.isFinite(p?.in)) throw new Error(`frame keys: feed post ${j} has no time`); events.push({ tag: `p${j}`, at: steps(p.in) }); }); data.visibility.forEach((v, j) => { const [a0, a1] = v.at ?? []; if (!Number.isFinite(a0) || !Number.isFinite(a1)) throw new Error(`frame keys: feed visibility ${j} has no times`); const skipped = a1 - a0 <= 0 && v.i === 0; events.push({ tag: `v${j}:${v.i}:${v.hide ? 1 : 0}:${steps(a1) - steps(a0)}:${skipped ? 1 : 0}`, at: steps(a0) }); }); const cap = FEED_EVENT_CAP * g; // The cap, checked against the plan itself at both extremes of card height. const M = data.motion ?? {}; const times = events.map((e) => e.at / g).sort((x, y) => x - y); for (const h of [1, 1e6]) { const plan = feedCues({ posts: data.posts, heights: data.posts.map(() => h), column: data.column, visibility: data.visibility, startsHidden: data.startsHidden, slideX: data.slideX, enterX: data.enterX, gap: M.gap, push: M.push, lag: M.lag, enter: M.enter, glowAt: M.glowAt, glowUp: M.glowUp, glowDown: M.glowDown, newest: M.newest, calm: M.calm, leave: M.leave, grid: g, }); for (const c of plan.cues) { let last = -Infinity; for (const t of times) if (t <= c.at + 1e-9) last = t; if (!(c.at + c.dur - last < FEED_EVENT_CAP - 1)) return null; } } // A card's markup (its item) is in a frame's key from its post's event // on: before it the card is hidden and moves nothing (the plan is causal: // a post's cues start at its event). An event still to come is in no // frame's key, so a post added later leaves the frames before it alone. const cardOf = new Map(items.filter((it) => Number.isInteger(it.event)).map((it) => [`p${it.event}`, it.hash])); const out = new Array(frames); for (let f = 0; f < frames; f += 1) { const t = f * per; let sig = ""; for (const e of events) { const d = t - e.at; if (d < 0) continue; const card = cardOf.get(e.tag); sig += `${e.tag}=${d >= cap ? "s" : d}${card ? `|${card}` : ""};`; } out[f] = createHash("sha1").update(sk).update(sig).digest("hex"); } return out; }