Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
Saves: the runtime stylesheet is not part of the document
nyblnet121314ea0037
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 328b49fc..1aedaad6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -34,6 +34,13 @@ pre-1.0.Tokyo opens in French chrome for a French reader, and the deck itself isunchanged either way.+- **Fix: saved files no longer grow by 100 KB on every save.** Each save wrote+ a fresh, uncompressed copy of the app's stylesheet into the file, which the+ next save then copied again — a deck saved ten times carried ten of them and+ had put on a megabyte for nothing. The stylesheet belongs in the compressed+ runtime payload, where it takes 27 KB and is written exactly once; a file+ that already accumulated copies drops all of them the next time you save it.+- **Fix: a large chart legend no longer crowds the axis labels.** Charts thatdon't set their own margins now leave room for the legend at whatever sizeit's set to, instead of assuming the default one.diff --git a/CLAUDE.md b/CLAUDE.mdindex 9a60b426..18bd2d94 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -551,6 +551,11 @@ names provisional.blocks + ~1KB loader (DecompressionStream → blob import; pre-2023 browsersget a plain-HTML message). Byte order: chrome → NOTICE → tooling comment →PLAINTEXT #bento-doc → splash → payloads last. Shell ~560KB (was 1.33MB).+ The loader's injected `<style>` carries `data-bento-transient` and+ `serializeBody` (kernel/src/save.ts) strips marked nodes from the clone —+ `capturePristine()` clones the LIVE document, so without that the inflated+ CSS was saved back as plaintext and re-appended each boot (+100KB per save,+ forever). Anything injected before the pristine capture must be marked.SPLICE CONTRACT (old updaters are frozen code): #bento-doc stays plaintext/same id, file survives DOMParser→splice→outerHTML, no stray script-close —release.mjs runs a conformance GATE before signing every release.diff --git a/docs/PLATFORM.md b/docs/PLATFORM.mdindex 202b57d9..c6924fd0 100644--- a/docs/PLATFORM.md+++ b/docs/PLATFORM.md@@ -62,6 +62,16 @@ checks) before any release.- Self-save: capture the pristine shell at boot, swap the `#bento-doc` block,re-serialize. File System Access API first, download fallback.+- **Runtime-injected DOM must be marked `data-bento-transient`.** The pristine+ capture clones the LIVE document, so anything the runtime adds before it —+ the compressed shell's inflated stylesheet, first of all — would otherwise be+ written into the saved file, then re-injected on the next boot and saved+ again: unbounded growth, one copy per save (~100KB each for the CSS, which+ ships deflated for a reason). `serializeBody` strips the marked nodes from+ every serialized shell. Inject before the capture only if you mark it —+ `scripts/shell-gate.mjs` proves both halves on every CI build (the loader+ marks what it injects; the runtime still strips it) and rejects a shell that+ carries any payload's content as plaintext.- Autosave (IndexedDB) keeps a latest-recovery snapshot + a capped versiontimeline, keyed by `docId`. Read-only players skip autosave.- Password-protected docs use the `bento/enc` envelope (PBKDF2-SHA-256 300k →diff --git a/kernel/src/save.ts b/kernel/src/save.tsindex e1f53fe7..5eb8df7c 100644--- a/kernel/src/save.ts+++ b/kernel/src/save.ts@@ -15,6 +15,23 @@ const DATA_BLOCK_ID = 'bento-doc'// inline <script> that carries this very code inside a built Bento file).const SCRIPT_CLOSE = '</scr' + 'ipt>'+/**+ * DOM the runtime injects at boot and that must NEVER reach a saved file.+ *+ * capturePristine() clones the live document, and the compressed shell's+ * loader has already inflated the app stylesheet into a <style> by then (see+ * scripts/postbuild-compress.mjs). Serializing the clone as-is wrote that+ * ~100KB of CSS back as PLAINTEXT — and the next boot inflated the payload and+ * appended another copy, so every save grew the file by another 100KB, forever.+ * The CSS ships deflated in the #bento-rt-css payload for a reason; the saved+ * file must carry it exactly once, compressed.+ *+ * So: anything injected before the pristine capture carries this attribute and+ * is stripped from every serialized shell. The kernel does not care what the+ * node is — only that the app declared it runtime-owned.+ */+const TRANSIENT_SELECTOR = '[data-bento-transient]'+let pristine: Document | null = null/** Call first thing at boot, before any DOM mutation. */@@ -76,6 +93,9 @@ export function readShellBlocks(type: string): Array<{ id: string; body: string;function serializeBody(shell: Document, body: string, title: string): string {const clone = shell.cloneNode(true) as Document+ // Runtime-injected DOM is not part of the shell (see TRANSIENT_SELECTOR).+ for (const el of Array.from(clone.querySelectorAll(TRANSIENT_SELECTOR))) el.remove()+// Re-declare the app's extra blocks: drop every one of a managed type, then// write the current set back. Removing a language from the file is therefore// just "stop listing it" — no deletion path to get wrong. The clear-set isdiff --git a/scripts/postbuild-compress.mjs b/scripts/postbuild-compress.mjsindex 57369e42..201403e6 100644--- a/scripts/postbuild-compress.mjs+++ b/scripts/postbuild-compress.mjs@@ -147,6 +147,20 @@ const GENERIC_TOOLING = `<!--const TOOLING_COMMENT = generator === 'bento-slides' ? SLIDES_TOOLING : GENERIC_TOOLING// --- loader (plain script, runs at end of body; no "</script>" literal) -----+// Keep the loader small: unlike the payloads it ships as PLAINTEXT in every+// file, so its comments are shipped bytes. Anything long goes here instead.+//+// TRANSIENT DOM — the style element it injects belongs to the RUNNING document+// only. A save clones the live DOM (kernel/src/save.ts capturePristine), so+// without the two guards below every save wrote this ~100KB of CSS back as+// plaintext, the next boot inflated the payload and appended another copy, and+// the file grew by 100KB per save without bound:+// 1. `data-bento-transient` — serializeBody() strips marked nodes from the+// clone, so the CSS lives in the deflated #bento-rt-css payload (27KB)+// and nowhere else in the file.+// 2. the sweep — a file written before guard 1 existed already carries N+// plaintext copies of exactly this CSS; dropping them before injecting+// means such a file is CLEANED by its next save rather than doubled.const loader = `(async () => {var fail = function (msg) {@@ -169,7 +183,14 @@ const loader = `}try {var css = await inflate('bento-rt-css')+ // drop stale plaintext copies (see TRANSIENT DOM above), then inject ours+ var old = document.querySelectorAll('style')+ for (var i = 0; i < old.length; i++) {+ if (old[i].hasAttribute('data-bento-transient') || old[i].textContent === css) old[i].remove()+ }var st = document.createElement('style')+ st.id = 'bento-rt-style'+ st.setAttribute('data-bento-transient', '')st.textContent = cssdocument.head.appendChild(st)var js = await inflate('bento-rt')diff --git a/scripts/shell-gate.mjs b/scripts/shell-gate.mjsindex 9a4e3436..72f806f8 100644--- a/scripts/shell-gate.mjs+++ b/scripts/shell-gate.mjs@@ -16,6 +16,14 @@// and proves the contract holds with it in the file (and, as a negative// control, that the same pack written *unescaped* is caught).//+// A THIRD invariant is about size rather than correctness: the runtime ships+// DEFLATED, and a save must not quietly turn it back into plaintext. The+// loader inflates the app stylesheet into a <style> at boot, and a save clones+// the live document — so unless that node is marked `data-bento-transient` for+// `serializeBody` to strip, every save writes ~100KB of CSS into the file and+// the next boot appends another copy. It is invisible in review and unbounded+// in a shipped file, so the gate checks the artifact for it.+//// The `<`-escape rule is deliberately restated here rather than imported: a// gate that shares code with the thing it gates cannot notice the thing// drifting. The one link back to the implementation is a source assertion@@ -30,6 +38,7 @@import { existsSync, readFileSync } from 'node:fs'import { dirname, join } from 'node:path'import { fileURLToPath } from 'node:url'+import { inflateRawSync } from 'node:zlib'const here = dirname(fileURLToPath(import.meta.url))const repoRoot = dirname(here)@@ -235,7 +244,91 @@ function checkPackCarryingShell(shell) {if (caught !== 2) fail('negative control passed — the pack-block checks have no teeth')}-// --- invariant 4: the product still applies the escape ----------------------+// --- invariant 4: the runtime stays compressed, and stays out of the save ---++const TRANSIENT_ATTR = 'data-bento-transient'+const PAYLOAD_TYPE = 'bento/deflate-b64'++/** Every `<style>` in the file, with its raw text. */+function scanStyles(html) {+ return Array.from(html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)).map((m) => m[1])+}++/** The inflated text of each `bento/deflate-b64` payload, by id. */+function inflatePayloads(html) {+ const out = new Map()+ for (const s of scanScripts(html).filter((x) => x.type === PAYLOAD_TYPE)) {+ try {+ out.set(s.id, inflateRawSync(Buffer.from(s.text.trim(), 'base64')).toString('utf8'))+ } catch (e) {+ fail(`payload #${s.id} does not inflate: ${e.message}`)+ }+ }+ return out+}++/**+ * No payload's content may ALSO appear as plaintext in the file.+ *+ * This is the shape the bug takes on disk: the file carries the stylesheet+ * twice, once deflated (27KB, the copy the loader uses) and once as a `<style>`+ * the previous save cloned out of the live DOM (100KB, dead weight that grows+ * by another copy every save).+ */+function checkRuntimeStaysCompressed(html, label) {+ const payloads = inflatePayloads(html)+ if (!payloads.size) return false // an uncompressed build — nothing to check+ const plaintext = [+ ...scanStyles(html),+ ...scanScripts(html).filter((s) => s.type !== PAYLOAD_TYPE).map((s) => s.text),+ ]+ for (const [id, text] of payloads) {+ if (plaintext.some((body) => body.includes(text)))+ fail(`#${id} also appears as plaintext in the file — the runtime must ship deflated only (${label})`)+ }+ return true+}++/**+ * …and the two halves of the mechanism that keeps it that way, checked in the+ * ARTIFACT rather than in source: the loader marks the style it injects, and+ * the runtime it boots still strips marked nodes when it serializes. Both are+ * string literals that survive minification.+ */+function checkTransientMarking(shell) {+ const scripts = scanScripts(shell)+ const loader = scripts.find((s) => !s.type && s.text.includes('bento-rt-css'))+ if (!loader) fail('boot loader not found in the shell')+ // Specifically: it SETS the attribute. Merely mentioning the name is what+ // the loader's stale-copy sweep does, and that must not satisfy this check.+ if (!new RegExp(String.raw`setAttribute\(\s*['"]${TRANSIENT_ATTR}['"]`).test(loader.text))+ fail(+ `the boot loader injects the stylesheet without marking it ${TRANSIENT_ATTR} — ` ++ 'every save would write it back as plaintext (scripts/postbuild-compress.mjs)',+ )+ const runtime = inflatePayloads(shell).get('bento-rt') ?? ''+ if (!runtime.includes(`[${TRANSIENT_ATTR}]`))+ fail(+ `the runtime no longer strips [${TRANSIENT_ATTR}] when serializing — ` ++ 'saved files would grow by the stylesheet on every save (kernel/src/save.ts)',+ )++ // NEGATIVE CONTROL — a shell carrying the inflated stylesheet as plaintext+ // (exactly what a save produced before the marker existed) must be caught.+ const css = inflatePayloads(shell).get('bento-rt-css')+ if (css) {+ const bloated = shell.replace('</head>', () => `<style>${css}</style>\n</head>`)+ let caught = false+ try {+ checkRuntimeStaysCompressed(bloated, 'plaintext-runtime control')+ } catch {+ caught = true+ }+ if (!caught) fail('negative control passed — the plaintext-runtime check has no teeth')+ }+}++// --- invariant 5: the product still applies the escape ----------------------/*** The only assertion that reaches into the implementation. The gate works on@@ -262,8 +355,13 @@ export function gateShell(shellPath) {checkSpliceContract(shell, 'shell')checkDataBlocks(shell, 'shell')checkPackCarryingShell(shell)+ const compressed = checkRuntimeStaysCompressed(shell, 'shell')+ if (compressed) checkTransientMarking(shell)checkEscapeIsImplemented()- console.log('conformance gate: old-updater splice contract OK (incl. pack-carrying shell)')+ console.log(+ 'conformance gate: old-updater splice contract OK (incl. pack-carrying shell)' ++ (compressed ? '; runtime ships deflated only' : ''),+ )}// CLI: node scripts/shell-gate.mjs <path-to-shell.html>