Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
sync: the transport and session layers move to the kernel, and bento/type (#313)
nyblnete1cdfabae63d
diff --git a/.claude/launch.json b/.claude/launch.jsonindex 416342a5..d91ef322 100644--- a/.claude/launch.json+++ b/.claude/launch.json@@ -150,6 +150,23 @@"working"],"port": 5193+ },+ {+ "name": "type-dev",+ "comment": "LOOPBACK ONLY, see spaces-dev.",+ "cwd": "type",+ "runtimeExecutable": "npm",+ "runtimeArgs": [+ "run",+ "dev",+ "--",+ "--host",+ "127.0.0.1",+ "--port",+ "5191",+ "--strictPort"+ ],+ "port": 5191}]-}+}\ No newline at end of filediff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ff4d66e5..d2b27163 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -51,6 +51,7 @@ jobs:slides/package-lock.jsonspaces/package-lock.jsondash/package-lock.json+ type/package-lock.json- name: Installworking-directory: slides@@ -547,6 +548,62 @@ jobs:# is the regression.run: node scripts/test-layouts.ts+ # bento/type: the word processor. Same pipeline, same gate.+ - name: Install (type)+ working-directory: type+ run: npm ci++ - name: Typecheck (type)+ working-directory: type+ run: node_modules/.bin/tsc -b++ - name: Build single-file shell (type)+ working-directory: type+ run: npm run build:single++ - name: Splice conformance gate (type)+ run: node scripts/shell-gate.mjs type/dist-single/Bento_Type.bento.html++ - name: Type inline-formatting rig+ # A block stores plain text + marks over character ranges, and the+ # round trip render→read must be exact: if it is not, formatting+ # silently mutates on every re-render, which surfaces as a signed+ # document that stops verifying. Includes a 2,000-case fuzz — it found+ # two bugs no hand-written case did.+ run: node scripts/test-type-inline.ts++ - name: Type model rig+ # The load contract (an unreadable file must never become an empty one+ # over live data), deterministic id repair, and the rule that marks and+ # footnote anchors move together — separating them is what put a+ # footnote marker in the middle of a word.+ run: node scripts/test-type-model.ts++ - name: Type store rig+ # A typed word is ONE undo press, and a scoped snapshot really is+ # scoped: 200 edits cost ~94KB rather than ~21.7MB.+ run: node scripts/test-type-store.ts++ - name: Type redline rig+ # accept(all) == what they sent back, reject(all) == what you sent.+ # Without both, "review these changes" is a lie.+ run: node scripts/test-type-redline.ts++ - name: Type paginated-output rig+ # The printed page count must be the one the editor computed — if print+ # re-paginates, "page 14 paragraph 3" stops meaning anything, which is+ # the whole reason documents like this are exchanged as PDF. Also pins+ # that footnotes reach the page their reference lands on, and that a+ # document's own page size is what prints.+ run: node scripts/test-type-print.ts++ - name: Type theme rig+ # Static checks so a theme cannot rot: both themes define the same+ # roles, the document surface is never themed, and no chrome rule+ # borrows a document token — that last one shipped a select at 1.92:1+ # against a WCAG AA floor of 4.5.+ run: node scripts/test-type-theme.mjs+- name: Clipboard embedded-font rigrun: |slides/node_modules/.bin/esbuild scripts/test-clipboard.ts --bundle --platform=node --format=esm --outfile="$RUNNER_TEMP/test-clipboard.mjs"@@ -599,3 +656,48 @@ jobs:# format half is REPORTED, not asserted, because the fix is a decision# nobody has taken yet; STRICT=1 turns it into a gate the day it is.run: SEEDS=250 STEPS=80 ACTORS=4 node scripts/test-sync-spaces.ts++ - name: collaborative text on a parent node+ # The token RGA — what lets two people type in one paragraph without+ # destroying each other's work — was reachable only on CHILD nodes,+ # because both shipped apps put their text there. bento/type does not:+ # a block IS the paragraph. Bound naively it would get a+ # last-writer-wins register for prose and lose an edit SILENTLY, with a+ # document that stays valid and converges. Every other sync rig stayed+ # green through that bug, so this one carries a negative control: the+ # same scenario with the RGA off MUST lose an edit.+ run: node scripts/test-sync-parent-text.ts++ - name: a flat document shape+ # bento/type is one level deep — `body` holds blocks and nothing sits+ # beneath them — so `children` is null and there is no element layer.+ # Binds type's real shape and checks both halves: text still merges+ # token-by-token, and the document keeps its shape. The second matters+ # because an engine that quietly wrote `elements: []` onto every block+ # would converge perfectly while corrupting the format.+ run: node scripts/test-sync-flat.ts++ - name: bento/type under the shared engine+ # Convergence for the flat ('body', null, 'text') binding, AND a report+ # on whether what the replicas converge on is a legal bento/type+ # document. Those are different questions: `text` merges token by token+ # through the RGA while `marks` and `notes` — character offsets INTO+ # that text — merge as ordinary registers, so two legal concurrent+ # edits can converge on offsets that no longer describe the text they+ # index. Reported, not asserted, exactly as the spaces tree question+ # is: it is a format decision nobody has taken. STRICT=1 makes it a+ # gate the day one is.+ run: SEEDS=250 STEPS=80 ACTORS=4 node scripts/test-sync-type.ts++ - name: the sync session layer+ # The session — differ hook, shadow, presence, catch-up, the empty+ # document repair — had NO tests before it was moved into the kernel+ # and parameterized for three apps. This was written against the+ # implementation as it shipped and run unchanged after the move, which+ # is the only thing that makes "behaviour is identical" a claim rather+ # than a hope. It drives the REAL session over the REAL store through a+ # REAL BroadcastChannel; two sessions in one process are two tabs.+ # The last four sections bind bento/type to the same kernel session —+ # flat document, text on the parent, a store with one listener and no+ # dirty flag — so a surviving slides assumption shows up there.+ run: node --no-warnings scripts/test-sync-session.tsdiff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 510c8dc8..10e9b721 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -166,6 +166,64 @@ is `FileSystemWritableFileStream` semantics whose comments record the bug thatwrote documents out as zero bytes. Forking that file forks that bug.Details and verification state: `tray/README.md` § Android.+## 2026-08-10 — No dark topbar for now; THEMES are the right shape for it later++**Decision.** Every Bento app keeps the shared light chrome. A dark navy topbar+was prototyped on the real slides and type builds and is NOT being adopted as a+one-off. What is wanted instead is a proper light/dark theme layer across all+apps, of which a "contrasting" navy-topbar theme would be one option.++**Why.** The prototype looked good on light content — and the accent argument is+real, `#f7a600` is a faint tint on `#f5f7fa` and a clear focal point on+`#1e2a3a`, which is the brand's own navy+orange. But it fails on its own terms+in two places: the bar's dropdown MENUS and popovers stay light, so a dark bar+with light menus hanging off it reads as unfinished; and slides' content+luminance varies (the starter deck alone runs #0D1B2E / #F2F0EA / #FF9E8A), so+on a dark deck the bar merges with the slide and destroys the separation a dark+bar exists to create. Scope was measured, not guessed: the slides topbar alone+carries 25 distinct `ed-*` control classes, and a ten-line override missed one+immediately and shipped an invisible Save button into the comparison.++**What this implies now.** App chrome must refer to TOKENS only, never literal+colours, so a theme layer is a later addition rather than a rewrite.+`type/src/styles.css` is written that way and should stay that way.++**Pointers.** Tokens are shared verbatim by `slides/src/styles.css`,+`spaces/src/styles.css` and now `type/src/styles.css`.++---++## 2026-08-10 — bento/type: the app is named, and a block stores TEXT + MARKS, not HTML++**Decision.** The word processor is `bento/type`; `doc.format` is `"bento/type"`+and, like every format id, cannot be renamed once a file exists. Its block model+is plain text plus a list of marks over character ranges+(`{ t:'b', from, to }`), NOT an HTML string and not inline nodes. HTML is what+`inline.ts toHtml()` renders; it is never what is stored.++**Why.** Four things the app already depends on need a plain-text spine, and all+four break against HTML: the redline diffs text word-by-word (against HTML a+formatting change reads as a rewritten sentence); signatures cover a canonical+form (canonicalizing HTML means ruling on attribute order, tag case, whitespace+and entity spelling — four ways two honest parties produce different bytes for+one document); the caret is a model position, forced by measurement, because+with hyphenation on the renderer inserts characters and any rendered-space+address drifts; and footnote anchors are already offsets into the same string,+so marks reuse that rule rather than adding a second concept.++The cost is mark arithmetic, in one file, pinned by `scripts/test-type-inline.ts`+(38 checks incl. a 2,000-case fuzz) — which caught two bugs no hand-written case+found: a mark silently truncated when another overlapped it, and same-kind marks+failing to re-merge after a render split them (423/2,000).++**Pointers.** `type/src/inline.ts` (the argument is in the file header),+`type/src/model.ts` (tagged `parseDoc`, following the spaces load contract:+an unreadable file must never become an empty one), `scripts/test-type-model.ts`.+Design + the measured spike behind it: `working/type-design.md` and+`working/type-spike/RESULTS.md` (gitignored) — Path A, continuous pagination,+Knuth–Plass viable live.++---## 2026-08-06 — The tree is DERIVED at read time, in one function, and it cannot cycle@@ -2536,6 +2594,463 @@ payload 72KB → 79KB). Most of it is the finding messages, which are theproduct: a code with no explanation is not actionable. Anyone tempted to shrinkthis should shorten prose, not drop checks.+## 2026-08-15 — The sync engine's shape gains a text property, and children become optional++**Context.** `DocShape` described a document as two levels — `parents` holding+`children` — and hard-coded `'html'` as the property carrying collaboratively+edited text. Both shipped apps fit: a slide holds elements, a page holds+blocks, and in each the text is on the child. bento/type fits neither. Its+`body` is a flat list of blocks, a block IS the paragraph, so its text sits one+level up and there is nothing beneath it to point `children` at.++**Decision.** Two additive changes to the shape, both proven byte-identical for+existing files by `scripts/test-sync-equiv.ts`:++1. `DocShape.text` names the property that gets the token RGA. It defaults to+ `'html'` in `shape()`, so slides and spaces are untouched.+2. `DocShape.children` may be `null`, meaning a FLAT document with no element+ layer. `C()` then reads as a frozen empty array and the differ never mints+ an element op; `applyEffect` drops an element-scoped op that arrives anyway,+ because it has nowhere to land.++`shape('body', null, 'text')` is type's binding.++**Why the text property had to be named rather than inferred.** It is the one+property whose merge behaviour decides whether two people can type in the same+paragraph at once. Everything else is a last-writer-wins register, which for+prose means one author's work disappears — and disappears SILENTLY: the+document stays valid, the replicas converge, and the result simply contains one+of the two edits. There is no error to notice.++**That failure mode is why two new rigs exist.** The four existing sync rigs+stayed green through every step of this change, including through a real bug —+none of them declares text anywhere but on a child, so none of them exercised+the new path at all. Green there means "nothing broke", never "the new thing+works".++- `scripts/test-sync-parent-text.ts` isolates ONE variable: text on a parent,+ children still present. It carries a **negative control** — the same scenario+ with the RGA off must lose an edit — because a rig that has never been seen+ failing is not a gate.+- `scripts/test-sync-flat.ts` binds type's real shape. Besides convergence it+ asserts the document keeps its SHAPE: an engine that quietly wrote+ `elements: []` onto every block would converge perfectly and still corrupt+ the format, so that is checked directly rather than inferred from+ convergence.++**Two bugs found this way, both invisible to the existing suite.**++- Making `text` configurable, the CONDITIONS were rewired to `S.text` while the+ OPERANDS stayed hard-coded — `diffText(id, bp.html, ap.html)`, the+ materialize write-backs, and four register keys built as `` `${el} html` ``.+ Every one is correct while `S.text === 'html'` and wrong for any other app.+ Grepping for `.html` does not find the register keys; they are template+ strings.+- The flat-shape guard read `op.el` as "this op is element-scoped". On a `txt`+ op `el` is the NODE key, which for a flat document is the block's own id — so+ the guard dropped every collaborative keystroke type would ever send, while+ structure ops kept converging. One author's edits landed and the other's+ vanished.++**A trap for whoever tests this next.** Two fixtures here read correct+behaviour as a bug: both minted an op, never delivered it, then delivered a+later one and found it had no effect. That is the per-actor sequence guarantee+holding the second op in the gap buffer, exactly as designed. Deliver the whole+sequence.++**Not done here.** type's session/transport layer is still slides-shaped+(PLATFORM §9), so this makes type's collaboration possible, not present.++## 2026-08-15 — bento/type's sync binding, and doc-level maps become a shape field++**The binding.** `type/src/sync/crdt.ts`, a facade like the other two apps':+`shape('body', null, 'text', ['footnotes'])`. It is the first FLAT binding and+the first whose text is not on a child; both were kernel changes made earlier+the same day, not things this file works around.++**Doc-level maps are now declared by the shape.** `assets` and `blobs` were+hard-coded as per-KEY registers, with the right reason attached: two people+adding different assets concurrently must both keep theirs. Any id-keyed map+wants that, and an app could not ask for it while the names were baked in.+`DocShape.maps` now names them; `shape()` unions the caller's list with+`assets`/`blobs` so an app declaring its own cannot accidentally drop those.++type's `footnotes` (note id → note text) is such a map. As one whole-value+register, two authors each adding a footnote kept both REFERENCES — those live+on different blocks and merge independently — while one of the two BODIES was+overwritten, leaving a marker in the text pointing at nothing.++**Measured, not argued.** Over 120 seeds × 60 steps × 3 actors:++| | before | after |+|---|---|---|+| seeds with a dangling note | 34 | 5 |+| seeds with any format violation | 30.8% | 7.5% |++**What the rig reports rather than asserts.** A block's `text` merges token by+token through the RGA, while its `marks` and `notes` are CHARACTER OFFSETS into+that text and merge as ordinary registers. Two independent merge domains+describing one paragraph — the same shape of problem `parent`-versus-position is+for bento/spaces, and like that one it is a format-level decision rather than a+bug to patch inside a rig. At 400 seeds × 80 steps × 4 actors (19,016 ops),+11.8% of seeds converge on a document with at least one violation.++The rig carries a worked example, because a percentage is not an account of+what goes wrong. Both authors insert text BEFORE a bold phrase and both shift+their own marks correctly with the app's `spliceText`:++```+merged text: "Notwithstanding the above, Under clause 4, Payment is due within 30 days."+bold covers: "t is du" (it should cover "30 days")+```++Neither replica ever held the correct offset — it is shifted by BOTH insertions+— so no register winner could have been right. `STRICT=1` turns the report into+a gate the day the decision is taken.++**Two smaller findings, named so they are not rediscovered as bugs.**++- Concurrent deletion can empty `body` entirely (4 of 400 seeds). A document+ with no blocks is not one the editor should ever present.+- The residual dangling notes are the same cross-domain split one level up: the+ REFERENCE is a block property and the BODY is a map entry, so deleting a+ footnote concurrently with editing its paragraph can keep one and not the+ other.++**Convergence itself is compared by VALUE, not by `JSON.stringify`.** A property+deleted and re-added moves to the end of its object, so replicas that applied+the same removals in a different order hold equal documents with different key+order — 288 of 400 seeds, every one spurious. Checked rather than assumed+before relying on it: canon.ts sorts keys (RFC 8785 §3.2.3), so two blocks+differing only in key order produce the same signing digest, and the redline+aligns on block id.++**Not done here.** The session and transport layer is still slides-shaped+(PLATFORM §9). type has a converging engine, not live collaboration.++## 2026-08-15 — The sync session and transport move to the kernel, behind a five-method host++**Context.** `crdt.ts` was kernelized and parameterized by document shape, but+the layer above it — the session (differ hook, shadow, presence, catch-up, gap+recovery, blobs, the fork snapshot exchange) and the online relay transport —+still lived in `slides/` and was slides-shaped. bento/dash had already responded+by PORTING `online.ts` wholesale (`dash/src/sync/online.ts` still says so in its+header). A second copy of the transport is a second thing to fix when the relay+protocol changes, and the relay is the part that must not fork.++**What actually coupled the session to slides.** Of 727 lines, FIVE places knew+what a slide was: repairing an emptied document, clamping the view, pruning a+selection, saying where a person is for presence, and recognising embedded media+in a refused batch. `online.ts` had exactly ONE: the hard no-network switch.+`blobs.ts` had none and moved untouched.++**Decision.** `kernel/src/sync/{session,online,blobs}.ts`, with apps supplying a+`SyncHost`: `heal`, `clampView`, `presence`, the store event names, a+`carriesMedia` probe, and the shape-bound engine class. `slides/src/sync/*.ts`+are facades, so `new SyncSession(store)` still works everywhere it already did.+bento/type gets one too, and needed no kernel changes to do it.++**Test first, and this time literally.** The session had NO tests. Moving+untested code across a seam is how behaviour changes silently, so+`scripts/test-sync-session.ts` was written against the implementation AS IT+SHIPPED, run to 13/13, and then run UNCHANGED after the move — same 13/13,+including the same merged string from a concurrent text edit. It drives the real+session over the real store through a real BroadcastChannel; two sessions in one+process are two tabs of one document, which is the transport that ships.++**Running app source in node needed a hook, and that was the right trade.**+`scripts/lib/ts-resolve-hooks.mjs` resolves Vite-style extensionless imports and+transpiles with esbuild — Node's built-in TypeScript is strip-only and rejects+`constructor(private store: Store)`. The alternative was editing session.ts to+drop the parameter property, which was rejected on principle: a rig that exists+to prove behaviour is unchanged cannot start by changing its subject.++**Two decisions inside the move worth keeping.**++- The offline switch is INJECTED (`setOfflineCheck`) and the kernel default is+ OFFLINE. Defaulting the other way means an app that forgot to wire it starts+ phoning home silently, which is the one failure this project should never+ ship.+- `PresenceInfo.slide` keeps its name on the wire. It now means "where this+ person is" — a block id for type — but deployed clients and the relay read+ that field, so renaming it would fork presence.++**bento/type now has live collaboration end to end**, proven through the store,+the differ, the debounce, a real channel and back:++```+two people typing in one paragraph:+ "Payment is due within sixty (60) days of invoice." ← both edits survived+```++Its host also pins a word-processor-specific rule the kernel could not know: a+remote edit arrives through `Store.touch`, never `commit`, so it never lands on+this person's undo stack. ⌘Z means "undo what I did" — a remote paragraph+arriving as a commit would make it revert a colleague's work and redo would+bring it back as if it were yours. The rig proves a local edit DOES push a step+before claiming the remote one does not.++**Not done here, and one correction.** bento/spaces has no session binding yet;+that one IS small, a host adapter over a store that already has on/emit/commit.++bento/dash is NOT. An earlier draft of this entry said dash needed "just a host+adapter"; that was wrong, and `dash/src/sync/crdt.ts` is why. Its 2,313 lines are+not a fork of the kernel engine but a DIFFERENT one, built for spreadsheet scale+— sparse per-row state so an untouched row costs zero bytes in `collab.sync`,+run-length order lists, O(inserts) rather than O(rows), sheet-scoped column ids.+The kernel engine would put O(rows) of state in the file. Merging those is a real+design question, not a refactor, and nothing here should be read as having+settled it. `scripts/test-dash-sync.ts` (23,100 checks) exercises dash's engine,+not the kernel's.++What is plausibly shared is dash's `online.ts`, whose own header calls it "A PORT+of slides/src/sync/online.ts". That is the RELAY protocol, which is the one part+that should not fork — the deployed worker verifies signatures and the+invite/member chain against it. It already imports kernel storage and update.+Left alone pending the dash session's answer on whether it is deliberately+diverged.++## 2026-08-15 — `changeEvents`: the kernel session stops assuming one app's event names++**What was wrong.** The kernelized session fired `store.emit('doc')` after every+remote change. In bento/slides `'doc'` means "something changed, repaint", so+that read as universal. It is not. In bento/spaces the store emits four events+and `'doc'` is the DIRTY/STATUS signal — repainting goes through `'tree'` and+`'page'` — so a remote op would have labelled a colleague's edit "Edited" in this+user's chrome and moved their dirty flag. The kernel had shipped one app's habit+as a default, in the very seam built to stop that.++**Decision.** `SyncHost` names both sets:++```ts+readonly changeEvents: readonly string[] // after EVERY remote change+readonly structureEvents: readonly string[] // extra, on a structural one+```++slides and type declare `changeEvents: ['doc']`, so neither changed. An app that+wants no always-on event declares `[]`.++**How it was found, which is the part worth keeping.** Not by a test — by the+bento/spaces session reviewing the interface before building against it. It also+caught three things in a spaces adapter this session had drafted: a `heal()` that+minted the repair page with a random id (two replicas healing concurrently would+create two pages and the CRDT would faithfully keep both — the fix is to derive+the id from `docId`), a view clamp that fell back to the home page rather than to+the deleted page's PARENT, and a `carriesMedia()` that re-decided a question+already settled by "Large assets travel out-of-band; the relay stays blind"+(2026-07-25).++The draft was deleted and `spaces/src/sync/session.ts` left to that session,+which holds context this one did not have — including a user decision taken this+week and not yet written down: a space does not auto-connect on open. The+"obvious" call there is auto-connect, and it is the wrong one; it would reproduce+the v0.9.1 regression where every anonymous visitor to the demo phoned home.++**The general lesson.** A seam is not proven by the app that shaped it. Both+defects here were invisible from bento/slides and bento/type, because both put+their text on a child, both call their repaint event `'doc'`, and both were+written by the same session. The third app is where the assumptions show, and it+is cheaper to ask its owner than to discover it after the room exists.++**Two changes left in the spaces zone**, both offered for revert: `Store.reindex()`+is now public (a remote apply writes straight to `doc`, bypassing commit, so+nothing else rebuilds the derived index), and `SpacesDoc.collab` is typed+`CollabCreds` instead of `unknown` — it was marked RESERVED "unused until collab+ships", and it ships. That type moved to `kernel/src/sync/crdt.ts` beside+`SyncStateJSON`, so a document-format type is not reachable only through the+session: the deployed relay verifies against that shape, and a second local+description of it is how a client and the worker drift apart.++## 2026-08-15 — Known gap: the moved sync modules still hold raw network primitives++**Recorded because it is security-relevant and easy to lose.** The session/+transport lift relocated four raw network calls into `kernel/src/sync/`:++```+kernel/src/sync/online.ts new WebSocket(...) the relay socket+kernel/src/sync/blobs.ts fetch() × 3 blob HEAD, upload, download+```++They are not new — `git show HEAD:slides/src/sync/blobs.ts | diff -+kernel/src/sync/blobs.ts` is IDENTICAL, and online.ts differs only in imports and+type names. The lift created none of them. What it did do is move them out from+under the paths that PR #305 targets — the fix for a privately reported advisory+(GHSA-5c3x-xqp6-g94r) where offline mode leaked from five places — so they are+now just as reachable and no longer in the diff that was under review. The bypass+is unchanged; the move made it easier to miss. That is the reason this entry+exists rather than a chat message.++**The fix, not applied here because `kernel/src/net.ts` does not exist in this+tree yet:** once #305 lands, `import { netFetch, netWebSocket } from '../net.ts'`,+swap the four call sites, and add the retry guard so a refused connection does+not spin against the switch:++```ts+} catch { if (!offlineEnabled()) this.retry(); return }+```++Writing that against an interface not yet present would have been guessing.++**A second call site that is invisible from `slides/`.** `kernel/src/sync/+online.ts` now imports `offlineEnabled` from `../update.ts` directly. (An+injection point was built for it and removed once `offlineEnabled` turned out to+already be in `kernel/src/update.ts`.) If #305's re-export from `update.ts` is+ever dropped, this breaks as a typecheck failure rather than a silent bypass —+but `scripts/test-offline.ts` would not catch it either way: that rig enforces+who may touch the PRIMITIVES, not who reads the SWITCH.++**The four above are NOT the whole defect.** #305 is broader: a single chokepoint+at `kernel/src/net.ts`, plus `render.ts` remote images (`remoteSrcBlocked`), and+dash. And the same hole was found independently from the opposite direction while+auditing the pack channel for an extensions question — `slides/src/packs.ts`+never consults `offlineEnabled` at all. Verified here rather than taken on+report: `grep -c offlineEnabled slides/src/packs.ts` → 0, against THREE reachable+network paths — `fetchPinned` (:133), a bare `fetch` HEAD probe (:141), and the+listing fetch in `fetchIndex` (:228). Meanwhile `docs/security.md:140` publishes+the claim that with offline on "you can watch the network tab stay silent". For+the pack channel that is currently false.++Scoped precisely, because an earlier draft of this entry overstated it as firing+"from the moment the listing loads": `fetchIndex` has two callers and NEITHER is+at boot — `availablePacks()` (editor.ts:1342, the Manage languages dialog) and+`refreshPacksForVersion()` (i18n.ts:76, via registerUpdatePrepare). So opening a+deck offline does not hit the network from this path. The honest statement is+"from the moment the pack UI is opened". Whether the second caller is reachable+in offline mode depends on gating in the update path that nobody has traced, and+is left as an open question rather than a claim — it is moot if everything routes+through `net.ts`, which is the argument for the chokepoint.++Two people finding the same hole from unrelated directions is some corroboration+that the advisory is real and aimed at the right place. It also means the+DECISIONS entry merged as 5eaccf8 UNDERSTATES it: that entry describes the+packs.ts symptom, not the missing chokepoint. Cite it with that in mind.++**A separate defect in the switch itself, verified while checking the above.**+`offlineEnabled()` (kernel/src/update.ts:43) reads `lsGet('bento-offline') ===+'on'`, and `lsGet` swallows its own failure and returns null. Note where the bug+actually is: `offlineEnabled` HAS a `try/catch` returning false, and it is DEAD+CODE — `lsGet` never throws, so the catch never runs and the gate fails through+`null === 'on'` instead. The defence looks present and is unreachable, which is+why reading the function alone does not reveal it. So where storage is+unavailable — Safari private browsing, a blocked file:// context, an opaque+origin — the gate answers ONLINE. The UI diverges rather than agreeing with it:+editor.ts:2871 seeds the checkbox from `offlineEnabled()` once, then :2873 calls+`setOffline(offCb.checked)`, whose write also swallows failure. Tick the box in+that context and the checkbox stays visibly ticked while the gate keeps answering+online, until something rebuilds the dialog. A security control that reads ON and+behaves OFF is worse than one that refuses to turn on. (Found by the bento/dash+session auditing against #305; confirmed here by reading both call sites.)++**FIXED by #305, merged as 759fb93 — verified rather than assumed after this+entry claimed otherwise.** The gate is now `sessionOffline ?? lsGet(...)` with the+in-memory value winning, `setOffline` RETURNS whether the write persisted, and the+dialog surfaces the failure. It still cannot persist across a reload where storage+is unavailable — `sessionOffline` is module state — but it no longer claims to,+which is the right shape for the constraint. `offlineEnabled`/`setOffline` moved+from `update.ts` into `net.ts`, with `update.ts` re-exporting them, so the+kernel's sync import keeps working.++**Why that fix is immune rather than lucky**, which is the transferable part: it+replaced the gate's SOURCE OF TRUTH, not its error handling. Hardening the+`catch` would have changed nothing, because the catch was never the path taken.+A defence that sits on the error path cannot protect a function that fails+without erroring.++This entry originally said the chokepoint would not fix it ("net.ts will+faithfully consult a gate that is lying"). That was true of the chokepoint IDEA+and false of the actual diff, which fixes both halves. The observation is still+the useful one — centralising call sites is not sufficient when the thing they+consult can lie — but it was already addressed, and recording a fixed defect as+outstanding is its own kind of error.++**Ordering, as it actually resolved.** #305 landed first (759fb93), which was the+right sequence: a security fix should not wait on a refactor. The kernel lift+takes second and applies the four swaps to the moved copies.++That integration is NOT a small apply, contrary to an early estimate from both+sides. Measured from this tree — and these numbers DRIFT, because origin/main+moves while the work sits uncommitted: they went from 13 commits and 69 upstream+files to 14 and 79 during a single conversation. Base 89b4462, 14 commits behind+origin/main, 28 uncommitted files here against 79 upstream, with six overlapping —+`.github/workflows/ci.yml` and `docs/DECISIONS.md` (append vs append),+`kernel/src/theme.ts` (another session's file, now also upstream), and the three+`slides/src/sync/*` rename-vs-modify pairs.++A shortcut was considered and rejected: writing `git show 759fb93:kernel/src/net.ts`+into the tree to unblock the swaps would produce a tree that is post-#305 in one+file and pre-#305 in sixty-eight, where the first failure is unattributable.++**The lift WILL fail CI on contact, by design.** `scripts/test-offline.ts` scans+`['kernel/src', 'slides/src', 'dash/src', 'spaces/src']`, so the four relocated+primitives are in scope the moment the integration lands — 3 in+`kernel/src/sync/blobs.ts`, 1 in `kernel/src/sync/online.ts`. That is the rig+working: the swaps are not optional cleanup, they are what makes the build green.+`netWebSocket(url)` returns a genuine `WebSocket` (not a proxy), so `binaryType`,+the four handlers and `.close(code)` are unchanged; the only behavioural+difference is that it THROWS `OfflineError` when the switch is on, which is why+the call site needs `if (!offlineEnabled()) this.retry()`.++**`type/src` was not in that scan list**, so bento/type — a fourth app with a+model, store, editor, pagination, signing and now a sync binding — was silently+exempt from the policy. It has no network path today (verified: zero matches for+all five primitives), which is precisely why it was worth raising while the fix+could not fail.++The fix taken was better than the one proposed, and the argument for it was in+the complaint. Adding `'type/src'` to the array fixes type and leaves the NEXT+app — and the next app is by definition the one nobody is thinking about. So the+list became DISCOVERY: any top-level directory containing `src/` is in scope, and+an app joins the policy by existing (slides #307). Discovery has its own failure+mode, and it is this rig's own lesson one level up — a green run over an empty+list is indistinguishable from a green run over the whole repo — so it asserts+that discovery still finds the known apps and does not sweep in non-app+directories.++The general form is worth keeping: **an exemption list is a latent violation with+a date on it.** When the answer is "add ourselves to the list", check whether the+list should exist.++**`kernel/src/theme.ts` is a shadow, not a member of this change set.** It sits+untracked in the shared checkout and shows up in every overlap measurement, which+made it look like an orphan needing an owner. It is not: it is byte-identical to+`origin/main:kernel/src/theme.ts`, shipped in #285, and imported upstream by+`slides/src/editor/editor.ts` and `slides/src/main.ts`. Nobody needs to adopt it.++It cannot simply be deleted from this tree today, because this tree's base+(89b4462) PREDATES #285 — so the untracked copy is the only copy here, and+`type/src/main.ts` imports it. Delete it now and bento/type stops building;+delete it after the rebase and nothing happens, because the tracked file takes+over. So: keep it until the rebase, drop it as part of the rebase, and do NOT+commit it — committing would add a file that already exists upstream and+manufacture a conflict out of nothing.++The general trap: an untracked file that is byte-identical to a tracked one+upstream is invisible to every tool you would reach for. It does not appear in+`git diff`, it survives `git checkout`, and it makes a file look present at a+commit where it is absent. Two separate sessions reasoned about this one wrongly+in opposite directions — one concluded it was an unowned orphan safe to remove+(it is neither), the other that a downstream app depended on it and therefore+owned it (it depends on it, but does not own it).++The actionable rule, which is narrower than the trap and is what either of us+needed: **search the REF, not the working tree.** Every observation behind the+wrong conclusions was TRUE of a checkout based at 89b4462 and FALSE of main — at+that base slides genuinely does not import the file and the file genuinely is+untracked, because the base predates #285. `git grep kernel/src/theme origin/main`+is one command and shows the two slides importers immediately. A working tree+held at an old base is not a view of the project; it is a view of the past, and+"I checked" means nothing without saying checked against WHAT.++(A matching blob is also weaker evidence than it looks: it says two commits+contain the same content, not that one came from the other. The `slides-theme`+branch shares this file's bytes and never merged; the content reached main by a+different PR.)++One trap worth recording for anyone verifying this: local `main` was 802804b and+STALE — #305 is on `origin/main`. Checking against `main` reports `kernel/src/+net.ts` as absent and the slides sync files as unchanged, i.e. that #305 never+landed. Compare against `origin/main`.+---## 2026-08-14 — a self-update must not be the one save that interruptsdiff --git a/docs/PARALLEL-WORK.md b/docs/PARALLEL-WORK.mdindex 1cef9025..6003b63f 100644--- a/docs/PARALLEL-WORK.md+++ b/docs/PARALLEL-WORK.md@@ -16,10 +16,20 @@ rules exist to keep N parallel workstreams from dissolving into merge hell.`src/i18n.ts` facade.- **Kernel zone — `kernel/src/`** — `save.ts` (splice + bento/enc),`autosave.ts`, `update.ts`, `anim.ts`, `charts.ts`, the `i18n.ts` engine,- `app.ts`, `doc.ts`, `sync/crdt.ts` (the CRDT engine); plus the rest of- `slides/src/sync/` (session, transport, blobs) and `server/`, which are- shared in effect even though they still live app-side. See- `docs/PLATFORM.md` §9.+ `app.ts`, `doc.ts`, and the whole of `sync/` — `crdt.ts` (the CRDT engine),+ `session.ts`, `online.ts` (the relay transport) and `blobs.ts`; plus+ `server/`, which is shared in effect even though it lives outside the kernel.+ See `docs/PLATFORM.md` §9.++ This entry used to add "plus the rest of `slides/src/sync/` (session,+ transport, blobs) … shared in effect even though they still live app-side".+ They no longer live app-side: the session and transport moved into+ `kernel/src/sync/` behind a small per-app `SyncHost`, and+ `slides/src/sync/*` are facades. The rule they were under has not changed —+ they were always serialized, and the parenthetical existed only to say so+ about files whose location disagreed with their status. Each app's+ `src/sync/crdt.ts` and `src/sync/session.ts` facade, which pin that app's+ document shape and its five host decisions, are APP zone.This zone is:**serialize, don't parallelize.** One coordinated change at a time, reviewedagainst the platform invariants. If your app task needs a kernel change,diff --git a/docs/PLATFORM.md b/docs/PLATFORM.mdindex 7dde8637..8e988a46 100644--- a/docs/PLATFORM.md+++ b/docs/PLATFORM.md@@ -198,16 +198,33 @@ engine, `app.ts` (per-app identity via `configureApp`), `doc.ts` (the`KernelDoc` envelope). Apps import these through facades at their own paths.The CRDT engine is `kernel/src/sync/crdt.ts` now. It takes its document shape-as a `DocShape` at construction (two property names: the doc key holding the-parent array, the parent key holding the child array), so one algebra serves-bento/slides and bento/spaces with neither app's vocabulary in the kernel. An-app imports its own binding — `slides/src/sync/crdt.ts` → `SLIDES_SHAPE` —+as a `DocShape` at construction, so one algebra serves every app with no app's+vocabulary in the kernel. A shape is four things:++- `parents` — the doc key holding the parent array (`slides`, `pages`, `body`)+- `children` — the parent key holding the child array, or `null` for a FLAT+ document that has no element layer (bento/type: a block IS the paragraph)+- `text` — the property that gets the token RGA rather than a last-writer-wins+ register. This is the one that decides whether two people can type in the+ same paragraph at once, which is why it is named rather than assumed.+- `maps` — doc-level keys merged per KEY rather than as one value, so two+ people adding different entries both keep theirs. Always includes `assets`+ and `blobs`; an app adds its own (bento/type: `footnotes`).++An app imports its own binding — `slides/src/sync/crdt.ts` → `SLIDES_SHAPE` —never the engine directly.-Also shared but NOT yet in `kernel/`: the session/transport layer-(`slides/src/sync/session.ts`, `online.ts`, `blobs.ts`) and the relay-(`server/`). Those are still slides-shaped — treat them as kernel-zone for-serialization.+The session and transport are in `kernel/src/sync/` too: `session.ts` (the+differ hook, shadow, presence, catch-up, gap recovery, the fork snapshot+exchange), `online.ts` (the E2EE relay transport) and `blobs.ts`. An app+supplies a small `SyncHost` for the handful of decisions the kernel cannot+make — what an EMPTY document is and how to repair it, how to clamp a view onto+a document that changed underneath it, where a person is for presence, which+store events its editor listens to, and what embedded media looks like in an op+batch — plus its shape-bound engine class. `slides/src/sync/*` are facades.++Still shared but outside the kernel: the relay (`server/`). Treat it as+kernel-zone for serialization.Shared build tooling: `scripts/postbuild-compress.mjs` (parameterised per appvia `--generator` / `--title`) and `scripts/shell-gate.mjs`.@@ -225,7 +242,11 @@ A new Bento app is on-platform when it:- [ ] self-saves (FSA + download) and autosaves per §4- [ ] supports the `bento/enc` envelope per §4 (or explicitly documents why not yet)- [ ] ships collab dormant-by-default per §5, or ships without collab wired- rather than with a half-secure version+ rather than with a half-secure version. Wiring it is now two small+ files, not a port: `src/sync/crdt.ts` declaring the app's `DocShape`,+ and `src/sync/session.ts` supplying a `SyncHost` (§9). Copying another+ app's session is the wrong move and was the actual history here —+ bento/dash ported the transport, and the copy is still being unpicked.- [ ] verifies signed updates per §6 with its own manifest path- [ ] exposes the AI round-trip surface per §7- [ ] uses the shared i18n runtime per §8diff --git a/kernel/src/sync/blobs.ts b/kernel/src/sync/blobs.tsnew file mode 100644index 00000000..dd7fd642--- /dev/null+++ b/kernel/src/sync/blobs.ts@@ -0,0 +1,311 @@+// 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 { netFetch } from '../net.ts'+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Encrypted asset blobs — the client half of docs/blob-offload.md.+//+// WHY THIS EXISTS. An asset cannot travel as a CRDT op: a Durable Object+// storage value caps near 2MB, and an asset costs ~1.78x its binary size on+// the wire (base64 twice — once into the data URI, once over the ciphertext).+// So ~1.05MB of binary is the ceiling for an op, against an 8MB embed budget.+// No frame-size constant fixes that. Assets go to the relay's blob store+// instead and the op carries only a reference.+//+// WHY CHUNKED. WebCrypto has NO streaming AES-GCM — encrypt/decrypt are+// one-shot — and a round trip costs roughly 5x the payload in memory+// (measured: 8MB -> 40MB, 64MB -> 320MB). Encrypting a large asset in one+// call would spike a browser tab, and mobile Safari kills tabs for less.+// Fixed-size chunks bound peak memory to ~5x CHUNK regardless of asset size,+// and fall out naturally as resumable upload units later.+//+// WHY THE KEY IS AN HMAC. Content addressing gives dedupe for free, but a bare+// sha256(plaintext) as the storage key would let the relay see that two+// different rooms hold the same image. HMAC(roomKey, hash) is deterministic+// WITHIN a room (so dedupe works) and opaque across rooms (so nothing+// correlates). The relay only ever sees the HMAC.++/** Plaintext bytes per chunk. Peak memory is ~5x this, not ~5x the asset. */+const CHUNK = 4 * 1024 * 1024+/** Must match the relay's MAX_BLOB. NOTE this bounds the ENCODED blob, not the+ * plaintext — the relay measures what it receives. */+export const MAX_BLOB = 8 * 1024 * 1024+const MAGIC = 0x4242 // 'BB'+const HEADER = 16+const IV_LEN = 12+const TAG_LEN = 16++const b64u = {+ enc(bytes: Uint8Array): string {+ let s = ''+ for (const b of bytes) s += String.fromCharCode(b)+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')+ },+ dec(s: string): Uint8Array {+ const b = atob(s.replace(/-/g, '+').replace(/_/g, '/'))+ const out = new Uint8Array(b.length)+ for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i)+ return out+ },+}++/** `data:<mime>;base64,<payload>` → bytes + mime. Null if not a data URI. */+export function dataUriToBytes(uri: string): { bytes: Uint8Array; mime: string } | null {+ const m = /^data:([^;,]*)(;base64)?,(.*)$/s.exec(uri)+ if (!m) return null+ const mime = m[1] || 'application/octet-stream'+ if (!m[2]) return { bytes: new TextEncoder().encode(decodeURIComponent(m[3])), mime }+ const raw = atob(m[3])+ const bytes = new Uint8Array(raw.length)+ for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i)+ return { bytes, mime }+}++/** bytes → `data:<mime>;base64,…`, chunked so a large asset doesn't blow the+ * argument stack via String.fromCharCode(...bytes). */+export function bytesToDataUri(bytes: Uint8Array, mime: string): string {+ let s = ''+ for (let i = 0; i < bytes.length; i += 0x8000) {+ s += String.fromCharCode(...bytes.subarray(i, Math.min(i + 0x8000, bytes.length)))+ }+ return `data:${mime};base64,${btoa(s)}`+}++/** Encoded size for `n` plaintext bytes: header + per-chunk IV and GCM tag.+ * The client must check THIS against MAX_BLOB, not the plaintext length —+ * otherwise an asset just under the limit passes here and is refused 413 by+ * the relay, which measures the ciphertext. */+export function encodedSize(n: number): number {+ return HEADER + Math.max(1, Math.ceil(n / CHUNK)) * (IV_LEN + TAG_LEN) + n+}++/** Largest plaintext asset that still fits in one blob. */+export function maxAssetBytes(): number {+ let n = MAX_BLOB+ while (n > 0 && encodedSize(n) > MAX_BLOB) n -= 1+ return n+}++async function hmacKey(rawRoomKey: Uint8Array): Promise<CryptoKey> {+ return crypto.subtle.importKey(+ 'raw', rawRoomKey as BufferSource, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],+ )+}++/**+ * Storage key for an asset: HMAC(roomKey, sha256(plaintext)), base64url,+ * truncated to 32 chars (the relay accepts [A-Za-z0-9_-]{16,64}). Same bytes+ * in the same room always yield the same key — that IS the dedupe.+ */+export async function blobKey(rawRoomKey: Uint8Array, bytes: Uint8Array): Promise<string> {+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes as BufferSource))+ const mac = await crypto.subtle.sign('HMAC', await hmacKey(rawRoomKey), digest as BufferSource)+ return b64u.enc(new Uint8Array(mac)).slice(0, 32)+}++async function aesKey(rawRoomKey: Uint8Array): Promise<CryptoKey> {+ return crypto.subtle.importKey('raw', rawRoomKey as BufferSource, 'AES-GCM', false, ['encrypt', 'decrypt'])+}++/**+ * Encrypt to the on-the-wire blob layout:+ * [magic u16][version u8][reserved u8][chunkSize u32][totalSize u32][nChunks u32]+ * then per chunk: [iv 12][ciphertext (plaintext + 16-byte tag)]+ * Chunk lengths are implied by chunkSize + totalSize, so nothing is ambiguous.+ */+export async function encodeBlob(rawRoomKey: Uint8Array, bytes: Uint8Array, mimeUnused?: string): Promise<Uint8Array> {+ void mimeUnused // mime rides in the op, not the blob: the blob is opaque+ const key = await aesKey(rawRoomKey)+ const nChunks = Math.max(1, Math.ceil(bytes.length / CHUNK))+ const out = new Uint8Array(HEADER + nChunks * (IV_LEN + TAG_LEN) + bytes.length)+ const dv = new DataView(out.buffer)+ dv.setUint16(0, MAGIC, true)+ dv.setUint8(2, 1)+ dv.setUint8(3, 0)+ dv.setUint32(4, CHUNK, true)+ dv.setUint32(8, bytes.length, true)+ dv.setUint32(12, nChunks, true)+ let at = HEADER+ for (let i = 0; i < nChunks; i++) {+ const slice = bytes.subarray(i * CHUNK, Math.min((i + 1) * CHUNK, bytes.length))+ const iv = crypto.getRandomValues(new Uint8Array(IV_LEN))+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, slice as BufferSource))+ out.set(iv, at); at += IV_LEN+ out.set(ct, at); at += ct.length+ }+ return out+}++/** Inverse of encodeBlob. Null on a wrong key, truncation or corruption —+ * every chunk is individually authenticated by its GCM tag. */+export async function decodeBlob(rawRoomKey: Uint8Array, blob: Uint8Array): Promise<Uint8Array | null> {+ if (blob.length < HEADER) return null+ const dv = new DataView(blob.buffer, blob.byteOffset, blob.byteLength)+ if (dv.getUint16(0, true) !== MAGIC || dv.getUint8(2) !== 1) return null+ const chunkSize = dv.getUint32(4, true)+ const total = dv.getUint32(8, true)+ const nChunks = dv.getUint32(12, true)+ if (!chunkSize || nChunks > 4096) return null+ const key = await aesKey(rawRoomKey)+ const out = new Uint8Array(total)+ let at = HEADER+ let wrote = 0+ for (let i = 0; i < nChunks; i++) {+ const plainLen = Math.min(chunkSize, total - wrote)+ const ctLen = plainLen + TAG_LEN+ if (at + IV_LEN + ctLen > blob.length) return null+ const iv = blob.subarray(at, at + IV_LEN); at += IV_LEN+ const ct = blob.subarray(at, at + ctLen); at += ctLen+ try {+ const plain = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ct as BufferSource))+ out.set(plain, wrote)+ wrote += plain.length+ } catch {+ return null // wrong key or tampered chunk+ }+ }+ return wrote === total ? out : null+}++// --- local cache -------------------------------------------------------------+// A blob a peer sent is worth keeping: the same asset is referenced by every+// slide that uses it, and re-fetching on each render would be absurd. Keyed by+// the blob key, which is already content-addressed.++const DB = 'bento-blobcache'+const STORE = 'blobs'+let dbP: Promise<IDBDatabase | null> | null = null++function db(): Promise<IDBDatabase | null> {+ if (dbP) return dbP+ dbP = new Promise((resolve) => {+ if (typeof indexedDB === 'undefined') return resolve(null)+ let req: IDBOpenDBRequest+ try { req = indexedDB.open(DB, 1) } catch { return resolve(null) }+ req.onupgradeneeded = () => {+ const d = req.result+ if (!d.objectStoreNames.contains(STORE)) d.createObjectStore(STORE)+ }+ req.onsuccess = () => resolve(req.result)+ req.onerror = () => resolve(null)+ })+ return dbP+}++export async function cacheGet(key: string): Promise<Uint8Array | null> {+ const d = await db()+ if (!d) return null+ return new Promise((resolve) => {+ try {+ const r = d.transaction(STORE, 'readonly').objectStore(STORE).get(key)+ r.onsuccess = () => resolve(r.result ? new Uint8Array(r.result as ArrayBuffer) : null)+ r.onerror = () => resolve(null)+ } catch { resolve(null) }+ })+}++export async function cachePut(key: string, bytes: Uint8Array): Promise<void> {+ const d = await db()+ if (!d) return+ try {+ // store the ArrayBuffer, not the view — structured clone keeps it compact+ d.transaction(STORE, 'readwrite').objectStore(STORE).put(bytes.slice().buffer, key)+ } catch { /* cache is best effort */ }+}++// --- transport ---------------------------------------------------------------++export interface BlobEndpoint {+ /** relay origin, e.g. https://sync.bento.page */+ base: string+ room: string+ tok: string+}++const url = (e: BlobEndpoint, key: string) =>+ `${e.base.replace(/\/$/, '')}/b/${encodeURIComponent(e.room)}/${encodeURIComponent(key)}?tok=${encodeURIComponent(e.tok)}`++export type PutResult =+ | { ok: true; key: string; deduped: boolean }+ | { ok: false; reason: 'too-large' | 'unsupported' | 'network' | 'forbidden' | 'room-full' }++/**+ * Encrypt and upload. Returns the key to put in the op. Dedupe is a HEAD+ * first: content addressing means an identical asset already uploaded by a+ * peer needs no second upload.+ *+ * 'unsupported' means the relay has no blob storage configured (501) — the+ * caller should fall back to inlining, NOT treat it as an error.+ */+export async function putBlob(e: BlobEndpoint, rawRoomKey: Uint8Array, bytes: Uint8Array): Promise<PutResult> {+ if (encodedSize(bytes.length) > MAX_BLOB) return { ok: false, reason: 'too-large' }+ const key = await blobKey(rawRoomKey, bytes)+ try {+ const head = await netFetch(url(e, key), { method: 'HEAD' })+ if (head.status === 200) {+ void cachePut(key, bytes)+ return { ok: true, key, deduped: true }+ }+ if (head.status === 501) return { ok: false, reason: 'unsupported' }+ if (head.status === 403) return { ok: false, reason: 'forbidden' }+ const body = await encodeBlob(rawRoomKey, bytes)+ const res = await netFetch(url(e, key), {+ method: 'PUT', body: body as BodyInit,+ headers: { 'content-type': 'application/octet-stream' },+ })+ if (res.status === 501) return { ok: false, reason: 'unsupported' }+ if (res.status === 403) return { ok: false, reason: 'forbidden' }+ if (res.status === 413) return { ok: false, reason: 'too-large' }+ // 507: the room's total blob quota is exhausted. Permanent for this room+ // until it expires — the caller must not retry in a loop.+ if (res.status === 507) return { ok: false, reason: 'room-full' }+ if (!res.ok) return { ok: false, reason: 'network' }+ void cachePut(key, bytes)+ return { ok: true, key, deduped: false }+ } catch {+ return { ok: false, reason: 'network' }+ }+}++/** Does `plain` actually hash to the address we asked for? One SHA-256 plus+ * one HMAC over bytes we have just decrypted anyway — negligible beside the+ * AES-GCM pass that produced them, and it runs once per fetch, not per use+ * (the cache is keyed by the same address). */+async function addressMatches(rawRoomKey: Uint8Array, key: string, plain: Uint8Array): Promise<boolean> {+ return (await blobKey(rawRoomKey, plain)) === key+}++/** Fetch and decrypt, cache-first. Null means "not available right now" —+ * callers render a placeholder rather than a broken image, and may retry.+ * A blob that fails its content-address check reads as unavailable too: a+ * placeholder is recoverable, the wrong picture is not. */+export async function getBlob(e: BlobEndpoint, rawRoomKey: Uint8Array, key: string): Promise<Uint8Array | null> {+ const hit = await cacheGet(key)+ try {+ // The hit is checked as well, so a cache written before this verification+ // existed (or edited under us in IndexedDB) heals: falling through re-fetches+ // and cachePut, keyed by the address, overwrites the bad entry.+ // INSIDE the try like the post-fetch check below: addressMatches can throw+ // (measured — crypto.subtle.importKey('raw', new Uint8Array(0), HMAC) rejects+ // with DataError on an empty room key), and the contract above promises null,+ // not a rejection. session.resolveBlobs has try/finally and no catch, so a+ // throw here escapes as an unhandled rejection.+ if (hit && await addressMatches(rawRoomKey, key, hit)) return hit+ const res = await netFetch(url(e, key))+ if (!res.ok) return null+ const enc = new Uint8Array(await res.arrayBuffer())+ const plain = await decodeBlob(rawRoomKey, enc)+ if (!plain) return null+ // GCM proves someone holding the room key sealed these bytes. It does NOT+ // prove they are the bytes this address names, and nothing else here did:+ // the relay is free to answer address A with the room's blob B, and every+ // check above passes. The picture silently becomes a different picture and+ // cachePut writes the swap to disk permanently. The address is the only+ // binding between reference and content, so verify it before both.+ if (!await addressMatches(rawRoomKey, key, plain)) return null+ void cachePut(key, plain)+ return plain+ } catch {+ return null+ }+}diff --git a/kernel/src/sync/crdt.ts b/kernel/src/sync/crdt.tsindex 3b31ef70..92742b87 100644--- a/kernel/src/sync/crdt.ts+++ b/kernel/src/sync/crdt.ts@@ -78,8 +78,27 @@ type SlideElement = { id: string }export interface DocShape {/** doc-level key holding the PARENT array: 'slides' | 'pages' */readonly parents: string- /** parent-level key holding the CHILD array: 'elements' | 'blocks' */- readonly children: string+ /**+ * Parent-level key holding the CHILD array: 'elements' | 'blocks' — or+ * `null` for a FLAT document, one level deep.+ *+ * bento/type is flat: a block IS the paragraph, so there is nothing beneath+ * it. Rather than make such an app invent an empty child array on every+ * node, the engine treats a childless shape as having no element layer at+ * all — `C()` reads as empty and the differ therefore never mints an element+ * op. See the guard in `applyEffect` for the receiving side.+ */+ readonly children: string | null+ /**+ * The property carrying collaboratively-edited TEXT, which gets the token+ * RGA rather than a last-writer-wins register.+ *+ * Named rather than hard-coded because it is the one property whose merge+ * behaviour decides whether two people can type in the same paragraph at+ * once. It was `'html'` in both existing apps, so the default keeps every+ * shipped file byte-identical; an app whose text lives elsewhere says so.+ */+ readonly text: string/*** Doc-level keys the differ never syncs.*@@ -92,20 +111,47 @@ export interface DocShape {* an assertion instead.*/readonly skipDoc: ReadonlySet<string>+ /**+ * Doc-level keys that are MAPS, merged per key rather than as one value.+ *+ * `assets` and `blobs` were hard-coded for this, with the right reason+ * attached: two people adding different assets concurrently must both keep+ * theirs. Any id-keyed map wants the same treatment, and an app has no way+ * to ask for it while the names are baked in — bento/type's `footnotes` is+ * one (note id → note text), and as a whole-value register it loses a note+ * BODY while both references survive, leaving a marker pointing at nothing.+ */+ readonly maps: ReadonlySet<string>}/** Derived, never authored: the volatile set is the same for every app apart* from the container name, so writing it out twice invites them to drift. */-export const shape = (parents: string, children: string): DocShape => {+export const shape = (+ parents: string,+ children: string | null,+ text = 'html',+ maps: readonly string[] = [],+): DocShape => {const skipDoc = new Set([parents, 'modified', 'collab', 'format', 'version'])- return { parents, children, skipDoc }+ // `assets` and `blobs` are per-key for every app and always have been —+ // unioned rather than defaulted so an app naming its own map cannot drop them.+ return { parents, children, text, skipDoc, maps: new Set(['assets', 'blobs', ...maps]) }}/** The parent array of a document, and the child array of a parent. Indexed* access through the descriptor: `d['slides']` is the same lookup `d.slides`* was, so these are byte-neutral by construction. */const P = (S: DocShape, d: BentoDoc): Slide[] => (d as unknown as Record<string, Slide[]>)[S.parents]-const C = (S: DocShape, p: Slide): SlideElement[] => (p as unknown as Record<string, SlideElement[]>)[S.children]+/**+ * A parent's children — empty, and FROZEN, when the shape is flat.+ *+ * Frozen on purpose: every mutating call site is supposed to be unreachable+ * without an element layer, and a throw says so at once. Silently swallowing a+ * push is how a replica ends up quietly missing content.+ */+const NO_CHILDREN: SlideElement[] = Object.freeze([]) as unknown as SlideElement[]+const C = (S: DocShape, p: Slide): SlideElement[] =>+ S.children === null ? NO_CHILDREN : (p as unknown as Record<string, SlideElement[]>)[S.children]/*** …and the write-back form for the child array.*@@ -114,7 +160,54 @@ const C = (S: DocShape, p: Slide): SlideElement[] => (p as unknown as Record<str* future edit that reassigns it would be replacing the array the caller's* document still points at.*/-const setC = (S: DocShape, p: Slide, v: SlideElement[]): void => { (p as unknown as Record<string, SlideElement[]>)[S.children] = v }+const setC = (S: DocShape, p: Slide, v: SlideElement[]): void => {+ if (S.children === null) return // a flat document has no child array to write+ ;(p as unknown as Record<string, SlideElement[]>)[S.children] = v+}++/**+ * Collaboration credentials, as they live in the file.+ *+ * PLATFORM-level, not app-level (§2): every Bento document carries `docId` and+ * may carry `collab`, and the relay, the invite chain and the fork-merge all+ * work purely in these terms. The shape is documented at length in+ * bento/slides' model.ts, which is where it was written, and in+ * docs/collab-design.md.+ */+export interface CollabCreds {+ room: string+ key: string+ on?: boolean+ sync?: SyncStateJSON+ writerPub?: string+ writerPriv?: string+ role?: 'writer' | 'reader'+ v?: number+ owner?: string+ ownerPriv?: string+ invite?: { pub: string; priv: string; role: 'writer' | 'commenter'; exp?: number; sig: string }+}++/** A blob the document references but does not inline. */+export interface BlobRef { key: string; mime: string; size: number }++/**+ * The document, as the SESSION needs to see it.+ *+ * crdt.ts keeps `SyncDoc` deliberately opaque (`object`) because the ENGINE+ * genuinely does not care what is in a document — it is told the shape. The+ * session is a different layer and does care about a few fields, but only the+ * ones PLATFORM §2 guarantees EVERY Bento document has, so each app's own+ * document type already satisfies it structurally — no conversion, and no+ * index signature, which would have forced every app to declare one.+ */+export interface SyncDoc {+ docId: string+ collab?: CollabCreds+ assets?: Record<string, string>+ blobs?: Record<string, BlobRef>+ modified?: string+}export const DOC_NODE = '@doc'@@ -256,7 +349,11 @@ export interface OrdOp extends OpBase {/** M3 — text RGA delta for one element's html. */export interface TxtOp extends OpBase {op: 'txt'- /** composite element key */+ /**+ * The node the text lives on: a composite element key, or a bare parent id+ * for an app whose text sits on the parent (bento/type's blocks). The field+ * keeps its name because it is on the wire in every shipped file.+ */el: string/** seed reference: (l,a) of the RGA base this delta applies to */sd: Reg@@ -378,6 +475,18 @@ export class SyncEngine {readonly S: DocShapeconstructor(actor: string, shape: DocShape) {+ // A hand-built DocShape that omits `text` disables the token RGA SILENTLY:+ // every property comparison against `undefined` fails, so collaborative+ // text quietly degrades to last-writer-wins and two people typing in one+ // paragraph destroy each other's work. Measured — a literal missing this+ // field turned four passing checks red with no other symptom. Build shapes+ // with `shape()`; if you must hand-build one, this says so immediately.+ if (!shape.text) throw new Error('DocShape.text is required — build it with shape()')+ // Same reasoning for `maps`, which arrived later: a literal without it+ // does not degrade quietly, it throws deep inside the differ on the first+ // doc-property diff. Failing here names the actual cause.+ if (!shape.maps) throw new Error('DocShape.maps is required — build it with shape()')+this.actor = actorthis.S = shape}@@ -496,7 +605,7 @@ export class SyncEngine {if (SKIP_DOC.has(k)) continue// `assets` and `blobs` are per-KEY registers, not whole-map ones, so two// people adding different assets concurrently both keep theirs.- if (k === 'assets' || k === 'blobs') {+ if (this.S.maps.has(k)) {const ba = (b[k] ?? {}) as Record<string, unknown>const aa = (a[k] ?? {}) as Record<string, unknown>for (const ak of new Set([...Object.keys(ba), ...Object.keys(aa)])) {@@ -571,8 +680,20 @@ export class SyncEngine {for (const k of new Set([...Object.keys(bp), ...Object.keys(ap)])) {if (k === this.S.children || k === 'id') continueif (JSON.stringify(bp[k]) === JSON.stringify(ap[k])) continue+ // Text on a PARENT gets the same token RGA as text on a child. An app+ // whose text lives one level up (bento/type: a block IS the paragraph)+ // would otherwise get a last-writer-wins register here, and two people+ // typing in one paragraph would silently destroy each other's work.+ if (k === this.S.text && opts.text && typeof bp[k] === 'string' && typeof ap[k] === 'string') {+ const t = this.diffText(id, bp[k] as string, ap[k] as string)+ if (t) {+ push(t)+ continue+ }+ }const o = push<SetOp>({ ...this.stamp(), op: 'set', sl: id, k, v: clone(ap[k]) })this.regs[`${id} ${k}`] = [o.l, o.a]+ if (k === this.S.text) delete this.txt[id] // LWW reset wins over RGA state}}// slide order: minimal ord ops (keep the longest already-ordered run).@@ -609,8 +730,8 @@ export class SyncEngine {for (const k of new Set([...Object.keys(bp), ...Object.keys(ap)])) {if (k === 'id') continueif (JSON.stringify(bp[k]) === JSON.stringify(ap[k])) continue- if (k === 'html' && opts.text && typeof bp.html === 'string' && typeof ap.html === 'string') {- const t = this.diffText(id, bp.html as string, ap.html as string)+ if (k === this.S.text && opts.text && typeof bp[this.S.text] === 'string' && typeof ap[this.S.text] === 'string') {+ const t = this.diffText(id, bp[this.S.text] as string, ap[this.S.text] as string)if (t) {push(t)continue@@ -618,7 +739,7 @@ export class SyncEngine {}const o = push<SetOp>({ ...this.stamp(), op: 'set', sl, el: id, k, v: clone(ap[k]) })this.regs[`${id} ${k}`] = [o.l, o.a]- if (k === 'html') delete this.txt[id] // LWW reset wins over RGA state+ if (k === this.S.text) delete this.txt[id] // LWW reset wins over RGA state}}// no cross-slide move branch: the composite key IS (slide, id), so a@@ -721,7 +842,7 @@ export class SyncEngine {// seed, so both their edits merge; after a set-html reset or a node// rebirth the lamport has grown, so fresh seeds out-rank stale ones.const sd: Reg = [- Math.max(this.regs[`${el} html`]?.[0] ?? 0, this.births[el]?.[0] ?? 0),+ Math.max(this.regs[`${el} ${this.S.text}`]?.[0] ?? 0, this.births[el]?.[0] ?? 0),contentHash(oldHtml),]st = this.txt[el] = { sd, toks: seedTokens(sd, oldHtml) }@@ -796,6 +917,24 @@ export class SyncEngine {}private applyEffect(doc: BentoDoc, op: Op, res: ApplyResult) {+ // A FLAT document has no element layer, so an element-scoped op has+ // nowhere to land. It should never arrive — peers in a room share a shape+ // — but the frame came off the wire, and materializing it would either+ // throw against the frozen child array or invent a key the format does not+ // have. Dropping is the only safe reading, and the version vector still+ // advanced in applyOne, so delivery does not stall behind it.+ const scope = op as Partial<{ el: string; kind: string; id: string }>+ // `el` does NOT mean "element" on a txt op — there it is the NODE key,+ // which for a flat document is the block's own id. Reading it as an+ // element key here dropped every collaborative keystroke type would ever+ // send, while structure ops kept converging: the rig saw one author's+ // edits land and the other's silently vanish.+ const elementScoped = scope.kind === 'element' ||+ (op.op === 'txt' ? String(scope.el).includes(SEP) : scope.el !== undefined)+ if (this.S.children === null && elementScoped) {+ dbg(scope.el ?? scope.id ?? '?', `${op.op} DROP no element layer in this shape`)+ return+ }switch (op.op) {case 'set':this.applySet(doc, op, res)@@ -826,6 +965,28 @@ export class SyncEngine {return (s ? C(this.S, s) : undefined)?.find((e) => e.id === bare) ?? this.limbo[key]}+ /**+ * Split a doc-level property key into (map, entry) if it addresses a+ * declared map — `assets.logo` → ['assets','logo'].+ *+ * Matched against the SHAPE rather than by looking for a dot: an ordinary+ * property whose name happens to contain one must not be mistaken for a map+ * entry and quietly written into a sub-object.+ */+ private mapKey(k: string): [string, string] | undefined {+ const i = k.indexOf('.')+ if (i <= 0) return undefined+ const field = k.slice(0, i)+ return this.S.maps.has(field) ? [field, k.slice(i + 1)] : undefined+ }++ /** either level: composite keys carry SEP, parent ids never do */+ private findNode(doc: BentoDoc, id: string): Record<string, unknown> | undefined {+ return (id.includes(SEP) ? this.findEl(doc, id) : this.findSlide(doc, id)) as+ | Record<string, unknown>+ | undefined+ }+private applySet(doc: BentoDoc, op: SetOp, res: ApplyResult) {const nodeId = op.el ?? op.sl ?? DOC_NODEconst rk = `${nodeId} ${op.k}`@@ -850,11 +1011,10 @@ export class SyncEngine {}if (nodeId === DOC_NODE) {this.regs[rk] = [op.l, op.a]- if (op.k.startsWith('assets.') || op.k.startsWith('blobs.')) {- const isBlob = op.k.startsWith('blobs.')- const field = isBlob ? 'blobs' : 'assets'+ const dot = this.mapKey(op.k)+ if (dot) {+ const [field, ak] = dotconst map = ((doc as unknown as Record<string, Record<string, unknown>>)[field] ??= {})- const ak = op.k.slice(field.length + 1)if (op.v === undefined) delete map[ak]else map[ak] = clone(op.v)} else {@@ -878,15 +1038,15 @@ export class SyncEngine {// JSON.stringify(undefined) is undefined — String() keeps this debug// line from throwing on every property REMOVAL.dbg(nodeId, `set ${op.k}@${op.l},${op.a} APPLY ${String(JSON.stringify(op.v)).slice(0, 40)}`)- if (op.el && op.k === 'html') {- const gen = this.txt[op.el]+ if (nodeId !== DOC_NODE && op.k === this.S.text) {+ const gen = this.txt[nodeId]if (gen && cmpReg([op.l, op.a], gen.sd) < 0) {// a live text generation outranks this set — value loses, reg advancesthis.regs[rk] = [op.l, op.a]return}- dbg(op.el, `set-html@${op.l},${op.a} RESET kills gen`)- delete this.txt[op.el] // the set out-stamps the generation: reset+ dbg(nodeId, `set-text@${op.l},${op.a} RESET kills gen`)+ delete this.txt[nodeId] // the set out-stamps the generation: reset}this.regs[rk] = [op.l, op.a]if (op.v === undefined) delete target[op.k]@@ -928,7 +1088,7 @@ export class SyncEngine {if (this.dead(id)) return // a delete still out-stamps this insertconst existing = this.findSlide(doc, id)if (existing) {- this.assignNode(existing as unknown as Record<string, unknown>, src as unknown as Record<string, unknown>, id, stamp, ['id', this.S.children])+ this.assignNode(existing as unknown as Record<string, unknown>, src as unknown as Record<string, unknown>, id, stamp, this.S.children === null ? ['id'] : ['id', this.S.children])} else {const sl = clone(src)setC(this.S, sl, []) // members materialize separately via insertElement@@ -971,7 +1131,7 @@ export class SyncEngine {// a text generation that survived the node's death (it out-ranked the// tomb) is the html authority — re-materialize over the ins payloadconst g = this.txt[id]- if (g && 'html' in live) (live as unknown as { html: string }).html = materialize(g)+ if (g && this.S.text in live) (live as unknown as Record<string, string>)[this.S.text] = materialize(g)}/**@@ -984,7 +1144,7 @@ export class SyncEngine {private assignNode(node: Record<string, unknown>, payload: Record<string, unknown>, id: string, birth: Reg, skip: string[]) {for (const k of new Set([...Object.keys(node), ...Object.keys(payload)])) {if (skip.includes(k)) continue- if (k === 'html' && this.txt[id]) {+ if (k === this.S.text && this.txt[id]) {if (this.txt[id].sd[0] < birth[0]) {// the RGA's seed predates this rebirth — void it; the assignment// wins even over higher-lamport deltas (they drop on every replica)@@ -1054,7 +1214,7 @@ export class SyncEngine {dbg(id, `stash-replay ${k} := ${String(JSON.stringify(ent.v)).slice(0, 40)}`)if ('v' in ent) node[k] = clone(ent.v)else delete node[k]- if (k === 'html') delete this.txt[id]+ if (k === this.S.text) delete this.txt[id]}delete this.stash[id]}@@ -1148,7 +1308,7 @@ export class SyncEngine {dbg(op.el, `txt@${op.l},${op.a} DROP birth ${JSON.stringify(birth)} > sd ${op.sd[0]}`)return}- const rr = this.regs[`${op.el} html`]+ const rr = this.regs[`${op.el} ${this.S.text}`]if (rr && cmpReg(op.sd, rr) < 0) {dbg(op.el, `txt@${op.l},${op.a} DROP reg ${JSON.stringify(rr)}`)return@@ -1167,8 +1327,8 @@ export class SyncEngine {if (op.base === undefined) {// seeds are deterministic (lamport + content hash): if our current// html IS the seed's base we can rebuild it without the base op- const node = this.findEl(doc, op.el)- const html = node && 'html' in node ? ((node as unknown as { html: string }).html as string) : undefined+ const node = this.findNode(doc, op.el)+ const html = node && this.S.text in node ? ((node as unknown as Record<string, string>)[this.S.text] as string) : undefinedif (html !== undefined && contentHash(html) === op.sd[1]) {dbg(op.el, `txt@${op.l},${op.a} RECONSTRUCT from html`)st = this.txt[op.el] = { sd: clone(op.sd), toks: seedTokens(op.sd, html) }@@ -1193,9 +1353,9 @@ export class SyncEngine {return}const advanced = applyTxtToState(st!, op)- const el = this.findEl(doc, op.el)- if (el && 'html' in el) {- ;(el as unknown as { html: string }).html = materialize(st!)+ const el = this.findNode(doc, op.el)+ if (el && this.S.text in el) {+ ;(el as unknown as Record<string, string>)[this.S.text] = materialize(st!)res.changed = true} else if (!el) {;(this.pending[op.el] ??= []).push(op)@@ -1371,7 +1531,7 @@ export class SyncEngine {const dst = lNode(id)if (!src || !dst) continueconst isSlide = rSlides.has(id) || !!this.findSlide(doc, id)- this.assignNode(dst, src, id, this.births[id], isSlide ? ['id', this.S.children] : ['id'])+ this.assignNode(dst, src, id, this.births[id], isSlide ? this.S.children === null ? ['id'] : ['id', this.S.children] : ['id'])res.changed = trueif (isSlide) res.structure = true}@@ -1397,14 +1557,14 @@ export class SyncEngine {const src = rNode(nodeId)const dst = lNode(nodeId)if (!src || !dst) continue- if (key === 'html') {+ if (key === this.S.text) {const gen = this.txt[nodeId]if (gen && cmpReg(rr, gen.sd) < 0) continue // generation outranks the setif (gen) delete this.txt[nodeId]}- if (nodeId === DOC_NODE && (key.startsWith('assets.') || key.startsWith('blobs.'))) {- const field = key.startsWith('blobs.') ? 'blobs' : 'assets'- const ak = key.slice(field.length + 1)+ const mk = nodeId === DOC_NODE ? this.mapKey(key) : undefined+ if (mk) {+ const [field, ak] = mkconst rm = ((rdoc as unknown as Record<string, Record<string, unknown>>)[field] ?? {})const lm = ((doc as unknown as Record<string, Record<string, unknown>>)[field] ??= {})if (rm[ak] === undefined) delete lm[ak]@@ -1417,7 +1577,7 @@ export class SyncEngine {// text RGA union (generations void when out-ranked by births or sets)for (const el of Object.keys(this.txt)) {const b = this.births[el]- const rr = this.regs[`${el} html`]+ const rr = this.regs[`${el} ${this.S.text}`]if ((b && this.txt[el].sd[0] < b[0]) || (rr && cmpReg(this.txt[el].sd, rr) < 0))delete this.txt[el]}@@ -1425,15 +1585,15 @@ export class SyncEngine {if (this.dead(el)) continueconst b = this.births[el]if (b && rt.sd[0] < b[0]) continue- const rr = this.regs[`${el} html`]+ const rr = this.regs[`${el} ${this.S.text}`]if (rr && cmpReg(rt.sd, rr) < 0) continueconst lt = this.txt[el]const c = lt ? cmpReg(rt.sd, lt.sd) : 1if (c > 0) this.txt[el] = clone(rt)else if (c === 0) mergeToks(lt!, rt)else continue- const node = this.findEl(doc, el)- if (node && 'html' in node) (node as unknown as { html: string }).html = materialize(this.txt[el])+ const node = this.findNode(doc, el)+ if (node && this.S.text in node) (node as unknown as Record<string, string>)[this.S.text] = materialize(this.txt[el])res.changed = true}if (res.structure) this.rematerialize(doc)diff --git a/kernel/src/sync/online.ts b/kernel/src/sync/online.tsnew file mode 100644index 00000000..d8fbfbab--- /dev/null+++ b/kernel/src/sync/online.ts@@ -0,0 +1,735 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento-sync online transport — E2EE WebSocket to the blind relay+// (server/sync-worker). Every session frame is AES-GCM encrypted with the+// room key from doc.collab.key; the relay sees ciphertext, fan-out routing,+// and nothing else. Auth is possession-proof: ?tok= is a hash of the key.+//+// Reconnects with backoff; frames queue while disconnected; op frames are+// persisted server-side (envelope {p:1}) and replayed to joiners from their+// last acked seq, with client-produced encrypted snapshots capping replay+// length. See docs/collab-design.md.++import type { Op, SyncStateJSON } from './crdt.ts'+import type { Frame, HostStore, RefusalCode, SyncDoc, SyncSession, Transport } from './session.ts'+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'++/** the app's store, structurally — see session.ts HostStore */+type Store = HostStore++export const DEFAULT_SYNC_HOST = 'wss://sync.bento.page'+const SNAP_EVERY = 200 // ops between encrypted snapshot uploads++const b64u = {+ enc(bytes: Uint8Array): string {+ let s = ''+ for (const b of bytes) s += String.fromCharCode(b)+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')+ },+ dec(s: string): Uint8Array {+ const b = atob(s.replace(/-/g, '+').replace(/_/g, '/'))+ const out = new Uint8Array(b.length)+ for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i)+ return out+ },+}++export function mintRoomKey(): string {+ const bytes = new Uint8Array(32)+ crypto.getRandomValues(bytes)+ return b64u.enc(bytes)+}++const EC = { name: 'ECDSA', namedCurve: 'P-256' } as const+const SIGN_ALG = { name: 'ECDSA', hash: 'SHA-256' } as const++/** Import a writer private key (PKCS#8, base64url) for signing op frames. */+export async function importSignKey(privB64: string): Promise<CryptoKey> {+ return crypto.subtle.importKey('pkcs8', b64u.dec(privB64) as BufferSource, EC, false, ['sign'])+}++/** ECDSA-P256/SHA-256 signature over `${i}.${d}`, base64url. */+export async function signFrame(key: CryptoKey, i: string, d: string): Promise<string> {+ const sig = await crypto.subtle.sign(SIGN_ALG, key, new TextEncoder().encode(`${i}.${d}`))+ return b64u.enc(new Uint8Array(sig))+}++/** Sign an arbitrary string with a b64url PKCS#8 private key (cert chains). */+export async function signText(privB64: string, text: string): Promise<string> {+ const key = await importSignKey(privB64)+ const sig = await crypto.subtle.sign(SIGN_ALG, key, new TextEncoder().encode(text))+ return b64u.enc(new Uint8Array(sig))+}++async function mintKeypair(): Promise<{ pub: string; priv: string }> {+ const kp = (await crypto.subtle.generateKey(EC, true, ['sign', 'verify'])) as CryptoKeyPair+ return {+ pub: b64u.enc(new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey))),+ priv: b64u.enc(new Uint8Array(await crypto.subtle.exportKey('pkcs8', kp.privateKey))),+ }+}++export type CollabInvite = { pub: string; priv: string; role: 'writer' | 'commenter'; exp?: number; sig: string }++/** Owner-signed invite: a delegation keypair whose private half rides in the+ * shared copy. Chain: owner signs `inv.${pub}.${role}.${exp||0}`; a joining+ * device later signs its own pubkey with the invite key (`dlg.${memberPub}`).+ * The relay verifies both signatures and never sees private material — so a+ * blind relay still cannot certify its own key. */+export async function mintInvite(ownerPrivB64: string, role: 'writer' | 'commenter' = 'writer', exp = 0): Promise<CollabInvite> {+ const kp = await mintKeypair()+ const sig = await signText(ownerPrivB64, `inv.${kp.pub}.${role}.${exp}`)+ return { pub: kp.pub, priv: kp.priv, role, ...(exp ? { exp } : {}), sig }+}++/** This device's member identity for a doc — minted once, kept in localStorage,+ * NEVER in the file (the file travels; a device key must not). */+export async function deviceIdentity(docId: string): Promise<{ pub: string; priv: string }> {+ const k = `bento-member-${docId}`+ try {+ const saved = lsGet(k)+ if (saved) return JSON.parse(saved)+ } catch { /* storage unavailable → ephemeral identity */ }+ const id = await mintKeypair()+ lsSet(k, JSON.stringify(id))+ return id+}++/** Auth material for the relay connection. Exactly one shape applies:+ * direct (owner or legacy shared-writer key) or chain (member via invite). */+export type AuthSpec =+ | { kind: 'direct'; pub: string; priv?: string }+ | { kind: 'chain'; owner: string; invite: CollabInvite; docId: string }++export type CollabCreds = {+ room: string+ key: string+ on: boolean+ v: number+ owner: string+ ownerPriv: string+ role: 'writer'+}++/**+ * Fresh collaboration credentials, minted at DOCUMENT CREATION and LIVE by+ * default (on:true): the moment identity and keys exist, any copy of the+ * file joins the same room — "send first" needs no ceremony. "Stop sharing"+ * in the Live popover turns it off; Offline mode hard-blocks regardless.+ *+ * Signed-writes scheme (v0.9.18+): the room id is the COMMITMENT to a fresh+ * ECDSA writer pubkey — `w` + base64url(SHA-256(writerPubRaw)) — so the relay+ * can pin the writer key trustlessly (a viewer holds the room id but can't+ * substitute their own key). `key` is the separate symmetric READ capability.+ * Async because keypair generation is. See docs/collab-design.md.+ */+export async function mintCollab(): Promise<CollabCreds> {+ // v2 (fine-grained): the room id commits to the OWNER's pubkey. The creator's+ // copy holds ownerPriv; shared copies carry owner-signed INVITES instead, and+ // each joining device mints its own member key (see mintInvite/deviceIdentity).+ const kp = await mintKeypair()+ const commit = new Uint8Array(await crypto.subtle.digest('SHA-256', b64u.dec(kp.pub) as BufferSource))+ return {+ room: `${syncHost()}/d/w${b64u.enc(commit)}`,+ key: mintRoomKey(),+ on: true,+ v: 2,+ owner: kp.pub,+ ownerPriv: kp.priv,+ role: 'writer',+ }+}++/** dev override for the relay host (e.g. ws://localhost:8787) */+export function syncHost(): string {+ try {+ return lsGet('bento-sync-url') || DEFAULT_SYNC_HOST+ } catch {+ return DEFAULT_SYNC_HOST+ }+}++export type OnlineStatus = 'connecting' | 'open' | 'closed'++/** A frame written to (or parked for) the relay. `ops` is set for persisted op+ * batches — the only frames the relay acks, and the only ones whose refusal+ * has to reach the session (an unsendable op must leave the resend log). */+type Outbound = { id: string; text: string; ops: Op[] | null; bytes: number; tries: number }++let frameSeq = 0+/** Short opaque per-frame id. Emitted FIRST in the envelope so the relay can+ * recover it with a bounded regex from an OVERSIZE frame — one it refuses+ * before parsing, since parsing an attacker-sized string is a CPU abuse+ * vector. Relay contract: docs/relay-design.md. */+const nextFrameId = (): string => `f${(++frameSeq).toString(36)}${Math.random().toString(36).slice(2, 6)}`++/** `{ctl:'refused'}` from the relay. Modern relays echo our frame id (`k`),+ * which is exact; older ones don't, and then the sizes are the only evidence+ * of WHICH frame it names (see matchRefused). */+type RefusedEnv = {+ code?: string+ /** our frame id, echoed back — authoritative when present */+ k?: string+ /** too-large: the relay's ceiling and the frame length it measured */+ max?: number+ got?: number+ /** storage-failed: i.length + d.length of the frame it tried to store */+ bytes?: number+ /** rate-limited: how long until the socket's byte window rolls over */+ retryInMs?: number+}++export class OnlineTransport implements Transport {+ readonly kind = 'online'+ status: OnlineStatus = 'connecting'+ onStatus: ((s: OnlineStatus) => void) | null = null+ private ws: WebSocket | null = null+ private key: CryptoKey | null = null+ /** writer signing key — null for readers (they can decrypt but not author). */+ private signKey: CryptoKey | null = null+ private queue: Outbound[] = []+ /** persisted frames written but not yet acked. The relay handles one+ * socket's frames in order and acks every stored one, so the head of this+ * list is the frame a `refused` reply is talking about. Purely a+ * correlation window — delivery is still guaranteed by the log + `need`. */+ private awaitingAck: Outbound[] = []+ /** rate-limit backoff deadline: sending into a refusing relay only burns the+ * next window too, so frames park until it passes */+ private paused = false+ private pauseTimer: ReturnType<typeof setTimeout> | null = null+ private lastLimitNotice = 0+ private static readonly ACK_WINDOW = 64+ private static readonly MAX_RETRIES = 4+ private closed = false+ private backoff = 800+ private url = ''+ // heartbeat: ping the relay (which auto-responds "pong" without waking the DO)+ // so idle connections stay alive; if a pong doesn't come back before the next+ // tick, treat the socket as dead and reconnect instead of waiting for a TCP+ // timeout that can take minutes.+ private pingTimer: ReturnType<typeof setInterval> | null = null+ private awaitingPong = false+ private static readonly PING_MS = 25_000+ /** the key THIS socket signs with (owner / legacy writer / device) — used to+ * recognise our own revocation and to attribute presence */+ myPub: string | null = null+ /**+ * Replay bookmark — MEMORY ONLY, deliberately: it is valid only alongside+ * the in-memory CRDT state it was earned with. A fresh join replays from+ * the room's snapshot (or 0); reconnects of THIS session resume from here.+ */+ private seq = 0++ constructor(+ room: string,+ private keyB64: string,+ docId: string,+ private onFrame: (f: Frame) => void,+ private hooks: {+ onSnap: (doc: SyncDoc, state: SyncStateJSON) => void+ getSnapshot: () => { doc: SyncDoc; state: SyncStateJSON }+ onOpen: () => void+ /** replay done: (actor,seq) pairs the room holds; return true to upload a snapshot */+ onReady: (seen: Set<string>, seq: number) => boolean+ /** the relay refused a frame; `ops` are the ones it will never accept+ * (null when the refusal couldn't be pinned to a frame we sent) */+ onRefused?: (code: RefusalCode, ops: Op[] | null) => void+ },+ private auth?: AuthSpec,+ ) {+ this.docId = docId+ this.init(room)+ }++ private docId = ''++ /** (actor,seq) pairs seen in the current connection's replay */+ private replaySeen = new Set<string>()++ /** Credentials the blob layer needs: the relay origin, the room name, the+ * possession-proof token, and the raw room key it encrypts blobs with.+ * Null until init() has derived the token. */+ blobCreds(): { base: string; room: string; tok: string; rawKey: Uint8Array } | null {+ if (!this.roomName || !this.tokValue) return null+ return { base: this.originValue, room: this.roomName, tok: this.tokValue, rawKey: b64u.dec(this.keyB64) }+ }+ private roomName = ''+ private tokValue = ''+ private originValue = ''++ private async init(room: string) {+ const raw = b64u.dec(this.keyB64)+ this.key = await crypto.subtle.importKey('raw', raw as BufferSource, 'AES-GCM', false, [+ 'encrypt',+ 'decrypt',+ ])+ const tokDigest = new Uint8Array(await crypto.subtle.digest('SHA-256', raw as BufferSource))+ const tok = b64u.enc(tokDigest.slice(0, 18))+ // Blob endpoints live on the same origin as the socket and use the same+ // room + token, so derive them here rather than duplicating the rule.+ try {+ const u = new URL(room.replace(/^ws/, 'http'))+ this.originValue = u.origin+ this.roomName = u.pathname.replace(/^\/d\//, '')+ this.tokValue = tok+ } catch { /* malformed room url — blobs simply stay unavailable */ }+ // Writers sign op frames; readers omit auth and the relay drops their+ // writes. Two writer shapes: DIRECT (the presented `w` key hash-matches the+ // room commitment — the owner, or a legacy shared-writer copy) and CHAIN+ // (a member: `w` = this device's key, plus the owner-signed invite and the+ // invite-signed delegation of the device key — verified by the relay).+ const a = this.auth+ if (a?.kind === 'direct') {+ if (a.priv) { try { this.signKey = await importSignKey(a.priv) } catch { this.signKey = null } }+ this.myPub = a.pub+ this.url = `${room}?tok=${tok}&w=${a.pub}`+ } else if (a?.kind === 'chain') {+ const id = await deviceIdentity(this.docId)+ try { this.signKey = await importSignKey(id.priv) } catch { this.signKey = null }+ this.myPub = id.pub+ const iv = a.invite+ const dg = await signText(iv.priv, `dlg.${id.pub}`)+ this.url = `${room}?tok=${tok}&w=${id.pub}&o=${a.owner}` ++ `&ivp=${iv.pub}&ivr=${iv.role}&ive=${iv.exp ?? 0}&ivs=${iv.sig}&dg=${dg}`+ } else {+ this.url = `${room}?tok=${tok}`+ }+ this.connect()+ }++ private lastSeq(): number {+ return this.seq+ }++ private saveSeq(q: number) {+ if (q > this.seq) this.seq = q+ }++ private setStatus(s: OnlineStatus) {+ this.status = s+ this.onStatus?.(s)+ }++ private connect() {+ if (this.closed) return+ this.setStatus('connecting')+ let ws: WebSocket+ try {+ ws = netWebSocket(`${this.url}&since=${this.lastSeq()}`)+ } catch {+ this.retry()+ return+ }+ this.ws = ws+ ws.onopen = () => {+ this.backoff = 800+ this.inReplay = true+ this.replaySeen = new Set()+ // acks don't survive the socket: whatever was un-acked is unknowable now,+ // and a stale entry would mis-name a later refusal. Delivery of those ops+ // is the log's job anyway (session.onRelayReady re-sends what the room lacks).+ this.awaitingAck = []+ this.setStatus('open')+ for (const out of this.queue.splice(0)) this.write(out)+ this.startHeartbeat(ws)+ this.hooks.onOpen()+ }+ ws.onmessage = (ev) => {+ const data = String(ev.data)+ if (data === 'pong') { this.awaitingPong = false; return } // keepalive reply+ this.onEnvelope(data).catch(() => {})+ }+ const drop = () => {+ if (this.ws !== ws) return+ this.stopHeartbeat()+ this.ws = null+ this.setStatus('closed')+ this.retry()+ }+ ws.onclose = drop+ ws.onerror = drop+ }++ private startHeartbeat(ws: WebSocket) {+ this.stopHeartbeat()+ this.awaitingPong = false+ this.pingTimer = setInterval(() => {+ if (this.ws !== ws || ws.readyState !== WebSocket.OPEN) return+ if (this.awaitingPong) {+ // no pong since the last ping → the socket is dead (half-open); force a+ // close so onclose fires and we reconnect, rather than hanging silently.+ try { ws.close() } catch { /* already gone */ }+ return+ }+ this.awaitingPong = true+ try { ws.send('ping') } catch { /* send failed → onclose will handle it */ }+ }, OnlineTransport.PING_MS)+ }++ private stopHeartbeat() {+ if (this.pingTimer) { clearInterval(this.pingTimer); this.pingTimer = null }+ this.awaitingPong = false+ }++ private retry() {+ if (this.closed) return+ setTimeout(() => this.connect(), this.backoff)+ this.backoff = Math.min(this.backoff * 1.8, 30000)+ }++ // --- refusals -------------------------------------------------------------++ /**+ * The relay refused a frame. Handling this is not optional politeness: when+ * the relay dropped oversize/over-quota frames SILENTLY, the sender got no+ * ack, the peer stayed behind, its `need`/vv catch-up asked for the very+ * same op, and the sender re-sent the identical doomed frame forever.+ *+ * 'rate-limited' is transient — back off and retry. Everything else is+ * permanent for that frame: it goes up to the session, which forgets the ops+ * so the loop cannot restart, and tells the user what they just lost.+ */+ private handleRefusal(env: RefusedEnv) {+ if (env.code === 'rate-limited') {+ this.throttle(typeof env.retryInMs === 'number' ? env.retryInMs : 10_000)+ return+ }+ if (env.code !== 'too-large' && env.code !== 'storage-failed' && env.code !== 'room-full') {+ // a code from a newer relay: no recovery we can invent is better than+ // leaving the op in the log, where `need` will retry it honestly+ console.warn('[bento-sync] relay refused a frame:', env.code)+ return+ }+ const culprit = this.matchRefused(env)+ if (culprit) this.awaitingAck = this.awaitingAck.filter((o) => o !== culprit)+ console.warn(`[bento-sync] relay refused a frame (${env.code})`, env)+ this.hooks.onRefused?.(env.code, culprit?.ops ?? null)+ }++ /**+ * Which frame does this refusal name? The relay quotes no id, so: head of+ * the ack queue by protocol order, CONFIRMED against the size it reported.+ * A mismatch means the refusal was for a frame we don't track — snapshots+ * are never acked, so they never enter the queue — and we must not hand the+ * session somebody else's ops to drop on a guess. Ambiguity → null → the+ * ops stay in the log (retried, at worst refused again and reported again),+ * because a wrong drop is silent permanent data divergence.+ */+ private matchRefused(env: RefusedEnv): Outbound | null {+ // Exact when the relay echoed our id. Everything below is the legacy+ // fallback for relays that don't (and a self-hoster's relay may be a year+ // old) — inferential, so it stays deliberately conservative.+ if (env.k) return this.awaitingAck.find((o) => o.id === env.k) ?? null+ // too-large measures the whole envelope; storage-failed measures i+d only+ const byText = typeof env.got === 'number'+ const want = byText ? env.got! : typeof env.bytes === 'number' ? env.bytes : null+ const size = (o: Outbound) => (byText ? o.text.length : o.bytes)+ const head = this.awaitingAck[0] ?? null+ if (want === null) return head // room-full carries no size — order is all we have+ if (head && size(head) === want) return head+ return this.awaitingAck.find((o) => size(o) === want) ?? null+ }++ /** Rate limited: hold everything for the window, then replay what we sent+ * into it. Un-acked frames may or may not have landed — re-sending is safe+ * (the CRDT dedups by actor:seq) and losing them silently is not. */+ private throttle(ms: number) {+ const wait = Math.min(Math.max(ms, 1000), 60_000)+ const retryable = this.awaitingAck.filter((o) => ++o.tries <= OnlineTransport.MAX_RETRIES)+ // past the retry cap we stop re-sending, but the op is NOT dropped: it+ // stays in the session log for the next `need`/reconnect to carry.+ this.awaitingAck = []+ this.queue = [...retryable, ...this.queue]+ if (this.pauseTimer) clearTimeout(this.pauseTimer)+ this.paused = true+ this.pauseTimer = setTimeout(() => {+ this.pauseTimer = null+ this.paused = false+ for (const out of this.queue.splice(0)) this.write(out)+ }, wait)+ // transient and self-healing, so say it at most once a minute+ const now = Date.now()+ if (now - this.lastLimitNotice > 60_000) {+ this.lastLimitNotice = now+ this.hooks.onRefused?.('rate-limited', null)+ }+ }++ /** write now, or park it (disconnected, or inside a rate-limit backoff) */+ private write(out: Outbound) {+ if (!this.paused && this.ws && this.ws.readyState === WebSocket.OPEN) {+ try {+ this.ws.send(out.text)+ } catch {+ this.park(out) // send threw → onclose will reconnect and flush+ return+ }+ if (out.ops) {+ this.awaitingAck.push(out)+ if (this.awaitingAck.length > OnlineTransport.ACK_WINDOW) this.awaitingAck.shift()+ }+ return+ }+ this.park(out)+ }++ private park(out: Outbound) {+ this.queue.push(out)+ if (this.queue.length > 500) this.queue.shift()+ }++ private async onEnvelope(text: string) {+ let env: { i?: string; d?: string; q?: number; snap?: number; ctl?: string; p?: string } & RefusedEnv+ try {+ env = JSON.parse(text)+ } catch {+ return+ }+ // the owner revoked a key; if it's OURS, stand down for good (the relay+ // refuses our reconnects anyway — don't retry into a wall of 403s)+ if (env.ctl === 'revoked') {+ if (env.p && env.p === this.myPub) {+ console.info('[bento-sync] this copy’s access was revoked by the owner')+ this.close()+ }+ return+ }+ // the relay would not take a frame and said so (v1.0.9 relay and later;+ // older relays never send this, which is why every path here is additive)+ if (env.ctl === 'refused') {+ this.handleRefusal(env)+ return+ }+ if (env.ctl === 'ack' || env.ctl === 'ready') {+ // one ack = the oldest un-acked persisted frame landed+ if (env.ctl === 'ack') this.awaitingAck.shift()+ if (typeof env.q === 'number') {+ this.saveSeq(env.q)+ this.maybeSnapshot(env.q)+ }+ if (env.ctl === 'ready') {+ this.inReplay = false+ const wantSnap = this.hooks.onReady(this.replaySeen, env.q ?? 0)+ this.replaySeen = new Set()+ // fresh rooms and just-merged forks get a snapshot immediately so+ // late joiners converge without needing the full op log+ if (wantSnap || env.q === 0) void this.uploadSnapshot(env.q ?? 0)+ }+ return+ }+ if (!env.i || !env.d || !this.key) return+ let payload: unknown+ try {+ const pt = await crypto.subtle.decrypt(+ { name: 'AES-GCM', iv: b64u.dec(env.i) as BufferSource },+ this.key,+ b64u.dec(env.d) as BufferSource,+ )+ payload = JSON.parse(new TextDecoder().decode(pt))+ } catch {+ return // wrong key / corrupted — ignore+ }+ if (typeof env.q === 'number') this.saveSeq(env.q)+ if (env.snap === 1) {+ const s = payload as { doc: SyncDoc; state: SyncStateJSON }+ if (s && s.doc && s.state) this.hooks.onSnap(s.doc, s.state)+ return+ }+ const frame = payload as Frame+ if (this.inReplay && frame.t === 'ops') {+ for (const op of frame.ops) this.replaySeen.add(`${op.a}:${op.s}`)+ }+ this.onFrame(frame)+ }++ private inReplay = true++ private snapInFlight = false++ /** every SNAP_EVERY persisted ops, upload a fresh encrypted snapshot */+ private maybeSnapshot(q: number) {+ if (q === 0 || q % SNAP_EVERY !== 0) return+ void this.uploadSnapshot(q)+ }++ /** encrypt + store the current (doc, state) as the room's snapshot */+ async uploadSnapshot(q: number) {+ if (this.snapInFlight) return+ this.snapInFlight = true+ try {+ const snap = this.hooks.getSnapshot()+ const text = await this.encrypt(JSON.stringify(snap))+ if (text && this.ws && this.ws.readyState === WebSocket.OPEN) {+ const env: Record<string, unknown> = { snap: 1, q, i: text.i, d: text.d }+ if (this.signKey) env.g = await signFrame(this.signKey, text.i, text.d)+ this.ws.send(JSON.stringify(env))+ }+ } finally {+ this.snapInFlight = false+ }+ }++ private async encrypt(plain: string): Promise<{ i: string; d: string } | null> {+ if (!this.key) return null+ const iv = new Uint8Array(12)+ crypto.getRandomValues(iv)+ const ct = await crypto.subtle.encrypt(+ { name: 'AES-GCM', iv: iv as BufferSource },+ this.key,+ new TextEncoder().encode(plain),+ )+ return { i: b64u.enc(iv), d: b64u.enc(new Uint8Array(ct)) }+ }++ send(frame: Frame) {+ void (async () => {+ const enc = await this.encrypt(JSON.stringify(frame))+ if (!enc) return+ let env: Record<string, unknown> = enc+ let ops: Op[] | null = null+ const id = nextFrameId()+ if (frame.t === 'ops') {+ env = { k: id, p: 1, ...enc }+ // sign the ciphertext so the relay verifies authorship while blind.+ if (this.signKey) env.g = await signFrame(this.signKey, enc.i, enc.d)+ ops = frame.ops+ }+ // remember what rode in the frame so a refusal can name it+ this.write({ id, text: JSON.stringify(env), ops, bytes: enc.i.length + enc.d.length, tries: 0 })+ })()+ }++ close() {+ this.closed = true+ if (this.pauseTimer) { clearTimeout(this.pauseTimer); this.pauseTimer = null }+ this.stopHeartbeat()+ this.ws?.close()+ this.ws = null+ this.setStatus('closed')+ }++ /** OWNER action: revoke one member key (or an invite key — cutting off every+ * copy descended from that invite). Signed `rev.${pub}`; the relay stores it,+ * drops that key's future writes/joins, and fans out a `revoked` note. */+ async revokeKey(pub: string, ownerPub: string, ownerPriv: string): Promise<boolean> {+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return false+ const g = await signText(ownerPriv, `rev.${pub}`)+ this.ws.send(JSON.stringify({ ctl: 'revoke', p: pub, o: ownerPub, g }))+ return true+ }+}++// --- share/join glue --------------------------------------------------------++let active: OnlineTransport | null = null++export function onlineTransport(): OnlineTransport | null {+ return active+}++/** inert stand-in when a re-keyed document has no collab config */+class NullTransport implements Transport {+ readonly kind = 'off'+ send() {}+ close() {}+}++/** does this document want its relay connected? (absent `on` = true: v0.8.0+ * files only carried collab while actively shared) */+export function sharingOn(store: Store): boolean {+ const c = store.doc.collab+ return !!c?.room && !!c.key && c.on !== false+}++/** connect the session to the relay in doc.collab (no-op unless sharing is on) */+export function joinFromDoc(session: SyncSession, store: Store): OnlineTransport | null {+ if (offlineEnabled()) return null // the hard no-network switch wins over everything+ if (active) return active+ if (!sharingOn(store)) return null+ session.addTransport((docId, onFrame) => {+ // re-invoked whenever the session re-keys (doc replaced): consult the+ // CURRENT document — its collab config may differ or be off+ const collab = store.doc.collab+ if (!collab?.room || !collab.key || collab.on === false || store.doc.docId !== docId) {+ active = null+ return new NullTransport()+ }+ active?.close()+ // Auth shape per copy: reader → none (unsigned, relay drops writes);+ // v2 owner → direct with ownerPriv; v2 member → invite chain (device key+ // minted per-machine); legacy → the shared writer key pair.+ let auth: AuthSpec | undefined+ if (collab.role !== 'reader') {+ if (collab.v === 2 && collab.owner && collab.ownerPriv) {+ auth = { kind: 'direct', pub: collab.owner, priv: collab.ownerPriv }+ } else if (collab.v === 2 && collab.owner && collab.invite) {+ auth = { kind: 'chain', owner: collab.owner, invite: collab.invite, docId }+ } else if (collab.writerPub) {+ auth = { kind: 'direct', pub: collab.writerPub, priv: collab.writerPriv }+ }+ }+ active = new OnlineTransport(collab.room, collab.key, docId, onFrame, {+ onSnap: (doc, state) => session.applySnapshot(doc, state),+ getSnapshot: () => session.snapshot(),+ onOpen: () => session.hello(),+ onReady: (seen) => session.onRelayReady(seen),+ onRefused: (code, ops) => session.refused(code, ops),+ }, auth)+ return active+ })+ return active+}++/** flip sharing on and connect — the "Start live session" action.+ * Credentials already exist (minted at creation); this only arms them. */+export async function startSharing(session: SyncSession, store: Store): Promise<OnlineTransport | null> {+ if (offlineEnabled()) return null+ if (active) return active+ if (!store.doc.collab) {+ const creds = await mintCollab()+ store.commit(() => { store.doc.collab = creds })+ }+ store.commit(() => { store.doc.collab!.on = true })+ return joinFromDoc(session, store)+}++/**+ * Offline-mode disconnect: drop the relay WITHOUT touching doc.collab.on —+ * the document's sharing intent is unchanged; this viewer just won't+ * network. Turning offline mode off re-joins via the normal path.+ */+export function disconnectOnline(session: SyncSession) {+ if (active) {+ session.removeTransport(active)+ active = null+ }+}++/** flip sharing off and disconnect. Credentials stay — copies saved during+ * the session can rejoin if sharing is turned back on. */+export function stopSharing(session: SyncSession, store: Store) {+ if (active) {+ session.removeTransport(active)+ active = null+ }+ if (store.doc.collab && store.doc.collab.on !== false) {+ store.commit(() => {+ store.doc.collab!.on = false+ })+ }+}++/** revocation: mint a fresh room + key. Every previously sent copy loses+ * access; only copies saved AFTER this can join future sessions. */+export async function rotateKeys(session: SyncSession, store: Store) {+ stopSharing(session, store)+ const fresh = await mintCollab()+ store.commit(() => {+ const sync = store.doc.collab?.sync+ store.doc.collab = sync ? { ...fresh, sync } : fresh+ })+}diff --git a/kernel/src/sync/session.ts b/kernel/src/sync/session.tsnew file mode 100644index 00000000..b25f88bd--- /dev/null+++ b/kernel/src/sync/session.ts@@ -0,0 +1,840 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento-sync session — the bridge between the CRDT engine (crdt.ts) and the+// running editor. Owns: the differ hook on the store, transports (same-machine+// BroadcastChannel always; an online relay transport can be added), presence,+// and peer catch-up. See docs/collab-design.md.+//+// Wire protocol (one JSON frame per message; E2EE happens inside the online+// transport — this layer never knows):+// {t:'hello', a, vv, p} join/announce — receivers reply hello + missing ops+// {t:'ops', a, ops} op batch+// {t:'need', a, vv} gap catch-up request (receivers send missing ops)+// {t:'p', a, p} presence heartbeat {t:'bye', a} leave+//+// The differ is the whole integration: every local mutation already flows+// through store.commit/touch → 'doc' event → (debounced) diff against the+// session's shadow → ops out. Remote ops apply surgically by id and re-emit+// the same store events the editor already listens to. Zero editor rewrites.++import {+ SyncEngine,+ SYNC_V,+ BLOB_INLINE_MAX,+ type BlobRef,+ type CollabCreds,+ type Op,+ type SyncDoc,+ type SyncStateJSON,+} from './crdt.ts'++// Re-exported: these are DOCUMENT-FORMAT types and live with the engine, but+// every consumer meets them through the session.+export type { BlobRef, CollabCreds, SyncDoc }+import { putBlob, getBlob, dataUriToBytes, bytesToDataUri, encodedSize, MAX_BLOB } from './blobs.ts'+import { mintCollab } from './online.ts'+import { lsGet, lsJson } from '../storage.ts'++/**+ * The store the session drives, reduced to what it actually touches.+ *+ * Every app already has this: bento/slides' Store satisfies it as written.+ * Stated structurally rather than imported so the kernel does not reach into+ * an app — kernel/README.md's rule.+ */+export interface HostStore {+ doc: SyncDoc+ readOnly?: boolean+ on(event: string, fn: () => void): unknown+ emit(event: string): void+ commit(fn: () => void): void+ setDirty(v: boolean): void+}++/**+ * The app-shaped decisions the session cannot make for itself.+ *+ * This is deliberately SMALL. Of 727 lines, five places knew what a slide was:+ * repairing an emptied document, clamping the current position, pruning a+ * selection of ids that no longer exist, saying where this person is for+ * presence, and recognising embedded media in a refused batch. Everything else+ * — the differ, the shadow, catch-up, gap recovery, blobs, the fork snapshot+ * exchange — was already generic and moved unchanged.+ *+ * A word processor answers all five differently: "empty" is a document with no+ * blocks, "where you are" is a block and a caret rather than a slide and a+ * selection.+ */+export interface SyncHost {+ readonly store: HostStore+ /**+ * Repair the document after a remote change — an emptied container, say.+ * Return true if it mutated the doc.+ *+ * THE REPAIR DOES NOT CONVERGE BY ITSELF. Returning true makes the session+ * mint the change as an ordinary local op, and an op is all it is: two+ * replicas that heal concurrently mint TWO nodes and the CRDT faithfully+ * keeps both. Nothing here deduplicates them.+ *+ * So any id the repair creates MUST be derived from stable document data —+ * `docId`, or the content — and never freshly generated, so that concurrent+ * healers produce the SAME node and the merge collapses it. bento/slides+ * gets away with a random id because a spare blank slide is visible and+ * harmless; a spare page in a space is a phantom in the sidebar, and a spare+ * paragraph is one somebody has to notice and delete.+ *+ * This comment previously said the session "mints the repair as a local op+ * so every replica converges on one healer's version", which reads as though+ * convergence were handled for you. It is not, and that belief is exactly+ * what produces a random-id heal. (Caught by the bento/spaces session, which+ * hit the race while writing its own adapter.)+ */+ heal(): boolean+ /**+ * Snapshot per-tab view state BEFORE a remote change is applied. Optional:+ * a shape whose view survives any edit does not need one.+ *+ * It exists because clamping after the fact is not enough. Keeping the user+ * on the same slide when someone else deletes a different one requires+ * knowing which slide they were on by IDENTITY, and after the apply that+ * information is gone — the index now points at whatever moved into the gap.+ * bento/slides fixed exactly this upstream (#262) and the fix is unavailable+ * to a post-hoc clamp.+ */+ captureView?(): unknown+ /**+ * Reconcile per-tab view state (current position, selection) with a document+ * that changed underneath it, given whatever `captureView` returned. Return+ * true if the SELECTION changed, which is the only part the session has to+ * announce.+ */+ clampView(view?: unknown): boolean+ /** Where this replica is, for presence. */+ presence(): { at: string; sel: string[] }+ /**+ * Store events fired after EVERY remote change.+ *+ * Was hard-coded to `'doc'`, which is what bento/slides calls "something in+ * the document changed, repaint". It is not universal: in bento/spaces the+ * same name is the DIRTY/STATUS signal and repainting goes through 'tree'+ * and 'page', so emitting it for a remote op would label a colleague's edit+ * "Edited" in this user's chrome. Which events a remote change should raise+ * is the app's to say — the kernel knowing one app's vocabulary is exactly+ * what this seam exists to stop.+ *+ * (Raised by the bento/spaces session reviewing this interface. The kernel+ * had shipped its own app's habit as a default.)+ */+ readonly changeEvents: readonly string[]+ /** Extra events a STRUCTURAL remote change needs, on top of changeEvents. */+ readonly structureEvents: readonly string[]+ /** Events that should push a fresh presence frame when the app emits them. */+ readonly presenceEvents: readonly string[]+ /** Structural probe: does this refused batch carry embedded media? */+ carriesMedia(ops: Op[]): boolean+ /**+ * The engine BOUND to this app's document shape.+ *+ * Passed as the class, not an instance, because the session constructs one+ * per attach and restores one from saved state — and `fromJSON` on a bound+ * subclass returns that subclass (pinned by scripts/test-sync-shape.ts).+ * A session that built a bare `SyncEngine` here would silently hold slides'+ * shape for every app.+ */+ readonly engine: {+ new (actor: string): SyncEngine+ fromJSON(actor: string, json: SyncStateJSON): SyncEngine+ }+}++export interface PresenceInfo {+ name: string+ color: string+ /**+ * WHERE THIS PERSON IS — a slide id in bento/slides, a page id in+ * bento/spaces, a block id in bento/type.+ *+ * The NAME is wrong for three of the four apps and is kept anyway, because+ * it is on the wire: deployed clients read this field, and the relay stores+ * frames containing it. Renaming it to `at` would fork presence between+ * versions for no user-visible gain — a live session would show colleagues+ * as nowhere. The app-side name IS `at` (SyncHost.presence returns `{at,+ * sel}`), so the honest name is used everywhere it costs nothing, and the+ * frozen one only where it is load-bearing.+ */+ slide: string+ /** selected element ids */+ sel: string[]+ /** element id currently being text-edited (in-text presence) */+ editing?: string+ /** v2 fine-grained: the key this copy signs with — key-bound identity */+ pub?: string+ /** capability of this copy, derived locally from its collab material */+ role?: 'owner' | 'editor' | 'viewer'+}++export interface Peer extends PresenceInfo {+ actor: string+ at: number+}++interface HelloFrame { t: 'hello'; a: string; vv: Record<string, number>; p: PresenceInfo }+interface OpsFrame { t: 'ops'; a: string; ops: Op[] }+interface NeedFrame { t: 'need'; a: string; vv: Record<string, number> }+interface PresFrame { t: 'p'; a: string; p: PresenceInfo }+interface ByeFrame { t: 'bye'; a: string }+/** state-based fork merge: a rejoining offline-edited copy announces itself */+interface SnapFrame {+ t: 'snap'+ a: string+ doc: SyncDoc+ state: SyncStateJSON+}+/** every frame is stamped with the sync protocol version (`pv: SYNC_V`) by+ * send(); frames without the current pv (old builds, stale relay logs from+ * the bare-id era) are dropped in onFrame — their keys don't interoperate */+export type Frame = (HelloFrame | OpsFrame | NeedFrame | PresFrame | ByeFrame | SnapFrame) & {+ pv?: number+}++export interface Transport {+ readonly kind: string+ send(frame: Frame): void+ close(): void+}++/**+ * Why the relay refused a frame (`{ctl:'refused', code, …}` — see+ * server/sync-worker). Everything but 'rate-limited' is PERMANENT for the+ * frame that drew it: retrying can only reproduce the refusal.+ */+export type RefusalCode = 'too-large' | 'storage-failed' | 'room-full' | 'rate-limited'++/**+ * Something the user deserves to know about the live session. The transport+ * detects it, the session records the consequence, the editor renders the+ * sentence (t() must run at display time, so no text crosses this boundary).+ */+export interface SyncNotice {+ code: RefusalCode+ /** true = the change will never reach collaborators; false = retrying */+ permanent: boolean+ /** how many ops were abandoned (0 when the refused frame wasn't ours to name) */+ ops: number+ /** the abandoned ops carried embedded media — lets the UI say "that image" */+ media?: boolean+}++/** Same-machine transport: every open tab/window of this document. */+class BroadcastTransport implements Transport {+ readonly kind = 'local'+ private ch: BroadcastChannel+ constructor(docId: string, onFrame: (f: Frame) => void) {+ this.ch = new BroadcastChannel(`bento-sync-${docId}`)+ this.ch.onmessage = (ev) => onFrame(ev.data as Frame)+ }+ send(frame: Frame) {+ this.ch.postMessage(frame)+ }+ close() {+ this.ch.close()+ }+}++const PEER_COLORS = ['#FF9E8A', '#8FA3BF', '#7FC8A9', '#E8C468', '#C792EA', '#6AB7D6', '#E88AB0', '#A9C77F']++const actorColor = (actor: string): string => {+ let h = 0+ for (let i = 0; i < actor.length; i++) h = (h * 31 + actor.charCodeAt(i)) >>> 0+ return PEER_COLORS[h % PEER_COLORS.length]+}++/**+ * Actor id: fresh per SESSION INSTANCE, deliberately — a reloaded tab is a+ * new replica with empty CRDT state, and the engine skips "own" ops on+ * apply, so reusing an id would make relay replay of the previous+ * incarnation's ops a no-op. Random ids sidestep the whole class.+ */+function tabActor(): string {+ return Math.random().toString(36).slice(2, 10)+}++const DIFF_DEBOUNCE_MS = 90+const HEARTBEAT_MS = 5000+const PEER_TTL_MS = 13000++export class SyncSession {+ readonly actor: string+ state!: SyncEngine+ private shadow = ''+ private docId = ''+ private log: Op[] = []+ private transports: Transport[] = []+ private peersMap = new Map<string, Peer>()+ private applying = false+ private diffTimer: number | null = null+ private heartbeat: number | null = null+ private peerListeners = new Set<() => void>()+ private noticeListeners = new Set<(n: SyncNotice) => void>()+ private editingEl: string | undefined+ /** extra transports (the online relay) get plugged in here */+ private makeExtraTransports: Array<(docId: string, onFrame: (f: Frame) => void) => Transport> = []++ private readonly host: SyncHost+ /** the app's store — every call site below predates the host and still reads+ * `this.store`, which is exactly the point: the move changed the seam, not+ * the session's logic */+ private get store(): HostStore { return this.host.store }++ constructor(host: SyncHost) {+ this.host = host+ const store = host.store+ this.actor = tabActor()+ this.attach()+ store.on('doc', () => this.onLocalChange())+ for (const ev of host.presenceEvents) store.on(ev, () => this.pushPresence())+ window.addEventListener('beforeunload', () => this.broadcast({ t: 'bye', a: this.actor }))+ }++ // --- lifecycle -----------------------------------------------------------++ /** a restored offline fork still owes the room its snapshot */+ private forkPending = false++ /** the loaded doc arrived carrying collab creds (was saved/shared) */+ private bornWithCollab = false+ /** the user opted in this session (saved, or hit "Start live session") */+ private explicitShare = false++ /** Should this doc auto-connect to the relay on open? See attach(). */+ shareEligible(): boolean {+ return this.bornWithCollab || this.explicitShare+ }++ /** Mark that the user opted into sharing (save / explicit Start live). */+ enableSharing() {+ this.explicitShare = true+ }++ private attach() {+ this.docId = this.store.doc.docId+ const doc = this.store.doc+ // Auto-connect eligibility: a doc that ARRIVED carrying collab creds was+ // saved/shared by someone — it should go live on open. A doc we mint creds+ // for right now (the anonymous starter demo, a fresh template instance) is+ // NOT auto-connected — it phones home only after the user saves or clicks+ // "Start live session" (enableSharing). This keeps casual visitors off the+ // relay and honours "nothing phones home unless you ask".+ this.bornWithCollab = !!doc.collab+ this.explicitShare = false+ // credentials are minted AT CREATION: any copy of the file can join once+ // it is live (on:true by default). Minting is async now (the writer+ // keypair) — fine because a freshly-minted doc is never auto-connected, so+ // the sub-frame gap before collab lands touches nothing. See eligibility.+ if (!doc.collab) void this.ensureCollab()+ const saved = doc.collab?.sync+ if (saved && saved.v === SYNC_V) {+ // this file was saved during/after a shared session: restore the CRDT+ // state so our offline edits carry real registers, remote replay+ // dedups by version vector, and a state-based snapshot exchange can+ // merge the fork BOTH ways (see docs/collab-design.md)+ this.state = this.host.engine.fromJSON(this.actor, JSON.parse(JSON.stringify(saved)))+ this.forkPending = true+ } else {+ // no saved state, or state from the pre-composite-key era (v1) — that+ // scheme collapsed same-id-on-many-slides, so it is discarded and the+ // file joins as a never-synced adopt (deterministic keys from the doc)+ this.state = new this.host.engine(this.actor)+ }+ this.state.adopt(doc)+ this.shadow = JSON.stringify(doc)+ this.log = []+ this.peersMap.clear()+ this.emitPeers()+ for (const tr of this.transports) tr.close()+ this.transports = [new BroadcastTransport(this.docId, (f) => this.onFrame(f))]+ for (const mk of this.makeExtraTransports) this.transports.push(mk(this.docId, (f) => this.onFrame(f)))+ this.hello() // announces + (for restored forks) broadcasts the state snapshot+ if (this.heartbeat) clearInterval(this.heartbeat)+ this.heartbeat = window.setInterval(() => {+ this.pushPresence()+ this.sweepPeers()+ }, HEARTBEAT_MS)+ }++ /** Mint collab credentials (incl. the writer keypair) for a doc created+ * without them. Direct mutation (no undo entry), guarded against a race with+ * a real collab arriving via loadDoc. */+ private async ensureCollab() {+ if (this.store.doc.collab) return+ const creds = await mintCollab()+ if (!this.store.doc.collab) this.store.doc.collab = creds+ }++ /** register a factory for an additional transport (online relay) and connect it */+ addTransport(mk: (docId: string, onFrame: (f: Frame) => void) => Transport): Transport {+ this.makeExtraTransports.push(mk)+ const tr = mk(this.docId, (f) => this.onFrame(f))+ this.transports.push(tr)+ this.broadcast({ t: 'hello', a: this.actor, vv: this.state.vv, p: this.presence() })+ return tr+ }++ removeTransport(tr: Transport) {+ tr.close()+ this.transports = this.transports.filter((x) => x !== tr)+ this.makeExtraTransports = []+ }++ get transportKinds(): string[] {+ return this.transports.map((t) => t.kind)+ }++ // --- local mutations → ops ----------------------------------------------++ private onLocalChange() {+ if (this.applying) return+ if (this.store.doc.docId !== this.docId) {+ // replaceDoc / loadDoc swapped in a different document — re-key+ this.attach()+ return+ }+ if (this.diffTimer) return+ this.diffTimer = window.setTimeout(() => {+ this.diffTimer = null+ this.flush()+ }, DIFF_DEBOUNCE_MS)+ }++ /** diff now (also called before presence-relevant transitions) */+ /**+ * Assets too large for an op (docs/blob-offload.md) are uploaded to the+ * relay's blob store and published as a small `blobs.<key>` reference, which+ * IS small enough to sync. Runs after a local edit; the reference lands on+ * the next flush like any other change.+ *+ * The bytes are always cached locally even when the upload fails, because+ * the cache is per-ORIGIN: same-machine tabs syncing over BroadcastChannel+ * resolve from it with no relay involved at all.+ */+ private async offloadAssets() {+ const doc = this.store.doc+ const assets = doc.assets ?? {}+ const creds = this.blobCreds()+ for (const [k, v] of Object.entries(assets)) {+ if (typeof v !== 'string' || v.length <= BLOB_INLINE_MAX) continue+ if (doc.blobs?.[k]) continue // already published+ const parsed = dataUriToBytes(v)+ if (!parsed) continue // raw SVG markup, not binary — leave it inline+ if (encodedSize(parsed.bytes.length) > MAX_BLOB) {+ this.notify('blob-too-large', k)+ continue+ }+ if (!creds) continue // no relay yet; retry on the next edit+ const res = await putBlob(+ { base: creds.base, room: creds.room, tok: creds.tok }, creds.rawKey, parsed.bytes,+ )+ if (!res.ok) {+ // 'unsupported' = relay has no blob storage. Not an error: small assets+ // still inline, and same-origin tabs resolve from the local cache.+ if (res.reason !== 'unsupported') this.notify(`blob-${res.reason}`, k)+ continue+ }+ this.store.commit(() => {+ const d = this.store.doc+ ;(d.blobs ??= {})[k] = { key: res.key, mime: parsed.mime, size: parsed.bytes.length }+ })+ }+ }++ /**+ * The other direction: a peer published a reference we have no bytes for.+ * Fetch, decrypt and materialise it into `assets` so the renderer can use it+ * exactly as if it had arrived inline.+ *+ * A blob that never arrives leaves the asset ABSENT rather than blank —+ * `assetRef()` in render.ts resolves a missing key to '', which the UI shows+ * as a visibly empty element. Silent-but-wrong is the failure mode we are+ * avoiding everywhere in this system.+ */+ private async resolveBlobs() {+ const doc = this.store.doc+ const refs = doc.blobs ?? {}+ const creds = this.blobCreds()+ for (const [k, ref] of Object.entries(refs)) {+ if (doc.assets?.[k]) continue // already have the bytes+ if (this.fetching.has(ref.key)) continue+ this.fetching.add(ref.key)+ try {+ // cache-first, so same-origin tabs need no relay at all+ const bytes = creds+ ? await getBlob({ base: creds.base, room: creds.room, tok: creds.tok }, creds.rawKey, ref.key)+ : null+ if (!bytes) { this.notify('blob-unavailable', k); continue }+ this.store.commit(() => {+ const d = this.store.doc+ ;(d.assets ??= {})[k] = bytesToDataUri(bytes, ref.mime)+ })+ } finally {+ this.fetching.delete(ref.key)+ }+ }+ }++ private fetching = new Set<string>()+ /** set by the editor when an online transport exists */+ /** Credentials the blob layer needs, taken from whichever transport can+ * reach a relay.+ *+ * Resolved ON DEMAND, deliberately. The obvious shape — a hook assigned when+ * the online transport connects — is what shipped broken: nothing ever+ * assigned it, so `creds` was always null, every upload was skipped by the+ * `if (!creds) continue` guard, and the whole offload was inert with no+ * error anywhere. Transports are also torn down and rebuilt on reconnect and+ * on rejoin, so even a correctly-assigned hook goes stale. Asking the live+ * transport list each time cannot drift. */+ private blobCreds(): { base: string; room: string; tok: string; rawKey: Uint8Array } | null {+ for (const tr of this.transports) {+ const f = (tr as { blobCreds?: () => { base: string; room: string; tok: string; rawKey: Uint8Array } | null }).blobCreds+ if (typeof f !== 'function') continue+ const c = f.call(tr)+ if (c) return c+ }+ return null+ }+ private notify(code: string, detail?: string) {+ // routed through the existing notice channel so the editor can toast it+ try { (this as unknown as { noticeFn?: (c: string, d?: string) => void }).noticeFn?.(code, detail) } catch { /* none */ }+ }++ flush() {+ if (this.applying) return+ const before = JSON.parse(this.shadow) as SyncDoc+ let ops: Op[]+ try {+ ops = this.state.diff(before, this.store.doc, { text: true })+ } catch (err) {+ this.recoverFromDiffFailure(err)+ return+ }+ this.shadow = JSON.stringify(this.store.doc)+ // Any large asset the differ just skipped needs its bytes offloaded; the+ // resulting reference syncs on the next flush like an ordinary change.+ void this.offloadAssets()+ if (!ops.length) return+ this.log.push(...ops)+ this.broadcast({ t: 'ops', a: this.actor, ops })+ }++ /**+ * A differ bug must not WEDGE the session. The shadow is only advanced after+ * a successful diff, so an uncaught throw here poisons every later flush:+ * the same delta is re-diffed, throws again, and nothing syncs for the rest+ * of the session — on any slide, not just the element that broke. That+ * amplifier is what turned the ~200KB-text stack overflow (fixed in crdt.ts:+ * splice-without-spread) into total, silent collab failure. The trigger is+ * gone; the amplifier stays armed for the next differ bug, so disarm it.+ *+ * Recovery, best-effort in this order:+ * - Advance the shadow past the poison delta. Re-diffing it would just+ * re-throw, and a wedged differ is strictly worse than one lost delta.+ * - Ship a state snapshot. diff() mints ops and advances its registers as+ * it goes, so a mid-diff throw leaves some changes stamped but never+ * broadcast — they now live only in our doc VALUES. That is exactly the+ * offline-fork case, and a snapshot is how those travel (see hello()).+ * forkPending re-sends it on the next reconnect too.+ *+ * Deliberately not a SyncNotice: those name conditions a user can act on+ * (too large, room full). This path is a bug — console is the right surface.+ */+ private recoverFromDiffFailure(err: unknown) {+ console.error('[bento-sync] diff failed; recovering via snapshot', err)+ this.shadow = JSON.stringify(this.store.doc)+ this.forkPending = true+ try {+ // inlined rather than this.snapshot() — that calls flush(), and flush()+ // is our caller+ this.broadcast({+ t: 'snap',+ a: this.actor,+ doc: JSON.parse(JSON.stringify(this.store.doc)) as SyncDoc,+ state: JSON.parse(JSON.stringify(this.state.toJSON())),+ })+ } catch (e2) {+ // snapshot itself failed (state unserializable) — the shadow is still+ // advanced, so editing continues and the next reconnect retries+ console.error('[bento-sync] snapshot recovery failed', e2)+ }+ }++ // --- remote frames --------------------------------------------------------++ private onFrame(f: Frame) {+ if (f.pv !== SYNC_V) return // old-protocol frame (bare-id keys) — ignore+ if (f.a === this.actor) return+ switch (f.t) {+ case 'hello': {+ this.touchPeer(f.a, f.p)+ // answer so the newcomer learns us + catch them up from our log,+ // AND tell them our vv so ops they minted before connecting (which+ // nothing else would push) flow back to us — need→ops terminates+ this.send({ t: 'p', a: this.actor, p: this.presence() })+ this.send({ t: 'need', a: this.actor, vv: this.state.vv })+ const missing = this.state.missingFor(this.log, f.vv)+ if (missing.length) this.send({ t: 'ops', a: this.actor, ops: missing })+ break+ }+ case 'ops':+ this.applyRemote(f.ops)+ break+ case 'need': {+ const missing = this.state.missingFor(this.log, f.vv)+ if (missing.length) this.send({ t: 'ops', a: this.actor, ops: missing })+ break+ }+ case 'p':+ this.touchPeer(f.a, f.p)+ break+ case 'snap':+ this.applySnapshot(f.doc, f.state)+ break+ case 'bye':+ this.peersMap.delete(f.a)+ this.emitPeers()+ break+ }+ }++ applyRemote(ops: Op[]) {+ // make sure our own pending edits are diffed first (they pre-date the+ // remote batch locally; LWW settles the rest)+ this.flush()+ for (const op of ops) if (!this.log.some((o) => o.a === op.a && o.s === op.s)) this.log.push(op)+ this.applying = true+ // Before the document moves, not after: see captureView on the host shape.+ const view = this.host.captureView?.()+ try {+ const res = this.state.apply(this.store.doc, ops)+ if (res.changed) this.afterRemoteChange(res.structure, view)+ } finally {+ this.applying = false+ }+ if (this.state.gappedActors.length) {+ this.send({ t: 'need', a: this.actor, vv: this.state.vv })+ }+ }++ private afterRemoteChange(structure: boolean, view?: unknown) {+ void this.resolveBlobs()+ const store = this.store+ // A delete-everything race can leave a document with no content at all,+ // which no editor can render. What "empty" means and what repairs it are+ // the app's to say.+ if (this.host.heal()) {+ // mint the repair as a local op so every replica converges on ONE+ // healer's version (LWW keeps all healers'; harmless duplicates)+ this.applying = false+ this.flush()+ this.applying = true+ }+ const selChanged = this.host.clampView(view)+ this.shadow = JSON.stringify(store.doc)+ store.doc.modified = new Date().toISOString()+ store.setDirty(true)+ for (const ev of this.host.changeEvents) store.emit(ev)+ if (structure) for (const ev of this.host.structureEvents) store.emit(ev)+ if (selChanged) store.emit('selection')+ }++ // --- presence -------------------------------------------------------------++ private presence(): PresenceInfo {+ let name = 'Guest'+ try {+ name = lsGet('bento-author') || 'Guest'+ } catch {+ /* storage unavailable */+ }+ // key-bound identity (v2): which key this copy signs with + its capability.+ // The device key is minted by the transport on first connect; until then a+ // member's pub is simply absent from presence (it fills in on reconnect).+ const c = this.store.doc.collab+ let pub: string | undefined+ let role: 'owner' | 'editor' | 'viewer' | undefined+ if (c) {+ if (c.role === 'reader') role = 'viewer'+ else if (c.v === 2 && c.ownerPriv) { role = 'owner'; pub = c.owner }+ else if (c.v === 2 && c.invite) {+ role = 'editor'+ pub = lsJson<{ pub?: string } | null>(`bento-member-${this.store.doc.docId}`, null)?.pub+ } else if (c.writerPriv) { role = 'editor'; pub = c.writerPub }+ }+ const where = this.host.presence()+ return {+ name,+ color: actorColor(this.actor),+ // `slide` is the WIRE name and is frozen — deployed clients and the+ // relay both read it. It means "where this person is", which for a word+ // processor is a block rather than a slide.+ slide: where.at,+ sel: where.sel,+ ...(this.editingEl ? { editing: this.editingEl } : {}),+ ...(pub ? { pub } : {}),+ ...(role ? { role } : {}),+ }+ }++ /** canvas hooks this while a text element is being edited (M3 presence) */+ setEditing(elId: string | undefined) {+ if (this.editingEl === elId) return+ this.editingEl = elId+ this.pushPresence()+ }++ private pushPresence() {+ this.send({ t: 'p', a: this.actor, p: this.presence() })+ }++ private touchPeer(actor: string, p: PresenceInfo) {+ this.peersMap.set(actor, { ...p, actor, at: Date.now() })+ this.emitPeers()+ }++ private sweepPeers() {+ const cut = Date.now() - PEER_TTL_MS+ let changed = false+ for (const [a, p] of this.peersMap) {+ if (p.at < cut) {+ this.peersMap.delete(a)+ changed = true+ }+ }+ if (changed) this.emitPeers()+ }++ peers(): Peer[] {+ return [...this.peersMap.values()].sort((a, b) => (a.actor < b.actor ? -1 : 1))+ }++ onPeers(fn: () => void): () => void {+ this.peerListeners.add(fn)+ return () => this.peerListeners.delete(fn)+ }++ private emitPeers() {+ this.peerListeners.forEach((fn) => fn())+ }++ // --- relay refusals -------------------------------------------------------++ /** the editor subscribes here to toast what the relay refused */+ onNotice(fn: (n: SyncNotice) => void): () => void {+ this.noticeListeners.add(fn)+ return () => this.noticeListeners.delete(fn)+ }++ private emitNotice(n: SyncNotice) {+ this.noticeListeners.forEach((fn) => fn(n))+ }++ /**+ * A transport reports that the relay refused a frame. For the PERMANENT+ * codes the named ops can never be delivered, so they leave the resend log.+ *+ * Why dropping is the right call, and why it is narrow: `missingFor` answers+ * every peer `need` (and `onRelayReady`) out of `log`, so an op the relay+ * will always refuse would be re-offered, re-sent, re-refused — forever.+ * That loop is the bug this exists to break. The price is real and cannot be+ * undone: the local document KEEPS the change, remote replicas never see it,+ * and nothing reconciles it later (short of the file being re-opened, which+ * re-adopts the doc wholesale). Because it is a permanent divergence we drop+ * ONLY the exact ops the refused frame carried — never a range, never the+ * rest of the log, and never anything when the frame couldn't be identified.+ */+ refused(code: RefusalCode, ops: Op[] | null) {+ const doomed = ops ?? []+ if (doomed.length) {+ const keys = new Set(doomed.map((o) => `${o.a}:${o.s}`))+ this.log = this.log.filter((o) => !keys.has(`${o.a}:${o.s}`))+ }+ this.emitNotice({+ code,+ permanent: code !== 'rate-limited',+ ops: doomed.length,+ ...(this.host.carriesMedia(doomed) ? { media: true } : {}),+ })+ }++ // --- snapshots (online catch-up + file-fork merge) ------------------------++ /** current (doc, sync-state) pair for an encrypted relay snapshot */+ snapshot(): { doc: SyncDoc; state: SyncStateJSON } {+ this.flush()+ return {+ doc: JSON.parse(JSON.stringify(this.store.doc)) as SyncDoc,+ state: JSON.parse(JSON.stringify(this.state.toJSON())),+ }+ }++ /** merge a remote snapshot (relay replay for far-behind joiners) */+ applySnapshot(rdoc: SyncDoc, rstate: SyncStateJSON) {+ if (!rstate || rstate.v !== SYNC_V) return // pre-v2 room snapshot — unusable+ this.flush()+ this.applying = true+ const view = this.host.captureView?.()+ try {+ const res = this.state.mergeSnapshot(this.store.doc, rdoc, rstate)+ if (res.changed) this.afterRemoteChange(true, view)+ } finally {+ this.applying = false+ }+ }++ /** re-announce (an online transport reconnected) */+ hello() {+ this.broadcast({ t: 'hello', a: this.actor, vv: this.state.vv, p: this.presence() })+ if (this.forkPending) {+ // rejoining offline fork: our contributions live in doc values ++ // restored registers, not ops — a state snapshot is how they travel+ const s = this.snapshot()+ this.broadcast({ t: 'snap', a: this.actor, doc: s.doc, state: s.state })+ }+ }++ /**+ * Relay replay finished. `seen` holds the (actor,seq) pairs the room+ * already has; anything in our log it lacks gets (re)sent for persistence+ * — covers ops minted before the transport connected. Returns whether a+ * fresh server snapshot should be uploaded (fork just merged).+ */+ onRelayReady(seen: Set<string>): boolean {+ const missing = this.log.filter((o) => !seen.has(`${o.a}:${o.s}`))+ if (missing.length) this.send({ t: 'ops', a: this.actor, ops: missing })+ const fork = this.forkPending+ this.forkPending = false+ return fork+ }++ /**+ * Stamp the CRDT state into doc.collab.sync so the SAVED file can rejoin+ * as a true fork later. Called by the save/serialize paths; only shared+ * documents carry it (never-shared files stay clean).+ */+ stampInto(doc: SyncDoc) {+ if (!doc.collab || doc.collab.on === false) return+ this.flush()+ doc.collab.sync = JSON.parse(JSON.stringify(this.state.toJSON()))+ }++ // --- plumbing -------------------------------------------------------------++ private send(frame: Frame) {+ const stamped = { ...frame, pv: SYNC_V }+ for (const tr of this.transports) tr.send(stamped)+ }++ private broadcast(frame: Frame) {+ this.send(frame)+ }+}+diff --git a/scripts/lib/sync-fixtures-type.ts b/scripts/lib/sync-fixtures-type.tsnew file mode 100644index 00000000..92cfd52d--- /dev/null+++ b/scripts/lib/sync-fixtures-type.ts@@ -0,0 +1,179 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Random bento/type documents and edits, for the sync rigs.+//+// A SEPARATE MODULE per shape, for the reason sync-fixtures-spaces.ts states:+// the slides generator picks its mutation with `Math.floor(rnd() * N)`, so+// adding a case to a shared file re-rolls the kind mapping for every seed in+// every rig that uses it — silently changing what years of coverage mean while+// the diff looks purely additive.+//+// WHAT A type DOCUMENT HAS THAT NEITHER OTHER APP DOES:+//+// · IT IS FLAT. `body` is the parent array and a block has no children. The+// engine's element layer is simply absent, so every op is parent-scoped.+// · THE TEXT IS ON THE PARENT, and it is PLAIN text with `marks` over+// character ranges — not an HTML string. The text merges token by token+// (RGA); the marks do not.+// · MARKS AND NOTES ARE OFFSETS INTO THAT TEXT. This is the interesting part+// and the reason this generator exists: an edit that changes text length+// must shift them, and the app does that with `spliceText`. Using the app's+// own function here is deliberate — it makes each replica's LOCAL state+// exactly what the editor would produce, so anything the rig finds after a+// merge is a property of the MERGE, not of arithmetic invented for a test.+// · FOOTNOTE BODIES LIVE IN A DOC-LEVEL MAP keyed by note id, so a note+// outlives a re-flow of the paragraph that references it. Two authors+// adding notes touch the same map.++import { spliceText, type Block, type BlockKind } from '../../type/src/model.ts';++export type Doc = Record<string, unknown> & {+ body: Block[];+ footnotes: Record<string, string>;+};++/** deterministic PRNG — the same one every other sync fixture uses */+export function mulberry32(a: number) {+ return function () {+ a |= 0; a = (a + 0x6d2b79f5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++export const stable = (v: unknown): string => JSON.stringify(v);++const KINDS: BlockKind[] = ['para', 'h1', 'h2', 'h3', 'quote'];+const MARKS = ['b', 'i', 'code', 'strike'] as const;+const WORDS = [+ 'payment', 'shall', 'be', 'due', 'within', 'thirty', 'days', 'of', 'invoice',+ 'the', 'parties', 'agree', 'that', 'notice', 'may', 'terminate', 'liability',+ 'is', 'limited', 'to', 'fees', 'paid', 'under', 'this', 'agreement',+];++const words = (rnd: () => number, n: number) =>+ Array.from({ length: n }, () => WORDS[Math.floor(rnd() * WORDS.length)]).join(' ');++export function baseDoc(rnd: () => number): Doc {+ const n = 3 + Math.floor(rnd() * 4);+ const body: Block[] = Array.from({ length: n }, (_, i) => {+ const b: Block = {+ id: `p${i + 1}`,+ kind: KINDS[Math.floor(rnd() * KINDS.length)],+ text: words(rnd, 4 + Math.floor(rnd() * 8)),+ };+ if (rnd() < 0.4 && b.text.length > 4) {+ const from = Math.floor(rnd() * (b.text.length - 3));+ b.marks = [{ t: MARKS[Math.floor(rnd() * MARKS.length)], from, to: from + 1 + Math.floor(rnd() * 3) }];+ }+ return b;+ });+ return {+ format: 'bento/type', version: 1, docId: 'doc-fixture',+ title: 'Agreement', page: { width: 816, height: 1056, marginX: 104, marginTop: 104, marginBottom: 104 },+ body, footnotes: {}, revisions: [], signatures: [],+ };+}++/** how many distinct mutation kinds `randomMutation` can pick */+export const MUTATION_KINDS = 15;++/**+ * Apply one random edit, as the editor would.+ *+ * `tag` distinguishes ids minted by different replicas, so a concurrent insert+ * from two actors is genuinely two blocks rather than an id collision the+ * engine would be entitled to merge.+ */+export function randomMutation(doc: Doc, rnd: () => number, tag: string): void {+ const pick = <T,>(a: T[]): T | undefined => (a.length ? a[Math.floor(rnd() * a.length)] : undefined);+ const kind = Math.floor(rnd() * MUTATION_KINDS);+ const b = pick(doc.body);+ const at = (t: string) => Math.floor(rnd() * (t.length + 1));++ switch (kind) {+ case 0: { // insert a block+ const i = Math.floor(rnd() * (doc.body.length + 1));+ doc.body.splice(i, 0, {+ id: `${tag}${Math.floor(rnd() * 1e6).toString(36)}`,+ kind: KINDS[Math.floor(rnd() * KINDS.length)],+ text: words(rnd, 3 + Math.floor(rnd() * 6)),+ });+ break;+ }+ case 1: { // delete a block (never the last one — an empty body is not a document)+ if (doc.body.length > 1) doc.body.splice(Math.floor(rnd() * doc.body.length), 1);+ break;+ }+ case 2: { // move a block+ if (doc.body.length > 1) {+ const from = Math.floor(rnd() * doc.body.length);+ const [m] = doc.body.splice(from, 1);+ doc.body.splice(Math.floor(rnd() * (doc.body.length + 1)), 0, m);+ }+ break;+ }+ case 3: case 4: case 5: { // TYPE — the common case, weighted accordingly+ if (!b) break;+ const i = doc.body.indexOf(b);+ doc.body[i] = spliceText(b, at(b.text), 0, ' ' + words(rnd, 1 + Math.floor(rnd() * 3)));+ break;+ }+ case 6: { // delete a span+ if (!b || b.text.length < 3) break;+ const i = doc.body.indexOf(b);+ const from = Math.floor(rnd() * (b.text.length - 2));+ doc.body[i] = spliceText(b, from, 1 + Math.floor(rnd() * Math.min(8, b.text.length - from)), '');+ break;+ }+ case 7: { // replace a span (type over a selection)+ if (!b || b.text.length < 3) break;+ const i = doc.body.indexOf(b);+ const from = Math.floor(rnd() * (b.text.length - 2));+ doc.body[i] = spliceText(b, from, 1 + Math.floor(rnd() * 4), words(rnd, 1));+ break;+ }+ case 8: { // change block kind+ if (b) b.kind = KINDS[Math.floor(rnd() * KINDS.length)];+ break;+ }+ case 9: { // add a mark+ if (!b || b.text.length < 2) break;+ const from = Math.floor(rnd() * (b.text.length - 1));+ const m = { t: MARKS[Math.floor(rnd() * MARKS.length)], from, to: from + 1 + Math.floor(rnd() * 4) };+ b.marks = [...(b.marks ?? []), { ...m, to: Math.min(m.to, b.text.length) }];+ break;+ }+ case 10: { // remove marks — property REMOVAL, the class that hid two crashes+ if (b && b.marks) delete b.marks;+ break;+ }+ case 11: { // add a footnote: a ref in the block AND a body in the doc-level map+ if (!b) break;+ const id = `n${tag}${Math.floor(rnd() * 1e5).toString(36)}`;+ b.notes = [...(b.notes ?? []), { id, at: at(b.text) }];+ doc.footnotes[id] = words(rnd, 3 + Math.floor(rnd() * 5));+ break;+ }+ case 12: { // remove a footnote, ref and body together+ if (!b || !b.notes?.length) break;+ const gone = b.notes[Math.floor(rnd() * b.notes.length)];+ b.notes = b.notes.filter(x => x.id !== gone.id);+ if (!b.notes.length) delete b.notes;+ delete doc.footnotes[gone.id];+ break;+ }+ case 13: { // set or clear a role+ if (!b) break;+ if (rnd() < 0.5) b.role = pick(['title', 'clause', 'recital'])!;+ else delete b.role;+ break;+ }+ case 14: { // doc-level props+ if (rnd() < 0.5) doc.title = `Agreement ${Math.floor(rnd() * 100)}`;+ else (doc.page as Record<string, number>).marginX = 80 + Math.floor(rnd() * 40);+ break;+ }+ }+}diff --git a/scripts/lib/ts-resolve-hooks.mjs b/scripts/lib/ts-resolve-hooks.mjsnew file mode 100644index 00000000..b942cbc3--- /dev/null+++ b/scripts/lib/ts-resolve-hooks.mjs@@ -0,0 +1,62 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Node module hooks for driving APP source (not just kernel source) from a rig.+//+// Two gaps between how the app is written and what Node loads on its own, and+// the kernel rigs hit neither — which is why this appeared only when the+// SESSION layer needed testing.+//+// 1. RESOLUTION. App source is written for Vite and imports without file+// extensions (`from '../store'`). Node requires them, so a rig importing+// app modules dies at load with ERR_MODULE_NOT_FOUND before one check+// runs. Kernel modules all carry `.ts`, so kernel rigs never noticed.+//+// 2. SYNTAX. Node's built-in TypeScript support is STRIP-ONLY: it removes+// types but refuses anything that emits code. `constructor(private store:+// Store)` — a parameter property, which session.ts uses — is exactly that,+// and fails with ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX.+//+// The alternative to (2) was editing session.ts to drop the parameter property.+// Rejected on principle: the rig exists to prove the session's behaviour is+// UNCHANGED across a move into the kernel, and it cannot do that if the first+// thing it does is change the code it is meant to be pinning. A test that+// requires edits to its subject has stopped being a control.+//+// esbuild is the app's own transpiler (it is what Vite uses), so this runs the+// same transform the shipped build does rather than a second interpretation of+// the language.++import { readFile } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';++const esbuild = await import('../../slides/node_modules/esbuild/lib/main.js');++export async function resolve(specifier, context, nextResolve) {+ try {+ return await nextResolve(specifier, context);+ } catch (err) {+ // only relative, extensionless specifiers — never bare package names+ if (!specifier.startsWith('.') || /\.[cm]?[jt]sx?$/.test(specifier)) throw err;+ for (const ext of ['.ts', '.tsx', '/index.ts']) {+ try {+ return await nextResolve(specifier + ext, context);+ } catch {+ /* try the next candidate */+ }+ }+ throw err;+ }+}++export async function load(url, context, nextLoad) {+ if (!/\.tsx?$/.test(url)) return nextLoad(url, context);+ const path = fileURLToPath(url);+ const source = await readFile(path, 'utf8');+ const { code } = await esbuild.transform(source, {+ loader: url.endsWith('.tsx') ? 'tsx' : 'ts',+ format: 'esm',+ target: 'es2022',+ sourcefile: path,+ });+ return { format: 'module', source: code, shortCircuit: true };+}diff --git a/scripts/test-sync-flat.ts b/scripts/test-sync-flat.tsnew file mode 100644index 00000000..ccd40c50--- /dev/null+++ b/scripts/test-sync-flat.ts@@ -0,0 +1,201 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// A FLAT document shape — one level deep, no element layer.+//+// node scripts/test-sync-flat.ts+//+// WHAT THIS PROVES. bento/slides and bento/spaces are both two levels deep: a+// slide holds elements, a page holds blocks. The engine assumed that depth —+// `children` was required, and the child accessor called `.length/.forEach/+// .push/.splice` on whatever key it named. bento/type is one level: `body` is+// an array of blocks and a block IS the paragraph, so there is nothing beneath+// it and no honest key to point `children` at.+//+// This rig binds type's ACTUAL shape — `shape('body', null, 'text')` — and+// checks the two things a flat binding has to get right:+//+// 1. text still merges token-by-token, because the text is on the parent+// (scripts/test-sync-parent-text.ts isolates that variable with children+// still present; here they are genuinely absent);+// 2. the document keeps its shape. An engine that quietly wrote an empty+// `elements: []` onto every block would still converge, and would still+// pass every convergence check, while corrupting the format — so the+// structural assertion is made directly.+//+// It also covers the receiving side: an element-scoped op has nowhere to land+// in a flat document, and must be dropped rather than throw or invent a key.++import { SyncEngine, shape } from '../slides/src/sync/crdt.ts'+import type { DocShape, Op } from '../slides/src/sync/crdt.ts'++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 H = (s: string) => console.log(`\n=== ${s} ===`)++console.log('bento-sync — a flat document shape\n')++/** bento/type: a document is a list of blocks, and a block carries its text. */+const TYPE_SHAPE: DocShape = shape('body', null, 'text')+class TypeSync extends SyncEngine {+ constructor(actor: string) { super(actor, TYPE_SHAPE) }+}++type Block = { id: string; kind: string; text: string }+type Doc = { body: Block[] }+const clone = <T,>(v: T): T => JSON.parse(JSON.stringify(v))++const mk = (): Doc => ({+ format: 'bento/type', version: 1, docId: 'd', title: 'Master Services Agreement',+ body: [+ { id: 'p1', kind: 'para', text: 'The parties agree as follows.' },+ { id: 'p2', kind: 'para', text: 'Payment is due within 30 days.' },+ ],+} as unknown as Doc)++/** two replicas of the same document, each having adopted it independently */+function pair() {+ const A = new TypeSync('alice')+ const B = new TypeSync('bob')+ const dA = mk()+ A.adopt(dA as never)+ const dB = clone(dA)+ B.adopt(dB as never)+ return { A, B, dA, dB }+}++H('the shape binds at all')+{+ ok(TYPE_SHAPE.children === null, 'children is null — a flat document declares no element layer')+ ok(TYPE_SHAPE.parents === 'body' && TYPE_SHAPE.text === 'text',+ 'blocks live in body, and their text is the collaboratively-merged property')+ ok(TYPE_SHAPE.skipDoc.has('body'),+ 'the container is skipped as a doc property — syncing it as a value would make the whole document one register')+ const { dA } = pair()+ ok(Array.isArray(dA.body) && dA.body.length === 2, 'a flat document adopts without throwing')+}++H('two authors typing in the same paragraph both survive')+{+ const { A, B, dA, dB } = pair()+ const beforeA = clone(dA)+ dA.body[1].text = 'Payment is due within sixty (60) days.'+ const opsA = A.diff(beforeA as never, dA as never, { text: true })++ const beforeB = clone(dB)+ dB.body[1].text = 'Payment is due within 30 days of invoice.'+ const opsB = B.diff(beforeB as never, dB as never, { text: true })++ ok(opsA.length === 1 && opsA[0].op === 'txt',+ `a paragraph edit is one token delta (got ${opsA.map(o => o.op).join(',') || 'nothing'})`)+ ok(String(opsA[0].el) === 'p2', `keyed by the block id itself (got ${JSON.stringify(String(opsA[0].el))})`)++ A.apply(dA as never, opsB)+ B.apply(dB as never, opsA)+ ok(JSON.stringify(dA) === JSON.stringify(dB), 'the replicas converge')+ const merged = dA.body[1].text+ console.log(` merged: ${JSON.stringify(merged)}`)+ ok(merged.includes('sixty (60)'), "the payment term one author changed survives")+ ok(merged.includes('of invoice'), "and so does the clause the other appended")+}++H('the document keeps its shape')+{+ // The failure this catches converges perfectly and still corrupts the file.+ const { A, B, dA, dB } = pair()+ const beforeA = clone(dA)+ dA.body[0].text = 'The parties hereby agree as follows.'+ const opsA = A.diff(beforeA as never, dA as never, { text: true })+ B.apply(dB as never, opsA)++ const keys = new Set(dB.body.flatMap(b => Object.keys(b)))+ ok(!keys.has('elements') && !keys.has('blocks') && !keys.has('children'),+ `no child array is invented on a block (keys: ${[...keys].sort().join(', ')})`)+ ok(JSON.stringify(Object.keys(dB.body[0]).sort()) === JSON.stringify(['id', 'kind', 'text']),+ 'a block round-trips with exactly the properties it started with')+}++H('structure — blocks insert, delete and reorder')+{+ const { A, B, dA, dB } = pair()+ const beforeA = clone(dA)+ dA.body.splice(1, 0, { id: 'p3', kind: 'h2', text: 'Payment' }) // insert in the MIDDLE+ const opsA = A.diff(beforeA as never, dA as never, { text: true })++ const beforeB = clone(dB)+ dB.body[0].text = 'The parties agree as set out below.'+ const opsB = B.diff(beforeB as never, dB as never, { text: true })++ A.apply(dA as never, opsB)+ B.apply(dB as never, opsA)+ ok(JSON.stringify(dA) === JSON.stringify(dB), 'a concurrent insert and edit converge')+ ok(dA.body.map(b => b.id).join(',') === 'p1,p3,p2',+ `the new heading lands where it was put (${dA.body.map(b => b.id).join(',')})`)+ ok(dA.body[0].text === 'The parties agree as set out below.', 'and the concurrent edit is not lost')++ // delete+ const beforeD = clone(dA)+ dA.body.splice(0, 1)+ const opsD = A.diff(beforeD as never, dA as never, { text: true })+ B.apply(dB as never, opsD)+ ok(JSON.stringify(dA) === JSON.stringify(dB) && dB.body.length === 2,+ 'a deleted block is gone on both replicas')++ // reorder+ const beforeR = clone(dA)+ dA.body.reverse()+ const opsR = A.diff(beforeR as never, dA as never, { text: true })+ B.apply(dB as never, opsR)+ ok(JSON.stringify(dA) === JSON.stringify(dB), 'a reorder converges')+}++H('an element-scoped op has nowhere to land, and is dropped')+{+ // Peers in a room share a shape, so this should never arrive — but it came+ // off the wire. Materializing it would throw against the frozen empty child+ // array, or invent a key the format does not have.+ const { A, dA } = pair()+ const before = clone(dA)+ const foreign = [+ { a: 'mallory', s: 1, l: 99, op: 'set', sl: 'p1', el: 'p1x1', k: 'text', v: 'injected' },+ { a: 'mallory', s: 2, l: 100, op: 'ins', kind: 'element', id: 'p1x2', sl: 'p1', ord: 'a', node: { id: 'x2' } },+ ] as unknown as Op[]+ let threw = false+ try { A.apply(dA as never, foreign) } catch { threw = true }+ ok(!threw, 'applying it does not throw')+ ok(JSON.stringify(dA) === JSON.stringify(before), 'and leaves the document untouched')+}++H('a saved state restores as the same flat binding')+{+ const { A, dA } = pair()+ const before = clone(dA)+ dA.body[0].text = 'Edited.'+ const first = A.diff(before as never, dA as never, { text: true })+ const back = TypeSync.fromJSON('alice', A.toJSON())+ ok(back instanceof TypeSync, 'a restored type engine is a type engine')+ ok(back.S.children === null && back.S.text === 'text',+ '…and still flat, with its text property intact')++ // it must still converge after the round trip+ const B = new TypeSync('bob')+ const dB = clone(dA)+ B.adopt(dB as never)+ const b2 = clone(dA)+ dA.body[1].text = 'Payment is due within 45 days.'+ const ops = back.diff(b2 as never, dA as never, { text: true })+ // both ops, in order: the restored engine continues alice's sequence, so+ // delivering only the later one leaves a per-actor gap and the engine+ // rightly holds it — that is delivery working, not a merge failure+ B.apply(dB as never, [...first, ...ops])+ ok(dB.body[1].text === 'Payment is due within 45 days.',+ 'and a replica applies edits minted by the restored engine')+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/scripts/test-sync-parent-text.ts b/scripts/test-sync-parent-text.tsnew file mode 100644index 00000000..d8e78f20--- /dev/null+++ b/scripts/test-sync-parent-text.ts@@ -0,0 +1,179 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// Collaborative text on a PARENT node.+//+// node scripts/test-sync-parent-text.ts+//+// WHY THIS EXISTS. The token RGA — the thing that lets two people type in one+// paragraph without destroying each other's work — was reachable only on CHILD+// nodes, because both shipped apps put their text there (a slide's elements, a+// page's blocks). bento/type does not: a block IS the paragraph, so its text+// lives one level up. Bound naively, type would have got a last-writer-wins+// register for prose, and the loss would be SILENT — the document stays valid,+// converges, and simply contains one of the two edits.+//+// The other four sync rigs stayed green throughout this change, which proves+// only that nothing broke. Nothing there declares text on a parent, so nothing+// there exercises the new path at all. This is that evidence.+//+// The negative control is the point of the second half: the same scenario run+// with the RGA disabled MUST lose an edit. A rig that has never been seen+// failing is not a gate.++import { SyncEngine, shape } from '../slides/src/sync/crdt.ts'+import type { DocShape } from '../slides/src/sync/crdt.ts'++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 H = (s: string) => console.log(`\n=== ${s} ===`)++console.log('bento-sync — collaborative text on a parent node\n')++/**+ * Text declared on the PARENT. This is not yet type's shape (type's body is+ * flat, which needs `children` to become optional) — it isolates ONE variable:+ * the level the text sits at. Children still exist and are still synced, so a+ * regression in the child path shows up here as well.+ */+const PARENT_TEXT: DocShape = shape('pages', 'blocks', 'text')+class ParentTextSync extends SyncEngine {+ constructor(actor: string) { super(actor, PARENT_TEXT) }+}++type Doc = { pages: Array<{ id: string; text: string; blocks: unknown[] }> }+const mk = (text: string): Doc => ({+ format: 'bento/parent-text', version: 1, docId: 'd', title: 'T',+ pages: [{ id: 'p1', text, blocks: [] }],+} as unknown as Doc)++/** the composite-key separator, written as an escape: a literal here is invisible and does not survive editing */+const SEP = '\u001f'+const clone = <T,>(v: T): T => JSON.parse(JSON.stringify(v))++const BASE = 'The parties agree.'+const ALICE = 'The parties hereby agree.' // inserts in the MIDDLE+const BOB = 'The parties agree. Signed.' // appends at the END++/** Both replicas edit the same parent's text from the same base, then swap. */+function race(text: boolean) {+ const A = new ParentTextSync('alice')+ const B = new ParentTextSync('bob')+ const dA = mk(BASE)+ A.adopt(dA as never)+ const dB = clone(dA)+ B.adopt(dB as never)++ const beforeA = clone(dA)+ dA.pages[0].text = ALICE+ const opsA = A.diff(beforeA as never, dA as never, { text })++ const beforeB = clone(dB)+ dB.pages[0].text = BOB+ const opsB = B.diff(beforeB as never, dB as never, { text })++ A.apply(dA as never, opsB)+ B.apply(dB as never, opsA)+ return { dA, dB, opsA, opsB }+}++H('a text edit on a parent mints an RGA delta, not a whole-value set')+{+ const { opsA } = race(true)+ ok(opsA.length === 1 && opsA[0].op === 'txt',+ `one token delta (got ${opsA.map(o => o.op).join(',') || 'nothing'})`)+ ok(String(opsA[0].el) === 'p1',+ `keyed by the BARE parent id — no composite key, because there is no child (got ${JSON.stringify(String(opsA[0].el))})`)+ ok(!String(opsA[0].el).includes(SEP),+ 'and specifically carries no separator, which is what routes it to the parent lookup')+}++H('two people typing in one paragraph both survive')+{+ const { dA, dB } = race(true)+ ok(JSON.stringify(dA) === JSON.stringify(dB), 'the replicas converge')+ const merged = dA.pages[0].text+ console.log(` alice: ${JSON.stringify(ALICE)}`)+ console.log(` bob: ${JSON.stringify(BOB)}`)+ console.log(` merged:${JSON.stringify(merged)}`)+ ok(merged.includes('hereby'), "alice's insertion survives")+ ok(merged.includes('Signed'), "bob's insertion survives")+ ok(merged === 'The parties hereby agree. Signed.',+ 'and they merge in document order rather than concatenating')+}++H('negative control — with the RGA off, an edit IS lost')+{+ // Same scenario, same code path, `text: false`. If this does NOT lose an+ // edit, the test above proves nothing: it would pass under plain LWW too.+ const { dA, dB, opsA } = race(false)+ ok(opsA.length === 1 && opsA[0].op === 'set',+ `the edit degrades to a whole-value set (got ${opsA[0].op})`)+ ok(JSON.stringify(dA) === JSON.stringify(dB), 'it still converges — which is exactly why the loss is silent')+ const merged = dA.pages[0].text+ const lost = !merged.includes('hereby') || !merged.includes('Signed')+ ok(lost, `one author's work is gone: ${JSON.stringify(merged)}`)+}++H('children still work — the child path is not collateral damage')+{+ const A = new ParentTextSync('alice')+ const B = new ParentTextSync('bob')+ const dA = mk(BASE)+ dA.pages[0].blocks = [{ id: 'b1', text: 'a note' }]+ A.adopt(dA as never)+ const dB = clone(dA)+ B.adopt(dB as never)++ const beforeA = clone(dA)+ ;(dA.pages[0].blocks[0] as { text: string }).text = 'a longer note'+ const opsA = A.diff(beforeA as never, dA as never, { text: true })++ const beforeB = clone(dB)+ dB.pages[0].text = BOB+ const opsB = B.diff(beforeB as never, dB as never, { text: true })++ ok(opsA.length === 1 && opsA[0].op === 'txt' && String(opsA[0].el) === 'p1' + SEP + 'b1',+ 'a CHILD text edit still keys on the composite key')+ A.apply(dA as never, opsB)+ B.apply(dB as never, opsA)+ ok(JSON.stringify(dA) === JSON.stringify(dB), 'parent and child text edits converge together')+ ok((dA.pages[0].blocks[0] as { text: string }).text === 'a longer note' &&+ dA.pages[0].text === BOB,+ 'and both land')+}++H('a whole-value set still beats a stale generation')+{+ // The reset path (someone pastes over the paragraph) has to out-stamp the+ // token history at parent level too, or the paste would be swallowed.+ const A = new ParentTextSync('alice')+ const dA = mk(BASE)+ A.adopt(dA as never)+ let before = clone(dA)+ dA.pages[0].text = ALICE+ const typed = A.diff(before as never, dA as never, { text: true }) // seeds a generation++ before = clone(dA)+ dA.pages[0].text = 'Replaced wholesale.'+ const pasted = A.diff(before as never, dA as never, { text: false })+ ok(pasted.length === 1 && pasted[0].op === 'set', 'the paste mints a set')++ const B = new ParentTextSync('bob')+ const dB = mk(BASE)+ B.adopt(dB as never)+ // BOTH ops, in order. Delivering only the paste leaves a per-actor sequence+ // gap and the engine correctly holds it in the buffer — an earlier version of+ // this fixture did exactly that and read the result as a bug in the code.+ B.apply(dB as never, [...typed, ...pasted])+ ok(dB.pages[0].text === 'Replaced wholesale.',+ `the set out-stamps the generation it arrives behind (got ${JSON.stringify(dB.pages[0].text)})`)+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/scripts/test-sync-session.ts b/scripts/test-sync-session.tsnew file mode 100644index 00000000..13987f8a--- /dev/null+++ b/scripts/test-sync-session.ts@@ -0,0 +1,270 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// The bento-sync SESSION layer — the bridge between the CRDT engine and a+// running editor.+//+// node scripts/test-sync-session.ts+//+// WHY THIS EXISTS, AND WHY NOW. crdt.ts has 45,000 checks behind it. The+// session layer — the differ hook, the shadow, presence, catch-up, the empty+// document repair — had NONE, and it is about to be moved into the kernel and+// parameterized for a second and third app. Moving untested code across a seam+// is how behaviour changes without anyone noticing, so this pins the behaviour+// FIRST, against the implementation as it shipped, and the same rig is then run+// against the kernelized one.+//+// Nothing here is a mock of the session. It drives the REAL SyncSession over+// the REAL Store through a REAL BroadcastChannel — two sessions in one process+// are exactly two tabs of one document, which is the transport that ships and+// is always on. Only `window` is shimmed, because the session reaches for+// `window.setTimeout` and a `beforeunload` listener; every other API it uses+// (localStorage through kernel/src/storage.ts) already degrades safely when+// absent, which is why this runs in node at all.++// ---- the browser surface the session expects -------------------------------+// Deliberately thin: three timer functions and an event listener. If this shim+// ever has to grow, that is a signal the session picked up a dependency the+// kernel should not have.+const listeners: Record<string, Array<() => void>> = {};+(globalThis as unknown as { window: unknown }).window = {+ setTimeout: (fn: () => void, ms: number) => setTimeout(fn, ms),+ clearTimeout: (h: number) => clearTimeout(h),+ setInterval: (fn: () => void, ms: number) => setInterval(fn, ms),+ clearInterval: (h: number) => clearInterval(h),+ addEventListener: (ev: string, fn: () => void) => { (listeners[ev] ??= []).push(fn); },+};++// App source is written for Vite and imports without file extensions; Node+// needs help resolving those. Registered BEFORE the dynamic imports below —+// which is why they are dynamic.+const { register } = await import('node:module');+register('./lib/ts-resolve-hooks.mjs', import.meta.url);++const { Store } = await import('../slides/src/store.ts');+const { SyncSession } = await import('../slides/src/sync/session.ts');+const { newDoc, emptySlide } = await import('../slides/src/model.ts');++let failures = 0, checks = 0;+function ok(cond: boolean, msg: string) {+ checks++;+ if (!cond) { failures++; console.log(` FAIL ${msg}`); } else console.log(` ok ${msg}`);+}+const H = (s: string) => console.log(`\n=== ${s} ===`);++/** the session debounces its differ by 90ms; settle generously past that */+const settle = (ms = 260) => new Promise(r => setTimeout(r, ms));++type AnyStore = InstanceType<typeof Store>;+type AnySession = InstanceType<typeof SyncSession>;++/** Two tabs of ONE document — the same docId, so they share a channel. */+function tabs(): { a: AnyStore; b: AnyStore; sa: AnySession; sb: AnySession; close: () => void } {+ const doc = newDoc();+ doc.docId = `rig-${Math.random().toString(36).slice(2, 10)}`;+ // newDoc() gives a bare deck; the session's interesting paths are about+ // ELEMENTS (text merging, stale selection), so put some there.+ doc.slides = [+ { ...emptySlide(), id: 's1', elements: [+ { id: 'e1', type: 'text', x: 100, y: 100, w: 600, h: 120, html: 'Title here' },+ { id: 'e2', type: 'shape', shape: 'rect', x: 100, y: 300, w: 200, h: 200, fill: '#8FA3BF' },+ ] },+ { ...emptySlide(), id: 's2', elements: [+ { id: 'e3', type: 'text', x: 100, y: 100, w: 600, h: 120, html: 'Second slide' },+ ] },+ ] as never;+ const a = new Store(JSON.parse(JSON.stringify(doc)));+ const b = new Store(JSON.parse(JSON.stringify(doc)));+ const sa = new SyncSession(a);+ const sb = new SyncSession(b);+ return { a, b, sa, sb, close: () => { sa.stop?.(); sb.stop?.(); } };+}++console.log('bento-sync — the session layer\n');++H('a local edit reaches the other tab');+{+ const { a, b, close } = tabs();+ a.commit(() => { a.doc.title = 'Renamed in tab A'; });+ await settle();+ ok(b.doc.title === 'Renamed in tab A',+ `the title crossed the channel (got ${JSON.stringify(b.doc.title)})`);+ close();+}++H('edits flow both ways, and each tab keeps its own view state');+{+ const { a, b, close } = tabs();+ a.commit(() => { a.doc.slides[0].notes = 'from A'; });+ await settle();+ b.commit(() => { b.doc.title = 'from B'; });+ await settle();+ ok(b.doc.slides[0].notes === 'from A' && a.doc.title === 'from B',+ 'both edits landed on both replicas');+ // view state is per-tab and must never be synced+ b.currentIndex = 0;+ b.selection = ['x'];+ await settle(120);+ ok(a.selection.length === 0, "one tab's selection does not become the other's");+ close();+}++H('the document event fires on the receiving tab');+{+ // The whole integration claim is "remote ops re-emit the store events the+ // editor already listens to, so no editor rewrites". If that stops being+ // true the canvas silently stops repainting on remote edits.+ const { a, b, close } = tabs();+ let docEvents = 0;+ b.on('doc', () => { docEvents++; });+ a.commit(() => { a.doc.title = 'repaint me'; });+ await settle();+ ok(docEvents > 0, `the receiving store emitted 'doc' (${docEvents} time(s))`);+ ok(b.dirty, 'and the receiving tab is marked dirty, so the change can be saved');+ close();+}++H('concurrent edits to one text element merge');+{+ const { a, b, close } = tabs();+ const el = a.doc.slides[0].elements.find(e => e.type === 'text');+ if (!el) { ok(false, 'fixture has a text element'); }+ else {+ const id = el.id;+ a.commit(() => { const e = a.doc.slides[0].elements.find(x => x.id === id)!; e.html = 'Hello'; });+ await settle();+ // now both edit the SAME element without seeing each other first+ a.commit(() => { const e = a.doc.slides[0].elements.find(x => x.id === id)!; e.html = 'Hello world'; });+ b.commit(() => { const e = b.doc.slides[0].elements.find(x => x.id === id)!; e.html = 'Well, Hello'; });+ await settle(400);+ const ha = a.doc.slides[0].elements.find(x => x.id === id)!.html;+ const hb = b.doc.slides[0].elements.find(x => x.id === id)!.html;+ ok(ha === hb, `the two tabs agree on the text (${JSON.stringify(ha)} vs ${JSON.stringify(hb)})`);+ }+ close();+}++H('presence');+{+ const { a, b, sa, sb, close } = tabs();+ await settle(150);+ const seen = () => sa.peers().map(p => p.actor);+ ok(seen().includes(sb.actor), `tab A sees tab B as a peer (${seen().length} peer(s))`);+ b.currentIndex = 0;+ b.emit('current');+ await settle(150);+ const peer = sa.peers().find(p => p.actor === sb.actor);+ ok(!!peer && typeof peer.slide === 'string', 'and knows which slide that peer is on');+ ok(!!peer?.color, 'a peer carries a colour, so the UI can label them');+ close();+}++H('an emptied deck heals');+{+ // The race this repairs: two tabs each delete the last slides. The merge can+ // land on a deck with NO slides, which the editor cannot render.+ const { a, b, close } = tabs();+ a.commit(() => { a.doc.slides.splice(0, a.doc.slides.length); });+ await settle(400);+ ok(a.doc.slides.length >= 1, `tab A is not left with an empty deck (${a.doc.slides.length} slide(s))`);+ ok(b.doc.slides.length >= 1, `nor is tab B (${b.doc.slides.length} slide(s))`);+ ok(a.currentIndex < a.doc.slides.length, 'and the current index is in range');+ close();+}++H('a stale selection is dropped on the receiving tab');+{+ const { a, b, close } = tabs();+ const el = a.doc.slides[0].elements[0];+ b.selection = [el.id];+ a.commit(() => { a.doc.slides[0].elements = a.doc.slides[0].elements.filter(e => e.id !== el.id); });+ await settle(400);+ ok(!b.selection.includes(el.id),+ 'an element deleted elsewhere leaves no dangling id selected');+ close();+}++// ---------------------------------------------------------------------------+// THE SEAM. The same kernel session, bound to a completely different app.+//+// This is what the move was for, and it is the only part that could not have+// been written before it. bento/type is flat where slides is nested, its text+// is on the parent, its store has one listener list instead of five events,+// and it has no dirty flag — so if the session had kept ANY slides assumption,+// it would surface here rather than in the seven sections above.+// ---------------------------------------------------------------------------+const { Store: TypeStore } = await import('../type/src/store.ts');+const { SyncSession: TypeSession } = await import('../type/src/sync/session.ts');+const { emptyDoc } = await import('../type/src/model.ts');++function typeTabs() {+ const doc = emptyDoc();+ doc.docId = `rig-type-${Math.random().toString(36).slice(2, 10)}`;+ doc.body = [+ { id: 'p1', kind: 'para', text: 'The parties agree as follows.' },+ { id: 'p2', kind: 'para', text: 'Payment is due within 30 days.' },+ ];+ const a = new TypeStore(JSON.parse(JSON.stringify(doc)));+ const b = new TypeStore(JSON.parse(JSON.stringify(doc)));+ const sa = new TypeSession(a, () => ({ block: 'p1' }));+ const sb = new TypeSession(b, () => ({ block: 'p2' }));+ return { a, b, sa, sb };+}++H('the same session drives bento/type');+{+ const { a, b } = typeTabs();+ a.commit(d => { d.body[0].text = 'The parties hereby agree as follows.'; });+ await settle();+ ok(b.doc.body[0].text === 'The parties hereby agree as follows.',+ `an edit in one document reaches the other (got ${JSON.stringify(b.doc.body[0].text)})`);+}++H('two people typing in one paragraph, over the live session');+{+ // The kernel change this whole line of work rests on, exercised end to end:+ // through the store, the differ, the debounce, a real channel, and back.+ const { a, b } = typeTabs();+ a.commit(d => { d.body[1].text = 'Payment is due within sixty (60) days.'; });+ b.commit(d => { d.body[1].text = 'Payment is due within 30 days of invoice.'; });+ await settle(500);+ const ta = a.doc.body[1].text, tb = b.doc.body[1].text;+ ok(ta === tb, `the two agree (${JSON.stringify(ta)})`);+ ok(ta.includes('sixty (60)') && ta.includes('of invoice'),+ 'and BOTH edits survived — the token RGA is reachable through the session');+}++H('a remote edit does not land on the local undo stack');+{+ // Word-processor specific and easy to get wrong: ⌘Z means "undo what I+ // did". If a remote paragraph arrived as a commit, undo would revert a+ // colleague's work and redo would bring it back as if it were yours.+ const { a, b } = typeTabs();+ // CONTROL FIRST. `0 → 0` proves nothing if undoDepth never moves, so show+ // that a LOCAL edit does push a step before claiming a remote one does not.+ const start = b.undoDepth;+ b.commit(d => { d.body[0].text = 'Edited by me.'; });+ const afterLocal = b.undoDepth;+ ok(afterLocal > start, `a local edit pushes an undo step (${start} → ${afterLocal})`);+ await settle();++ a.commit(d => { d.body[1].text = 'Edited by the other person.'; });+ await settle();+ ok(b.doc.body[1].text === 'Edited by the other person.', 'the remote edit arrived');+ ok(b.undoDepth === afterLocal,+ `and added nothing to this person's undo stack (${afterLocal} → ${b.undoDepth})`);+}++H('an emptied document heals with a paragraph, not a slide');+{+ const { a } = typeTabs();+ a.commit(d => { d.body.splice(0, d.body.length); });+ await settle(400);+ ok(a.doc.body.length >= 1, `the document still has a block (${a.doc.body.length})`);+ ok(a.doc.body[0]?.kind === 'para' && a.doc.body[0]?.text === '',+ 'and it is an empty paragraph — somewhere to put the caret');+}++console.log(`\n${checks - failures}/${checks} checks passed`);+// BroadcastChannel and the heartbeat keep node's event loop alive+process.exit(failures ? 1 : 0);diff --git a/scripts/test-sync-shape.ts b/scripts/test-sync-shape.tsindex 389b7064..1d545ad5 100644--- a/scripts/test-sync-shape.ts+++ b/scripts/test-sync-shape.ts@@ -22,7 +22,7 @@// silently holding slides' shape, and the resulting room cannot be repaired in// the field.-import { SyncEngine, SyncState, SLIDES_SHAPE } from '../slides/src/sync/crdt.ts'+import { SyncEngine, SyncState, SLIDES_SHAPE, shape } from '../slides/src/sync/crdt.ts'import type { DocShape } from '../slides/src/sync/crdt.ts'let failures = 0@@ -36,11 +36,10 @@ function ok(cond: boolean, msg: string) {console.log('bento-sync — the document-shape seam\n')/** bento/spaces: pages hold blocks. The binding spaces will ship. */-const SPACES_SHAPE: DocShape = {- parents: 'pages',- children: 'blocks',- skipDoc: new Set(['pages', 'modified', 'collab', 'format', 'version']),-}+// Built with `shape()`, not by hand. A literal here omitted `text` when that+// field was added and silently disabled the token RGA for this shape — the+// engine now refuses such a shape, and this rig should model what apps do.+const SPACES_SHAPE: DocShape = shape('pages', 'blocks')class SpacesSync extends SyncEngine {constructor(actor: string) { super(actor, SPACES_SHAPE) }}diff --git a/scripts/test-sync-spaces.ts b/scripts/test-sync-spaces.tsindex 74ef8224..971ae2d2 100644--- a/scripts/test-sync-spaces.ts+++ b/scripts/test-sync-spaces.ts@@ -28,11 +28,19 @@// The engine is the kernel's, bound to ('pages','blocks'). Nothing here is// spaces app code: this is the shape binding and its evidence.-import { SyncEngine, shape } from '../kernel/src/sync/crdt.ts'+import { SyncEngine } from '../kernel/src/sync/crdt.ts'import { mulberry32, baseDoc, randomMutation, type Doc } from './lib/sync-fixtures-spaces.ts'import { effectiveParents, descendantsOf } from '../spaces/src/model.ts'-export const SPACES_SHAPE = shape('pages', 'blocks')+// The binding lives with the APP (spaces/src/sync/crdt.ts), not here. Two+// definitions of a frozen format constant is precisely how a fork starts: the+// shape strings are minted into every persisted SyncStateJSON and every relay+// frame, so a rig that carries its own copy can go green while the app ships+// something else. Re-exported so existing importers are unaffected.+// (`export … from` re-exports without binding the name locally, and this rig+// uses it below — so it is imported and re-exported.)+import { SPACES_SHAPE } from '../spaces/src/sync/crdt.ts'+export { SPACES_SHAPE }class SpacesSync extends SyncEngine {constructor(actor: string) { super(actor, SPACES_SHAPE) }}diff --git a/scripts/test-sync-type.ts b/scripts/test-sync-type.tsnew file mode 100644index 00000000..21b009eb--- /dev/null+++ b/scripts/test-sync-type.ts@@ -0,0 +1,307 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/type under the shared CRDT engine — convergence, and the format's own+// invariants after convergence.+//+// node scripts/test-sync-type.ts+// SEEDS=300 STEPS=80 ACTORS=4 node scripts/test-sync-type.ts+//+// TWO DIFFERENT QUESTIONS, following scripts/test-sync-spaces.ts:+//+// 1. DO REPLICAS CONVERGE? The engine's own property, and the standard ask.+//+// 2. IS WHAT THEY CONVERGE ON A LEGAL bento/type DOCUMENT? This is the one+// with teeth here. A block's `text` merges TOKEN BY TOKEN through the RGA,+// while its `marks` and `notes` — which are CHARACTER OFFSETS INTO THAT+// TEXT — merge as ordinary last-writer-wins registers. Two independent+// merge domains describing one paragraph. Two perfectly legal concurrent+// edits (you bold a phrase, I type a sentence before it) can therefore+// converge on a state every replica agrees about, in which the bold covers+// the wrong words or runs past the end of the text.+//+// That is the exact shape of the `parent`-versus-position problem spaces+// has, and like that one it is a FORMAT-LEVEL decision, not a bug to patch+// inside a rig. So it is MEASURED and REPORTED as data rather than+// asserted — with STRICT=1 to turn it into a gate the day the decision is+// taken.+//+// The engine is the kernel's, bound to ('body', null, 'text'). Nothing here is+// type app code beyond the binding and the model's own helpers.++import { SyncEngine } from '../kernel/src/sync/crdt.ts';+import { mulberry32, baseDoc, randomMutation, type Doc } from './lib/sync-fixtures-type.ts';+import { parseDoc, spliceText, type Block } from '../type/src/model.ts';++// The binding lives with the APP, never in the rig: two definitions of a+// frozen format constant is how a fork starts. (`export … from` does not bind+// the name locally and this rig uses it, so it is imported and re-exported.)+import { TYPE_SHAPE } from '../type/src/sync/crdt.ts';+export { TYPE_SHAPE };+class TypeSync extends SyncEngine {+ constructor(actor: string) { super(actor, TYPE_SHAPE); }+}++const SEEDS = parseInt(process.env.SEEDS ?? '120', 10);+const STEPS = parseInt(process.env.STEPS ?? '60', 10);+const ACTORS = parseInt(process.env.ACTORS ?? '3', 10);+const STRICT = process.env.STRICT === '1';++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 clone = <T,>(v: T): T => JSON.parse(JSON.stringify(v));++/**+ * Value equality, independent of JSON key order.+ *+ * What a CRDT promises is that replicas agree on the VALUE. Key order is not+ * part of that: a property deleted and re-added moves to the end of its+ * object, so two replicas that applied the same removals in a different order+ * hold equal documents whose `JSON.stringify` differs. Comparing raw strings+ * reports those as divergence — 28 of 120 seeds here, all of them spurious.+ *+ * Measured, not assumed, before relying on it: bento/type signs a canonical+ * digest (canon.ts sorts keys per RFC 8785 §3.2.3), and two blocks differing+ * only in key order produce the SAME digest. So key order reaches neither the+ * signature chain nor the redline, which aligns on block id.+ */+const canon = (v: unknown): unknown =>+ Array.isArray(v) ? v.map(canon)+ : (v && typeof v === 'object')+ ? Object.fromEntries(Object.keys(v as object).sort().map(k => [k, canon((v as Record<string, unknown>)[k])]))+ : v;+const same = (a: unknown, b: unknown) => JSON.stringify(canon(a)) === JSON.stringify(canon(b));++class Replica {+ doc: Doc;+ state: TypeSync;+ shadow: string;+ constructor(actor: string, doc: Doc) {+ this.doc = doc;+ this.state = new TypeSync(actor);+ this.state.adopt(this.doc as never);+ this.shadow = JSON.stringify(this.doc);+ }+ mutate(fn: () => void) {+ fn();+ return this.flush();+ }+ flush() {+ const ops = this.state.diff(JSON.parse(this.shadow), this.doc as never, { text: true });+ this.shadow = JSON.stringify(this.doc);+ return ops;+ }+ receive(ops: unknown[]) {+ this.state.apply(this.doc as never, ops as never);+ this.shadow = JSON.stringify(this.doc);+ }+}++// ---------------------------------------------------------------------------+// the format's invariants, checked on a MERGED document+// ---------------------------------------------------------------------------++interface Violations {+ markOutOfRange: number; // a mark reaching past the end of the text it indexes+ markInverted: number; // from > to+ noteOutOfRange: number; // a footnote anchored past the end of its paragraph+ danglingNote: number; // a reference whose footnote body is not in the map+ dupBlockId: number; // the redline aligns on block id — duplicates break it+ emptyBody: number; // a document with no blocks at all+}+const ZERO = (): Violations => ({+ markOutOfRange: 0, markInverted: 0, noteOutOfRange: 0,+ danglingNote: 0, dupBlockId: 0, emptyBody: 0,+});++function inspect(doc: Doc): Violations {+ const v = ZERO();+ if (!Array.isArray(doc.body) || doc.body.length === 0) v.emptyBody++;+ const seen = new Set<string>();+ for (const b of doc.body ?? []) {+ if (seen.has(b.id)) v.dupBlockId++;+ seen.add(b.id);+ const len = (b.text ?? '').length;+ for (const m of b.marks ?? []) {+ if (m.from > m.to) v.markInverted++;+ else if (m.to > len || m.from < 0) v.markOutOfRange++;+ }+ for (const n of b.notes ?? []) {+ if (n.at > len || n.at < 0) v.noteOutOfRange++;+ if (doc.footnotes?.[n.id] === undefined) v.danglingNote++;+ }+ }+ return v;+}+const total = (v: Violations) => Object.values(v).reduce((a, b) => a + b, 0);++// ---------------------------------------------------------------------------+// the run+// ---------------------------------------------------------------------------++console.log('bento/type under the shared CRDT engine\n');++const worst = ZERO();+const seedsWith = ZERO();+let seedsWithViolations = 0;+let diverged = 0;+let keyOrderOnly = 0;+let opsTotal = 0;+let soloBroken = 0;+let measured = 0;+let unparseable = 0;++for (let seed = 1; seed <= SEEDS; seed++) {+ const rnd = mulberry32(seed * 7919);+ const base = baseDoc(mulberry32(seed * 104729));+ const reps = Array.from({ length: ACTORS }, (_, i) => new Replica(`a${i}`, clone(base)));+ // a lone replica running actor 0's edits and receiving nothing — the control+ const solo = new Replica('solo', clone(base));+ const queues = new Map<string, unknown[][]>();+ for (let f = 0; f < ACTORS; f++) for (let t = 0; t < ACTORS; t++) if (f !== t) queues.set(`${f}>${t}`, []);++ for (let s = 0; s < STEPS; s++) {+ if (rnd() < 0.6) {+ const a = Math.floor(rnd() * ACTORS);+ const mseed = (seed * 1_000_003 + s * 7919) >>> 0;+ if (a === 0) solo.mutate(() => randomMutation(solo.doc, mulberry32(mseed), 's'));+ const ops = reps[a].mutate(() => randomMutation(reps[a].doc, mulberry32(mseed), `a${a}`));+ opsTotal += ops.length;+ if (ops.length) for (let t = 0; t < ACTORS; t++) if (t !== a) queues.get(`${a}>${t}`)!.push(ops);+ } else {+ const keys = [...queues.keys()].filter(k => queues.get(k)!.length);+ if (!keys.length) continue;+ const k = keys[Math.floor(rnd() * keys.length)];+ reps[parseInt(k.split('>')[1], 10)].receive(queues.get(k)!.shift()!);+ }+ }+ // drain everything+ let guard = 0;+ for (;;) {+ const k = [...queues.keys()].find(x => queues.get(x)!.length);+ if (!k || guard++ > 10000) break;+ reps[parseInt(k.split('>')[1], 10)].receive(queues.get(k)!.shift()!);+ }++ const first = JSON.stringify(reps[0].doc);+ let orderOnly = false;+ for (let i = 1; i < ACTORS; i++) {+ if (JSON.stringify(reps[i].doc) === first) continue;+ if (same(reps[0].doc, reps[i].doc)) { orderOnly = true; continue; }+ diverged++;+ if (diverged === 1) console.log(` FAIL seed ${seed}: replicas a0 and a${i} disagree in VALUE`);+ break;+ }+ if (orderOnly) keyOrderOnly++;++ // THE CONTROL, and the measurement below is worthless without it. If the+ // GENERATOR produced illegal documents, every violation would be its fault+ // rather than the merge's — so the solo replica, driven by the same edits+ // and receiving nothing, must be spotless. Seeds where it is not are+ // excluded rather than counted, which is a stronger basis than "every+ // generator bug we happened to notice has been fixed".+ if (total(inspect(solo.doc)) > 0) { soloBroken++; continue; }+ measured++;++ // Does the merged document still PARSE as bento/type? Convergence on+ // something the app would reject is a different and worse failure than+ // convergence on something it merely renders oddly.+ const parsed = parseDoc(JSON.stringify(reps[0].doc));+ if (!parsed.ok) unparseable++;++ const v = inspect(reps[0].doc);+ if (total(v) > 0) {+ seedsWithViolations++;+ for (const k of Object.keys(worst) as Array<keyof Violations>) {+ worst[k] = Math.max(worst[k], v[k]);+ if (v[k] > 0) seedsWith[k]++;+ }+ }+}++console.log(`${SEEDS} seeds × ${STEPS} steps × ${ACTORS} actors — ${opsTotal} ops\n`);++ok(diverged === 0, `all replicas converge in value (${diverged} seed(s) diverged)`);+console.log(` note ${keyOrderOnly} seed(s) converged on equal documents whose JSON KEY ORDER differs` ++ ' — a property deleted and re-added moves to the end of its object.');+console.log(' Benign here and checked rather than assumed: canon.ts sorts keys, so the');+console.log(' signing digest is identical, and the redline aligns on block id.');+ok(unparseable === 0, `every merged document still parses as bento/type (${unparseable} rejected)`);+ok(soloBroken === 0,+ `the generator itself produces legal documents (${soloBroken} seed(s) excluded as unsound)`);++// ---- the offset-domain report ----------------------------------------------+console.log('\n --- marks and notes are offsets into RGA-merged text ---');+console.log(` measured on ${measured} seed(s) with a provably clean control`);+console.log(` seeds converging on a document with at least one violation: ${seedsWithViolations}` ++ ` (${((seedsWithViolations / Math.max(1, measured)) * 100).toFixed(1)}%)`);+for (const k of Object.keys(worst) as Array<keyof Violations>) {+ console.log(` ${k.padEnd(16)} seeds: ${String(seedsWith[k]).padStart(4)} worst in one document: ${worst[k]}`);+}++if (STRICT) {+ ok(seedsWithViolations === 0,+ `STRICT: no merged document violates the format (${seedsWithViolations} seed(s) did)`);+} else {+ console.log('\n Reported, not asserted: whether an offset that no longer describes its');+ console.log(' text is a defect to fix in the model or a cost to accept is a FORMAT');+ console.log(' decision nobody has taken. STRICT=1 turns this into a gate the day it is.');+}++// ---------------------------------------------------------------------------+// a legible example of the same thing, so the statistic is not the only account+// ---------------------------------------------------------------------------+console.log('\n=== what that looks like on one paragraph ===');+{+ // Constructed so the outcome does NOT depend on who wins the register race.+ // BOTH authors insert text BEFORE the bold and both correctly shift their own+ // marks with the app's own spliceText. The merged TEXT contains both+ // insertions, so the correct offset is shifted by both — a number neither+ // replica ever held. Whichever mark set wins, it is wrong.+ //+ // (An earlier version of this example had one author type at the start and+ // the other only re-bold. It converged on the RIGHT answer and demonstrated+ // nothing, while reading as though it had.)+ const TEXT = 'Payment is due within 30 days.';+ const TERM = '30 days';+ const mk = (): Doc => ({+ format: 'bento/type', version: 1, docId: 'd', title: 'T',+ page: { width: 816, height: 1056, marginX: 104, marginTop: 104, marginBottom: 104 },+ body: [{ id: 'p1', kind: 'para', text: TEXT,+ marks: [{ t: 'b', from: TEXT.indexOf(TERM), to: TEXT.indexOf(TERM) + TERM.length }] } as Block],+ footnotes: {}, revisions: [], signatures: [],+ } as unknown as Doc);++ const A = new Replica('alice', mk());+ const B = new Replica('bob', mk());+ const covered = (d: Doc) => {+ const b = d.body[0];+ const m = b.marks?.[0];+ return m ? b.text.slice(m.from, m.to) : '(none)';+ };+ console.log(` before: ${JSON.stringify(A.doc.body[0].text)}`);+ console.log(` bold covers ${JSON.stringify(covered(A.doc))}`);++ const opsA = A.mutate(() => { A.doc.body[0] = spliceText(A.doc.body[0], 0, 0, 'Under clause 4, '); });+ const opsB = B.mutate(() => { B.doc.body[0] = spliceText(B.doc.body[0], 0, 0, 'Notwithstanding the above, '); });+ console.log(` alice types a prefix, and her bold correctly follows it to ${JSON.stringify(covered(A.doc))}`);+ console.log(` bob types a different prefix, and his follows to ${JSON.stringify(covered(B.doc))}`);++ A.receive(opsB);+ B.receive(opsA);+ ok(same(A.doc, B.doc), 'the two replicas converge');+ const merged = A.doc.body[0].text;+ console.log(` merged text: ${JSON.stringify(merged)}`);+ console.log(` bold covers: ${JSON.stringify(covered(A.doc))} (it should cover ${JSON.stringify(TERM)})`);+ ok(merged.includes('Under clause 4') && merged.includes('Notwithstanding the above'),+ 'both insertions survive — the TEXT merged correctly, token by token');+ console.log(` The text merged; the offsets describing it did not. Neither replica ever`);+ console.log(` held the correct offset, so no register winner could have been right.`);+}++console.log(`\n${checks - failures}/${checks} checks passed`);+if (failures) process.exit(1);diff --git a/scripts/test-type-inline.ts b/scripts/test-type-inline.tsnew file mode 100644index 00000000..1c2902f0--- /dev/null+++ b/scripts/test-type-inline.ts@@ -0,0 +1,223 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/type inline-formatting rig.+//+// node scripts/test-type-inline.ts (Node ≥ 23.6 strips types natively)+//+// WHAT THIS PROVES. `type/src/inline.ts` stores plain text plus marks over+// character ranges, and renders HTML from it. Everything downstream of the+// model — the word-level redline, the canonical form a signature covers, the+// caret's model position, and footnote anchors — assumes that spine is exact.+//+// So the load-bearing property is the ROUND TRIP:+//+// fromDom(parse(toHtml(text, marks))) == { text, marks }+//+// If it does not hold, formatting silently mutates every time a block is+// re-rendered — which is invisible until a signed document stops verifying, or+// a redline reports a change nobody made.+//+// The rig carries its own 40-line HTML parser rather than a DOM dependency,+// because the round trip has to be checkable in CI, and a property only+// checked in a browser is a property nobody checks.++import {+ normalize, coversAll, activeAt, addMark, removeMark, toggleMark, shift,+ toHtml, fromDom, type Mark,+} from '../type/src/inline.ts';++let checks = 0, failures = 0;+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };+const H = (s: string) => console.log(`\n=== ${s} ===`);+const J = (v: unknown) => JSON.stringify(v);++// ───────────────────────────────────────────── a minimal DOM, for the parser+interface TNode { nodeType: 3; nodeValue: string; childNodes: TNode[] }+interface ENode { nodeType: 1; tagName: string; attrs: Record<string, string>;+ childNodes: Array<TNode | ENode>; getAttribute(n: string): string | null }+type AnyNode = TNode | ENode;++const VOID = new Set(['br', 'img', 'hr']);+function parse(html: string): ENode {+ const root: ENode = { nodeType: 1, tagName: 'DIV', attrs: {}, childNodes: [], getAttribute: () => null };+ const stack: ENode[] = [root];+ const re = /<\/?([a-zA-Z][a-zA-Z0-9]*)((?:\s+[a-zA-Z-]+="[^"]*")*)\s*\/?>/g;+ let last = 0, m: RegExpExecArray | null;+ const text = (s: string) => {+ if (!s) return;+ const decoded = s.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');+ stack[stack.length - 1].childNodes.push({ nodeType: 3, nodeValue: decoded, childNodes: [] });+ };+ while ((m = re.exec(html))) {+ text(html.slice(last, m.index));+ last = re.lastIndex;+ const tag = m[1].toLowerCase();+ if (m[0][1] === '/') { if (stack.length > 1) stack.pop(); continue; }+ const attrs: Record<string, string> = {};+ for (const a of (m[2] ?? '').matchAll(/([a-zA-Z-]+)="([^"]*)"/g)) attrs[a[1]] = a[2];+ const el: ENode = { nodeType: 1, tagName: tag.toUpperCase(), attrs, childNodes: [],+ getAttribute(n) { return this.attrs[n] ?? null; } };+ stack[stack.length - 1].childNodes.push(el);+ if (!VOID.has(tag)) stack.push(el);+ }+ text(html.slice(last));+ return root;+}+// sanity: the parser itself must be right, or every result below is noise+{+ const p = parse('a<strong>b<em>c</em></strong>d');+ const kinds = p.childNodes.map(n => n.nodeType === 3 ? 't' : (n as ENode).tagName);+ if (J(kinds) !== J(['t', 'STRONG', 't'])) { console.log(' FAIL the rig\'s own parser is broken'); process.exit(1); }+}++const roundTrip = (text: string, marks: Mark[]) => {+ const html = toHtml(text, marks);+ const back = fromDom(parse(html) as unknown as Node);+ return { html, text: back.text, marks: back.marks };+};++// ───────────────────────────────────────────────────────────── normalize+H('normalize gives one representation of any formatting');+{+ const t = 'abcdefghij';+ ok(J(normalize([{ t: 'b', from: 5, to: 8 }, { t: 'b', from: 0, to: 3 }], t.length))+ === J([{ t: 'b', from: 0, to: 3 }, { t: 'b', from: 5, to: 8 }]), 'marks come back sorted');+ ok(normalize([{ t: 'b', from: 0, to: 4 }, { t: 'b', from: 4, to: 8 }], t.length).length === 1,+ 'touching marks of the same kind merge');+ ok(normalize([{ t: 'b', from: 0, to: 6 }, { t: 'b', from: 3, to: 8 }], t.length)[0].to === 8,+ 'overlapping marks of the same kind merge');+ ok(normalize([{ t: 'b', from: 3, to: 3 }], t.length).length === 0, 'an empty mark is dropped');+ ok(normalize([{ t: 'b', from: 5, to: 999 }], t.length)[0].to === 10, 'marks are clamped to the text');+ ok(normalize([{ t: 'b', from: 0, to: 4 }, { t: 'i', from: 0, to: 4 }], t.length).length === 2,+ 'different kinds do NOT merge');+ ok(normalize([{ t: 'link', from: 0, to: 4, href: 'a' }, { t: 'link', from: 4, to: 8, href: 'b' }], t.length).length === 2,+ 'links with different targets do not merge');+}++// ─────────────────────────────────────────────────────────── toggle/remove+H('toggle behaves the way ⌘B does');+{+ const t = 'the quick brown fox';+ let m: Mark[] = [];+ m = toggleMark(m, t.length, 4, 9, 'b');+ ok(J(m) === J([{ t: 'b', from: 4, to: 9 }]), 'toggling an unmarked range marks it');+ m = toggleMark(m, t.length, 4, 9, 'b');+ ok(m.length === 0, 'toggling it again clears it');+ m = toggleMark([], t.length, 0, 19, 'b');+ m = toggleMark(m, t.length, 4, 9, 'b');+ ok(J(m) === J([{ t: 'b', from: 0, to: 4 }, { t: 'b', from: 9, to: 19 }]),+ 'clearing the middle of a marked run splits it');+ ok(coversAll([{ t: 'b', from: 0, to: 4 }, { t: 'b', from: 4, to: 9 }], 0, 9, 'b'),+ 'two adjacent marks together cover the range');+ ok(!coversAll([{ t: 'b', from: 0, to: 4 }, { t: 'b', from: 5, to: 9 }], 0, 9, 'b'),+ 'a gap means the range is not fully covered');+ ok(J([...activeAt([{ t: 'b', from: 2, to: 6 }], 4)]) === J(['b']), 'activeAt reports what the caret sits in');+}++// ────────────────────────────────────────────────────────────────── shift+H('marks follow an edit — the same rule footnote anchors use');+{+ const t = 'Payment is due within 30 days of invoice.';+ const bold: Mark[] = [{ t: 'b', from: 22, to: 29 }]; // "30 days"+ ok(J(shift(bold, 0, 8, 3, t.length)) === J([{ t: 'b', from: 17, to: 24 }]),+ 'an edit BEFORE a mark moves it by the delta');+ ok(J(shift(bold, 30, 5, 5, t.length)) === J(bold), 'an edit after a mark leaves it alone');+ ok(shift(bold, 22, 7, 0, t.length).length === 0, 'a mark whose text is deleted is dropped');+ const straddle: Mark[] = [{ t: 'b', from: 0, to: 30 }];+ const after = shift(straddle, 22, 7, 20, t.length + 13);+ ok(after[0].from === 0 && after[0].to === 43,+ `a mark straddling the edit is clipped, not dropped (0–${after[0].to})`);+}++// ─────────────────────────────────────────────────────────── the round trip+H('THE round trip: render then read back');+{+ const cases: Array<[string, Mark[]]> = [+ ['plain text with no marks', []],+ ['bold at the start', [{ t: 'b', from: 0, to: 4 }]],+ ['bold at the very end', [{ t: 'b', from: 12, to: 20 }]],+ ['nested bold and italic', [{ t: 'b', from: 0, to: 20 }, { t: 'i', from: 5, to: 12 }]],+ ['partially overlapping runs', [{ t: 'b', from: 0, to: 12 }, { t: 'i', from: 6, to: 20 }]],+ ['adjacent different marks', [{ t: 'b', from: 0, to: 8 }, { t: 'i', from: 8, to: 16 }]],+ ['three marks over one run', [{ t: 'b', from: 2, to: 18 }, { t: 'i', from: 4, to: 16 }, { t: 'u', from: 6, to: 14 }]],+ ['a link', [{ t: 'link', from: 2, to: 10, href: 'https://example.invalid/a' }]],+ ['a link inside bold', [{ t: 'b', from: 0, to: 20 }, { t: 'link', from: 4, to: 12, href: '#x' }]],+ ['code', [{ t: 'code', from: 5, to: 9 }]],+ ['strike', [{ t: 's', from: 1, to: 7 }]],+ ];+ for (const [label, marks] of cases) {+ const text = 'The quick brown fox jumps.';+ const r = roundTrip(text, marks);+ const want = normalize(marks, text.length);+ ok(r.text === text && J(r.marks) === J(want),+ `${label} — ${r.text === text ? '' : 'TEXT CHANGED; '}${J(r.marks) === J(want) ? '' : `marks ${J(r.marks)} ≠ ${J(want)}; `}${r.html.length} chars`);+ }+}++H('the round trip survives characters that mean something in HTML');+{+ for (const text of ['a < b && c > d', 'quotes "here" and ‘there’', '5 < 6 & 7 > 6',+ 'em—dash, ellipsis…, ampersand & more']) {+ const marks: Mark[] = [{ t: 'b', from: 2, to: Math.min(8, text.length) }];+ const r = roundTrip(text, marks);+ ok(r.text === text, `“${text.slice(0, 22)}…” survives escaping (got “${r.text.slice(0, 22)}…”)`);+ }+}++H('unknown markup contributes text and no formatting');+{+ const back = fromDom(parse('a<script>bad()</script>b<span class="x">c</span>') as unknown as Node);+ ok(!/</.test(back.text), 'no markup leaks into the text');+ ok(back.marks.length === 0, 'no marks are invented from tags the model has no word for');+ ok(back.text.includes('b') && back.text.includes('c'), 'the text inside unknown tags is kept');+}++// ─────────────────────────────────────────────────── idempotence + stability+H('stability — the properties the signature depends on');+{+ const text = 'The quick brown fox jumps.';+ const marks: Mark[] = [{ t: 'b', from: 0, to: 12 }, { t: 'i', from: 6, to: 20 }];+ const once = roundTrip(text, marks);+ const twice = roundTrip(once.text, once.marks);+ ok(J(once.marks) === J(twice.marks) && once.html === twice.html,+ 'a second round trip changes nothing (idempotent)');+ ok(J(normalize([...marks].reverse(), text.length)) === J(normalize(marks, text.length)),+ 'the order marks were authored in does not affect the stored form');+}++// ──────────────────────────────────────────────────────────────── fuzz+// Hand-picked cases test the shapes you thought of. The bug this rig already+// caught — a mark silently truncated when another one overlapped it — was in+// the list only because it was written down as a known-hard case. Random marks+// cover the ones nobody wrote down.+H('fuzz: 2,000 random mark sets round-trip exactly');+{+ let seed = 0x5eed;+ const rnd = () => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff);+ const KINDS: MarkType[] = ['b', 'i', 'u', 's', 'code', 'link'];+ const TEXT = 'The quick brown fox jumps over the lazy dog & <friends> too.';+ let bad = 0, worst = '';+ for (let n = 0; n < 2000; n++) {+ const count = 1 + ((rnd() * 5) | 0);+ const marks: Mark[] = [];+ for (let i = 0; i < count; i++) {+ const a = (rnd() * TEXT.length) | 0, b = (rnd() * TEXT.length) | 0;+ const t = KINDS[(rnd() * KINDS.length) | 0];+ const from = Math.min(a, b), to = Math.max(a, b);+ if (to <= from) continue;+ marks.push(t === 'link' ? { t, from, to, href: '#' + i } : { t, from, to });+ }+ const want = normalize(marks, TEXT.length);+ const r = roundTrip(TEXT, marks);+ if (r.text !== TEXT || J(r.marks) !== J(want)) {+ bad++;+ if (!worst) worst = `in ${J(want)}\n out ${J(r.marks)}\n html ${r.html}`;+ }+ }+ ok(bad === 0, `2,000 random mark sets survive the round trip (${bad} failed)`);+ if (bad) console.log(` ${worst}`);+}++console.log(`\n${checks - failures}/${checks} checks passed`);+if (failures) process.exit(1);diff --git a/scripts/test-type-model.ts b/scripts/test-type-model.tsnew file mode 100644index 00000000..0f968e74--- /dev/null+++ b/scripts/test-type-model.ts@@ -0,0 +1,132 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/type model rig. node scripts/test-type-model.ts+//+// Two properties, both of which fail SILENTLY and neither of which a shipped+// file can be talked out of once it exists:+//+// 1. THE LOAD CONTRACT. An unreadable document must never be replaced by an+// empty one. bento/spaces learned this the expensive way — a parse that+// returned null let the caller fall back to a starter, so opening a file+// from another app presented an empty document over live data, and the+// first save wrote it to disk. Only an ABSENT or EMPTY block may start a+// new document; everything else is an error the user gets told about.+//+// 2. OFFSETS MOVE TOGETHER. Marks and footnote anchors are offsets into the+// same string. Code that updates one and not the other is what put a+// footnote marker in the middle of a word during the spike, so there is+// one function that moves both and this pins it.++import { parseDoc, spliceText, emptyDoc, FORMAT, plainText, wordCount, type Block } from '../type/src/model.ts';++let checks = 0, failures = 0;+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };+const H = (s: string) => console.log(`\n=== ${s} ===`);+const J = (v: unknown) => JSON.stringify(v);++const doc = (over: Record<string, unknown> = {}) => JSON.stringify({+ format: FORMAT, version: 1, docId: 'doc-1', title: 'T',+ body: [{ id: 'p1', kind: 'para', text: 'Hello world.' }],+ footnotes: {}, revisions: [], signatures: [], ...over,+});++H('the load contract — an unreadable file never becomes an empty one');+{+ ok(parseDoc('').ok === false && (parseDoc('') as { err: string }).err === 'empty',+ 'an empty block is the ONLY path to a new document');+ ok((parseDoc(' \n ') as { err: string }).err === 'empty', 'whitespace counts as empty');++ const bad = parseDoc('{not json');+ ok(!bad.ok && bad.err === 'json', 'malformed JSON is an error, not a fresh document');++ const slides = parseDoc(JSON.stringify({ format: 'bento/slides', slides: [] }));+ ok(!slides.ok && slides.err === 'format', 'a slides file is refused');+ ok(!slides.ok && slides.err === 'format' && slides.found === 'bento/slides',+ 'and the refusal names the format it actually found, so the message can be useful');++ const noBody = parseDoc(JSON.stringify({ format: FORMAT }));+ ok(!noBody.ok && noBody.err === 'shape', 'a document with no body is refused');++ const good = parseDoc(doc());+ ok(good.ok && good.doc.body.length === 1, 'a well-formed document loads');+}++H('repairs are derived from the bytes, so every reader agrees');+{+ const dup = parseDoc(doc({ body: [+ { id: 'p1', kind: 'para', text: 'one' },+ { id: 'p1', kind: 'para', text: 'two' },+ ] }));+ ok(dup.ok && dup.doc.body[0].id !== dup.doc.body[1].id, 'duplicate ids are made unique');+ ok(dup.ok && dup.doc.body[1].id === 'p1~1',+ 'the repair is positional, so two readers of these bytes produce the SAME ids');+ ok(dup.ok && dup.repaired.some(r => /duplicate id/.test(r)), 'and the repair is reported');++ const weird = parseDoc(doc({ body: [{ id: 'x', kind: 'marquee', text: 'hi' }] }));+ ok(weird.ok && weird.doc.body[0].kind === 'para', 'an unknown block kind reads as a paragraph');++ const orphan = parseDoc(doc({+ body: [{ id: 'p1', kind: 'para', text: 'Hello world.', notes: [{ id: 'gone', at: 5 }] }],+ footnotes: {},+ }));+ ok(orphan.ok && !orphan.doc.body[0].notes,+ 'a footnote reference with no note behind it is dropped, and the text kept');++ const overflow = parseDoc(doc({+ body: [{ id: 'p1', kind: 'para', text: 'short', marks: [{ t: 'b', from: 0, to: 999 }] }],+ }));+ ok(overflow.ok && overflow.doc.body[0].marks![0].to === 5, 'marks past the end are clamped');+}++H('unknown fields survive — format additivity (PLATFORM §3)');+{+ const r = parseDoc(doc({ somethingNewer: { a: 1 }, body: [{ id: 'p1', kind: 'para', text: 'x' }] }));+ ok(r.ok && J((r.doc as Record<string, unknown>).somethingNewer) === J({ a: 1 }),+ 'a field this build does not know is preserved, not dropped');+}++H('marks and footnote anchors move together');+{+ const b: Block = {+ id: 'p1', kind: 'para',+ text: 'Payment is due within 30 days of invoice, without set-off.',+ marks: [{ t: 'b', from: 22, to: 29 }], // "30 days"+ notes: [{ id: 'n1', at: 58 }], // after the full stop+ };+ // counsel rewrites the term: "30 days" → "sixty (60) calendar days"+ const at = b.text.indexOf('30 days');+ const next = spliceText(b, at, '30 days'.length, 'sixty (60) calendar days');++ ok(next.text.includes('sixty (60) calendar days'), 'the text is replaced');+ const mark = next.marks![0];+ ok(next.text.slice(mark.from, mark.to) === 'sixty (60) calendar days',+ `the bold still covers the term it was put on (“${next.text.slice(mark.from, mark.to)}”)`);+ ok(next.notes![0].at === next.text.length,+ 'the footnote anchor moved with the text after it, and still sits at the end');++ const before = spliceText(b, 0, 7, 'Fees'); // edit BEFORE both+ ok(before.marks![0].from === 22 - 3, 'an earlier edit shifts the mark by the delta');+ ok(before.notes![0].at === 58 - 3, 'and shifts the anchor by the same delta');++ const wipe = spliceText(b, 22, 7, ''); // delete the marked words+ ok(!wipe.marks, 'a mark whose text is deleted is dropped, not left dangling');++ const inside: Block = { ...b, notes: [{ id: 'n1', at: 24 }] }; // anchor INSIDE "30 days"+ ok(!spliceText(inside, 22, 7, 'sixty').notes,+ 'an anchor inside deleted text is dropped rather than landing mid-word');+}++H('odds and ends');+{+ const d = emptyDoc();+ ok(d.docId && d.body.length === 1 && d.format === FORMAT, 'emptyDoc is well formed');+ ok(emptyDoc().docId !== emptyDoc().docId, 'each new document gets its own identity');+ const r = parseDoc(doc({ body: [+ { id: 'a', kind: 'h2', text: 'Heading' }, { id: 'b', kind: 'para', text: 'two words' }] }));+ ok(r.ok && wordCount(r.doc) === 3, 'word count counts across blocks');+ ok(r.ok && plainText(r.doc) === 'Heading\ntwo words', 'plain text joins blocks with newlines');+}++console.log(`\n${checks - failures}/${checks} checks passed`);+if (failures) process.exit(1);diff --git a/scripts/test-type-print.ts b/scripts/test-type-print.tsnew file mode 100644index 00000000..75a69574--- /dev/null+++ b/scripts/test-type-print.ts@@ -0,0 +1,133 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/type paginated-output rig. node scripts/test-type-print.ts+//+// `buildPrintDocument` is pure: document + metrics in, HTML out. So the+// structural promises are checkable without a browser, and they are the ones+// the design leans on:+//+// · the printed page count is the one the editor computed — if print+// re-paginates, "page 14 paragraph 3" stops meaning anything, which is the+// entire reason a document like this is exchanged as PDF at all;+// · every page shows a WINDOW onto one shared flow, offset by that page's+// start. Slicing content per page would re-lay-out each fragment, and+// re-layout is exactly how printed pagination drifts from the screen;+// · a footnote appears on the page its reference lands on, numbered in+// document order;+// · the page box is sized from the DOCUMENT's geometry, so a document set to+// A4 prints A4.+//+// Line-level fidelity (that the print flow breaks lines identically to the+// editor) needs real layout and is verified in the browser: measured at zero+// drift across 222 lines and 8 pages.++import { buildPrintDocument } from '../type/src/print.ts';+import { emptyDoc, LETTER, type TypeDoc } from '../type/src/model.ts';+import type { Metrics } from '../type/src/paginate.ts';++let checks = 0, failures = 0;+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };+const H = (s: string) => console.log(`\n=== ${s} ===`);++function fixture(): { doc: TypeDoc; metrics: Metrics } {+ const doc = emptyDoc();+ doc.title = 'Master Services Agreement';+ doc.body = [+ { id: 'h1', kind: 'h1', text: 'Master Services Agreement' },+ { id: 'p1', kind: 'para', text: 'The parties agree as follows.',+ notes: [{ id: 'n1', at: 28 }] },+ { id: 'p2', kind: 'para', text: 'Payment is due within 30 days.',+ marks: [{ t: 'b', from: 22, to: 29 }], notes: [{ id: 'n2', at: 30 }] },+ { id: 'p3', kind: 'para', text: 'Governed by the laws of Sweden.' },+ ];+ doc.footnotes = { n1: 'The first note.', n2: 'The second note, a little longer.' };+ const metrics: Metrics = {+ ms: 0,+ pages: [+ { n: 1, start: 0, end: 700, notes: ['n1'], reserved: 30 },+ { n: 2, start: 700, end: 1400, notes: ['n2'], reserved: 34 },+ { n: 3, start: 1400, end: Infinity, notes: [], reserved: 0 },+ ],+ };+ return { doc, metrics };+}++H('the printed pagination is the computed one');+{+ const { doc, metrics } = fixture();+ const html = buildPrintDocument(doc, metrics);+ const pages = html.match(/class="t-page"/g)?.length ?? 0;+ ok(pages === metrics.pages.length, `one page box per computed page (${pages} of ${metrics.pages.length})`);++ // each page offsets the SAME flow rather than slicing it+ const offsets = [...html.matchAll(/class="t-body" style="margin-top:(-?\d+)px"/g)].map(m => +m[1]);+ ok(offsets.length === metrics.pages.length, 'every page carries the flow');+ ok(offsets.join() === metrics.pages.map(p => -p.start).join(),+ `each page is offset by its own start (${offsets.join(', ')})`);++ // the window is the page's real extent, so it cannot cut a line in half+ const heights = [...html.matchAll(/class="t-flow" style="height:([\d.]+)px/g)].map(m => +m[1]);+ ok(heights[0] === 700 && heights[1] === 700,+ `interior pages are clipped at their break, not a nominal height (${heights[0]}, ${heights[1]})`);+ const contentH = LETTER.height - LETTER.marginTop - LETTER.marginBottom;+ ok(heights[2] === contentH - 0, `the last page has no break, so it runs to the content height (${heights[2]})`);+}++H('footnotes go to the foot of the page their reference lands on');+{+ const { doc, metrics } = fixture();+ const html = buildPrintDocument(doc, metrics);+ const sections = html.split('class="t-page"').slice(1);+ ok(sections[0].includes('The first note.'), 'page 1 carries note 1');+ ok(sections[1].includes('The second note'), 'page 2 carries note 2');+ ok(!sections[2].includes('t-fn'), 'page 3 has no note area, because no reference lands there');+ ok(!/sidenote/.test(html), 'the editing view’s sidenotes do not leak into print');+ // numbering is derived in document order, not stored+ ok(/<b>1<\/b>The first note/.test(html) && /<b>2<\/b>The second note/.test(html),+ 'notes are numbered in document order');+}++H('the page box comes from the document');+{+ const { doc, metrics } = fixture();+ const a4 = { ...doc, page: { width: 794, height: 1123, marginX: 96, marginTop: 96, marginBottom: 96 } };+ const html = buildPrintDocument(a4 as TypeDoc, metrics);+ ok(/@page \{ size: 794px 1123px/.test(html), 'an A4 document prints A4');+ ok(/width: 794px; height: 1123px/.test(html), 'and the page box matches');+ const letter = buildPrintDocument(doc, metrics);+ ok(/@page \{ size: 816px 1056px/.test(letter), 'a Letter document prints Letter');+}++H('running head and page numbers');+{+ const { doc, metrics } = fixture();+ const plain = buildPrintDocument(doc, metrics);+ ok((plain.match(/t-run head/g) ?? []).length === 3, 'a running head on every page');+ ok(plain.includes('>Master Services Agreement</div>'), 'the head defaults to the document title');+ ok((plain.match(/t-run foot/g) ?? []).length === 3, 'a page number on every page');++ const custom = buildPrintDocument(doc, metrics, { header: 'Draft — privileged', pageNumbers: false });+ ok(custom.includes('Draft — privileged'), 'the head can be overridden');+ ok(!/t-run foot/.test(custom), 'page numbers can be turned off');++ const bare = buildPrintDocument(doc, metrics, { bareFirstPage: true });+ const first = bare.split('class="t-page"')[1];+ ok(!first.includes('t-run head'), 'a bare first page carries no running head');+ ok(bare.split('class="t-page"')[2].includes('t-run head'), 'but page 2 still does');+}++H('content is escaped, and formatting survives');+{+ const { doc, metrics } = fixture();+ doc.body[3].text = 'Clause <script>alert(1)</script> & "quoted".';+ doc.title = 'A & B <Ltd>';+ const html = buildPrintDocument(doc, metrics);+ ok(!/<script>alert/.test(html), 'author text cannot introduce a script tag');+ ok(html.includes('&') && html.includes('<'), 'ampersands and angle brackets are escaped');+ ok(/<title>A & B <Ltd><\/title>/.test(html), 'the title is escaped too');+ ok(/<strong>30 days<\/strong>/.test(html), 'marks render as formatting, from the same renderer the editor uses');+}++console.log(`\n${checks - failures}/${checks} checks passed`);+if (failures) process.exit(1);diff --git a/scripts/test-type-redline.ts b/scripts/test-type-redline.tsnew file mode 100644index 00000000..30ef227b--- /dev/null+++ b/scripts/test-type-redline.ts@@ -0,0 +1,160 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/type redline rig. node scripts/test-type-redline.ts+//+// The two invariants everything rests on:+// accept(all) == the document they sent back+// reject(all) == the document you sent+// If either fails, "review these changes" is a lie, because the reviewer's+// choices do not add up to either endpoint.+//+// The fixture is built to be able to FAIL. An earlier version of this rig+// passed against three deliberately broken apply() implementations, because+// its only same-block edits were length-preserving, its only inserted block+// went at the end, and nothing exercised a stale change set. Each is present+// here on purpose.++import { redline, apply, describe, diffTokens, tokenize } from '../type/src/redline.ts';+import { sign, verify, newKey, digest } from '../type/src/canon.ts';+import type { Block } from '../type/src/model.ts';++let checks = 0, failures = 0;+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };+const H = (s: string) => console.log(`\n=== ${s} ===`);+const same = (a: { body: Block[] }, b: { body: Block[] }) => JSON.stringify(a.body) === JSON.stringify(b.body);++const A = {+ docId: 'doc-1',+ body: [+ { id: 'p1', kind: 'para', text: 'The parties agree as follows.' },+ // two edits in one block, the EARLIER one length-changing+ { id: 'p2', kind: 'para', text: 'Payment is due within 30 days of invoice, without set-off.',+ marks: [{ t: 'b', from: 22, to: 29 }], // "30 days"+ notes: [{ id: 'n1', at: 58 }] },+ { id: 'p3', kind: 'para', text: 'This agreement is governed by the laws of Sweden.' },+ { id: 'p4', kind: 'para', text: 'Either party may terminate on notice.' },+ ] as Block[],+};++// Offsets are DERIVED from the text, never typed. The first version of this+// fixture hand-counted them, got two wrong, and reported a failure against+// correct code — a test that lies is worse than no test.+const P2 = 'Payment is due within sixty (60) calendar days of invoice, without set-off or counterclaim.';+const TERM = 'sixty (60) calendar days';++const B = {+ docId: 'doc-1',+ body: [+ { id: 'p1', kind: 'para', text: 'The parties agree as follows.' },+ { id: 'p2', kind: 'para', text: P2,+ marks: [{ t: 'b', from: P2.indexOf(TERM), to: P2.indexOf(TERM) + TERM.length }],+ notes: [{ id: 'n1', at: P2.length }] },+ // a NEW block in the MIDDLE, not at the end+ { id: 'p6', kind: 'para', text: 'Late payment shall bear interest at the statutory rate.' },+ { id: 'p4', kind: 'para', text: 'Either party may terminate on notice.' },+ { id: 'p5', kind: 'para', text: 'Neither party shall be liable for indirect losses.' },+ ] as Block[],+};++H('the two invariants');+{+ const set = redline(A, B, { author: 'counsel' });+ const all = new Set(set.changes.map(c => c.id));+ ok(same(apply(A, set, all), B), 'accept ALL reproduces the document they sent back');+ ok(same(apply(A, set, new Set()), A), 'accept NONE leaves the document you sent');+}++H('what the reviewer sees');+{+ const set = redline(A, B, { author: 'counsel' });+ for (const c of set.changes) console.log(` · ${c.kind.padEnd(10)} ${describe(c)}`);+ const kinds = set.changes.map(c => c.kind);+ ok(kinds.includes('block-del'), 'the deleted governing-law clause is reported');+ ok(kinds.includes('block-ins'), 'the two added clauses are reported');+ ok(kinds.includes('text'), 'the payment-terms edits are reported');+ const ins = set.changes.filter(c => c.kind === 'block-ins') as Array<{ index: number }>;+ ok(ins.some(c => c.index > 0 && c.index < B.body.length - 1),+ 'a block inserted in the MIDDLE records its position, not just "somewhere"');+ const texts = set.changes.filter(c => c.kind === 'text' && (c as { blockId: string }).blockId === 'p2');+ ok(texts.length >= 2, `the two separate edits in one paragraph are two changes (${texts.length})`);+}++H('marks and footnote anchors survive an accepted edit');+{+ const set = redline(A, B, { author: 'counsel' });+ const out = apply(A, set, new Set(set.changes.map(c => c.id)));+ const p2 = out.body.find(b => b.id === 'p2')!;+ ok(p2.text === B.body[1].text, 'the text matches what they sent');+ ok(JSON.stringify(p2.marks) === JSON.stringify(B.body[1].marks),+ `the bold covers the same term (“${p2.text.slice(p2.marks![0].from, p2.marks![0].to)}”)`);+ ok(p2.notes![0].at === B.body[1].notes![0].at,+ 'the footnote anchor lands where they put it, not mid-word');+}++H('a formatting change is a change');+{+ const bolded = { docId: 'doc-1', body: A.body.map(b => b.id === 'p4'+ ? { ...b, marks: [{ t: 'b' as const, from: 0, to: 12 }] } : b) };+ const set = redline(A, bolded);+ const fmt = set.changes.filter(c => c.kind === 'format');+ ok(fmt.length === 1, `bolding a clause with no text edit is reported (${fmt.length} change)`);+ ok(/bold/.test(describe(fmt[0])), `and described in words: “${describe(fmt[0])}”`);+ const all = new Set(set.changes.map(c => c.id));+ ok(same(apply(A, set, all), bolded), 'accepting it applies the formatting');+ ok(same(apply(A, set, new Set()), A), 'rejecting it leaves the document unformatted');++ // and it must NOT double-report when the text moved too+ const both = redline(A, B);+ ok(both.changes.filter(c => c.kind === 'format').length === 0,+ 'a block whose text also changed does not get a second, redundant format card');+}++H('partial acceptance — every subset applies cleanly');+{+ const set = redline(A, B, { author: 'counsel' });+ const ids = set.changes.map(c => c.id);+ let bad = 0;+ for (let mask = 0; mask < (1 << ids.length); mask++) {+ const acc = new Set(ids.filter((_, i) => mask & (1 << i)));+ try { const d = apply(A, set, acc); if (!Array.isArray(d.body)) bad++; }+ catch { bad++; }+ }+ ok(bad === 0, `all ${1 << ids.length} subsets apply without throwing`);+}++H('determinism');+{+ ok(JSON.stringify(redline(A, B).changes) === JSON.stringify(redline(A, B).changes),+ 'the same pair always yields the same change set');+ ok(redline(A, A).changes.length === 0, 'a document against itself yields no changes');+ const rev = redline(B, A);+ ok(same(apply(B, rev, new Set(rev.changes.map(c => c.id))), A), 'the redline is symmetric');+}++H('granularity');+{+ const ops = diffTokens(tokenize('Payment is due within 30 days.'), tokenize('Payment is due within 60 days.'));+ const changed = ops.filter(o => o.op !== 'eq');+ ok(changed.length === 2 && changed[0].tokens.join('') === '30' && changed[1].tokens.join('') === '60',+ 'a changed number is one deleted word and one inserted word, not a rewritten sentence');+}++H('a proposal is attributable');+{+ const key = await newKey();+ const set = redline(A, B, { author: 'counsel' });+ const proposed = apply(A, set, new Set(set.changes.map(c => c.id)));+ const sig = await sign({ ...proposed, docId: A.docId }, key, { name: 'counsel' });+ ok((await verify({ ...proposed, docId: A.docId }, sig)).ok, 'the proposed document verifies');+ ok(!(await verify({ ...A, docId: A.docId }, sig)).ok, 'and does not verify against the original');+ const tampered = JSON.parse(JSON.stringify(set));+ const t = tampered.changes.find((c: { kind: string }) => c.kind === 'text');+ t.added = ' nine hundred (900) days';+ const other = apply(A, tampered, new Set(tampered.changes.map((c: { id: string }) => c.id)));+ ok(await digest({ ...proposed, docId: A.docId }) !== await digest({ ...other, docId: A.docId }),+ 'altering a change after signing changes the digest');+}++console.log(`\n${checks - failures}/${checks} checks passed`);+if (failures) process.exit(1);diff --git a/scripts/test-type-store.ts b/scripts/test-type-store.tsnew file mode 100644index 00000000..276ff25f--- /dev/null+++ b/scripts/test-type-store.ts@@ -0,0 +1,134 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/type store + undo rig. node scripts/test-type-store.ts+//+// The claims worth pinning, because each fails silently and each costs work:+// · a typed word is ONE undo press, not one per keystroke+// · a scoped snapshot really is scoped — the whole document is not copied+// per keystroke (spaces measured an undo depth of NINE when it was)+// · undo/redo round-trips exactly, including interleaved+// · a block snapshot restores the block it names even after the body moved++import { Store } from '../type/src/store.ts';+import { emptyDoc, uid, type TypeDoc } from '../type/src/model.ts';++let checks = 0, failures = 0;+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };+const H = (s: string) => console.log(`\n=== ${s} ===`);++const doc = (n = 3): TypeDoc => {+ const d = emptyDoc();+ d.body = Array.from({ length: n }, (_, i) => ({ id: `p${i}`, kind: 'para' as const, text: `block ${i}` }));+ return d;+};++H('a typing run is one undo step');+{+ const s = new Store(doc());+ const before = s.block('p1')!.text;+ for (const ch of 'hello') {+ s.commit(d => { d.body[1].text += ch; }, { scope: { block: 'p1' }, run: 'type:p1' });+ }+ ok(s.block('p1')!.text === before + 'hello', 'five characters landed');+ ok(s.undoDepth === 1, `and cost ONE undo step, not five (depth ${s.undoDepth})`);+ s.undo();+ ok(s.block('p1')!.text === before, 'one undo removes the whole run');+ s.redo();+ ok(s.block('p1')!.text === before + 'hello', 'and redo puts it back');+}++H('a different run, or none, starts a new step');+{+ const s = new Store(doc());+ s.commit(d => { d.body[0].text += 'a'; }, { scope: { block: 'p0' }, run: 'type:p0' });+ s.commit(d => { d.body[1].text += 'b'; }, { scope: { block: 'p1' }, run: 'type:p1' });+ ok(s.undoDepth === 2, 'typing in a different block starts a new step');+ s.commit(d => { d.body[1].text += 'c'; }, { scope: { block: 'p1' }, run: 'type:p1' });+ ok(s.undoDepth === 2, 'continuing the same run does not');+ s.breakRun();+ s.commit(d => { d.body[1].text += 'd'; }, { scope: { block: 'p1' }, run: 'type:p1' });+ ok(s.undoDepth === 3, 'breakRun() closes the group (what a click or a paste does)');+}++H('scoped snapshots do not copy the whole document');+{+ // 400 blocks of real prose, then 200 keystrokes in ONE of them+ const d = emptyDoc();+ d.body = Array.from({ length: 400 }, (_, i) => ({+ id: `p${i}`, kind: 'para' as const,+ text: 'The parties agree that the schedule attached hereto forms part of this agreement. '.repeat(3),+ }));+ const s = new Store(d);+ let bytes = 0;+ for (let i = 0; i < 200; i++) {+ s.commit(x => { x.body[7].text += 'x'; }, { scope: { block: 'p7' }, run: `k${i}` });+ }+ ok(s.undoDepth === 200, `200 distinct edits are 200 undo steps (depth ${s.undoDepth})`);+ // the point: each step holds ONE block, not 400+ const oneBlock = JSON.stringify(d.body[7]).length;+ const wholeDoc = JSON.stringify(d).length;+ bytes = oneBlock * 200;+ ok(bytes < wholeDoc * 200 / 50,+ `200 scoped steps cost ~${(bytes / 1024).toFixed(0)}KB, where whole-document ones would cost ~${(wholeDoc * 200 / 1024 / 1024).toFixed(1)}MB`);+ // and they still restore correctly+ for (let i = 0; i < 200; i++) s.undo();+ ok(!s.block('p7')!.text.endsWith('x'), 'undoing all 200 restores the original text');+}++H('undo/redo round-trips, interleaved');+{+ const s = new Store(doc());+ const snap = () => s.doc.body.map(b => b.text).join('|');+ const start = snap();+ s.commit(d => { d.body[0].text = 'one'; });+ const a = snap();+ s.commit(d => { d.body[1].text = 'two'; });+ const b = snap();+ s.undo(); ok(snap() === a, 'undo returns to the previous state');+ s.undo(); ok(snap() === start, 'and to the one before that');+ s.redo(); ok(snap() === a, 'redo replays');+ s.redo(); ok(snap() === b, 'and replays again');+ ok(!s.canRedo, 'the redo stack is exhausted');+ s.commit(d => { d.body[2].text = 'three'; });+ ok(!s.canRedo, 'a new edit clears the redo stack');+}++H('a block snapshot survives the body moving under it');+{+ const s = new Store(doc(4));+ s.commit(d => { d.body[2].text = 'edited'; }, { scope: { block: 'p2' } });+ // something else removes an earlier block, so indices shift+ s.commit(d => { d.body.splice(0, 1); });+ s.undo(); // put the block back+ s.undo(); // undo the edit+ ok(s.block('p2')!.text === 'block 2', 'the block-scoped undo found its block by id, not by index');+}++H('replace() is undoable');+{+ const s = new Store(doc());+ const before = s.doc.body.length;+ const other = emptyDoc(); other.body = [{ id: 'z', kind: 'para', text: 'replaced' }];+ s.replace(other);+ ok(s.doc.body.length === 1, 'the document was replaced');+ s.undo();+ ok(s.doc.body.length === before, 'and undo brings the original back');+}++H('listeners fire once per commit');+{+ const s = new Store(doc());+ let n = 0;+ const off = s.on(() => n++);+ s.commit(d => { d.body[0].text = 'x'; });+ s.commit(d => { d.body[0].text = 'y'; });+ s.undo();+ ok(n === 3, `two commits and an undo fired three times (${n})`);+ off();+ s.commit(d => { d.body[0].text = 'z'; });+ ok(n === 3, 'and unsubscribing stops them');+}++console.log(`\n${checks - failures}/${checks} checks passed`);+if (failures) process.exit(1);diff --git a/scripts/test-type-theme.mjs b/scripts/test-type-theme.mjsnew file mode 100644index 00000000..720cc2be--- /dev/null+++ b/scripts/test-type-theme.mjs@@ -0,0 +1,109 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/type theme rig. node scripts/test-type-theme.mjs+//+// Static checks over the stylesheet, so a theme cannot rot silently.+//+// The bug this exists because of: the block-style <select> was given+// `background: var(--paper)`. In light theme that is white on white chrome and+// looks fine. In dark theme it is a WHITE box with pale grey text — measured at+// 1.92:1 against a WCAG AA floor of 4.5. It happened because `--paper` is+// deliberately NOT themed (a document is white because paper is white), and I+// used a document token for a chrome control. That is a whole bug CLASS, and it+// is checkable without a browser:+//+// · chrome must never reference a --paper* token+// · every themed token must exist in BOTH themes, or one theme silently+// inherits the other's value+// · no literal colour may appear outside a token block++import { readFileSync } from 'node:fs';+import { join, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++const root = join(dirname(fileURLToPath(import.meta.url)), '..');+const css = readFileSync(join(root, 'type/src/styles.css'), 'utf8');++let checks = 0, failures = 0;+const ok = (c, m) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`); } else console.log(` ok ${m}`); };+const H = (s) => console.log(`\n=== ${s} ===`);++/** The declarations inside a given selector's block. */+const blockFor = (selector) => {+ const i = css.indexOf(selector);+ if (i < 0) return '';+ return css.slice(i, css.indexOf('}', i));+};+const tokensIn = (block) => [...block.matchAll(/--([a-z0-9-]+)\s*:/g)].map(m => m[1]);++const light = blockFor(':root, :root[data-theme="light"]');+const dark = blockFor(':root[data-theme="dark"]');+const base = blockFor(':root {');++H('both themes define the same roles');+{+ const l = new Set(tokensIn(light)), d = new Set(tokensIn(dark));+ ok(l.size > 5, `the light theme defines ${l.size} tokens`);+ const missing = [...l].filter(t => !d.has(t));+ const extra = [...d].filter(t => !l.has(t));+ ok(missing.length === 0,+ `every light token has a dark counterpart${missing.length ? ` — missing: ${missing.join(', ')}` : ''}`);+ ok(extra.length === 0,+ `and the dark theme invents none${extra.length ? ` — extra: ${extra.join(', ')}` : ''}`);+}++H('the document surface is NOT themed');+{+ const paperTokens = tokensIn(base).filter(t => t.startsWith('paper'));+ ok(paperTokens.length > 0, `paper tokens live in the unthemed block (${paperTokens.join(', ')})`);+ const themedPaper = [...tokensIn(light), ...tokensIn(dark)].filter(t => t.startsWith('paper'));+ ok(themedPaper.length === 0,+ `no paper token is themed${themedPaper.length ? ` — ${themedPaper.join(', ')} would invert the document` : ''}`);+}++H('chrome never borrows a document token');+{+ // every rule that is NOT the page or its decorations+ const rules = css.split('}').filter(r => r.includes('{'));+ const offenders = [];+ for (const r of rules) {+ const sel = r.slice(0, r.indexOf('{')).trim();+ if (!sel || sel.startsWith(':root') || sel.startsWith('/*')) continue;+ const isDocument = /\.t-paper|\.t-deco/.test(sel);+ if (isDocument) continue;+ if (/var\(--paper/.test(r)) offenders.push(sel.replace(/\s+/g, ' ').slice(0, 48));+ }+ ok(offenders.length === 0,+ `no chrome rule uses a --paper token${offenders.length ? ` — ${offenders.join(' | ')}` : ''}`);+}++H('no literal colours outside the token blocks');+{+ const lines = css.split('\n');+ const strays = [];+ lines.forEach((line, i) => {+ if (/^\s*--/.test(line)) return; // a token definition+ if (/#[0-9a-fA-F]{3,8}\b/.test(line)) strays.push(`${i + 1}: ${line.trim().slice(0, 56)}`);+ });+ ok(strays.length === 0,+ `every colour comes from a token${strays.length ? `\n ${strays.join('\n ')}` : ''}`);+}++H('the suite palette is not forked');+{+ // the light theme must still BE the shared palette — a drifted copy is how+ // three apps stop looking like one product+ const shared = { ink: '#1e2a3a', 'ink-2': '#31445c', chrome: '#f5f7fa',+ 'chrome-2': '#eceff4', line: '#e3e8ef', muted: '#5b6472',+ accent: '#f7a600', 'accent-ink': '#7a5200', blue: '#5b8def' };+ const wrong = [];+ for (const [name, value] of Object.entries(shared)) {+ const m = light.match(new RegExp(`--${name}\\s*:\\s*([^;]+);`));+ if (!m || m[1].trim().toLowerCase() !== value) wrong.push(`--${name} is ${m ? m[1].trim() : 'missing'}, suite uses ${value}`);+ }+ ok(wrong.length === 0, `the light theme matches slides/spaces exactly${wrong.length ? `\n ${wrong.join('\n ')}` : ''}`);+}++console.log(`\n${checks - failures}/${checks} checks passed`);+if (failures) process.exit(1);diff --git a/slides/src/sync/blobs.ts b/slides/src/sync/blobs.tsindex 41c64ce0..da5f2d29 100644--- a/slides/src/sync/blobs.ts+++ b/slides/src/sync/blobs.ts@@ -1,312 +1,13 @@// SPDX-License-Identifier: MIT// Copyright (c) 2026 The Bento authors-// Encrypted asset blobs — the client half of docs/blob-offload.md.+// Blob storage for bento-sync — A FACADE. The implementation is the kernel's.//-// WHY THIS EXISTS. An asset cannot travel as a CRDT op: a Durable Object-// storage value caps near 2MB, and an asset costs ~1.78x its binary size on-// the wire (base64 twice — once into the data URI, once over the ciphertext).-// So ~1.05MB of binary is the ceiling for an op, against an 8MB embed budget.-// No frame-size constant fixes that. Assets go to the relay's blob store-// instead and the op carries only a reference.+// It moved unchanged: this file never imported anything from the app. Large+// media travels out-of-band (the relay stores ciphertext by content key) and+// nothing in that mechanism knows what a slide is, so there was nothing to+// parameterize — unlike session.ts, which needed a host adapter first.//-// WHY CHUNKED. WebCrypto has NO streaming AES-GCM — encrypt/decrypt are-// one-shot — and a round trip costs roughly 5x the payload in memory-// (measured: 8MB -> 40MB, 64MB -> 320MB). Encrypting a large asset in one-// call would spike a browser tab, and mobile Safari kills tabs for less.-// Fixed-size chunks bound peak memory to ~5x CHUNK regardless of asset size,-// and fall out naturally as resumable upload units later.-//-// WHY THE KEY IS AN HMAC. Content addressing gives dedupe for free, but a bare-// sha256(plaintext) as the storage key would let the relay see that two-// different rooms hold the same image. HMAC(roomKey, hash) is deterministic-// WITHIN a room (so dedupe works) and opaque across rooms (so nothing-// correlates). The relay only ever sees the HMAC.--/** Plaintext bytes per chunk. Peak memory is ~5x this, not ~5x the asset. */-const CHUNK = 4 * 1024 * 1024-/** Must match the relay's MAX_BLOB. NOTE this bounds the ENCODED blob, not the- * plaintext — the relay measures what it receives. */-// 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 { netFetch } from '../../../kernel/src/net.ts'--export const MAX_BLOB = 8 * 1024 * 1024-const MAGIC = 0x4242 // 'BB'-const HEADER = 16-const IV_LEN = 12-const TAG_LEN = 16--const b64u = {- enc(bytes: Uint8Array): string {- let s = ''- for (const b of bytes) s += String.fromCharCode(b)- return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')- },- dec(s: string): Uint8Array {- const b = atob(s.replace(/-/g, '+').replace(/_/g, '/'))- const out = new Uint8Array(b.length)- for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i)- return out- },-}--/** `data:<mime>;base64,<payload>` → bytes + mime. Null if not a data URI. */-export function dataUriToBytes(uri: string): { bytes: Uint8Array; mime: string } | null {- const m = /^data:([^;,]*)(;base64)?,(.*)$/s.exec(uri)- if (!m) return null- const mime = m[1] || 'application/octet-stream'- if (!m[2]) return { bytes: new TextEncoder().encode(decodeURIComponent(m[3])), mime }- const raw = atob(m[3])- const bytes = new Uint8Array(raw.length)- for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i)- return { bytes, mime }-}--/** bytes → `data:<mime>;base64,…`, chunked so a large asset doesn't blow the- * argument stack via String.fromCharCode(...bytes). */-export function bytesToDataUri(bytes: Uint8Array, mime: string): string {- let s = ''- for (let i = 0; i < bytes.length; i += 0x8000) {- s += String.fromCharCode(...bytes.subarray(i, Math.min(i + 0x8000, bytes.length)))- }- return `data:${mime};base64,${btoa(s)}`-}--/** Encoded size for `n` plaintext bytes: header + per-chunk IV and GCM tag.- * The client must check THIS against MAX_BLOB, not the plaintext length —- * otherwise an asset just under the limit passes here and is refused 413 by- * the relay, which measures the ciphertext. */-export function encodedSize(n: number): number {- return HEADER + Math.max(1, Math.ceil(n / CHUNK)) * (IV_LEN + TAG_LEN) + n-}--/** Largest plaintext asset that still fits in one blob. */-export function maxAssetBytes(): number {- let n = MAX_BLOB- while (n > 0 && encodedSize(n) > MAX_BLOB) n -= 1- return n-}--async function hmacKey(rawRoomKey: Uint8Array): Promise<CryptoKey> {- return crypto.subtle.importKey(- 'raw', rawRoomKey as BufferSource, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'],- )-}--/**- * Storage key for an asset: HMAC(roomKey, sha256(plaintext)), base64url,- * truncated to 32 chars (the relay accepts [A-Za-z0-9_-]{16,64}). Same bytes- * in the same room always yield the same key — that IS the dedupe.- */-export async function blobKey(rawRoomKey: Uint8Array, bytes: Uint8Array): Promise<string> {- const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes as BufferSource))- const mac = await crypto.subtle.sign('HMAC', await hmacKey(rawRoomKey), digest as BufferSource)- return b64u.enc(new Uint8Array(mac)).slice(0, 32)-}--async function aesKey(rawRoomKey: Uint8Array): Promise<CryptoKey> {- return crypto.subtle.importKey('raw', rawRoomKey as BufferSource, 'AES-GCM', false, ['encrypt', 'decrypt'])-}--/**- * Encrypt to the on-the-wire blob layout:- * [magic u16][version u8][reserved u8][chunkSize u32][totalSize u32][nChunks u32]- * then per chunk: [iv 12][ciphertext (plaintext + 16-byte tag)]- * Chunk lengths are implied by chunkSize + totalSize, so nothing is ambiguous.- */-export async function encodeBlob(rawRoomKey: Uint8Array, bytes: Uint8Array, mimeUnused?: string): Promise<Uint8Array> {- void mimeUnused // mime rides in the op, not the blob: the blob is opaque- const key = await aesKey(rawRoomKey)- const nChunks = Math.max(1, Math.ceil(bytes.length / CHUNK))- const out = new Uint8Array(HEADER + nChunks * (IV_LEN + TAG_LEN) + bytes.length)- const dv = new DataView(out.buffer)- dv.setUint16(0, MAGIC, true)- dv.setUint8(2, 1)- dv.setUint8(3, 0)- dv.setUint32(4, CHUNK, true)- dv.setUint32(8, bytes.length, true)- dv.setUint32(12, nChunks, true)- let at = HEADER- for (let i = 0; i < nChunks; i++) {- const slice = bytes.subarray(i * CHUNK, Math.min((i + 1) * CHUNK, bytes.length))- const iv = crypto.getRandomValues(new Uint8Array(IV_LEN))- const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, slice as BufferSource))- out.set(iv, at); at += IV_LEN- out.set(ct, at); at += ct.length- }- return out-}--/** Inverse of encodeBlob. Null on a wrong key, truncation or corruption —- * every chunk is individually authenticated by its GCM tag. */-export async function decodeBlob(rawRoomKey: Uint8Array, blob: Uint8Array): Promise<Uint8Array | null> {- if (blob.length < HEADER) return null- const dv = new DataView(blob.buffer, blob.byteOffset, blob.byteLength)- if (dv.getUint16(0, true) !== MAGIC || dv.getUint8(2) !== 1) return null- const chunkSize = dv.getUint32(4, true)- const total = dv.getUint32(8, true)- const nChunks = dv.getUint32(12, true)- if (!chunkSize || nChunks > 4096) return null- const key = await aesKey(rawRoomKey)- const out = new Uint8Array(total)- let at = HEADER- let wrote = 0- for (let i = 0; i < nChunks; i++) {- const plainLen = Math.min(chunkSize, total - wrote)- const ctLen = plainLen + TAG_LEN- if (at + IV_LEN + ctLen > blob.length) return null- const iv = blob.subarray(at, at + IV_LEN); at += IV_LEN- const ct = blob.subarray(at, at + ctLen); at += ctLen- try {- const plain = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ct as BufferSource))- out.set(plain, wrote)- wrote += plain.length- } catch {- return null // wrong key or tampered chunk- }- }- return wrote === total ? out : null-}--// --- local cache --------------------------------------------------------------// A blob a peer sent is worth keeping: the same asset is referenced by every-// slide that uses it, and re-fetching on each render would be absurd. Keyed by-// the blob key, which is already content-addressed.--const DB = 'bento-blobcache'-const STORE = 'blobs'-let dbP: Promise<IDBDatabase | null> | null = null--function db(): Promise<IDBDatabase | null> {- if (dbP) return dbP- dbP = new Promise((resolve) => {- if (typeof indexedDB === 'undefined') return resolve(null)- let req: IDBOpenDBRequest- try { req = indexedDB.open(DB, 1) } catch { return resolve(null) }- req.onupgradeneeded = () => {- const d = req.result- if (!d.objectStoreNames.contains(STORE)) d.createObjectStore(STORE)- }- req.onsuccess = () => resolve(req.result)- req.onerror = () => resolve(null)- })- return dbP-}--export async function cacheGet(key: string): Promise<Uint8Array | null> {- const d = await db()- if (!d) return null- return new Promise((resolve) => {- try {- const r = d.transaction(STORE, 'readonly').objectStore(STORE).get(key)- r.onsuccess = () => resolve(r.result ? new Uint8Array(r.result as ArrayBuffer) : null)- r.onerror = () => resolve(null)- } catch { resolve(null) }- })-}--export async function cachePut(key: string, bytes: Uint8Array): Promise<void> {- const d = await db()- if (!d) return- try {- // store the ArrayBuffer, not the view — structured clone keeps it compact- d.transaction(STORE, 'readwrite').objectStore(STORE).put(bytes.slice().buffer, key)- } catch { /* cache is best effort */ }-}--// --- transport -----------------------------------------------------------------export interface BlobEndpoint {- /** relay origin, e.g. https://sync.bento.page */- base: string- room: string- tok: string-}--const url = (e: BlobEndpoint, key: string) =>- `${e.base.replace(/\/$/, '')}/b/${encodeURIComponent(e.room)}/${encodeURIComponent(key)}?tok=${encodeURIComponent(e.tok)}`--export type PutResult =- | { ok: true; key: string; deduped: boolean }- | { ok: false; reason: 'too-large' | 'unsupported' | 'network' | 'forbidden' | 'room-full' }--/**- * Encrypt and upload. Returns the key to put in the op. Dedupe is a HEAD- * first: content addressing means an identical asset already uploaded by a- * peer needs no second upload.- *- * 'unsupported' means the relay has no blob storage configured (501) — the- * caller should fall back to inlining, NOT treat it as an error.- */-export async function putBlob(e: BlobEndpoint, rawRoomKey: Uint8Array, bytes: Uint8Array): Promise<PutResult> {- if (encodedSize(bytes.length) > MAX_BLOB) return { ok: false, reason: 'too-large' }- const key = await blobKey(rawRoomKey, bytes)- try {- const head = await netFetch(url(e, key), { method: 'HEAD' })- if (head.status === 200) {- void cachePut(key, bytes)- return { ok: true, key, deduped: true }- }- if (head.status === 501) return { ok: false, reason: 'unsupported' }- if (head.status === 403) return { ok: false, reason: 'forbidden' }- const body = await encodeBlob(rawRoomKey, bytes)- const res = await netFetch(url(e, key), {- method: 'PUT', body: body as BodyInit,- headers: { 'content-type': 'application/octet-stream' },- })- if (res.status === 501) return { ok: false, reason: 'unsupported' }- if (res.status === 403) return { ok: false, reason: 'forbidden' }- if (res.status === 413) return { ok: false, reason: 'too-large' }- // 507: the room's total blob quota is exhausted. Permanent for this room- // until it expires — the caller must not retry in a loop.- if (res.status === 507) return { ok: false, reason: 'room-full' }- if (!res.ok) return { ok: false, reason: 'network' }- void cachePut(key, bytes)- return { ok: true, key, deduped: false }- } catch {- return { ok: false, reason: 'network' }- }-}--/** Does `plain` actually hash to the address we asked for? One SHA-256 plus- * one HMAC over bytes we have just decrypted anyway — negligible beside the- * AES-GCM pass that produced them, and it runs once per fetch, not per use- * (the cache is keyed by the same address). */-async function addressMatches(rawRoomKey: Uint8Array, key: string, plain: Uint8Array): Promise<boolean> {- return (await blobKey(rawRoomKey, plain)) === key-}+// The path stays valid because scripts/test-blobs.ts and session.ts import it+// from here.-/** Fetch and decrypt, cache-first. Null means "not available right now" —- * callers render a placeholder rather than a broken image, and may retry.- * A blob that fails its content-address check reads as unavailable too: a- * placeholder is recoverable, the wrong picture is not. */-export async function getBlob(e: BlobEndpoint, rawRoomKey: Uint8Array, key: string): Promise<Uint8Array | null> {- const hit = await cacheGet(key)- try {- // The hit is checked as well, so a cache written before this verification- // existed (or edited under us in IndexedDB) heals: falling through re-fetches- // and cachePut, keyed by the address, overwrites the bad entry.- // INSIDE the try like the post-fetch check below: addressMatches can throw- // (measured — crypto.subtle.importKey('raw', new Uint8Array(0), HMAC) rejects- // with DataError on an empty room key), and the contract above promises null,- // not a rejection. session.resolveBlobs has try/finally and no catch, so a- // throw here escapes as an unhandled rejection.- if (hit && await addressMatches(rawRoomKey, key, hit)) return hit- const res = await netFetch(url(e, key))- if (!res.ok) return null- const enc = new Uint8Array(await res.arrayBuffer())- const plain = await decodeBlob(rawRoomKey, enc)- if (!plain) return null- // GCM proves someone holding the room key sealed these bytes. It does NOT- // prove they are the bytes this address names, and nothing else here did:- // the relay is free to answer address A with the room's blob B, and every- // check above passes. The picture silently becomes a different picture and- // cachePut writes the swap to disk permanently. The address is the only- // binding between reference and content, so verify it before both.- if (!await addressMatches(rawRoomKey, key, plain)) return null- void cachePut(key, plain)- return plain- } catch {- return null- }-}+export * from '../../../kernel/src/sync/blobs.ts';diff --git a/slides/src/sync/online.ts b/slides/src/sync/online.tsindex c0be426f..4f13bfb0 100644--- a/slides/src/sync/online.ts+++ b/slides/src/sync/online.ts@@ -1,734 +1,16 @@// SPDX-License-Identifier: MIT// Copyright (c) 2026 The Bento authors-// bento-sync online transport — E2EE WebSocket to the blind relay-// (server/sync-worker). Every session frame is AES-GCM encrypted with the-// room key from doc.collab.key; the relay sees ciphertext, fan-out routing,-// and nothing else. Auth is possession-proof: ?tok= is a hash of the key.+// The online relay transport for bento/slides — A FACADE. The implementation+// is kernel/src/sync/online.ts.//-// Reconnects with backoff; frames queue while disconnected; op frames are-// persisted server-side (envelope {p:1}) and replayed to joiners from their-// last acked seq, with client-produced encrypted snapshots capping replay-// length. See docs/collab-design.md.--import type { Store } from '../store'-import type { BentoDoc } from '../model'-import type { Op, SyncStateJSON } from './crdt'-import type { Frame, RefusalCode, SyncSession, Transport } from './session'-import { offlineEnabled } from '../update'-import { netWebSocket } from '../../../kernel/src/net.ts'-import { lsGet, lsSet } from '../../../kernel/src/storage.ts'--export const DEFAULT_SYNC_HOST = 'wss://sync.bento.page'-const SNAP_EVERY = 200 // ops between encrypted snapshot uploads--const b64u = {- enc(bytes: Uint8Array): string {- let s = ''- for (const b of bytes) s += String.fromCharCode(b)- return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')- },- dec(s: string): Uint8Array {- const b = atob(s.replace(/-/g, '+').replace(/_/g, '/'))- const out = new Uint8Array(b.length)- for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i)- return out- },-}--export function mintRoomKey(): string {- const bytes = new Uint8Array(32)- crypto.getRandomValues(bytes)- return b64u.enc(bytes)-}--const EC = { name: 'ECDSA', namedCurve: 'P-256' } as const-const SIGN_ALG = { name: 'ECDSA', hash: 'SHA-256' } as const--/** Import a writer private key (PKCS#8, base64url) for signing op frames. */-export async function importSignKey(privB64: string): Promise<CryptoKey> {- return crypto.subtle.importKey('pkcs8', b64u.dec(privB64) as BufferSource, EC, false, ['sign'])-}--/** ECDSA-P256/SHA-256 signature over `${i}.${d}`, base64url. */-export async function signFrame(key: CryptoKey, i: string, d: string): Promise<string> {- const sig = await crypto.subtle.sign(SIGN_ALG, key, new TextEncoder().encode(`${i}.${d}`))- return b64u.enc(new Uint8Array(sig))-}--/** Sign an arbitrary string with a b64url PKCS#8 private key (cert chains). */-export async function signText(privB64: string, text: string): Promise<string> {- const key = await importSignKey(privB64)- const sig = await crypto.subtle.sign(SIGN_ALG, key, new TextEncoder().encode(text))- return b64u.enc(new Uint8Array(sig))-}--async function mintKeypair(): Promise<{ pub: string; priv: string }> {- const kp = (await crypto.subtle.generateKey(EC, true, ['sign', 'verify'])) as CryptoKeyPair- return {- pub: b64u.enc(new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey))),- priv: b64u.enc(new Uint8Array(await crypto.subtle.exportKey('pkcs8', kp.privateKey))),- }-}--export type CollabInvite = { pub: string; priv: string; role: 'writer' | 'commenter'; exp?: number; sig: string }--/** Owner-signed invite: a delegation keypair whose private half rides in the- * shared copy. Chain: owner signs `inv.${pub}.${role}.${exp||0}`; a joining- * device later signs its own pubkey with the invite key (`dlg.${memberPub}`).- * The relay verifies both signatures and never sees private material — so a- * blind relay still cannot certify its own key. */-export async function mintInvite(ownerPrivB64: string, role: 'writer' | 'commenter' = 'writer', exp = 0): Promise<CollabInvite> {- const kp = await mintKeypair()- const sig = await signText(ownerPrivB64, `inv.${kp.pub}.${role}.${exp}`)- return { pub: kp.pub, priv: kp.priv, role, ...(exp ? { exp } : {}), sig }-}--/** This device's member identity for a doc — minted once, kept in localStorage,- * NEVER in the file (the file travels; a device key must not). */-export async function deviceIdentity(docId: string): Promise<{ pub: string; priv: string }> {- const k = `bento-member-${docId}`- try {- const saved = lsGet(k)- if (saved) return JSON.parse(saved)- } catch { /* storage unavailable → ephemeral identity */ }- const id = await mintKeypair()- lsSet(k, JSON.stringify(id))- return id-}--/** Auth material for the relay connection. Exactly one shape applies:- * direct (owner or legacy shared-writer key) or chain (member via invite). */-export type AuthSpec =- | { kind: 'direct'; pub: string; priv?: string }- | { kind: 'chain'; owner: string; invite: CollabInvite; docId: string }--export type CollabCreds = {- room: string- key: string- on: boolean- v: number- owner: string- ownerPriv: string- role: 'writer'-}--/**- * Fresh collaboration credentials, minted at DOCUMENT CREATION and LIVE by- * default (on:true): the moment identity and keys exist, any copy of the- * file joins the same room — "send first" needs no ceremony. "Stop sharing"- * in the Live popover turns it off; Offline mode hard-blocks regardless.- *- * Signed-writes scheme (v0.9.18+): the room id is the COMMITMENT to a fresh- * ECDSA writer pubkey — `w` + base64url(SHA-256(writerPubRaw)) — so the relay- * can pin the writer key trustlessly (a viewer holds the room id but can't- * substitute their own key). `key` is the separate symmetric READ capability.- * Async because keypair generation is. See docs/collab-design.md.- */-export async function mintCollab(): Promise<CollabCreds> {- // v2 (fine-grained): the room id commits to the OWNER's pubkey. The creator's- // copy holds ownerPriv; shared copies carry owner-signed INVITES instead, and- // each joining device mints its own member key (see mintInvite/deviceIdentity).- const kp = await mintKeypair()- const commit = new Uint8Array(await crypto.subtle.digest('SHA-256', b64u.dec(kp.pub) as BufferSource))- return {- room: `${syncHost()}/d/w${b64u.enc(commit)}`,- key: mintRoomKey(),- on: true,- v: 2,- owner: kp.pub,- ownerPriv: kp.priv,- role: 'writer',- }-}--/** dev override for the relay host (e.g. ws://localhost:8787) */-export function syncHost(): string {- try {- return lsGet('bento-sync-url') || DEFAULT_SYNC_HOST- } catch {- return DEFAULT_SYNC_HOST- }-}--export type OnlineStatus = 'connecting' | 'open' | 'closed'--/** A frame written to (or parked for) the relay. `ops` is set for persisted op- * batches — the only frames the relay acks, and the only ones whose refusal- * has to reach the session (an unsendable op must leave the resend log). */-type Outbound = { id: string; text: string; ops: Op[] | null; bytes: number; tries: number }--let frameSeq = 0-/** Short opaque per-frame id. Emitted FIRST in the envelope so the relay can- * recover it with a bounded regex from an OVERSIZE frame — one it refuses- * before parsing, since parsing an attacker-sized string is a CPU abuse- * vector. Relay contract: docs/relay-design.md. */-const nextFrameId = (): string => `f${(++frameSeq).toString(36)}${Math.random().toString(36).slice(2, 6)}`--/** `{ctl:'refused'}` from the relay. Modern relays echo our frame id (`k`),- * which is exact; older ones don't, and then the sizes are the only evidence- * of WHICH frame it names (see matchRefused). */-type RefusedEnv = {- code?: string- /** our frame id, echoed back — authoritative when present */- k?: string- /** too-large: the relay's ceiling and the frame length it measured */- max?: number- got?: number- /** storage-failed: i.length + d.length of the frame it tried to store */- bytes?: number- /** rate-limited: how long until the socket's byte window rolls over */- retryInMs?: number-}--export class OnlineTransport implements Transport {- readonly kind = 'online'- status: OnlineStatus = 'connecting'- onStatus: ((s: OnlineStatus) => void) | null = null- private ws: WebSocket | null = null- private key: CryptoKey | null = null- /** writer signing key — null for readers (they can decrypt but not author). */- private signKey: CryptoKey | null = null- private queue: Outbound[] = []- /** persisted frames written but not yet acked. The relay handles one- * socket's frames in order and acks every stored one, so the head of this- * list is the frame a `refused` reply is talking about. Purely a- * correlation window — delivery is still guaranteed by the log + `need`. */- private awaitingAck: Outbound[] = []- /** rate-limit backoff deadline: sending into a refusing relay only burns the- * next window too, so frames park until it passes */- private paused = false- private pauseTimer: ReturnType<typeof setTimeout> | null = null- private lastLimitNotice = 0- private static readonly ACK_WINDOW = 64- private static readonly MAX_RETRIES = 4- private closed = false- private backoff = 800- private url = ''- // heartbeat: ping the relay (which auto-responds "pong" without waking the DO)- // so idle connections stay alive; if a pong doesn't come back before the next- // tick, treat the socket as dead and reconnect instead of waiting for a TCP- // timeout that can take minutes.- private pingTimer: ReturnType<typeof setInterval> | null = null- private awaitingPong = false- private static readonly PING_MS = 25_000- /** the key THIS socket signs with (owner / legacy writer / device) — used to- * recognise our own revocation and to attribute presence */- myPub: string | null = null- /**- * Replay bookmark — MEMORY ONLY, deliberately: it is valid only alongside- * the in-memory CRDT state it was earned with. A fresh join replays from- * the room's snapshot (or 0); reconnects of THIS session resume from here.- */- private seq = 0-- constructor(- room: string,- private keyB64: string,- docId: string,- private onFrame: (f: Frame) => void,- private hooks: {- onSnap: (doc: BentoDoc, state: SyncStateJSON) => void- getSnapshot: () => { doc: BentoDoc; state: SyncStateJSON }- onOpen: () => void- /** replay done: (actor,seq) pairs the room holds; return true to upload a snapshot */- onReady: (seen: Set<string>, seq: number) => boolean- /** the relay refused a frame; `ops` are the ones it will never accept- * (null when the refusal couldn't be pinned to a frame we sent) */- onRefused?: (code: RefusalCode, ops: Op[] | null) => void- },- private auth?: AuthSpec,- ) {- this.docId = docId- this.init(room)- }-- private docId = ''-- /** (actor,seq) pairs seen in the current connection's replay */- private replaySeen = new Set<string>()-- /** Credentials the blob layer needs: the relay origin, the room name, the- * possession-proof token, and the raw room key it encrypts blobs with.- * Null until init() has derived the token. */- blobCreds(): { base: string; room: string; tok: string; rawKey: Uint8Array } | null {- if (!this.roomName || !this.tokValue) return null- return { base: this.originValue, room: this.roomName, tok: this.tokValue, rawKey: b64u.dec(this.keyB64) }- }- private roomName = ''- private tokValue = ''- private originValue = ''-- private async init(room: string) {- const raw = b64u.dec(this.keyB64)- this.key = await crypto.subtle.importKey('raw', raw as BufferSource, 'AES-GCM', false, [- 'encrypt',- 'decrypt',- ])- const tokDigest = new Uint8Array(await crypto.subtle.digest('SHA-256', raw as BufferSource))- const tok = b64u.enc(tokDigest.slice(0, 18))- // Blob endpoints live on the same origin as the socket and use the same- // room + token, so derive them here rather than duplicating the rule.- try {- const u = new URL(room.replace(/^ws/, 'http'))- this.originValue = u.origin- this.roomName = u.pathname.replace(/^\/d\//, '')- this.tokValue = tok- } catch { /* malformed room url — blobs simply stay unavailable */ }- // Writers sign op frames; readers omit auth and the relay drops their- // writes. Two writer shapes: DIRECT (the presented `w` key hash-matches the- // room commitment — the owner, or a legacy shared-writer copy) and CHAIN- // (a member: `w` = this device's key, plus the owner-signed invite and the- // invite-signed delegation of the device key — verified by the relay).- const a = this.auth- if (a?.kind === 'direct') {- if (a.priv) { try { this.signKey = await importSignKey(a.priv) } catch { this.signKey = null } }- this.myPub = a.pub- this.url = `${room}?tok=${tok}&w=${a.pub}`- } else if (a?.kind === 'chain') {- const id = await deviceIdentity(this.docId)- try { this.signKey = await importSignKey(id.priv) } catch { this.signKey = null }- this.myPub = id.pub- const iv = a.invite- const dg = await signText(iv.priv, `dlg.${id.pub}`)- this.url = `${room}?tok=${tok}&w=${id.pub}&o=${a.owner}` +- `&ivp=${iv.pub}&ivr=${iv.role}&ive=${iv.exp ?? 0}&ivs=${iv.sig}&dg=${dg}`- } else {- this.url = `${room}?tok=${tok}`- }- this.connect()- }-- private lastSeq(): number {- return this.seq- }-- private saveSeq(q: number) {- if (q > this.seq) this.seq = q- }-- private setStatus(s: OnlineStatus) {- this.status = s- this.onStatus?.(s)- }-- private connect() {- if (this.closed) return- this.setStatus('connecting')- let ws: WebSocket- try {- ws = netWebSocket(`${this.url}&since=${this.lastSeq()}`)- } catch {- // Offline is a decision, not an outage: retrying would spin until the- // switch flips, and net.ts has closed anything already open anyway.- if (!offlineEnabled()) this.retry()- return- }- this.ws = ws- ws.onopen = () => {- this.backoff = 800- this.inReplay = true- this.replaySeen = new Set()- // acks don't survive the socket: whatever was un-acked is unknowable now,- // and a stale entry would mis-name a later refusal. Delivery of those ops- // is the log's job anyway (session.onRelayReady re-sends what the room lacks).- this.awaitingAck = []- this.setStatus('open')- for (const out of this.queue.splice(0)) this.write(out)- this.startHeartbeat(ws)- this.hooks.onOpen()- }- ws.onmessage = (ev) => {- const data = String(ev.data)- if (data === 'pong') { this.awaitingPong = false; return } // keepalive reply- this.onEnvelope(data).catch(() => {})- }- const drop = () => {- if (this.ws !== ws) return- this.stopHeartbeat()- this.ws = null- this.setStatus('closed')- this.retry()- }- ws.onclose = drop- ws.onerror = drop- }-- private startHeartbeat(ws: WebSocket) {- this.stopHeartbeat()- this.awaitingPong = false- this.pingTimer = setInterval(() => {- if (this.ws !== ws || ws.readyState !== WebSocket.OPEN) return- if (this.awaitingPong) {- // no pong since the last ping → the socket is dead (half-open); force a- // close so onclose fires and we reconnect, rather than hanging silently.- try { ws.close() } catch { /* already gone */ }- return- }- this.awaitingPong = true- try { ws.send('ping') } catch { /* send failed → onclose will handle it */ }- }, OnlineTransport.PING_MS)- }-- private stopHeartbeat() {- if (this.pingTimer) { clearInterval(this.pingTimer); this.pingTimer = null }- this.awaitingPong = false- }-- private retry() {- if (this.closed) return- setTimeout(() => this.connect(), this.backoff)- this.backoff = Math.min(this.backoff * 1.8, 30000)- }-- // --- refusals --------------------------------------------------------------- /**- * The relay refused a frame. Handling this is not optional politeness: when- * the relay dropped oversize/over-quota frames SILENTLY, the sender got no- * ack, the peer stayed behind, its `need`/vv catch-up asked for the very- * same op, and the sender re-sent the identical doomed frame forever.- *- * 'rate-limited' is transient — back off and retry. Everything else is- * permanent for that frame: it goes up to the session, which forgets the ops- * so the loop cannot restart, and tells the user what they just lost.- */- private handleRefusal(env: RefusedEnv) {- if (env.code === 'rate-limited') {- this.throttle(typeof env.retryInMs === 'number' ? env.retryInMs : 10_000)- return- }- if (env.code !== 'too-large' && env.code !== 'storage-failed' && env.code !== 'room-full') {- // a code from a newer relay: no recovery we can invent is better than- // leaving the op in the log, where `need` will retry it honestly- console.warn('[bento-sync] relay refused a frame:', env.code)- return- }- const culprit = this.matchRefused(env)- if (culprit) this.awaitingAck = this.awaitingAck.filter((o) => o !== culprit)- console.warn(`[bento-sync] relay refused a frame (${env.code})`, env)- this.hooks.onRefused?.(env.code, culprit?.ops ?? null)- }-- /**- * Which frame does this refusal name? The relay quotes no id, so: head of- * the ack queue by protocol order, CONFIRMED against the size it reported.- * A mismatch means the refusal was for a frame we don't track — snapshots- * are never acked, so they never enter the queue — and we must not hand the- * session somebody else's ops to drop on a guess. Ambiguity → null → the- * ops stay in the log (retried, at worst refused again and reported again),- * because a wrong drop is silent permanent data divergence.- */- private matchRefused(env: RefusedEnv): Outbound | null {- // Exact when the relay echoed our id. Everything below is the legacy- // fallback for relays that don't (and a self-hoster's relay may be a year- // old) — inferential, so it stays deliberately conservative.- if (env.k) return this.awaitingAck.find((o) => o.id === env.k) ?? null- // too-large measures the whole envelope; storage-failed measures i+d only- const byText = typeof env.got === 'number'- const want = byText ? env.got! : typeof env.bytes === 'number' ? env.bytes : null- const size = (o: Outbound) => (byText ? o.text.length : o.bytes)- const head = this.awaitingAck[0] ?? null- if (want === null) return head // room-full carries no size — order is all we have- if (head && size(head) === want) return head- return this.awaitingAck.find((o) => size(o) === want) ?? null- }-- /** Rate limited: hold everything for the window, then replay what we sent- * into it. Un-acked frames may or may not have landed — re-sending is safe- * (the CRDT dedups by actor:seq) and losing them silently is not. */- private throttle(ms: number) {- const wait = Math.min(Math.max(ms, 1000), 60_000)- const retryable = this.awaitingAck.filter((o) => ++o.tries <= OnlineTransport.MAX_RETRIES)- // past the retry cap we stop re-sending, but the op is NOT dropped: it- // stays in the session log for the next `need`/reconnect to carry.- this.awaitingAck = []- this.queue = [...retryable, ...this.queue]- if (this.pauseTimer) clearTimeout(this.pauseTimer)- this.paused = true- this.pauseTimer = setTimeout(() => {- this.pauseTimer = null- this.paused = false- for (const out of this.queue.splice(0)) this.write(out)- }, wait)- // transient and self-healing, so say it at most once a minute- const now = Date.now()- if (now - this.lastLimitNotice > 60_000) {- this.lastLimitNotice = now- this.hooks.onRefused?.('rate-limited', null)- }- }-- /** write now, or park it (disconnected, or inside a rate-limit backoff) */- private write(out: Outbound) {- if (!this.paused && this.ws && this.ws.readyState === WebSocket.OPEN) {- try {- this.ws.send(out.text)- } catch {- this.park(out) // send threw → onclose will reconnect and flush- return- }- if (out.ops) {- this.awaitingAck.push(out)- if (this.awaitingAck.length > OnlineTransport.ACK_WINDOW) this.awaitingAck.shift()- }- return- }- this.park(out)- }-- private park(out: Outbound) {- this.queue.push(out)- if (this.queue.length > 500) this.queue.shift()- }-- private async onEnvelope(text: string) {- let env: { i?: string; d?: string; q?: number; snap?: number; ctl?: string; p?: string } & RefusedEnv- try {- env = JSON.parse(text)- } catch {- return- }- // the owner revoked a key; if it's OURS, stand down for good (the relay- // refuses our reconnects anyway — don't retry into a wall of 403s)- if (env.ctl === 'revoked') {- if (env.p && env.p === this.myPub) {- console.info('[bento-sync] this copy’s access was revoked by the owner')- this.close()- }- return- }- // the relay would not take a frame and said so (v1.0.9 relay and later;- // older relays never send this, which is why every path here is additive)- if (env.ctl === 'refused') {- this.handleRefusal(env)- return- }- if (env.ctl === 'ack' || env.ctl === 'ready') {- // one ack = the oldest un-acked persisted frame landed- if (env.ctl === 'ack') this.awaitingAck.shift()- if (typeof env.q === 'number') {- this.saveSeq(env.q)- this.maybeSnapshot(env.q)- }- if (env.ctl === 'ready') {- this.inReplay = false- const wantSnap = this.hooks.onReady(this.replaySeen, env.q ?? 0)- this.replaySeen = new Set()- // fresh rooms and just-merged forks get a snapshot immediately so- // late joiners converge without needing the full op log- if (wantSnap || env.q === 0) void this.uploadSnapshot(env.q ?? 0)- }- return- }- if (!env.i || !env.d || !this.key) return- let payload: unknown- try {- const pt = await crypto.subtle.decrypt(- { name: 'AES-GCM', iv: b64u.dec(env.i) as BufferSource },- this.key,- b64u.dec(env.d) as BufferSource,- )- payload = JSON.parse(new TextDecoder().decode(pt))- } catch {- return // wrong key / corrupted — ignore- }- if (typeof env.q === 'number') this.saveSeq(env.q)- if (env.snap === 1) {- const s = payload as { doc: BentoDoc; state: SyncStateJSON }- if (s && s.doc && s.state) this.hooks.onSnap(s.doc, s.state)- return- }- const frame = payload as Frame- if (this.inReplay && frame.t === 'ops') {- for (const op of frame.ops) this.replaySeen.add(`${op.a}:${op.s}`)- }- this.onFrame(frame)- }-- private inReplay = true-- private snapInFlight = false-- /** every SNAP_EVERY persisted ops, upload a fresh encrypted snapshot */- private maybeSnapshot(q: number) {- if (q === 0 || q % SNAP_EVERY !== 0) return- void this.uploadSnapshot(q)- }-- /** encrypt + store the current (doc, state) as the room's snapshot */- async uploadSnapshot(q: number) {- if (this.snapInFlight) return- this.snapInFlight = true- try {- const snap = this.hooks.getSnapshot()- const text = await this.encrypt(JSON.stringify(snap))- if (text && this.ws && this.ws.readyState === WebSocket.OPEN) {- const env: Record<string, unknown> = { snap: 1, q, i: text.i, d: text.d }- if (this.signKey) env.g = await signFrame(this.signKey, text.i, text.d)- this.ws.send(JSON.stringify(env))- }- } finally {- this.snapInFlight = false- }- }-- private async encrypt(plain: string): Promise<{ i: string; d: string } | null> {- if (!this.key) return null- const iv = new Uint8Array(12)- crypto.getRandomValues(iv)- const ct = await crypto.subtle.encrypt(- { name: 'AES-GCM', iv: iv as BufferSource },- this.key,- new TextEncoder().encode(plain),- )- return { i: b64u.enc(iv), d: b64u.enc(new Uint8Array(ct)) }- }-- send(frame: Frame) {- void (async () => {- const enc = await this.encrypt(JSON.stringify(frame))- if (!enc) return- let env: Record<string, unknown> = enc- let ops: Op[] | null = null- const id = nextFrameId()- if (frame.t === 'ops') {- env = { k: id, p: 1, ...enc }- // sign the ciphertext so the relay verifies authorship while blind.- if (this.signKey) env.g = await signFrame(this.signKey, enc.i, enc.d)- ops = frame.ops- }- // remember what rode in the frame so a refusal can name it- this.write({ id, text: JSON.stringify(env), ops, bytes: enc.i.length + enc.d.length, tries: 0 })- })()- }-- close() {- this.closed = true- if (this.pauseTimer) { clearTimeout(this.pauseTimer); this.pauseTimer = null }- this.stopHeartbeat()- this.ws?.close()- this.ws = null- this.setStatus('closed')- }-- /** OWNER action: revoke one member key (or an invite key — cutting off every- * copy descended from that invite). Signed `rev.${pub}`; the relay stores it,- * drops that key's future writes/joins, and fans out a `revoked` note. */- async revokeKey(pub: string, ownerPub: string, ownerPriv: string): Promise<boolean> {- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return false- const g = await signText(ownerPriv, `rev.${pub}`)- this.ws.send(JSON.stringify({ ctl: 'revoke', p: pub, o: ownerPub, g }))- return true- }-}--// --- share/join glue ----------------------------------------------------------let active: OnlineTransport | null = null--export function onlineTransport(): OnlineTransport | null {- return active-}--/** inert stand-in when a re-keyed document has no collab config */-class NullTransport implements Transport {- readonly kind = 'off'- send() {}- close() {}-}--/** does this document want its relay connected? (absent `on` = true: v0.8.0- * files only carried collab while actively shared) */-export function sharingOn(store: Store): boolean {- const c = store.doc.collab- return !!c?.room && !!c.key && c.on !== false-}--/** connect the session to the relay in doc.collab (no-op unless sharing is on) */-export function joinFromDoc(session: SyncSession, store: Store): OnlineTransport | null {- if (offlineEnabled()) return null // the hard no-network switch wins over everything- if (active) return active- if (!sharingOn(store)) return null- session.addTransport((docId, onFrame) => {- // re-invoked whenever the session re-keys (doc replaced): consult the- // CURRENT document — its collab config may differ or be off- const collab = store.doc.collab- if (!collab?.room || !collab.key || collab.on === false || store.doc.docId !== docId) {- active = null- return new NullTransport()- }- active?.close()- // Auth shape per copy: reader → none (unsigned, relay drops writes);- // v2 owner → direct with ownerPriv; v2 member → invite chain (device key- // minted per-machine); legacy → the shared writer key pair.- let auth: AuthSpec | undefined- if (collab.role !== 'reader') {- if (collab.v === 2 && collab.owner && collab.ownerPriv) {- auth = { kind: 'direct', pub: collab.owner, priv: collab.ownerPriv }- } else if (collab.v === 2 && collab.owner && collab.invite) {- auth = { kind: 'chain', owner: collab.owner, invite: collab.invite, docId }- } else if (collab.writerPub) {- auth = { kind: 'direct', pub: collab.writerPub, priv: collab.writerPriv }- }- }- active = new OnlineTransport(collab.room, collab.key, docId, onFrame, {- onSnap: (doc, state) => session.applySnapshot(doc, state),- getSnapshot: () => session.snapshot(),- onOpen: () => session.hello(),- onReady: (seen) => session.onRelayReady(seen),- onRefused: (code, ops) => session.refused(code, ops),- }, auth)- return active- })- return active-}--/** flip sharing on and connect — the "Start live session" action.- * Credentials already exist (minted at creation); this only arms them. */-export async function startSharing(session: SyncSession, store: Store): Promise<OnlineTransport | null> {- if (offlineEnabled()) return null- if (active) return active- if (!store.doc.collab) {- const creds = await mintCollab()- store.commit(() => { store.doc.collab = creds })- }- store.commit(() => { store.doc.collab!.on = true })- return joinFromDoc(session, store)-}--/**- * Offline-mode disconnect: drop the relay WITHOUT touching doc.collab.on —- * the document's sharing intent is unchanged; this viewer just won't- * network. Turning offline mode off re-joins via the normal path.- */-export function disconnectOnline(session: SyncSession) {- if (active) {- session.removeTransport(active)- active = null- }-}--/** flip sharing off and disconnect. Credentials stay — copies saved during- * the session can rejoin if sharing is turned back on. */-export function stopSharing(session: SyncSession, store: Store) {- if (active) {- session.removeTransport(active)- active = null- }- if (store.doc.collab && store.doc.collab.on !== false) {- store.commit(() => {- store.doc.collab!.on = false- })- }-}+// It needed almost nothing to move: the E2EE transport, the credential+// minting, the invite/member signature chain and the reconnect logic never+// knew what a slide was — they work in terms of `doc.collab` and `docId`,+// which every Bento document has (PLATFORM §2).+//+// Even the hard no-network switch needed nothing: `offlineEnabled` was ALREADY+// in kernel/src/update.ts, and this app's update.ts is itself a facade over it.+// An injection point was built for it first and then removed — the dependency+// it was defending against did not exist.-/** revocation: mint a fresh room + key. Every previously sent copy loses- * access; only copies saved AFTER this can join future sessions. */-export async function rotateKeys(session: SyncSession, store: Store) {- stopSharing(session, store)- const fresh = await mintCollab()- store.commit(() => {- const sync = store.doc.collab?.sync- store.doc.collab = sync ? { ...fresh, sync } : fresh- })-}+export * from '../../../kernel/src/sync/online.ts';diff --git a/slides/src/sync/session.ts b/slides/src/sync/session.tsindex 3687d648..fe9422f9 100644--- a/slides/src/sync/session.ts+++ b/slides/src/sync/session.ts@@ -1,705 +1,79 @@// SPDX-License-Identifier: MIT// Copyright (c) 2026 The Bento authors-// bento-sync session — the bridge between the CRDT engine (crdt.ts) and the-// running editor. Owns: the differ hook on the store, transports (same-machine-// BroadcastChannel always; an online relay transport can be added), presence,-// and peer catch-up. See docs/collab-design.md.+// bento-sync session for bento/slides — the kernel session, bound to this app.//-// Wire protocol (one JSON frame per message; E2EE happens inside the online-// transport — this layer never knows):-// {t:'hello', a, vv, p} join/announce — receivers reply hello + missing ops-// {t:'ops', a, ops} op batch-// {t:'need', a, vv} gap catch-up request (receivers send missing ops)-// {t:'p', a, p} presence heartbeat {t:'bye', a} leave+// A FACADE, like crdt.ts beside it. The session moved to+// kernel/src/sync/session.ts once it had stopped knowing what a slide is:+// of its 727 lines, FIVE places did, and they are the five implemented below.+// Everything else — the differ hook, the shadow, presence, catch-up, gap+// recovery, blobs, the fork snapshot exchange — was already generic.//-// The differ is the whole integration: every local mutation already flows-// through store.commit/touch → 'doc' event → (debounced) diff against the-// session's shadow → ops out. Remote ops apply surgically by id and re-emit-// the same store events the editor already listens to. Zero editor rewrites.--import type { Store, ViewSnapshot } from '../store'-import type { BentoDoc, Slide } from '../model'-import { uid } from '../model'-import { SyncState, SYNC_V, BLOB_INLINE_MAX, type Op } from './crdt'-import { putBlob, getBlob, dataUriToBytes, bytesToDataUri, encodedSize, MAX_BLOB } from './blobs'-import { mintCollab } from './online'-import { lsGet, lsJson } from '../../../kernel/src/storage.ts'--export interface PresenceInfo {- name: string- color: string- /** current slide id */- slide: string- /** selected element ids */- sel: string[]- /** element id currently being text-edited (in-text presence) */- editing?: string- /** v2 fine-grained: the key this copy signs with — key-bound identity */- pub?: string- /** capability of this copy, derived locally from its collab material */- role?: 'owner' | 'editor' | 'viewer'-}--export interface Peer extends PresenceInfo {- actor: string- at: number-}--interface HelloFrame { t: 'hello'; a: string; vv: Record<string, number>; p: PresenceInfo }-interface OpsFrame { t: 'ops'; a: string; ops: Op[] }-interface NeedFrame { t: 'need'; a: string; vv: Record<string, number> }-interface PresFrame { t: 'p'; a: string; p: PresenceInfo }-interface ByeFrame { t: 'bye'; a: string }-/** state-based fork merge: a rejoining offline-edited copy announces itself */-interface SnapFrame {- t: 'snap'- a: string- doc: BentoDoc- state: import('./crdt').SyncStateJSON-}-/** every frame is stamped with the sync protocol version (`pv: SYNC_V`) by- * send(); frames without the current pv (old builds, stale relay logs from- * the bare-id era) are dropped in onFrame — their keys don't interoperate */-export type Frame = (HelloFrame | OpsFrame | NeedFrame | PresFrame | ByeFrame | SnapFrame) & {- pv?: number-}--export interface Transport {- readonly kind: string- send(frame: Frame): void- close(): void-}--/**- * Why the relay refused a frame (`{ctl:'refused', code, …}` — see- * server/sync-worker). Everything but 'rate-limited' is PERMANENT for the- * frame that drew it: retrying can only reproduce the refusal.- */-export type RefusalCode = 'too-large' | 'storage-failed' | 'room-full' | 'rate-limited'--/**- * Something the user deserves to know about the live session. The transport- * detects it, the session records the consequence, the editor renders the- * sentence (t() must run at display time, so no text crosses this boundary).- */-export interface SyncNotice {- code: RefusalCode- /** true = the change will never reach collaborators; false = retrying */- permanent: boolean- /** how many ops were abandoned (0 when the refused frame wasn't ours to name) */- ops: number- /** the abandoned ops carried embedded media — lets the UI say "that image" */- media?: boolean-}--/** Same-machine transport: every open tab/window of this document. */-class BroadcastTransport implements Transport {- readonly kind = 'local'- private ch: BroadcastChannel- constructor(docId: string, onFrame: (f: Frame) => void) {- this.ch = new BroadcastChannel(`bento-sync-${docId}`)- this.ch.onmessage = (ev) => onFrame(ev.data as Frame)- }- send(frame: Frame) {- this.ch.postMessage(frame)- }- close() {- this.ch.close()- }-}--const PEER_COLORS = ['#FF9E8A', '#8FA3BF', '#7FC8A9', '#E8C468', '#C792EA', '#6AB7D6', '#E88AB0', '#A9C77F']--const actorColor = (actor: string): string => {- let h = 0- for (let i = 0; i < actor.length; i++) h = (h * 31 + actor.charCodeAt(i)) >>> 0- return PEER_COLORS[h % PEER_COLORS.length]-}--/**- * Actor id: fresh per SESSION INSTANCE, deliberately — a reloaded tab is a- * new replica with empty CRDT state, and the engine skips "own" ops on- * apply, so reusing an id would make relay replay of the previous- * incarnation's ops a no-op. Random ids sidestep the whole class.- */-function tabActor(): string {- return Math.random().toString(36).slice(2, 10)-}--const DIFF_DEBOUNCE_MS = 90-const HEARTBEAT_MS = 5000-const PEER_TTL_MS = 13000--export class SyncSession {- readonly actor: string- state!: SyncState- private shadow = ''- private docId = ''- private log: Op[] = []- private transports: Transport[] = []- private peersMap = new Map<string, Peer>()- private applying = false- private diffTimer: number | null = null- private heartbeat: number | null = null- private peerListeners = new Set<() => void>()- private noticeListeners = new Set<(n: SyncNotice) => void>()- private editingEl: string | undefined- /** extra transports (the online relay) get plugged in here */- private makeExtraTransports: Array<(docId: string, onFrame: (f: Frame) => void) => Transport> = []-- constructor(private store: Store) {- this.actor = tabActor()- this.attach()- store.on('doc', () => this.onLocalChange())- store.on('current', () => this.pushPresence())- store.on('selection', () => this.pushPresence())- window.addEventListener('beforeunload', () => this.broadcast({ t: 'bye', a: this.actor }))- }-- // --- lifecycle ------------------------------------------------------------- /** a restored offline fork still owes the room its snapshot */- private forkPending = false-- /** the loaded doc arrived carrying collab creds (was saved/shared) */- private bornWithCollab = false- /** the user opted in this session (saved, or hit "Start live session") */- private explicitShare = false-- /** Should this doc auto-connect to the relay on open? See attach(). */- shareEligible(): boolean {- return this.bornWithCollab || this.explicitShare- }-- /** Mark that the user opted into sharing (save / explicit Start live). */- enableSharing() {- this.explicitShare = true- }-- private attach() {- this.docId = this.store.doc.docId- const doc = this.store.doc- // Auto-connect eligibility: a doc that ARRIVED carrying collab creds was- // saved/shared by someone — it should go live on open. A doc we mint creds- // for right now (the anonymous starter demo, a fresh template instance) is- // NOT auto-connected — it phones home only after the user saves or clicks- // "Start live session" (enableSharing). This keeps casual visitors off the- // relay and honours "nothing phones home unless you ask".- this.bornWithCollab = !!doc.collab- this.explicitShare = false- // credentials are minted AT CREATION: any copy of the file can join once- // it is live (on:true by default). Minting is async now (the writer- // keypair) — fine because a freshly-minted doc is never auto-connected, so- // the sub-frame gap before collab lands touches nothing. See eligibility.- if (!doc.collab) void this.ensureCollab()- const saved = doc.collab?.sync- if (saved && saved.v === SYNC_V) {- // this file was saved during/after a shared session: restore the CRDT- // state so our offline edits carry real registers, remote replay- // dedups by version vector, and a state-based snapshot exchange can- // merge the fork BOTH ways (see docs/collab-design.md)- this.state = SyncState.fromJSON(this.actor, JSON.parse(JSON.stringify(saved)))- this.forkPending = true- } else {- // no saved state, or state from the pre-composite-key era (v1) — that- // scheme collapsed same-id-on-many-slides, so it is discarded and the- // file joins as a never-synced adopt (deterministic keys from the doc)- this.state = new SyncState(this.actor)- }- this.state.adopt(doc)- this.shadow = JSON.stringify(doc)- this.log = []- this.peersMap.clear()- this.emitPeers()- for (const tr of this.transports) tr.close()- this.transports = [new BroadcastTransport(this.docId, (f) => this.onFrame(f))]- for (const mk of this.makeExtraTransports) this.transports.push(mk(this.docId, (f) => this.onFrame(f)))- this.hello() // announces + (for restored forks) broadcasts the state snapshot- if (this.heartbeat) clearInterval(this.heartbeat)- this.heartbeat = window.setInterval(() => {- this.pushPresence()- this.sweepPeers()- }, HEARTBEAT_MS)- }-- /** Mint collab credentials (incl. the writer keypair) for a doc created- * without them. Direct mutation (no undo entry), guarded against a race with- * a real collab arriving via loadDoc. */- private async ensureCollab() {- if (this.store.doc.collab) return- const creds = await mintCollab()- if (!this.store.doc.collab) this.store.doc.collab = creds- }-- /** register a factory for an additional transport (online relay) and connect it */- addTransport(mk: (docId: string, onFrame: (f: Frame) => void) => Transport): Transport {- this.makeExtraTransports.push(mk)- const tr = mk(this.docId, (f) => this.onFrame(f))- this.transports.push(tr)- this.broadcast({ t: 'hello', a: this.actor, vv: this.state.vv, p: this.presence() })- return tr- }-- removeTransport(tr: Transport) {- tr.close()- this.transports = this.transports.filter((x) => x !== tr)- this.makeExtraTransports = []- }-- get transportKinds(): string[] {- return this.transports.map((t) => t.kind)- }-- // --- local mutations → ops ------------------------------------------------ private onLocalChange() {- if (this.applying) return- if (this.store.doc.docId !== this.docId) {- // replaceDoc / loadDoc swapped in a different document — re-key- this.attach()- return- }- if (this.diffTimer) return- this.diffTimer = window.setTimeout(() => {- this.diffTimer = null- this.flush()- }, DIFF_DEBOUNCE_MS)- }-- /** diff now (also called before presence-relevant transitions) */- /**- * Assets too large for an op (docs/blob-offload.md) are uploaded to the- * relay's blob store and published as a small `blobs.<key>` reference, which- * IS small enough to sync. Runs after a local edit; the reference lands on- * the next flush like any other change.- *- * The bytes are always cached locally even when the upload fails, because- * the cache is per-ORIGIN: same-machine tabs syncing over BroadcastChannel- * resolve from it with no relay involved at all.- */- private async offloadAssets() {- const doc = this.store.doc- const assets = doc.assets ?? {}- const creds = this.blobCreds()- for (const [k, v] of Object.entries(assets)) {- if (typeof v !== 'string' || v.length <= BLOB_INLINE_MAX) continue- if (doc.blobs?.[k]) continue // already published- const parsed = dataUriToBytes(v)- if (!parsed) continue // raw SVG markup, not binary — leave it inline- if (encodedSize(parsed.bytes.length) > MAX_BLOB) {- this.notify('blob-too-large', k)- continue- }- if (!creds) continue // no relay yet; retry on the next edit- const res = await putBlob(- { base: creds.base, room: creds.room, tok: creds.tok }, creds.rawKey, parsed.bytes,- )- if (!res.ok) {- // 'unsupported' = relay has no blob storage. Not an error: small assets- // still inline, and same-origin tabs resolve from the local cache.- if (res.reason !== 'unsupported') this.notify(`blob-${res.reason}`, k)- continue- }- this.store.commit(() => {- const d = this.store.doc- ;(d.blobs ??= {})[k] = { key: res.key, mime: parsed.mime, size: parsed.bytes.length }- })- }- }-- /**- * The other direction: a peer published a reference we have no bytes for.- * Fetch, decrypt and materialise it into `assets` so the renderer can use it- * exactly as if it had arrived inline.- *- * A blob that never arrives leaves the asset ABSENT rather than blank —- * `assetRef()` in render.ts resolves a missing key to '', which the UI shows- * as a visibly empty element. Silent-but-wrong is the failure mode we are- * avoiding everywhere in this system.- */- private async resolveBlobs() {- const doc = this.store.doc- const refs = doc.blobs ?? {}- const creds = this.blobCreds()- for (const [k, ref] of Object.entries(refs)) {- if (doc.assets?.[k]) continue // already have the bytes- if (this.fetching.has(ref.key)) continue- this.fetching.add(ref.key)- try {- // cache-first, so same-origin tabs need no relay at all- const bytes = creds- ? await getBlob({ base: creds.base, room: creds.room, tok: creds.tok }, creds.rawKey, ref.key)- : null- if (!bytes) { this.notify('blob-unavailable', k); continue }- this.store.commit(() => {- const d = this.store.doc- ;(d.assets ??= {})[k] = bytesToDataUri(bytes, ref.mime)- })- } finally {- this.fetching.delete(ref.key)- }- }- }-- private fetching = new Set<string>()- /** set by the editor when an online transport exists */- /** Credentials the blob layer needs, taken from whichever transport can- * reach a relay.- *- * Resolved ON DEMAND, deliberately. The obvious shape — a hook assigned when- * the online transport connects — is what shipped broken: nothing ever- * assigned it, so `creds` was always null, every upload was skipped by the- * `if (!creds) continue` guard, and the whole offload was inert with no- * error anywhere. Transports are also torn down and rebuilt on reconnect and- * on rejoin, so even a correctly-assigned hook goes stale. Asking the live- * transport list each time cannot drift. */- private blobCreds(): { base: string; room: string; tok: string; rawKey: Uint8Array } | null {- for (const tr of this.transports) {- const f = (tr as { blobCreds?: () => { base: string; room: string; tok: string; rawKey: Uint8Array } | null }).blobCreds- if (typeof f !== 'function') continue- const c = f.call(tr)- if (c) return c- }- return null- }- private notify(code: string, detail?: string) {- // routed through the existing notice channel so the editor can toast it- try { (this as unknown as { noticeFn?: (c: string, d?: string) => void }).noticeFn?.(code, detail) } catch { /* none */ }- }-- flush() {- if (this.applying) return- const before = JSON.parse(this.shadow) as BentoDoc- let ops: Op[]- try {- ops = this.state.diff(before, this.store.doc, { text: true })- } catch (err) {- this.recoverFromDiffFailure(err)- return- }- this.shadow = JSON.stringify(this.store.doc)- // Any large asset the differ just skipped needs its bytes offloaded; the- // resulting reference syncs on the next flush like an ordinary change.- void this.offloadAssets()- if (!ops.length) return- this.log.push(...ops)- this.broadcast({ t: 'ops', a: this.actor, ops })- }-- /**- * A differ bug must not WEDGE the session. The shadow is only advanced after- * a successful diff, so an uncaught throw here poisons every later flush:- * the same delta is re-diffed, throws again, and nothing syncs for the rest- * of the session — on any slide, not just the element that broke. That- * amplifier is what turned the ~200KB-text stack overflow (fixed in crdt.ts:- * splice-without-spread) into total, silent collab failure. The trigger is- * gone; the amplifier stays armed for the next differ bug, so disarm it.- *- * Recovery, best-effort in this order:- * - Advance the shadow past the poison delta. Re-diffing it would just- * re-throw, and a wedged differ is strictly worse than one lost delta.- * - Ship a state snapshot. diff() mints ops and advances its registers as- * it goes, so a mid-diff throw leaves some changes stamped but never- * broadcast — they now live only in our doc VALUES. That is exactly the- * offline-fork case, and a snapshot is how those travel (see hello()).- * forkPending re-sends it on the next reconnect too.- *- * Deliberately not a SyncNotice: those name conditions a user can act on- * (too large, room full). This path is a bug — console is the right surface.- */- private recoverFromDiffFailure(err: unknown) {- console.error('[bento-sync] diff failed; recovering via snapshot', err)- this.shadow = JSON.stringify(this.store.doc)- this.forkPending = true- try {- // inlined rather than this.snapshot() — that calls flush(), and flush()- // is our caller- this.broadcast({- t: 'snap',- a: this.actor,- doc: JSON.parse(JSON.stringify(this.store.doc)) as BentoDoc,- state: JSON.parse(JSON.stringify(this.state.toJSON())),- })- } catch (e2) {- // snapshot itself failed (state unserializable) — the shadow is still- // advanced, so editing continues and the next reconnect retries- console.error('[bento-sync] snapshot recovery failed', e2)- }- }-- // --- remote frames ---------------------------------------------------------- private onFrame(f: Frame) {- if (f.pv !== SYNC_V) return // old-protocol frame (bare-id keys) — ignore- if (f.a === this.actor) return- switch (f.t) {- case 'hello': {- this.touchPeer(f.a, f.p)- // answer so the newcomer learns us + catch them up from our log,- // AND tell them our vv so ops they minted before connecting (which- // nothing else would push) flow back to us — need→ops terminates- this.send({ t: 'p', a: this.actor, p: this.presence() })- this.send({ t: 'need', a: this.actor, vv: this.state.vv })- const missing = this.state.missingFor(this.log, f.vv)- if (missing.length) this.send({ t: 'ops', a: this.actor, ops: missing })- break- }- case 'ops':- this.applyRemote(f.ops)- break- case 'need': {- const missing = this.state.missingFor(this.log, f.vv)- if (missing.length) this.send({ t: 'ops', a: this.actor, ops: missing })- break- }- case 'p':- this.touchPeer(f.a, f.p)- break- case 'snap':- this.applySnapshot(f.doc, f.state)- break- case 'bye':- this.peersMap.delete(f.a)- this.emitPeers()- break- }- }-- applyRemote(ops: Op[]) {- // make sure our own pending edits are diffed first (they pre-date the- // remote batch locally; LWW settles the rest)- this.flush()- for (const op of ops) if (!this.log.some((o) => o.a === op.a && o.s === op.s)) this.log.push(op)- const view = this.store.captureView()- this.applying = true- try {- const res = this.state.apply(this.store.doc, ops)- if (res.changed) this.afterRemoteChange(res.structure, view)- } finally {- this.applying = false- }- if (this.state.gappedActors.length) {- this.send({ t: 'need', a: this.actor, vv: this.state.vv })- }- }-- private afterRemoteChange(structure: boolean, view: ViewSnapshot) {- void this.resolveBlobs()- const store = this.store- // an all-slides-deleted race leaves an empty deck — heal with a blank- if (store.doc.slides.length === 0) {+// Behaviour is pinned by scripts/test-sync-session.ts, which was written+// against this file BEFORE the move and run unchanged after it.++export * from '../../../kernel/src/sync/session.ts';++import { SyncSession as KernelSession, type SyncHost } from '../../../kernel/src/sync/session.ts';+import type { Op } from './crdt';+import { SyncState } from './crdt';+import { uid } from '../model';+import type { Slide } from '../model';+import type { Store, ViewSnapshot } from '../store';++/** What a deck knows about itself that the session cannot work out. */+function slidesHost(store: Store): SyncHost {+ return {+ store,+ engine: SyncState,++ heal(): boolean {+ // an all-slides-deleted race leaves an empty deck — heal with a blank+ //+ // The id is RANDOM here, deliberately and unlike the other apps: the+ // repair is minted as a local op and nothing deduplicates it, so two+ // concurrent healers make two blank slides. That was the shipped+ // behaviour before this moved to the kernel and it stays — a spare blank+ // slide is visible in the sidebar and deleted in one click. An app where+ // the duplicate is INVISIBLE (a paragraph, a page) must derive the id+ // from docId instead; see the heal() contract in the kernel.+ if (store.doc.slides.length > 0) return false;const blank: Slide = {id: uid('s'),background: store.doc.theme.background,transition: 'fade',elements: [],notes: '',- }- store.doc.slides.push(blank)- // mint it as a local op so every replica converges on ONE healer's- // slide (LWW keeps all healers' slides; harmless extra blanks)- this.applying = false- this.flush()- this.applying = true- }- const { currentChanged, selectionChanged } = store.reconcileView(view)- this.shadow = JSON.stringify(store.doc)- store.doc.modified = new Date().toISOString()- store.setDirty(true)- store.emit('doc')- if (structure) {- store.emit('slides')- }- if (currentChanged) store.emit('current')- if (selectionChanged) store.emit('selection')- }-- // --- presence --------------------------------------------------------------- private presence(): PresenceInfo {- let name = 'Guest'- try {- name = lsGet('bento-author') || 'Guest'- } catch {- /* storage unavailable */- }- // key-bound identity (v2): which key this copy signs with + its capability.- // The device key is minted by the transport on first connect; until then a- // member's pub is simply absent from presence (it fills in on reconnect).- const c = this.store.doc.collab- let pub: string | undefined- let role: 'owner' | 'editor' | 'viewer' | undefined- if (c) {- if (c.role === 'reader') role = 'viewer'- else if (c.v === 2 && c.ownerPriv) { role = 'owner'; pub = c.owner }- else if (c.v === 2 && c.invite) {- role = 'editor'- pub = lsJson<{ pub?: string } | null>(`bento-member-${this.store.doc.docId}`, null)?.pub- } else if (c.writerPriv) { role = 'editor'; pub = c.writerPub }- }- return {- name,- color: actorColor(this.actor),- slide: this.store.slide?.id ?? '',- sel: this.store.selection.slice(),- ...(this.editingEl ? { editing: this.editingEl } : {}),- ...(pub ? { pub } : {}),- ...(role ? { role } : {}),- }- }-- /** canvas hooks this while a text element is being edited (M3 presence) */- setEditing(elId: string | undefined) {- if (this.editingEl === elId) return- this.editingEl = elId- this.pushPresence()- }-- private pushPresence() {- this.send({ t: 'p', a: this.actor, p: this.presence() })- }-- private touchPeer(actor: string, p: PresenceInfo) {- this.peersMap.set(actor, { ...p, actor, at: Date.now() })- this.emitPeers()- }-- private sweepPeers() {- const cut = Date.now() - PEER_TTL_MS- let changed = false- for (const [a, p] of this.peersMap) {- if (p.at < cut) {- this.peersMap.delete(a)- changed = true- }- }- if (changed) this.emitPeers()- }-- peers(): Peer[] {- return [...this.peersMap.values()].sort((a, b) => (a.actor < b.actor ? -1 : 1))- }-- onPeers(fn: () => void): () => void {- this.peerListeners.add(fn)- return () => this.peerListeners.delete(fn)- }-- private emitPeers() {- this.peerListeners.forEach((fn) => fn())- }-- // --- relay refusals --------------------------------------------------------- /** the editor subscribes here to toast what the relay refused */- onNotice(fn: (n: SyncNotice) => void): () => void {- this.noticeListeners.add(fn)- return () => this.noticeListeners.delete(fn)- }-- private emitNotice(n: SyncNotice) {- this.noticeListeners.forEach((fn) => fn(n))- }-- /**- * A transport reports that the relay refused a frame. For the PERMANENT- * codes the named ops can never be delivered, so they leave the resend log.- *- * Why dropping is the right call, and why it is narrow: `missingFor` answers- * every peer `need` (and `onRelayReady`) out of `log`, so an op the relay- * will always refuse would be re-offered, re-sent, re-refused — forever.- * That loop is the bug this exists to break. The price is real and cannot be- * undone: the local document KEEPS the change, remote replicas never see it,- * and nothing reconciles it later (short of the file being re-opened, which- * re-adopts the doc wholesale). Because it is a permanent divergence we drop- * ONLY the exact ops the refused frame carried — never a range, never the- * rest of the log, and never anything when the frame couldn't be identified.- */- refused(code: RefusalCode, ops: Op[] | null) {- const doomed = ops ?? []- if (doomed.length) {- const keys = new Set(doomed.map((o) => `${o.a}:${o.s}`))- this.log = this.log.filter((o) => !keys.has(`${o.a}:${o.s}`))- }- this.emitNotice({- code,- permanent: code !== 'rate-limited',- ops: doomed.length,- ...(carriesMedia(doomed) ? { media: true } : {}),- })- }-- // --- snapshots (online catch-up + file-fork merge) -------------------------- /** current (doc, sync-state) pair for an encrypted relay snapshot */- snapshot(): { doc: BentoDoc; state: import('./crdt').SyncStateJSON } {- this.flush()- return {- doc: JSON.parse(JSON.stringify(this.store.doc)) as BentoDoc,- state: JSON.parse(JSON.stringify(this.state.toJSON())),- }- }-- /** merge a remote snapshot (relay replay for far-behind joiners) */- applySnapshot(rdoc: BentoDoc, rstate: import('./crdt').SyncStateJSON) {- if (!rstate || rstate.v !== SYNC_V) return // pre-v2 room snapshot — unusable- this.flush()- const view = this.store.captureView()- this.applying = true- try {- const res = this.state.mergeSnapshot(this.store.doc, rdoc, rstate)- if (res.changed) this.afterRemoteChange(true, view)- } finally {- this.applying = false- }- }-- /** re-announce (an online transport reconnected) */- hello() {- this.broadcast({ t: 'hello', a: this.actor, vv: this.state.vv, p: this.presence() })- if (this.forkPending) {- // rejoining offline fork: our contributions live in doc values +- // restored registers, not ops — a state snapshot is how they travel- const s = this.snapshot()- this.broadcast({ t: 'snap', a: this.actor, doc: s.doc, state: s.state })- }- }-- /**- * Relay replay finished. `seen` holds the (actor,seq) pairs the room- * already has; anything in our log it lacks gets (re)sent for persistence- * — covers ops minted before the transport connected. Returns whether a- * fresh server snapshot should be uploaded (fork just merged).- */- onRelayReady(seen: Set<string>): boolean {- const missing = this.log.filter((o) => !seen.has(`${o.a}:${o.s}`))- if (missing.length) this.send({ t: 'ops', a: this.actor, ops: missing })- const fork = this.forkPending- this.forkPending = false- return fork- }-- /**- * Stamp the CRDT state into doc.collab.sync so the SAVED file can rejoin- * as a true fork later. Called by the save/serialize paths; only shared- * documents carry it (never-shared files stay clean).- */- stampInto(doc: BentoDoc) {- if (!doc.collab || doc.collab.on === false) return- this.flush()- doc.collab.sync = JSON.parse(JSON.stringify(this.state.toJSON()))- }-- // --- plumbing --------------------------------------------------------------- private send(frame: Frame) {- const stamped = { ...frame, pv: SYNC_V }- for (const tr of this.transports) tr.send(stamped)- }-- private broadcast(frame: Frame) {- this.send(frame)- }+ };+ store.doc.slides.push(blank);+ return true;+ },++ // The store owns this pair; the shape only forwards. Clamping after the+ // fact used to live here and was wrong in one specific way: when someone+ // else deleted a DIFFERENT slide, min()-ing the index moved this tab to+ // whatever slid into the slot. captureView records the slide IDS first, so+ // reconcileView can keep the same slide when it survives and choose the+ // nearest surviving neighbour when it does not (#262).+ captureView(): unknown {+ return store.captureView();+ },++ clampView(view?: unknown): boolean {+ const { currentChanged, selectionChanged } = store.reconcileView(view as ViewSnapshot);+ if (currentChanged) store.emit('current');+ return selectionChanged;+ },++ presence() {+ return { at: store.slide?.id ?? '', sel: store.selection.slice() };+ },++ changeEvents: ['doc'],+ structureEvents: ['slides', 'current'],+ presenceEvents: ['current', 'selection'],++ carriesMedia,+ };}/**@@ -708,19 +82,35 @@ export class SyncSession {* difference between a message the user can act on and one they can't.* Structural probe only — a refused batch can be megabytes, so nothing here* re-serializes or walks deep into it.+ *+ * App-shaped: `type: 'image' | 'media'` with a `src` is what an embedded blob+ * looks like in a DECK. A word processor's would look nothing like it.*/function carriesMedia(ops: Op[]): boolean {- const isData = (v: unknown): boolean => typeof v === 'string' && v.startsWith('data:')+ const isData = (v: unknown): boolean => typeof v === 'string' && v.startsWith('data:');const inEl = (n: unknown): boolean => {- const el = n as { type?: string; src?: unknown } | null- return !!el && (el.type === 'image' || el.type === 'media') && isData(el.src)- }+ const el = n as { type?: string; src?: unknown } | null;+ return !!el && (el.type === 'image' || el.type === 'media') && isData(el.src);+ };return ops.some((o) => {- if (o.op === 'set') return isData(o.v) // element src, or a doc-level assets.<k>+ if (o.op === 'set') return isData(o.v); // element src, or a doc-level assets.<k>if (o.op === 'ins') {- const node = o.node as { elements?: unknown[] }- return inEl(o.node) || !!node.elements?.some(inEl)+ const node = o.node as { elements?: unknown[] };+ return inEl(o.node) || !!node.elements?.some(inEl);}- return false- })+ return false;+ });+}++/**+ * The session bound to bento/slides.+ *+ * Constructed as `new SyncSession(store)`, exactly as before the host existed+ * — which is what keeps the seam invisible to editor.ts and everything else+ * that already builds one.+ */+export class SyncSession extends KernelSession {+ constructor(store: Store) {+ super(slidesHost(store));+ }}diff --git a/spaces/src/model.ts b/spaces/src/model.tsindex cdb34329..9adc91f5 100644--- a/spaces/src/model.ts+++ b/spaces/src/model.ts@@ -13,6 +13,8 @@// meeting a future 'kanban' block keeps it and renders its html fallback.// There is no server; a break here is permanent.+import type { CollabCreds } from './sync/crdt.ts'+export const FORMAT = 'bento/spaces'export const FORMAT_VERSION = 1@@ -154,8 +156,17 @@ export interface SpacesDoc {fonts?: Array<{ family: string; asset: string; weight?: string; style?: string }>readonly?: booleantemplate?: boolean- /** RESERVED — collaboration credentials, unused until collab ships */- collab?: unknown+ /**+ * Collaboration credentials (PLATFORM §2).+ *+ * Was `unknown` and marked RESERVED "unused until collab ships". It has:+ * sync/session.ts binds this app to the kernel session. The type is the+ * KERNEL's so there is one definition of what a room, a key and an invite+ * chain are — the deployed relay verifies against that shape, and a second+ * local description of it is how a client and the worker drift apart.+ * `import type` is erased, so this adds no runtime dependency.+ */+ collab?: CollabCreds[extra: string]: unknown}diff --git a/spaces/src/store.ts b/spaces/src/store.tsindex 52a4eccf..015e29bd 100644--- a/spaces/src/store.ts+++ b/spaces/src/store.ts@@ -189,7 +189,17 @@ export class Store {if (wasClean) this.emit('doc')}- private reindex(): void {+ /**+ * Rebuild the id index, and fall back to the home page if the page being+ * viewed no longer exists.+ *+ * PUBLIC because a remote collaborator's edit lands on `doc` directly —+ * bypassing commit, deliberately, so it never joins this person's undo+ * stack — and every `block(id)` / `page` read after that would otherwise+ * answer from a stale index. sync/session.ts calls it. It was private while+ * the only writer was the store itself.+ */+ reindex(): void {this.index = buildIndex(this.doc)if (!this.index.page.has(this.pageId)) this.pageId = homePage(this.doc)?.id ?? ''}diff --git a/spaces/src/sync/crdt.ts b/spaces/src/sync/crdt.tsnew file mode 100644index 00000000..a8ea8932--- /dev/null+++ b/spaces/src/sync/crdt.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento-sync for bento/spaces — the kernel engine, bound to this app's shape.+//+// A FACADE, exactly as slides/src/sync/crdt.ts is. The engine lives in+// kernel/src/sync/crdt.ts and takes its document shape as two property names,+// so the same algebra serves both apps without either one's vocabulary living+// in the kernel. The kernel's own DocShape comment already names this binding+// (`'slides' | 'pages'`, `'elements' | 'blocks'`) — the seam was designed for+// it before there was anything to bind.++export * from '../../../kernel/src/sync/crdt.ts'++import { SyncEngine, shape } from '../../../kernel/src/sync/crdt.ts'+import type { DocShape } from '../../../kernel/src/sync/crdt.ts'++/**+ * bento/spaces: the document holds `pages`, a page holds `blocks`.+ *+ * These two strings are the whole difference between this app's engine and+ * slides'. Treat them as frozen from the first shared file: every persisted+ * SyncStateJSON and every relay frame is minted under them, so changing either+ * would fork a space from its own copies.+ *+ * Note what is NOT synced structurally here. A page's `parent` is an ordinary+ * property — the page TREE is derived at read time from that field+ * (`model.ts effectiveParents`), so the CRDT only has to agree on the flat+ * pre-order array and the parent value, and cycle repair stays a pure function+ * of the document. Trying to sync the tree as a hierarchy would put two sources+ * of truth in the file.+ */+export const SPACES_SHAPE: DocShape = shape('pages', 'blocks')++/** The engine bound to bento/spaces. */+export class SyncState extends SyncEngine {+ constructor(actor: string) {+ super(actor, SPACES_SHAPE)+ }+}diff --git a/type/index.html b/type/index.htmlnew file mode 100644index 00000000..57028096--- /dev/null+++ b/type/index.html@@ -0,0 +1,20 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="color-scheme" content="only light" />+ <meta name="generator" content="bento-type" />+ <title>bento/type</title>+ <!-- NOTICE+ bento/type — MIT licensed. https://bento.page+ This file is the document, the viewer and the editor. The runtime is+ open source; the document itself is the JSON block below.+ -->+ <script type="application/bento+json" id="bento-doc"></script>+ </head>+ <body>+ <div id="app"></div>+ <script type="module" src="/src/main.ts"></script>+ </body>+</html>diff --git a/type/package-lock.json b/type/package-lock.jsonnew file mode 100644index 00000000..4ca7ca97--- /dev/null+++ b/type/package-lock.json@@ -0,0 +1,1297 @@+{+ "name": "bento-type",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "bento-type",+ "version": "0.1.0",+ "license": "MIT",+ "devDependencies": {+ "@types/node": "^24.13.2",+ "typescript": "~5.8.3",+ "vite": "^7.1.1",+ "vite-plugin-singlefile": "^2.3.3"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",+ "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",+ "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",+ "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",+ "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",+ "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",+ "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",+ "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",+ "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",+ "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",+ "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",+ "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",+ "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",+ "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",+ "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",+ "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",+ "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",+ "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",+ "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",+ "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",+ "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",+ "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",+ "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",+ "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",+ "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",+ "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",+ "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@napi-rs/lzma-linux-x64-gnu": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",+ "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^22.20 || ^24.12 || >=25"+ }+ },+ "node_modules/@rollup/rollup-android-arm-eabi": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.4.tgz",+ "integrity": "sha512-RrPokAb7dmbxFoeO3TloqHyOjgye8RkBhSqmp4aJMIex4c9r46ZstPnleDQOq1t46VOVjwIuwNogIqbodV1Vvg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-android-arm64": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.4.tgz",+ "integrity": "sha512-JKuJc+pnpks2pjy7L/N3v/cAkZxYlnmuZoD840ldbMI5KDbC4iO9NKwPKYdjYFCMAIIlBzYSFHxIJVYzRo2/8A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-darwin-arm64": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.4.tgz",+ "integrity": "sha512-krw5uS2STmvJ02x0uTXHbqQNuz+9eZ1iw+qXk9dmW2gvV4jV7O2hEoOnuhFrpOPiel1mBFtqbxYZZtC46hXLOw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-darwin-x64": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.4.tgz",+ "integrity": "sha512-wsTxtgApb4PrOsNJIm0FZ1h3WvCC+k9uxLJ4ad75hgoS4NiRes2SoJFlDAyMwiUY8IssDqGcHbXuN0sx1tfF1A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-arm64": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.4.tgz",+ "integrity": "sha512-GUOnQlyZe3yAXhWOtOMsn5Qkrv5E5mZXa0thbARWi5Ei2szlVXJFQhddZ4HbAzh8q92w5twp+CQvs/eFanz9YQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-x64": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.4.tgz",+ "integrity": "sha512-/Y7f3QuxjzPKsjA/rfEDa3+0vXqyjmJ50Ln8dPpCmWkKTrUoWHG1cWhTqaAMLob2m2nESWuC7yGrREz019Ztqg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.4.tgz",+ "integrity": "sha512-81wiiX3v7aqy+T+bT61TJ78yJjRquqFFTTbAPt08imfQQzkPIW8t6aJbkTagtCCrXMNc9D66+geqlK7ydLPNqA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.4.tgz",+ "integrity": "sha512-9kmDIvNZqdoHOBZgNtpTBeLWYO/LVipM3H/j62P8848/l/VPEQL6N3uxU9pvP1oZAsXyC2MEnFP3ovRjo7WYNQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-gnu": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.4.tgz",+ "integrity": "sha512-CcnXHWnXg69g+DX5VWL3FHts3qMRN2uVEHX+BZvGLdd07/gXkn3ePjYtO1LDJvxkGKVHMclKBRa1QUTH+6toYQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-musl": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.4.tgz",+ "integrity": "sha512-iFOibiHnTRuhrWLlRsOQFdZJJIa7S8OwkneJr4ocALP16u5yk6lWLINFwhHaEqBFMsKDUZofLkGos7+CPzGB3g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-loong64-gnu": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.4.tgz",+ "integrity": "sha512-XnWYMI7euHlb5a871xPja+Gm7DRCFU+FGRrtS2sMq9N8FvqtpagUy6gD4YOemC5MRk9xbh8+jYMEJbigFQwsgA==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-loong64-musl": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.4.tgz",+ "integrity": "sha512-qGDAlO0U8xedCcsdRm9oaoQY8DAx/QT7uIxJWhCdx0ceIWX783UC9QSYkdpzAe29wNiVfp24+bZdQmn49o45SQ==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.4.tgz",+ "integrity": "sha512-ru4H6ezD7ysA5EiEK6qkkaEb4modH8CTej6kUy/gQi20u3kB3G7Zn8snXXkeJSCOFKG/rbPPtM/+9Wgas1961w==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-ppc64-musl": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.4.tgz",+ "integrity": "sha512-2W4MO5WQVJnbJaZdvDb9rhBDuFU1nKIepPFpJUBsTh2k1YY2g+ODViaWuyOAjQ5cOP7NvrvLzt3wvHOoiAvc7w==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.4.tgz",+ "integrity": "sha512-+fxjfuoAmVMCYV5QyjoIpu0cp5DOiOTeqYFk1AVaxGr+/ravWLX89XfQmptsoWcaVy/TGf2hexzbUOrCQIL1CQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-musl": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.4.tgz",+ "integrity": "sha512-jTn8JfHGL4djjFxPuM06LmNUJDsst2jeVlsd9OmIH6zc5sC9K6rIuO4YajXatLUpBmBKl6b35ro1QZocLi+tcA==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-s390x-gnu": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.4.tgz",+ "integrity": "sha512-oCJCJL4pXsoDcP2QZ+JVlPTIRc6266zsIaeJJsWImmF7HO0W8nb6HuSgZlMWxJwaPf8ehbSw8yo0EUw925hKsA==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-gnu": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.4.tgz",+ "integrity": "sha512-W69hukhZ3KKNRCaMIEzKvcFye42hh0FE1+YoYaf5+Ikacuftoco6yO/xouz0hc5d5W/s3yBro5jRiuEE/Q5vUw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-musl": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.4.tgz",+ "integrity": "sha512-qiXbGG2jkjXhzXpsFZSR2Xpb8DN/UaxYsbb/STbuR/6fpaDgRmmaq1B/LmtF2wQFOFOSsK2jdE0RZ3a0zHn4QA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-openbsd-x64": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.4.tgz",+ "integrity": "sha512-nWeM//hxv8mIo6jD7Hu4o48DVmV9pbV6gsKaWU+4NFyqHoPKwrkRiZGLKUhOBk8qNmDmpwFtPKg80Bo/Tn4xiQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ]+ },+ "node_modules/@rollup/rollup-openharmony-arm64": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.4.tgz",+ "integrity": "sha512-s62SQ/vgsRSvMwDkOEfTqfgASF0f26ZNaQuTA6Aok5lrikf89yI2W0gFHvZb2Jpgc6N8JnOKZgCK2iciO3CsxQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ]+ },+ "node_modules/@rollup/rollup-win32-arm64-msvc": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.4.tgz",+ "integrity": "sha512-J6wGf8TVGbXJq+HH+ttTvrcfNKPbuZecV6KT1B8I18BC5IURUh5kl4Yl5OEP5eFIUoI5BWxCsyYMhFsDx8kekw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-ia32-msvc": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.4.tgz",+ "integrity": "sha512-zmfrQd/0wu6oJs8Vq8KwY/YtsKSsLtKe/HwAP4Wqy8LhWjeT55fHRAkOhYQ12wI3ayS4Tt12d5CDRD7N96SAYQ==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-gnu": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.4.tgz",+ "integrity": "sha512-qPzHqdj9rfUD+w79dtE07zi/kFwKyCJqplp5K5ygeLTp7jLpAoc16OAH39HSmRC9UpozaecsleI8uAdEj6v2yw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-msvc": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.4.tgz",+ "integrity": "sha512-zD6NdeWEByGE9QF9vCrlJ5YQB4oq9q91kPZS37Jwj5hOkvR1lTBSpsKhKDw4IJtbQ35LsTS1HD9DZYGKIshU1Q==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@types/estree": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/node": {+ "version": "24.13.3",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",+ "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~7.18.0"+ }+ },+ "node_modules/braces": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",+ "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fill-range": "^7.1.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/esbuild": {+ "version": "0.28.2",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",+ "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.28.2",+ "@esbuild/android-arm": "0.28.2",+ "@esbuild/android-arm64": "0.28.2",+ "@esbuild/android-x64": "0.28.2",+ "@esbuild/darwin-arm64": "0.28.2",+ "@esbuild/darwin-x64": "0.28.2",+ "@esbuild/freebsd-arm64": "0.28.2",+ "@esbuild/freebsd-x64": "0.28.2",+ "@esbuild/linux-arm": "0.28.2",+ "@esbuild/linux-arm64": "0.28.2",+ "@esbuild/linux-ia32": "0.28.2",+ "@esbuild/linux-loong64": "0.28.2",+ "@esbuild/linux-mips64el": "0.28.2",+ "@esbuild/linux-ppc64": "0.28.2",+ "@esbuild/linux-riscv64": "0.28.2",+ "@esbuild/linux-s390x": "0.28.2",+ "@esbuild/linux-x64": "0.28.2",+ "@esbuild/netbsd-arm64": "0.28.2",+ "@esbuild/netbsd-x64": "0.28.2",+ "@esbuild/openbsd-arm64": "0.28.2",+ "@esbuild/openbsd-x64": "0.28.2",+ "@esbuild/openharmony-arm64": "0.28.2",+ "@esbuild/sunos-x64": "0.28.2",+ "@esbuild/win32-arm64": "0.28.2",+ "@esbuild/win32-ia32": "0.28.2",+ "@esbuild/win32-x64": "0.28.2"+ }+ },+ "node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/fill-range": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",+ "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "to-regex-range": "^5.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/is-number": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.12.0"+ }+ },+ "node_modules/micromatch": {+ "version": "4.0.8",+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",+ "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "braces": "^3.0.3",+ "picomatch": "^2.3.1"+ },+ "engines": {+ "node": ">=8.6"+ }+ },+ "node_modules/micromatch/node_modules/picomatch": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",+ "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/nanoid": {+ "version": "3.3.18",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",+ "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/picomatch": {+ "version": "4.0.5",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",+ "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/postcss": {+ "version": "8.5.26",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",+ "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.17",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/rollup": {+ "version": "4.62.4",+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.4.tgz",+ "integrity": "sha512-RXOqwaPsBGjMNMa4sQjDjHieHEZDFoj/Rdr46l2MU5DfEs16wHJPC2RPTPHWhNl+M3aI472LLqFkFKut4SblOg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/estree": "1.0.9"+ },+ "bin": {+ "rollup": "dist/bin/rollup"+ },+ "engines": {+ "node": ">=18.0.0",+ "npm": ">=8.0.0"+ },+ "optionalDependencies": {+ "@napi-rs/lzma-linux-x64-gnu": "1.5.1",+ "@rollup/rollup-android-arm-eabi": "4.62.4",+ "@rollup/rollup-android-arm64": "4.62.4",+ "@rollup/rollup-darwin-arm64": "4.62.4",+ "@rollup/rollup-darwin-x64": "4.62.4",+ "@rollup/rollup-freebsd-arm64": "4.62.4",+ "@rollup/rollup-freebsd-x64": "4.62.4",+ "@rollup/rollup-linux-arm-gnueabihf": "4.62.4",+ "@rollup/rollup-linux-arm-musleabihf": "4.62.4",+ "@rollup/rollup-linux-arm64-gnu": "4.62.4",+ "@rollup/rollup-linux-arm64-musl": "4.62.4",+ "@rollup/rollup-linux-loong64-gnu": "4.62.4",+ "@rollup/rollup-linux-loong64-musl": "4.62.4",+ "@rollup/rollup-linux-ppc64-gnu": "4.62.4",+ "@rollup/rollup-linux-ppc64-musl": "4.62.4",+ "@rollup/rollup-linux-riscv64-gnu": "4.62.4",+ "@rollup/rollup-linux-riscv64-musl": "4.62.4",+ "@rollup/rollup-linux-s390x-gnu": "4.62.4",+ "@rollup/rollup-linux-x64-gnu": "4.62.4",+ "@rollup/rollup-linux-x64-musl": "4.62.4",+ "@rollup/rollup-openbsd-x64": "4.62.4",+ "@rollup/rollup-openharmony-arm64": "4.62.4",+ "@rollup/rollup-win32-arm64-msvc": "4.62.4",+ "@rollup/rollup-win32-ia32-msvc": "4.62.4",+ "@rollup/rollup-win32-x64-gnu": "4.62.4",+ "@rollup/rollup-win32-x64-msvc": "4.62.4",+ "fsevents": "~2.3.2"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/tinyglobby": {+ "version": "0.2.17",+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fdir": "^6.5.0",+ "picomatch": "^4.0.4"+ },+ "engines": {+ "node": ">=12.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/SuperchupuDev"+ }+ },+ "node_modules/to-regex-range": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "is-number": "^7.0.0"+ },+ "engines": {+ "node": ">=8.0"+ }+ },+ "node_modules/typescript": {+ "version": "5.8.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",+ "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici-types": {+ "version": "7.18.2",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",+ "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/vite": {+ "version": "7.3.6",+ "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz",+ "integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "esbuild": "^0.27.0 || ^0.28.0",+ "fdir": "^6.5.0",+ "picomatch": "^4.0.3",+ "postcss": "^8.5.6",+ "rollup": "^4.43.0",+ "tinyglobby": "^0.2.15"+ },+ "bin": {+ "vite": "bin/vite.js"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "funding": {+ "url": "https://github.com/vitejs/vite?sponsor=1"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ },+ "peerDependencies": {+ "@types/node": "^20.19.0 || >=22.12.0",+ "jiti": ">=1.21.0",+ "less": "^4.0.0",+ "lightningcss": "^1.21.0",+ "sass": "^1.70.0",+ "sass-embedded": "^1.70.0",+ "stylus": ">=0.54.8",+ "sugarss": "^5.0.0",+ "terser": "^5.16.0",+ "tsx": "^4.8.1",+ "yaml": "^2.4.2"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ },+ "jiti": {+ "optional": true+ },+ "less": {+ "optional": true+ },+ "lightningcss": {+ "optional": true+ },+ "sass": {+ "optional": true+ },+ "sass-embedded": {+ "optional": true+ },+ "stylus": {+ "optional": true+ },+ "sugarss": {+ "optional": true+ },+ "terser": {+ "optional": true+ },+ "tsx": {+ "optional": true+ },+ "yaml": {+ "optional": true+ }+ }+ },+ "node_modules/vite-plugin-singlefile": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/vite-plugin-singlefile/-/vite-plugin-singlefile-2.3.3.tgz",+ "integrity": "sha512-XVnGH0QzbOa8fxRSsHdCarVN1BSBXNi7uLMQYlrGRN5apdHkk62XQWRJhVever0lnfuyBkwn+kvVChdm/OoOUg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "micromatch": "^4.0.8"+ },+ "engines": {+ "node": ">18.0.0"+ },+ "peerDependencies": {+ "rollup": "^4.59.0",+ "vite": "^5.4.21 || ^6.0.0 || ^7.0.0 || ^8.0.0"+ },+ "peerDependenciesMeta": {+ "rollup": {+ "optional": true+ }+ }+ }+ }+}diff --git a/type/package.json b/type/package.jsonnew file mode 100644index 00000000..e06ab353--- /dev/null+++ b/type/package.json@@ -0,0 +1,19 @@+{+ "name": "bento-type",+ "private": true,+ "version": "0.1.0",+ "type": "module",+ "license": "MIT",+ "scripts": {+ "dev": "vite",+ "build": "tsc -b && vite build",+ "build:single": "tsc -b && SINGLEFILE=1 vite build --outDir dist-single && mv dist-single/index.html dist-single/Bento_Type.bento.html && node ../scripts/postbuild-compress.mjs dist-single/Bento_Type.bento.html --generator bento-type --title \"bento/type\"",+ "preview": "vite preview"+ },+ "devDependencies": {+ "@types/node": "^24.13.2",+ "typescript": "~5.8.3",+ "vite": "^7.1.1",+ "vite-plugin-singlefile": "^2.3.3"+ }+}diff --git a/type/src/canon.ts b/type/src/canon.tsnew file mode 100644index 00000000..d3e045ab--- /dev/null+++ b/type/src/canon.ts@@ -0,0 +1,170 @@+// SPDX-License-Identifier: MIT+// Canonicalization + the signature chain, for bento/type.+//+// WHY THIS IS THE HIGH-RISK SMALL PIECE. A signature is over BYTES. If two+// honest parties can serialize the same document to different bytes, every+// signature is worthless; if two DIFFERENT documents can serialize to the same+// bytes, every signature is a forgery waiting to happen. Neither failure is+// visible until someone is in a dispute, which is the worst possible time.+//+// The rule set here is RFC 8785 (JSON Canonicalization Scheme) plus two+// deliberate additions, both of which JCS leaves open and both of which bite a+// word processor specifically:+//+// 1. UNICODE NORMALIZATION. JCS canonicalizes structure, not text. "é" as+// U+00E9 and as U+0065 U+0301 are different byte strings and identical+// documents — and a Mac and a Windows machine will genuinely produce+// different ones from the same keystrokes. We normalize to NFC.+// 2. AN EXPLICIT EXCLUDE LIST, not an include list. Volatile fields+// (modified, sync state, cached previews) must not enter the signature or+// merely opening a file breaks it. An exclude list fails SAFE: a new+// content field added by a later version is signed by default, whereas a+// forgotten include would silently leave new content unsigned.+//+// `slides/src/autosave.ts` already computes a content key on this principle+// ("excludes volatile fields ... that churn without a real edit"). This is the+// same idea made exact enough to sign.++import type { Signature } from './model.ts';++export interface ChainEntry { ok: boolean; why: string | null; linked: boolean; name: string }+export interface ChainResult { ok: boolean; entries: ChainEntry[] }++/** Fields that never enter a signature. Everything else is signed. */+export const VOLATILE = new Set([+ 'modified', // touched by every save+ 'sync', // CRDT state, per-replica+ 'collab', // credentials + room state+ 'preview', // cached first-page render+ 'signatures', // the chain itself — a signature cannot cover itself+ 'autosave',+]);++/** RFC 8785 number serialization: ECMAScript Number::toString, with -0 → 0. */+function num(n: number): string {+ if (!Number.isFinite(n)) throw new TypeError(`non-finite number in document: ${n}`);+ if (Object.is(n, -0)) return '0';+ return String(n);+}++/** RFC 8785 string serialization: minimal escaping, NFC-normalized. */+function str(s: string): string {+ const t = s.normalize('NFC');+ let out = '"';+ for (const ch of t) {+ const c = ch.codePointAt(0) ?? 0;+ if (ch === '"') out += '\\"';+ else if (ch === '\\') out += '\\\\';+ else if (c === 0x08) out += '\\b';+ else if (c === 0x0c) out += '\\f';+ else if (c === 0x0a) out += '\\n';+ else if (c === 0x0d) out += '\\r';+ else if (c === 0x09) out += '\\t';+ else if (c < 0x20) out += '\\u' + c.toString(16).padStart(4, '0');+ else out += ch;+ }+ return out + '"';+}++/**+ * Canonical JSON. Keys sorted by UTF-16 code unit (RFC 8785 §3.2.3), volatile+ * fields dropped at EVERY level, no insignificant whitespace.+ */+export function canonicalize(value: unknown, { volatile = VOLATILE } = {}): string {+ const go = (v: unknown): string => {+ if (v === null) return 'null';+ if (typeof v === 'boolean') return v ? 'true' : 'false';+ if (typeof v === 'number') return num(v);+ if (typeof v === 'string') return str(v);+ if (Array.isArray(v)) return '[' + v.map(go).join(',') + ']';+ if (typeof v === 'object') {+ const o = v as Record<string, unknown>;+ const keys = Object.keys(o)+ .filter(k => !volatile.has(k) && o[k] !== undefined)+ .sort(); // UTF-16 code-unit order+ return '{' + keys.map(k => str(k) + ':' + go(o[k])).join(',') + '}';+ }+ throw new TypeError(`cannot canonicalize ${typeof v}`);+ };+ return go(value);+}++const enc = new TextEncoder();++// base64url, isomorphic. The first version used Node's Buffer, which passes+// every test under `node` and throws "Buffer is not defined" the moment the+// same module is loaded in a browser — where this code actually has to run.+// btoa/atob exist in both.+const b64u = (buf: ArrayBuffer | Uint8Array): string => {+ const bytes = new Uint8Array(buf);+ let s = '';+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+};+const unb64u = (s: string): Uint8Array => {+ const t = s.replace(/-/g, '+').replace(/_/g, '/');+ const bin = atob(t + '='.repeat((4 - (t.length % 4)) % 4));+ const out = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);+ return out;+};++export async function digest(doc: unknown): Promise<string> {+ const bytes = enc.encode(canonicalize(doc));+ return b64u(await crypto.subtle.digest('SHA-256', bytes));+}++// ---------------------------------------------------------------- signatures+const EC = { name: 'ECDSA', namedCurve: 'P-256' };+const SIG = { name: 'ECDSA', hash: 'SHA-256' };++export const newKey = (): Promise<CryptoKeyPair> =>+ crypto.subtle.generateKey(EC, true, ['sign', 'verify']) as Promise<CryptoKeyPair>;+export const exportPub = async (k: CryptoKeyPair): Promise<string> =>+ b64u(await crypto.subtle.exportKey('raw', k.publicKey));++/**+ * Sign a revision, chaining to the previous signature.+ *+ * The signed text is `bento-type-sig.v1|<docId>|<content digest>|<prev sig or "">`.+ *+ * Chaining is what buys ORDER without a trusted clock. A self-asserted+ * timestamp can be backdated freely, so it is carried for display and+ * deliberately NOT relied on; what cannot be faked is that signature n commits+ * to signature n-1, so the sequence is tamper-evident even though the times+ * are not. The UI should say "signed after B's revision", never "signed at+ * 14:32" — see type-design.md §3.3.+ */+export async function sign(+ doc: { docId: string },+ key: CryptoKeyPair,+ { name = '', prev = null }: { name?: string; prev?: { sig: string } | null } = {},+): Promise<Signature> {+ const content = await digest(doc);+ const prevSig = prev ? prev.sig : '';+ const text = `bento-type-sig.v1|${doc.docId}|${content}|${prevSig}`;+ const sig = b64u(await crypto.subtle.sign(SIG, key.privateKey, enc.encode(text)));+ return { alg: 'ES256', pub: await exportPub(key), name, content, prev: prevSig, sig };+}++export async function verify(doc: { docId: string }, entry: Signature): Promise<{ ok: boolean; why: string | null }> {+ const content = await digest(doc);+ if (content !== entry.content) return { ok: false, why: 'content-changed' };+ const pub = await crypto.subtle.importKey('raw', unb64u(entry.pub), EC, false, ['verify']);+ const text = `bento-type-sig.v1|${doc.docId}|${entry.content}|${entry.prev}`;+ const ok = await crypto.subtle.verify(SIG, pub, unb64u(entry.sig), enc.encode(text));+ return { ok, why: ok ? null : 'bad-signature' };+}++/** Verify a whole chain: every signature valid, and correctly linked. */+export async function verifyChain(doc: { docId: string }, chain: Signature[]): Promise<ChainResult> {+ const out: ChainEntry[] = [];+ let expectedPrev = '';+ for (const entry of chain) {+ const r = await verify(doc, entry);+ const linked = entry.prev === expectedPrev;+ out.push({ ...r, linked, name: entry.name });+ expectedPrev = entry.sig;+ }+ return { ok: out.every(r => r.ok && r.linked), entries: out };+}diff --git a/type/src/editor.ts b/type/src/editor.tsnew file mode 100644index 00000000..925c8071--- /dev/null+++ b/type/src/editor.ts@@ -0,0 +1,321 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// The editing loop.+//+// The browser lays out and the browser moves the caret; this file owns the+// MODEL. Three rules keep that honest:+//+// 1. THE CARET IS A MODEL POSITION — (block id, offset into that block's+// text) — never a DOM position. Forced by measurement: with hyphenation on+// the renderer inserts characters, so any address in rendered space drifts+// (working/type-spike/RESULTS.md, C3). Footnote markers are skipped when+// counting, for the same reason.+// 2. STRUCTURAL EDITS ARE INTERCEPTED. Splitting a paragraph and merging two+// are done in the model and re-rendered, not left to contentEditable — the+// browser's version invents elements with no id, and an id it invented is+// a paragraph the redline cannot align.+// 3. UNDO IS OURS. The browser's contentEditable undo knows nothing about the+// model, so it is suppressed and every ⌘Z goes through the store.++import { renderBody, renderBlock, readBlock, isNoteAtom, TAG } from './render.ts';+import { toggleMark, activeAt, type MarkType } from './inline.ts';+import { uid, type Block, type TypeDoc } from './model.ts';+import type { Store } from './store.ts';++export interface Caret { id: string; at: number; to?: number }++export class Editor {+ readonly host: HTMLElement;+ readonly store: Store;+ /** fires after the model changed and the DOM was reconciled */+ onChange: (() => void) | null = null;+ /** fires when the caret moves, so a toolbar can show what is active */+ onSelection: ((marks: Set<MarkType>) => void) | null = null;++ constructor(host: HTMLElement, store: Store) {+ this.host = host;+ this.store = store;+ host.contentEditable = 'true';+ host.spellcheck = true;+ this.render();+ host.addEventListener('beforeinput', this.#beforeInput);+ host.addEventListener('input', this.#input);+ host.addEventListener('keydown', this.#keydown);+ document.addEventListener('selectionchange', this.#selectionChange);+ }++ render(): void {+ renderBody(this.store.doc, this.host);+ }++ // ───────────────────────────────────────────────────────── caret ↔ model++ /** Where the caret is, in the document's own coordinates. */+ caret(): Caret | null {+ const sel = getSelection();+ if (!sel || !sel.rangeCount) return null;+ const r = sel.getRangeAt(0);+ if (!this.host.contains(r.startContainer)) return null;+ const startBlock = this.#blockOf(r.startContainer);+ if (!startBlock) return null;+ const at = this.#offsetIn(startBlock, r.startContainer, r.startOffset);+ if (sel.isCollapsed) return { id: startBlock.dataset.id!, at };+ const endBlock = this.#blockOf(r.endContainer);+ if (endBlock !== startBlock) return { id: startBlock.dataset.id!, at }; // cross-block: anchor only+ return { id: startBlock.dataset.id!, at, to: this.#offsetIn(startBlock, r.endContainer, r.endOffset) };+ }++ setCaret(c: Caret | null): void {+ if (!c) return;+ const block = this.#el(c.id);+ if (!block) return;+ const a = this.#pointAt(block, c.at);+ if (!a) return;+ const r = document.createRange();+ r.setStart(a.node, a.offset);+ if (c.to !== undefined && c.to !== c.at) {+ const b = this.#pointAt(block, c.to);+ if (b) r.setEnd(b.node, b.offset); else r.collapse(true);+ } else r.collapse(true);+ const sel = getSelection()!;+ sel.removeAllRanges();+ sel.addRange(r);+ }++ #el(id: string): HTMLElement | null {+ return this.host.querySelector<HTMLElement>(`[data-id="${CSS.escape(id)}"]`);+ }+ #blockOf(node: Node): HTMLElement | null {+ let n: Node | null = node;+ while (n && n !== this.host) {+ if (n.nodeType === 1 && (n as HTMLElement).dataset?.id) return n as HTMLElement;+ n = n.parentNode;+ }+ return null;+ }+ /** Characters before (container, offset) inside this block — atoms excluded. */+ #offsetIn(block: HTMLElement, container: Node, offset: number): number {+ let count = 0, done = false;+ const walk = (n: Node): void => {+ if (done) return;+ if (n === container && n.nodeType !== 3) {+ // an element container: offset counts CHILDREN, not characters+ for (let i = 0; i < offset && i < n.childNodes.length; i++) walk(n.childNodes[i]);+ done = true; return;+ }+ if (n.nodeType === 3) {+ if (n === container) { count += Math.min(offset, n.nodeValue!.length); done = true; return; }+ count += n.nodeValue!.length; return;+ }+ if (n.nodeType === 1 && isNoteAtom(n as Element)) return; // atoms are not characters+ for (const c of Array.from(n.childNodes)) { walk(c); if (done) return; }+ };+ for (const c of Array.from(block.childNodes)) { walk(c); if (done) break; }+ return count;+ }+ /** The DOM point `at` characters into this block. */+ #pointAt(block: HTMLElement, at: number): { node: Node; offset: number } | null {+ let count = 0;+ let last: { node: Node; offset: number } | null = null;+ const walk = (n: Node): { node: Node; offset: number } | null => {+ if (n.nodeType === 3) {+ const len = n.nodeValue!.length;+ if (count + len >= at) return { node: n, offset: at - count };+ count += len;+ last = { node: n, offset: len };+ return null;+ }+ if (n.nodeType === 1 && isNoteAtom(n as Element)) return null;+ for (const c of Array.from(n.childNodes)) { const r = walk(c); if (r) return r; }+ return null;+ };+ for (const c of Array.from(block.childNodes)) { const r = walk(c); if (r) return r; }+ return last ?? { node: block, offset: 0 };+ }++ // ─────────────────────────────────────────────────────────── input++ #runId: string | null = null;++ #input = (): void => {+ const c = this.caret();+ if (!c) return;+ const el = this.#el(c.id);+ if (!el) return;+ const prev = this.store.block(c.id);+ if (!prev) return;+ const next = readBlock(el, prev);+ if (next.text === prev.text && JSON.stringify(next.marks) === JSON.stringify(prev.marks)) return;+ // one undo step per typing run, per block+ this.#runId ??= `type:${c.id}:${Date.now()}`;+ this.store.commit(d => {+ const i = d.body.findIndex(b => b.id === c.id);+ if (i >= 0) d.body[i] = next;+ }, { scope: { block: c.id }, run: this.#runId });+ this.onChange?.();+ };++ /**+ * Structural edits are done in the MODEL, not by contentEditable.+ *+ * Left to itself the browser splits a paragraph by cloning the element —+ * including its `data-id`. Two blocks with one id is precisely what the+ * redline cannot align and what the model's own parse has to repair, so the+ * split is intercepted and the new block gets a fresh id here.+ */+ #beforeInput = (e: InputEvent): void => {+ const c = this.caret();+ if (!c) return;+ if (e.inputType === 'insertParagraph') {+ e.preventDefault();+ this.#splitBlock(c);+ return;+ }+ if (e.inputType === 'deleteContentBackward' && c.to === undefined && c.at === 0) {+ const i = this.store.doc.body.findIndex(b => b.id === c.id);+ if (i > 0) { e.preventDefault(); this.#mergeBack(i); }+ return;+ }+ };++ #splitBlock(c: Caret): void {+ const i = this.store.doc.body.findIndex(b => b.id === c.id);+ if (i < 0) return;+ const src = this.store.doc.body[i];+ const head = spliceKeep(src, 0, c.at);+ const tailText = src.text.slice(c.at);+ const tail: Block = {+ id: uid(),+ // a heading's continuation is a paragraph — nobody wants two headings+ kind: src.kind === 'para' || src.kind === 'quote' ? src.kind : 'para',+ text: tailText,+ };+ const shifted = shiftPast(src, c.at);+ if (shifted.marks?.length) tail.marks = shifted.marks;+ if (shifted.notes?.length) tail.notes = shifted.notes;+ this.store.breakRun();+ this.#runId = null;+ this.store.commit(d => { d.body.splice(i, 1, head, tail); });+ this.render();+ this.setCaret({ id: tail.id, at: 0 });+ this.onChange?.();+ }++ #mergeBack(i: number): void {+ const body = this.store.doc.body;+ const prev = body[i - 1], cur = body[i];+ const at = prev.text.length;+ const merged: Block = { ...prev, text: prev.text + cur.text };+ const marks = [...(prev.marks ?? []), ...(cur.marks ?? []).map(m => ({ ...m, from: m.from + at, to: m.to + at }))];+ const notes = [...(prev.notes ?? []), ...(cur.notes ?? []).map(n => ({ ...n, at: n.at + at }))];+ if (marks.length) merged.marks = marks; else delete merged.marks;+ if (notes.length) merged.notes = notes; else delete merged.notes;+ this.store.breakRun();+ this.#runId = null;+ this.store.commit(d => { d.body.splice(i - 1, 2, merged); });+ this.render();+ this.setCaret({ id: merged.id, at });+ this.onChange?.();+ }++ // ────────────────────────────────────────────────────────── formatting++ /** ⌘B and friends, applied to the model and re-rendered. */+ toggle(t: MarkType, href?: string): void {+ const c = this.caret();+ if (!c || c.to === undefined || c.to === c.at) return; // nothing selected+ const from = Math.min(c.at, c.to), to = Math.max(c.at, c.to);+ const blk = this.store.block(c.id);+ if (!blk) return;+ this.store.breakRun();+ this.#runId = null;+ this.store.commit(d => {+ const i = d.body.findIndex(b => b.id === c.id);+ if (i < 0) return;+ const b = d.body[i];+ const marks = toggleMark(b.marks ?? [], b.text.length, from, to, t, href);+ if (marks.length) b.marks = marks; else delete b.marks;+ }, { scope: { block: c.id } });+ this.render();+ this.setCaret({ id: c.id, at: from, to });+ this.onChange?.();+ }++ /** Change a block's kind — paragraph, heading, quote. */+ setKind(kind: Block['kind']): void {+ const c = this.caret();+ if (!c) return;+ this.store.breakRun();+ this.store.commit(d => {+ const b = d.body.find(x => x.id === c.id);+ if (b) b.kind = kind;+ }, { scope: { block: c.id } });+ this.render();+ this.setCaret(c);+ this.onChange?.();+ }++ // ───────────────────────────────────────────────────────────── keys++ #keydown = (e: KeyboardEvent): void => {+ const mod = e.metaKey || e.ctrlKey;+ if (!mod) return;+ const k = e.key.toLowerCase();+ if (k === 'z') {+ e.preventDefault();+ const c = this.caret();+ if (e.shiftKey) this.store.redo(); else this.store.undo();+ this.render();+ if (c && this.#el(c.id)) this.setCaret(c);+ this.onChange?.();+ return;+ }+ if (k === 'b' || k === 'i' || k === 'u') {+ e.preventDefault();+ this.toggle(k === 'b' ? 'b' : k === 'i' ? 'i' : 'u');+ }+ };++ #selectionChange = (): void => {+ if (!this.onSelection) return;+ const c = this.caret();+ if (!c) return;+ const blk = this.store.block(c.id);+ if (!blk) return;+ this.onSelection(activeAt(blk.marks ?? [], c.to !== undefined ? Math.min(c.at, c.to) + 1 : c.at));+ };++ destroy(): void {+ this.host.removeEventListener('beforeinput', this.#beforeInput);+ this.host.removeEventListener('input', this.#input);+ this.host.removeEventListener('keydown', this.#keydown);+ document.removeEventListener('selectionchange', this.#selectionChange);+ }+}++/** The head of a split: text up to `at`, with marks and notes clipped to it. */+function spliceKeep(b: Block, from: number, to: number): Block {+ const text = b.text.slice(from, to);+ const out: Block = { ...b, text };+ const marks = (b.marks ?? [])+ .map(m => ({ ...m, from: Math.max(0, m.from - from), to: Math.min(to - from, m.to - from) }))+ .filter(m => m.to > m.from);+ const notes = (b.notes ?? []).filter(n => n.at >= from && n.at <= to).map(n => ({ ...n, at: n.at - from }));+ if (marks.length) out.marks = marks; else delete out.marks;+ if (notes.length) out.notes = notes; else delete out.notes;+ return out;+}++/** The tail of a split: everything from `at`, rebased to 0. */+function shiftPast(b: Block, at: number): { marks?: Block['marks']; notes?: Block['notes'] } {+ const len = b.text.length - at;+ const marks = (b.marks ?? [])+ .map(m => ({ ...m, from: Math.max(0, m.from - at), to: Math.min(len, m.to - at) }))+ .filter(m => m.to > m.from);+ const notes = (b.notes ?? []).filter(n => n.at > at).map(n => ({ ...n, at: n.at - at }));+ return { marks: marks.length ? marks : undefined, notes: notes.length ? notes : undefined };+}++export { TAG, renderBlock };+export type { TypeDoc };diff --git a/type/src/inline.ts b/type/src/inline.tsnew file mode 100644index 00000000..0c994b4aBinary files /dev/null and b/type/src/inline.ts differdiff --git a/type/src/main.ts b/type/src/main.tsnew file mode 100644index 00000000..eb096e12--- /dev/null+++ b/type/src/main.ts@@ -0,0 +1,530 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Boot. Read the embedded document, build the store and the editor, wire the+// chrome. Kernel integration (save splice, autosave, encryption, signed+// updates, i18n) comes next — PLATFORM §10.++import './styles.css';+import { configureApp } from '../../kernel/src/app.ts';+import {+ capturePristine, readEmbeddedDoc, saveFile, currentFileName, canWriteInPlace,+} from '../../kernel/src/save.ts';+import { startTheme, setTheme, themeChoice, type ThemeChoice } from '../../kernel/src/theme.ts';+import { parseDoc, emptyDoc, uid, wordCount, type TypeDoc } from './model.ts';+import { Store } from './store.ts';+import { Editor } from './editor.ts';+import { paginate, drawPages, type Metrics } from './paginate.ts';+import { redline, apply as applyRedline, describe, type ChangeSet } from './redline.ts';+import { printDocument, buildPrintDocument } from './print.ts';+import { sign as signDoc, verifyChain, newKey } from './canon.ts';+import { uid as newId } from './model.ts';+import type { MarkType } from './inline.ts';++// Tell the kernel who this app is — must precede any kernel module use+// (window title suffix, save-picker label, update manifest).+configureApp({+ appId: 'bento-type',+ appName: 'bento/type',+ manifestUrl: 'https://bento.page/releases/type/manifest.json',+});++// The pristine capture must happen BEFORE any DOM mutation: saves re-serialize+// the captured clone, so anything the app injects afterwards (theme attributes,+// the editor's rendered blocks, measuring probes) never reaches a saved file.+capturePristine();++// Theme after the capture, for exactly that reason — `data-theme` is a viewer+// preference and must not travel in the document.+startTheme();++// ───────────────────────────────────────────────────────────── the document++const SAMPLE: Array<[string, string]> = [+ ['h1', 'Master Services Agreement'],+ ['h2', '1. Scope of Work'],+ ['para', 'The Supplier shall provide the services described in Schedule A, exercising the degree of skill and care reasonably expected of a professional supplier of comparable services. Where Schedule A conflicts with this agreement, this agreement governs.'],+ ['para', 'The Supplier may not subcontract any part of the services without the prior written consent of the Customer, such consent not to be unreasonably withheld or delayed.'],+ ['h2', '2. Fees and Payment'],+ ['para', 'Payment is due within 30 days of invoice, without set-off. Invoices shall be issued monthly in arrears and shall itemise the services performed during the period to which they relate.'],+ ['quote', 'Time for payment is of the essence.'],+ ['h2', '3. Limitation of Liability'],+ ['para', 'Subject to the foregoing, the total aggregate liability of each party under this agreement shall not exceed the total fees paid in the twelve months preceding the event giving rise to the claim.'],+];++function sampleDoc(): TypeDoc {+ const d = emptyDoc();+ d.title = 'Master Services Agreement';+ d.meta = { author: 'A. Nyblom', company: 'Example Ltd' };+ d.body = SAMPLE.map(([kind, text]) => ({ id: uid(), kind: kind as never, text }));+ // one bold run and one footnote, so both mechanisms are visible on open+ const pay = d.body.find(b => b.text.includes('30 days'))!;+ const at = pay.text.indexOf('30 days');+ pay.marks = [{ t: 'b', from: at, to: at + '30 days'.length }];+ const nid = uid('n');+ d.footnotes[nid] = 'Time runs from receipt of a valid invoice at the address in Schedule B.';+ pay.notes = [{ id: nid, at: pay.text.indexOf('without set-off.') + 'without set-off.'.length }];+ return d;+}++const embedded = readEmbeddedDoc() ?? '';+const parsed = parseDoc(embedded);+let doc: TypeDoc;+let loadNote = '';+if (parsed.ok) {+ doc = parsed.doc;+ if (parsed.repaired.length) loadNote = `repaired: ${parsed.repaired.join('; ')}`;+} else if (parsed.err === 'empty') {+ doc = sampleDoc();+} else {+ // NEVER silently start a new document over a file we could not read — the+ // spaces load contract (model.ts). Say what happened and stop.+ document.body.innerHTML =+ `<div style="max-width:44rem;margin:12vh auto;padding:0 2rem;font:15px/1.6 system-ui;color:#e6e9ef">+ <h1 style="font-size:20px">This file could not be opened</h1>+ <p>${parsed.detail}</p>+ <p style="color:#8d95a3">Nothing has been changed. Close this tab rather than saving over it.</p>+ </div>`;+ throw new Error(`bento/type: ${parsed.detail}`);+}++// ───────────────────────────────────────────────────────────────── chrome++const app = document.getElementById('app')!;+app.innerHTML = `+ <div class="t-bar">+ <div class="t-brand">bento/<b>type</b></div>+ <div class="t-sep"></div>+ <button id="save" class="primary" title="Save (⌘S)">Save</button>+ <div class="t-sep"></div>+ <select id="kind" title="Block style">+ <option value="para">Body</option>+ <option value="h1">Title</option>+ <option value="h2">Heading</option>+ <option value="h3">Subheading</option>+ <option value="quote">Quote</option>+ </select>+ <div class="t-sep"></div>+ <button id="mb" title="Bold (⌘B)"><b>B</b></button>+ <button id="mi" title="Italic (⌘I)"><i>I</i></button>+ <button id="mu" title="Underline (⌘U)"><u>U</u></button>+ <button id="mc" title="Code"></></button>+ <div class="t-sep"></div>+ <button id="undo" title="Undo (⌘Z)">↶</button>+ <button id="redo" title="Redo (⇧⌘Z)">↷</button>+ <div class="t-sep"></div>+ <button id="theme" title="Theme: follow the system, light, or dark"></button>+ <div class="t-sep"></div>+ <button id="snap" title="Record a revision to compare against later">Snapshot</button>+ <button id="review" title="Compare with the last snapshot">Review…</button>+ <div class="t-sep"></div>+ <button id="sign" title="Sign this revision">Sign</button>+ <div class="t-sep"></div>+ <button id="print" title="Print or save as PDF (⌘P)">Print…</button>+ <div class="t-spacer"></div>+ <div class="t-stat" id="stat"></div>+ </div>+ <div class="t-main">+ <div class="t-side">+ <div class="t-tabs">+ <button data-tab="outline" class="on">Outline</button>+ <button data-tab="review">Review</button>+ <button data-tab="sigs">Signatures</button>+ </div>+ <div class="t-panel on" data-panel="outline"><div class="t-outline" id="outline"></div></div>+ <div class="t-panel" data-panel="review"><div id="reviewPanel"></div></div>+ <div class="t-panel" data-panel="sigs"><div id="sigsPanel"></div></div>+ </div>+ <div class="t-scroll"><div class="t-wrap">+ <div class="t-paper" id="paper"></div><div class="t-deco" id="deco"></div>+ </div></div>+ </div>`;++const paper = document.getElementById('paper')!;+const deco = document.getElementById('deco')!;+const statEl = document.getElementById('stat')!;++const store = new Store(doc);+const editor = new Editor(paper, store);++let metrics: Metrics = { pages: [], ms: 0 };++/**+ * Re-measure and redraw. Deliberately NOT on every keystroke: pagination reads+ * layout, so calling it per character would force a synchronous reflow on each+ * one. It runs on an idle beat instead, which is what makes typing feel free.+ */+let idle: number | undefined;+const repaginate = () => {+ metrics = paginate(store.doc, paper);+ drawPages(store.doc, paper, deco, metrics);+ buildOutline();+ paint();+ void paintSigs();+};+const schedule = () => {+ clearTimeout(idle);+ idle = setTimeout(repaginate, 180) as unknown as number;+};++const paint = () => {+ const d = store.doc;+ const notes = Object.keys(d.footnotes).length;+ statEl.textContent =+ `${metrics.pages.length || 1} ${metrics.pages.length === 1 ? 'page' : 'pages'}` ++ ` · ${wordCount(d).toLocaleString()} words` ++ (notes ? ` · ${notes} note${notes > 1 ? 's' : ''}` : '') ++ ` · ${metrics.ms.toFixed(0)}ms` ++ (loadNote ? ` · ${loadNote}` : '');+};++const refresh = () => { markDirty(); paint(); schedule(); };+editor.onChange = refresh;+store.on(refresh);++const MARK_BTN: Array<[string, MarkType]> = [['mb', 'b'], ['mi', 'i'], ['mu', 'u'], ['mc', 'code']];+for (const [id, t] of MARK_BTN) {+ document.getElementById(id)!.addEventListener('mousedown', (e) => {+ e.preventDefault(); // keep the selection alive+ editor.toggle(t);+ });+}+editor.onSelection = (active) => {+ for (const [id, t] of MARK_BTN) document.getElementById(id)!.classList.toggle('on', active.has(t));+};+document.getElementById('kind')!.addEventListener('change', (e) => {+ editor.setKind((e.target as HTMLSelectElement).value as never);+});+document.getElementById('undo')!.addEventListener('mousedown', (e) => {+ e.preventDefault(); store.undo(); editor.render(); refresh();+});+document.getElementById('redo')!.addEventListener('mousedown', (e) => {+ e.preventDefault(); store.redo(); editor.render(); refresh();+});++// ────────────────────────────────────────────────────────── sidebar++const esc = (t: string) => t.replace(/[&<>]/g, c => ({ '&': '&', '<': '<', '>': '>' }[c]!));+const el = (tag: string, cls?: string) => {+ const n = document.createElement(tag); if (cls) n.className = cls; return n;+};+function showTab(name: string) {+ document.querySelectorAll<HTMLElement>('.t-tabs button')+ .forEach(b => b.classList.toggle('on', b.dataset.tab === name));+ document.querySelectorAll<HTMLElement>('.t-panel')+ .forEach(p => p.classList.toggle('on', p.dataset.panel === name));+}+document.querySelectorAll<HTMLElement>('.t-tabs button')+ .forEach(b => b.addEventListener('click', () => showTab(b.dataset.tab!)));++/** The outline, with the page each heading lands on. */+function buildOutline() {+ const box = document.getElementById('outline')!;+ const heads = store.doc.body.filter(b => b.kind === 'h2' || b.kind === 'h3');+ box.replaceChildren();+ if (!heads.length) {+ const h = el('div', 't-hint'); h.textContent = 'Headings appear here.';+ box.appendChild(h); return;+ }+ const paperTop = paper.getBoundingClientRect().top + store.doc.page.marginTop;+ for (const b of heads) {+ const node = paper.querySelector<HTMLElement>(`[data-id="${CSS.escape(b.id)}"]`);+ const y = node ? node.getBoundingClientRect().top - paperTop : 0;+ const pg = metrics.pages.find(p => y >= p.start - 1 && (!isFinite(p.end) || y < p.end));+ const a = el('a', b.kind) as HTMLAnchorElement;+ a.innerHTML = `<span class="pg">${pg ? pg.n : ''}</span>${esc(b.text)}`;+ a.addEventListener('click', () =>+ paper.querySelector(`[data-id="${CSS.escape(b.id)}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'center' }));+ box.appendChild(a);+ }+}++// ───────────────────────────────────────────── revisions and redlining++let currentSet: ChangeSet | null = null;+const decided = new Map<string, boolean>();++document.getElementById('snap')!.addEventListener('click', () => {+ const label = `Revision ${store.doc.revisions.length + 1}`;+ store.commit(d => {+ d.revisions.push({ id: newId('rev'), at: new Date().toISOString(), label,+ body: JSON.parse(JSON.stringify(d.body)) });+ });+ markDirty(); paint();+ toast(`${label} recorded — edit, then Review`);+});++document.getElementById('review')!.addEventListener('click', () => {+ if (!store.doc.revisions.length) { toast('Take a Snapshot first, then edit, then Review'); return; }+ const base = store.doc.revisions[store.doc.revisions.length - 1];+ currentSet = redline({ docId: store.doc.docId, body: base.body },+ { docId: store.doc.docId, body: store.doc.body },+ { author: store.doc.meta?.author || 'you' });+ decided.clear();+ showTab('review');+ buildReview(base.label, base.body);+});++function buildReview(label: string, baseBody: typeof store.doc.body) {+ const box = document.getElementById('reviewPanel')!;+ box.replaceChildren();+ const head = el('div', 't-hint');+ head.textContent = currentSet!.changes.length+ ? `${currentSet!.changes.length} change${currentSet!.changes.length > 1 ? 's' : ''} since ${label}`+ : `No changes since ${label}. Edit the document, then press Review again.`;+ head.style.marginBottom = '9px';+ box.appendChild(head);+ if (!currentSet!.changes.length) return;++ const bar = el('div'); bar.style.cssText = 'display:flex;gap:6px;margin-bottom:9px';+ for (const [text, val] of [['Accept all', true], ['Reject all', false]] as const) {+ const b = el('button') as HTMLButtonElement;+ b.textContent = text; b.style.flex = '1';+ b.addEventListener('click', () => {+ for (const c of currentSet!.changes) decided.set(c.id, val);+ applyDecisions(label, baseBody);+ });+ bar.appendChild(b);+ }+ box.appendChild(bar);++ for (const c of currentSet!.changes) {+ const card = el('div', 't-card');+ const what = c.kind === 'text'+ ? `${c.removed ? `<del>${esc(c.removed)}</del>` : ''}${c.added ? `<ins>${esc(c.added)}</ins>` : ''}`+ : esc(describe(c));+ card.innerHTML = `<div class="who">${esc(c.author)} · ${c.kind}</div><div class="what">${what}</div>`;+ const btns = el('div', 'btns');+ for (const [text, val] of [['Accept', true], ['Reject', false]] as const) {+ const b = el('button') as HTMLButtonElement;+ b.textContent = text;+ b.addEventListener('click', () => {+ decided.set(c.id, val);+ card.classList.add('done');+ card.querySelectorAll('button').forEach(x => (x as HTMLButtonElement).disabled = true);+ applyDecisions(label, baseBody);+ });+ btns.appendChild(b);+ }+ card.appendChild(btns);+ box.appendChild(card);+ }+}++/**+ * Rebuild from the BASE plus the accepted changes.+ *+ * Rebuilding from the base rather than patching the live document is what makes+ * "reject" mean anything — the rejected text has to come back. Undecided+ * changes stay as the author left them, so nothing vanishes while you think.+ */+function applyDecisions(_label: string, baseBody: typeof store.doc.body) {+ const accepted = new Set([...decided].filter(([, v]) => v).map(([k]) => k));+ const undecided = currentSet!.changes.filter(c => !decided.has(c.id)).map(c => c.id);+ const take = new Set([...accepted, ...undecided]);+ try {+ const next = applyRedline({ docId: store.doc.docId, body: baseBody }, currentSet!, take);+ store.commit(d => { d.body = next.body; });+ editor.render(); markDirty(); repaginate();+ toast(decided.size === currentSet!.changes.length+ ? 'All changes resolved' : `${decided.size}/${currentSet!.changes.length} resolved`);+ } catch (e) { toast(`Could not apply: ${(e as Error).message}`); }+}++// ─────────────────────────────────────────────────────────── signatures++const KEYSTORE = 'bento-type-key';+let deviceKey: CryptoKeyPair | null = null;+async function getKey(): Promise<CryptoKeyPair> {+ if (deviceKey) return deviceKey;+ let saved: string | null = null;+ try { saved = localStorage.getItem(KEYSTORE); } catch { /* storage blocked */ }+ const EC = { name: 'ECDSA', namedCurve: 'P-256' } as const;+ if (saved) {+ const j = JSON.parse(saved);+ deviceKey = {+ privateKey: await crypto.subtle.importKey('jwk', j.priv, EC, true, ['sign']),+ publicKey: await crypto.subtle.importKey('jwk', j.pub, EC, true, ['verify']),+ };+ return deviceKey;+ }+ const k = await newKey();+ try {+ localStorage.setItem(KEYSTORE, JSON.stringify({+ priv: await crypto.subtle.exportKey('jwk', k.privateKey),+ pub: await crypto.subtle.exportKey('jwk', k.publicKey),+ }));+ } catch { /* an unsaved key still signs this session */ }+ deviceKey = k;+ return k;+}+const fingerprint = (pub: string) =>+ pub.replace(/[^a-zA-Z0-9]/g, '').slice(0, 24).match(/.{1,4}/g)!.join(' ').toUpperCase();++document.getElementById('sign')!.addEventListener('click', async () => {+ let who = '';+ try { who = localStorage.getItem('bento-type-name') ?? ''; } catch { /* ignore */ }+ const name = window.prompt('Your name, shown beside the signature', who);+ if (!name) return;+ try { localStorage.setItem('bento-type-name', name); } catch { /* ignore */ }+ const key = await getKey();+ const prev = store.doc.signatures[store.doc.signatures.length - 1] ?? null;+ const entry = await signDoc(store.doc, key, { name, prev });+ entry.at = new Date().toISOString();+ store.commit(d => { d.signatures.push(entry); });+ markDirty(); showTab('sigs'); await paintSigs();+ toast('Signed');+});++async function paintSigs() {+ const box = document.getElementById('sigsPanel')!;+ const sigs = store.doc.signatures;+ box.replaceChildren();+ if (!sigs.length) {+ const h = el('div', 't-hint');+ h.innerHTML = `Nothing signed yet.<br><br>A signature covers the document's <b>content</b> —+ not its timestamp, not which theme you are using — so re-saving never breaks one, but+ changing a word, or even a bold run, always does.<br><br>Each signature also commits to the+ one before it, which proves the <b>order</b> people signed in without trusting anyone's clock.`;+ box.appendChild(h);+ return;+ }+ const res = await verifyChain(store.doc, sigs);+ sigs.forEach((s, i) => {+ const r = res.entries[i];+ const card = el('div', 't-card');+ const state = r.ok && r.linked ? `<span class="t-ok">✓ valid</span>`+ : (!r.ok && r.why === 'content-changed'+ ? `<span class="t-bad">✕ the document has changed since this was signed</span>`+ : !r.linked ? `<span class="t-warn">⚠ not linked to the previous signature</span>`+ : `<span class="t-bad">✕ invalid signature</span>`);+ card.innerHTML =+ `<div class="what" style="font-weight:600">${esc(s.name || 'unnamed')}</div>` ++ `<div class="t-fp">${fingerprint(s.pub)}</div>` ++ `<div class="who" style="margin:5px 0 0">${state}` ++ `${i > 0 ? ` · after ${esc(sigs[i - 1].name || 'previous')}` : ''}</div>`;+ box.appendChild(card);+ });+ // two names on one key is exactly what a signature cannot prove+ const byKey = new Map<string, Set<string>>();+ for (const s of sigs) {+ if (!byKey.has(s.pub)) byKey.set(s.pub, new Set());+ byKey.get(s.pub)!.add(s.name || 'unnamed');+ }+ const shared = [...byKey.values()].find(n => n.size > 1);+ if (shared) {+ const w = el('div', 't-hint');+ w.style.cssText = 'margin-top:10px;border-inline-start:2px solid var(--warnc);padding-inline-start:9px';+ w.innerHTML = `<span class="t-warn">Two names, one key.</span> ${[...shared].map(esc).join(' and ')}+ signed with the <b>same</b> key — on this device that is simply you signing twice. Between real+ parties it would mean one of the names is a claim the signature does not support.`;+ box.appendChild(w);+ }+ const foot = el('div', 't-hint');+ foot.style.marginTop = '10px';+ foot.innerHTML = res.ok+ ? `The chain is intact. Verify a signer by reading their fingerprint aloud — nothing here proves+ <i>who</i> holds a key, only that the same key signed these exact words, in this order.`+ : `<span class="t-bad">This chain no longer verifies.</span> Either the text changed after+ signing, or a signature was altered or removed.`;+ box.appendChild(foot);+}++// ─────────────────────────────────────────────────────────── a small toast+let toastEl: HTMLElement | null = null, toastT: number | undefined;+function toast(msg: string) {+ if (!toastEl) {+ toastEl = el('div');+ toastEl.style.cssText = 'position:fixed;left:50%;bottom:26px;transform:translateX(-50%);' ++ 'background:var(--ink);color:var(--chrome);padding:9px 15px;border-radius:8px;font-size:12.5px;' ++ 'box-shadow:0 10px 34px rgb(0 0 0 / .35);opacity:0;transition:opacity .18s;pointer-events:none;z-index:99';+ document.body.appendChild(toastEl);+ }+ toastEl.textContent = msg;+ toastEl.style.opacity = '1';+ clearTimeout(toastT);+ toastT = setTimeout(() => { toastEl!.style.opacity = '0'; }, 2200) as unknown as number;+}++// ─────────────────────────────────────────────────────────────── saving+//+// The whole platform promise in one button: this file rewrites ITSELF. The+// kernel owns the splice, the File System Access path and the download+// fallback, so the app only has to say when and with what.+let dirty = false;+const markDirty = () => { dirty = true; paintTitle(); };++function paintTitle() {+ const name = currentFileName();+ const t = store.doc.title || 'Untitled';+ document.title = `${dirty ? '• ' : ''}${t} — bento/type`;+ const btn = document.getElementById('save')!;+ btn.textContent = dirty ? 'Save' : 'Saved';+ btn.classList.toggle('primary', dirty);+ btn.title = name+ ? `${dirty ? 'Save' : 'Saved to'} ${name}${canWriteInPlace() ? '' : ' (downloads a copy)'}`+ : 'Save (⌘S)';+}++async function save(forcePicker = false) {+ const result = await saveFile(store.doc, forcePicker);+ if (result === 'cancelled') return;+ dirty = false;+ paintTitle();+}++document.getElementById('save')!.addEventListener('click', () => void save());+addEventListener('keydown', (e) => {+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {+ e.preventDefault();+ void save(e.shiftKey); // ⇧⌘S = save as+ }+});+// Leaving with unsaved work should cost a prompt. A document that edits itself+// has no server-side copy to fall back on.+addEventListener('beforeunload', (e) => { if (dirty) { e.preventDefault(); e.returnValue = ''; } });++// ─────────────────────────────────────────────────────────────── printing+//+// Print uses the SAME page breaks the editor computed, so the printed+// pagination is the one the outline and the page numbers already showed. It+// repaginates first rather than trusting a stale measurement — the alternative+// is a document that prints differently from the one on screen, which is the+// exact failure the deterministic-pagination promise exists to prevent.+function doPrint() {+ repaginate();+ printDocument(store.doc, metrics, { pageNumbers: true, bareFirstPage: false });+}+document.getElementById('print')!.addEventListener('click', doPrint);+addEventListener('keydown', (e) => {+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'p') { e.preventDefault(); doPrint(); }+});++// theme picker — cycles auto → light → dark, and says which it is+const themeBtn = document.getElementById('theme')!;+const THEME_LABEL: Record<ThemeChoice, string> = { auto: '◐ Auto', light: '☀ Light', dark: '☾ Dark' };+const paintTheme = () => { themeBtn.textContent = THEME_LABEL[themeChoice()]; };+themeBtn.addEventListener('click', () => {+ const order: ThemeChoice[] = ['auto', 'light', 'dark'];+ const next = order[(order.indexOf(themeChoice()) + 1) % order.length];+ setTheme(next);+ paintTheme();+ // the page shadow and grid change with the theme, so re-measure+ repaginate();+});+paintTheme();++repaginate();+dirty = false; paintTitle();++// scripting surface, per PLATFORM §7+(window as unknown as Record<string, unknown>).bento = {+ format: store.doc.format,+ get doc() { return store.doc; },+ store, editor,+ save: (picker = false) => save(picker),+ print: () => doPrint(),+ printHtml: () => { repaginate(); return buildPrintDocument(store.doc, metrics, { pageNumbers: true }); },+ paginate: () => { repaginate(); return metrics; },+ get pages() { return metrics.pages; },+};diff --git a/type/src/model.ts b/type/src/model.tsnew file mode 100644index 00000000..c36b5b4e--- /dev/null+++ b/type/src/model.ts@@ -0,0 +1,244 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// The bento/type document model. This JSON is what lives inside the #bento-doc+// block — the format IS the product (docs/PLATFORM.md §3).+//+// The shape of a document here is deliberately narrow: a flat, ordered list of+// blocks, each holding PLAIN TEXT plus marks over character ranges (see+// inline.ts for why that spine and not HTML). No nesting, no inline nodes, no+// tree. A word processor's document is a stream of prose that gets poured into+// pages; the structure lives in the block kinds and in the pagination, not in+// the container.++import { normalize, shift as shiftMarks, type Mark } from './inline.ts';++export const FORMAT = 'bento/type';+export const VERSION = 1;++/** The kinds of block a document is made of. */+export type BlockKind = 'para' | 'h1' | 'h2' | 'h3' | 'quote';++/** A footnote reference anchored INTO a block's text, by character offset. */+export interface NoteRef { id: string; at: number }++export interface Block {+ /** stable identity: the redline aligns on it, so it must never be re-minted+ * for a block the author considers the same paragraph */+ id: string;+ kind: BlockKind;+ /** the block's text, with no markup of any kind in it */+ text: string;+ /** formatting over character ranges; absent means none */+ marks?: Mark[];+ /** footnote references, by offset into `text` */+ notes?: NoteRef[];+ /** authoring role, for restyling and for a table of contents */+ role?: string;+}++/** Page geometry, in CSS px at 96dpi. US Letter by default. */+export interface PageSpec {+ width: number; height: number;+ marginX: number; marginTop: number; marginBottom: number;+}+export const LETTER: PageSpec = {+ width: 816, height: 1056, marginX: 104, marginTop: 104, marginBottom: 104,+};++export interface Signature {+ alg: 'ES256';+ /** raw P-256 public key, base64url — the identity. The name is only a claim. */+ pub: string;+ /** self-asserted, shown beside the signature and NOT proof of anything */+ name: string;+ /** digest of the canonical content at the moment of signing */+ content: string;+ /** the signature this one commits to, chaining the order */+ prev: string;+ sig: string;+ /** self-asserted wall clock. Display only — order comes from `prev`. */+ at?: string;+}++/** A recorded revision, kept so a redline can be produced with no server. */+export interface Revision {+ id: string; at: string; label: string;+ body: Block[];+}++export interface TypeDoc {+ format: typeof FORMAT;+ version: number;+ /** minted once at creation, NEVER regenerated (PLATFORM §3) */+ docId: string;+ title: string;+ subtitle?: string;+ meta?: { author?: string; company?: string; subject?: string; keywords?: string };+ page: PageSpec;+ body: Block[];+ /** note id → note text. Kept out of the blocks so a note can outlive a+ * re-flow of the paragraph that references it. */+ footnotes: Record<string, string>;+ revisions: Revision[];+ signatures: Signature[];+ fonts?: Array<{ family: string; asset: string; weight?: string; style?: string }>;+ assets?: Record<string, string>;+ readonly?: boolean;+ template?: boolean;+ /** volatile, never signed */+ modified?: string;+ /** unknown fields are PRESERVED — format additivity (PLATFORM §3) */+ [extra: string]: unknown;+}++export const uid = (p = 'b'): string => {+ const r = globalThis.crypto?.randomUUID?.();+ return r ? `${p}-${r.slice(0, 8)}` : `${p}-${Math.random().toString(36).slice(2, 10)}`;+};+export const newDocId = (): string => globalThis.crypto?.randomUUID?.() ?? uid('doc');++export function emptyDoc(): TypeDoc {+ return {+ format: FORMAT, version: VERSION, docId: newDocId(),+ title: 'Untitled', page: { ...LETTER },+ body: [{ id: uid(), kind: 'para', text: '' }],+ footnotes: {}, revisions: [], signatures: [],+ };+}++/**+ * Parse result — TAGGED, never null.+ *+ * Following bento/spaces, which learned this the hard way: a `parseDoc` that+ * returns null lets the caller fall back to the starter document, so opening a+ * file from another app, or one with a single hand-edited typo, silently+ * presents an EMPTY document over live data — and the first ⌘S writes it to+ * disk. The only path to a starter is an absent or empty block.+ */+export type ParseResult =+ | { ok: true; doc: TypeDoc; repaired: string[] }+ | { ok: false; err: 'empty' }+ | { ok: false; err: 'json' | 'format' | 'shape'; detail: string; found?: string };++const isObj = (v: unknown): v is Record<string, unknown> =>+ !!v && typeof v === 'object' && !Array.isArray(v);++/**+ * Read a document, repairing what can be repaired from the BYTES ALONE.+ *+ * Repairs are deterministic so that two readers of one file agree on every id —+ * the redline aligns blocks by id, and two parties whose copies disagree would+ * see phantom changes.+ */+export function parseDoc(raw: string): ParseResult {+ const trimmed = raw.trim();+ if (!trimmed) return { ok: false, err: 'empty' };++ let json: unknown;+ try { json = JSON.parse(trimmed); }+ catch (e) { return { ok: false, err: 'json', detail: (e as Error).message }; }+ if (!isObj(json)) return { ok: false, err: 'shape', detail: 'the document is not an object' };++ const found = typeof json.format === 'string' ? json.format : undefined;+ if (found !== FORMAT) {+ return { ok: false, err: 'format',+ detail: `this file is ${found ? `a ${found} document` : 'not a Bento document'}`, found };+ }+ if (!Array.isArray(json.body)) return { ok: false, err: 'shape', detail: 'body is missing' };++ const repaired: string[] = [];+ const seen = new Set<string>();+ const body: Block[] = [];+ (json.body as unknown[]).forEach((b, i) => {+ if (!isObj(b)) { repaired.push(`dropped a block at ${i} that was not an object`); return; }+ const kind: BlockKind = ['para', 'h1', 'h2', 'h3', 'quote'].includes(b.kind as string)+ ? b.kind as BlockKind : 'para';+ if (kind !== b.kind) repaired.push(`block ${i}: unknown kind ${JSON.stringify(b.kind)} read as a paragraph`);+ const text = typeof b.text === 'string' ? b.text : '';+ // ids must be unique: the redline aligns on them, so a duplicate makes one+ // paragraph invisible to review. Derive the replacement from position, so+ // every reader of these bytes repairs it identically.+ let id = typeof b.id === 'string' && b.id ? b.id : `b${i}`;+ if (seen.has(id)) { id = `${id}~${i}`; repaired.push(`block ${i}: duplicate id repaired to ${id}`); }+ seen.add(id);++ const marks = Array.isArray(b.marks)+ ? normalize((b.marks as Mark[]).filter(m => isObj(m) && typeof m.from === 'number'+ && typeof m.to === 'number' && typeof m.t === 'string'), text.length)+ : undefined;+ const notes = Array.isArray(b.notes)+ ? (b.notes as NoteRef[]).filter(n => isObj(n) && typeof n.id === 'string' && typeof n.at === 'number')+ .map(n => ({ id: n.id, at: Math.max(0, Math.min(n.at, text.length)) }))+ .sort((x, y) => x.at - y.at)+ : undefined;++ const out: Block = { id, kind, text };+ if (marks?.length) out.marks = marks;+ if (notes?.length) out.notes = notes;+ if (typeof b.role === 'string') out.role = b.role;+ body.push(out);+ });+ if (!body.length) body.push({ id: uid(), kind: 'para', text: '' });++ const footnotes: Record<string, string> = {};+ if (isObj(json.footnotes)) {+ for (const [k, v] of Object.entries(json.footnotes)) if (typeof v === 'string') footnotes[k] = v;+ }+ // a reference to a note that is not there would render as a marker with+ // nothing behind it — drop the reference, keep the text+ let dangling = 0;+ for (const b of body) {+ if (!b.notes) continue;+ const keep = b.notes.filter(n => footnotes[n.id] !== undefined);+ if (keep.length !== b.notes.length) dangling += b.notes.length - keep.length;+ if (keep.length) b.notes = keep; else delete b.notes;+ }+ if (dangling) repaired.push(`dropped ${dangling} footnote reference(s) with no note behind them`);++ const doc: TypeDoc = {+ ...(json as object) as TypeDoc, // unknown fields ride along+ format: FORMAT,+ version: typeof json.version === 'number' ? json.version : VERSION,+ docId: typeof json.docId === 'string' && json.docId ? json.docId : newDocId(),+ title: typeof json.title === 'string' ? json.title : 'Untitled',+ page: isObj(json.page) ? { ...LETTER, ...(json.page as object) } as PageSpec : { ...LETTER },+ body, footnotes,+ revisions: Array.isArray(json.revisions) ? json.revisions as Revision[] : [],+ signatures: Array.isArray(json.signatures) ? json.signatures as Signature[] : [],+ };+ if (typeof json.docId !== 'string' || !json.docId) repaired.push('minted a missing docId');+ return { ok: true, doc, repaired };+}++/** The document's text, in order — what gets measured, searched and diffed. */+export const plainText = (doc: TypeDoc): string => doc.body.map(b => b.text).join('\n');++export const wordCount = (doc: TypeDoc): number =>+ doc.body.reduce((n, b) => n + (b.text.trim() ? b.text.trim().split(/\s+/).length : 0), 0);++/**+ * Replace [at, at+removed) of a block's text with `added`, keeping marks and+ * footnote anchors pointing at the same words.+ *+ * One function, because these two must move together: they are offsets into the+ * same string, and a version of this that updated only one of them is exactly+ * the bug that put a footnote marker in the middle of a word during the spike.+ */+export function spliceText(block: Block, at: number, removed: number, added: string): Block {+ const text = block.text.slice(0, at) + added + block.text.slice(at + removed);+ const out: Block = { ...block, text };+ if (block.marks?.length) {+ const m = shiftMarks(block.marks, at, removed, added.length, text.length);+ if (m.length) out.marks = m; else delete out.marks;+ }+ if (block.notes?.length) {+ const end = at + removed;+ const delta = added.length - removed;+ const n = block.notes+ .filter(x => !(x.at > at && x.at < end)) // its anchor text is gone+ .map(x => x.at >= end ? { ...x, at: x.at + delta } : x);+ if (n.length) out.notes = n; else delete out.notes;+ }+ return out;+}diff --git a/type/src/paginate.ts b/type/src/paginate.tsnew file mode 100644index 00000000..a0fcae77--- /dev/null+++ b/type/src/paginate.ts@@ -0,0 +1,242 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Where the pages break, and what goes at the foot of each.+//+// The document flows continuously; pages are COMPUTED over it and drawn as+// decorations. That is not a shortcut — it was the outcome of the spike+// (working/type-spike/RESULTS.md). Fragmenting the DOM into real page boxes+// works, and reproduces the same pagination, but it is not transparent to+// editing: arrow keys stall at the seam (six presses advance four characters)+// and backspace deletes two characters instead of one, because the browser sees+// two paragraphs where the author wrote one. Continuous flow has none of that+// and costs 4ms for 134 pages.+//+// Four rules the spike forced, each after getting it wrong first:+//+// 1. RANGE GEOMETRY, NEVER HIT-TESTING. `caretPositionFromPoint` takes viewport+// coordinates and only answers for on-screen content, so it cannot find a+// break on page 60 without scrolling there. `getClientRects()` reports+// correctly for content far out of view.+// 2. MEASURE SCOPED, NOT GLOBALLY. The naive version re-scanned every line box+// with a per-character walk on each of ~120 iterations — O(pages · chars) —+// and hung the tab. Binary-search the blocks for the target y, then measure+// only inside that block.+// 3. DECORATIONS GO OUTSIDE THE EDITABLE. Markers inserted into the flow put+// page 2's rule at y=390 on an 864px page body, and would enter the undo+// stack. An overlay fixes placement and cannot be typed into.+// 4. FOOTNOTES NEED A TERMINATION RULE. Reserving room for notes shortens the+// page, which can push a reference off it, which frees the room — a real+// 2-cycle, measured on 5 of 40 pages at high note density. When a state+// repeats, DEFER the last note to the next page: same page count as the+// alternatives, less wasted note area, and what a typesetter does.++import type { PageSpec, TypeDoc } from './model.ts';++export interface Page {+ n: number;+ /** paper-space y this page starts at (0 = the first line's top) */+ start: number;+ /** paper-space y it ends at; Infinity for the last page */+ end: number;+ /** footnote ids landing on this page, in order */+ notes: string[];+ /** px reserved at the foot for those notes */+ reserved: number;+}++export interface Metrics {+ pages: Page[];+ /** ms the last pass took, for the status line and for catching regressions */+ ms: number;+}++/** A line box, in paper space. */+interface LineBox { top: number; bottom: number }++const bodyHeight = (p: PageSpec) => p.height - p.marginTop - p.marginBottom;++/**+ * Every line box in the flow, in order.+ *+ * One Range per text node and one rect per line — no per-character walk. The+ * origin is the CONTENT box, so y=0 is the first line's top rather than the top+ * of the page margin; getting that wrong silently under-fills page one.+ */+function lineBoxes(host: HTMLElement, page: PageSpec): LineBox[] {+ const out: LineBox[] = [];+ const top0 = host.getBoundingClientRect().top + page.marginTop;+ const walker = document.createTreeWalker(host, NodeFilter.SHOW_TEXT, {+ acceptNode: n => n.nodeValue?.trim().length ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT,+ });+ const r = document.createRange();+ let n: Node | null;+ while ((n = walker.nextNode())) {+ r.selectNodeContents(n);+ for (const rect of Array.from(r.getClientRects())) {+ if (rect.height) out.push({ top: rect.top - top0, bottom: rect.bottom - top0 });+ }+ }+ return out.sort((a, b) => a.top - b.top);+}++/** Footnote ids whose marker falls in [start, end), in document order. */+function notesIn(host: HTMLElement, page: PageSpec, start: number, end: number): string[] {+ const top0 = host.getBoundingClientRect().top + page.marginTop;+ const out: string[] = [];+ for (const sup of Array.from(host.querySelectorAll<HTMLElement>('sup.t-note'))) {+ const y = sup.getBoundingClientRect().top - top0;+ if (y >= start - 0.5 && y < end - 0.5) out.push(sup.dataset.note!);+ }+ return out;+}++/**+ * How tall the note area would be for these notes — MEASURED, not estimated.+ * A wrong estimate here moves every page break after it.+ */+let notesProbe: HTMLElement | null = null;+function measureNotes(doc: TypeDoc, page: PageSpec, ids: string[]): number {+ if (!ids.length) return 0;+ if (!notesProbe) {+ notesProbe = document.createElement('div');+ // marked transient so a save can never capture it (kernel/src/save.ts+ // strips marked nodes from the pristine clone)+ notesProbe.setAttribute('data-bento-transient', '');+ notesProbe.style.cssText = 'position:absolute;left:-10000px;top:0;visibility:hidden;contain:strict';+ document.body.appendChild(notesProbe);+ }+ const probe = notesProbe;+ probe.style.width = `${page.width - page.marginX * 2}px`;+ probe.innerHTML = `<div class="t-fnarea">` ++ ids.map((id, i) => `<p><b>${i + 1}</b>${escapeHtml(doc.footnotes[id] ?? '')}</p>`).join('') ++ `</div>`;+ return (probe.firstElementChild as HTMLElement).getBoundingClientRect().height + 10;+}+const escapeHtml = (s: string) =>+ s.replace(/[&<>]/g, c => ({ '&': '&', '<': '<', '>': '>' }[c]!));++/**+ * Compute the pages.+ *+ * The reserve↔break relation is circular, so each page iterates to a fixpoint.+ * When a state repeats — a genuine 2-cycle, not a hypothetical — the last note+ * is deferred to the next page and the loop ends.+ */+export function paginate(doc: TypeDoc, host: HTMLElement): Metrics {+ const t0 = performance.now();+ const page = doc.page;+ const H = bodyHeight(page);+ const boxes = lineBoxes(host, page);+ const pages: Page[] = [];++ let start = 0;+ /** notes pushed off the previous page — they MUST be placed on this one */+ let deferred: string[] = [];+ let guard = 0;++ while (guard++ < 2000) {+ const carried = deferred;+ deferred = [];+ let reserved = 0;+ let end = Infinity;+ let notes: string[] = carried;+ const seen = new Set<string>();++ for (let iter = 0; iter < 16; iter++) {+ const avail = H - reserved;+ let e = Infinity;+ for (const b of boxes) {+ if (b.top < start - 0.5) continue;+ if (b.bottom - start > avail) { e = b.top; break; }+ }+ const ids = carried.concat(notesIn(host, page, start, e));+ const need = measureNotes(doc, page, ids);+ if (Math.abs(need - reserved) < 0.5) { end = e; notes = ids; reserved = need; break; }++ // A state we have already been in is the 2-cycle: reserving room for+ // these notes shortens the page enough to push one of them off it, which+ // frees the room, which pulls it back. Break it by DEFERRING the last+ // note — never a carried one, or it would ping-pong forever.+ const key = `${ids.length}:${Math.round(need)}`;+ if (seen.has(key)) {+ if (ids.length > carried.length) {+ notes = ids.slice(0, -1);+ deferred = ids.slice(-1);+ } else {+ notes = ids; // nothing left to defer; take it+ }+ reserved = measureNotes(doc, page, notes);+ end = e;+ break;+ }+ seen.add(key);+ reserved = need; end = e; notes = ids;+ }++ pages.push({ n: pages.length + 1, start, end, notes, reserved });+ if (!isFinite(end)) break;+ start = end;+ }++ return { pages, ms: performance.now() - t0 };+}++/**+ * Draw the page furniture and the notes into the overlay.+ *+ * Notes go in the RIGHT-HAND GUTTER, beside their reference — not at the foot+ * of the page. In a continuous flow nothing physically reserves the space a+ * page-foot note would need, so the note lands on top of the body text (the+ * spike did exactly this before it was caught). Only a paginated OUTPUT can put+ * a note at a page foot, because only there is the space real. The BREAKS still+ * reserve room for them, so the page numbers are the ones the printed document+ * will have.+ */+export function drawPages(doc: TypeDoc, host: HTMLElement, deco: HTMLElement, metrics: Metrics): void {+ const page = doc.page;+ deco.replaceChildren();+ const frag = document.createDocumentFragment();++ for (const pg of metrics.pages) {+ if (pg.n === 1) continue;+ const y = pg.start + page.marginTop;+ const rule = el('div', 'rule'); rule.style.top = `${y}px`;+ const tl = el('div', 'tick'); tl.style.top = `${y}px`; tl.style.left = `${page.marginX - 24}px`;+ const tr = el('div', 'tick'); tr.style.top = `${y}px`;+ tr.style.left = `${page.width - page.marginX + 14}px`;+ const num = el('div', 'num'); num.style.top = `${y + 7}px`;+ num.style.left = `${page.width - page.marginX + 34}px`;+ num.textContent = String(pg.n);+ frag.append(rule, tl, tr, num);+ }++ // sidenotes, stacked so two never overlap+ const paperTop = host.getBoundingClientRect().top;+ let lastBottom = -1e9;+ const numbers = new Map<string, number>();+ Array.from(host.querySelectorAll<HTMLElement>('sup.t-note'))+ .forEach((sup, i) => numbers.set(sup.dataset.note!, i + 1));++ for (const sup of Array.from(host.querySelectorAll<HTMLElement>('sup.t-note'))) {+ const id = sup.dataset.note!;+ const text = doc.footnotes[id];+ if (!text) continue;+ const note = el('div', 'sidenote');+ note.dataset.note = id;+ note.innerHTML = `<b>${numbers.get(id)}</b>${escapeHtml(text)}`;+ frag.appendChild(note);+ const y = sup.getBoundingClientRect().top - paperTop;+ note.style.top = `${Math.max(y - 2, lastBottom + 8)}px`;+ // measured after insertion, so the stack accounts for real wrapped height+ deco.appendChild(note);+ lastBottom = parseFloat(note.style.top) + note.getBoundingClientRect().height;+ }+ deco.prepend(frag);+}++function el(tag: string, cls: string): HTMLElement {+ const n = document.createElement(tag);+ n.className = cls;+ return n;+}diff --git a/type/src/print.ts b/type/src/print.tsnew file mode 100644index 00000000..30f4be1c--- /dev/null+++ b/type/src/print.ts@@ -0,0 +1,189 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Paginated output — print, and PDF through the browser's own print dialog.+//+// WHY THIS IS NOT A NICETY. Two promises in the design live entirely here:+//+// 1. DETERMINISTIC PAGINATION. A .docx repaginates differently on a different+// machine — different font versions, different metrics, a printer driver in+// the loop — which is why legal and academic work is exchanged as PDF, not+// for looks but because page 14 paragraph 3 must be page 14 paragraph 3 for+// everyone. That property is only observable in the printed artifact.+// 2. FOOTNOTES AT PAGE FEET. The editing view puts notes in the margin beside+// their reference, because in a continuous flow nothing physically reserves+// the space a page-foot note would need and the note lands on top of the+// body (the spike did exactly that before it was caught). Here the space IS+// real, so notes go where a reader expects them.+//+// The output is built by FRAGMENTING the document into real page boxes — the+// thing the editor deliberately does not do, because fragmentation is not+// transparent to editing (arrow keys stall at the seam, backspace deletes two+// characters). Nothing is edited here, so the objection does not apply, and the+// pagination is the same computation the editor already ran.++import type { Block, TypeDoc } from './model.ts';+import { blockHtml, TAG } from './render.ts';+import type { Metrics } from './paginate.ts';++export interface PrintOptions {+ /** running head text; omitted = the document title */+ header?: string;+ /** show page numbers in the footer */+ pageNumbers?: boolean;+ /** first page carries no header/footer, as a title page usually should not */+ bareFirstPage?: boolean;+}++const esc = (s: string) => s.replace(/[&<>"]/g, c =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]!));++/**+ * The stylesheet the printed document carries.+ *+ * `@page` is sized from the document's own geometry, so a deck set to A4 prints+ * A4 and one set to Letter prints Letter — the page size is document data, not+ * a print-time question the user is asked twice.+ *+ * Margins are handled by the page BOX, not by `@page`, because the running head+ * and the footnote area have to live inside the margin and `@page` margins are+ * unreachable from content.+ */+function printCss(doc: TypeDoc): string {+ const p = doc.page;+ return `+@page { size: ${p.width}px ${p.height}px; margin: 0; }+* { box-sizing: border-box; -webkit-print-color-adjust: exact; print-color-adjust: exact; }+html, body { margin: 0; padding: 0; background: #fff; }+body {+ font: 17px/1.62 "Iowan Old Style","Palatino Linotype",Palatino,Georgia,serif;+ color: #1a1a1a; hyphens: auto; -webkit-hyphens: auto;+}+.t-page {+ position: relative;+ width: ${p.width}px; height: ${p.height}px;+ padding: ${p.marginTop}px ${p.marginX}px ${p.marginBottom}px;+ overflow: hidden;+ /* one sheet per page, and never a stray blank one after the last */+ break-after: page; page-break-after: always;+}+.t-page:last-child { break-after: auto; page-break-after: auto; }+.t-flow { position: relative; }+/* The flow is shifted UP by the page's start offset and clipped by the page+ box. Every page therefore renders the SAME document with the same line+ breaking, and shows its own window onto it — which is what makes the printed+ pagination identical to the one the editor computed. */+.t-body { position: relative; }+h1 { font-size: 26px; line-height: 1.24; font-weight: 600; margin: 0 0 14px; hyphens: none; }+h2 { font-size: 15.5px; font-weight: 600; margin: 24px 0 8px; hyphens: none; }+h3 { font-size: 14px; font-weight: 600; margin: 16px 0 6px; color: #3a3d44; hyphens: none; }+p { margin: 0 0 10px; text-align: justify; orphans: 2; widows: 2; text-wrap: pretty; }+p + p { text-indent: 1.4em; margin-top: -10px; padding-top: 10px; }+blockquote { margin: 12px 0 12px 24px; padding-left: 14px; border-left: 2px solid #d8dce2;+ color: #3a3d44; font-style: italic; }+strong { font-weight: 600; }+code { font: .88em/1 ui-monospace, SFMono-Regular, Menlo, monospace;+ background: #f1f0ec; padding: 1px 4px; border-radius: 3px; }+a { color: #2d4a7a; text-decoration: none; }+sup.t-note { font: 600 9px/1 -apple-system, system-ui, sans-serif; color: #7a5200;+ vertical-align: super; padding: 0 1px; }+.t-run { position: absolute; left: ${p.marginX}px; right: ${p.marginX}px;+ font: 10px/1 -apple-system, system-ui, sans-serif; color: #8b8f97;+ letter-spacing: .06em; }+.t-run.head { top: ${Math.max(28, p.marginTop - 46)}px; }+.t-run.foot { bottom: ${Math.max(28, p.marginBottom - 46)}px; text-align: center; }+/* footnotes sit at the FOOT of the page, in the space pagination reserved */+.t-fn { position: absolute; left: ${p.marginX}px; right: ${p.marginX}px;+ border-top: 1px solid #b9bdc5; padding-top: 5px;+ font: 12px/1.4 "Iowan Old Style",Palatino,Georgia,serif; color: #333; }+.t-fn p { margin: 0 0 2px; text-align: left; text-indent: 0; padding-top: 0; }+.t-fn b { font: 600 9px/1 -apple-system, system-ui, sans-serif; color: #7a5200;+ vertical-align: super; margin-right: 4px; }+`;+}++/** The body, rendered once — every page shows a window onto this same flow. */+function bodyHtml(body: Block[]): string {+ return body.map(b => `<${TAG[b.kind]} data-id="${esc(b.id)}">${blockHtml(b)}</${TAG[b.kind]}>`).join('\n');+}++/**+ * Build the printable document.+ *+ * Each page holds a copy of the whole flow, shifted up by that page's start+ * offset and clipped to the page box. That sounds wasteful and is the point:+ * every page lays the document out identically, so a line cannot break+ * differently on page 12 than the editor said it would. The alternative —+ * slicing the content per page — re-lays out each fragment and is exactly how+ * printed pagination drifts from what was on screen.+ */+export function buildPrintDocument(doc: TypeDoc, metrics: Metrics, opts: PrintOptions = {}): string {+ const p = doc.page;+ const head = opts.header ?? doc.title;+ const flow = bodyHtml(doc.body);+ const contentH = p.height - p.marginTop - p.marginBottom;++ // footnote numbering is derived, in document order, exactly as on screen+ const noteNumber = new Map<string, number>();+ let n = 0;+ for (const b of doc.body) for (const ref of b.notes ?? []) noteNumber.set(ref.id, ++n);++ const pages = metrics.pages.map((pg, i) => {+ const bare = opts.bareFirstPage && i === 0;+ const notes = pg.notes.filter(id => doc.footnotes[id] !== undefined);+ const fnHtml = notes.length+ ? `<div class="t-fn" style="bottom:${p.marginBottom + 10}px">` ++ notes.map(id => `<p><b>${noteNumber.get(id) ?? ''}</b>${esc(doc.footnotes[id]!)}</p>`).join('') ++ `</div>`+ : '';+ // The window is the page's ACTUAL extent — end minus start — not the+ // nominal content height. Clipping at a fixed height cuts the last line in+ // half, because pagination chose the break at a line boundary that is+ // almost never exactly `contentH - reserved` from the page top. The last+ // page has no end, so it gets the nominal height and simply runs out.+ const windowH = isFinite(pg.end) ? pg.end - pg.start : contentH - pg.reserved;+ const window = `<div class="t-flow" style="height:${windowH}px;overflow:hidden">` ++ `<div class="t-body" style="margin-top:${-pg.start}px">${flow}</div></div>`;+ return `<section class="t-page">` ++ (bare ? '' : `<div class="t-run head">${esc(head)}</div>`) ++ window + fnHtml ++ (bare || opts.pageNumbers === false ? '' : `<div class="t-run foot">${pg.n}</div>`) ++ `</section>`;+ }).join('\n');++ return `<!doctype html>+<html lang="en"><head><meta charset="utf-8">+<title>${esc(doc.title)}</title>+<style>${printCss(doc)}</style>+</head><body>${pages}</body></html>`;+}++/**+ * Open the print dialog on the paginated document.+ *+ * A hidden same-origin iframe rather than a popup: a popup is blocked without a+ * user gesture and lands in a window the user then has to close, and printing+ * the CURRENT document is not an option — the editor's DOM is one continuous+ * flow with decorations in an overlay, so it would print as one enormous page+ * with the notes in the margin.+ */+export function printDocument(doc: TypeDoc, metrics: Metrics, opts: PrintOptions = {}): void {+ const html = buildPrintDocument(doc, metrics, opts);+ const frame = document.createElement('iframe');+ frame.setAttribute('data-bento-transient', '');+ frame.style.cssText = 'position:fixed;right:0;bottom:0;width:1px;height:1px;opacity:0;border:0';+ document.body.appendChild(frame);+ const win = frame.contentWindow!;+ win.document.open();+ win.document.write(html);+ win.document.close();+ const go = () => {+ win.focus();+ win.print();+ // leave it a moment: removing the frame during print cancels the job in+ // some engines+ setTimeout(() => frame.remove(), 1000);+ };+ if (win.document.readyState === 'complete') setTimeout(go, 60);+ else win.addEventListener('load', () => setTimeout(go, 60));+}diff --git a/type/src/redline.ts b/type/src/redline.tsnew file mode 100644index 00000000..32a3e909--- /dev/null+++ b/type/src/redline.ts@@ -0,0 +1,278 @@+// SPDX-License-Identifier: MIT+// Redlining for bento/type.+//+// A redline is NOT a CRDT op log. CRDT ops are mechanical, auto-merged and+// per-keystroke; a redline is semantic, attributable, and above all REVIEWED —+// a human accepts or rejects each one. The op log may be a source for building+// one, but the change set is its own object with its own correctness rules.+//+// The two invariants everything else rests on:+// accept(all) == the document they sent back+// reject(all) == the document you sent+// If either fails, "review these changes" is a lie, because the reviewer's+// choices do not add up to either endpoint. Every other property (attribution,+// signing, partial acceptance) is worthless without those two.+//+// Granularity is WORDS, not lines and not characters. Line diffs are useless on+// prose (a reflowed paragraph reads as wholly rewritten); character diffs are+// technically correct and unreadable, marking "30" → "60" as a change of one+// glyph inside a word nobody can see.++import type { Block } from './model.ts';+import type { Mark } from './inline.ts';++export type Change =+ | { id: string; kind: 'text'; blockId: string; at: number; removed: string; added: string; author: string }+ | { id: string; kind: 'format'; blockId: string; before: Mark[]; after: Mark[]; author: string }+ | { id: string; kind: 'block-ins'; blockId: string; block: Block; index: number; author: string }+ | { id: string; kind: 'block-del'; blockId: string; block: Block; author: string }+ | { id: string; kind: 'reorder'; from: string[]; to: string[]; author: string };++export interface ChangeSet { base: string; author: string; changes: Change[] }++/** Split into words + the whitespace between them, so joins are lossless. */+export function tokenize(text: string): string[] {+ return text.match(/\s+|[^\s]+/g) ?? [];+}++/**+ * Myers-style LCS over tokens, returned as a compact op list.+ * O(n·m) memory is fine here: a paragraph is hundreds of tokens, not millions,+ * and blocks are diffed independently.+ */+export function diffTokens(a: string[], b: string[]): Array<{ op: string; tokens: string[] }> {+ const n = a.length, m = b.length;+ // trim the common head and tail first — in a redline most of a paragraph is+ // untouched, so this is the difference between instant and quadratic+ let s = 0;+ while (s < n && s < m && a[s] === b[s]) s++;+ let e = 0;+ while (e < n - s && e < m - s && a[n - 1 - e] === b[m - 1 - e]) e++;+ const A = a.slice(s, n - e), B = b.slice(s, m - e);++ const N = A.length, M = B.length;+ const lcs = Array.from({ length: N + 1 }, () => new Uint32Array(M + 1));+ for (let i = N - 1; i >= 0; i--)+ for (let j = M - 1; j >= 0; j--)+ lcs[i][j] = A[i] === B[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);++ const ops: Array<{ op: string; tokens: string[] }> = [];+ const push = (op: string, tokens: string[]) => {+ if (!tokens.length) return;+ const last = ops[ops.length - 1];+ if (last && last.op === op) last.tokens.push(...tokens);+ else ops.push({ op, tokens: [...tokens] });+ };+ push('eq', a.slice(0, s));+ let i = 0, j = 0;+ while (i < N && j < M) {+ if (A[i] === B[j]) { push('eq', [A[i]]); i++; j++; }+ else if (lcs[i + 1][j] >= lcs[i][j + 1]) { push('del', [A[i]]); i++; }+ else { push('ins', [B[j]]); j++; }+ }+ push('del', A.slice(i));+ push('ins', B.slice(j));+ push('eq', a.slice(n - e));+ return ops;+}++/**+ * A change set between two revisions of a document.+ *+ * Blocks are aligned by id where both sides have one — which is why stable ids+ * matter: without them a moved paragraph reads as a delete plus an unrelated+ * insert, and the reviewer sees two changes where the author made one.+ */+export function redline(+ before: { docId: string; body: Block[] },+ after: { docId: string; body: Block[] },+ { author = 'anon' }: { author?: string } = {},+): ChangeSet {+ const changes: Change[] = [];+ let seq = 0;+ const id = () => `c${++seq}`;++ const beforeById = new Map(before.body.map(b => [b.id, b]));+ const afterById = new Map(after.body.map(b => [b.id, b]));++ // blocks removed outright+ for (const b of before.body) {+ if (!afterById.has(b.id)) {+ changes.push({ id: id(), kind: 'block-del', blockId: b.id, block: b, author });+ }+ }+ // blocks added outright+ after.body.forEach((b, index) => {+ if (!beforeById.has(b.id)) {+ changes.push({ id: id(), kind: 'block-ins', blockId: b.id, block: b, index, author });+ }+ });+ // blocks present on both sides: diff their text, and note reordering+ const beforeOrder = before.body.filter(b => afterById.has(b.id)).map(b => b.id);+ const afterOrder = after.body.filter(b => beforeById.has(b.id)).map(b => b.id);+ if (beforeOrder.join() !== afterOrder.join()) {+ changes.push({ id: id(), kind: 'reorder', from: beforeOrder, to: afterOrder, author });+ }+ // A formatting change is a change. It has no text delta, so the token diff+ // below cannot see it — and in a contract, bolding a limitation of liability+ // is exactly the edit the other side must be shown. Reported separately, and+ // only when the TEXT is unchanged: when text moved too, the mark arithmetic+ // in `apply` carries the formatting with it and a second card would be noise.+ for (const b of before.body) {+ const a2 = afterById.get(b.id);+ if (!a2 || a2.text !== b.text) continue;+ const wasMarks = JSON.stringify(b.marks ?? []);+ const nowMarks = JSON.stringify(a2.marks ?? []);+ if (wasMarks !== nowMarks) {+ changes.push({ id: id(), kind: 'format', blockId: b.id,+ before: b.marks ?? [], after: a2.marks ?? [], author });+ }+ }++ for (const b of before.body) {+ const a2 = afterById.get(b.id);+ if (!a2 || a2.text === b.text) continue;+ const ops = diffTokens(tokenize(b.text), tokenize(a2.text));+ // One CHANGE per contiguous edit region, so a reviewer accepts a thought+ // rather than a token — and regions separated by only a few unchanged+ // characters are COALESCED into one.+ //+ // Without that, "30 days" → "sixty (60) calendar days" arrives as three+ // separate changes ("30"→"sixty", insert "(60) calendar ", …) which a+ // reviewer has to accept individually and could half-accept into nonsense.+ // Measured on the fixture: 3 changes become 1. The threshold is in+ // characters of untouched text between two edits.+ const COALESCE = 12;+ const raw = [];+ let cursor = 0, i = 0;+ while (i < ops.length) {+ if (ops[i].op === 'eq') { cursor += ops[i].tokens.join('').length; i++; continue; }+ const start = cursor;+ let removed = '', added = '';+ while (i < ops.length && ops[i].op !== 'eq') {+ if (ops[i].op === 'del') removed += ops[i].tokens.join('');+ else added += ops[i].tokens.join('');+ i++;+ }+ cursor += removed.length;+ raw.push({ at: start, removed, added });+ }+ const merged = [];+ for (const r of raw) {+ const prev = merged[merged.length - 1];+ const gap = prev ? r.at - (prev.at + prev.removed.length) : Infinity;+ if (prev && gap >= 0 && gap < COALESCE) {+ const between = b.text.slice(prev.at + prev.removed.length, r.at);+ prev.removed += between + r.removed;+ prev.added += between + r.added;+ } else merged.push({ ...r });+ }+ for (const m of merged) {+ changes.push({ id: id(), kind: 'text', blockId: b.id, at: m.at,+ removed: m.removed, added: m.added, author });+ }+ }+ return { base: before.docId, author, changes };+}++/**+ * Apply a change set, accepting only the ids in `accept`.+ * Rejected changes leave the document exactly as it was.+ */+export function apply(before: { docId: string; body: Block[] }, set: ChangeSet, accept: Set<string> | null = null): { docId: string; body: Block[] } {+ const take = (c: Change) => accept === null || accept.has(c.id);+ const body = before.body.map(b => ({ ...b }));+ const byId = new Map(body.map(b => [b.id, b]));++ // text edits first, right-to-left inside each block so earlier offsets stay valid+ const textChanges = set.changes.filter((c): c is Extract<Change, { kind: 'text' }> => c.kind === 'text' && take(c));+ const byBlock = new Map();+ for (const c of textChanges) {+ if (!byBlock.has(c.blockId)) byBlock.set(c.blockId, []);+ byBlock.get(c.blockId).push(c);+ }+ for (const [blockId, list] of byBlock) {+ const blk = byId.get(blockId);+ if (!blk) continue;+ list.sort((x: Extract<Change, { kind: 'text' }>, y: Extract<Change, { kind: 'text' }>) => y.at - x.at);+ if (blk.notes) blk.notes = blk.notes.map(n => ({ ...n }));+ for (const c of list) {+ if (blk.text.slice(c.at, c.at + c.removed.length) !== c.removed) {+ throw new Error(`change ${c.id} does not apply: expected ${JSON.stringify(c.removed)} at ${c.at}`);+ }+ blk.text = blk.text.slice(0, c.at) + c.added + blk.text.slice(c.at + c.removed.length);+ // Anything anchored INTO this block by character offset has to move with+ // the text, or it lands mid-word. TWO things are: footnote markers, and+ // formatting marks. A version of this that moved only one of them is the+ // bug that put a marker in the middle of a word during the spike.+ if (blk.marks) {+ const delta = c.added.length - c.removed.length;+ const end = c.at + c.removed.length;+ const move = (p: number) => p <= c.at ? p+ : p >= end ? p + delta+ : c.at + Math.min(p - c.at, c.added.length);+ const moved = blk.marks+ .map(m => ({ ...m, from: move(m.from), to: move(m.to) }))+ .filter(m => m.to > m.from);+ if (moved.length) blk.marks = moved; else delete blk.marks;+ }+ if (blk.notes) {+ const delta = c.added.length - c.removed.length;+ blk.notes = blk.notes+ // a marker inside the replaced span has lost its anchor entirely+ .filter(n => !(n.at > c.at && n.at < c.at + c.removed.length))+ .map(n => n.at >= c.at + c.removed.length ? { ...n, at: n.at + delta } : n);+ }+ }+ }++ // formatting+ for (const c of set.changes.filter((c): c is Extract<Change, { kind: 'format' }> => c.kind === 'format' && take(c))) {+ const blk = byId.get(c.blockId);+ if (!blk) continue;+ if (c.after.length) blk.marks = c.after.map(m => ({ ...m })); else delete blk.marks;+ }++ let out = body;+ // deletions+ const dels = new Set(set.changes.filter((c): c is Extract<Change, { kind: 'block-del' }> => c.kind === 'block-del' && take(c)).map(c => c.blockId));+ out = out.filter(b => !dels.has(b.id));+ // reorder+ const reorder = set.changes.find((c): c is Extract<Change, { kind: 'reorder' }> => c.kind === 'reorder' && take(c));+ if (reorder) {+ const rank = new Map(reorder.to.map((bid, i) => [bid, i]));+ out.sort((x, y) => (rank.get(x.id) ?? 1e9) - (rank.get(y.id) ?? 1e9));+ }+ // insertions, at their recorded index+ for (const c of set.changes.filter((c): c is Extract<Change, { kind: 'block-ins' }> => c.kind === 'block-ins' && take(c))) {+ out.splice(Math.min(c.index, out.length), 0, { ...c.block });+ }+ return { ...before, body: out };+}++/** A one-line human summary, the thing a reviewer actually reads. */+export function describe(c: Change): string {+ const clip = (s: string, n = 40) => s.length > n ? s.slice(0, n) + '…' : s;+ switch (c.kind) {+ case 'text':+ if (!c.removed) return `insert “${clip(c.added)}”`;+ if (!c.added) return `delete “${clip(c.removed)}”`;+ return `“${clip(c.removed, 24)}” → “${clip(c.added, 24)}”`;+ case 'format': {+ const names: Record<string, string> = { b: 'bold', i: 'italic', u: 'underline', s: 'strikethrough', code: 'code', link: 'link' };+ const was = new Set(c.before.map(m => m.t)), now = new Set(c.after.map(m => m.t));+ const added = [...now].filter(t => !was.has(t)).map(t => names[t] ?? t);+ const removed = [...was].filter(t => !now.has(t)).map(t => names[t] ?? t);+ if (added.length && !removed.length) return `apply ${added.join(', ')}`;+ if (removed.length && !added.length) return `remove ${removed.join(', ')}`;+ if (added.length || removed.length) return `${removed.join(', ')} → ${added.join(', ')}`;+ return 'change formatting';+ }+ case 'block-ins': return `insert new paragraph “${clip(c.block.text)}”`;+ case 'block-del': return `delete paragraph “${clip(c.block.text)}”`;+ case 'reorder': return `reorder ${c.to.length} paragraphs`;+ // every kind is handled above; TypeScript proves it, so this can only be+ // reached by a Change shape added without updating this switch+ default: return 'change';+ }+}diff --git a/type/src/render.ts b/type/src/render.tsnew file mode 100644index 00000000..ff537721--- /dev/null+++ b/type/src/render.ts@@ -0,0 +1,85 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// model → DOM. One renderer, shared by the editor, the paginated view and+// (eventually) print, so what an author edits is what the reader gets.+//+// The renderer is PURE with respect to the document: it reads and never writes.+// Everything it emits is reconstructible from the model, which is what lets the+// editor re-render a block at any moment without asking whether it is safe.++import { toHtml, fromDom, type Mark } from './inline.ts';+import type { Block, TypeDoc } from './model.ts';++export const TAG: Record<Block['kind'], string> = {+ para: 'p', h1: 'h1', h2: 'h2', h3: 'h3', quote: 'blockquote',+};++/** Footnote markers are ATOMS: they occupy a position but no characters. */+export const isNoteAtom = (el: Element) =>+ el.tagName === 'SUP' && el.classList.contains('t-note');++const noteMarker = (id: string) =>+ `<sup class="t-note" data-note="${id}" contenteditable="false">•</sup>`;++/** One block, as HTML. Marks become tags; note refs become atoms. */+export function blockHtml(b: Block): string {+ const inject = b.notes?.length+ ? new Map(b.notes.map(n => [n.at, noteMarker(n.id)]))+ : undefined;+ const html = toHtml(b.text, b.marks ?? [], inject);+ // an empty block still needs a line box, or it collapses and cannot be clicked+ return html || '<br>';+}++export function renderBlock(b: Block): HTMLElement {+ const el = document.createElement(TAG[b.kind]);+ el.dataset.id = b.id;+ el.dataset.kind = b.kind;+ el.innerHTML = blockHtml(b);+ return el;+}++/** The whole body. Callers own the host; this replaces its contents. */+export function renderBody(doc: TypeDoc, host: HTMLElement): void {+ const frag = document.createDocumentFragment();+ for (const b of doc.body) frag.appendChild(renderBlock(b));+ host.replaceChildren(frag);+ numberNotes(host, doc);+}++/**+ * Number the footnote markers in document order and put the number in the+ * marker. Numbering is DERIVED, never stored: inserting a note renumbers+ * everything after it, and a stored number would be wrong the moment it did.+ */+export function numberNotes(host: HTMLElement, _doc: TypeDoc): string[] {+ const order: string[] = [];+ for (const sup of host.querySelectorAll<HTMLElement>('sup.t-note')) {+ order.push(sup.dataset.note!);+ sup.textContent = String(order.length);+ }+ return order;+}++/**+ * Read one rendered block back into the model.+ *+ * The DOM is the only place the browser records what the author just typed, so+ * this is the seam where user intent enters the model — and the reason marks+ * are ranges over plain text rather than markup is that this function can then+ * be total: whatever the browser produced, the result is text plus marks, with+ * nothing that has no place to go.+ */+export function readBlock(el: HTMLElement, prev: Block): Block {+ const { text, marks, atoms } = fromDom(el, isNoteAtom);+ const out: Block = { ...prev, id: el.dataset.id || prev.id, text };+ const kind = el.dataset.kind as Block['kind'] | undefined;+ if (kind && kind in TAG) out.kind = kind;+ if (marks.length) out.marks = marks as Mark[]; else delete out.marks;+ const notes = atoms+ .map(a => ({ id: (a.el as HTMLElement).dataset.note!, at: a.at }))+ .filter(n => n.id);+ if (notes.length) out.notes = notes; else delete out.notes;+ return out;+}diff --git a/type/src/store.ts b/type/src/store.tsnew file mode 100644index 00000000..b3c24816--- /dev/null+++ b/type/src/store.ts@@ -0,0 +1,143 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Document state and undo.+//+// TWO THINGS THIS GETS RIGHT ON PURPOSE.+//+// 1. SCOPED SNAPSHOTS. bento/spaces measured the naive version: stringifying+// the whole document on every checkpoint left an undo depth of NINE on a+// 200-page handbook, because nine snapshots exhausted the memory budget. A+// typing run here records only the BLOCK it touched. That is fast and deep —+// and it is only correct while the mutation touched nothing else, so `doc`+// stays the default and callers must ASK for the narrow scope.+//+// 2. PRESENTATION IS NOT AN EDIT. Repagination, typesetting and footnote+// placement all mutate the DOM and none of them mutate the document, so they+// cannot enter the undo stack — there is no path from them to `commit`. The+// spike proved this matters: five typed characters must cost five undo+// presses, not five plus however many times the page re-laid-out.++import type { Block, TypeDoc } from './model.ts';++type Snap =+ | { kind: 'doc'; doc: TypeDoc }+ | { kind: 'block'; id: string; index: number; block: Block };++export type Scope = 'doc' | { block: string };+type Listener = (doc: TypeDoc) => void;++const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v)) as T;+const LIMIT = 200;++export class Store {+ #doc: TypeDoc;+ #undo: Snap[] = [];+ #redo: Snap[] = [];+ #listeners = new Set<Listener>();+ /** the open coalescing run, so a burst of typing is ONE undo step */+ #run: string | null = null;++ constructor(doc: TypeDoc) { this.#doc = doc; }++ get doc(): TypeDoc { return this.#doc; }+ get canUndo(): boolean { return this.#undo.length > 0; }+ get canRedo(): boolean { return this.#redo.length > 0; }+ /** depth, for diagnostics and for proving the scoped-snapshot claim */+ get undoDepth(): number { return this.#undo.length; }++ on(fn: Listener): () => void { this.#listeners.add(fn); return () => this.#listeners.delete(fn); }+ #emit() { for (const fn of this.#listeners) fn(this.#doc); }++ #snap(scope: Scope): Snap {+ if (scope === 'doc') return { kind: 'doc', doc: clone(this.#doc) };+ const index = this.#doc.body.findIndex(b => b.id === scope.block);+ if (index < 0) return { kind: 'doc', doc: clone(this.#doc) };+ return { kind: 'block', id: scope.block, index, block: clone(this.#doc.body[index]) };+ }++ #push(s: Snap) {+ this.#undo.push(s);+ if (this.#undo.length > LIMIT) this.#undo.shift();+ this.#redo.length = 0;+ }++ /**+ * Mutate the document.+ *+ * `run` names a coalescing group: successive commits with the SAME run share+ * one undo step, which is how a typed word is one press of ⌘Z rather than+ * five. Any commit without a run, or with a different one, closes the group.+ */+ commit(fn: (doc: TypeDoc) => void, opts: { scope?: Scope; run?: string } = {}): void {+ const scope = opts.scope ?? 'doc';+ const run = opts.run ?? null;+ if (run === null || run !== this.#run) this.#push(this.#snap(scope));+ this.#run = run;+ fn(this.#doc);+ this.#emit();+ }++ /** End the current typing run, so the next edit starts a new undo step. */+ breakRun(): void { this.#run = null; }++ /**+ * Announce a change that was made to the document from OUTSIDE — a remote+ * collaborator's edit applied surgically by the sync session.+ *+ * Deliberately NOT `commit`: a remote edit must not land on this person's+ * undo stack. ⌘Z means "undo what I did", and pushing a snapshot here would+ * make it revert a colleague's paragraph instead — while also making their+ * edit re-appear on redo, which is worse.+ */+ touch(): void { this.#emit(); }++ /** Replace the whole document — loading a file, or restoring a revision. */+ replace(doc: TypeDoc): void {+ this.#push({ kind: 'doc', doc: clone(this.#doc) });+ this.#run = null;+ this.#doc = doc;+ this.#emit();+ }++ #apply(s: Snap): Snap {+ if (s.kind === 'doc') {+ const inverse: Snap = { kind: 'doc', doc: clone(this.#doc) };+ this.#doc = s.doc;+ return inverse;+ }+ // A block snapshot restores that block in place. If the block is gone (a+ // later whole-doc edit removed it) fall back to re-inserting at the index+ // it had, rather than dropping the user's text on the floor.+ const at = this.#doc.body.findIndex(b => b.id === s.id);+ if (at >= 0) {+ const inverse: Snap = { kind: 'block', id: s.id, index: at, block: clone(this.#doc.body[at]) };+ this.#doc.body[at] = s.block;+ return inverse;+ }+ const index = Math.min(s.index, this.#doc.body.length);+ const inverse: Snap = { kind: 'doc', doc: clone(this.#doc) };+ this.#doc.body.splice(index, 0, s.block);+ return inverse;+ }++ undo(): boolean {+ const s = this.#undo.pop();+ if (!s) return false;+ this.#redo.push(this.#apply(s));+ this.#run = null;+ this.#emit();+ return true;+ }++ redo(): boolean {+ const s = this.#redo.pop();+ if (!s) return false;+ this.#undo.push(this.#apply(s));+ this.#run = null;+ this.#emit();+ return true;+ }++ block(id: string): Block | undefined { return this.#doc.body.find(b => b.id === id); }+}diff --git a/type/src/styles.css b/type/src/styles.cssnew file mode 100644index 00000000..94840128--- /dev/null+++ b/type/src/styles.css@@ -0,0 +1,235 @@+/* SPDX-License-Identifier: MIT+ Copyright (c) 2026 The Bento authors+ bento/type — chrome and page.++ The token set is the suite's, character for character, from+ slides/src/styles.css and spaces/src/styles.css. Do not fork it: a person+ with two Bento apps open should not be able to tell they were built+ separately, and the accent is doing brand work in all three.++ The page sits on LIGHT chrome and is separated by a shadow, exactly as a+ slide does on the slides canvas (.ed-stage). Dark surround is the obvious+ instinct for a document editor and it is not what this suite does. */++/* ————— tokens —————+ Split in two on purpose:++ THEMED (chrome) flips with the theme. NOT THEMED (paper, geometry) does not.+ Dark theme dims the APP, never the document: a slide's background is data the+ author chose, and a page is white because paper is white. Somebody proofing a+ contract at midnight still has to see what will print. */++:root {+ /* document surface — deliberately outside the themed set */+ --paper: #fff;+ --paper-ink: #1a1a1a;+ --paper-ink-2: #3a3d44;+ --paper-rule: #c3cad4;+ --paper-link-underline: #a9bcd8;++ /* geometry */+ --radius: 10px;+ --page-w: 816px; --page-h: 1056px;+ --mar-x: 104px; --mar-t: 104px; --mar-b: 104px;+ --gutter: 250px;+}++/* LIGHT — the suite's shared palette, character for character with+ slides/src/styles.css and spaces/src/styles.css. */+:root, :root[data-theme="light"] {+ --ink: #1e2a3a;+ --ink-2: #31445c;+ --chrome: #f5f7fa;+ --chrome-2: #eceff4;+ --line: #e3e8ef;+ --muted: #5b6472;+ --accent: #f7a600;+ --accent-ink: #7a5200;+ --blue: #5b8def;+ --field: #ffffff; /* form-control surface — CHROME, not paper */+ --grid-dot: #d5dbe4;+ --good: #1c7a45;+ --bad: #c0392b;+ --warnc: #a06a12;+ --page-shadow: 0 10px 40px rgb(20 30 45 / 0.18), 0 2px 8px rgb(20 30 45 / 0.10);+}++/* DARK — the same roles, not the same values. `--ink` is the chrome's+ FOREGROUND, so it inverts; `--accent` does not, because it is brand. */+:root[data-theme="dark"] {+ --ink: #e7eaf0;+ --ink-2: #b3bcca;+ --chrome: #1b1f26;+ --chrome-2: #262b34;+ --line: #333a45;+ --muted: #8b95a4;+ --accent: #f7a600;+ --accent-ink: #3a2a00; /* text ON the accent, so it flips */+ --blue: #7aa5f5; /* lifted: #5b8def is too dark to read here */+ --field: #12151a;+ --grid-dot: #2b313b;+ /* deeper, because a white page on a dark canvas needs more separation than+ the same page on a light one */+ --good: #5fb87a;+ --bad: #e06c5c;+ --warnc: #e0a33c;+ --page-shadow: 0 14px 48px rgb(0 0 0 / 0.55), 0 2px 10px rgb(0 0 0 / 0.4);+}++* { box-sizing: border-box; }+html, body {+ margin: 0; height: 100%;+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;+ font-size: 13px;+ color: var(--ink);+ background: var(--chrome);+ overscroll-behavior: none;+}+#app { display: grid; grid-template-rows: auto 1fr; height: 100vh; overflow: hidden; }+.t-main { display: grid; grid-template-columns: 250px 1fr; overflow: hidden; }+.t-side { background: var(--chrome); border-inline-end: 1px solid var(--line); overflow: auto; }+.t-tabs { display: flex; position: sticky; top: 0; z-index: 5;+ background: var(--chrome); border-bottom: 1px solid var(--line); }+.t-tabs button { flex: 1; border: 0; border-radius: 0; background: transparent;+ color: var(--muted); padding: 9px 4px; font-size: 11.5px; cursor: pointer; }+.t-tabs button:hover { background: var(--chrome-2); }+.t-tabs button.on { color: var(--ink); box-shadow: inset 0 -2px 0 var(--accent); font-weight: 600; }+.t-panel { display: none; padding: 10px 12px; }+.t-panel.on { display: block; }+.t-hint { color: var(--muted); font-size: 11.5px; line-height: 1.55; }+.t-outline a { display: block; color: var(--ink-2); text-decoration: none; padding: 3px 6px;+ border-radius: 4px; font-size: 12px; line-height: 1.35; cursor: pointer; }+.t-outline a:hover { background: var(--chrome-2); }+.t-outline a.h3 { padding-inline-start: 18px; color: var(--muted); font-size: 11.5px; }+.t-outline .pg { float: inline-end; color: var(--muted);+ font: 10px/1.5 ui-monospace, SFMono-Regular, monospace; }+.t-card { border: 1px solid var(--line); border-radius: 8px; padding: 8px 9px;+ margin-bottom: 7px; background: var(--field); }+.t-card .who { font-size: 10.5px; color: var(--muted); margin-bottom: 4px; }+.t-card .what { font-size: 12px; line-height: 1.45; word-break: break-word; color: var(--ink); }+.t-card .what del { color: var(--bad); text-decoration: line-through; }+.t-card .what ins { color: var(--good); text-decoration: none; }+.t-card .btns { display: flex; gap: 5px; margin-top: 7px; }+.t-card .btns button { flex: 1; padding: 3px 6px; font-size: 11px; font: inherit;+ border: 1px solid var(--line); background: var(--chrome); color: var(--ink-2);+ border-radius: 6px; cursor: pointer; }+.t-card .btns button:hover { background: var(--chrome-2); }+.t-card.done { opacity: .45; }+.t-fp { font: 10px/1.5 ui-monospace, SFMono-Regular, monospace; color: var(--muted);+ word-break: break-all; margin-top: 3px; }+.t-ok { color: var(--good); } .t-bad { color: var(--bad); } .t-warn { color: var(--warnc); }++/* ————— toolbar ————— */+.t-bar {+ display: flex; align-items: center; gap: 6px; flex-wrap: wrap;+ padding: 8px 14px;+ background: var(--chrome);+ border-bottom: 1px solid var(--line);+}+.t-brand {+ font-weight: 600; color: var(--ink); margin-inline-end: 6px;+ letter-spacing: .01em; white-space: nowrap;+}+.t-brand small { color: var(--muted); font-weight: 400; margin-inline-start: 4px; }++.t-bar button {+ display: inline-flex; align-items: center; gap: 6px;+ font: inherit; font-size: 13px;+ color: var(--ink-2);+ background: transparent;+ border: 1px solid transparent;+ border-radius: 8px;+ padding: 6px 9px;+ cursor: pointer;+ white-space: nowrap;+}+.t-bar button:hover { background: var(--chrome-2); }+.t-bar button:active { background: var(--line); }+.t-bar button.on {+ background: var(--accent); border-color: var(--accent);+ color: var(--accent-ink); font-weight: 600;+}+.t-bar button.primary { background: var(--ink); color: var(--chrome); padding: 6px 14px; }+.t-bar button.primary:hover { background: var(--ink-2); }+.t-bar select {+ font: inherit; font-size: 13px; color: var(--ink-2);+ background: var(--field); border: 1px solid var(--line);+ border-radius: 8px; padding: 5px 8px; cursor: pointer;+}+.t-sep { width: 1px; height: 20px; background: var(--line); margin: 0 5px; }+.t-spacer { flex: 1; }+.t-stat {+ color: var(--muted);+ font: 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;+ white-space: nowrap;+}++/* ————— the page ————— */+.t-scroll {+ overflow: auto; padding: 28px 0 200px; scrollbar-gutter: stable both-edges;+ /* the slides canvas texture, so a page and a slide sit on the same surface */+ background:+ radial-gradient(circle at 1px 1px, var(--grid-dot) 1px, transparent 0) 0 0 / 22px 22px,+ var(--chrome);+}+.t-wrap { position: relative; margin: 0 auto; width: calc(var(--page-w) + var(--gutter)); }+.t-paper {+ background: var(--paper);+ width: var(--page-w); min-height: var(--page-h);+ padding: var(--mar-t) var(--mar-x) var(--mar-b);+ /* the slides canvas shadow, so a page and a slide read as the same object */+ box-shadow: var(--page-shadow);+ border-radius: 2px;+ position: relative; z-index: 1;+ color: var(--paper-ink);+ font: 17px/1.62 "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif;+ hyphens: auto; -webkit-hyphens: auto;+}+.t-paper:focus { outline: none; }+.t-paper h1 { font-size: 26px; line-height: 1.24; font-weight: 600; margin: 0 0 14px; hyphens: none; }+.t-paper h2 { font-size: 15.5px; font-weight: 600; margin: 24px 0 8px; hyphens: none; break-after: avoid; }+.t-paper h3 { font-size: 14px; font-weight: 600; margin: 16px 0 6px; color: var(--paper-ink-2); hyphens: none; }+.t-paper p { margin: 0 0 10px; text-align: justify; orphans: 2; widows: 2; text-wrap: pretty; }+.t-paper p + p { text-indent: 1.4em; margin-top: -10px; padding-top: 10px; }+.t-paper blockquote {+ margin: 12px 0 12px 24px; padding-inline-start: 14px;+ border-inline-start: 2px solid var(--line);+ color: var(--paper-ink-2); font-style: italic;+}+.t-paper strong { font-weight: 600; }+.t-paper code {+ font: 0.88em/1 ui-monospace, SFMono-Regular, Menlo, monospace;+ background: var(--chrome-2); padding: 1px 4px; border-radius: 3px;+}+.t-paper a { color: var(--blue); text-decoration: none; border-bottom: .5px solid var(--paper-link-underline); }+.t-paper sup.t-note {+ font: 600 9px/1 -apple-system, system-ui, sans-serif;+ color: var(--accent-ink); vertical-align: super; cursor: pointer; padding: 0 1px;+}+.t-paper sup.t-note:hover { background: rgb(247 166 0 / 0.22); border-radius: 2px; }++/* Decorations live OUTSIDE the editable: they cannot be typed into, cannot+ enter the undo stack, and cannot perturb layout. */+.t-deco { position: absolute; inset: 0; pointer-events: none; z-index: 2; }+.t-deco .rule {+ position: absolute; left: var(--mar-x);+ width: calc(var(--page-w) - var(--mar-x) * 2);+ border-top: 1px solid var(--line);+}+.t-deco .tick { position: absolute; width: 10px; border-top: 1px solid var(--paper-rule); }+.t-deco .num {+ position: absolute; color: var(--muted);+ font: 10px/1 -apple-system, system-ui, sans-serif; letter-spacing: .07em;+}+.t-deco .sidenote {+ position: absolute; left: var(--page-w);+ width: calc(var(--gutter) - 26px); margin-inline-start: 22px;+ font: 11.5px/1.42 -apple-system, system-ui, sans-serif;+ color: var(--muted);+ padding-inline-start: 11px;+ border-inline-start: 2px solid var(--accent);+}+.t-deco .sidenote b {+ font: 600 9px/1 -apple-system, system-ui, sans-serif;+ color: var(--accent-ink); vertical-align: super; margin-inline-end: 4px;+}diff --git a/type/src/sync/crdt.ts b/type/src/sync/crdt.tsnew file mode 100644index 00000000..405ccca8--- /dev/null+++ b/type/src/sync/crdt.ts@@ -0,0 +1,63 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento-sync for bento/type — the kernel engine, bound to this app's shape.+//+// A FACADE, as slides/src/sync/crdt.ts and spaces/src/sync/crdt.ts are. The+// engine lives in kernel/src/sync/crdt.ts and takes its document shape as+// property names, so one algebra serves three apps without any app's+// vocabulary living in the kernel.+//+// type is the first FLAT binding, and the first whose text is not on a child.+// Both of those were kernel changes (docs/DECISIONS.md, 2026-08-15) rather+// than anything this file works around.++export * from '../../../kernel/src/sync/crdt.ts';++import { SyncEngine, shape } from '../../../kernel/src/sync/crdt.ts';+import type { DocShape } from '../../../kernel/src/sync/crdt.ts';++/**+ * bento/type: the document holds `body`, a block holds its own `text`, and+ * there is nothing beneath a block.+ *+ * Frozen from the first shared file, exactly as the other two bindings are:+ * these strings are minted into every persisted SyncStateJSON and every relay+ * frame, so changing one would fork a document from its own copies.+ *+ * WHY FLAT. A word processor's document is a stream of prose poured into+ * pages; the structure lives in the block kinds and the pagination, not in the+ * container (model.ts says the same). There is no honest key to point+ * `children` at, so the shape says `null` rather than making every block carry+ * an empty array to satisfy the engine.+ *+ * WHY `text` IS NAMED. It is the property that gets the token RGA instead of a+ * last-writer-wins register — the difference between two people typing in one+ * paragraph and one of them silently losing their work. Both other apps put+ * their text on a child under the key `html`; type's is on the block itself+ * and is plain text, so it has to say so.+ *+ * WHAT IS NOT SOLVED BY THE SHAPE, and is documented rather than hidden:+ * `marks` and `notes` are offsets INTO that text, and they merge as ordinary+ * whole-value registers while the text merges token by token. Those are two+ * independent merge domains describing one paragraph, so concurrent edits can+ * converge on offsets that no longer describe the text they index — the same+ * class of problem `parent`-vs-position is for bento/spaces.+ * scripts/test-sync-type.ts measures it rather than assuming either way.+ *+ * WHY `footnotes` IS DECLARED A MAP. A footnote's BODY lives in a doc-level+ * map keyed by note id, so it can outlive a re-flow of the paragraph that+ * references it (model.ts says so). As one whole-value register, two authors+ * adding a footnote each would keep both REFERENCES — those live on different+ * blocks and merge independently — while one of the two bodies was overwritten,+ * leaving a marker in the text pointing at nothing. Measured before it was+ * declared: 34 of 120 fuzz seeds converged on a document with a dangling note.+ * Per-key, as `assets` and `blobs` have always been, both survive.+ */+export const TYPE_SHAPE: DocShape = shape('body', null, 'text', ['footnotes']);++/** The engine bound to bento/type. */+export class SyncState extends SyncEngine {+ constructor(actor: string) {+ super(actor, TYPE_SHAPE);+ }+}diff --git a/type/src/sync/session.ts b/type/src/sync/session.tsnew file mode 100644index 00000000..a2285b57--- /dev/null+++ b/type/src/sync/session.ts@@ -0,0 +1,119 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento-sync session for bento/type — the kernel session, bound to this app.+//+// The session moved into the kernel with a small host adapter for the five+// things it could not know: what an EMPTY document is, how to clamp a view+// onto a document that changed underneath it, where a person is for presence,+// which store events an editor listens to, and what embedded media looks like.+// This file answers those five for a word processor. Everything else — the+// differ, the shadow, catch-up, gap recovery, blobs, the fork snapshot+// exchange — is shared with bento/slides and got no type-specific code at all.+//+// The differences from slides are the interesting part, and none of them are+// cosmetic:+//+// · EMPTY means no BLOCKS, and the repair is an empty paragraph — a document+// always has somewhere to put the caret.+// · WHERE YOU ARE is a block id, not a slide id. It rides the wire field+// named `slide`, which is frozen (deployed clients and the relay read it)+// and means "where this person is".+// · type's Store has no per-event listeners and no dirty flag; it has one+// listener list and scoped undo. The adapter bridges that rather than+// asking the app to grow a slides-shaped store.++export * from '../../../kernel/src/sync/session.ts';++import {+ SyncSession as KernelSession,+ type HostStore,+ type SyncHost,+} from '../../../kernel/src/sync/session.ts';+import type { Op } from '../../../kernel/src/sync/crdt.ts';+import { SyncState } from './crdt.ts';+import type { Store } from '../store.ts';++/**+ * type's Store, presented as the store the kernel session expects.+ *+ * `on` takes an EVENT in the kernel's interface and none in type's, because+ * type's editor re-renders from one signal rather than five. Only 'doc' has a+ * meaning here; the rest are accepted and dropped, which is the honest mapping+ * — an app is not obliged to have a 'slides' event.+ */+function hostStore(store: Store): HostStore {+ return {+ get doc() { return store.doc; },+ on(event: string, fn: () => void) {+ return event === 'doc' ? store.on(() => fn()) : () => {};+ },+ // A remote edit repaints but must NEVER push an undo entry — see+ // Store.touch. 'doc' is the only event type has.+ emit(event: string) { if (event === 'doc') store.touch(); },+ commit(fn: () => void) { store.commit(() => fn()); },+ // type has no dirty flag: the document is saved from the editor's own+ // state, and a remote edit does not change whether THIS person has+ // unsaved work. Accepting and ignoring beats inventing a flag nothing reads.+ setDirty() {},+ };+}++/** What a word-processing document knows that the session cannot work out. */+function typeHost(store: Store, caret: () => { block: string }): SyncHost {+ return {+ store: hostStore(store),+ engine: SyncState,++ heal(): boolean {+ // A delete-everything race can leave a document with no blocks, which+ // gives the caret nowhere to live. One empty paragraph is the repair.+ if (store.doc.body.length > 0) return false;+ // DETERMINISTIC id, derived from docId. The repair is minted as an+ // ordinary local op and nothing deduplicates it, so a random id means+ // two replicas healing at once produce TWO empty paragraphs and the+ // CRDT keeps both. bento/slides tolerates that (a spare blank slide is+ // obvious and harmless); a spare empty paragraph in a contract is not —+ // it is invisible in the flow and changes the pagination.+ store.doc.body.push({ id: `heal-${store.doc.docId}`, kind: 'para', text: '' });+ return true;+ },++ clampView(): boolean {+ // Nothing to clamp: the caret is a MODEL position (block id + offset),+ // so a block that disappears is handled where the caret lives rather+ // than by an index that can point past the end. This is the payoff for+ // that decision showing up somewhere unrelated to editing.+ return false;+ },++ presence() {+ return { at: caret().block, sel: [] };+ },++ // type's editor re-renders from one signal, so a structural change needs+ // no extra events beyond the 'doc' the session already emits.+ changeEvents: ['doc'],+ structureEvents: [],+ presenceEvents: [],++ carriesMedia(ops: Op[]): boolean {+ // A type document embeds fonts and images as doc-level assets rather+ // than as element properties, so the probe is simpler than slides': any+ // data: URI in a set op is the payload that made the batch too big.+ return ops.some(o => o.op === 'set' && typeof o.v === 'string' && o.v.startsWith('data:'));+ },+ };+}++/**+ * The session bound to bento/type.+ *+ * `caret` is a callback rather than a value because presence is pushed+ * whenever the session likes; the editor owns where the caret is and should+ * not have to mirror it into the session on every keystroke.+ */+export class SyncSession extends KernelSession {+ constructor(store: Store, caret: () => { block: string } = () => ({ block: '' })) {+ super(typeHost(store, caret));+ }+}diff --git a/type/tsconfig.json b/type/tsconfig.jsonnew file mode 100644index 00000000..f51f643a--- /dev/null+++ b/type/tsconfig.json@@ -0,0 +1,19 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "useDefineForClassFields": true,+ "module": "ESNext",+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "skipLibCheck": true,+ "moduleResolution": "bundler",+ "allowImportingTsExtensions": true,+ "isolatedModules": true,+ "moduleDetection": "force",+ "noEmit": true,+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "noFallthroughCasesInSwitch": true+ },+ "include": ["src"]+}diff --git a/type/vite.config.ts b/type/vite.config.tsnew file mode 100644index 00000000..eb02eb39--- /dev/null+++ b/type/vite.config.ts@@ -0,0 +1,25 @@+import { defineConfig } from 'vite'+import { viteSingleFile } from 'vite-plugin-singlefile'+import { readFileSync } from 'node:fs'++const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))++// base './' so builds open from file:// or any static host.+// SINGLEFILE=1 → everything (JS, CSS, assets) inlined into one HTML file:+// that file IS the Bento document format.+export default defineConfig({+ base: './',+ // The app version baked into every shipped shell — what update checks+ // compare against the release manifest. Single source: package.json.+ define: { __APP_VERSION__: JSON.stringify(pkg.version) },+ plugins: [...(process.env.SINGLEFILE ? [viteSingleFile()] : [])],+ // Dev-only: allow serving ../kernel (shared TS-source kernel) — without a+ // workspace root, vite's fs allow-list stops at the app dir. Build output+ // is unaffected (rollup has no such restriction).+ server: { fs: { allow: ['..'] } },+ build: {+ // Keep asset inlining aggressive; a Bento file must have zero external requests.+ assetsInlineLimit: 100_000_000,+ chunkSizeWarningLimit: 4096,+ },+})