Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
type: Replace from JSON brings content, never history (#708)
nyblnet7b81d13d777f
diff --git a/scripts/test-type-share.ts b/scripts/test-type-share.tsindex 65f46c9b..8efd25b6 100644--- a/scripts/test-type-share.ts+++ b/scripts/test-type-share.ts@@ -31,7 +31,8 @@ const { mintCollab } = await import('../kernel/src/sync/online.ts')const { mergeDoc } = await import('../type/src/merge.ts')const { newThread, writeThreads } = await import('../type/src/comments.ts')const { sign, newKey } = await import('../type/src/canon.ts')-const { TYPE_FIELDS, HISTORY_CLASS } = await import('../type/src/docclass.ts')+const { TYPE_FIELDS, HISTORY_CLASS, keepLiveHistory } = await import('../type/src/docclass.ts')+const { Store } = await import('../type/src/store.ts')import type { TypeDoc } from '../type/src/model.ts'let checks = 0, failures = 0@@ -375,5 +376,58 @@ H('the class map is the single source')'the invite opt-out list is DERIVED from the map, not hand-listed')}+H('Replace from JSON brings CONTENT, never history')+{+ // Copy document JSON leaves history out (tier copyJSON), so before this rule+ // pasting it straight back silently emptied every history field: the+ // ordinary AI round trip deleted the document's revisions and comments.+ // The rule (same as bento/spaces'): a paste never installs history — every+ // history-class field keeps the LIVE value, whatever the paste carries.+ const store = new Store(JSON.parse(JSON.stringify(F.doc)))+ const liveRevs = JSON.stringify(store.doc.revisions)+ const liveNotes = JSON.stringify(store.doc.comments)+ ok(has(store.doc, DRAFT) && has(store.doc, NOTE), 'the live document has history to lose (a draft and a comment)')++ // 1. the unchanged round trip+ const pasted = parseDoc(JSON.stringify(docForExport(store.doc)))+ ok(pasted.ok && !has(pasted.doc, DRAFT), 'the pasted Copy JSON really carries no history')+ store.replace(keepLiveHistory(store.doc, (pasted as { doc: TypeDoc }).doc))+ ok(JSON.stringify(store.doc.revisions) === liveRevs, 'an unchanged round trip keeps every revision')+ ok(JSON.stringify(store.doc.comments) === liveNotes, 'and every comment thread')++ // 2. a paste carrying DIFFERENT history does not install it+ const forged = JSON.parse(JSON.stringify(docForExport(store.doc)))+ forged.revisions = [{ id: 'evil', at: 'x', label: 'Forged', body: [{ id: 'p1', kind: 'para', text: 'FORGED-DRAFT' }] }]+ forged.comments = { evil: { id: 'evil', text: 'FORGED-NOTE', author: 'Mallory', at: 'x', replies: [],+ anchor: { block: F.doc.body[0].id, from: 0, to: 3 } } }+ forged.body[0].text = 'Payment is due within 90 days.'+ const fp = parseDoc(JSON.stringify(forged))+ ok(fp.ok && has(fp.doc, 'FORGED-DRAFT'), 'the forged paste really carries its own revisions')+ store.replace(keepLiveHistory(store.doc, (fp as { doc: TypeDoc }).doc))+ ok(!has(store.doc, 'FORGED-DRAFT') && JSON.stringify(store.doc.revisions) === liveRevs,+ 'a paste cannot install or swap revisions')+ ok(!has(store.doc, 'FORGED-NOTE') && JSON.stringify(store.doc.comments) === liveNotes,+ 'nor comment threads')+ ok(store.doc.body[0].text === 'Payment is due within 90 days.', 'while its CONTENT does land — that is what a paste is for')++ // 3. a document with NO history: a paste carrying some does not give it any+ const bareStore = new Store(JSON.parse(JSON.stringify((await bare()).doc)))+ const withRevs = JSON.parse(JSON.stringify(bareStore.doc))+ withRevs.revisions = [{ id: 'r', at: 'x', label: 'R', body: [] }]+ const wp = parseDoc(JSON.stringify(withRevs))+ bareStore.replace(keepLiveHistory(bareStore.doc, (wp as { doc: TypeDoc }).doc))+ ok((bareStore.doc.revisions ?? []).length === 0, 'a document with no history gets none from a paste')++ // 4. both paste paths in main.ts go through it (DOM code, so checked by source)+ const main = readFileSync(new URL('../type/src/main.ts', import.meta.url), 'utf8')+ const replaceBody = main.slice(main.indexOf('onReplaceDoc: json =>'), main.indexOf('onRestoreDoc:'))+ const loadBody = main.slice(main.indexOf('loadDoc: (json: string) =>'), main.indexOf('i18n: i18nApi'))+ ok(/store\.replace\(keepLiveHistory\(store\.doc, parsed\.doc\)\)/.test(replaceBody),+ 'Replace from JSON… replaces through keepLiveHistory')+ ok(/store\.replace\(keepLiveHistory\(store\.doc, parsed\.doc\)\)/.test(loadBody),+ 'and so does bento.loadDoc, its scripted twin')+ ok(!/store\.replace\(parsed\.doc\)/.test(replaceBody + loadBody), 'neither replaces with the raw paste')+}+console.log(`\n${checks - failures}/${checks} checks passed`)if (failures) process.exit(1)diff --git a/type/src/docclass.ts b/type/src/docclass.tsindex ed9172f4..ebbd0369 100644--- a/type/src/docclass.ts+++ b/type/src/docclass.ts@@ -97,3 +97,33 @@ export type HistoryField = FieldsOfClass<typeof TYPE_FIELDS, 'history'>;export const HISTORY_CLASS: readonly HistoryField[] =(Object.keys(TYPE_FIELDS) as Array<keyof typeof TYPE_FIELDS>).filter((k): k is HistoryField => TYPE_FIELDS[k] === 'history');++/**+ * A PASTED document never brings its own history: every history-class field+ * keeps the LIVE value, and one the live document lacks is removed from the+ * paste. For "Replace from JSON…" and its scripted twin `bento.loadDoc` only.+ *+ * History is this file's own log — earlier drafts, the comment threads, and+ * (once signatures commit to it) the salt every signature's commitment is+ * made under. A paste must not be able to forge it, swap it, or erase it.+ * Without this, the ordinary AI round trip was destructive: Copy document JSON+ * leaves history out (the copy table's 'copyJSON' tier), so pasting the result+ * straight back defaulted every history field to empty and silently deleted+ * the document's revisions and comments.+ *+ * Same rule as bento/spaces' keepLiveHistory, deliberately — but NOT applied to+ * every whole-document replace as spaces does: type's crash recovery restores a+ * NEWER copy of this same document, and there the snapshot's history is the+ * newer one and is meant to come back (scripts/test-type-autosave.ts).+ *+ * Read from the map, so a history field classified later is kept the same way.+ * Mutates and returns `next`; values are copied, never shared with `live`.+ */+export function keepLiveHistory<T extends object>(live: T, next: T): T {+ const n = next as Record<string, unknown>, l = live as Record<string, unknown>;+ for (const k of HISTORY_CLASS) {+ if (Object.hasOwn(l, k) && l[k] !== undefined) n[k] = structuredClone(l[k]);+ else delete n[k];+ }+ return next;+}diff --git a/type/src/main.ts b/type/src/main.tsindex 679e1cde..09c52dab 100644--- a/type/src/main.ts+++ b/type/src/main.ts@@ -20,6 +20,7 @@ import { startTheme, setTheme, themeChoice, type ThemeChoice } from '../../kerneimport { parseDoc, emptyDoc, uid, wordCount, withoutEmbeddedCaps, type TypeDoc } from './model.ts';import { gateRestored } from './restoregate.ts';import { Store } from './store.ts';+import { keepLiveHistory } from './docclass.ts';import { Editor } from './editor.ts';import { paginate, drawPages, type Metrics } from './paginate.ts';import { takeSnapshot, startReview } from './redlineview.ts';@@ -232,7 +233,9 @@ const showAbout = () => openAbout({: t('That is not a bento/type document: {detail}', { detail: parsed.detail }));return;}- store.replace(parsed.doc);+ // The paste brings content, never history: this file's revisions and+ // comments stay as they are (docclass.ts keepLiveHistory).+ store.replace(keepLiveHistory(store.doc, parsed.doc));// store.replace swaps the model; only this rebuilds the paper from it.// Without it the document changed and the screen did not — which is what// "Replace from JSON…" did on the day it was added.@@ -1027,7 +1030,7 @@ dirty = false; paintTitle();loadDoc: (json: string) => {const parsed = parseDoc(json);if (!parsed.ok) throw new Error(`bento/type: ${parsed.err === 'empty' ? 'empty document' : parsed.detail}`);- store.replace(parsed.doc);+ store.replace(keepLiveHistory(store.doc, parsed.doc)); // the same rule as Replace from JSONeditor.render();schedule();return true;