@tearleads/client-sdk 0.1.207 → 0.1.209

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/client/documents/index.d.ts +8 -0
  2. package/client/documents/index.js +14 -1
  3. package/client/documents/index.js.map +1 -1
  4. package/client/index.d.ts +1 -1
  5. package/client/index.js.map +1 -1
  6. package/data/documents/documentRestore.d.ts +30 -0
  7. package/data/documents/documentRestore.js +86 -0
  8. package/data/documents/documentRestore.js.map +1 -0
  9. package/data/documents/documentRowList.d.ts +6 -0
  10. package/data/documents/documentRowList.js +31 -0
  11. package/data/documents/documentRowList.js.map +1 -1
  12. package/data/documents/index.d.ts +1 -0
  13. package/data/documents/index.js.map +1 -1
  14. package/index.d.ts +3 -3
  15. package/index.js +1 -1
  16. package/index.js.map +1 -1
  17. package/internal/loro/historyTimeline.d.ts +57 -0
  18. package/internal/loro/historyTimeline.js +271 -0
  19. package/internal/loro/historyTimeline.js.map +1 -0
  20. package/internal/loro/index.d.ts +1 -0
  21. package/internal/loro/index.js +1 -0
  22. package/internal/loro/index.js.map +1 -1
  23. package/package.json +1 -1
  24. package/stores/documents/documentStore/history/restoreContent.js +127 -0
  25. package/stores/documents/documentStore/history/restoreContent.js.map +1 -0
  26. package/stores/documents/documentStore/index.js +4 -4
  27. package/stores/documents/documentStore/index.js.map +1 -1
  28. package/stores/documents/documentStore/mutations.js +1 -1
  29. package/stores/documents/documentStore/mutations.js.map +1 -1
  30. package/stores/documents/documentStore/rows/index.js +8 -0
  31. package/stores/documents/documentStore/rows/index.js.map +1 -1
  32. package/stores/documents/registry.js +1 -0
  33. package/stores/documents/registry.js.map +1 -1
  34. package/stores/documents/removedDocumentStore.js +1 -0
  35. package/stores/documents/removedDocumentStore.js.map +1 -1
  36. package/stores/documents/types.d.ts +10 -1
  37. package/stores/documents/types.js.map +1 -1
  38. package/workflows/documents/history/documentHistory.d.ts +72 -0
  39. package/workflows/documents/history/documentHistory.js +103 -0
  40. package/workflows/documents/history/documentHistory.js.map +1 -0
  41. package/workflows/documents/history/documentHistoryChange.d.ts +51 -0
  42. package/workflows/documents/history/documentHistoryChange.js +110 -0
  43. package/workflows/documents/history/documentHistoryChange.js.map +1 -0
  44. package/workflows/documents/index.d.ts +2 -0
  45. package/workflows/documents/index.js +2 -0
  46. package/workflows/documents/index.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"registry.js","sourceRoot":"","sources":["registry.ts"],"names":[],"mappings":"AACA,OAAO,EACL,8BAA8B,EAC9B,uCAAuC,GACxC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AAwBpE,MAAM,8BAA8B,GAAG,IAAI,OAAO,EAG/C,CAAC;AAGJ,mEAAmE;AACnE,qEAAqE;AACrE,wEAAwE;AACxE,SAAS,4BAA4B;IAGnC,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAA8B,CAAC;IAEnE,OAAO;QACL,IAAI,EAAE,CAAC,WAAwB,EAAE,GAAG,IAA0B,EAAQ,EAAE;YACtE,MAAM,SAAS,GAAG,gBAAgB,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;YACpD,IAAI,CAAC,SAAS,EAAE,CAAC;gBACf,OAAO;YACT,CAAC;YAED,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;gBACjC,QAAQ,CAAC,GAAG,IAAI,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;QACD,SAAS,EAAE,CAAC,WAAwB,EAAE,QAAkB,EAAgB,EAAE;YACxE,MAAM,SAAS,GACb,gBAAgB,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,IAAI,GAAG,EAAY,CAAC;YAC3D,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACxB,gBAAgB,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;YAE7C,OAAO,GAAG,EAAE;gBACV,SAAS,CAAC,M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,QAAQ,CAAC,CAAC;QACxC,KAAK,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n registerInternalDocumentRelink,\n relinkDocumentStoreWithCommitSideEffect,\n} from \"./documentStore/internalRelink\";\nimport { createRemovedDocumentStore } from \"./removedDocumentStore\";\nimport type {\n DocumentAttachmentUpload,\n DocumentStore,\n DocumentStoreFacade,\n DocumentsRuntime,\n PersistedDocumentListener,\n} from \"./types\";\n\ninterface DocumentStoreRegistry {\n /** How the last open built each store's backing store, by store key. */\n freshStoreFactories: Map<string, () => DocumentStore>;\n /** Each backing store's way to stop its sync lane, by local id. */\n retireHandlersByLocalId: Map<string, () => void>;\n /**\n * Stores whose document was removed under them, each with whether its\n * removal still holds; see retireDocumentStore.\n */\n retiredStores: Map<string, () => boolean>;\n storeKeysByDocumentId: Map<string, string>;\n storeKeysByLocalId: Map<string, string>;\n storesByKey: Map<string, DocumentStoreFacade>;\n}\n\nconst documentStoreRegistriesByScope = new WeakMap<\n DomainScope,\n DocumentStoreRegistry\n>();\ntype PersistedDocumentDeletionListener = (localId: string) => void;\n\n// Per-scope listener plumbing shared by the persisted-document and\n// persisted-document-deletion channels: emit fans out to the scope's\n// listeners, and unsubscribing the last listener drops the scope entry.\nfunction createScopedListenerRegistry<\n Listener extends (...args: never[]) => void,\n>() {\n const listenersByScope = new WeakMap<DomainScope, Set<Listener>>();\n\n return {\n emit: (domainScope: DomainScope, ...args: Parameters<Listener>): void => {\n const listeners = listenersByScope.get(domainScope);\n if (!listeners) {\n return;\n }\n\n for (const listener of listeners) {\n listener(...args);\n }\n },\n subscribe: (domainScope: DomainScope, listener: Listener): (() => void) => {\n const listeners =\n listenersByScope.get(domainScope) ?? new Set<Listener>();\n listeners.add(listener);\n listenersByScope.set(domainScope, listeners);\n\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n listenersByScope.delete(domainScope);\n }\n };\n },\n };\n}\n\nconst persistedDocumentListeners =\n createScopedListenerRegistry<PersistedDocumentListener>();\nconst persistedDocumentDeletionListeners =\n createScopedListenerRegistry<PersistedDocumentDeletionListener>();\n\nexport function getOrCreateDocumentStoreRegistry(\n domainScope: DomainScope,\n): DocumentStoreRegistry {\n const existingRegistry = documentStoreRegistriesByScope.get(domainScope);\n if (existingRegistry) {\n return existingRegistry;\n }\n\n const nextRegistry: DocumentStoreRegistry = {\n freshStoreFactories: new Map(),\n retireHandlersByLocalId: new Map(),\n retiredStores: new Map(),\n storeKeysByDocumentId: new Map(),\n storeKeysByLocalId: new Map(),\n storesByKey: new Map(),\n };\n documentStoreRegistriesByScope.set(domainScope, nextRegistry);\n return nextRegistry;\n}\n\nexport function resolveDocumentStoreKey(\n registry: DocumentStoreRegistry,\n localId: string,\n documentId: string | null,\n): string {\n return (\n (documentId ? registry.storeKeysByDocumentId.get(documentId) : undefined) ??\n registry.storeKeysByLocalId.get(localId) ??\n localId\n );\n}\n\nexport function registerDocumentStore(\n domainScope: DomainScope,\n localId: string,\n store: DocumentStoreFacade,\n documentId: string | null,\n) {\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const storeKey = resolveDocumentStoreKey(registry, localId, documentId);\n registry.storeKeysByLocalId.set(localId, storeKey);\n if (documentId) {\n registry.storeKeysByDocumentId.set(documentId, storeKey);\n }\n registry.storesByKey.set(storeKey, store);\n}\n\nexport function registerDocumentStoreIdentity(\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n) {\n if (!documentId) {\n return;\n }\n\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const localStoreKey = registry.storeKeysByLocalId.get(localId) ?? localId;\n const documentStoreKey =\n registry.storeKeysByDocumentId.get(documentId) ?? documentId;\n\n registry.storeKeysByLocalId.set(localId, documentStoreKey);\n registry.storeKeysByDocumentId.set(documentId, documentStoreKey);\n\n if (documentStoreKey === localStoreKey) {\n return;\n }\n\n const localStore = registry.storesByKey.get(localStoreKey);\n const documentStore = registry.storesByKey.get(documentStoreKey);\n if (localStore) {\n documentStore?.rebindTo(localStore);\n registry.storesByKey.set(documentStoreKey, localStore);\n // The store's retirement and how to rebuild it move with it.\n moveKeyedEntry(\n registry.freshStoreFactories,\n localStoreKey,\n documentStoreKey,\n );\n moveKeyedEntry(registry.retiredStores, localStoreKey, documentStoreKey);\n }\n registry.storesByKey.delete(localStoreKey);\n}\n\nfunction moveKeyedEntry<Value>(\n entries: Map<string, Value>,\n fromKey: string,\n toKey: string,\n): void {\n const value = entries.get(fromKey);\n entries.delete(fromKey);\n if (value !== undefined) entries.set(toKey, value);\n}\n\n/**\n * Whether an open store holds local writes for the document that have not\n * reached SQLite yet, which no persisted-write scan can see.\n */\nexport function hasQueuedDocumentStoreWrites(\n domainScope: DomainScope,\n localId: string,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n return registry?.storesByKey.get(storeKey)?.hasQueuedWrites() ?? false;\n}\n\n/**\n * Whether any open store in `domainScope` holds local edits that have not\n * reached SQLite yet — queued writes, or applied edits whose save failed — so\n * a host can warn before an unload loses them. A retired store reads through\n * its removed stand-in, which holds none: the document it stood for is gone.\n */\nexport function hasPendingLocalDocumentWrites(\n domainScope: DomainScope,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) return false;\n for (const store of registry.storesByKey.values()) {\n if (store.hasQueuedWrites() || store.hasUnsavedLocalEdits()) return true;\n }\n return false;\n}\n\nexport function requestDocumentStoreSync(state: {\n syncLane: {\n requestSync: () => void;\n } | null;\n}) {\n state.syncLane?.requestSync();\n}\n\nexport function requestRegisteredDocumentRemoteSync(\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return false;\n }\n\n const storeKey = resolveDocumentStoreKey(registry, localId, documentId);\n const store = registry.storesByKey.get(storeKey);\n if (!store || registry.retiredStores.has(storeKey)) {\n return false;\n }\n\n // Explicit refresh uses this path to recover missed websocket invalidations\n // without instantiating every unopened document discovered in the container.\n store.requestRemoteSync();\n return true;\n}\n\n/**\n * Discard a registered document's local edits through its store, so the\n * teardown serializes on the store's write machinery instead of racing an\n * in-flight persist that would resurrect the deleted rows. Only registered\n * stores qualify — an unregistered document has no lane submitting its queue,\n * so there is nothing this escape hatch could unstick. No deletion is\n * emitted: the document survives as a re-seeded shell that keeps its listing\n * entry, and the re-pull's own persist announces the restored content.\n *\n * Resolution is strict, unlike the read-side lookups: a destructive action\n * must never run against whichever store won a lookup priority. Both\n * identifiers must map to the SAME registered store — an unknown or stale\n * documentId refuses rather than trusting the localId alone — and the store\n * revalidates the expected documentId against its persisted record inside\n * the teardown's serialized mutation, so even a stale registry mapping\n * cannot discard a different identity's edits.\n */\nexport async function discardRegisteredDocumentLocalState(\n domainScope: DomainScope,\n localId: string,\n documentId: string,\n): Promise<boolean> {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return false;\n }\n\n const localStoreKey = registry.storeKeysByLocalId.get(localId);\n const documentStoreKey = registry.storeKeysByDocumentId.get(documentId);\n if (\n !localStoreKey ||\n !documentStoreKey ||\n documentStoreKey !== localStoreKey\n ) {\n return false;\n }\n const store = registry.storesByKey.get(localStoreKey);\n if (!store) {\n return false;\n }\n\n return store.discardLocalState(documentId);\n}\n\nexport function createDocumentStoreFacade(\n initialStore: DocumentStore,\n): DocumentStoreFacade {\n let targetStore = initialStore;\n const listeners = new Set<() => void>();\n\n const emitFacade = () => {\n for (const listener of listeners) {\n listener();\n }\n };\n\n let unsubscribeTarget = targetStore.subscribe(() => {\n emitFacade();\n });\n\n const connectTarget = (nextStore: DocumentStore) => {\n if (targetStore === nextStore) {\n return;\n }\n\n unsubscribeTarget();\n targetStore = nextStore;\n unsubscribeTarget = targetStore.subscribe(() => {\n emitFacade();\n });\n emitFacade();\n };\n\n const facade: DocumentStoreFacade = {\n addRow: (fields, options) => targetStore.addRow(fields, options),\n assertCanRotateContentKey: (proof) =>\n targetStore.assertCanRotateContentKey(proof),\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) =>\n targetStore.attachFiles(files),\n discardLocalState: (expectedDocumentId: string) =>\n targetStore.discardLocalState(expectedDocumentId),\n ensureInitialized: () => targetStore.ensureInitialized(),\n getSnapshot: () => targetStore.getSnapshot(),\n hasQueuedWrites: () => targetStore.hasQueuedWrites(),\n hasUnsavedLocalEdits: () => targetStore.hasUnsavedLocalEdits(),\n removeAttachment: (slotId: string) => targetStore.removeAttachment(slotId),\n removeRow: (id, options) => targetStore.removeRow(id, options),\n replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) =>\n targetStore.replaceAttachment(slotId, file),\n requestRemoteSync: () => targetStore.requestRemoteSync(),\n requestRemoteSyncAndWait: (signal) =>\n targetStore.requestRemoteSyncAndWait(signal),\n requestSync: () => targetStore.requestSync(),\n relink: (input) => targetStore.relink(input),\n rebindTo: (store) => connectTarget(store),\n setStructuredFields: (kind, patch, options) =>\n targetStore.setStructuredFields(kind, patch, options),\n setText: (value: string) => targetStore.setText(value),\n subscribe: (listener: () => void) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n updateRowFields: (id, patch, options) =>\n targetStore.updateRowFields(id, patch, options),\n updateRuntime: (runtime: DocumentsRuntime) =>\n targetStore.updateRuntime(runtime),\n };\n registerInternalDocumentRelink(facade, (input, commitSideEffect) =>\n relinkDocumentStoreWithCommitSideEffect(\n targetStore,\n input,\n commitSideEffect,\n ),\n );\n return facade;\n}\n\nexport function emitPersistedDocument(\n domainScope: DomainScope,\n persistedDocument: Parameters<PersistedDocumentListener>[0],\n placementChanged = false,\n): void {\n persistedDocumentListeners.emit(domainScope, persistedDocument, {\n placementChanged,\n });\n}\n\nexport function subscribeToPersistedDocuments(\n domainScope: DomainScope,\n listener: PersistedDocumentListener,\n): () => void {\n return persistedDocumentListeners.subscribe(domainScope, listener);\n}\n\nexport function emitPersistedDocumentDeletion(\n domainScope: DomainScope,\n localId: string,\n): void {\n persistedDocumentDeletionListeners.emit(domainScope, localId);\n}\n\nexport function subscribeToPersistedDocumentDeletions(\n domainScope: DomainScope,\n listener: PersistedDocumentDeletionListener,\n): () => void {\n return persistedDocumentDeletionListeners.subscribe(domainScope, listener);\n}\n\nexport function requestDomainDocumentSync(domainScope: DomainScope): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return;\n }\n\n for (const [storeKey, store] of registry.storesByKey) {\n if (!registry.retiredStores.has(storeKey)) store.requestSync();\n }\n}\n\n/** Lets the backing store for `localId` stop its sync lane when retired. */\nexport function onDocumentStoreRetired(\n domainScope: DomainScope,\n localId: string,\n stopSyncLane: () => void,\n): void {\n getOrCreateDocumentStoreRegistry(domainScope).retireHandlersByLocalId.set(\n localId,\n stopSyncLane,\n );\n}\n\n/**\n * Retires the store of a document a paused organization's cleanup removed.\n * Its backing store's sync lane stops and the facade an editor may hold\n * switches to a read-only stand-in, so nothing recreates or downloads the\n * document. While `stillRemoved()` holds, reopening returns the stand-in;\n * after that, the next open rebinds the facade to a fresh backing store that\n * loads whatever SQLite holds by then, such as a copy rediscovered on resume.\n */\nexport function retireDocumentStore(\n domainScope: DomainScope,\n localId: string,\n stillRemoved: () => boolean,\n): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n const store = registry?.storesByKey.get(storeKey);\n if (!registry || !store || registry.retiredStores.has(storeKey)) return;\n registry.retireHandlersByLocalId.get(localId)?.();\n store.rebindTo(createRemovedDocumentStore(store.getSnapshot()));\n registry.retiredStores.set(storeKey, stillRemoved);\n}\n\n/**\n * Undoes a retirement whose deletion did not commit: the document survives,\n * so its facade gets a fresh backing store again.\n */\nexport function restoreDocumentStore(\n domainScope: DomainScope,\n localId: string,\n): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n const store = registry?.storesByKey.get(storeKey);\n if (!registry || !store || !registry.retiredStores.delete(storeKey)) return;\n const createFresh = registry.freshStoreFactories.get(storeKey);\n // Without a factory the next open rebinds it instead.\n if (createFresh) store.rebindTo(createFresh());\n else registry.retiredStores.set(storeKey, () => false);\n}\n\n/** The registered store for a key, rebound once its removal has lifted. */\nexport function takeRegisteredDocumentStore(\n registry: DocumentStoreRegistry,\n storeKey: string,\n createFresh: () => DocumentStore,\n): DocumentStoreFacade | undefined {\n registry.freshStoreFactories.set(storeKey, createFresh);\n const store = registry.storesByKey.get(storeKey);\n const stillRemoved = registry.retiredStores.get(storeKey);\n if (store && stillRemoved && !stillRemoved()) {\n registry.retiredStores.delete(storeKey);\n store.rebindTo(createFresh());\n }\n return store;\n}\n"]}
