Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
shell: a deck opens inside Teams again — the loader probes nothing, and payloads are base86 (38 KB smaller) (#495)
nyblnete215abea1294
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex aefe964d..bc9ff7dc 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1388,6 +1388,19 @@ jobs:# routes the argument. Bare {{date}} stays viewer-locale (#381).run: node scripts/test-slides-fields.ts+ - name: Shell loader and carrier rig+ # base86 payloads (scripts/lib/b86.mjs) round-trip and can never+ # contain </script, <!--, -->, ]]> or ${; the loader inflates+ # synchronously and runs the runtime as an inline classic script+ # FIRST (mounted before DOMContentLoaded, as the uncompressed build+ # is), probes and waits on nothing, falls to new Function then blob+ # only on a refusal, installs Trusted Types policies lazily, and+ # records window.bento.loader. The gate goes red on a hand-edited+ # payload. The browser half drives headless Chrome with a real+ # background tab: mounted before DCL hidden, splash gone within 50 ms+ # of the mount there. Needs slides/node_modules and the built shell.+ run: node scripts/test-shell-loader.ts+- name: Maths in links rig# resolveMath transforms text runs only: a `$` inside an href never# pairs with one in the text, so a link whose address carries adiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 07bb466f..2f977d92 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,33 @@ pre-1.0.## [Unreleased]+- **A deck opens inside Teams and SharePoint again.** Their viewer refuses+ the way 1.1.0's file started itself (a script loaded from a `blob:` URL).+ The file now starts the way nothing refuses: the runtime is inserted as an+ inline script first, and only if a policy turns that down does it fall+ back to `new Function`, then to the blob import — measured in Teams with+ seven variants. Inside such a viewer the frame has no storage, so+ autosave and preferences do not persist there, and its policy blocks every+ connection — so inside an embedded view the app makes no request at all:+ no update check at launch, no language-pack listing, no live-session+ socket; the About dialog says so. The deck itself opens, presents and+ saves.+- **A deck opened in a background tab is ready when you switch to it.** The+ compressed file used to finish starting in a later task and hold its+ splash on a timer — in a tab that was not visible (or a viewer rendering+ the file off-screen for a preview card) timers are throttled and frames+ never come, so the editor sat behind the splash until the tab was looked+ at. The runtime now unpacks and starts inside the file's own script,+ before the page is even "loaded", and a hidden document drops the splash+ the moment the editor exists; visible, the brand moment is held for at+ most 0.8 s and never waits on its own fade.+- **Every file is about 38 KB smaller.** The runtime's two compressed blocks+ used to be base64; they are now base86 — 86 printable characters chosen so+ the text can never close or comment out the block that carries it — which+ is 6.25% denser (4 bytes in 5 characters instead of 3 in 4). Measured on+ the release shell: 699,847 → 661,768 bytes. Older versions keep opening+ their own files; this one still reads theirs. The new decoder is also+ quicker than the old `atob` path (11 ms against 47 for the runtime).- **A web link whose address contains a dollar sign works again.** Sincelinks arrived, an address like `…/$a$b` had its two dollars read as aformula and the link broke; formulas are now looked for in the text only,diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 8229e6dd..854fae48 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -7047,3 +7047,194 @@ it shipped (#485, against main 131015e): 756,103 → 690,067 B compressed(−66,036 B, −8.7%). The spike that measured all of the above was PR #483(closed, three rounds).+## 2026-09-16 — The shell starts the way nothing refuses, and carries its runtime in base86++A .bento.html attached in Microsoft Teams stopped opening once the shell was+compressed (1.0.x). The maintainer tested seven loader variants in Teams,+each with a marker on the first slide, and the results decided the loader:++| variant | open pane | preview pane |+| --- | --- | --- |+| A — 1.1.0 shell, module import from a `blob:` URL | blank | blank |+| B — the runtime inserted as an inline module script | splash only | works |+| B2 — B plus an on-page diagnostic panel | splash only | works |+| B3 — B plus `trustedTypes.createPolicy` at boot | splash only | blank |+| B4 — inline first, then `new Function`, then blob; eager policies | works | blank |+| B5 — `new Function('')` probe first, then inline; eager policies | works | blank |+| B6 — B5 with the policies made lazy | works | blank |+| C — the uncompressed build, every script parser-inserted | works | works |++**Two panes, two policies.** The open pane sends a header policy that allows+the file's own inline scripts by sha256 hash plus `'unsafe-eval'` (hashes+present, so `'unsafe-inline'` is ignored per spec), no `blob:`, a sandbox+without `allow-same-origin`, `connect-src 'none'`. C works there because+every script it has is parser-inserted and hashed; A fails on `blob:`; B+fails because an inserted script is unhashed. Reproduced locally+(`scripts/loader-csp-server.py --hash`) before anything was built on it.+The preview column is recorded as observed but is NOT evidence — see+"The preview pane is not deterministic" below; every decision here rests on+the open pane, which answered the same way on every upload.++**Consequence: no probing.** The loader does first the one thing refused+nowhere — insert the inline module, exactly as B — a step that a hashing+policy refuses with a report and nothing accepts silently, so the cascade+never guesses; it reaches for anything else only after a `securitypolicyviolation` attributed to that attempt+(matched by `blockedURI`, not by timing: the eval probe's own violation+arrives a task later and was once read as the inline attempt failing):+then `new Function("'use strict';" + js)()` — an indirect eval, ungoverned+by script hashes and allowed by `'unsafe-eval'`; the bundle has no top-level+`import`, `export` or `await`, so it is a classic function body, and a+`//# sourceURL=bento-slides.js` names it in DevTools — then the blob import.+Trusted Types policies (`bento` for the script sink, `default` because the+renderer and the save path assign `innerHTML` and `script.text` from strings)+are created only after a sink throws the TypeError that names them, and that+step is retried once. The loader counts violations from its first statement+and records `{ path, tried, tt, violations }` on `window.bento.loader`.+Measured under five local policies: zero violations wherever inline is+allowed; path `function` under the open-pane policy; the lazy install under+enforced Trusted Types.++**Cost.** Boot to editor mount in plain Chrome, twelve interleaved runs:+1.1.0 loader median 404 ms, this loader 421 ms (b64) / 367 ms (b86). The+inline-module path parses the bundle the same way the blob import did; the+eval-first order was ~80 ms quicker but probes (kept as+`--loader cascade-eval-first` for the record).++**Encoding.** Every shell byte is paid per send, so the two payload blocks+moved from base64 to base86: printable ASCII 0x21–0x7E minus `<` `>` `&`+`"` `'` `\` `-` `{` — 86 symbols, so `</script`, `<!--`, `-->`, `]]>` and+`${` are unproducible by construction (asserted by the gate on every payload+and by a 10,000-buffer rig). Four bytes in five characters: 6.4 bits per+character against base64's 6, a payload ×1.25 instead of ×1.333 — 6.25%+smaller; the theoretical limit for 86 symbols is 6.43 bits, so 4→5 is within+0.4% of it and a 7→9 group (6.22 bits/char) would be WORSE, not better —+larger groups buy nothing here. Block type `bento/deflate-b86`; the gate,+the site scripts and the loader read both types. Measured on the release+shell: 699,847 → 661,768 B (−38,079, −5.4% of the file; the payloads+themselves −6.25%). The in-page decoder — a 128-entry lookup and 32-bit+groups — takes 11 ms on the runtime payload against 47 ms for+`Uint8Array.from(atob(...))`, so the smaller file also boots sooner.++**Set aside, measured.** Alternative carriers (`<template>`, `text/plain`)+and a plain-JavaScript inflater for hosts without DecompressionStream stay+as opt-in flags (`--carrier`, `--inflate`), built because the delivery of+the payload was once the hypothesis; the diagnostic panel showed the+payload found and inflated in Teams, so neither is needed there.++**No request from an embedded view.** The open-pane diagnostic panel, read+in Teams, ended with `connect-src` violations for the launch update check —+a request the policy forbids and the app has no business making from a+frame that cannot store the answer. kernel `net.ts` now+decides once at boot whether the document is an embedded view and `netFetch` /+`netWebSocket` — the one place the app touches the network — refuse before+any request. The decision needs ALL THREE signs — framed (`self !== top`),+an opaque DOCUMENT origin (`self.origin === 'null'`) and a storage read+throwing `SecurityError` — because the first cut ("opaque, or storage throws") would+have switched off updates and collab for people nobody embedded: Firefox+reports origin `null` for a file:// deck (Chromium 152 reports `file://`,+measured, so Chromium desktops were never at risk), and so do a data: URL, a+WebView loaded from a string with no base URL, and a top-level response under+CSP `sandbox`; a normal tab with site data blocked throws on the storage+read. That the Teams pane is all three is measured, not assumed: the B2+diagnostic panel, opened in Teams by the maintainer, printed `framed`+alongside origin `null` and the storage `SecurityError`. The origin sign+reads `self.origin`, the document's origin, not `location.origin`, which is+the URL's: measured in Chromium 152, a sandboxed frame loaded by `src`+reports its http origin in `location.origin` while `self.origin` is `null`+(a `srcdoc` or `data:` frame says `null` in both — the B2 panel probed+`location.origin` and printed `null`, so that is how the Teams pane loads+the file). On `location.origin` the local sandboxed-iframe harness was not+sandboxed at all and made the manifest request; on `self.origin` it is, and a top-level file:// deck (Chromium:+`self.origin` `null`, `location.origin` `file://`) still is not, because+it is not framed. The rig probes each+sign alone and in pairs in child processes (the decision is cached per+process) and asserts only the triple is sandboxed. The refusal is terminal —+a frame's sandboxing does not change while it lives — so the transport must+not retry a `SandboxedError` (kernel's change in `sync/online.ts`, on top of+this one). With the fix: the launch check, the relay join and the pack listing never+start, the About dialog says "Updates are not checked inside an embedded+view", and `window.bento.sandboxed` exposes the decision. Measured: a plain+tab makes exactly one manifest request at launch; the sandboxed frames make+none and raise no violation after boot over five seconds. Storage still does+not persist there — autosave and preferences are per visit — and that is+stated in the changelog line. Previews are untouched:+`preview.ts`, the remover and the gate's preview-carrying-shell invariant+are not part of this change, and the thumbnailers that render the preview+run no script at all.++**The preview pane is not deterministic.** Eleven more files were built to+bisect why the preview card stayed blue for base86 when it had rendered the+editor for base64 (B7): base86 minus one candidate symbol at a time (`%`,+`*`, `?`, `#`, `:`, `@`), minus `?` and `#`, and minus the six URL+delimiters (`% : / ? # @`, 80 symbols, 7→9 groups). Round seven settled+it: B11d (no `:`) and B11e (no `@`) rendered the editor on first upload and+were blue on a second upload of the SAME bytes, and B7 — the editor+yesterday — was blue today. The preview pane's outcome varies between+uploads of identical bytes, so no conclusion about any character stands,+including B10b's one-time success; the earlier reading of blank preview+cards as "a reported violation is fatal" is withdrawn on the same ground.+The open pane has been deterministic throughout: base86 + this cascade ++`sandboxed()` open there every time. The counts below are kept as data —+what each alphabet exposes in the real runtime payload — with no inference+drawn from them:++| payload | chars | `/*` | `*/` | `//` | `%xx` | `://` | `?x=` | `#`+alnum | `@`+alnum |+| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |+| b64 | 660,200 | 0 | 0 | 227 | 0 | 0 | 0 | 0 | 0 |+| b86 | 618,937 | 82 | 90 | 72 | 486 | 2 | 249 | 5,240 | 5,416 |+| b80 | 636,621 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |++**The tell, and the mechanism.** Blue preview cards showed the splash with+no mark, wordmark or bar — every one of those begins at opacity 0 and+animates in — so the card was rendered by a document whose animations never+advanced: a hidden document. Chrome measured in a background tab (CDP,+Chromium 152): CSS animations hold their first frame, `requestAnimationFrame`+never fires, `setTimeout(25)` fires after 675 ms, decoding runs 4–6× slower;+`setTimeout(0)`, promises and an inserted script's execution are prompt.+Against that, the two files that differed in Teams differed exactly here:+the uncompressed build's runtime is a parser-inserted script, so its editor+is mounted BEFORE DOMContentLoaded (measured: mounted at DCL, 105 ms hidden);+the compressed shell's loader awaited `DecompressionStream` and then+inserted a `type="module"` script — both land in later tasks — so `load`+fired at 12 ms with nothing mounted and the editor arrived ~300 ms later+hidden (A: 292–437 ms, B7-b86: 287–364 ms). A viewer that renders the+document off-screen and captures it around `load` sees the splash from the+compressed file and the editor from the uncompressed one, and the race+between its capture and a throttled task is the nondeterminism observed.+Then the splash: `main.ts` held it on a 1250 ms timer and removed it 550 ms+after adding the fade class — two timers a hidden document throttles (splash+gone at 2.4–2.9 s hidden against 1.8 s visible, for every build including+the uncompressed one), so a deck opened in a background tab showed its splash+until it was looked at.++**Consequence: mounted before `load`, and the splash never waits.** The+loader now decodes and inflates synchronously — the ~2 KB JavaScript+inflater that was an opt-in flag, 18 ms on the runtime payload against+`DecompressionStream`'s 6 (99 against 18 hidden) — and runs the runtime as+an inline CLASSIC script, which executes inside `appendChild`; whether the+policy took it is known when the call returns, so no wait, no violation+listener on the critical path. Then `new Function`, also synchronous; the+blob import is the one promise and the last resort. Measured: the compressed+shell mounts at 123 ms visible / 138 ms hidden, before DOMContentLoaded in+both, as the uncompressed build does; the old loader 109 / 287 ms, after+`load`. The splash is removed at once when `document.hidden`, on a+`visibilitychange` to hidden, or — visible — after a hold capped at 800 ms+from navigation and a fade that ends by timer or `transitionend`, whichever+first: gone 2 ms after the mount hidden, 1,241 ms after it visible. The rig+drives headless Chrome with a real background tab (a decoy tab activated+before navigation) and asserts both, plus that the built loader contains no+`requestAnimationFrame`, `setTimeout`, `setInterval`, `fonts.ready` or+`DOMContentLoaded` and exactly one `await`. The editor's own boot was+audited for the same waits: `main.ts` reaches `new Editor` and+`window.bento` synchronously from the doc; the constructor builds the whole+UI synchronously; the canvas renders in its constructor and only its+re-scale rides a `ResizeObserver`; `fitTopbar` measures synchronously once+and re-measures on observers; the launch update check sits on a 1.5 s+timer that is off the mount path; nothing awaits a frame or a font before+the app exists.++The experimental alphabets stay in `scripts/lib/b86.mjs` behind+`--encoding` (`makeCodec` is build-side only; the shipped loader carries+the b86 decoder alone, verified by grep on the built shell), and the+diagnostic panel stays behind `--diag`. Default: b86, cascade, no panel.+diff --git a/docs/PLATFORM.md b/docs/PLATFORM.mdindex 16850f5f..eb6a7e19 100644--- a/docs/PLATFORM.md+++ b/docs/PLATFORM.md@@ -19,8 +19,14 @@ dependency to the core document lifecycle is off-platform.Byte order of a shipped shell (postbuild-compress):`chrome → NOTICE → tooling comment → plaintext #bento-doc → splash → compressed payloads`.-Runtime JS/CSS ship deflated in `bento/deflate-b64` script blocks with a ~1KB-loader (DecompressionStream → blob import).+Runtime JS/CSS ship deflated in `bento/deflate-b86` script blocks (base86:+86 printable ASCII symbols chosen so a payload can never close or comment out+its own block; 6.25% smaller than the `bento/deflate-b64` blocks of 1.1.0 and+earlier, which every reader still accepts) with a ~3KB loader+(a synchronous JavaScript inflate → an inline classic script, then `new+Function`, then a blob import — whichever the host's policy allows first,+tried in that order; the app is mounted before DOMContentLoaded, as in the+uncompressed build, with no timer or frame on the way).## 2. The splice contract (FROZEN)diff --git a/kernel/src/net.ts b/kernel/src/net.tsindex c510febe..5bf4563d 100644--- a/kernel/src/net.ts+++ b/kernel/src/net.ts@@ -42,6 +42,61 @@ export class OfflineError extends Error {}}+/** Thrown by netFetch/netWebSocket inside an embedded view (see sandboxed). */+export class SandboxedError extends Error {+ constructor(what = 'the network') {+ super(`This file is open inside an embedded view — not reaching ${what}.`)+ this.name = 'SandboxedError'+ }+}++/**+ * Is this document an EMBEDDED VIEW — the way Microsoft Teams / SharePoint+ * open an attachment: a sandboxed frame without allow-same-origin, whose+ * policy blocks every connection and whose preview pane treats a reported+ * violation as fatal? ALL THREE signs are required, because each alone is+ * something else:+ *+ * · framed (`self !== top`; a cross-origin top throws on the read and+ * counts as framed) — a Teams pane is always a frame: the B2 diagnostic+ * panel, opened in Teams by the maintainer, printed `framed` alongside+ * origin 'null' and the storage SecurityError;+ * · an opaque DOCUMENT origin (`self.origin === 'null'`; `location.origin`+ * is the URL's origin, a different thing — measured in Chromium 152, a+ * sandboxed frame loaded by src reports its http origin there while+ * self.origin is 'null'; the B2 panel in Teams printed location.origin+ * 'null', so that pane loads the file as srcdoc or a data: URL, where+ * both agree) — BUT so are documents nobody embedded: Chromium 152+ * reports self.origin 'null' for a top-level file:// deck (location+ * origin 'file://'), and so do a data: URL, a WebView loaded from a+ * string with no base URL, and a top-level response under CSP `sandbox`.+ * On the origin alone those users would have lost updates and collab;+ * · a storage read throwing SecurityError — BUT a normal tab with site+ * data blocked throws there too, top-level, with a real origin (the+ * offline-mode notes above treat that as survivable, and it is).+ *+ * A Teams pane is framed AND opaque AND storage-less; nothing else that+ * opens a deck is all three. Decided once; a frame's sandboxing does not+ * change while it lives. Inside one, no launch update check,+ * no language-pack listing, no relay socket. Remote media in the document+ * is loaded by the browser from a src attribute and is not ours to gate.+ */+let sandboxFlag: boolean | null = null+export const sandboxed = (): boolean => {+ if (sandboxFlag !== null) return sandboxFlag+ let framed = false+ try { framed = typeof self !== 'undefined' && typeof top !== 'undefined' && self !== top } catch { framed = true }+ let opaque = false+ try {+ const o = typeof self !== 'undefined' && typeof (self as { origin?: unknown }).origin === 'string' ? (self as { origin: string }).origin : location.origin+ opaque = o === 'null'+ } catch { opaque = false }+ let storageThrows = false+ try { void globalThis.localStorage } catch (e) { storageThrows = !!e && (e as { name?: string }).name === 'SecurityError' }+ sandboxFlag = framed && opaque && storageThrows+ return sandboxFlag+}+/*** Set for THIS session once anyone flips the switch, so the guarantee holds* even where the preference cannot be stored. Storage-blocked contexts are@@ -120,6 +175,7 @@ export function startNetGuard(): void {/** fetch(), refused when offline and abortable the moment the switch flips. */export async function netFetch(input: string | URL, init: RequestInit = {}): Promise<Response> {+ if (sandboxed()) throw new SandboxedError(String(input))if (offlineEnabled()) throw new OfflineError(String(input))const ac = new AbortController()inFlight.add(ac)@@ -137,6 +193,7 @@ export async function netFetch(input: string | URL, init: RequestInit = {}): Pro/** new WebSocket(), refused when offline and closed the moment the switch flips. */export function netWebSocket(url: string): WebSocket {+ if (sandboxed()) throw new SandboxedError(url)if (offlineEnabled()) throw new OfflineError(url)const ws = new WebSocket(url)sockets.add(ws)diff --git a/kernel/src/sync/online.ts b/kernel/src/sync/online.tsindex 2856edda..3bcc7188 100644--- a/kernel/src/sync/online.ts+++ b/kernel/src/sync/online.ts@@ -16,7 +16,7 @@ import { lsGet, lsSet } from '../storage.ts'import { offlineEnabled } from '../update.ts'// Every request in the app goes through the one chokepoint (kernel/src/net.ts)// so the offline switch cannot be forgotten — see GHSA-5c3x-xqp6-g94r.-import { netWebSocket } from '../net.ts'+import { netWebSocket, SandboxedError } from '../net.ts'import { appConfig } from '../app.ts'/** the app's store, structurally — see session.ts HostStore */@@ -403,7 +403,13 @@ export class OnlineTransport implements Transport {let ws: WebSockettry {ws = netWebSocket(`${this.url}&since=${this.lastSeq()}`)- } catch {+ } catch (e) {+ // A sandboxed embed (Teams/SharePoint preview) refuses every socket at+ // the net chokepoint, permanently and identically — retrying would only+ // flap 'connecting' forever. Treat it as TERMINAL, exactly as drop()+ // treats close codes 4001/1008: stop, schedule no reconnect. (The offline+ // switch is different — it can flip back off, so it stays retryable.)+ if (e instanceof SandboxedError) { this.closed = true; this.setStatus('closed'); return }this.retry()return}diff --git a/kernel/src/update.ts b/kernel/src/update.tsindex 672e9524..be44c4ba 100644--- a/kernel/src/update.ts+++ b/kernel/src/update.ts@@ -41,7 +41,7 @@ export const APP_VERSION: string = typeof __APP_VERSION__ !== 'undefined' ? __AP* Re-exported here because this has been update.ts's public surface since* 0.9.x and shipped code imports it from here.*/-export { offlineEnabled, setOffline, OfflineError, startNetGuard } from './net.ts'+export { offlineEnabled, setOffline, OfflineError, startNetGuard, sandboxed, SandboxedError } from './net.ts'export const autoCheckEnabled = (): boolean => lsGet('bento-auto-check') !== 'off'export const setAutoCheck = (on: boolean): void => {diff --git a/scripts/lib/b86.mjs b/scripts/lib/b86.mjsnew file mode 100644index 00000000..1c0ff219--- /dev/null+++ b/scripts/lib/b86.mjs@@ -0,0 +1,266 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// base86 — the densest ASCII carrier that is SAFE inside an HTML script block+// by construction, for the deflated runtime payloads (bento/deflate-b86).+//+// Alphabet: printable ASCII 0x21–0x7E (94 symbols) minus `<` `>` `&` `"` `'`+// `\` `-` and `{` — 86 symbols. What that makes unproducible, whatever the+// bytes: `</script` (no `<`), `<!--` and `-->` (no `<`, `>`, `-`), `]]>`+// (no `>`) and `${` (no `{`; `$` stays). Quotes, ampersand and backslash go+// so the text is also safe inside an attribute or a JS string. Space is not+// in the alphabet, so a run of payload never wraps or tokenises.+//+// Groups: 4 bytes → 5 chars (86^5 = 4,704,270,176 > 2^32): 6.4 bits per+// character, so a payload costs ×1.25 against base64's ×1.333 — 6.25%+// smaller. The limit for 86 symbols is log2(86) = 6.43 bits per character,+// so 4→5 is within 0.4% of it; a 7-byte → 9-char group would be WORSE+// (6.22 bits per character) — larger groups buy nothing here, and 32-bit+// arithmetic is all the decoder needs.+//+// Tail: the last partial group of n bytes (1–3) is padded with zero bytes,+// encoded, and n+1 characters are emitted; a decoder pads the missing+// characters with the highest symbol and keeps the first n bytes — the+// Ascii85 rule, which rounds correctly because the padding is maximal.++export const ALPHABET = (() => {+ let s = ''+ for (let c = 0x21; c <= 0x7e; c++) {+ const ch = String.fromCharCode(c)+ if ('<>&"\'\\-{'.includes(ch)) continue+ s += ch+ }+ return s+})()+export const BASE = ALPHABET.length // 86+if (BASE !== 86) throw new Error(`b86: alphabet is ${BASE} symbols, expected 86`)++const VALUE = new Int16Array(128).fill(-1)+for (let i = 0; i < BASE; i++) VALUE[ALPHABET.charCodeAt(i)] = i++/** Uint8Array → base86 text. */+export function encode(bytes) {+ const out = []+ const n = bytes.length+ let i = 0+ for (; i + 4 <= n; i += 4) {+ let v = ((bytes[i] << 24) >>> 0) + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + bytes[i + 3]+ const c4 = v % BASE; v = Math.floor(v / BASE)+ const c3 = v % BASE; v = Math.floor(v / BASE)+ const c2 = v % BASE; v = Math.floor(v / BASE)+ const c1 = v % BASE; v = Math.floor(v / BASE)+ out.push(ALPHABET[v], ALPHABET[c1], ALPHABET[c2], ALPHABET[c3], ALPHABET[c4])+ }+ const rest = n - i+ if (rest) {+ let v = 0+ for (let k = 0; k < 4; k++) v = v * 256 + (k < rest ? bytes[i + k] : 0)+ const chars = new Array(5)+ for (let k = 4; k >= 0; k--) { chars[k] = ALPHABET[v % BASE]; v = Math.floor(v / BASE) }+ out.push(...chars.slice(0, rest + 1))+ }+ return out.join('')+}++/** base86 text → Uint8Array. Throws on a character outside the alphabet. */+export function decode(text) {+ const len = text.length+ const full = Math.floor(len / 5)+ const rest = len - full * 5 // 0, or 2–4 (n+1 chars for n bytes)+ if (rest === 1) throw new Error('b86: a trailing single character cannot encode a byte')+ const out = new Uint8Array(full * 4 + (rest ? rest - 1 : 0))+ let o = 0+ let i = 0+ const val = (c) => { const v = VALUE[c]; if (v < 0) throw new Error(`b86: bad character ${JSON.stringify(String.fromCharCode(c))}`); return v }+ for (; i + 5 <= len; i += 5) {+ const v = (((val(text.charCodeAt(i)) * BASE + val(text.charCodeAt(i + 1))) * BASE + val(text.charCodeAt(i + 2))) * BASE + val(text.charCodeAt(i + 3))) * BASE + val(text.charCodeAt(i + 4))+ out[o++] = (v / 16777216) & 255; out[o++] = (v >>> 16) & 255; out[o++] = (v >>> 8) & 255; out[o++] = v & 255+ }+ if (rest) {+ let v = 0+ for (let k = 0; k < 5; k++) v = v * BASE + (k < rest ? val(text.charCodeAt(i + k)) : BASE - 1)+ const bytes = [(v / 16777216) & 255, (v >>> 16) & 255, (v >>> 8) & 255, v & 255]+ for (let k = 0; k < rest - 1; k++) out[o++] = bytes[k]+ }+ return out+}++/** The five sequences a payload must never contain — asserted by the gate. */+export const FORBIDDEN = ['</script', '<!--', '-->', ']]>', '${']++/** The decoder as it ships inside the loader: the same arithmetic, as a+ * string, with a 128-entry lookup built from the alphabet at boot. */+export const LOADER_DECODER = `+ var B86 = ${JSON.stringify(ALPHABET)}+ var b86v = new Int16Array(128); for (var q = 0; q < 128; q++) b86v[q] = -1+ for (var q = 0; q < 86; q++) b86v[B86.charCodeAt(q)] = q+ var b86decode = function (t) {+ var n = t.length, full = (n / 5) | 0, rest = n - full * 5+ var out = new Uint8Array(full * 4 + (rest ? rest - 1 : 0)), o = 0, i = 0, v+ // a character outside the alphabet is an error, never a guess+ var c = function (j) { var x = t.charCodeAt(j), y = x < 128 ? b86v[x] : -1; if (y < 0) throw new Error('base86: bad character code ' + x + ' at index ' + j); return y }+ for (; i + 5 <= n; i += 5) {+ v = (((c(i) * 86 + c(i + 1)) * 86 + c(i + 2)) * 86 + c(i + 3)) * 86 + c(i + 4)+ out[o++] = (v / 16777216) & 255; out[o++] = (v >>> 16) & 255; out[o++] = (v >>> 8) & 255; out[o++] = v & 255+ }+ if (rest) {+ v = 0+ for (var k = 0; k < 5; k++) v = v * 86 + (k < rest ? c(i + k) : 85)+ var tail = [(v / 16777216) & 255, (v >>> 16) & 255, (v >>> 8) & 255, v & 255]+ for (var k2 = 0; k2 < rest - 1; k2++) out[o++] = tail[k2]+ }+ return out+ }`++// ————— Experimental alphabets (Teams preview bisection, 2026-09-16) —————+//+// Built to bisect why Teams' preview card stayed blue for base86 files when+// a base64 file had rendered; the bisection was overturned when the same+// bytes previewed on one upload and not the next (DECISIONS, "The preview+// pane is not deterministic"). No character conclusion stands. Kept+// build-side only, behind `--encoding` in postbuild-compress: makeCodec is+// never part of the shipped loader, which carries the b86 decoder alone.+//+// b85np / b85ns / b85nq / b85nh / b85nc / b85na+// b86 minus `%` / `*` / `?` / `#` / `:` / `@` (85; 4→5)+// b84 b86 minus `?` and `#` (84 < 85 → 7→9 group)+// b80 b86 minus the RFC 3986 gen-delims `: / ? # @` and `%` (80;+// 80^5 < 2^32 so the group is 7 bytes → 9 chars, 80^9 > 2^56,+// BigInt arithmetic: 6.32 bits per char, ×1.286)+//+// Tail rule generalised from Ascii85: n leftover bytes are zero-padded to a+// full group, encoded, and the first m characters emitted, where m is the+// least count such that max-symbol padding on decode still recovers the n+// bytes: BASE^(C−m) ≤ 256^(B−n). Both sides compute the same table.++const tailTable = (B, C, base) => {+ const chars = new Array(B).fill(0)+ for (let n = 1; n < B; n++) {+ let m = C+ while (m > 0 && Math.pow(base, C - (m - 1)) <= Math.pow(256, B - n)) m--+ chars[n] = m+ }+ return chars // chars[n] = characters emitted for n leftover bytes+}++export function makeCodec(alphabet) {+ const base = alphabet.length+ const big = Math.pow(base, 5) <= 4294967296+ const [B, C] = big ? [7, 9] : [4, 5]+ if (big && Math.pow(base, 9) <= Math.pow(2, 56)) throw new Error(`alphabet of ${base} symbols cannot carry 7 bytes in 9 chars`)+ const tail = tailTable(B, C, base)+ const value = new Int16Array(128).fill(-1)+ for (let i = 0; i < base; i++) value[alphabet.charCodeAt(i)] = i+ const val = (c) => { const v = value[c]; if (v < 0) throw new Error(`base${base}: bad character ${JSON.stringify(String.fromCharCode(c))}`); return v }+ const groupEnc = (bytes, i, count) => {+ let v = 0n+ for (let k = 0; k < B; k++) v = v * 256n + BigInt(k < count ? bytes[i + k] : 0)+ const out = new Array(C)+ const bb = BigInt(base)+ for (let k = C - 1; k >= 0; k--) { out[k] = alphabet[Number(v % bb)]; v /= bb }+ return out+ }+ const groupDec = (text, i, count, into, o) => {+ let v = 0n+ const bb = BigInt(base)+ for (let k = 0; k < C; k++) v = v * bb + BigInt(k < count ? val(text.charCodeAt(i + k)) : base - 1)+ const bytes = new Array(B)+ for (let k = B - 1; k >= 0; k--) { bytes[k] = Number(v & 255n); v >>= 8n }+ return bytes+ }+ const encode = (bytes) => {+ if (!big) { // same arithmetic as the shipped b86, parameterised by base+ const out = []; const n = bytes.length; let i = 0+ for (; i + 4 <= n; i += 4) {+ let v = ((bytes[i] << 24) >>> 0) + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + bytes[i + 3]+ const c = new Array(5)+ for (let k = 4; k >= 0; k--) { c[k] = alphabet[v % base]; v = Math.floor(v / base) }+ out.push(c[0], c[1], c[2], c[3], c[4])+ }+ const rest = n - i+ if (rest) { let v = 0; for (let k = 0; k < 4; k++) v = v * 256 + (k < rest ? bytes[i + k] : 0); const c = new Array(5); for (let k = 4; k >= 0; k--) { c[k] = alphabet[v % base]; v = Math.floor(v / base) }; out.push(...c.slice(0, tail[rest])) }+ return out.join('')+ }+ const out = []; const n = bytes.length; let i = 0+ for (; i + B <= n; i += B) out.push(...groupEnc(bytes, i, B))+ const rest = n - i+ if (rest) out.push(...groupEnc(bytes, i, rest).slice(0, tail[rest]))+ return out.join('')+ }+ const decode = (text) => {+ const len = text.length+ const full = Math.floor(len / C)+ const rest = len - full * C+ const restBytes = rest ? tail.indexOf(rest) : 0+ if (rest && restBytes < 1) throw new Error(`base${base}: a trailing run of ${rest} characters encodes nothing`)+ const out = new Uint8Array(full * B + restBytes)+ let o = 0; let i = 0+ if (!big) {+ for (; i + 5 <= len; i += 5) {+ const v = (((val(text.charCodeAt(i)) * base + val(text.charCodeAt(i + 1))) * base + val(text.charCodeAt(i + 2))) * base + val(text.charCodeAt(i + 3))) * base + val(text.charCodeAt(i + 4))+ out[o++] = (v / 16777216) & 255; out[o++] = (v >>> 16) & 255; out[o++] = (v >>> 8) & 255; out[o++] = v & 255+ }+ if (rest) { let v = 0; for (let k = 0; k < 5; k++) v = v * base + (k < rest ? val(text.charCodeAt(i + k)) : base - 1); const bytes = [(v / 16777216) & 255, (v >>> 16) & 255, (v >>> 8) & 255, v & 255]; for (let k = 0; k < restBytes; k++) out[o++] = bytes[k] }+ return out+ }+ for (; i + C <= len; i += C) { const b = groupDec(text, i, C); for (let k = 0; k < B; k++) out[o++] = b[k] }+ if (rest) { const b = groupDec(text, i, rest); for (let k = 0; k < restBytes; k++) out[o++] = b[k] }+ return out+ }+ // the decoder as it ships inside the loader for this alphabet+ const loaderDecoder = !big ? `+ var B86 = ${JSON.stringify(alphabet)}+ var b86v = new Int16Array(128); for (var q = 0; q < 128; q++) b86v[q] = -1+ for (var q = 0; q < ${base}; q++) b86v[B86.charCodeAt(q)] = q+ var b86tail = ${JSON.stringify(tail)}+ var b86decode = function (t) {+ var n = t.length, full = (n / 5) | 0, rest = n - full * 5, restBytes = rest ? b86tail.indexOf(rest) : 0+ if (rest && restBytes < 1) throw new Error('base${base}: bad tail length ' + rest)+ var out = new Uint8Array(full * 4 + restBytes), o = 0, i = 0, v+ var c = function (j) { var x = t.charCodeAt(j), y = x < 128 ? b86v[x] : -1; if (y < 0) throw new Error('base${base}: bad character code ' + x + ' at index ' + j); return y }+ for (; i + 5 <= n; i += 5) {+ v = (((c(i) * ${base} + c(i + 1)) * ${base} + c(i + 2)) * ${base} + c(i + 3)) * ${base} + c(i + 4)+ out[o++] = (v / 16777216) & 255; out[o++] = (v >>> 16) & 255; out[o++] = (v >>> 8) & 255; out[o++] = v & 255+ }+ if (rest) {+ v = 0+ for (var k = 0; k < 5; k++) v = v * ${base} + (k < rest ? c(i + k) : ${base - 1})+ var tl = [(v / 16777216) & 255, (v >>> 16) & 255, (v >>> 8) & 255, v & 255]+ for (var k2 = 0; k2 < restBytes; k2++) out[o++] = tl[k2]+ }+ return out+ }` : `+ var B86 = ${JSON.stringify(alphabet)}+ var b86v = new Int16Array(128); for (var q = 0; q < 128; q++) b86v[q] = -1+ for (var q = 0; q < ${base}; q++) b86v[B86.charCodeAt(q)] = q+ var b86tail = ${JSON.stringify(tail)}+ var b86decode = function (t) {+ var n = t.length, full = (n / ${C}) | 0, rest = n - full * ${C}, restBytes = rest ? b86tail.indexOf(rest) : 0+ if (rest && restBytes < 1) throw new Error('base${base}: bad tail length ' + rest)+ var out = new Uint8Array(full * ${B} + restBytes), o = 0, i = 0, bb = BigInt(${base})+ var c = function (j) { var x = t.charCodeAt(j), y = x < 128 ? b86v[x] : -1; if (y < 0) throw new Error('base${base}: bad character code ' + x + ' at index ' + j); return y }+ var grp = function (at, count, take) {+ var v = 0n+ for (var k = 0; k < ${C}; k++) v = v * bb + BigInt(k < count ? c(at + k) : ${base - 1})+ var bytes = new Array(${B})+ for (var k2 = ${B - 1}; k2 >= 0; k2--) { bytes[k2] = Number(v & 255n); v >>= 8n }+ for (var k3 = 0; k3 < take; k3++) out[o++] = bytes[k3]+ }+ for (; i + ${C} <= n; i += ${C}) grp(i, ${C}, ${B})+ if (rest) grp(i, rest, restBytes)+ return out+ }`+ return { ALPHABET: alphabet, BASE: base, GROUP: [B, C], encode, decode, LOADER_DECODER: loaderDecoder }+}++const without = (drop) => ALPHABET.split('').filter((ch) => !drop.includes(ch)).join('')+export const VARIANTS = {+ b86: { ALPHABET, BASE, GROUP: [4, 5], encode, decode, LOADER_DECODER },+ b85np: makeCodec(without('%')),+ b85ns: makeCodec(without('*')),+ b80: makeCodec(without('%:/?#@')),+ b85nq: makeCodec(without('?')),+ b85nh: makeCodec(without('#')),+ b85nc: makeCodec(without(':')),+ b85na: makeCodec(without('@')),+ b84: makeCodec(without('?#')), // 84 < 85 forces the 7→9 group+}diff --git a/scripts/lib/inflate-raw.js b/scripts/lib/inflate-raw.jsnew file mode 100644index 00000000..bb456613--- /dev/null+++ b/scripts/lib/inflate-raw.js@@ -0,0 +1,119 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// A raw DEFLATE (RFC 1951) decoder in plain JavaScript — stored, fixed and+// dynamic Huffman blocks — for a host without DecompressionStream. No+// dependencies, no window, so it runs in node for the byte-identity check+// and is inlined (minified) into the shell loader when asked for.+//+// inflateRaw(bytes: Uint8Array) → Uint8Array+//+// Straightforward, not fast: a bit reader, canonical Huffman tables built as+// (code length → first code) plus a symbol list, and a linear decode loop.+// The runtime payload is ~650 KB and inflates in well under a second even+// so; this path is a fallback, not the default.++export function inflateRaw(src) {+ var pos = 0, bit = 0+ var out = new Uint8Array(src.length * 4 + 1024), len = 0+ function grow(n) {+ if (len + n <= out.length) return+ var next = new Uint8Array(Math.max(out.length * 2, len + n + 1024))+ next.set(out.subarray(0, len)); out = next+ }+ function bits(n) {+ var v = 0+ for (var i = 0; i < n; i++) {+ if (pos >= src.length) throw new Error('inflate: unexpected end of data')+ v |= ((src[pos] >> bit) & 1) << i+ if (++bit === 8) { bit = 0; pos++ }+ }+ return v+ }+ // A canonical Huffman table from code lengths: count[len], symbols in code order.+ function table(lengths) {+ var count = new Uint16Array(16), symbol = new Uint16Array(lengths.length), i+ for (i = 0; i < lengths.length; i++) count[lengths[i]]+++ count[0] = 0+ var offs = new Uint16Array(16)+ for (i = 1; i < 16; i++) offs[i] = offs[i - 1] + count[i - 1]+ for (i = 0; i < lengths.length; i++) if (lengths[i]) symbol[offs[lengths[i]]++] = i+ return { count: count, symbol: symbol }+ }+ function decode(t) {+ var code = 0, first = 0, index = 0+ for (var l = 1; l < 16; l++) {+ code |= bits(1)+ var c = t.count[l]+ if (code - c < first) return t.symbol[index + (code - first)]+ index += c; first += c; first <<= 1; code <<= 1+ }+ throw new Error('inflate: bad code')+ }+ var LBASE = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258]+ var LEXT = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0]+ var DBASE = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577]+ var DEXT = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13]+ var fixedLit = null, fixedDist = null+ function codes(lit, dist) {+ for (;;) {+ var sym = decode(lit)+ if (sym < 256) { grow(1); out[len++] = sym; continue }+ if (sym === 256) return+ sym -= 257+ if (sym >= 29) throw new Error('inflate: bad length symbol')+ var n = LBASE[sym] + bits(LEXT[sym])+ var ds = decode(dist)+ if (ds >= 30) throw new Error('inflate: bad distance symbol')+ var d = DBASE[ds] + bits(DEXT[ds])+ if (d > len) throw new Error('inflate: distance too far back')+ grow(n)+ for (var i = 0; i < n; i++) { out[len] = out[len - d]; len++ }+ }+ }+ var last+ do {+ last = bits(1)+ var type = bits(2)+ if (type === 0) {+ // stored: skip to a byte boundary, LEN, NLEN, raw bytes+ if (bit) { bit = 0; pos++ }+ var n = src[pos] | (src[pos + 1] << 8), nn = src[pos + 2] | (src[pos + 3] << 8)+ if ((n ^ 0xffff) !== nn) throw new Error('inflate: stored length check failed')+ pos += 4+ grow(n); out.set(src.subarray(pos, pos + n), len); len += n; pos += n+ } else if (type === 1) {+ if (!fixedLit) {+ var l = new Uint8Array(288), i+ for (i = 0; i < 144; i++) l[i] = 8+ for (; i < 256; i++) l[i] = 9+ for (; i < 280; i++) l[i] = 7+ for (; i < 288; i++) l[i] = 8+ fixedLit = table(l)+ var dl = new Uint8Array(30); for (i = 0; i < 30; i++) dl[i] = 5+ fixedDist = table(dl)+ }+ codes(fixedLit, fixedDist)+ } else if (type === 2) {+ var nlen = bits(5) + 257, ndist = bits(5) + 1, ncode = bits(4) + 4+ var ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]+ var cl = new Uint8Array(19), j+ for (j = 0; j < ncode; j++) cl[ORDER[j]] = bits(3)+ var clt = table(cl)+ var lengths = new Uint8Array(nlen + ndist), k = 0+ while (k < nlen + ndist) {+ var s = decode(clt)+ if (s < 16) lengths[k++] = s+ else {+ var rep, val = 0+ if (s === 16) { if (!k) throw new Error('inflate: repeat with no previous length'); val = lengths[k - 1]; rep = 3 + bits(2) }+ else if (s === 17) rep = 3 + bits(3)+ else rep = 11 + bits(7)+ if (k + rep > nlen + ndist) throw new Error('inflate: too many lengths')+ while (rep--) lengths[k++] = val+ }+ }+ codes(table(lengths.subarray(0, nlen)), table(lengths.subarray(nlen)))+ } else throw new Error('inflate: bad block type')+ } while (!last)+ return out.subarray(0, len)+}diff --git a/scripts/loader-csp-server.py b/scripts/loader-csp-server.pynew file mode 100644index 00000000..cbaf17fa--- /dev/null+++ b/scripts/loader-csp-server.py@@ -0,0 +1,82 @@+#!/usr/bin/env python3+# Serve a directory with a Content-Security-Policy that allows inline script+# but NOT blob: — the closest local stand-in for SharePoint's framed HTML+# viewer (which Teams uses to open .bento.html attachments). A shell whose+# loader boots the runtime from a blob: URL is refused there; one that injects+# an inline module is not.+#+# python3 scripts/loader-csp-server.py <dir> [port] [--tt bento|other] [--hash]+#+# --hash serves each HTML file under the Teams/SharePoint-shaped policy:+# script-src = the sha256 of every inline <script> in that file + 'unsafe-eval'+# (so 'unsafe-inline' is ignored), default-src 'none', connect-src 'none',+# sandbox allow-scripts.+#+# --tt adds `require-trusted-types-for 'script'` (a string assigned to a+# script sink throws; parser-inserted scripts are exempt) and allowlists ONE+# policy name — `bento` is what the inline-tt loader creates, `other` is the+# wrong-allowlist case that must make the loader print a policy refusal.+#+# Two ports would be clearer but one is enough: every response carries the+# header, including harness.html, so the sandboxed iframes it hosts inherit+# nothing from it and get the header on their own documents.+import http.server, sys, os, re, hashlib, base64++CSP = "script-src 'unsafe-inline' 'self'; default-src 'self' data: 'unsafe-inline'; img-src * data: blob:; media-src * data: blob:; font-src * data:; style-src 'unsafe-inline' 'self'"+if '--no-eval-inline' in sys.argv:+ # inline allowed, eval refused: the eval probe must throw synchronously+ # and the cascade must take the inline path with no wait+ CSP = "script-src 'unsafe-inline' 'self'; default-src 'self' data: 'unsafe-inline'; img-src * data: blob:; media-src * data: blob:; font-src * data:; style-src 'unsafe-inline' 'self'"+if '--preview' in sys.argv:+ # A preview-like pane: inline script allowed, no eval, no blob, a+ # names-only trusted-types allowlist, sandboxed. The local assertion is+ # "zero violation events" — a loader that raises none has nothing for+ # any host to object to.+ CSP = ("default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; "+ "font-src data: blob:; media-src data: blob:; connect-src 'none'; worker-src 'none'; sandbox allow-scripts; trusted-types somename")+TT_NAMES_ONLY = None+if '--tt-names' in sys.argv:+ # an allowlist WITHOUT require-trusted-types-for: sinks take strings, but+ # createPolicy('x') for a name outside the list throws "Policy disallowed"+ TT_NAMES_ONLY = sys.argv[sys.argv.index('--tt-names') + 1]+ CSP += f"; trusted-types {TT_NAMES_ONLY}"+if '--tt' in sys.argv:+ name = sys.argv[sys.argv.index('--tt') + 1]+ # `any` = require Trusted Types but allowlist no names (every policy+ # name allowed); a name = allowlist exactly that name (space-separated+ # names allowed, e.g. "bento default")+ CSP += "; require-trusted-types-for 'script'" + ('' if name == 'any' else f"; trusted-types {name}")++HASH_MODE = '--hash' in sys.argv++def hashed_policy(path):+ # SharePoint's viewer, as observed from Teams: every inline <script> in the+ # file is allowed by its sha256, nothing else; 'unsafe-inline' is ignored+ # once hashes are present (per spec); eval is allowed; the frame is+ # sandboxed without allow-same-origin; connect-src is none.+ html = open(path, encoding='utf-8').read()+ hashes = []+ for m in re.finditer(r'<script\b[^>]*>([\s\S]*?)</script>', html):+ h = base64.b64encode(hashlib.sha256(m.group(1).encode('utf-8')).digest()).decode()+ hashes.append(f"'sha256-{h}'")+ return ("default-src 'none'; script-src " + ' '.join(hashes) + " 'unsafe-inline' 'unsafe-eval'; "+ "style-src 'unsafe-inline'; img-src data: blob:; font-src data: blob:; media-src data: blob:; "+ "connect-src 'none'; worker-src 'none'; sandbox allow-scripts"+ + (f"; trusted-types {TT_NAMES_ONLY}" if TT_NAMES_ONLY else ''))++class H(http.server.SimpleHTTPRequestHandler):+ def end_headers(self):+ csp = CSP+ if HASH_MODE:+ local = self.translate_path(self.path.split('?')[0])+ if os.path.isfile(local) and local.endswith('.html'):+ csp = hashed_policy(local)+ self.send_header('Content-Security-Policy', csp)+ self.send_header('Cache-Control', 'no-store')+ super().end_headers()+ def log_message(self, *a):+ pass++os.chdir(sys.argv[1])+port = int(sys.argv[2]) if len(sys.argv) > 2 and not sys.argv[2].startswith('--') else 5179+http.server.ThreadingHTTPServer(('127.0.0.1', port), H).serve_forever()diff --git a/scripts/postbuild-compress.mjs b/scripts/postbuild-compress.mjsindex b7aeb670..54781c7d 100644--- a/scripts/postbuild-compress.mjs+++ b/scripts/postbuild-compress.mjs@@ -13,9 +13,16 @@// head chrome → NOTICE → tooling comment → #bento-doc (PLAINTEXT, always)// → splash (paints while the payload parses) → payloads + 1KB loader last//-// The loader inflates via the native DecompressionStream and boots the module-// from a blob URL. Browsers without DecompressionStream (pre-2023 Safari) get-// a plain-HTML message instead of a blank page.+// The loader decodes and inflates SYNCHRONOUSLY (a ~2 KB JavaScript+// inflater; see --inflate) and runs the runtime as an inline classic script,+// inside its own parser-inserted script — so the editor is mounted before+// DOMContentLoaded, exactly as the uncompressed build is, and no task, timer+// or frame stands between the file and its app. A hidden document (a+// background tab, a viewer rendering off-screen for a preview card)+// throttles timers and delivers no frames; the earlier promise-based loader+// mounted the app ~300 ms after `load` there and Teams' preview card+// captured the splash by chance. Under a policy that refuses the inline+// script it falls to new Function, then — the only promise — a blob import.//// COMPATIBILITY CONTRACT (老 updaters are frozen code — we conform to them):// - #bento-doc stays plaintext with the same id.@@ -28,6 +35,7 @@ import { readFileSync, writeFileSync } from 'node:fs'import { deflateRawSync, inflateRawSync } from 'node:zlib'import { createRequire } from 'node:module'import { join } from 'node:path'+import { FORBIDDEN, VARIANTS } from './lib/b86.mjs'/*** ZOPFLI, not zlib.@@ -106,6 +114,98 @@ const flag = (name, fallback) => {}const generator = flag('generator', 'bento-slides')const titleFallback = flag('title', 'bento/slides')+// How the inflated runtime is started. `cascade` (the default since 1.1.1):+// see below. `blob` (the 1.1.0 loader): a module import from a blob: URL. `inline`: an inline <script type="module"> whose+// textContent is the inflated bundle — no blob: URL at all, so it runs where a+// Content-Security-Policy allows 'unsafe-inline' but not blob: (SharePoint's+// framed HTML viewer, which Teams uses to open attachments, is the case that+// found this: the shipped shell showed its splash and nothing else there).+// The bundle is byte-identical either way; only the 1KB loader differs.+const loaderMode = flag('loader', 'cascade')+if (!['blob', 'inline', 'inline-tt', 'cascade', 'cascade-eval-first', 'cascade-eager-tt'].includes(loaderMode)) throw new Error(`--loader must be blob, inline, inline-tt, cascade, cascade-eval-first or cascade-eager-tt, got ${loaderMode}`)+// NO PROBING. Teams' open pane hashes the file's inline scripts and allows+// eval; a hashing policy refuses an inserted script WITH a report, and no+// policy accepts one silently, so an inline insertion is the one first step+// that never leaves the loader guessing. (Its preview pane was once read as+// killing a frame on any reported violation; that reading did not survive+// re-uploads of identical bytes — DECISIONS 2026-09-16.) So `cascade` does+// the one thing that is refused nowhere first — insert the inline module, exactly as the plain inline+// loader — and only on a violation attributed to that attempt falls to+// new Function, then to the blob import. `cascade-eval-first` is the earlier+// order, kept for the record.+// Trusted Types are LAZY in `cascade`: no createPolicy at boot. Only when a+// sink throws the TypeError that names TrustedScript/TrustedHTML are the+// policies (bento + default) installed and that step retried once. An eager+// createPolicy under a names-only allowlist raises CSP violations even when+// caught, and a violation nobody needed is a violation nobody has to+// explain.+// `cascade-eager-tt` keeps the eager install for comparison.+// `cascade`: eval first. `new Function('')` throws AT ONCE under a policy+// without 'unsafe-eval', so the probe is synchronous and costs nothing; where+// it passes, the bundle runs through new Function immediately — an indirect+// eval, which a script-hash policy does not govern. Otherwise (2) an inline+// <script type="module"> (Trusted Types policies installed first where+// trustedTypes exists), abandoned on a synchronous throw or a+// securitypolicyviolation in a short window, then (3) the blob import. The+// path taken is recorded on window.bento.loader. This is the shape+// SharePoint's viewer needs: it hashes the file's own inline scripts and+// allows exactly those, so an inserted script is refused (unhashed) while+// eval is allowed. `cascade-inline-first` is the earlier order (inline,+// function, blob) — a build-time switch only, no runtime cost.+// `inline-tt`: inline, and the source is assigned through a Trusted Types+// policy named "bento" where the page enforces `require-trusted-types-for+// 'script'` (assigning a plain string to script.textContent throws there;+// the parser-inserted loader itself is exempt). `--diag` adds a visible+// on-page diagnostic panel — environment facts before the boot, every error+// after it — for a viewer where no console can be opened. Never on by default:+// the loader ships in every file and diag text is bytes.+const diag = process.argv.includes('--diag')+// The payload carrier alphabet. `b86` (default): scripts/lib/b86.mjs — 86+// printable ASCII symbols chosen so `</script`, `<!--`, `-->`, `]]>` and `${`+// are unproducible by construction, 4 bytes → 5 chars, 6.25% smaller than+// base64 (block type bento/deflate-b86). `b64`: base64, the pre-1.1.1 block+// type bento/deflate-b64, kept for comparison; every reader handles both.+// The other names (EXPERIMENT, never the default — see the variants note+// in lib/b86.mjs): narrower alphabets built for a Teams preview-pane+// bisection that proved nondeterministic; block type bento/deflate-<name>,+// which the gate does not accept, so they cannot reach a release.+const encoding = flag('encoding', 'b86')+if (!['b64', ...Object.keys(VARIANTS)].includes(encoding)) throw new Error(`--encoding must be b64, b86 or one of ${Object.keys(VARIANTS).join('|')}, got ${encoding}`)+const codec = encoding === 'b64' ? null : VARIANTS[encoding]+const PAYLOAD_TYPE = `bento/deflate-${encoding}`+// How the two deflated payloads are CARRIED in the file. `script` (shipped):+// <script type="bento/deflate-b64">. `template`: <template data-bento-payload>+// (its content is inert DOM, not a script, so a viewer that strips non-JS+// scripts leaves it alone). `textplain`: <script type="text/plain">. base64+// cannot contain "</" so no carrier can close itself early. All three keep+// the same ids, and none is transient — a save keeps the runtime.+const carrier = flag('carrier', 'script')+if (!['script', 'template', 'textplain'].includes(carrier)) throw new Error(`--carrier must be script, template or textplain, got ${carrier}`)+// How the payload is inflated. `js` (shipped): a plain-JavaScript RFC 1951+// decoder inlined into the loader (scripts/lib/inflate-raw.js, ~2 KB+// minified) — SYNCHRONOUS, which is the point: the runtime is decoded,+// inflated and evaluated inside the loader's own parser-inserted script,+// so the editor is mounted before DOMContentLoaded and `load`, exactly as+// the uncompressed build is, and no task, timer or frame stands between+// the file and its app (a hidden document — a background tab, a viewer+// rendering off-screen — throttles timers and never delivers frames; the+// uncompressed build previewed in Teams' pane every time and the+// compressed one by chance, until this). Costs 18 ms against+// DecompressionStream's 6 on the runtime payload, visible; 99 against 18+// hidden. `native`: DecompressionStream, promise-based — the mount then+// lands in a later task, after `load`. `auto`: native where present.+const inflateMode = flag('inflate', 'js')+if (!['native', 'auto', 'js'].includes(inflateMode)) throw new Error(`--inflate must be native, auto or js, got ${inflateMode}`)+const INFLATE_JS = inflateMode === 'native' ? '' : (() => {+ const { execFileSync } = createRequire(import.meta.url)('node:child_process')+ const src = readFileSync(new URL('./lib/inflate-raw.js', import.meta.url), 'utf8').replace(/^export function/m, 'function')+ const esbuild = join(process.cwd(), 'node_modules/.bin/esbuild')+ const min = execFileSync(esbuild, ['--minify', '--format=esm', '--target=es2017'], { input: src + '\nexport { inflateRaw }', encoding: 'utf8' })+ // esbuild renames the function; the export clause says what it became+ const m = /export\s*\{\s*(\w+)(?:\s+as\s+inflateRaw)?\s*\};?\s*$/.exec(min)+ if (!m) throw new Error('inflater: export clause not found after minify')+ return min.slice(0, m.index) + (m[1] === 'inflateRaw' ? '' : `var inflateRaw=${m[1]};`)+})()const html = readFileSync(path, 'utf8')if (html.includes('id="bento-rt"')) {@@ -156,9 +256,14 @@ if (!styleM) throw new Error('app stylesheet not found')const js = mod[1]const css = styleM[1]-const b64 = async (s) => (await deflate(Buffer.from(s, 'utf8'))).toString('base64')-const jsB64 = await b64(js)-const cssB64 = await b64(css)+const pack = async (s) => {+ const packed = await deflate(Buffer.from(s, 'utf8'))+ const text = codec ? codec.encode(new Uint8Array(packed)) : packed.toString('base64')+ for (const f of FORBIDDEN) if (text.includes(f)) throw new Error(`payload text contains ${JSON.stringify(f)} — the carrier alphabet is not safe`)+ return text+}+const jsB64 = await pack(js)+const cssB64 = await pack(css)// --- other parts ------------------------------------------------------------const notice = html.match(/<!--\s*NOTICE[\s\S]*?-->/)?.[0] ?? ''@@ -268,8 +373,78 @@ const TOOLING_COMMENT = generator === 'bento-slides' ? SLIDES_TOOLING : GENERIC_// 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 DIAG = `+ var box = null+ var say = function (t, b) {+ if (!box) {+ box = document.createElement('pre')+ box.id = 'bento-diag'+ box.setAttribute('data-bento-transient', '') // never saved into the file+ box.style.cssText = 'position:fixed;left:0;right:0;bottom:0;max-height:70vh;overflow:auto;margin:0;padding:12px 16px;background:#000;color:#7CFC00;font:15px/1.45 ui-monospace,Menlo,monospace;white-space:pre-wrap;word-break:break-all;z-index:2147483647'+ document.body.appendChild(box)+ // the first three lines are the instrument a preview CARD can show:+ // large type, so a thumbnail-sized render of the pane still reads+ big = document.createElement('div')+ big.style.cssText = 'font-size:52px;line-height:1.1;font-weight:700;color:#fff;margin-bottom:12px'+ box.appendChild(big)+ rest = document.createElement('div')+ box.appendChild(rest)+ }+ if (b && bigLines < 3) { bigLines++; big.textContent += t + '\\n' } else rest.textContent += t + '\\n'+ }+ var big = null, rest = null, bigLines = 0+ window.addEventListener('error', function (e) { say('window error: ' + e.message + ' @ ' + (e.filename || '?') + ':' + e.lineno) })+ window.addEventListener('unhandledrejection', function (e) { var r = e.reason; say('unhandled rejection: ' + (r && r.stack ? String(r.stack).split('\\n').slice(0, 4).join(' | ') : String(r))) })+ var probe = function (name, fn) { try { var v = fn(); say(name + ': ' + v) } catch (e) { say(name + ': THROWS ' + (e && e.name) + ' ' + (e && e.message)) } }+ var st0 = document.getElementById('bento-diag-static'); if (st0) st0.remove()+ say('LOADER RAN ' + ${JSON.stringify(encoding)} + ' · ' + document.visibilityState + (document.hidden ? ' (hidden)' : ''), true)+ // a running count of animation frames since loader start: a document that+ // is never painted (a background tab, an off-screen render) delivers none+ var rafN = 0, rafLine = document.createElement('div'), rafT0 = performance.now()+ var rafShow = function () { rafLine.textContent = 'rAF callbacks since loader start: ' + rafN + ' · visibility ' + document.visibilityState + ' · hidden ' + document.hidden + ' · t=' + Math.round(performance.now() - rafT0) + ' ms' }+ var rafTick = function () { rafN++; rafShow(); if (rafN < 600) requestAnimationFrame(rafTick) }+ rafLine.style.cssText = 'font-size:40px;line-height:1.1;font-weight:700;color:#ffd166;margin-bottom:12px'+ box.insertBefore(rafLine, rest)+ requestAnimationFrame(rafTick); rafShow()+ setInterval(rafShow, 500)+ document.addEventListener('visibilitychange', function () { say('visibilitychange → ' + document.visibilityState + ' at t=' + Math.round(performance.now()) + ' ms') })+ var pl = function (id) {+ var el = document.getElementById(id); if (!el) return 'NOT FOUND'+ var t = (el.content ? el.content.textContent : el.textContent) || ''+ var expect = el.getAttribute('data-len')+ var line = 'found <' + el.tagName.toLowerCase() + (el.type ? ' type=' + el.type : '') + '> text length ' + t.length + (expect ? ' (built as ' + expect + (String(t.length) === expect ? ', same' : ', DIFFERS by ' + (t.length - Number(expect))) + ')' : '')+ var raw = t.trim()+ if (raw.length !== t.length) line += '; trimmed ' + (t.length - raw.length) + ' whitespace chars'+ var alpha = (el.type === ${JSON.stringify(PAYLOAD_TYPE)} && ${JSON.stringify(!!codec)}) ? ${JSON.stringify(codec ? codec.ALPHABET : '')} : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='+ for (var i = 0; i < raw.length; i++) {+ if (alpha.indexOf(raw.charAt(i)) < 0) { line += '; FIRST BAD CHAR at index ' + i + ': code ' + raw.charCodeAt(i) + ' ' + JSON.stringify(raw.charAt(i)) + ' around ' + JSON.stringify(raw.slice(Math.max(0, i - 8), i + 9)); return line }+ }+ return line + '; every char in the alphabet'+ }+ var pljs = pl('bento-rt')+ say(/every char in the alphabet/.test(pljs) ? 'JS PAYLOAD INTACT' + (/DIFFERS/.test(pljs) ? ' but LENGTH DIFFERS' : '') : /NOT FOUND/.test(pljs) ? 'JS PAYLOAD NOT FOUND' : 'JS PAYLOAD CORRUPT: ' + pljs.replace(/^.*FIRST BAD CHAR/, 'bad char'), true)+ say('bento loader diag ' + new Date().toISOString() + ' — the loader ran (the static "loader did not run" line was removed by its first statement)')+ say('payload js (#bento-rt): ' + pljs)+ say('payload css (#bento-rt-css): ' + pl('bento-rt-css'))+ probe('typeof DecompressionStream', function () { return typeof DecompressionStream })+ probe('document.scripts', function () { var t = []; for (var i = 0; i < document.scripts.length; i++) t.push(document.scripts[i].type || '(no type)'); return document.scripts.length + ' [' + t.join(', ') + ']' })+ probe('trustedTypes', function () { return !!window.trustedTypes + (window.trustedTypes ? ' (default policy ' + (window.trustedTypes.defaultPolicy ? 'set' : 'none') + ')' : '') })+ probe('currentScript', function () { return document.currentScript ? 'parser' : 'no currentScript' })+ probe('localStorage.length', function () { return localStorage.length })+ probe('sessionStorage.length', function () { return sessionStorage.length })+ probe('indexedDB', function () { return typeof indexedDB })+ probe('location.origin', function () { return location.origin })+ probe('self.origin (the document origin)', function () { return self.origin })+ probe('location.href', function () { return String(location.href).slice(0, 80) })+ probe('framed (self !== top)', function () { return self !== top })+ probe('userAgent', function () { return navigator.userAgent.slice(0, 40) })+ probe('meta csp', function () { var m = document.querySelector('meta[http-equiv=Content-Security-Policy]'); return m ? m.content : 'no meta csp (a header CSP is invisible here)' })+ document.addEventListener('securitypolicyviolation', function (e) { say('CSP violation: ' + e.violatedDirective + ' blocked ' + e.blockedURI + (e.sample ? ' sample ' + e.sample : '')) })+`const loader = `-(async () => {+(async () => {${diag ? DIAG : ''}+ var violations = 0+ document.addEventListener('securitypolicyviolation', function () { violations++ })var fail = function (msg) {var d = document.createElement('div')d.style.cssText = 'position:fixed;inset:0;display:flex;align-items:center;justify-content:center;background:#0D1B2E;color:#F2F0EA;font:16px/1.6 sans-serif;text-align:center;padding:40px;z-index:99999'@@ -277,7 +452,7 @@ const loader = `document.body.appendChild(d)var s = document.getElementById('bento-splash'); if (s) s.remove()}- if (typeof DecompressionStream === 'undefined') {+ if (${inflateMode === 'js' ? "typeof Uint8Array === 'undefined' || typeof TextDecoder === 'undefined'" : inflateMode === 'native' ? "typeof DecompressionStream === 'undefined'" : 'false'}) {// The old text said "2023 or later" and then listed Chrome 80, which is// 2020 — a reader checking their version against it learns nothing. It also// never said what kind of file this is, and never mentioned that the data@@ -286,15 +461,28 @@ const loader = `fail('<b>This is a bento/dash spreadsheet.</b><br>Opening it needs a browser released in 2023 or later \\u2014 Safari 16.4+, Firefox 113+, or a current Chrome or Edge.<br><br>Nothing is lost: your data is stored as plain readable JSON inside this same file. Open it in a newer browser, or open it in a text editor and look for the block marked "bento-doc".')return}- var inflate = async function (id) {- var b64 = document.getElementById(id).textContent.trim()- var bytes = Uint8Array.from(atob(b64), function (c) { return c.charCodeAt(0) })- var ds = new DecompressionStream('deflate-raw')- var stream = new Blob([bytes]).stream().pipeThrough(ds)- return await new Response(stream).text()+ ${INFLATE_JS}${codec ? codec.LOADER_DECODER : ''}+ var inflate = ${inflateMode === 'js' ? 'function' : 'async function'} (id) {+ var el = document.getElementById(id)+ var txt = (el.content ? el.content.textContent : el.textContent).trim()+ var bytes+ try { bytes = ${codec ? 'b86decode(txt)' : "Uint8Array.from(atob(txt), function (c) { return c.charCodeAt(0) })"} }+ catch (e) {${diag ? ` say('DECODE FAILED for #' + id + ': ' + (e && e.name) + ': ' + (e && e.message), true);` : ''} throw e }+ var text+ ${inflateMode === 'js' ? `text = new TextDecoder().decode(inflateRaw(bytes))${diag ? `+ say('inflated #' + id + ' with the JavaScript decoder: ' + text.length + ' chars')` : ''}` : `if (${inflateMode === 'auto' ? "typeof DecompressionStream === 'undefined'" : 'false'}) {+ text = new TextDecoder().decode(inflateRaw(bytes))${diag ? `+ say('inflated #' + id + ' with the JavaScript decoder: ' + text.length + ' chars')` : ''}+ } else {+ var ds = new DecompressionStream('deflate-raw')+ var stream = new Blob([bytes]).stream().pipeThrough(ds)+ text = await new Response(stream).text()${diag ? `+ say('inflated #' + id + ' with DecompressionStream: ' + text.length + ' chars')` : ''}+ }`}+ return text}try {- var css = await inflate('bento-rt-css')+ var css = ${inflateMode === 'js' ? '' : 'await '}inflate('bento-rt-css')// drop stale plaintext copies (see TRANSIENT DOM above), then inject oursvar old = document.querySelectorAll('style')for (var i = 0; i < old.length; i++) {@@ -305,10 +493,124 @@ const loader = `st.setAttribute('data-bento-transient', '')st.textContent = cssdocument.head.appendChild(st)- var js = await inflate('bento-rt')- var url = URL.createObjectURL(new Blob([js], { type: 'text/javascript' }))- await import(url)- } catch (e) {+ var js = ${inflateMode === 'js' ? '' : 'await '}inflate('bento-rt')+ ${['cascade', 'cascade-eval-first', 'cascade-eager-tt'].includes(loaderMode) ? `var tried = [], path = null, tt = 'none'+ var installTT = function () {+ if (tt !== 'none' || !(window.trustedTypes && window.trustedTypes.createPolicy)) return+ tt = 'installed'+ try { window.trustedTypes.createPolicy('bento', { createScript: function (s) { return s } }) } catch (e) { tried.push('tt bento: ' + (e && e.message)) }+ if (!window.trustedTypes.defaultPolicy) {+ try { window.trustedTypes.createPolicy('default', { createHTML: function (s) { return s }, createScript: function (s) { return s }, createScriptURL: function (s) { return s } }) } catch (e) { tried.push('tt default: ' + (e && e.message)) }+ }+ }+ // a sink refused a plain string: install the policies and let the caller retry once+ var needsTT = function (e) { return !!(e && /Trusted(Script|HTML)/.test(String(e.message))) && tt === 'none' }+ ${loaderMode === 'cascade-eager-tt' ? 'installTT()' : ''}+ // Every step but the last is SYNCHRONOUS: an inline CLASSIC script+ // inserted with appendChild executes during the insertion (a module+ // script would be deferred to a later task — and in a hidden document+ // that task may never come before whoever is looking has looked), so+ // whether it ran is known when appendChild returns: the app is there,+ // or the policy refused it (a hashing policy reports the refusal; the+ // report arrives in a later task and is counted, but nothing waits for+ // it). Then new Function, also synchronous. Only the blob import is a+ // promise, and it is the last resort.+ var mounted = function () { return !!(window.bento && window.bento.doc) }+ var runNow = function (name, fn) {+ if (mounted()) return true+ try { fn() } catch (e) { tried.push(name + ': ' + (e && e.name) + ': ' + (e && e.message))${diag ? `; say('loader path ' + name + ' → ' + tried[tried.length - 1] + ' (t=' + Math.round(performance.now()) + ' ms since navigation)', true)` : ''}; return false }+ var okp = mounted()+ tried.push(name + (okp ? ': ok' : ': ran, no app (refused, or the app did not mount)'))${diag ? `+ say('loader path ' + name + ' → ' + tried[tried.length - 1] + ' (t=' + Math.round(performance.now()) + ' ms since navigation)', true)` : ''}+ if (okp) path = name+ return okp+ }+ var viaInline = function () {+ // classic, not module: the bundle has no top-level import/export/await,+ // and a classic inline script runs inside appendChild+ var sc = document.createElement('script')+ sc.id = 'bento-rt-script'+ sc.setAttribute('data-bento-transient', '')+ var src = "'use strict';" + js + "\\n//# sourceURL=bento-slides.js"+ try { sc.textContent = src } catch (e) {+ if (!needsTT(e)) throw e+ tried.push('inline sink: ' + (e && e.message)); installTT(); sc.textContent = src+ }+ document.body.appendChild(sc)+ // a refused script stays in the DOM as dead weight — and a save would+ // strip it anyway (transient), but keep the document clean+ if (!mounted()) sc.remove()+ }+ var viaFunction = function () {+ // an indirect eval, ungoverned by script hashes and allowed by+ // 'unsafe-eval'; 'use strict' restores module semantics and the+ // sourceURL names it in DevTools (stacks say bento-slides.js)+ var run = function () { new Function("'use strict';" + js + "\\n//# sourceURL=bento-slides.js")() }+ try { run() } catch (e) { if (!needsTT(e)) throw e; tried.push('function sink: ' + (e && e.message)); installTT(); run() }+ }+ ${loaderMode === 'cascade-eval-first' ? `runNow('function', viaFunction)+ if (!path) runNow('inline', viaInline)` : `runNow('inline', viaInline)+ if (!path) runNow('function', viaFunction)`}+ if (!path) {+ // the one asynchronous step, and the last: a blob: module import+ var why = null+ var onv = function (e) { if (e.blockedURI === 'blob') why = e.violatedDirective + ' blocked blob' }+ document.addEventListener('securitypolicyviolation', onv)+ try {+ var url = URL.createObjectURL(new Blob([js], { type: 'text/javascript' }))+ await import(url)+ } catch (e) { why = why || ((e && e.name) + ': ' + (e && e.message)) }+ document.removeEventListener('securitypolicyviolation', onv)+ var okb = !why && mounted()+ tried.push('blob' + (okb ? ': ok' : why ? ': ' + why : ': imported, no app'))${diag ? `+ say('loader path blob → ' + tried[tried.length - 1] + ' (t=' + Math.round(performance.now()) + ' ms since navigation)', true)` : ''}+ if (okb) path = 'blob'+ }+ if (!path) throw new Error('every loader path was refused: ' + tried.join('; '))+ if (window.bento) window.bento.loader = { path: path, tried: tried, tt: tt, violations: violations }` : loaderMode !== 'blob' ? `// inline module: allowed under CSP 'unsafe-inline', needs no blob: source.+ // Transient like the style above — a save must never write the inflated+ // bundle back as plaintext (serializeBody strips marked nodes).+ var sc = document.createElement('script')+ sc.type = 'module'+ sc.id = 'bento-rt-script'+ sc.setAttribute('data-bento-transient', '')+ var src = js${loaderMode === 'inline-tt' ? `+ // Trusted Types: where the page requires them for script sinks, a plain+ // string assignment throws; a policy-made TrustedScript does not. A CSP+ // that allowlists policy names refuses any other name — that refusal is+ // itself the diagnosis, so it is reported rather than swallowed.+ if (window.trustedTypes && window.trustedTypes.createPolicy) {+ try {+ var pol = window.trustedTypes.createPolicy('bento', { createScript: function (s) { return s } })+ src = pol.createScript(js)${diag ? `+ say('trustedTypes: policy "bento" created; assigning a TrustedScript')` : ''}+ } catch (e) {${diag ? `+ say('trustedTypes: createPolicy("bento") REFUSED: ' + (e && e.name) + ': ' + (e && e.message))` : ''}+ }+ // The app itself assigns innerHTML (the renderer, the sanitizer) and+ // script.text (the save path writes #bento-doc back) from strings. Under+ // enforced Trusted Types every one of those throws unless a DEFAULT+ // policy exists — the browser routes plain-string sink assignments+ // through it. A CSP that allowlists policy names must include "default"+ // for this to be allowed; where it is refused, the refusal is reported.+ if (!window.trustedTypes.defaultPolicy) {+ try {+ window.trustedTypes.createPolicy('default', { createHTML: function (s) { return s }, createScript: function (s) { return s }, createScriptURL: function (s) { return s } })${diag ? `+ say('trustedTypes: DEFAULT policy created (string sinks pass through)')` : ''}+ } catch (e) {${diag ? `+ say('trustedTypes: createPolicy("default") REFUSED: ' + (e && e.name) + ': ' + (e && e.message))` : ''}+ }+ }+ }` : ''}+ try { sc.textContent = src } catch (e) {${diag ? `+ say('script.textContent assignment threw: ' + (e && e.name) + ': ' + (e && e.message) + ' — trying script.text')` : ''}+ sc.text = src+ }+ document.body.appendChild(sc)${diag ? `+ say('module script appended (' + js.length + ' chars); waiting for the app to mount')` : ''}` : `var url = URL.createObjectURL(new Blob([js], { type: 'text/javascript' }))+ await import(url)`}+ } catch (e) {${diag ? `+ say('BOOT FAILED: ' + (e && e.name) + ': ' + (e && e.message) + (e && e.stack ? ' | ' + String(e.stack).split('\\n').slice(0, 3).join(' | ') : ''), true)` : ''}fail('This file could not start: ' + (e && e.message ? e.message : e))}})()@@ -331,10 +633,13 @@ const out = `<!DOCTYPE html><style>${splashCss}</style></head><body>- ${splashDiv}+ ${splashDiv}${diag ? `+ <pre id="bento-diag-static" style="position:fixed;left:0;right:0;bottom:0;margin:0;padding:12px 16px;background:#000;color:#ff5555;font:15px/1.45 ui-monospace,Menlo,monospace;z-index:2147483647">loader did not run — this line is static markup; the loader's first statement removes it</pre>` : ''}<div id="app"></div>- <script id="bento-rt-css" type="bento/deflate-b64">${cssB64}</script>- <script id="bento-rt" type="bento/deflate-b64">${jsB64}</script>+ ${carrier === 'template' ? `<template id="bento-rt-css" data-bento-payload="css">${cssB64}</template>+ <template id="bento-rt" data-bento-payload="js">${jsB64}</template>` : carrier === 'textplain' ? `<script id="bento-rt-css" type="text/plain" data-bento-payload="css" data-bento-encoding="${encoding}">${cssB64}</script>+ <script id="bento-rt" type="text/plain" data-bento-payload="js">${jsB64}</script>` : `<script id="bento-rt-css" type="${PAYLOAD_TYPE}" data-len="${cssB64.length}">${cssB64}</script>+ <script id="bento-rt" type="${PAYLOAD_TYPE}" data-len="${jsB64.length}">${jsB64}</script>`}<script>${loader}</script></body></html>@@ -347,4 +652,4 @@ if (closes !== opens) throw new Error(`script tag imbalance: ${opens} opens, ${cwriteFileSync(path, out)const kb = (n) => `${Math.round(n / 1024)}KB`-console.log(`compressed shell: ${kb(html.length)} → ${kb(out.length)} (js ${kb(js.length)}→${kb(jsB64.length)}, css ${kb(css.length)}→${kb(cssB64.length)})`)+console.log(`compressed shell: ${kb(html.length)} → ${kb(out.length)} (js ${kb(js.length)}→${kb(jsB64.length)}, css ${kb(css.length)}→${kb(cssB64.length)}, ${encoding})`)diff --git a/scripts/publish-site.mjs b/scripts/publish-site.mjsindex b0ef171c..096cee7b 100755--- a/scripts/publish-site.mjs+++ b/scripts/publish-site.mjs@@ -106,7 +106,7 @@ if (doGallery) {const shellFile = join(site, 'releases/slides/Bento_Slides.bento.html')if (existsSync(shellFile)) {const appHash = (file) => {- const blocks = [...readFileSync(file, 'utf8').matchAll(/type="bento\/deflate-b64"[^>]*>([A-Za-z0-9+/=]+)</g)].map((m) => m[1])+ const blocks = [...readFileSync(file, 'utf8').matchAll(/type="bento\/deflate-b(?:64|86)"[^>]*>([^<]+)</g)].map((m) => m[1])return blocks.length ? createHash('sha256').update(blocks.join('')).digest('hex') : null}const shellHash = appHash(shellFile)diff --git a/scripts/reseed-guestbook.mjs b/scripts/reseed-guestbook.mjsindex 06ee1f3b..576264c4 100644--- a/scripts/reseed-guestbook.mjs+++ b/scripts/reseed-guestbook.mjs@@ -46,7 +46,7 @@ const warn = (m) => { console.warn(`⚠ guestbook re-seed skipped: ${m}`) }// App payload fingerprint — the deflate-b64 runtime blocks. Two decks with the// same hash embed the same shell (identical runtime), whatever their doc holds.const appHash = (html) => {- const blocks = [...html.matchAll(/type="bento\/deflate-b64"[^>]*>([A-Za-z0-9+/=]+)</g)].map((m) => m[1])+ const blocks = [...html.matchAll(/type="bento\/deflate-b(?:64|86)"[^>]*>([^<]+)</g)].map((m) => m[1])return blocks.length ? createHash('sha256').update(blocks.join('')).digest('hex') : null}diff --git a/scripts/shell-gate.mjs b/scripts/shell-gate.mjsindex bf52c727..7aa0b4cf 100644--- a/scripts/shell-gate.mjs+++ b/scripts/shell-gate.mjs@@ -39,6 +39,7 @@ import { existsSync, readFileSync } from 'node:fs'import { dirname, join } from 'node:path'import { fileURLToPath } from 'node:url'import { inflateRawSync } from 'node:zlib'+import { decode as b86decode, FORBIDDEN } from './lib/b86.mjs'const here = dirname(fileURLToPath(import.meta.url))const repoRoot = dirname(here)@@ -247,19 +248,25 @@ function checkPackCarryingShell(shell) {// --- invariant 4: the runtime stays compressed, and stays out of the save ---const TRANSIENT_ATTR = 'data-bento-transient'-const PAYLOAD_TYPE = 'bento/deflate-b64'+const PAYLOAD_TYPES = ['bento/deflate-b64', 'bento/deflate-b86']+const isPayload = (s) => PAYLOAD_TYPES.includes(s.type)/** 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. */+/** The inflated text of each payload block (b64 or b86), by id. */function inflatePayloads(html) {const out = new Map()- for (const s of scanScripts(html).filter((x) => x.type === PAYLOAD_TYPE)) {+ for (const s of scanScripts(html).filter(isPayload)) {+ // A payload's text must never be able to close or comment out the block+ // that carries it. base64 cannot produce these; base86 excludes the+ // characters by construction; a hand-edited payload is caught here.+ for (const f of FORBIDDEN) if (s.text.includes(f)) fail(`payload #${s.id} contains ${JSON.stringify(f)} — a payload must not be able to end its own block`)try {- out.set(s.id, inflateRawSync(Buffer.from(s.text.trim(), 'base64')).toString('utf8'))+ const bytes = s.type === 'bento/deflate-b86' ? Buffer.from(b86decode(s.text.trim())) : Buffer.from(s.text.trim(), 'base64')+ out.set(s.id, inflateRawSync(bytes).toString('utf8'))} catch (e) {fail(`payload #${s.id} does not inflate: ${e.message}`)}@@ -280,7 +287,7 @@ function checkRuntimeStaysCompressed(html, label) {if (!payloads.size) return false // an uncompressed build — nothing to checkconst plaintext = [...scanStyles(html),- ...scanScripts(html).filter((s) => s.type !== PAYLOAD_TYPE).map((s) => s.text),+ ...scanScripts(html).filter((s) => !isPayload(s)).map((s) => s.text),]for (const [id, text] of payloads) {if (plaintext.some((body) => body.includes(text)))diff --git a/scripts/test-shell-loader.ts b/scripts/test-shell-loader.tsnew file mode 100644index 00000000..ef0e9d33--- /dev/null+++ b/scripts/test-shell-loader.ts@@ -0,0 +1,255 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The compressed shell's carrier and loader (postbuild-compress.mjs):+//+// node scripts/test-shell-loader.ts+//+// WHAT THIS PROVES. (1) base86 (scripts/lib/b86.mjs) round-trips every byte+// length mod 4 and the edge values, and its text can never contain the five+// sequences that would end or comment out the block carrying it — asserted+// over 10,000 random buffers and their concatenations, by construction (the+// characters are not in the alphabet) and by search; the loader's own inline+// decoder agrees with the node one byte for byte. (2) A shell built from a+// synthetic vite-shaped page carries bento/deflate-b86 blocks, passes the+// splice gate, and the gate goes RED when a payload is hand-edited to contain+// `-->`. (3) The loader probes nothing and WAITS on nothing: no new+// Function('') probe, no createPolicy outside the lazy install; the runtime+// is decoded and inflated synchronously and run as an inline CLASSIC script+// (executed inside appendChild), then new Function, then — the only promise+// — a blob import; no timer, frame or module-graph task stands between the+// file and its app, so the editor is mounted before DOMContentLoaded, as the+// uncompressed build is. (4) In a real browser, in a HIDDEN document (a+// background tab; a viewer rendering off-screen for a preview card), the+// shell mounts before DOMContentLoaded and the splash is gone within 50 ms+// of the mount; visible, the brand hold ends within its cap. A hidden+// document throttles timers and never delivers frames — a splash that+// waited on its own fade stayed over the mounted editor for as long as+// nobody looked. Needs the built shell and Chrome; self-skips without.++import { readFileSync, writeFileSync, mkdtempSync, rmSync, existsSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dirname, join } from 'node:path'+import { tmpdir } from 'node:os'+import { execFileSync, spawn, spawnSync } from 'node:child_process'+import { createServer } from 'node:http'+import { randomBytes } from 'node:crypto'+import { deflateRawSync } from 'node:zlib'+import { encode, decode, ALPHABET, BASE, FORBIDDEN, LOADER_DECODER } from './lib/b86.mjs'++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}+const root = join(dirname(fileURLToPath(import.meta.url)), '..')+const eq = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((v, i) => v === b[i])++console.log('base86 — the alphabet\n')+ok(BASE === 86 && ALPHABET.length === 86, 'eighty-six symbols')+ok(!/[<>&"'\\\-{ ]/.test(ALPHABET), 'no < > & " \' \\ - { or space — the five sequences are unproducible by construction')+ok(new Set(ALPHABET).size === 86 && [...ALPHABET].every((c) => c.charCodeAt(0) >= 0x21 && c.charCodeAt(0) <= 0x7e), 'distinct, printable ASCII')++console.log('\nbase86 — round trips\n')+let rt = true+for (let len = 0; len < 64; len++) for (let r = 0; r < 8; r++) { const b = new Uint8Array(randomBytes(len)); if (!eq(decode(encode(b)), b)) rt = false; if (encode(b).length !== Math.floor(len / 4) * 5 + (len % 4 ? len % 4 + 1 : 0)) rt = false }+ok(rt, 'every length 0–63 (all residues mod 4), byte-identical, n bytes → 5n/4 chars with the n+1 tail')+const edges = [[0, 0, 0, 0], [255, 255, 255, 255], [255], [0], [255, 255, 255], [128, 0, 0, 1], [255, 255, 255, 255, 255]]+ok(edges.every((e) => eq(decode(encode(new Uint8Array(e))), new Uint8Array(e))), 'edge values incl. all-0xFF groups and tails')+let threw = false+try { decode('a') } catch { threw = true }+ok(threw, 'a lone trailing character is refused')+threw = false+try { decode('ab<de') } catch { threw = true }+ok(threw, 'a character outside the alphabet is refused')+const loaderDecode = new Function(LOADER_DECODER + '\nreturn b86decode')() as (t: string) => Uint8Array+let agree = true+for (let len = 0; len < 64; len++) { const b = new Uint8Array(randomBytes(len)); if (!eq(loaderDecode(encode(b)), b)) agree = false }+ok(agree, "the loader's inline decoder (LOADER_DECODER) agrees with decode() byte for byte")++console.log('\nbase86 — the five sequences never appear\n')+let hits = 0, cat = ''+for (let r = 0; r < 10000; r++) {+ const t = encode(new Uint8Array(randomBytes(1 + (r % 97))))+ for (const f of FORBIDDEN) if (t.includes(f)) hits+++ cat += t+ if (cat.length > 100000) { for (const f of FORBIDDEN) if (cat.includes(f)) hits++; cat = cat.slice(-8) }+}+for (const f of FORBIDDEN) if (cat.includes(f)) hits+++ok(hits === 0, `${FORBIDDEN.map((f) => JSON.stringify(f)).join(' ')} — zero hits in 10,000 random buffers and their concatenations`)+// worst case by construction: the bytes that would spell them in base64 or raw+ok(!FORBIDDEN.some((f) => encode(new Uint8Array(Buffer.from(f.repeat(50)))).includes(f)), 'encoding the sequences themselves does not reproduce them')++console.log('\nthe built shell\n')+// a synthetic vite-shaped single file: module script + linked stylesheet + doc block + splash+const dir = mkdtempSync(join(tmpdir(), 'shell-loader-'))+const page = `<!DOCTYPE html><html><head><meta charset="UTF-8"><title>t</title>+<script type="module" crossorigin>window.bento = { doc: { format: 'bento/slides' } }; const T = '[data-bento-transient]'; document.getElementById('app').textContent = 'mounted' + T.length</script>+<style rel="stylesheet" crossorigin>#app{color:red}</style>+<script type="application/bento+json" id="bento-doc"></script></head>+<body><style>#bento-splash{opacity:.5}</style><div id="bento-splash"><div>splash</div></div><div id="app"></div></body></html>`+const shellPath = join(dir, 'shell.html')+writeFileSync(shellPath, page)+const run = (args: string[]) => execFileSync(process.execPath, [join(root, 'scripts/postbuild-compress.mjs'), shellPath, ...args], { cwd: join(root, 'slides'), encoding: 'utf8', env: { ...process.env, ZOPFLI: '0' } })+run(['--loader', 'cascade'])+const built = readFileSync(shellPath, 'utf8')+ok((built.match(/type="bento\/deflate-b86"/g) ?? []).length === 2, 'two bento/deflate-b86 payload blocks')+ok(!/type="bento\/deflate-b64"/.test(built), 'no base64 block')+const gate = (file: string) => { try { execFileSync(process.execPath, [join(root, 'scripts/shell-gate.mjs'), file], { encoding: 'utf8', stdio: 'pipe' }); return 'ok' } catch (e) { return String((e as { stderr?: string }).stderr ?? e) } }+ok(gate(shellPath) === 'ok', 'the splice gate passes')+const m = /(<script id="bento-rt-css" type="bento\/deflate-b86"[^>]*>)([^<]*)(<\/script>)/.exec(built)!+const badPath = join(dir, 'bad.html')+writeFileSync(badPath, built.slice(0, m.index + m[1].length) + m[2].slice(0, 20) + '-->' + m[2].slice(23) + built.slice(m.index + m[1].length + m[2].length))+const g = gate(badPath)+ok(g !== 'ok' && /must not be able to end its own block/.test(g), 'the gate goes red when a payload is hand-edited to contain -->')+// the payload really is the deflated module+const payload = m[2]+ok(eq(decode(payload), new Uint8Array(deflateRawSync(Buffer.from('#app{color:red}'), { level: 9 }))), 'the css payload decodes to the deflated stylesheet (zlib level 9 under ZOPFLI=0)')+ok(/data-len="\d+"/.test(m[1]) && Number(/data-len="(\d+)"/.exec(m[1])![1]) === payload.length, 'the block carries data-len equal to its text length')++console.log('\nthe loader probes nothing and waits on nothing\n')+const loader = /<script>\n\(async \(\) => \{([\s\S]*?)\n<\/script>\n\s*<\/body>/.exec(built)?.[1] ?? ''+ok(loader.length > 0, 'the loader is the last script in the body')+ok(!/new Function\(''\)/.test(loader), "no new Function('') eval probe")+ok(/var installTT = function/.test(loader) && (loader.match(/createPolicy\(/g) ?? []).length === 2 && !/^\s*installTT\(\)/m.test(loader), 'createPolicy appears only inside the lazy install, never called at boot')+ok(/runNow\('inline', viaInline\)/.test(loader) && /if \(!path\) runNow\('function', viaFunction\)/.test(loader) && /if \(!path\) \{[\s\S]{0,400}await import\(url\)/.test(loader), 'order: inline classic script, then new Function, then blob — each only after the previous was refused, synchronously')+ok(!/sc\.type = 'module'/.test(loader) && /var inflate = function/.test(loader) && (loader.replace(/\/\/[^\n]*/g, "").match(/\bawait\b/g) ?? []).length === 1, 'the inline script is classic, the inflate is synchronous, and the only await is the blob import')+ok(!/requestAnimationFrame|setTimeout|setInterval|fonts\.ready|DOMContentLoaded/.test(loader), 'no frame, timer, font or load wait anywhere in the loader')+ok(/window\.bento\.loader = \{ path: path, tried: tried, tt: tt, violations: violations \}/.test(loader), 'window.bento.loader records path, tried, tt and the violation count')+ok(/sourceURL=bento-slides\.js/.test(loader), 'the evaluated bundle is named bento-slides.js for DevTools')+ok(/data-bento-transient/.test(loader) && /b86decode/.test(loader) && !/atob\(/.test(loader), 'the loader carries the base86 decoder, no atob, and marks what it injects transient')+ok(!/<\/scr\x69pt>/.test(loader), 'no script-close inside the loader')+rmSync(dir, { recursive: true, force: true })++console.log('\nan embedded view makes no request\n')+// kernel net.ts decides once: framed AND opaque origin AND a storage read+// throwing SecurityError means a sandboxed frame (the Teams pane's B2 panel+// printed all three) — and then netFetch/netWebSocket refuse before touching+// the network, so a frame whose policy is+// connect-src 'none' raises no violation after boot (Teams' preview pane+// treats one as fatal). Behavioural, in child processes, because the+// decision is cached per process.+const netPath = join(root, 'kernel/src/net.ts')+const probe = (setup: string) => execFileSync(process.execPath, ['--input-type=module', '-e', `${setup}\nconst m = await import(${JSON.stringify('file://' + netPath)}); const out = { sandboxed: m.sandboxed() }; try { await m.netFetch('https://example.invalid/x'); out.fetch = 'went out' } catch (e) { out.fetch = e.name } try { m.netWebSocket('wss://example.invalid/x'); out.ws = 'opened' } catch (e) { out.ws = e.name } console.log(JSON.stringify(out))`], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })+const SEC = 'Object.defineProperty(globalThis, "localStorage", { get() { const e = new Error("blocked"); e.name = "SecurityError"; throw e } });'+const NONET = 'globalThis.fetch = async () => { throw new Error("must not be called") }; globalThis.WebSocket = class { constructor() { throw new Error("must not be constructed") } };'+const NET = 'globalThis.fetch = async () => { throw new TypeError("no network in this test") }; globalThis.WebSocket = class { constructor() {} addEventListener() {} };'+// (a) a file:// deck double-clicked on a desktop in Firefox (origin "null"; Chromium says "file://"), a data: URL+// page, a WebView loaded from a string: top-level, OPAQUE origin, storage works — must NOT be sandboxed+const fileDeck = JSON.parse(probe(`globalThis.self = globalThis; globalThis.self.origin = "null"; globalThis.top = globalThis; globalThis.location = { origin: "null", protocol: "file:" }; globalThis.localStorage = { getItem() { return null }, setItem() {} }; ${NET}`))+ok(fileDeck.sandboxed === false && fileDeck.fetch === 'TypeError' && fileDeck.ws === 'opened', `a file:// deck (top-level, origin "null", storage works): NOT sandboxed, requests go out (${JSON.stringify(fileDeck)})`)+const dataUrl = JSON.parse(probe(`globalThis.self = globalThis; globalThis.self.origin = "null"; globalThis.top = globalThis; globalThis.location = { origin: "null", protocol: "data:" }; globalThis.localStorage = { getItem() { return null }, setItem() {} }; ${NET}`))+ok(dataUrl.sandboxed === false && dataUrl.ws === 'opened', `a top-level opaque document with working storage (data: URL, WebView string load): NOT sandboxed (${JSON.stringify(dataUrl)})`)+// (a') Chromium 152 top-level file:// — origin "file://", measured+const chromeFile = JSON.parse(probe(`globalThis.self = globalThis; globalThis.self.origin = "null"; globalThis.top = globalThis; globalThis.location = { origin: "file://", protocol: "file:" }; globalThis.localStorage = { getItem() { return null }, setItem() {} }; ${NET}`))+ok(chromeFile.sandboxed === false && chromeFile.ws === 'opened', `a Chromium file:// deck (location.origin "file://", self.origin "null", measured): NOT sandboxed (${JSON.stringify(chromeFile)})`)+// (b) top-level, real origin, storage throws (a private window): not sandboxed — the offline switch is that user's tool+const privateWin = JSON.parse(probe(`globalThis.self = globalThis; globalThis.self.origin = "https://example.test"; globalThis.top = globalThis; globalThis.location = { origin: "https://example.test" }; ${SEC} ${NET}`))+ok(privateWin.sandboxed === false && privateWin.fetch === 'TypeError', `a top-level document whose storage throws: NOT sandboxed (${JSON.stringify(privateWin)})`)+// (c) framed + opaque + storage throws: the Teams pane — sandboxed, refused before the network+const teams = JSON.parse(probe(`globalThis.self = globalThis; globalThis.self.origin = "null"; globalThis.top = {}; globalThis.location = { origin: "null" }; ${SEC} ${NONET}`))+ok(teams.sandboxed === true && teams.fetch === 'SandboxedError' && teams.ws === 'SandboxedError', `framed + opaque + storage throws (a Teams pane): sandboxed, fetch and WebSocket refused before the network (${JSON.stringify(teams)})`)+// (c') a cross-origin top throws on the read — counts as framed+const xTop = JSON.parse(probe(`globalThis.self = globalThis; globalThis.self.origin = "null"; Object.defineProperty(globalThis, "top", { get() { throw new Error("cross-origin") } }); globalThis.location = { origin: "null" }; ${SEC} ${NONET}`))+ok(xTop.sandboxed === true, `a cross-origin top (the read throws) counts as framed (${JSON.stringify(xTop)})`)+// (d) framed with allow-same-origin: real origin, storage works — not sandboxed+const framedSame = JSON.parse(probe(`globalThis.self = globalThis; globalThis.self.origin = "https://example.test"; globalThis.top = {}; globalThis.location = { origin: "https://example.test" }; globalThis.localStorage = { getItem() { return null }, setItem() {} }; ${NET}`))+ok(framedSame.sandboxed === false && framedSame.fetch === 'TypeError', `framed with allow-same-origin: NOT sandboxed (${JSON.stringify(framedSame)})`)+// (c'') a sandboxed frame loaded by src: location.origin is the http URL's origin, self.origin is "null" (Chromium 152, measured) — sandboxed+const srcFrame = JSON.parse(probe(`globalThis.self = globalThis; globalThis.self.origin = "null"; globalThis.top = {}; globalThis.location = { origin: "http://localhost:5303" }; ${SEC} ${NONET}`))+ok(srcFrame.sandboxed === true && srcFrame.ws === 'SandboxedError', `a sandboxed frame loaded by src (location.origin is the URL's, self.origin "null"): sandboxed — the document origin decides, not the URL's (${JSON.stringify(srcFrame)})`)+// two of three are not enough+const twoOfThree = JSON.parse(probe(`globalThis.self = globalThis; globalThis.self.origin = "null"; globalThis.top = {}; globalThis.location = { origin: "null" }; globalThis.localStorage = { getItem() { return null }, setItem() {} }; ${NET}`))+ok(twoOfThree.sandboxed === false, `framed + opaque but storage works: NOT sandboxed — all three signs are required (${JSON.stringify(twoOfThree)})`)+const editorSrc = readFileSync(join(root, 'slides/src/editor/editor.ts'), 'utf8')+ok(/autoCheckEnabled\(\) \|\| offlineEnabled\(\) \|\| sandboxed\(\)\) return/.test(editorSrc), 'the launch update check is skipped when sandboxed — one request otherwise, none inside an embedded view')+ok(/private tryJoin\(\) \{[\s\S]{0,200}if \(sandboxed\(\)\) return/.test(editorSrc), 'the relay join is skipped when sandboxed (no socket, no retry loop)')+ok(/Updates are not checked inside an embedded view/.test(editorSrc) && /checkB\.disabled = sandboxed\(\)/.test(editorSrc), 'the About dialog says so and disables the manual check')+ok(/sandboxed: sandboxed\(\),/.test(readFileSync(join(root, 'slides/src/main.ts'), 'utf8')), 'window.bento.sandboxed exposes the decision')+const netSrc = readFileSync(netPath, 'utf8')+ok((netSrc.match(/if \(sandboxed\(\)\) throw new SandboxedError/g) ?? []).length === 2, 'both primitives check sandboxed() first — the one place the app touches the network')++console.log('\nin a hidden document, in a browser\n')+const CHROME = [process.env.BENTO_CHROME, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser']+ .find((p) => p && existsSync(p)) ?? (spawnSync('which', ['google-chrome']).status === 0 ? 'google-chrome' : undefined)+const builtShell = join(root, 'slides/dist-single/Bento_Slides.bento.html')+if (!CHROME || !existsSync(builtShell)) {+ console.log(` ⚠ SKIPPED — needs Chrome (BENTO_CHROME) and the built shell (${builtShell}); the loader-shape checks above still gate.`)+} else {+ await browserSection(CHROME, builtShell)+}++async function browserSection(chrome: string, shell: string) {+ const html = readFileSync(shell, 'utf8')+ // a recorder injected before any script of the page: when did the app+ // appear (the assignment to window.bento), when did the splash leave, and+ // was the app there at DOMContentLoaded+ const recorder = `(() => { const r = { vis0: document.visibilityState, mountT: null, splashGoneT: null, dclMounted: null, dclT: null }; window.__rec = r+ let b; Object.defineProperty(window, 'bento', { configurable: true, get() { return b }, set(v) { b = v; if (r.mountT === null && v && v.doc) r.mountT = performance.now() } })+ document.addEventListener('DOMContentLoaded', () => { r.dclMounted = !!(b && b.doc); r.dclT = performance.now() })+ })()`+ const server = createServer((req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }); res.end(html) })+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))+ const port = (server.address() as { port: number }).port+ const profile = mkdtempSync(join(tmpdir(), 'bento-hidden-'))+ const child = spawn(chrome, ['--headless=new', '--disable-gpu', '--no-sandbox', '--no-first-run', '--no-default-browser-check', '--disable-background-networking', '--disable-component-update', '--disable-sync', '--disable-default-apps', '--remote-debugging-port=0', '--user-data-dir=' + profile, 'about:blank'], { stdio: 'ignore' })+ const kill = () => { try { child.kill('SIGKILL') } catch { /* gone */ } }+ try {+ const portFile = join(profile, 'DevToolsActivePort')+ for (let i = 0; i < 100 && !existsSync(portFile); i++) await new Promise((r) => setTimeout(r, 100))+ const cdpPort = readFileSync(portFile, 'utf8').split('\n')[0].trim()+ const json = async (p: string, init?: RequestInit) => { const r = await fetch(`http://127.0.0.1:${cdpPort}${p}`, init); const txt = await r.text(); try { return JSON.parse(txt) } catch { return txt } }+ const run = async (hidden: boolean) => {+ const t = (await json('/json/new?about:blank', { method: 'PUT' })) as { id: string; webSocketDebuggerUrl: string }+ let decoy: { id: string } | null = null+ if (hidden) { decoy = (await json('/json/new?about:blank', { method: 'PUT' })) as { id: string }; await json(`/json/activate/${decoy.id}`); await new Promise((r) => setTimeout(r, 300)) }+ const ws = new WebSocket(t.webSocketDebuggerUrl)+ await new Promise<void>((res, rej) => { ws.addEventListener('open', () => res()); ws.addEventListener('error', () => rej(new Error('cdp socket'))) })+ let id = 0; const pending = new Map<number, (m: { result?: { result?: { value?: unknown } } }) => void>()+ ws.addEventListener('message', (ev) => { const m = JSON.parse(String(ev.data)); if (m.id && pending.has(m.id)) { pending.get(m.id)!(m); pending.delete(m.id) } })+ const send = (method: string, params: Record<string, unknown> = {}) => new Promise<{ result?: { result?: { value?: unknown } } }>((res) => { const i = ++id; pending.set(i, res); ws.send(JSON.stringify({ id: i, method, params })) })+ await send('Page.enable')+ await send('Page.addScriptToEvaluateOnNewDocument', { source: recorder })+ await send('Page.navigate', { url: `http://127.0.0.1:${port}/deck.html` })+ const t0 = Date.now(); let rec: Record<string, unknown> | null = null+ while (Date.now() - t0 < 15000) {+ await new Promise((r) => setTimeout(r, 10))+ // the splash's departure is sampled here (10 ms cadence) rather than by a+ // MutationObserver in the page: observer callbacks are microtasks the+ // parser delivers late, and a splash removed inside the same task as the+ // mount was reported gone before it was seen+ const v = (await send('Runtime.evaluate', { expression: 'JSON.stringify(Object.assign({}, window.__rec, { vis: document.visibilityState, now: performance.now(), splash: !!document.getElementById("bento-splash"), loader: window.bento && window.bento.loader }))', returnByValue: true })).result?.result?.value+ if (typeof v !== 'string') continue+ const cur = JSON.parse(v) as Record<string, unknown> & { splash: boolean; now: number; mountT: number | null }+ if (cur.mountT !== null && !cur.splash && (rec === null || rec.splashGoneT === null)) cur.splashGoneT = cur.now+ else if (rec && rec.splashGoneT !== null) cur.splashGoneT = rec.splashGoneT+ rec = cur+ if (rec.mountT !== null && rec.splashGoneT !== null && rec.dclMounted !== null) break+ }+ ws.close()+ await json(`/json/close/${t.id}`); if (decoy) await json(`/json/close/${decoy.id}`)+ return rec+ }+ const h = await run(true)+ const hv = h as { vis0: string; mountT: number | null; splashGoneT: number | null; dclMounted: boolean | null; loader?: { path?: string; violations?: number } } | null+ ok(hv?.vis0 === 'hidden', `the hidden run really was hidden from the first byte (visibilityState at start: ${hv?.vis0})`)+ ok(hv?.mountT !== null && hv?.dclMounted === true, `hidden: the editor is mounted BEFORE DOMContentLoaded (mount at ${hv?.mountT?.toFixed(0)} ms; at DCL: ${hv?.dclMounted})`)+ const gap = hv && hv.mountT !== null && hv.splashGoneT !== null ? hv.splashGoneT - hv.mountT : Infinity+ ok(gap <= 50, `hidden: the splash is gone within 50 ms of the mount (${Number.isFinite(gap) ? gap.toFixed(0) + ' ms' : 'never within 15 s'})`)+ ok(hv?.loader?.path === 'inline' && hv?.loader?.violations === 0, `hidden: loader path inline, zero violations (${JSON.stringify(hv?.loader)})`)+ const v = await run(false)+ const vv = v as { vis0: string; mountT: number | null; splashGoneT: number | null; dclMounted: boolean | null } | null+ ok(vv?.vis0 === 'visible' && vv?.dclMounted === true, `visible: mounted before DOMContentLoaded too (mount at ${vv?.mountT?.toFixed(0)} ms)`)+ const vgap = vv && vv.mountT !== null && vv.splashGoneT !== null ? vv.splashGoneT - vv.mountT : Infinity+ ok(vgap <= 2000, `visible: the brand hold ends within its cap (splash gone ${Number.isFinite(vgap) ? vgap.toFixed(0) + ' ms' : 'never'} after mount; cap 800 ms hold + 550 ms fade)`)+ } finally {+ kill()+ server.close()+ rmSync(profile, { recursive: true, force: true })+ }+}++console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)diff --git a/scripts/test-sync-vouch.ts b/scripts/test-sync-vouch.tsindex 329562bc..f9432332 100644--- a/scripts/test-sync-vouch.ts+++ b/scripts/test-sync-vouch.ts@@ -28,6 +28,40 @@// dash's deliberate twin — so this drives both, with the same frames.import { webcrypto } from 'node:crypto'+import { execFileSync } from 'node:child_process'++// ——— SANDBOXED EMBED: the transport must not reconnect-flap (own process) ———+// A sandboxed embed (Teams/SharePoint preview) refuses every socket at the net+// chokepoint (kernel/src/net.ts sandboxed()). connect() must treat that+// SandboxedError as TERMINAL — no retry — exactly as drop() treats close codes+// 4001/1008. net.ts memoises the sandboxed() decision ONCE per process, so this+// case cannot share a process with the connect-normally cases below: the rig+// RE-SPAWNS ITSELF under sandboxed globals and reports what the transport did.+if (process.env.BENTO_SYNC_SANDBOXED === '1') {+ const g = globalThis as unknown as Record<string, unknown>+ g.self = globalThis; g.top = {} // self !== top → framed+ g.location = { origin: 'null' } // opaque origin+ Object.defineProperty(globalThis, 'localStorage', { // a storage read throws+ configurable: true,+ get() { const e = new Error('blocked') as Error & { name: string }; e.name = 'SecurityError'; throw e },+ })+ let built = 0+ g.WebSocket = class { constructor() { built++ } close() {} addEventListener() {} removeEventListener() {} send() {} }+ const { OnlineTransport } = await import('../kernel/src/sync/online.ts')+ const raw = webcrypto.getRandomValues(new Uint8Array(32))+ const kb = Buffer.from(raw).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')+ let connecting = 0+ const tr = new OnlineTransport(+ 'wss://relay.test/d/rSANDBOXSANDBOXSANDBOXSANDBOXSANDBOXSANDBO', kb, 'doc-sbx',+ () => {},+ { onSnap() {}, getSnapshot: () => ({ doc: { docId: 'doc-sbx' }, state: { v: 2 } as never }), onOpen() {}, onReady: () => false },+ undefined,+ )+ ;(tr as unknown as { onStatus: (s: string) => void }).onStatus = (s) => { if (s === 'connecting') connecting++ }+ await new Promise((r) => setTimeout(r, 2600)) // past the 800ms + 1440ms backoff steps+ console.log(JSON.stringify({ connecting, built }))+ process.exit(0) // a buggy retry timer would otherwise keep this child alive+}// --- the world the transport expects ---------------------------------------// A WebSocket constructor the kernel's net chokepoint will `new`. Each instance@@ -287,5 +321,23 @@ for (const [name, Transport] of [['kernel', KernelTransport], ['dash', DashTranstr.close()}+// ——— a sandboxed embed opens no socket and does not reconnect-flap ———+// Runs in its own process (the guard at the top of this file) because+// net.ts memoises sandboxed() once per process. Without the terminal handling+// in connect(), the bare catch retries and `connecting` climbs past 1.+{+ console.log('a sandboxed embed opens no socket and does not reconnect-flap…')+ let out = ''+ try {+ out = execFileSync(process.execPath, [process.argv[1]], {+ env: { ...process.env, BENTO_SYNC_SANDBOXED: '1' }, encoding: 'utf8', timeout: 15000,+ })+ } catch (e) { out = String((e as { stdout?: string }).stdout ?? '') }+ const line = out.trim().split('\n').filter(Boolean).pop() ?? '{}'+ const r = JSON.parse(line) as { connecting: number; built: number }+ ok(r.built === 0, `no socket is constructed in a sandboxed embed — netWebSocket refuses first (built=${r.built})`)+ ok(r.connecting === 1, `connect() runs once then stops — SandboxedError is terminal, no retry flap (connecting=${r.connecting}; a retry loop climbs past 1)`)+}+console.log(failures === 0 ? `\nALL PASS (${checks} checks)` : `\n${failures} FAILURES of ${checks} checks`)process.exit(failures ? 1 : 0)diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.tsindex 07880448..bd159380 100644--- a/slides/src/editor/editor.ts+++ b/slides/src/editor/editor.ts@@ -13,7 +13,7 @@ import {type ChartElement, type ShapeKind, type Slide, type SlideElement, type TableElement } from '../model'import { THEME_CHOICES, setTheme, themeChoice } from '../../../kernel/src/theme.ts'import type { InPlaceOutcome } from '../update'-import { APP_VERSION, applyUpdate, applyUpdateInPlace, autoCheckEnabled, canUpdateInPlace, checkForUpdates, compareVersions, offlineEnabled, setAutoCheck, setOffline } from '../update'+import { APP_VERSION, applyUpdate, applyUpdateInPlace, autoCheckEnabled, canUpdateInPlace, checkForUpdates, compareVersions, offlineEnabled, sandboxed, setAutoCheck, setOffline } from '../update'import { CHART_PRESETS } from '../charts'import { renderSlide, renderThumbnail } from '../render'import { openExportImagesDialog } from './exportimages'@@ -167,6 +167,8 @@ export class Editor {/** Connect to the relay if the current doc is live AND share-eligible. */private tryJoin() {if (!this.session) return+ // an embedded view blocks every connection: no relay socket, no retry loop+ if (sandboxed()) returnif (sharingOn(this.store) && this.session.shareEligible() && !onlineTransport()) {joinFromDoc(this.session, this.store)this.wireOnlineStatus()@@ -306,7 +308,9 @@ export class Editor {this.updatesB = btn(ICONS.sync, '', () => this.openAbout(true), t('Check for updates'))this.updatesB.style.display = 'none'setTimeout(async () => {- if (!autoCheckEnabled() || offlineEnabled()) return+ // an embedded view (Teams, SharePoint) blocks every connection and its+ // preview pane treats a reported refusal as fatal: no request at all+ if (!autoCheckEnabled() || offlineEnabled() || sandboxed()) returnconst r = await checkForUpdates()this.lastAutoCheck = rif (r.status === 'update') {@@ -3307,7 +3311,9 @@ export class Editor {const status = div('ed-about-status')status.textContent =- this.lastAutoCheck?.status === 'current'+ sandboxed()+ ? t('Updates are not checked inside an embedded view — open the file in a browser tab to check.')+ : this.lastAutoCheck?.status === 'current'? t("Checked automatically at launch — you're on the latest version (v{v}).", { v: APP_VERSION }): this.lastAutoCheck?.status === 'error'? t("Launch check couldn't reach the release server ({m}). Check manually below.", { m: this.lastAutoCheck.message })@@ -3317,6 +3323,7 @@ export class Editor {const checkB = document.createElement('button')checkB.className = 'ed-btn'checkB.textContent = t('Check for updates')+ checkB.disabled = sandboxed() // nothing to check from inside an embedded viewcheckB.addEventListener('click', async () => {checkB.disabled = truestatus.textContent = t('Checking…')diff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.tsindex 07de8e01..b7e7f565 100644--- a/slides/src/i18n/de.ts+++ b/slides/src/i18n/de.ts@@ -923,4 +923,5 @@ export const de: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Dasselbe Deck ohne alle Standardwerte — die Form, die ein KI-Agent schreiben sollte. „Aus JSON ersetzen“ nimmt es zurück; die gespeicherte Datei ist immer vollständig.","Compact JSON copied": "Kompaktes JSON kopiert","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Geladen: {dropped} Felder verworfen, {warnings} Warnungen — siehe Konsole",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "In einer eingebetteten Ansicht werden keine Updates geprüft — öffnen Sie die Datei in einem Browser-Tab, um zu prüfen.",}diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.tsindex 27dd6624..e2a6cb5c 100644--- a/slides/src/i18n/es.ts+++ b/slides/src/i18n/es.ts@@ -923,4 +923,5 @@ export const es: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "La misma presentación sin ningún valor predeterminado: la forma que debería escribir un agente de IA. «Reemplazar desde JSON» lo acepta; el archivo guardado siempre es completo.","Compact JSON copied": "JSON compacto copiado","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Cargado: {dropped} campos descartados, {warnings} avisos; consulta la consola",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Dentro de una vista incrustada no se comprueban las actualizaciones: abre el archivo en una pestaña del navegador para comprobar.",}diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.tsindex 54a5ea61..52dc0251 100644--- a/slides/src/i18n/fr.ts+++ b/slides/src/i18n/fr.ts@@ -923,4 +923,5 @@ export const fr: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "La même présentation sans aucune valeur par défaut : la forme qu’un agent IA devrait écrire. « Remplacer depuis JSON » la reprend ; le fichier enregistré est toujours complet.","Compact JSON copied": "JSON compact copié","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Chargé : {dropped} champs ignorés, {warnings} avertissements — voir la console",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Les mises à jour ne sont pas vérifiées dans une vue intégrée — ouvrez le fichier dans un onglet du navigateur pour vérifier.",}diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.tsindex 38c32af7..726954c0 100644--- a/slides/src/i18n/it.ts+++ b/slides/src/i18n/it.ts@@ -923,4 +923,5 @@ export const it: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "La stessa presentazione senza alcun valore predefinito: la forma che un agente IA dovrebbe scrivere. «Sostituisci da JSON» la riprende; il file salvato è sempre completo.","Compact JSON copied": "JSON compatto copiato","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Caricato: {dropped} campi scartati, {warnings} avvisi — vedi la console",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "In una vista incorporata gli aggiornamenti non vengono controllati — apri il file in una scheda del browser per controllare.",}diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.tsindex ad618e9f..26daa767 100644--- a/slides/src/i18n/ja.ts+++ b/slides/src/i18n/ja.ts@@ -923,4 +923,5 @@ export const ja: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "既定値をすべて省いた同じデッキ。AI エージェントが書くべき形です。「JSON から置き換え」で戻せます。保存されるファイルは常に完全な形です。","Compact JSON copied": "コンパクトな JSON をコピーしました","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "読み込み完了: {dropped} 個のフィールドを破棄、警告 {warnings} 件 — コンソールを確認",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "埋め込み表示ではアップデートを確認しません — 確認するにはファイルをブラウザーのタブで開いてください。",}diff --git a/slides/src/i18n/packed.ts b/slides/src/i18n/packed.tsindex af1af331..0dd03df2 100644--- a/slides/src/i18n/packed.ts+++ b/slides/src/i18n/packed.ts@@ -929,4 +929,5 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": ["既定値をすべて省いた同じデッキ。AI エージェントが書くべき形です。「JSON から置き換え」で戻せます。保存されるファイルは常に完全な形です。","同一份文稿,省去所有默认值——AI 智能体应当书写的形式。“从 JSON 替换”可读回它;保存的文件始终是完整的。","同一份文稿,省去所有預設值——AI 代理程式應當書寫的形式。「從 JSON 取代」可讀回它;儲存的檔案始終是完整的。","La misma presentación sin ningún valor predeterminado: la forma que debería escribir un agente de IA. «Reemplazar desde JSON» lo acepta; el archivo guardado siempre es completo.","La même présentation sans aucune valeur par défaut : la forme qu’un agent IA devrait écrire. « Remplacer depuis JSON » la reprend ; le fichier enregistré est toujours complet.","Dasselbe Deck ohne alle Standardwerte — die Form, die ein KI-Agent schreiben sollte. „Aus JSON ersetzen“ nimmt es zurück; die gespeicherte Datei ist immer vollständig.","La stessa presentazione senza alcun valore predefinito: la forma che un agente IA dovrebbe scrivere. «Sostituisci da JSON» la riprende; il file salvato è sempre completo.","A mesma apresentação sem nenhum valor predefinido: a forma que um agente de IA deve escrever. «Substituir a partir de JSON» aceita-a; o ficheiro guardado é sempre completo."],"Compact JSON copied": ["コンパクトな JSON をコピーしました","已复制精简 JSON","已複製精簡 JSON","JSON compacto copiado","JSON compact copié","Kompaktes JSON kopiert","JSON compatto copiato","JSON compacto copiado"],"Loaded: {dropped} fields dropped, {warnings} warnings — see console": ["読み込み完了: {dropped} 個のフィールドを破棄、警告 {warnings} 件 — コンソールを確認","已加载:丢弃 {dropped} 个字段,{warnings} 条警告 — 见控制台","已載入:捨棄 {dropped} 個欄位,{warnings} 則警告 — 見主控台","Cargado: {dropped} campos descartados, {warnings} avisos; consulta la consola","Chargé : {dropped} champs ignorés, {warnings} avertissements — voir la console","Geladen: {dropped} Felder verworfen, {warnings} Warnungen — siehe Konsole","Caricato: {dropped} campi scartati, {warnings} avvisi — vedi la console","Carregado: {dropped} campos descartados, {warnings} avisos — ver a consola"],+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": ["埋め込み表示ではアップデートを確認しません — 確認するにはファイルをブラウザーのタブで開いてください。","在嵌入视图中不检查更新 — 请在浏览器标签页中打开文件以检查。","在嵌入檢視中不檢查更新 — 請在瀏覽器分頁中開啟檔案以檢查。","Dentro de una vista incrustada no se comprueban las actualizaciones: abre el archivo en una pestaña del navegador para comprobar.","Les mises à jour ne sont pas vérifiées dans une vue intégrée — ouvrez le fichier dans un onglet du navigateur pour vérifier.","In einer eingebetteten Ansicht werden keine Updates geprüft — öffnen Sie die Datei in einem Browser-Tab, um zu prüfen.","In una vista incorporata gli aggiornamenti non vengono controllati — apri il file in una scheda del browser per controllare.","Numa vista incorporada as atualizações não são verificadas — abra o ficheiro num separador do navegador para verificar."],}diff --git a/slides/src/i18n/packs/ar.ts b/slides/src/i18n/packs/ar.tsindex b8fb5cda..b2704409 100644--- a/slides/src/i18n/packs/ar.ts+++ b/slides/src/i18n/packs/ar.ts@@ -943,4 +943,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "العرض نفسه بدون أي قيمة افتراضية: الشكل الذي ينبغي لوكيل الذكاء الاصطناعي كتابته. «استبدال من JSON» يقبله؛ الملف المحفوظ كامل دائمًا.","Compact JSON copied": "تم نسخ JSON المضغوط","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "تم التحميل: {dropped} حقول مهملة، {warnings} تحذيرات — راجع وحدة التحكم",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "لا يتم التحقق من التحديثات داخل عرض مضمّن — افتح الملف في علامة تبويب المتصفح للتحقق.",}diff --git a/slides/src/i18n/packs/bn.ts b/slides/src/i18n/packs/bn.tsindex 5765690f..af18958c 100644--- a/slides/src/i18n/packs/bn.ts+++ b/slides/src/i18n/packs/bn.ts@@ -946,4 +946,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "সব ডিফল্ট বাদ দেওয়া একই ডেক — একটি AI এজেন্টের যেভাবে লেখা উচিত। “JSON থেকে প্রতিস্থাপন” এটি ফিরিয়ে নেয়; সংরক্ষিত ফাইল সবসময় পূর্ণ।","Compact JSON copied": "সংক্ষিপ্ত JSON কপি হয়েছে","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "লোড হয়েছে: {dropped}টি ফিল্ড বাদ, {warnings}টি সতর্কতা — কনসোল দেখুন",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "এমবেড করা ভিউতে আপডেট পরীক্ষা করা হয় না — পরীক্ষা করতে ফাইলটি ব্রাউজার ট্যাবে খুলুন।",}diff --git a/slides/src/i18n/packs/da.ts b/slides/src/i18n/packs/da.tsindex 4e339abb..e944ff62 100644--- a/slides/src/i18n/packs/da.ts+++ b/slides/src/i18n/packs/da.ts@@ -935,4 +935,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Samme dæk uden alle standardværdier — den form en AI-agent bør skrive. »Erstat fra JSON« tager den tilbage; den gemte fil er altid fuldstændig.","Compact JSON copied": "Kompakt JSON kopieret","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Indlæst: {dropped} felter udeladt, {warnings} advarsler — se konsollen",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Opdateringer tjekkes ikke i en indlejret visning — åbn filen i en browserfane for at tjekke.",}diff --git a/slides/src/i18n/packs/fa.ts b/slides/src/i18n/packs/fa.tsindex 9fceb6d1..87858278 100644--- a/slides/src/i18n/packs/fa.ts+++ b/slides/src/i18n/packs/fa.ts@@ -939,4 +939,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "همان دک بدون هیچ مقدار پیشفرض؛ شکلی که یک عامل هوش مصنوعی باید بنویسد. «جایگزینی از JSON» آن را میپذیرد؛ پروندهٔ ذخیرهشده همیشه کامل است.","Compact JSON copied": "JSON فشرده کپی شد","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "بارگذاری شد: {dropped} فیلد حذف شد، {warnings} هشدار — کنسول را ببینید",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "در نمای جاسازیشده بهروزرسانیها بررسی نمیشوند — برای بررسی، پرونده را در یک زبانهٔ مرورگر باز کنید.",}diff --git a/slides/src/i18n/packs/fi.ts b/slides/src/i18n/packs/fi.tsindex 638c6453..786c1fdb 100644--- a/slides/src/i18n/packs/fi.ts+++ b/slides/src/i18n/packs/fi.ts@@ -940,4 +940,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Sama pakka ilman oletusarvoja — muoto, jonka tekoälyagentin tulisi kirjoittaa. ”Korvaa JSON:sta” ottaa sen vastaan; tallennettu tiedosto on aina täydellinen.","Compact JSON copied": "Tiivis JSON kopioitu","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Ladattu: {dropped} kenttää hylätty, {warnings} varoitusta — katso konsoli",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Päivityksiä ei tarkisteta upotetussa näkymässä — avaa tiedosto selaimen välilehdessä tarkistaaksesi.",}diff --git a/slides/src/i18n/packs/fil.ts b/slides/src/i18n/packs/fil.tsindex f746d125..57a7be7d 100644--- a/slides/src/i18n/packs/fil.ts+++ b/slides/src/i18n/packs/fil.ts@@ -952,4 +952,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Ang parehong deck na wala ang lahat ng default — ang anyong dapat isulat ng isang AI agent. Tinatanggap ito ng “Palitan mula sa JSON”; ang na-save na file ay laging buo.","Compact JSON copied": "Nakopya ang compact na JSON","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Na-load: {dropped} field ang inalis, {warnings} babala — tingnan ang console",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Hindi sinusuri ang mga update sa loob ng naka-embed na view — buksan ang file sa isang tab ng browser para suriin.",}diff --git a/slides/src/i18n/packs/he.ts b/slides/src/i18n/packs/he.tsindex 5931f2b4..f174dd2b 100644--- a/slides/src/i18n/packs/he.ts+++ b/slides/src/i18n/packs/he.ts@@ -936,4 +936,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "אותה מצגת בלי ברירות המחדל — הצורה שסוכן AI צריך לכתוב. «החלפה מ-JSON» מקבלת אותה; הקובץ השמור תמיד מלא.","Compact JSON copied": "JSON קומפקטי הועתק","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "נטען: {dropped} שדות הושמטו, {warnings} אזהרות — ראו את הקונסולה",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "בתצוגה מוטמעת לא נבדקים עדכונים — פתחו את הקובץ בלשונית דפדפן כדי לבדוק.",}diff --git a/slides/src/i18n/packs/hi.ts b/slides/src/i18n/packs/hi.tsindex d7350990..7a095930 100644--- a/slides/src/i18n/packs/hi.ts+++ b/slides/src/i18n/packs/hi.ts@@ -943,4 +943,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "वही डेक, हर डिफ़ॉल्ट हटाकर — वह रूप जो एक AI एजेंट को लिखना चाहिए। “JSON से बदलें” इसे वापस लेता है; सहेजी गई फ़ाइल हमेशा पूरी होती है।","Compact JSON copied": "संक्षिप्त JSON कॉपी हो गया","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "लोड हुआ: {dropped} फ़ील्ड हटाए गए, {warnings} चेतावनियाँ — कंसोल देखें",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "एम्बेडेड दृश्य में अपडेट की जाँच नहीं होती — जाँचने के लिए फ़ाइल को ब्राउज़र टैब में खोलें।",}diff --git a/slides/src/i18n/packs/id.ts b/slides/src/i18n/packs/id.tsindex 6aeec9ba..da16942f 100644--- a/slides/src/i18n/packs/id.ts+++ b/slides/src/i18n/packs/id.ts@@ -933,4 +933,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Dek yang sama tanpa semua nilai bawaan — bentuk yang seharusnya ditulis agen AI. “Ganti dari JSON” menerimanya kembali; berkas yang disimpan selalu lengkap.","Compact JSON copied": "JSON ringkas disalin","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Dimuat: {dropped} bidang dibuang, {warnings} peringatan — lihat konsol",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Pembaruan tidak diperiksa di dalam tampilan tersemat — buka berkas di tab browser untuk memeriksa.",}diff --git a/slides/src/i18n/packs/ko.ts b/slides/src/i18n/packs/ko.tsindex 57d9452b..8a37a7a7 100644--- a/slides/src/i18n/packs/ko.ts+++ b/slides/src/i18n/packs/ko.ts@@ -927,4 +927,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "모든 기본값을 뺀 같은 덱 — AI 에이전트가 작성해야 할 형태입니다. “JSON에서 바꾸기”로 되돌릴 수 있으며, 저장되는 파일은 항상 완전한 형태입니다.","Compact JSON copied": "간결한 JSON을 복사했습니다","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "불러옴: 필드 {dropped}개 삭제됨, 경고 {warnings}건 — 콘솔 참조",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "임베디드 보기에서는 업데이트를 확인하지 않습니다 — 확인하려면 파일을 브라우저 탭에서 여세요.",}diff --git a/slides/src/i18n/packs/ms.ts b/slides/src/i18n/packs/ms.tsindex 2bcf0e7e..0e1994c7 100644--- a/slides/src/i18n/packs/ms.ts+++ b/slides/src/i18n/packs/ms.ts@@ -936,4 +936,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Dek yang sama tanpa semua nilai lalai — bentuk yang patut ditulis oleh ejen AI. “Ganti daripada JSON” menerimanya semula; fail yang disimpan sentiasa lengkap.","Compact JSON copied": "JSON padat disalin","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Dimuatkan: {dropped} medan digugurkan, {warnings} amaran — lihat konsol",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Kemas kini tidak disemak dalam paparan terbenam — buka fail dalam tab pelayar untuk menyemak.",}diff --git a/slides/src/i18n/packs/nb.ts b/slides/src/i18n/packs/nb.tsindex ef3f4a7e..7d0d3a19 100644--- a/slides/src/i18n/packs/nb.ts+++ b/slides/src/i18n/packs/nb.ts@@ -937,4 +937,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Samme kortstokk uten alle standardverdier — formen en KI-agent bør skrive. «Erstatt fra JSON» tar den tilbake; den lagrede filen er alltid fullstendig.","Compact JSON copied": "Kompakt JSON kopiert","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Lastet: {dropped} felt forkastet, {warnings} advarsler — se konsollen",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Oppdateringer sjekkes ikke i en innebygd visning — åpne filen i en nettleserfane for å sjekke.",}diff --git a/slides/src/i18n/packs/nl.ts b/slides/src/i18n/packs/nl.tsindex c03f8a23..d662823f 100644--- a/slides/src/i18n/packs/nl.ts+++ b/slides/src/i18n/packs/nl.ts@@ -931,4 +931,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Hetzelfde deck zonder alle standaardwaarden — de vorm die een AI-agent zou moeten schrijven. ‘Vervangen uit JSON’ neemt het terug; het opgeslagen bestand is altijd volledig.","Compact JSON copied": "Compacte JSON gekopieerd","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Geladen: {dropped} velden weggelaten, {warnings} waarschuwingen — zie de console",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "In een ingesloten weergave wordt niet op updates gecontroleerd — open het bestand in een browsertabblad om te controleren.",}diff --git a/slides/src/i18n/packs/pl.ts b/slides/src/i18n/packs/pl.tsindex 1d29acf2..364ef16a 100644--- a/slides/src/i18n/packs/pl.ts+++ b/slides/src/i18n/packs/pl.ts@@ -934,4 +934,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Ta sama prezentacja bez wartości domyślnych — postać, którą powinien pisać agent AI. „Zastąp z JSON” przyjmuje ją z powrotem; zapisany plik jest zawsze pełny.","Compact JSON copied": "Skopiowano zwięzły JSON","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Wczytano: odrzucono {dropped} pól, {warnings} ostrzeżeń — zobacz konsolę",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "W widoku osadzonym aktualizacje nie są sprawdzane — otwórz plik w karcie przeglądarki, aby sprawdzić.",}diff --git a/slides/src/i18n/packs/ru.ts b/slides/src/i18n/packs/ru.tsindex 7c9dd8d7..94e8b016 100644--- a/slides/src/i18n/packs/ru.ts+++ b/slides/src/i18n/packs/ru.ts@@ -935,4 +935,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Та же презентация без значений по умолчанию — форма, которую должен писать ИИ-агент. «Заменить из JSON» принимает её обратно; сохранённый файл всегда полный.","Compact JSON copied": "Компактный JSON скопирован","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Загружено: отброшено полей: {dropped}, предупреждений: {warnings} — см. консоль",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Во встроенном представлении обновления не проверяются — откройте файл во вкладке браузера, чтобы проверить.",}diff --git a/slides/src/i18n/packs/sv.ts b/slides/src/i18n/packs/sv.tsindex e2a3d202..5ef05f2d 100644--- a/slides/src/i18n/packs/sv.ts+++ b/slides/src/i18n/packs/sv.ts@@ -932,4 +932,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Samma presentation utan alla standardvärden — formen en AI-agent bör skriva. ”Ersätt från JSON” tar tillbaka den; den sparade filen är alltid fullständig.","Compact JSON copied": "Kompakt JSON kopierad","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Inläst: {dropped} fält bortfiltrerade, {warnings} varningar — se konsolen",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Uppdateringar kontrolleras inte i en inbäddad vy — öppna filen i en webbläsarflik för att kontrollera.",}diff --git a/slides/src/i18n/packs/th.ts b/slides/src/i18n/packs/th.tsindex b4ddcf16..f85b92e7 100644--- a/slides/src/i18n/packs/th.ts+++ b/slides/src/i18n/packs/th.ts@@ -937,4 +937,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "เด็คเดียวกันโดยตัดค่าเริ่มต้นทั้งหมดออก คือรูปแบบที่เอเจนต์ AI ควรเขียน “แทนที่จาก JSON” รับกลับได้ ไฟล์ที่บันทึกจะสมบูรณ์เสมอ","Compact JSON copied": "คัดลอก JSON แบบกระชับแล้ว","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "โหลดแล้ว: ตัดฟิลด์ออก {dropped} รายการ, คำเตือน {warnings} รายการ — ดูคอนโซล",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "ไม่ตรวจสอบการอัปเดตในมุมมองแบบฝัง — เปิดไฟล์ในแท็บเบราว์เซอร์เพื่อตรวจสอบ",}diff --git a/slides/src/i18n/packs/tk.ts b/slides/src/i18n/packs/tk.tsindex ce7fa809..aa21c235 100644--- a/slides/src/i18n/packs/tk.ts+++ b/slides/src/i18n/packs/tk.ts@@ -960,4 +960,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Ähli deslapky bahalary aýrylan şol bir toplum — AI agentiň ýazmaly görnüşi. «JSON-dan çalyş» ony yzyna alýar; ýatda saklanan faýl elmydama doly.","Compact JSON copied": "Ykjam JSON göçürildi","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Ýüklendi: {dropped} meýdan taşlandy, {warnings} duýduryş — konsola serediň",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Gurnalan görnüşde täzelenmeler barlanmaýar — barlamak üçin faýly brauzer goýmasynda açyň.",}diff --git a/slides/src/i18n/packs/tr.ts b/slides/src/i18n/packs/tr.tsindex 922c77b9..c3725562 100644--- a/slides/src/i18n/packs/tr.ts+++ b/slides/src/i18n/packs/tr.ts@@ -934,4 +934,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Tüm varsayılanlar çıkarılmış aynı deste — bir yapay zekâ ajanının yazması gereken biçim. “JSON'dan değiştir” geri alır; kaydedilen dosya her zaman tamdır.","Compact JSON copied": "Kompakt JSON kopyalandı","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Yüklendi: {dropped} alan atıldı, {warnings} uyarı — konsola bakın",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Gömülü görünümde güncellemeler denetlenmez — denetlemek için dosyayı bir tarayıcı sekmesinde açın.",}diff --git a/slides/src/i18n/packs/uk.ts b/slides/src/i18n/packs/uk.tsindex 6174ae4f..6944fbac 100644--- a/slides/src/i18n/packs/uk.ts+++ b/slides/src/i18n/packs/uk.ts@@ -943,4 +943,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Та сама презентація без значень за замовчуванням — форма, яку має писати ШІ-агент. «Замінити з JSON» приймає її назад; збережений файл завжди повний.","Compact JSON copied": "Компактний JSON скопійовано","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Завантажено: відкинуто полів: {dropped}, попереджень: {warnings} — див. консоль",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "У вбудованому поданні оновлення не перевіряються — відкрийте файл у вкладці браузера, щоб перевірити.",}diff --git a/slides/src/i18n/packs/ur.ts b/slides/src/i18n/packs/ur.tsindex e0da7132..c28e0130 100644--- a/slides/src/i18n/packs/ur.ts+++ b/slides/src/i18n/packs/ur.ts@@ -953,4 +953,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "وہی ڈیک، ہر ڈیفالٹ ہٹا کر — وہ شکل جو ایک AI ایجنٹ کو لکھنی چاہیے۔ “JSON سے بدلیں” اسے واپس لیتا ہے؛ محفوظ شدہ فائل ہمیشہ مکمل ہوتی ہے۔","Compact JSON copied": "کمپیکٹ JSON کاپی ہو گیا","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "لوڈ ہو گیا: {dropped} فیلڈز ہٹائے گئے، {warnings} انتباہات — کنسول دیکھیں",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "ایمبیڈڈ منظر میں اپ ڈیٹس کی جانچ نہیں ہوتی — جانچ کے لیے فائل کو براؤزر ٹیب میں کھولیں۔",}diff --git a/slides/src/i18n/packs/vi.ts b/slides/src/i18n/packs/vi.tsindex 69849d16..db0bf8ab 100644--- a/slides/src/i18n/packs/vi.ts+++ b/slides/src/i18n/packs/vi.ts@@ -933,4 +933,5 @@ export const strings: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "Cùng bộ trang chiếu nhưng bỏ mọi giá trị mặc định: dạng mà một tác tử AI nên viết. “Thay thế từ JSON” nhận lại nó; tệp đã lưu luôn đầy đủ.","Compact JSON copied": "Đã sao chép JSON gọn","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Đã tải: bỏ {dropped} trường, {warnings} cảnh báo — xem console",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Không kiểm tra cập nhật trong chế độ xem nhúng — mở tệp trong một thẻ trình duyệt để kiểm tra.",}diff --git a/slides/src/i18n/pt.ts b/slides/src/i18n/pt.tsindex 37301e30..2cfa0e4a 100644--- a/slides/src/i18n/pt.ts+++ b/slides/src/i18n/pt.ts@@ -921,4 +921,5 @@ export const pt: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "A mesma apresentação sem nenhum valor predefinido: a forma que um agente de IA deve escrever. «Substituir a partir de JSON» aceita-a; o ficheiro guardado é sempre completo.","Compact JSON copied": "JSON compacto copiado","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "Carregado: {dropped} campos descartados, {warnings} avisos — ver a consola",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "Numa vista incorporada as atualizações não são verificadas — abra o ficheiro num separador do navegador para verificar.",}diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.tsindex 8aa898b4..d3027652 100644--- a/slides/src/i18n/zh-Hans.ts+++ b/slides/src/i18n/zh-Hans.ts@@ -923,4 +923,5 @@ export const zhHans: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "同一份文稿,省去所有默认值——AI 智能体应当书写的形式。“从 JSON 替换”可读回它;保存的文件始终是完整的。","Compact JSON copied": "已复制精简 JSON","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "已加载:丢弃 {dropped} 个字段,{warnings} 条警告 — 见控制台",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "在嵌入视图中不检查更新 — 请在浏览器标签页中打开文件以检查。",}diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.tsindex afa407d3..314dfb5c 100644--- a/slides/src/i18n/zh-Hant.ts+++ b/slides/src/i18n/zh-Hant.ts@@ -923,4 +923,5 @@ export const zhHant: Catalog = {"The same deck with every default left out — the shape an AI agent should write. Replace from JSON takes it back; the saved file is always full.": "同一份文稿,省去所有預設值——AI 代理程式應當書寫的形式。「從 JSON 取代」可讀回它;儲存的檔案始終是完整的。","Compact JSON copied": "已複製精簡 JSON","Loaded: {dropped} fields dropped, {warnings} warnings — see console": "已載入:捨棄 {dropped} 個欄位,{warnings} 則警告 — 見主控台",+ "Updates are not checked inside an embedded view — open the file in a browser tab to check.": "在嵌入檢視中不檢查更新 — 請在瀏覽器分頁中開啟檔案以檢查。",}diff --git a/slides/src/main.ts b/slides/src/main.tsindex 17727471..037e4b1d 100644--- a/slides/src/main.ts+++ b/slides/src/main.ts@@ -15,7 +15,7 @@ import {} from './save'import { maybeShowReturnGate } from './editor/returngate'import { buildSlidePreview } from './preview'-import { APP_VERSION, checkForUpdates, buildUpdatedFile, applyUpdate } from './update'+import { APP_VERSION, checkForUpdates, buildUpdatedFile, applyUpdate, sandboxed } from './update'import { i18nApi, t, applyDirection } from './i18n'import { parseDoc, type BentoDoc, type TextElement } from './model'import { compactJson } from './compact'@@ -265,19 +265,21 @@ if (location.hash === '#present') {}// Dismiss the boot splash (inline in index.html so it paints before this-// bundle parses). Hold it briefly so the assemble animation reads as a-// brand moment instead of a flicker; the pristine capture ran before this,-// so saved files keep the splash for their own next boot.-{- const splash = document.getElementById('bento-splash')- if (splash) {- const wait = Math.max(0, 1250 - performance.now())- setTimeout(() => {- splash.classList.add('done')- setTimeout(() => splash.remove(), 550)- }, wait)- }-}+// bundle parses). The pristine capture ran before this, so saved files keep+// the splash for their own next boot. Visible, it is held briefly so the+// assemble animation reads as a brand moment instead of a flicker — but+// the hold is a capped timer that a visibility change cuts short, and+// removal never waits on an animation or transition: a HIDDEN document+// (a background tab; a viewer rendering the file off-screen for a preview+// card) freezes CSS animations at their first frame, delivers no frames,+// and throttles timers to a wakeup a second or none at all — so a splash+// that waited for its own fade to end stayed over the mounted editor for+// as long as nobody looked, and Teams' preview card showed the splash with+// the mark still at opacity 0 (measured: identical bytes previewed on one+// upload and not the next, the race being the pane's capture against a+// throttled timer). Hidden, the splash goes the moment the editor exists.+dismissSplash()+// Small scripting surface for tooling and automation: read/replace the// document model and serialize the full .bento.html file.@@ -389,6 +391,10 @@ if (location.hash === '#present') {* returns the updated file's html (this doc inside the new shell);* apply() downloads it. check(url) accepts an override for testing.*/+ /** true inside an embedded view (a sandboxed frame — Teams, SharePoint):+ * no update check, no network at all from the app; storage does not+ * persist. Decided once at boot by kernel net.ts sandboxed(). */+ sandboxed: sandboxed(),updates: {version: APP_VERSION,check: (url?: string) => checkForUpdates(url),@@ -438,3 +444,33 @@ if (location.hash === '#present') {}} // editorMode++/**+ * Remove the boot splash: at once when the document is hidden, else after a+ * capped hold that a visibilitychange cuts short. The fade is a CSS+ * transition; removal follows it by a timer OR transitionend, whichever+ * comes first, and never depends on either alone.+ */+function dismissSplash() {+ const splash = document.getElementById('bento-splash')+ if (!splash) return+ let gone = false+ const remove = () => {+ if (gone) return+ gone = true+ document.removeEventListener('visibilitychange', onVisibility)+ splash.remove()+ }+ const fade = () => {+ if (gone) return+ if (document.hidden) { remove(); return }+ splash.classList.add('done')+ splash.addEventListener('transitionend', remove, { once: true })+ setTimeout(remove, 550)+ }+ const onVisibility = () => { if (document.hidden) remove() }+ document.addEventListener('visibilitychange', onVisibility)+ if (document.hidden) { remove(); return }+ // the brand hold, at most: 800 ms after navigation, visible only+ setTimeout(fade, Math.max(0, 800 - performance.now()))+}