1
+ {"version":3,"file":"registry.js","sourceRoot":"","sources":["registry.ts"],"names":[],"mappings":"AACA,OAAO,EACL,8BAA8B,EAC9B,uCAAuC,GACxC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AAwBpE,MAAM,8BAA8B,GAAG,IAAI,OAAO,EAG/C,CAAC;AAGJ,mEAAmE;AACnE,qEAAqE;AACrE,wEAAwE;AACxE,SAAS,4BAA4B;IAGnC,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAA8B,CAAC;IAEnE,OAAO;QACL,IAAI,EAAE,CAAC,WAAwB,EAAE,GAAG,IAA0B,EAAQ,EAAE;YACtE,MAAM,SAAS,GAAG,gBAAgB,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;YACpD,IAAI,CAAC,SAAS,EAAE,CAAC;gBACf,OAAO;YACT,CAAC;YAED,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;gBACjC,QAAQ,CAAC,GAAG,IAAI,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;QACD,SAAS,EAAE,CAAC,WAAwB,EAAE,QAAkB,EAA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AgB,EAChB,WAAgC;IAEhC,QAAQ,CAAC,mBAAmB,CAAC,GAAG,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;IACxD,MAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACjD,MAAM,YAAY,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC1D,IAAI,KAAK,IAAI,YAAY,IAAI,CAAC,YAAY,EAAE,EAAE,CAAC;QAC7C,QAAQ,CAAC,aAAa,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACxC,KAAK,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n registerInternalDocumentRelink,\n relinkDocumentStoreWithCommitSideEffect,\n} from \"./documentStore/internalRelink\";\nimport { createRemovedDocumentStore } from \"./removedDocumentStore\";\nimport type {\n DocumentAttachmentUpload,\n DocumentStore,\n DocumentStoreFacade,\n DocumentsRuntime,\n PersistedDocumentListener,\n} from \"./types\";\n\ninterface DocumentStoreRegistry {\n /** How the last open built each store's backing store, by store key. */\n freshStoreFactories: Map<string, () => DocumentStore>;\n /** Each backing store's way to stop its sync lane, by local id. */\n retireHandlersByLocalId: Map<string, () => void>;\n /**\n * Stores whose document was removed under them, each with whether its\n * removal still holds; see retireDocumentStore.\n */\n retiredStores: Map<string, () => boolean>;\n storeKeysByDocumentId: Map<string, string>;\n storeKeysByLocalId: Map<string, string>;\n storesByKey: Map<string, DocumentStoreFacade>;\n}\n\nconst documentStoreRegistriesByScope = new WeakMap<\n DomainScope,\n DocumentStoreRegistry\n>();\ntype PersistedDocumentDeletionListener = (localId: string) => void;\n\n// Per-scope listener plumbing shared by the persisted-document and\n// persisted-document-deletion channels: emit fans out to the scope's\n// listeners, and unsubscribing the last listener drops the scope entry.\nfunction createScopedListenerRegistry<\n Listener extends (...args: never[]) => void,\n>() {\n const listenersByScope = new WeakMap<DomainScope, Set<Listener>>();\n\n return {\n emit: (domainScope: DomainScope, ...args: Parameters<Listener>): void => {\n const listeners = listenersByScope.get(domainScope);\n if (!listeners) {\n return;\n }\n\n for (const listener of listeners) {\n listener(...args);\n }\n },\n subscribe: (domainScope: DomainScope, listener: Listener): (() => void) => {\n const listeners =\n listenersByScope.get(domainScope) ?? new Set<Listener>();\n listeners.add(listener);\n listenersByScope.set(domainScope, listeners);\n\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n listenersByScope.delete(domainScope);\n }\n };\n },\n };\n}\n\nconst persistedDocumentListeners =\n createScopedListenerRegistry<PersistedDocumentListener>();\nconst persistedDocumentDeletionListeners =\n createScopedListenerRegistry<PersistedDocumentDeletionListener>();\n\nexport function getOrCreateDocumentStoreRegistry(\n domainScope: DomainScope,\n): DocumentStoreRegistry {\n const existingRegistry = documentStoreRegistriesByScope.get(domainScope);\n if (existingRegistry) {\n return existingRegistry;\n }\n\n const nextRegistry: DocumentStoreRegistry = {\n freshStoreFactories: new Map(),\n retireHandlersByLocalId: new Map(),\n retiredStores: new Map(),\n storeKeysByDocumentId: new Map(),\n storeKeysByLocalId: new Map(),\n storesByKey: new Map(),\n };\n documentStoreRegistriesByScope.set(domainScope, nextRegistry);\n return nextRegistry;\n}\n\nexport function resolveDocumentStoreKey(\n registry: DocumentStoreRegistry,\n localId: string,\n documentId: string | null,\n): string {\n return (\n (documentId ? registry.storeKeysByDocumentId.get(documentId) : undefined) ??\n registry.storeKeysByLocalId.get(localId) ??\n localId\n );\n}\n\nexport function registerDocumentStore(\n domainScope: DomainScope,\n localId: string,\n store: DocumentStoreFacade,\n documentId: string | null,\n) {\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const storeKey = resolveDocumentStoreKey(registry, localId, documentId);\n registry.storeKeysByLocalId.set(localId, storeKey);\n if (documentId) {\n registry.storeKeysByDocumentId.set(documentId, storeKey);\n }\n registry.storesByKey.set(storeKey, store);\n}\n\nexport function registerDocumentStoreIdentity(\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n) {\n if (!documentId) {\n return;\n }\n\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const localStoreKey = registry.storeKeysByLocalId.get(localId) ?? localId;\n const documentStoreKey =\n registry.storeKeysByDocumentId.get(documentId) ?? documentId;\n\n registry.storeKeysByLocalId.set(localId, documentStoreKey);\n registry.storeKeysByDocumentId.set(documentId, documentStoreKey);\n\n if (documentStoreKey === localStoreKey) {\n return;\n }\n\n const localStore = registry.storesByKey.get(localStoreKey);\n const documentStore = registry.storesByKey.get(documentStoreKey);\n if (localStore) {\n documentStore?.rebindTo(localStore);\n registry.storesByKey.set(documentStoreKey, localStore);\n // The store's retirement and how to rebuild it move with it.\n moveKeyedEntry(\n registry.freshStoreFactories,\n localStoreKey,\n documentStoreKey,\n );\n moveKeyedEntry(registry.retiredStores, localStoreKey, documentStoreKey);\n }\n registry.storesByKey.delete(localStoreKey);\n}\n\nfunction moveKeyedEntry<Value>(\n entries: Map<string, Value>,\n fromKey: string,\n toKey: string,\n): void {\n const value = entries.get(fromKey);\n entries.delete(fromKey);\n if (value !== undefined) entries.set(toKey, value);\n}\n\n/**\n * Whether an open store holds local writes for the document that have not\n * reached SQLite yet, which no persisted-write scan can see.\n */\nexport function hasQueuedDocumentStoreWrites(\n domainScope: DomainScope,\n localId: string,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n return registry?.storesByKey.get(storeKey)?.hasQueuedWrites() ?? false;\n}\n\n/**\n * Whether any open store in `domainScope` holds local edits that have not\n * reached SQLite yet — queued writes, or applied edits whose save failed — so\n * a host can warn before an unload loses them. A retired store reads through\n * its removed stand-in, which holds none: the document it stood for is gone.\n */\nexport function hasPendingLocalDocumentWrites(\n domainScope: DomainScope,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) return false;\n for (const store of registry.storesByKey.values()) {\n if (store.hasQueuedWrites() || store.hasUnsavedLocalEdits()) return true;\n }\n return false;\n}\n\nexport function requestDocumentStoreSync(state: {\n syncLane: {\n requestSync: () => void;\n } | null;\n}) {\n state.syncLane?.requestSync();\n}\n\nexport function requestRegisteredDocumentRemoteSync(\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n): boolean {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return false;\n }\n\n const storeKey = resolveDocumentStoreKey(registry, localId, documentId);\n const store = registry.storesByKey.get(storeKey);\n if (!store || registry.retiredStores.has(storeKey)) {\n return false;\n }\n\n // Explicit refresh uses this path to recover missed websocket invalidations\n // without instantiating every unopened document discovered in the container.\n store.requestRemoteSync();\n return true;\n}\n\n/**\n * Discard a registered document's local edits through its store, so the\n * teardown serializes on the store's write machinery instead of racing an\n * in-flight persist that would resurrect the deleted rows. Only registered\n * stores qualify — an unregistered document has no lane submitting its queue,\n * so there is nothing this escape hatch could unstick. No deletion is\n * emitted: the document survives as a re-seeded shell that keeps its listing\n * entry, and the re-pull's own persist announces the restored content.\n *\n * Resolution is strict, unlike the read-side lookups: a destructive action\n * must never run against whichever store won a lookup priority. Both\n * identifiers must map to the SAME registered store — an unknown or stale\n * documentId refuses rather than trusting the localId alone — and the store\n * revalidates the expected documentId against its persisted record inside\n * the teardown's serialized mutation, so even a stale registry mapping\n * cannot discard a different identity's edits.\n */\nexport async function discardRegisteredDocumentLocalState(\n domainScope: DomainScope,\n localId: string,\n documentId: string,\n): Promise<boolean> {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return false;\n }\n\n const localStoreKey = registry.storeKeysByLocalId.get(localId);\n const documentStoreKey = registry.storeKeysByDocumentId.get(documentId);\n if (\n !localStoreKey ||\n !documentStoreKey ||\n documentStoreKey !== localStoreKey\n ) {\n return false;\n }\n const store = registry.storesByKey.get(localStoreKey);\n if (!store) {\n return false;\n }\n\n return store.discardLocalState(documentId);\n}\n\nexport function createDocumentStoreFacade(\n initialStore: DocumentStore,\n): DocumentStoreFacade {\n let targetStore = initialStore;\n const listeners = new Set<() => void>();\n\n const emitFacade = () => {\n for (const listener of listeners) {\n listener();\n }\n };\n\n let unsubscribeTarget = targetStore.subscribe(() => {\n emitFacade();\n });\n\n const connectTarget = (nextStore: DocumentStore) => {\n if (targetStore === nextStore) {\n return;\n }\n\n unsubscribeTarget();\n targetStore = nextStore;\n unsubscribeTarget = targetStore.subscribe(() => {\n emitFacade();\n });\n emitFacade();\n };\n\n const facade: DocumentStoreFacade = {\n addRow: (fields, options) => targetStore.addRow(fields, options),\n assertCanRotateContentKey: (proof) =>\n targetStore.assertCanRotateContentKey(proof),\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) =>\n targetStore.attachFiles(files),\n discardLocalState: (expectedDocumentId: string) =>\n targetStore.discardLocalState(expectedDocumentId),\n ensureInitialized: () => targetStore.ensureInitialized(),\n getSnapshot: () => targetStore.getSnapshot(),\n hasQueuedWrites: () => targetStore.hasQueuedWrites(),\n hasUnsavedLocalEdits: () => targetStore.hasUnsavedLocalEdits(),\n removeAttachment: (slotId: string) => targetStore.removeAttachment(slotId),\n removeRow: (id, options) => targetStore.removeRow(id, options),\n replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) =>\n targetStore.replaceAttachment(slotId, file),\n requestRemoteSync: () => targetStore.requestRemoteSync(),\n requestRemoteSyncAndWait: (signal) =>\n targetStore.requestRemoteSyncAndWait(signal),\n requestSync: () => targetStore.requestSync(),\n relink: (input) => targetStore.relink(input),\n rebindTo: (store) => connectTarget(store),\n restoreContent: (content, options) =>\n targetStore.restoreContent(content, options),\n setStructuredFields: (kind, patch, options) =>\n targetStore.setStructuredFields(kind, patch, options),\n setText: (value: string) => targetStore.setText(value),\n subscribe: (listener: () => void) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n updateRowFields: (id, patch, options) =>\n targetStore.updateRowFields(id, patch, options),\n updateRuntime: (runtime: DocumentsRuntime) =>\n targetStore.updateRuntime(runtime),\n };\n registerInternalDocumentRelink(facade, (input, commitSideEffect) =>\n relinkDocumentStoreWithCommitSideEffect(\n targetStore,\n input,\n commitSideEffect,\n ),\n );\n return facade;\n}\n\nexport function emitPersistedDocument(\n domainScope: DomainScope,\n persistedDocument: Parameters<PersistedDocumentListener>[0],\n placementChanged = false,\n): void {\n persistedDocumentListeners.emit(domainScope, persistedDocument, {\n placementChanged,\n });\n}\n\nexport function subscribeToPersistedDocuments(\n domainScope: DomainScope,\n listener: PersistedDocumentListener,\n): () => void {\n return persistedDocumentListeners.subscribe(domainScope, listener);\n}\n\nexport function emitPersistedDocumentDeletion(\n domainScope: DomainScope,\n localId: string,\n): void {\n persistedDocumentDeletionListeners.emit(domainScope, localId);\n}\n\nexport function subscribeToPersistedDocumentDeletions(\n domainScope: DomainScope,\n listener: PersistedDocumentDeletionListener,\n): () => void {\n return persistedDocumentDeletionListeners.subscribe(domainScope, listener);\n}\n\nexport function requestDomainDocumentSync(domainScope: DomainScope): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n if (!registry) {\n return;\n }\n\n for (const [storeKey, store] of registry.storesByKey) {\n if (!registry.retiredStores.has(storeKey)) store.requestSync();\n }\n}\n\n/** Lets the backing store for `localId` stop its sync lane when retired. */\nexport function onDocumentStoreRetired(\n domainScope: DomainScope,\n localId: string,\n stopSyncLane: () => void,\n): void {\n getOrCreateDocumentStoreRegistry(domainScope).retireHandlersByLocalId.set(\n localId,\n stopSyncLane,\n );\n}\n\n/**\n * Retires the store of a document a paused organization's cleanup removed.\n * Its backing store's sync lane stops and the facade an editor may hold\n * switches to a read-only stand-in, so nothing recreates or downloads the\n * document. While `stillRemoved()` holds, reopening returns the stand-in;\n * after that, the next open rebinds the facade to a fresh backing store that\n * loads whatever SQLite holds by then, such as a copy rediscovered on resume.\n */\nexport function retireDocumentStore(\n domainScope: DomainScope,\n localId: string,\n stillRemoved: () => boolean,\n): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n const store = registry?.storesByKey.get(storeKey);\n if (!registry || !store || registry.retiredStores.has(storeKey)) return;\n registry.retireHandlersByLocalId.get(localId)?.();\n store.rebindTo(createRemovedDocumentStore(store.getSnapshot()));\n registry.retiredStores.set(storeKey, stillRemoved);\n}\n\n/**\n * Undoes a retirement whose deletion did not commit: the document survives,\n * so its facade gets a fresh backing store again.\n */\nexport function restoreDocumentStore(\n domainScope: DomainScope,\n localId: string,\n): void {\n const registry = documentStoreRegistriesByScope.get(domainScope);\n const storeKey = registry?.storeKeysByLocalId.get(localId) ?? localId;\n const store = registry?.storesByKey.get(storeKey);\n if (!registry || !store || !registry.retiredStores.delete(storeKey)) return;\n const createFresh = registry.freshStoreFactories.get(storeKey);\n // Without a factory the next open rebinds it instead.\n if (createFresh) store.rebindTo(createFresh());\n else registry.retiredStores.set(storeKey, () => false);\n}\n\n/** The registered store for a key, rebound once its removal has lifted. */\nexport function takeRegisteredDocumentStore(\n registry: DocumentStoreRegistry,\n storeKey: string,\n createFresh: () => DocumentStore,\n): DocumentStoreFacade | undefined {\n registry.freshStoreFactories.set(storeKey, createFresh);\n const store = registry.storesByKey.get(storeKey);\n const stillRemoved = registry.retiredStores.get(storeKey);\n if (store && stillRemoved && !stillRemoved()) {\n registry.retiredStores.delete(storeKey);\n store.rebindTo(createFresh());\n }\n return store;\n}\n"]}
@@ -29,6 +29,7 @@ export function createRemovedDocumentStore(lastSnapshot) {
29
29
  requestRemoteSyncAndWait: async () => false,
30
30
  requestSync: () => undefined,
31
31
  relink: async () => null,
32
+ restoreContent: async () => false,
32
33
  setStructuredFields: refuse,
33
34
  setText: refuse,
34
35
  subscribe: () => () => undefined,
@@ -1 +1 @@
1
- {"version":3,"file":"removedDocumentStore.js","sourceRoot":"","sources":["removedDocumentStore.ts"],"names":[],"mappings":"AAEA,MAAM,wBAAwB,GAC5B,mEAAmE,CAAC;AAEtE;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACxC,YAA8B;IAE9B,MAAM,QAAQ,GAAqB;QACjC,GAAG,YAAY;QACf,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,KAAK;QACf,OAAO,EAAE,KAAK;KACf,CAAC;IACF,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC,CAAC;IACzE,OAAO;QACL,MAAM,EAAE,MAAM;QACd,yBAAyB,EAAE,MAAM;QACjC,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;QAC5B,iBAAiB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACpC,iBAAiB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACpC,WAAW,EAAE,GAAG,EAAE,CAAC,QAAQ;QAC3B,eAAe,EAAE,GAAG,EAAE,CAAC,KAAK;QAC5B,oBAAoB,EAAE,GAAG,EAAE,CAAC,KAAK;QACjC,gBAAgB,EAAE,GAAG,EAAE,CAAC,SAAS;QACjC,SAAS,EAAE,MAAM;QACjB,iBAAiB,EAAE,MAAM;QACzB,iBAAiB,EAAE,GAAG,EAAE,CAAC,SAAS;QAClC,wBAAwB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QAC3C,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;QAC5B,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,IAAI;QACxB,mBAAmB,EAAE,MAAM;QAC3B,OAAO,EAAE,MAAM;QACf,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,SAAS;QAChC,eAAe,EAAE,MAAM;QACvB,aAAa,EAAE,GAAG,EAAE,CAAC,SAAS;KAC/B,CAAC;AACJ,CAAC","sourcesContent":["import type { DocumentSnapshot, DocumentStore } from \"./types\";\n\nconst REMOVED_DOCUMENT_MESSAGE =\n \"This document was removed while its organization's sync is paused\";\n\n/**\n * Stands in for a store whose document a paused organization's cleanup\n * removed. It keeps showing the last snapshot, read-only, and does nothing\n * else, so an open editor neither recreates the document nor downloads it\n * while the pause lasts.\n */\nexport function createRemovedDocumentStore(\n lastSnapshot: DocumentSnapshot,\n): DocumentStore {\n const snapshot: DocumentSnapshot = {\n ...lastSnapshot,\n canAttach: false,\n canWrite: false,\n syncing: false,\n };\n const refuse = () => Promise.reject(new Error(REMOVED_DOCUMENT_MESSAGE));\n return {\n addRow: refuse,\n assertCanRotateContentKey: refuse,\n attachFiles: () => undefined,\n discardLocalState: async () => false,\n ensureInitialized: async () => false,\n getSnapshot: () => snapshot,\n hasQueuedWrites: () => false,\n hasUnsavedLocalEdits: () => false,\n removeAttachment: () => undefined,\n removeRow: refuse,\n replaceAttachment: refuse,\n requestRemoteSync: () => undefined,\n requestRemoteSyncAndWait: async () => false,\n requestSync: () => undefined,\n relink: async () => null,\n setStructuredFields: refuse,\n setText: refuse,\n subscribe: () => () => undefined,\n updateRowFields: refuse,\n updateRuntime: () => undefined,\n };\n}\n"]}
1
+ {"version":3,"file":"removedDocumentStore.js","sourceRoot":"","sources":["removedDocumentStore.ts"],"names":[],"mappings":"AAEA,MAAM,wBAAwB,GAC5B,mEAAmE,CAAC;AAEtE;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACxC,YAA8B;IAE9B,MAAM,QAAQ,GAAqB;QACjC,GAAG,YAAY;QACf,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,KAAK;QACf,OAAO,EAAE,KAAK;KACf,CAAC;IACF,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC,CAAC;IACzE,OAAO;QACL,MAAM,EAAE,MAAM;QACd,yBAAyB,EAAE,MAAM;QACjC,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;QAC5B,iBAAiB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACpC,iBAAiB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACpC,WAAW,EAAE,GAAG,EAAE,CAAC,QAAQ;QAC3B,eAAe,EAAE,GAAG,EAAE,CAAC,KAAK;QAC5B,oBAAoB,EAAE,GAAG,EAAE,CAAC,KAAK;QACjC,gBAAgB,EAAE,GAAG,EAAE,CAAC,SAAS;QACjC,SAAS,EAAE,MAAM;QACjB,iBAAiB,EAAE,MAAM;QACzB,iBAAiB,EAAE,GAAG,EAAE,CAAC,SAAS;QAClC,wBAAwB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QAC3C,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;QAC5B,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,IAAI;QACxB,cAAc,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACjC,mBAAmB,EAAE,MAAM;QAC3B,OAAO,EAAE,MAAM;QACf,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,SAAS;QAChC,eAAe,EAAE,MAAM;QACvB,aAAa,EAAE,GAAG,EAAE,CAAC,SAAS;KAC/B,CAAC;AACJ,CAAC","sourcesContent":["import type { DocumentSnapshot, DocumentStore } from \"./types\";\n\nconst REMOVED_DOCUMENT_MESSAGE =\n \"This document was removed while its organization's sync is paused\";\n\n/**\n * Stands in for a store whose document a paused organization's cleanup\n * removed. It keeps showing the last snapshot, read-only, and does nothing\n * else, so an open editor neither recreates the document nor downloads it\n * while the pause lasts.\n */\nexport function createRemovedDocumentStore(\n lastSnapshot: DocumentSnapshot,\n): DocumentStore {\n const snapshot: DocumentSnapshot = {\n ...lastSnapshot,\n canAttach: false,\n canWrite: false,\n syncing: false,\n };\n const refuse = () => Promise.reject(new Error(REMOVED_DOCUMENT_MESSAGE));\n return {\n addRow: refuse,\n assertCanRotateContentKey: refuse,\n attachFiles: () => undefined,\n discardLocalState: async () => false,\n ensureInitialized: async () => false,\n getSnapshot: () => snapshot,\n hasQueuedWrites: () => false,\n hasUnsavedLocalEdits: () => false,\n removeAttachment: () => undefined,\n removeRow: refuse,\n replaceAttachment: refuse,\n requestRemoteSync: () => undefined,\n requestRemoteSyncAndWait: async () => false,\n requestSync: () => undefined,\n relink: async () => null,\n restoreContent: async () => false,\n setStructuredFields: refuse,\n setText: refuse,\n subscribe: () => () => undefined,\n updateRowFields: refuse,\n updateRuntime: () => undefined,\n };\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import type { ContainerAccessLevel } from "../../internal/crypto/index.js";
2
2
  import type { DocumentAttachment } from "../../data/documents/documentContent.js";
3
3
  import type { DocumentFieldValidationIssue, StoredDocumentKind } from "../../data/documents/documentKinds.js";
4
+ import type { DocumentRestoreContent } from "../../data/documents/documentRestore.js";
4
5
  import type { DocumentRow } from "../../data/documents/documentRowList.js";
5
6
  import type { DocumentSummary } from "../../data/documents/documentSummary.js";
6
7
  import type { BlobByteSourceInput } from "../../workflows/blobs/index.js";
@@ -46,7 +47,7 @@ export type DocumentAttachmentStatus = "syncing" | "intent-mismatch";
46
47
  export type AddDocumentRow = (fields: Readonly<Record<string, string>>, options?: DocumentMutationGuard | undefined) => Promise<string>;
47
48
  export type UpdateDocumentRowFields = (id: string, patch: Readonly<Record<string, string>>, options?: DocumentMutationGuard | undefined) => Promise<void>;
48
49
  export type RemoveDocumentRow = (id: string, options?: DocumentMutationGuard | undefined) => Promise<void>;
49
- export type DocumentContextValue = DocumentSnapshot & Pick<DocumentStore, "addRow" | "attachFiles" | "relink" | "removeAttachment" | "removeRow" | "replaceAttachment" | "requestSync" | "setStructuredFields" | "setText" | "updateRowFields">;
50
+ export type DocumentContextValue = DocumentSnapshot & Pick<DocumentStore, "addRow" | "attachFiles" | "relink" | "removeAttachment" | "removeRow" | "replaceAttachment" | "requestSync" | "restoreContent" | "setStructuredFields" | "setText" | "updateRowFields">;
50
51
  export interface DocumentSnapshot {
51
52
  attachments: ReadonlyArray<DocumentAttachment>;
52
53
  attachmentStatusBySlotId: Readonly<Record<string, DocumentAttachmentStatus>>;
@@ -92,6 +93,14 @@ export interface DocumentStore {
92
93
  removeAttachment: (slotId: string) => void;
93
94
  removeRow: RemoveDocumentRow;
94
95
  replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) => Promise<void>;
96
+ /**
97
+ * Write a past version's text, structured fields, and rows back as one
98
+ * ordinary local edit; attachments are left as they are. Nothing is rewound:
99
+ * the restore is new operations that sync and merge like any other write.
100
+ * Resolves true when the document durably holds the content, false when
101
+ * the restore was refused or did not persist.
102
+ */
103
+ restoreContent: (content: DocumentRestoreContent, options?: DocumentMutationGuard | undefined) => Promise<boolean>;
95
104
  /** Pull remote document updates even when no websocket event marked it dirty. */
96
105
  requestRemoteSync: () => void;
97
106
  /** Pull remote updates and report whether the requested sync pass completed. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAeA,MAAM,CAAC,MAAM,mBAAmB,GAAG,SAAS,CAAC","sourcesContent":["import type { ContainerAccessLevel } from \"@tearleads/crypto\";\nimport type { DocumentAttachment } from \"../../data/documents/documentContent\";\nimport type {\n DocumentFieldValidationIssue,\n StoredDocumentKind,\n} from \"../../data/documents/documentKinds\";\nimport type { DocumentRow } from \"../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type { BlobByteSourceInput } from \"../../workflows/blobs\";\nimport type {\n DocumentRotationProofMode,\n DocumentsWorkflowRuntime,\n RelinkPersistedDocumentInput,\n} from \"../../workflows/documents\";\n\nexport const DEFAULT_DOCUMENT_ID = \"default\";\n\nexport type DocumentsRuntime = DocumentsWorkflowRuntime;\nexport type DocumentStructuredFieldPatch = Readonly<\n Record<string, string | undefined>\n>;\n\n/**\n * Host admission checked after readiness and again at local queue execution.\n * The predicate must be synchronous and side-effect-free. False is a no-op;\n * a throw is reported as a write failure and also refuses the mutation.\n * This does not cancel initialization or roll back an already admitted write.\n */\nexport interface DocumentMutationGuard {\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface DocumentMutationOptions extends DocumentMutationGuard {\n deferRemoteSync?: boolean | undefined;\n}\n\nexport interface DocumentStoreOpenOptions {\n /**\n * The caller attaches a file immediately after creating the document. The\n * birth commits locally without its own pending update, so the attach's\n * delta carries it; a failed attach enqueues the birth on its own.\n */\n deferInitialUpdate?: boolean | undefined;\n /**\n * Rows and structured fields a newly created record starts with. They are\n * written into its birth update with the initial kind and text, so a\n * document whose content is known up front queues one update. Fields need a\n * non-note `initialDocumentKind`. Both are ignored when the record exists.\n */\n initialRows?: ReadonlyArray<Readonly<Record<string, string>>> | undefined;\n initialStructuredFields?: DocumentStructuredFieldPatch | undefined;\n remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n}\n\nexport interface DocumentAttachmentUpload {\n bytes: BlobByteSourceInput;\n name: string;\n mimeType: string | null;\n}\n\n// `syncing`: the slot's upload is still queued. `intent-mismatch`: the held\n// bytes are a validly signed served binding whose digest differs from the one\n// the document content records (its content update has not arrived).\nexport type DocumentAttachmentStatus = \"syncing\" | \"intent-mismatch\";\n\n// Add a row to the document's repeated-row list, returning the new row id.\nexport type AddDocumentRow = (\n fields: Readonly<Record<string, string>>,\n options?: DocumentMutationGuard | undefined,\n) => Promise<string>;\n// Patch one or more cells of a single row (merges per-cell).\nexport type UpdateDocumentRowFields = (\n id: string,\n patch: Readonly<Record<string, string>>,\n options?: DocumentMutationGuard | undefined,\n) => Promise<void>;\nexport type RemoveDocumentRow = (\n id: string,\n options?: DocumentMutationGuard | undefined,\n) => Promise<void>;\n\n// The store surface exposed through context: the snapshot fields plus the\n// store's mutation methods, spelled as a Pick so the two can't drift.\nexport type DocumentContextValue = DocumentSnapshot &\n Pick<\n DocumentStore,\n | \"addRow\"\n | \"attachFiles\"\n | \"relink\"\n | \"removeAttachment\"\n | \"removeRow\"\n | \"replaceAttachment\"\n | \"requestSync\"\n | \"setStructuredFields\"\n | \"setText\"\n | \"updateRowFields\"\n >;\n\nexport interface DocumentSnapshot {\n attachments: ReadonlyArray<DocumentAttachment>;\n attachmentStatusBySlotId: Readonly<Record<string, DocumentAttachmentStatus>>;\n attachmentStorageKeyBySlotId: Readonly<Record<string, string>>;\n canAttach: boolean;\n canWrite: boolean;\n currentAuthorId: string | null;\n documentId: string | null;\n documentKind: StoredDocumentKind;\n effectiveAccessLevel: ContainerAccessLevel;\n fieldValidationIssues: ReadonlyArray<DocumentFieldValidationIssue>;\n ready: boolean;\n rows: ReadonlyArray<DocumentRow>;\n structuredFields: Readonly<Record<string, string>>;\n text: string;\n title: string;\n syncing: boolean;\n}\n\nexport interface DocumentStore {\n addRow: AddDocumentRow;\n /** Fail unless this store can produce a mergeable full-history checkpoint. */\n assertCanRotateContentKey: (\n proof: DocumentRotationProofMode,\n ) => Promise<Uint8Array>;\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) => void;\n /**\n * Convert this document's persisted local state to the discovered-share\n * shell so the store re-pulls the server copy — the escape hatch for\n * queued local writes that can no longer sync. `expectedDocumentId` is\n * revalidated against the persisted record inside the teardown's\n * serialized mutation, so a stale caller can never discard a different\n * identity's edits. Refuses (returns false) local-only, unlinked,\n * move-pending, and identity-mismatched documents.\n */\n discardLocalState: (expectedDocumentId: string) => Promise<boolean>;\n ensureInitialized: () => Promise<boolean>;\n getSnapshot: () => DocumentSnapshot;\n /** Whether local writes are queued that have not reached SQLite yet. */\n hasQueuedWrites: () => boolean;\n /**\n * Whether applied local edits have not reached SQLite, e.g. after a failed\n * save, even though no write is queued any more.\n */\n hasUnsavedLocalEdits: () => boolean;\n removeAttachment: (slotId: string) => void;\n removeRow: RemoveDocumentRow;\n replaceAttachment: (\n slotId: string,\n file: DocumentAttachmentUpload,\n ) => Promise<void>;\n /** Pull remote document updates even when no websocket event marked it dirty. */\n requestRemoteSync: () => void;\n /** Pull remote updates and report whether the requested sync pass completed. */\n requestRemoteSyncAndWait: (\n signal?: AbortSignal | undefined,\n ) => Promise<boolean>;\n requestSync: () => void;\n relink: (input: DocumentStoreRelinkInput) => Promise<DocumentSummary | null>;\n setStructuredFields: (\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options?: DocumentMutationOptions | undefined,\n ) => Promise<void>;\n setText: (value: string) => Promise<void>;\n subscribe: (listener: () => void) => () => void;\n updateRowFields: UpdateDocumentRowFields;\n updateRuntime: (runtime: DocumentsRuntime) => void;\n}\n\nexport interface DocumentStoreFacade extends DocumentStore {\n rebindTo: (store: DocumentStore) => void;\n}\n\nexport type PersistedDocumentListener = (\n document: DocumentSummary,\n change: { readonly placementChanged: boolean },\n) => void;\n\nexport interface DocumentStoreRelinkInput extends RelinkPersistedDocumentInput {\n contentKeyBundle?: string | null | undefined;\n documentKekTargets?: string | null | undefined;\n documentManifestBundle?: string | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAgBA,MAAM,CAAC,MAAM,mBAAmB,GAAG,SAAS,CAAC","sourcesContent":["import type { ContainerAccessLevel } from \"@tearleads/crypto\";\nimport type { DocumentAttachment } from \"../../data/documents/documentContent\";\nimport type {\n DocumentFieldValidationIssue,\n StoredDocumentKind,\n} from \"../../data/documents/documentKinds\";\nimport type { DocumentRestoreContent } from \"../../data/documents/documentRestore\";\nimport type { DocumentRow } from \"../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type { BlobByteSourceInput } from \"../../workflows/blobs\";\nimport type {\n DocumentRotationProofMode,\n DocumentsWorkflowRuntime,\n RelinkPersistedDocumentInput,\n} from \"../../workflows/documents\";\n\nexport const DEFAULT_DOCUMENT_ID = \"default\";\n\nexport type DocumentsRuntime = DocumentsWorkflowRuntime;\nexport type DocumentStructuredFieldPatch = Readonly<\n Record<string, string | undefined>\n>;\n\n/**\n * Host admission checked after readiness and again at local queue execution.\n * The predicate must be synchronous and side-effect-free. False is a no-op;\n * a throw is reported as a write failure and also refuses the mutation.\n * This does not cancel initialization or roll back an already admitted write.\n */\nexport interface DocumentMutationGuard {\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface DocumentMutationOptions extends DocumentMutationGuard {\n deferRemoteSync?: boolean | undefined;\n}\n\nexport interface DocumentStoreOpenOptions {\n /**\n * The caller attaches a file immediately after creating the document. The\n * birth commits locally without its own pending update, so the attach's\n * delta carries it; a failed attach enqueues the birth on its own.\n */\n deferInitialUpdate?: boolean | undefined;\n /**\n * Rows and structured fields a newly created record starts with. They are\n * written into its birth update with the initial kind and text, so a\n * document whose content is known up front queues one update. Fields need a\n * non-note `initialDocumentKind`. Both are ignored when the record exists.\n */\n initialRows?: ReadonlyArray<Readonly<Record<string, string>>> | undefined;\n initialStructuredFields?: DocumentStructuredFieldPatch | undefined;\n remoteSyncMode?: \"on-demand\" | \"startup\" | undefined;\n}\n\nexport interface DocumentAttachmentUpload {\n bytes: BlobByteSourceInput;\n name: string;\n mimeType: string | null;\n}\n\n// `syncing`: the slot's upload is still queued. `intent-mismatch`: the held\n// bytes are a validly signed served binding whose digest differs from the one\n// the document content records (its content update has not arrived).\nexport type DocumentAttachmentStatus = \"syncing\" | \"intent-mismatch\";\n\n// Add a row to the document's repeated-row list, returning the new row id.\nexport type AddDocumentRow = (\n fields: Readonly<Record<string, string>>,\n options?: DocumentMutationGuard | undefined,\n) => Promise<string>;\n// Patch one or more cells of a single row (merges per-cell).\nexport type UpdateDocumentRowFields = (\n id: string,\n patch: Readonly<Record<string, string>>,\n options?: DocumentMutationGuard | undefined,\n) => Promise<void>;\nexport type RemoveDocumentRow = (\n id: string,\n options?: DocumentMutationGuard | undefined,\n) => Promise<void>;\n\n// The store surface exposed through context: the snapshot fields plus the\n// store's mutation methods, spelled as a Pick so the two can't drift.\nexport type DocumentContextValue = DocumentSnapshot &\n Pick<\n DocumentStore,\n | \"addRow\"\n | \"attachFiles\"\n | \"relink\"\n | \"removeAttachment\"\n | \"removeRow\"\n | \"replaceAttachment\"\n | \"requestSync\"\n | \"restoreContent\"\n | \"setStructuredFields\"\n | \"setText\"\n | \"updateRowFields\"\n >;\n\nexport interface DocumentSnapshot {\n attachments: ReadonlyArray<DocumentAttachment>;\n attachmentStatusBySlotId: Readonly<Record<string, DocumentAttachmentStatus>>;\n attachmentStorageKeyBySlotId: Readonly<Record<string, string>>;\n canAttach: boolean;\n canWrite: boolean;\n currentAuthorId: string | null;\n documentId: string | null;\n documentKind: StoredDocumentKind;\n effectiveAccessLevel: ContainerAccessLevel;\n fieldValidationIssues: ReadonlyArray<DocumentFieldValidationIssue>;\n ready: boolean;\n rows: ReadonlyArray<DocumentRow>;\n structuredFields: Readonly<Record<string, string>>;\n text: string;\n title: string;\n syncing: boolean;\n}\n\nexport interface DocumentStore {\n addRow: AddDocumentRow;\n /** Fail unless this store can produce a mergeable full-history checkpoint. */\n assertCanRotateContentKey: (\n proof: DocumentRotationProofMode,\n ) => Promise<Uint8Array>;\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) => void;\n /**\n * Convert this document's persisted local state to the discovered-share\n * shell so the store re-pulls the server copy — the escape hatch for\n * queued local writes that can no longer sync. `expectedDocumentId` is\n * revalidated against the persisted record inside the teardown's\n * serialized mutation, so a stale caller can never discard a different\n * identity's edits. Refuses (returns false) local-only, unlinked,\n * move-pending, and identity-mismatched documents.\n */\n discardLocalState: (expectedDocumentId: string) => Promise<boolean>;\n ensureInitialized: () => Promise<boolean>;\n getSnapshot: () => DocumentSnapshot;\n /** Whether local writes are queued that have not reached SQLite yet. */\n hasQueuedWrites: () => boolean;\n /**\n * Whether applied local edits have not reached SQLite, e.g. after a failed\n * save, even though no write is queued any more.\n */\n hasUnsavedLocalEdits: () => boolean;\n removeAttachment: (slotId: string) => void;\n removeRow: RemoveDocumentRow;\n replaceAttachment: (\n slotId: string,\n file: DocumentAttachmentUpload,\n ) => Promise<void>;\n /**\n * Write a past version's text, structured fields, and rows back as one\n * ordinary local edit; attachments are left as they are. Nothing is rewound:\n * the restore is new operations that sync and merge like any other write.\n * Resolves true when the document durably holds the content, false when\n * the restore was refused or did not persist.\n */\n restoreContent: (\n content: DocumentRestoreContent,\n options?: DocumentMutationGuard | undefined,\n ) => Promise<boolean>;\n /** Pull remote document updates even when no websocket event marked it dirty. */\n requestRemoteSync: () => void;\n /** Pull remote updates and report whether the requested sync pass completed. */\n requestRemoteSyncAndWait: (\n signal?: AbortSignal | undefined,\n ) => Promise<boolean>;\n requestSync: () => void;\n relink: (input: DocumentStoreRelinkInput) => Promise<DocumentSummary | null>;\n setStructuredFields: (\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options?: DocumentMutationOptions | undefined,\n ) => Promise<void>;\n setText: (value: string) => Promise<void>;\n subscribe: (listener: () => void) => () => void;\n updateRowFields: UpdateDocumentRowFields;\n updateRuntime: (runtime: DocumentsRuntime) => void;\n}\n\nexport interface DocumentStoreFacade extends DocumentStore {\n rebindTo: (store: DocumentStore) => void;\n}\n\nexport type PersistedDocumentListener = (\n document: DocumentSummary,\n change: { readonly placementChanged: boolean },\n) => void;\n\nexport interface DocumentStoreRelinkInput extends RelinkPersistedDocumentInput {\n contentKeyBundle?: string | null | undefined;\n documentKekTargets?: string | null | undefined;\n documentManifestBundle?: string | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\n"]}
@@ -0,0 +1,72 @@
1
+ import { type DocumentFieldValidationIssue, type DocumentProjectorRegistryInput } from "../../../data/documents/documentKinds.js";
2
+ import type { DocumentsPersistence } from "../../../data/persistence/documents/documentsPersistence.js";
3
+ import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
4
+ import { type DocumentHistoryChange, type DocumentHistoryContent } from "./documentHistoryChange.js";
5
+ /** One step of a document's history: a single change by a single writer. */
6
+ export interface DocumentHistoryStop {
7
+ /** Position in the timeline, oldest first. */
8
+ readonly index: number;
9
+ /** The Loro peer that made the change; resolve it through edit attribution. */
10
+ readonly peerId: string;
11
+ /** Counter of the change's first operation. */
12
+ readonly startCounter: number;
13
+ /** One past the counter of the change's last operation. */
14
+ readonly endCounter: number;
15
+ /**
16
+ * When the writing device recorded the change, in Unix milliseconds, or
17
+ * null when it recorded no time. Self-reported: see `DocumentHistory`.
18
+ */
19
+ readonly committedAt: number | null;
20
+ }
21
+ /** The document as it was at one stop, in the shape a document store shows. */
22
+ export interface DocumentHistoryView extends DocumentHistoryContent {
23
+ readonly fieldValidationIssues: ReadonlyArray<DocumentFieldValidationIssue>;
24
+ readonly title: string;
25
+ }
26
+ /** The last operation a version includes for one peer. */
27
+ export interface DocumentHistoryVersionEntry {
28
+ readonly counter: number;
29
+ readonly peerId: string;
30
+ }
31
+ /** A version of a document, as the operations that head it. */
32
+ export type DocumentHistoryVersion = ReadonlyArray<DocumentHistoryVersionEntry>;
33
+ /**
34
+ * A read-only replay of one document's durable local history.
35
+ *
36
+ * It is a capture: it holds the history that was durable when it was opened
37
+ * and never changes afterwards, so the live document keeps editing and
38
+ * syncing untouched. Open another to see later edits. Call `close()` when
39
+ * done; it holds a WASM document.
40
+ *
41
+ * Times are the writing devices' own clocks, and a change is never recorded
42
+ * earlier than the newest time its document already held. History that
43
+ * arrived through a rotation baseline is whatever that baseline's writer
44
+ * asserted.
45
+ */
46
+ export interface DocumentHistory {
47
+ /** Every change, in the order the timeline plays them. */
48
+ readonly stops: ReadonlyArray<DocumentHistoryStop>;
49
+ /** What `stops[index]` changed, compared with the stop before it. */
50
+ changeAt(index: number): DocumentHistoryChange;
51
+ close(): void;
52
+ /** The version after `stops[0..index]`. */
53
+ versionAt(index: number): DocumentHistoryVersion;
54
+ /**
55
+ * The document after `stops[0..index]`; `-1` is the empty document before
56
+ * the first change. Replaying a distant stop of a large document can take
57
+ * tens of milliseconds, so keep it out of rendering.
58
+ */
59
+ viewAt(index: number): DocumentHistoryView;
60
+ }
61
+ /**
62
+ * Open a replay of the document's durable local history (checkpoint plus
63
+ * tail). Returns null when the document has none yet, such as a discovered
64
+ * shell that has not hydrated. The history is loaded into a scratch document,
65
+ * never the one a document store is editing.
66
+ */
67
+ export declare function openDocumentHistory(input: {
68
+ readonly documentProjectors: DocumentProjectorRegistryInput;
69
+ readonly execSql: ExecSql;
70
+ readonly localId: string;
71
+ readonly persistence: Pick<DocumentsPersistence, "loadHistoryRestoreState">;
72
+ }): Promise<DocumentHistory | null>;
@@ -0,0 +1,103 @@
1
+ import { base64ToBytes } from "../../../internal/encoding/index.js";
2
+ import { createReadOnlyDocument, importSnapshot, openHistoryViewer, } from "../../../internal/loro/index.js";
3
+ import { getDocumentAttachments } from "../../../data/documents/documentContent.js";
4
+ import { readStoredDocumentState, } from "../../../data/documents/documentKinds.js";
5
+ import { listDocumentRows } from "../../../data/documents/documentRowList.js";
6
+ import { importDocumentHistoryTailUpdates } from "../historyContent.js";
7
+ import { compareDocumentHistoryContent, } from "./documentHistoryChange.js";
8
+ /** Views kept so stepping to a neighbor does not replay the document twice. */
9
+ const VIEW_CACHE_SIZE = 8;
10
+ class DocumentHistoryReader {
11
+ viewer;
12
+ documentProjectors;
13
+ stops;
14
+ closed = false;
15
+ /** Insertion-ordered: the first key is the least recently used. */
16
+ views = new Map();
17
+ constructor(viewer, documentProjectors) {
18
+ this.viewer = viewer;
19
+ this.documentProjectors = documentProjectors;
20
+ this.stops = viewer.stops.map((stop, index) => ({
21
+ index,
22
+ peerId: stop.peerId,
23
+ startCounter: stop.startCounter,
24
+ endCounter: stop.endCounter,
25
+ committedAt: stop.timestamp === null ? null : stop.timestamp * 1000,
26
+ }));
27
+ }
28
+ changeAt(index) {
29
+ this.assertStop(index, 0);
30
+ return compareDocumentHistoryContent(this.viewAt(index - 1), this.viewAt(index));
31
+ }
32
+ close() {
33
+ if (this.closed)
34
+ return;
35
+ this.closed = true;
36
+ this.views.clear();
37
+ this.viewer.free();
38
+ }
39
+ versionAt(index) {
40
+ this.assertStop(index, -1);
41
+ return this.viewer.versionAt(index);
42
+ }
43
+ viewAt(index) {
44
+ this.assertStop(index, -1);
45
+ const cached = this.views.get(index);
46
+ if (cached !== undefined) {
47
+ this.views.delete(index);
48
+ this.views.set(index, cached);
49
+ return cached;
50
+ }
51
+ this.viewer.checkout(index);
52
+ const { doc } = this.viewer;
53
+ const view = {
54
+ ...readStoredDocumentState(doc, this.documentProjectors),
55
+ attachments: getDocumentAttachments(doc),
56
+ rows: listDocumentRows(doc),
57
+ };
58
+ this.views.set(index, view);
59
+ if (this.views.size > VIEW_CACHE_SIZE) {
60
+ const oldest = this.views.keys().next();
61
+ if (!oldest.done)
62
+ this.views.delete(oldest.value);
63
+ }
64
+ return view;
65
+ }
66
+ assertStop(index, lowest) {
67
+ if (this.closed) {
68
+ throw new Error("Document history is closed.");
69
+ }
70
+ if (!Number.isInteger(index) ||
71
+ index < lowest ||
72
+ index >= this.stops.length) {
73
+ throw new RangeError(`Document history stop ${index} is out of range.`);
74
+ }
75
+ }
76
+ }
77
+ /**
78
+ * Open a replay of the document's durable local history (checkpoint plus
79
+ * tail). Returns null when the document has none yet, such as a discovered
80
+ * shell that has not hydrated. The history is loaded into a scratch document,
81
+ * never the one a document store is editing.
82
+ */
83
+ export async function openDocumentHistory(input) {
84
+ const history = await input.persistence.loadHistoryRestoreState(input.execSql, input.localId);
85
+ if (!history) {
86
+ return null;
87
+ }
88
+ const doc = createReadOnlyDocument();
89
+ try {
90
+ // A tail-only state (a crash before the birth checkpoint landed) has an
91
+ // empty snapshot; the tail rows alone carry the history.
92
+ if (history.snapshot.length > 0) {
93
+ importSnapshot(doc, base64ToBytes(history.snapshot));
94
+ }
95
+ importDocumentHistoryTailUpdates(doc, history.tailUpdates.map((update) => update.updateData));
96
+ return new DocumentHistoryReader(openHistoryViewer(doc), input.documentProjectors);
97
+ }
98
+ catch (error) {
99
+ doc.free();
100
+ throw error;
101
+ }
102
+ }
103
+ //# sourceMappingURL=documentHistory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"documentHistory.js","sourceRoot":"","sources":["documentHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,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CAAC,MAAM,CAAC,UAAU,CAAC,CACvD,CAAC;QACF,OAAO,IAAI,qBAAqB,CAC9B,iBAAiB,CAAC,GAAG,CAAC,EACtB,KAAK,CAAC,kBAAkB,CACzB,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,IAAI,EAAE,CAAC;QACX,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport {\n createReadOnlyDocument,\n type HistoryViewer,\n importSnapshot,\n openHistoryViewer,\n} from \"@tearleads/loro\";\nimport { getDocumentAttachments } from \"../../../data/documents/documentContent\";\nimport {\n type DocumentFieldValidationIssue,\n type DocumentProjectorRegistryInput,\n readStoredDocumentState,\n} from \"../../../data/documents/documentKinds\";\nimport { listDocumentRows } from \"../../../data/documents/documentRowList\";\nimport type { DocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { importDocumentHistoryTailUpdates } from \"../historyContent\";\nimport {\n compareDocumentHistoryContent,\n type DocumentHistoryChange,\n type DocumentHistoryContent,\n} from \"./documentHistoryChange\";\n\n/** Views kept so stepping to a neighbor does not replay the document twice. */\nconst VIEW_CACHE_SIZE = 8;\n\n/** One step of a document's history: a single change by a single writer. */\nexport interface DocumentHistoryStop {\n /** Position in the timeline, oldest first. */\n readonly index: number;\n /** The Loro peer that made the change; resolve it through edit attribution. */\n readonly peerId: string;\n /** Counter of the change's first operation. */\n readonly startCounter: number;\n /** One past the counter of the change's last operation. */\n readonly endCounter: number;\n /**\n * When the writing device recorded the change, in Unix milliseconds, or\n * null when it recorded no time. Self-reported: see `DocumentHistory`.\n */\n readonly committedAt: number | null;\n}\n\n/** The document as it was at one stop, in the shape a document store shows. */\nexport interface DocumentHistoryView extends DocumentHistoryContent {\n readonly fieldValidationIssues: ReadonlyArray<DocumentFieldValidationIssue>;\n readonly title: string;\n}\n\n/** The last operation a version includes for one peer. */\nexport interface DocumentHistoryVersionEntry {\n readonly counter: number;\n readonly peerId: string;\n}\n\n/** A version of a document, as the operations that head it. */\nexport type DocumentHistoryVersion = ReadonlyArray<DocumentHistoryVersionEntry>;\n\n/**\n * A read-only replay of one document's durable local history.\n *\n * It is a capture: it holds the history that was durable when it was opened\n * and never changes afterwards, so the live document keeps editing and\n * syncing untouched. Open another to see later edits. Call `close()` when\n * done; it holds a WASM document.\n *\n * Times are the writing devices' own clocks, and a change is never recorded\n * earlier than the newest time its document already held. History that\n * arrived through a rotation baseline is whatever that baseline's writer\n * asserted.\n */\nexport interface DocumentHistory {\n /** Every change, in the order the timeline plays them. */\n readonly stops: ReadonlyArray<DocumentHistoryStop>;\n /** What `stops[index]` changed, compared with the stop before it. */\n changeAt(index: number): DocumentHistoryChange;\n close(): void;\n /** The version after `stops[0..index]`. */\n versionAt(index: number): DocumentHistoryVersion;\n /**\n * The document after `stops[0..index]`; `-1` is the empty document before\n * the first change. Replaying a distant stop of a large document can take\n * tens of milliseconds, so keep it out of rendering.\n */\n viewAt(index: number): DocumentHistoryView;\n}\n\nclass DocumentHistoryReader implements DocumentHistory {\n readonly stops: ReadonlyArray<DocumentHistoryStop>;\n private closed = false;\n /** Insertion-ordered: the first key is the least recently used. */\n private readonly views = new Map<number, DocumentHistoryView>();\n\n constructor(\n private readonly viewer: HistoryViewer,\n private readonly documentProjectors: DocumentProjectorRegistryInput,\n ) {\n this.stops = viewer.stops.map((stop, index) => ({\n index,\n peerId: stop.peerId,\n startCounter: stop.startCounter,\n endCounter: stop.endCounter,\n committedAt: stop.timestamp === null ? null : stop.timestamp * 1000,\n }));\n }\n\n changeAt(index: number): DocumentHistoryChange {\n this.assertStop(index, 0);\n return compareDocumentHistoryContent(\n this.viewAt(index - 1),\n this.viewAt(index),\n );\n }\n\n close(): void {\n if (this.closed) return;\n this.closed = true;\n this.views.clear();\n this.viewer.free();\n }\n\n versionAt(index: number): DocumentHistoryVersion {\n this.assertStop(index, -1);\n return this.viewer.versionAt(index);\n }\n\n viewAt(index: number): DocumentHistoryView {\n this.assertStop(index, -1);\n const cached = this.views.get(index);\n if (cached !== undefined) {\n this.views.delete(index);\n this.views.set(index, cached);\n return cached;\n }\n this.viewer.checkout(index);\n const { doc } = this.viewer;\n const view: DocumentHistoryView = {\n ...readStoredDocumentState(doc, this.documentProjectors),\n attachments: getDocumentAttachments(doc),\n rows: listDocumentRows(doc),\n };\n this.views.set(index, view);\n if (this.views.size > VIEW_CACHE_SIZE) {\n const oldest = this.views.keys().next();\n if (!oldest.done) this.views.delete(oldest.value);\n }\n return view;\n }\n\n private assertStop(index: number, lowest: -1 | 0): void {\n if (this.closed) {\n throw new Error(\"Document history is closed.\");\n }\n if (\n !Number.isInteger(index) ||\n index < lowest ||\n index >= this.stops.length\n ) {\n throw new RangeError(`Document history stop ${index} is out of range.`);\n }\n }\n}\n\n/**\n * Open a replay of the document's durable local history (checkpoint plus\n * tail). Returns null when the document has none yet, such as a discovered\n * shell that has not hydrated. The history is loaded into a scratch document,\n * never the one a document store is editing.\n */\nexport async function openDocumentHistory(input: {\n readonly documentProjectors: DocumentProjectorRegistryInput;\n readonly execSql: ExecSql;\n readonly localId: string;\n readonly persistence: Pick<DocumentsPersistence, \"loadHistoryRestoreState\">;\n}): Promise<DocumentHistory | null> {\n const history = await input.persistence.loadHistoryRestoreState(\n input.execSql,\n input.localId,\n );\n if (!history) {\n return null;\n }\n\n const doc = createReadOnlyDocument();\n try {\n // A tail-only state (a crash before the birth checkpoint landed) has an\n // empty snapshot; the tail rows alone carry the history.\n if (history.snapshot.length > 0) {\n importSnapshot(doc, base64ToBytes(history.snapshot));\n }\n importDocumentHistoryTailUpdates(\n doc,\n history.tailUpdates.map((update) => update.updateData),\n );\n return new DocumentHistoryReader(\n openHistoryViewer(doc),\n input.documentProjectors,\n );\n } catch (error) {\n doc.free();\n throw error;\n }\n}\n"]}
@@ -0,0 +1,51 @@
1
+ import type { DocumentAttachment } from "../../../data/documents/documentContent.js";
2
+ import type { StoredDocumentKind } from "../../../data/documents/documentKinds.js";
3
+ import type { DocumentRow } from "../../../data/documents/documentRowList.js";
4
+ /** The parts of a document that its history can change. */
5
+ export interface DocumentHistoryContent {
6
+ readonly attachments: ReadonlyArray<DocumentAttachment>;
7
+ readonly documentKind: StoredDocumentKind;
8
+ readonly rows: ReadonlyArray<DocumentRow>;
9
+ readonly structuredFields: Readonly<Record<string, string>>;
10
+ readonly text: string;
11
+ }
12
+ /**
13
+ * The one region of text that differs between two versions, in UTF-16 units
14
+ * of the newer text. Edits in several places are reported as the single region
15
+ * that spans them.
16
+ */
17
+ export interface DocumentHistoryTextChange {
18
+ /** Where the region starts, in both the older and the newer text. */
19
+ readonly start: number;
20
+ /** Length of the region in the newer text. */
21
+ readonly insertedLength: number;
22
+ /** Length of the region it replaced in the older text. */
23
+ readonly removedLength: number;
24
+ }
25
+ export interface DocumentHistoryRowChange {
26
+ readonly id: string;
27
+ /** Cells whose value was set, changed, or cleared, in key order. */
28
+ readonly fields: ReadonlyArray<string>;
29
+ }
30
+ /** What one step of history changed, compared with the step before it. */
31
+ export interface DocumentHistoryChange {
32
+ readonly attachments: {
33
+ readonly added: ReadonlyArray<string>;
34
+ readonly removed: ReadonlyArray<string>;
35
+ /** Slots that kept their place but now hold different bytes or a new name. */
36
+ readonly replaced: ReadonlyArray<string>;
37
+ };
38
+ /** Structured fields set, changed, or cleared, in key order. */
39
+ readonly fields: ReadonlyArray<string>;
40
+ readonly kindChanged: boolean;
41
+ readonly rows: {
42
+ readonly added: ReadonlyArray<string>;
43
+ readonly changed: ReadonlyArray<DocumentHistoryRowChange>;
44
+ readonly removed: ReadonlyArray<string>;
45
+ };
46
+ readonly text: DocumentHistoryTextChange | null;
47
+ }
48
+ /** Compare a version with the one before it. Pure. */
49
+ export declare function compareDocumentHistoryContent(before: DocumentHistoryContent, after: DocumentHistoryContent): DocumentHistoryChange;
50
+ /** Whether a step changed anything a reader of the document would see. */
51
+ export declare function isEmptyDocumentHistoryChange(change: DocumentHistoryChange): boolean;
@@ -0,0 +1,110 @@
1
+ function isHighSurrogate(codeUnit) {
2
+ return codeUnit >= 0xd800 && codeUnit <= 0xdbff;
3
+ }
4
+ function isLowSurrogate(codeUnit) {
5
+ return codeUnit >= 0xdc00 && codeUnit <= 0xdfff;
6
+ }
7
+ function compareTextChange(before, after) {
8
+ if (before === after)
9
+ return null;
10
+ const shorter = Math.min(before.length, after.length);
11
+ let start = 0;
12
+ while (start < shorter &&
13
+ before.charCodeAt(start) === after.charCodeAt(start)) {
14
+ start += 1;
15
+ }
16
+ // Keep a shared high surrogate with the differing low surrogate after it.
17
+ if (start > 0 && isHighSurrogate(before.charCodeAt(start - 1)))
18
+ start -= 1;
19
+ let shared = 0;
20
+ while (shared < shorter - start &&
21
+ before.charCodeAt(before.length - 1 - shared) ===
22
+ after.charCodeAt(after.length - 1 - shared)) {
23
+ shared += 1;
24
+ }
25
+ // Keep a shared low surrogate with the differing high surrogate before it.
26
+ if (shared > 0 && isLowSurrogate(before.charCodeAt(before.length - shared))) {
27
+ shared -= 1;
28
+ }
29
+ return {
30
+ start,
31
+ insertedLength: after.length - shared - start,
32
+ removedLength: before.length - shared - start,
33
+ };
34
+ }
35
+ function changedKeys(before, after) {
36
+ const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
37
+ return [...keys].filter((key) => before[key] !== after[key]).sort();
38
+ }
39
+ function compareRows(before, after) {
40
+ const beforeById = new Map(before.map((row) => [row.id, row]));
41
+ const afterIds = new Set(after.map((row) => row.id));
42
+ const added = [];
43
+ const changed = [];
44
+ for (const row of after) {
45
+ const previous = beforeById.get(row.id);
46
+ if (previous === undefined) {
47
+ added.push(row.id);
48
+ continue;
49
+ }
50
+ const fields = changedKeys(previous.fields, row.fields);
51
+ if (fields.length > 0)
52
+ changed.push({ id: row.id, fields });
53
+ }
54
+ return {
55
+ added,
56
+ changed,
57
+ removed: before.filter((row) => !afterIds.has(row.id)).map((row) => row.id),
58
+ };
59
+ }
60
+ function sameAttachment(left, right) {
61
+ return (left.contentSha256 === right.contentSha256 &&
62
+ left.name === right.name &&
63
+ left.byteLength === right.byteLength &&
64
+ left.mimeType === right.mimeType);
65
+ }
66
+ function compareAttachments(before, after) {
67
+ const beforeBySlot = new Map(before.map((item) => [item.slotId, item]));
68
+ const afterSlots = new Set(after.map((item) => item.slotId));
69
+ const added = [];
70
+ const replaced = [];
71
+ for (const attachment of after) {
72
+ const previous = beforeBySlot.get(attachment.slotId);
73
+ if (previous === undefined) {
74
+ added.push(attachment.slotId);
75
+ }
76
+ else if (!sameAttachment(previous, attachment)) {
77
+ replaced.push(attachment.slotId);
78
+ }
79
+ }
80
+ return {
81
+ added,
82
+ removed: before
83
+ .filter((item) => !afterSlots.has(item.slotId))
84
+ .map((item) => item.slotId),
85
+ replaced,
86
+ };
87
+ }
88
+ /** Compare a version with the one before it. Pure. */
89
+ export function compareDocumentHistoryContent(before, after) {
90
+ return {
91
+ attachments: compareAttachments(before.attachments, after.attachments),
92
+ fields: changedKeys(before.structuredFields, after.structuredFields),
93
+ kindChanged: before.documentKind !== after.documentKind,
94
+ rows: compareRows(before.rows, after.rows),
95
+ text: compareTextChange(before.text, after.text),
96
+ };
97
+ }
98
+ /** Whether a step changed anything a reader of the document would see. */
99
+ export function isEmptyDocumentHistoryChange(change) {
100
+ return (!change.kindChanged &&
101
+ change.text === null &&
102
+ change.fields.length === 0 &&
103
+ change.rows.added.length === 0 &&
104
+ change.rows.changed.length === 0 &&
105
+ change.rows.removed.length === 0 &&
106
+ change.attachments.added.length === 0 &&
107
+ change.attachments.removed.length === 0 &&
108
+ change.attachments.replaced.length === 0);
109
+ }
110
+ //# sourceMappingURL=documentHistoryChange.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"documentHistoryChange.js","sourceRoot":"","sources":["documentHistoryChange.ts"],"names":[],"mappings":"AAoDA,SAAS,eAAe,CAAC,QAAgB;IACvC,OAAO,QAAQ,IAAI,MAAM,IAAI,QAAQ,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,MAAM,KAAK,CAAC;QAC9B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC;QAChC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC;QAChC,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC;QACrC,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC;QACvC,MAAM,CAAC,WAAW,CAAC,QAAQ,CAAC,MAAM,KAAK,CAAC,CACzC,CAAC;AACJ,CAAC","sourcesContent":["import type { DocumentAttachment } from \"../../../data/documents/documentContent\";\nimport type { StoredDocumentKind } from \"../../../data/documents/documentKinds\";\nimport type { DocumentRow } from \"../../../data/documents/documentRowList\";\n\n/** The parts of a document that its history can change. */\nexport interface DocumentHistoryContent {\n readonly attachments: ReadonlyArray<DocumentAttachment>;\n readonly documentKind: StoredDocumentKind;\n readonly rows: ReadonlyArray<DocumentRow>;\n readonly structuredFields: Readonly<Record<string, string>>;\n readonly text: string;\n}\n\n/**\n * The one region of text that differs between two versions, in UTF-16 units\n * of the newer text. Edits in several places are reported as the single region\n * that spans them.\n */\nexport interface DocumentHistoryTextChange {\n /** Where the region starts, in both the older and the newer text. */\n readonly start: number;\n /** Length of the region in the newer text. */\n readonly insertedLength: number;\n /** Length of the region it replaced in the older text. */\n readonly removedLength: number;\n}\n\nexport interface DocumentHistoryRowChange {\n readonly id: string;\n /** Cells whose value was set, changed, or cleared, in key order. */\n readonly fields: ReadonlyArray<string>;\n}\n\n/** What one step of history changed, compared with the step before it. */\nexport interface DocumentHistoryChange {\n readonly attachments: {\n readonly added: ReadonlyArray<string>;\n readonly removed: ReadonlyArray<string>;\n /** Slots that kept their place but now hold different bytes or a new name. */\n readonly replaced: ReadonlyArray<string>;\n };\n /** Structured fields set, changed, or cleared, in key order. */\n readonly fields: ReadonlyArray<string>;\n readonly kindChanged: boolean;\n readonly rows: {\n readonly added: ReadonlyArray<string>;\n readonly changed: ReadonlyArray<DocumentHistoryRowChange>;\n readonly removed: ReadonlyArray<string>;\n };\n readonly text: DocumentHistoryTextChange | null;\n}\n\nfunction isHighSurrogate(codeUnit: number): boolean {\n return codeUnit >= 0xd800 && codeUnit <= 0xdbff;\n}\n\nfunction isLowSurrogate(codeUnit: number): boolean {\n return codeUnit >= 0xdc00 && codeUnit <= 0xdfff;\n}\n\nfunction compareTextChange(\n before: string,\n after: string,\n): DocumentHistoryTextChange | null {\n if (before === after) return null;\n const shorter = Math.min(before.length, after.length);\n let start = 0;\n while (\n start < shorter &&\n before.charCodeAt(start) === after.charCodeAt(start)\n ) {\n start += 1;\n }\n // Keep a shared high surrogate with the differing low surrogate after it.\n if (start > 0 && isHighSurrogate(before.charCodeAt(start - 1))) start -= 1;\n let shared = 0;\n while (\n shared < shorter - start &&\n before.charCodeAt(before.length - 1 - shared) ===\n after.charCodeAt(after.length - 1 - shared)\n ) {\n shared += 1;\n }\n // Keep a shared low surrogate with the differing high surrogate before it.\n if (shared > 0 && isLowSurrogate(before.charCodeAt(before.length - shared))) {\n shared -= 1;\n }\n return {\n start,\n insertedLength: after.length - shared - start,\n removedLength: before.length - shared - start,\n };\n}\n\nfunction changedKeys(\n before: Readonly<Record<string, string>>,\n after: Readonly<Record<string, string>>,\n): string[] {\n const keys = new Set([...Object.keys(before), ...Object.keys(after)]);\n return [...keys].filter((key) => before[key] !== after[key]).sort();\n}\n\nfunction compareRows(\n before: ReadonlyArray<DocumentRow>,\n after: ReadonlyArray<DocumentRow>,\n): DocumentHistoryChange[\"rows\"] {\n const beforeById = new Map(before.map((row) => [row.id, row]));\n const afterIds = new Set(after.map((row) => row.id));\n const added: string[] = [];\n const changed: DocumentHistoryRowChange[] = [];\n for (const row of after) {\n const previous = beforeById.get(row.id);\n if (previous === undefined) {\n added.push(row.id);\n continue;\n }\n const fields = changedKeys(previous.fields, row.fields);\n if (fields.length > 0) changed.push({ id: row.id, fields });\n }\n return {\n added,\n changed,\n removed: before.filter((row) => !afterIds.has(row.id)).map((row) => row.id),\n };\n}\n\nfunction sameAttachment(\n left: DocumentAttachment,\n right: DocumentAttachment,\n): boolean {\n return (\n left.contentSha256 === right.contentSha256 &&\n left.name === right.name &&\n left.byteLength === right.byteLength &&\n left.mimeType === right.mimeType\n );\n}\n\nfunction compareAttachments(\n before: ReadonlyArray<DocumentAttachment>,\n after: ReadonlyArray<DocumentAttachment>,\n): DocumentHistoryChange[\"attachments\"] {\n const beforeBySlot = new Map(before.map((item) => [item.slotId, item]));\n const afterSlots = new Set(after.map((item) => item.slotId));\n const added: string[] = [];\n const replaced: string[] = [];\n for (const attachment of after) {\n const previous = beforeBySlot.get(attachment.slotId);\n if (previous === undefined) {\n added.push(attachment.slotId);\n } else if (!sameAttachment(previous, attachment)) {\n replaced.push(attachment.slotId);\n }\n }\n return {\n added,\n removed: before\n .filter((item) => !afterSlots.has(item.slotId))\n .map((item) => item.slotId),\n replaced,\n };\n}\n\n/** Compare a version with the one before it. Pure. */\nexport function compareDocumentHistoryContent(\n before: DocumentHistoryContent,\n after: DocumentHistoryContent,\n): DocumentHistoryChange {\n return {\n attachments: compareAttachments(before.attachments, after.attachments),\n fields: changedKeys(before.structuredFields, after.structuredFields),\n kindChanged: before.documentKind !== after.documentKind,\n rows: compareRows(before.rows, after.rows),\n text: compareTextChange(before.text, after.text),\n };\n}\n\n/** Whether a step changed anything a reader of the document would see. */\nexport function isEmptyDocumentHistoryChange(\n change: DocumentHistoryChange,\n): boolean {\n return (\n !change.kindChanged &&\n change.text === null &&\n change.fields.length === 0 &&\n change.rows.added.length === 0 &&\n change.rows.changed.length === 0 &&\n change.rows.removed.length === 0 &&\n change.attachments.added.length === 0 &&\n change.attachments.removed.length === 0 &&\n change.attachments.replaced.length === 0\n );\n}\n"]}
@@ -15,6 +15,8 @@ export { runSerializedDocumentBlobMutation } from "./attachments/blobMutationLoc
15
15
  export { reclaimDocumentOrphanBlobs } from "./attachments/orphanBlobReclaims.js";
16
16
  export { resolveDocumentCreateAuthor } from "./author.js";
17
17
  export { buildMaterializedDocumentCreatePlan, createRemoteDocument, documentWriterProjectionFromCreateResponse, } from "./create/index.js";
18
+ export { type DocumentHistory, type DocumentHistoryStop, type DocumentHistoryVersion, type DocumentHistoryVersionEntry, type DocumentHistoryView, openDocumentHistory, } from "./history/documentHistory.js";
19
+ export { type DocumentHistoryChange, type DocumentHistoryRowChange, type DocumentHistoryTextChange, isEmptyDocumentHistoryChange, } from "./history/documentHistoryChange.js";
18
20
  export { importDocumentHistoryTailUpdates, loadPersistedDocumentContent, mergePersistedDocumentHistory, } from "./historyContent.js";
19
21
  export { buildMaterializedDocumentLinkSetMutationPlan } from "./linkSet/index.js";
20
22
  export { createLinkSetAttachmentReuse, type LinkSetAttachmentReuse, } from "./linkSet/linkSetBlobRewraps.js";