@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
@@ -0,0 +1,127 @@
1
+ import { encodeVersionVector } from "../../../../internal/loro/index.js";
2
+ import { restoreDocumentContent, } from "../../../../data/documents/documentRestore.js";
3
+ import { createPendingUpdateFields } from "../../../../data/documents/documentSync.js";
4
+ import { requestDocumentStoreSync } from "../../registry.js";
5
+ import { ensureDocumentStoreReady } from "../initialization/index.js";
6
+ import { chainQueuedWrite } from "../localWriteQueue/index.js";
7
+ import { settleDocumentLocalWrite } from "../mutations.js";
8
+ import { advancePendingBaseVersion, pendingDeltaSinceBase, persistDocument, } from "../persistence.js";
9
+ import { reportDocumentStoreWriteFailure } from "../reportWriteFailure.js";
10
+ import { resolveRowAttribution } from "../rows/rowAttribution.js";
11
+ import { canWriteDocument, } from "../state.js";
12
+ import { captureDocumentStoreSyncGeneration, isDocumentStoreSyncGenerationCurrent, } from "../sync/syncGeneration.js";
13
+ // Fixed literal: a reported message must never carry document content.
14
+ const RESTORE_FAILURE_MESSAGE = "Documents: content restore failed";
15
+ /**
16
+ * Leads the commit message of every restore. The rest of the message is
17
+ * random, so two restores in a row are two steps as well.
18
+ */
19
+ const DOCUMENT_RESTORE_COMMIT_MESSAGE = "restore";
20
+ /**
21
+ * Apply and persist one restore. Resolves true when the document durably
22
+ * holds the content: it was written and saved, or it already matched.
23
+ */
24
+ async function persistRestoredContent(state, expectedLocalWriteGeneration, content, options) {
25
+ if (state.localWriteGeneration !== expectedLocalWriteGeneration) {
26
+ return false;
27
+ }
28
+ const currentDoc = state.doc;
29
+ if (!currentDoc || !canWriteDocument(state)) {
30
+ return false;
31
+ }
32
+ const generation = captureDocumentStoreSyncGeneration(state, currentDoc);
33
+ if (!generation || options.stillCurrent?.() === false) {
34
+ return false;
35
+ }
36
+ // A restore is always its own step of history. Loro folds a writer's
37
+ // commits into one change while they fall within the merge interval, which
38
+ // would fold a restore into the edit it replaces and take that version off
39
+ // the timeline. Changes with different messages never share a change, so
40
+ // close the edits before it and give the restore a message of its own.
41
+ currentDoc.commit();
42
+ const changed = restoreDocumentContent(currentDoc, content, resolveRowAttribution(state), state.runtime.infra.documentProjectors);
43
+ if (changed) {
44
+ currentDoc.commit({
45
+ message: `${DOCUMENT_RESTORE_COMMIT_MESSAGE} ${crypto.randomUUID()}`,
46
+ });
47
+ }
48
+ // Every operation since the last persisted base travels in this update,
49
+ // including edits an earlier failed save left behind.
50
+ const update = pendingDeltaSinceBase(state, currentDoc);
51
+ const pendingUpdate = update.byteLength === 0 ? null : createPendingUpdateFields(update);
52
+ // The persist keeps whatever text and fields are on screen: an edit queued
53
+ // behind this restore has already shown its value, and publishing the
54
+ // restored document over it would regress an editor the user is typing in.
55
+ // The restored content is published when the local writes drain
56
+ // (settleDocumentLocalWrite), as it is for every other write.
57
+ const saveOptions = {
58
+ preserveSnapshotStructuredFields: true,
59
+ preserveSnapshotText: true,
60
+ };
61
+ if (!pendingUpdate) {
62
+ // Already this content: nothing to save, only the identity to revalidate.
63
+ return isPersistedAndCurrent(state, generation, await persistDocument(state, currentDoc, {}, saveOptions, generation));
64
+ }
65
+ const coveredVersion = encodeVersionVector(currentDoc);
66
+ // From here until a persist covers it, the doc holds edits SQLite lacks.
67
+ state.unsavedLocalEdits = true;
68
+ const persisted = await persistDocument(state, currentDoc, { snapshotEndVersion: coveredVersion }, { ...saveOptions, pendingUpdate }, generation);
69
+ if (!isPersistedAndCurrent(state, generation, persisted)) {
70
+ return false;
71
+ }
72
+ advancePendingBaseVersion(state, currentDoc);
73
+ requestDocumentStoreSync(state);
74
+ return true;
75
+ }
76
+ /**
77
+ * Whether a persist landed on the document this write started against. A
78
+ * refused persist, a lost compare-and-set, or a superseded generation means
79
+ * the store now holds something else.
80
+ */
81
+ function isPersistedAndCurrent(state, generation, persisted) {
82
+ return (persisted !== null &&
83
+ !persisted.pullContinuationSuperseded &&
84
+ !persisted.syncIdentitySuperseded &&
85
+ isDocumentStoreSyncGenerationCurrent(state, generation));
86
+ }
87
+ /**
88
+ * Restore the document to `content` as one ordinary local write, queued
89
+ * behind the writes already in flight. Resolves false when the restore was
90
+ * refused or did not persist: the store is not ready, the document cannot be
91
+ * written, the caller's guard expired, or the save failed.
92
+ */
93
+ export async function restoreDocumentStoreContent(state, scheduleSync, content, options = {}) {
94
+ let ready;
95
+ try {
96
+ ready = await ensureDocumentStoreReady(state, scheduleSync);
97
+ if (options.stillCurrent?.() === false)
98
+ ready = false;
99
+ }
100
+ catch (error) {
101
+ reportDocumentStoreWriteFailure(state, RESTORE_FAILURE_MESSAGE, error);
102
+ return false;
103
+ }
104
+ if (!ready || !state.doc || !canWriteDocument(state)) {
105
+ return false;
106
+ }
107
+ const writeGeneration = state.localWriteGeneration;
108
+ let restored = false;
109
+ // Counted as a local write in flight, like a text or field write: while the
110
+ // count is above zero a sync pass keeps the snapshot on screen, and the
111
+ // document is published once the count drains.
112
+ state.pendingLocalWrites += 1;
113
+ await chainQueuedWrite(state, state.writeChain
114
+ .catch(() => undefined)
115
+ .then(async () => {
116
+ restored = await persistRestoredContent(state, writeGeneration, content, options);
117
+ })
118
+ .catch((error) => {
119
+ reportDocumentStoreWriteFailure(state, RESTORE_FAILURE_MESSAGE, error);
120
+ })
121
+ // Always settle, so the count cannot stick above zero.
122
+ .finally(() => {
123
+ settleDocumentLocalWrite(state, writeGeneration);
124
+ }));
125
+ return restored;
126
+ }
127
+ //# sourceMappingURL=restoreContent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"restoreContent.js","sourceRoot":"","sources":["restoreContent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAEL,sBAA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EAA4E;IAC5E,wEAAwE;IACxE,+CAA+C;IAC/C,KAAK,CAAC,kBAAkB,IAAI,CAAC,CAAC;IAC9B,MAAM,gBAAgB,CACpB,KAAK,EACL,KAAK,CAAC,UAAU;SACb,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC;SACtB,IAAI,CAAC,KAAK,IAAI,EAAE;QACf,QAAQ,GAAG,MAAM,sBAAsB,CACrC,KAAK,EACL,eAAe,EACf,OAAO,EACP,OAAO,CACR,CAAC;IACJ,CAAC,CAAC;SACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACxB,+BAA+B,CAAC,KAAK,EAAE,uBAAuB,EAAE,KAAK,CAAC,CAAC;IACzE,CAAC,CAAC;QACF,uDAAuD;SACtD,OAAO,CAAC,GAAG,EAAE;QACZ,wBAAwB,CAAC,KAAK,EAAE,eAAe,CAAC,CAAC;IACnD,CAAC,CAAC,CACL,CAAC;IACF,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import { encodeVersionVector } from \"@tearleads/loro\";\nimport {\n type DocumentRestoreContent,\n restoreDocumentContent,\n} from \"../../../../data/documents/documentRestore\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport type { DocumentMutationGuard } from \"../../types\";\nimport { ensureDocumentStoreReady } from \"../initialization\";\nimport { chainQueuedWrite } from \"../localWriteQueue\";\nimport { settleDocumentLocalWrite } from \"../mutations\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"../persistence\";\nimport { reportDocumentStoreWriteFailure } from \"../reportWriteFailure\";\nimport { resolveRowAttribution } from \"../rows/rowAttribution\";\nimport {\n canWriteDocument,\n type DocumentStoreState,\n type SaveDocumentRecordOptions,\n} from \"../state\";\nimport {\n captureDocumentStoreSyncGeneration,\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\n\n// Fixed literal: a reported message must never carry document content.\nconst RESTORE_FAILURE_MESSAGE = \"Documents: content restore failed\";\n\n/**\n * Leads the commit message of every restore. The rest of the message is\n * random, so two restores in a row are two steps as well.\n */\nconst DOCUMENT_RESTORE_COMMIT_MESSAGE = \"restore\";\n\n/**\n * Apply and persist one restore. Resolves true when the document durably\n * holds the content: it was written and saved, or it already matched.\n */\nasync function persistRestoredContent(\n state: DocumentStoreState,\n expectedLocalWriteGeneration: number,\n content: DocumentRestoreContent,\n options: DocumentMutationGuard,\n): Promise<boolean> {\n if (state.localWriteGeneration !== expectedLocalWriteGeneration) {\n return false;\n }\n const currentDoc = state.doc;\n if (!currentDoc || !canWriteDocument(state)) {\n return false;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation || options.stillCurrent?.() === false) {\n return false;\n }\n\n // A restore is always its own step of history. Loro folds a writer's\n // commits into one change while they fall within the merge interval, which\n // would fold a restore into the edit it replaces and take that version off\n // the timeline. Changes with different messages never share a change, so\n // close the edits before it and give the restore a message of its own.\n currentDoc.commit();\n const changed = restoreDocumentContent(\n currentDoc,\n content,\n resolveRowAttribution(state),\n state.runtime.infra.documentProjectors,\n );\n if (changed) {\n currentDoc.commit({\n message: `${DOCUMENT_RESTORE_COMMIT_MESSAGE} ${crypto.randomUUID()}`,\n });\n }\n // Every operation since the last persisted base travels in this update,\n // including edits an earlier failed save left behind.\n const update = pendingDeltaSinceBase(state, currentDoc);\n const pendingUpdate =\n update.byteLength === 0 ? null : createPendingUpdateFields(update);\n // The persist keeps whatever text and fields are on screen: an edit queued\n // behind this restore has already shown its value, and publishing the\n // restored document over it would regress an editor the user is typing in.\n // The restored content is published when the local writes drain\n // (settleDocumentLocalWrite), as it is for every other write.\n const saveOptions: SaveDocumentRecordOptions = {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n };\n if (!pendingUpdate) {\n // Already this content: nothing to save, only the identity to revalidate.\n return isPersistedAndCurrent(\n state,\n generation,\n await persistDocument(state, currentDoc, {}, saveOptions, generation),\n );\n }\n const coveredVersion = encodeVersionVector(currentDoc);\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n const persisted = await persistDocument(\n state,\n currentDoc,\n { snapshotEndVersion: coveredVersion },\n { ...saveOptions, pendingUpdate },\n generation,\n );\n if (!isPersistedAndCurrent(state, generation, persisted)) {\n return false;\n }\n advancePendingBaseVersion(state, currentDoc);\n requestDocumentStoreSync(state);\n return true;\n}\n\n/**\n * Whether a persist landed on the document this write started against. A\n * refused persist, a lost compare-and-set, or a superseded generation means\n * the store now holds something else.\n */\nfunction isPersistedAndCurrent(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n persisted: Awaited<ReturnType<typeof persistDocument>>,\n): boolean {\n return (\n persisted !== null &&\n !persisted.pullContinuationSuperseded &&\n !persisted.syncIdentitySuperseded &&\n isDocumentStoreSyncGenerationCurrent(state, generation)\n );\n}\n\n/**\n * Restore the document to `content` as one ordinary local write, queued\n * behind the writes already in flight. Resolves false when the restore was\n * refused or did not persist: the store is not ready, the document cannot be\n * written, the caller's guard expired, or the save failed.\n */\nexport async function restoreDocumentStoreContent(\n state: DocumentStoreState,\n scheduleSync: () => void,\n content: DocumentRestoreContent,\n options: DocumentMutationGuard = {},\n): Promise<boolean> {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, RESTORE_FAILURE_MESSAGE, error);\n return false;\n }\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return false;\n }\n\n const writeGeneration = state.localWriteGeneration;\n let restored = false;\n // Counted as a local write in flight, like a text or field write: while the\n // count is above zero a sync pass keeps the snapshot on screen, and the\n // document is published once the count drains.\n state.pendingLocalWrites += 1;\n await chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(async () => {\n restored = await persistRestoredContent(\n state,\n writeGeneration,\n content,\n options,\n );\n })\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, RESTORE_FAILURE_MESSAGE, error);\n })\n // Always settle, so the count cannot stick above zero.\n .finally(() => {\n settleDocumentLocalWrite(state, writeGeneration);\n }),\n );\n return restored;\n}\n"]}
@@ -4,13 +4,14 @@ import { createDocumentStoreFacade, emitPersistedDocument, getOrCreateDocumentSt
4
4
  import { attachFilesToDocumentStore, replaceAttachmentInDocumentStore, } from "./attachments/index.js";
5
5
  import { removeAttachmentFromDocumentStore } from "./attachments/attachmentRemoval.js";
6
6
  import { discardDocumentStoreLocalState } from "./discard.js";
7
+ import { restoreDocumentStoreContent } from "./history/restoreContent.js";
7
8
  import { ensureDocumentStoreInitialized, ensureDocumentStoreReady, relinkDocumentStore, } from "./initialization/index.js";
8
9
  import { assertInitialContentFitsKind } from "./initialization/initialContent.js";
9
10
  import { registerInternalDocumentRelink } from "./internalRelink.js";
10
11
  import { countQueuedWrite } from "./localWriteQueue/index.js";
11
12
  import { setDocumentStructuredFields, setDocumentText } from "./mutations.js";
12
13
  import { assertLoadedDocumentStoreCanRotate } from "./rotation/rotationPreflight.js";
13
- import { addRowToDocumentStore, removeRowFromDocumentStore, updateRowInDocumentStore, } from "./rows/index.js";
14
+ import { createRowWrites } from "./rows/index.js";
14
15
  import { createDocumentStoreState, refreshAttachabilitySnapshot, resetDocumentStore, subscribeToDocumentStore, } from "./state.js";
15
16
  import { registerDocumentStoreSyncLane } from "./sync/index.js";
16
17
  import { logRevalidationScheduled } from "./sync/remoteRevalidationTelemetry.js";
@@ -171,7 +172,7 @@ function createBackingDocumentStore(localId, initialRuntime, persistence = defau
171
172
  // Local writes count as queued from the call, readiness wait included.
172
173
  const liveWrite = (write) => withLiveSyncLane(() => countQueuedWrite(state, write()));
173
174
  const store = {
174
- addRow: (fields, options) => liveWrite(() => addRowToDocumentStore(state, scheduleSync, fields, options)),
175
+ ...createRowWrites(state, scheduleSync, liveWrite),
175
176
  assertCanRotateContentKey: (proof) => withLiveSyncLane(() => assertLoadedDocumentStoreCanRotate(state, scheduleSync, proof)),
176
177
  attachFiles: (files) => liveWrite(() => attachFilesToDocumentStore(state, scheduleSync, files)),
177
178
  discardLocalState: (expectedDocumentId) => withLiveSyncLane(() => discardBackingDocumentStoreLocalState(state, scheduleSync, expectedDocumentId)),
@@ -180,16 +181,15 @@ function createBackingDocumentStore(localId, initialRuntime, persistence = defau
180
181
  hasQueuedWrites: () => state.queuedWrites > 0,
181
182
  hasUnsavedLocalEdits: () => state.unsavedLocalEdits,
182
183
  removeAttachment: (slotId) => liveWrite(() => removeAttachmentFromDocumentStore(state, scheduleSync, slotId)),
183
- removeRow: (id, options) => liveWrite(() => removeRowFromDocumentStore(state, scheduleSync, id, options)),
184
184
  replaceAttachment: (slotId, file) => liveWrite(() => replaceAttachmentInDocumentStore(state, scheduleSync, slotId, file)),
185
185
  requestRemoteSync: () => withLiveSyncLane(() => requestRemoteDocumentStoreSync(state, scheduleSync)),
186
+ restoreContent: (content, options) => liveWrite(() => restoreDocumentStoreContent(state, scheduleSync, content, options)),
186
187
  requestRemoteSyncAndWait: (signal) => requestRemoteDocumentStoreSyncAndWait(state, scheduleSync, signal),
187
188
  requestSync: () => withLiveSyncLane(() => requestOrdinaryDocumentStoreSync(state, scheduleSync)),
188
189
  relink: (input) => withLiveSyncLane(() => relinkDocumentStore(state, input, scheduleSync)),
189
190
  setStructuredFields: (kind, patch, options) => liveWrite(() => setDocumentStructuredFields(state, scheduleSync, kind, patch, options)),
190
191
  setText: (value) => liveWrite(() => setDocumentText(state, scheduleSync, value)),
191
192
  subscribe: (listener) => subscribeToDocumentStore(state, listener),
192
- updateRowFields: (id, patch, options) => liveWrite(() => updateRowInDocumentStore(state, scheduleSync, id, patch, options)),
193
193
  updateRuntime: (runtime) => updateDocumentStoreRuntime(state, runtime, scheduleSync),
194
194
  };
195
195
  return registerBackingStoreInternalRelink({ ...context, store });
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.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B,EACnB,OAAO,CACR,CAAC;IACJ,MAAM,aAAa,GAAG,2BAA2B,CAC/C,QAAQ,EACR,uBAAuB,CAAC,QAAQ,EAAE,OAAO,EAAE,iBAAiB,CAAC,EAC7D,aAAa,CACd,CAAC;IACF,IAAI,aAAa,EAAE,CAAC;QAClB,qBAAqB,CACnB,WAAW,EACX,OAAO,EACP,aAAa,EACb,iBAAiB,CAClB,CAAC;QACF,OAAO,aAAa,CAAC;IACvB,CAAC;IAED,MAAM,SAAS,GAAG,yBAAyB,CAAC,aAAa,EAAE,CAAC,CAAC;IAC7D,qBAAqB,CAAC,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,iBAAiB,CAAC,CAAC;IAC1E,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,iBAAiB,CAC/B,WAAwB,EACxB,OAAe,EACf,OAAyB,EACzB,oBAAmC,IAAI,EACvC,WAAW,GAAG,EAAE,EAChB,sBAA0C,qBAAqB,EAC/D,UAAoC,EAAE;IAEtC,MAAM,KAAK,GAAG,wBAAwB,CACpC,WAAW,EACX,OAAO,EACP,OAAO,EACP,iBAAiB,EACjB,WAAW,EACX,mBAAmB,EACnB,OAAO,CACR,CAAC;IACF,KAAK,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;IAC7B,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../../data/documents/documentKinds\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n createDocumentProjectionUserKeyResolver,\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n didDocumentProjectionKeyRuntimeChange,\n didRegainSyncPrerequisites,\n requestDocumentSyncLaneAndWait,\n} from \"../../../workflows/documents\";\nimport {\n createDocumentStoreFacade,\n emitPersistedDocument,\n getOrCreateDocumentStoreRegistry,\n registerDocumentStore,\n registerDocumentStoreIdentity,\n requestDocumentStoreSync,\n resolveDocumentStoreKey,\n takeRegisteredDocumentStore,\n} from \"../registry\";\nimport type {\n DocumentAttachmentUpload,\n DocumentStore,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentsRuntime,\n} from \"../types\";\nimport {\n attachFilesToDocumentStore,\n replaceAttachmentInDocumentStore,\n} from \"./attachments\";\nimport { removeAttachmentFromDocumentStore } from \"./attachments/attachmentRemoval\";\nimport { discardDocumentStoreLocalState } from \"./discard\";\nimport {\n ensureDocumentStoreInitialized,\n ensureDocumentStoreReady,\n relinkDocumentStore,\n} from \"./initialization\";\nimport { assertInitialContentFitsKind } from \"./initialization/initialContent\";\nimport { registerInternalDocumentRelink } from \"./internalRelink\";\nimport { countQueuedWrite } from \"./localWriteQueue\";\nimport { setDocumentStructuredFields, setDocumentText } from \"./mutations\";\nimport { assertLoadedDocumentStoreCanRotate } from \"./rotation/rotationPreflight\";\nimport {\n addRowToDocumentStore,\n removeRowFromDocumentStore,\n updateRowInDocumentStore,\n} from \"./rows\";\nimport {\n createDocumentStoreState,\n type DocumentStoreState,\n refreshAttachabilitySnapshot,\n resetDocumentStore,\n subscribeToDocumentStore,\n} from \"./state\";\nimport { registerDocumentStoreSyncLane } from \"./sync\";\nimport { logRevalidationScheduled } from \"./sync/remoteRevalidationTelemetry\";\nimport { settleDeferredStartupProbe } from \"./sync/startupProbeDeferral\";\nimport {\n allowDocumentStoreRemoteSync,\n captureDocumentStoreRemoteSyncRequestGeneration,\n captureDocumentStoreSyncLaneGeneration,\n type DocumentStoreRemoteSyncRequestGeneration,\n type DocumentStoreSyncLaneGeneration,\n didDocumentStoreRemoteSyncRequestComplete,\n hasPendingIndependentDocumentStoreRemoteSync,\n invalidateDocumentStoreRemoteSync,\n invalidateDocumentStoreSyncLane,\n isDocumentStoreRemoteSyncBlocked,\n isDocumentStoreRemoteSyncRequestGenerationCurrent,\n markDocumentStoreRemoteSyncPending,\n registerDocumentStoreRemoteSyncWaiter,\n} from \"./sync/syncGeneration\";\nimport { handleDocumentRemoteEvents } from \"./sync/syncRemoteSignals\";\n\nexport {\n discardRegisteredDocumentLocalState,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"../registry\";\n\nfunction refreshDocumentStoreSyncLane(\n state: DocumentStoreState,\n force = false,\n): void {\n if (!force && state.syncLane && !state.syncLane.isDisposed?.()) {\n return;\n }\n if (state.syncLane) {\n invalidateDocumentStoreSyncLane(state);\n }\n let syncLaneGeneration: DocumentStoreSyncLaneGeneration | null = null;\n state.syncLane = registerDocumentStoreSyncLane(\n state,\n () => syncLaneGeneration,\n );\n syncLaneGeneration = captureDocumentStoreSyncLaneGeneration(state);\n}\n\nfunction updateDocumentStoreRuntime(\n state: DocumentStoreState,\n nextRuntime: DocumentsRuntime,\n scheduleSync: () => void,\n) {\n const previousRuntime = state.runtime;\n const serverEventsReconnected =\n (nextRuntime.state.serverEventsConnectionGeneration ?? 0) >\n (previousRuntime.state.serverEventsConnectionGeneration ?? 0);\n const domainScopeChanged =\n previousRuntime.state.domainScope !== nextRuntime.state.domainScope;\n const projectionKeyRuntimeChanged = didDocumentProjectionKeyRuntimeChange(\n previousRuntime,\n nextRuntime,\n );\n if (projectionKeyRuntimeChanged) {\n state.resolveProjectionUserKey =\n createDocumentProjectionUserKeyResolver(nextRuntime);\n state.writerProjection = null;\n }\n state.runtime = nextRuntime;\n refreshDocumentStoreSyncLane(state, domainScopeChanged);\n if (domainScopeChanged) {\n state.locallyAcceptedUpdateIds = new Set();\n state.remoteUpdatePending = false;\n state.writerProjection = null;\n }\n\n if (nextRuntime.infra.dbStatus !== \"ready\") {\n if (state.snapshot.ready || state.initialized || state.initializePromise) {\n resetDocumentStore(state);\n }\n state.lastEventCount = nextRuntime.state.events.length;\n return;\n }\n\n refreshAttachabilitySnapshot(state);\n ensureDocumentStoreInitialized(state, scheduleSync);\n handleDocumentRemoteEvents(state, scheduleSync);\n\n if (state.snapshot.ready) {\n settleDeferredStartupProbe(state, serverEventsReconnected, scheduleSync);\n if (serverEventsReconnected) {\n // The invalidation stream is lossy while disconnected. Once the server\n // has acknowledged this socket's authoritative interest declaration,\n // every already-open remote document needs one HTTP probe to cover peer\n // writes made during the gap. This also closes iOS background/resume reconnects where the\n // native network source remained online throughout.\n requestRemoteDocumentStoreSync(state, scheduleSync);\n logRevalidationScheduled(state.runtime, \"reconnect\");\n } else if (didRegainSyncPrerequisites(previousRuntime, state.runtime)) {\n scheduleSync();\n }\n }\n}\n\nfunction requestRemoteDocumentStoreSync(\n state: DocumentStoreState,\n scheduleSync: () => void,\n owner: \"independent\" | \"waiter\" = \"independent\",\n): number {\n allowDocumentStoreRemoteSync(state);\n const signalSequence = markDocumentStoreRemoteSyncPending(state, owner);\n scheduleSync();\n return signalSequence;\n}\n\nfunction requestOrdinaryDocumentStoreSync(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): void {\n // A normal UI reopen is a fresh owner for remote-only work. It may recover\n // a probe that an earlier, now-unmounted owner aborted.\n if (isDocumentStoreRemoteSyncBlocked(state)) {\n requestRemoteDocumentStoreSync(state, scheduleSync);\n return;\n }\n scheduleSync();\n}\n\nfunction requestRemoteDocumentStoreSyncAndWait(\n state: DocumentStoreState,\n scheduleSync: () => void,\n signal?: AbortSignal,\n): Promise<boolean> {\n let requestGeneration: DocumentStoreRemoteSyncRequestGeneration | null = null;\n let requestedSignalSequence = 0;\n let releaseWaiter: (() => boolean) | null = null;\n const releaseRemoteSyncWaiter = (invalidate: boolean) => {\n const releasedLastWaiter = releaseWaiter?.() ?? false;\n if (\n invalidate &&\n releasedLastWaiter &&\n requestGeneration !== null &&\n isDocumentStoreRemoteSyncRequestGenerationCurrent(\n state,\n requestGeneration,\n ) &&\n !hasPendingIndependentDocumentStoreRemoteSync(state)\n ) {\n invalidateDocumentStoreRemoteSync(state);\n }\n };\n // A coordinator can be disposed and recreated while this same-scope store\n // remains registered. Refresh its handle before requesting work.\n refreshDocumentStoreSyncLane(state);\n return requestDocumentSyncLaneAndWait({\n didCompleteRequest: () =>\n requestGeneration !== null &&\n didDocumentStoreRemoteSyncRequestComplete(\n state,\n requestGeneration,\n requestedSignalSequence,\n ),\n domainScope: state.runtime.state.domainScope,\n localId: state.localId,\n request: () => {\n requestGeneration =\n captureDocumentStoreRemoteSyncRequestGeneration(state);\n releaseWaiter = registerDocumentStoreRemoteSyncWaiter(\n state,\n requestGeneration,\n );\n requestedSignalSequence = requestRemoteDocumentStoreSync(\n state,\n scheduleSync,\n \"waiter\",\n );\n },\n onInvalidated: () => releaseRemoteSyncWaiter(true),\n signal,\n }).then(\n (completed) => {\n releaseRemoteSyncWaiter(!completed);\n return completed;\n },\n (error: unknown) => {\n releaseRemoteSyncWaiter(true);\n throw error;\n },\n );\n}\n\nasync function discardBackingDocumentStoreLocalState(\n state: DocumentStoreState,\n scheduleSync: () => void,\n expectedDocumentId: string,\n) {\n try {\n return await discardDocumentStoreLocalState(state, expectedDocumentId);\n } finally {\n // Restart hydration whenever the attempt reset the store. This runs outside\n // its identity-chained task because initialization also chains writes.\n ensureDocumentStoreInitialized(state, scheduleSync);\n scheduleSync();\n }\n}\n\nfunction createLiveSyncLaneRequest(state: DocumentStoreState) {\n return <Result>(request: () => Result): Result => {\n refreshDocumentStoreSyncLane(state);\n return request();\n };\n}\n\nfunction registerBackingStoreInternalRelink(input: {\n scheduleSync: () => void;\n state: DocumentStoreState;\n store: DocumentStore;\n withLiveSyncLane: ReturnType<typeof createLiveSyncLaneRequest>;\n}): DocumentStore {\n registerInternalDocumentRelink(input.store, (relinkInput, commitSideEffect) =>\n input.withLiveSyncLane(() =>\n relinkDocumentStore(\n input.state,\n relinkInput,\n input.scheduleSync,\n commitSideEffect,\n ),\n ),\n );\n return input.store;\n}\n\nfunction createBackingStoreContext(\n localId: string,\n runtime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n documentId: string | null,\n text: string,\n documentKind: StoredDocumentKind,\n options: DocumentStoreOpenOptions,\n) {\n const state = createDocumentStoreState(\n localId,\n runtime,\n persistence,\n {\n emitPersistedDocument,\n registerDocumentIdentity: registerDocumentStoreIdentity,\n },\n documentId,\n text,\n documentKind,\n (options.remoteSyncMode ?? \"startup\") === \"startup\",\n );\n if (options.deferInitialUpdate) state.deferInitialUpdate = true;\n const { initialRows, initialStructuredFields } = options;\n assertInitialContentFitsKind({ initialStructuredFields }, documentKind);\n state.initialContent = { initialRows, initialStructuredFields };\n refreshDocumentStoreSyncLane(state);\n const scheduleSync = () => requestDocumentStoreSync(state);\n return {\n scheduleSync,\n state,\n withLiveSyncLane: createLiveSyncLaneRequest(state),\n };\n}\n\nfunction createBackingDocumentStore(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n openOptions: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const context = createBackingStoreContext(\n localId,\n initialRuntime,\n persistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n openOptions,\n );\n\n const { scheduleSync, state, withLiveSyncLane } = context;\n // Local writes count as queued from the call, readiness wait included.\n const liveWrite = <Result>(write: () => Promise<Result>) =>\n withLiveSyncLane(() => countQueuedWrite(state, write()));\n const store: DocumentStore = {\n addRow: (fields, options) =>\n liveWrite(() =>\n addRowToDocumentStore(state, scheduleSync, fields, options),\n ),\n assertCanRotateContentKey: (proof) =>\n withLiveSyncLane(() =>\n assertLoadedDocumentStoreCanRotate(state, scheduleSync, proof),\n ),\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) =>\n liveWrite(() => attachFilesToDocumentStore(state, scheduleSync, files)),\n discardLocalState: (expectedDocumentId: string) =>\n withLiveSyncLane(() =>\n discardBackingDocumentStoreLocalState(\n state,\n scheduleSync,\n expectedDocumentId,\n ),\n ),\n ensureInitialized: () =>\n withLiveSyncLane(() => ensureDocumentStoreReady(state, scheduleSync)),\n getSnapshot: () => state.snapshot,\n hasQueuedWrites: () => state.queuedWrites > 0,\n hasUnsavedLocalEdits: () => state.unsavedLocalEdits,\n removeAttachment: (slotId: string) =>\n liveWrite(() =>\n removeAttachmentFromDocumentStore(state, scheduleSync, slotId),\n ),\n removeRow: (id, options) =>\n liveWrite(() =>\n removeRowFromDocumentStore(state, scheduleSync, id, options),\n ),\n replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) =>\n liveWrite(() =>\n replaceAttachmentInDocumentStore(state, scheduleSync, slotId, file),\n ),\n requestRemoteSync: () =>\n withLiveSyncLane(() =>\n requestRemoteDocumentStoreSync(state, scheduleSync),\n ),\n requestRemoteSyncAndWait: (signal) =>\n requestRemoteDocumentStoreSyncAndWait(state, scheduleSync, signal),\n requestSync: () =>\n withLiveSyncLane(() =>\n requestOrdinaryDocumentStoreSync(state, scheduleSync),\n ),\n relink: (input) =>\n withLiveSyncLane(() => relinkDocumentStore(state, input, scheduleSync)),\n setStructuredFields: (kind, patch, options) =>\n liveWrite(() =>\n setDocumentStructuredFields(state, scheduleSync, kind, patch, options),\n ),\n setText: (value: string) =>\n liveWrite(() => setDocumentText(state, scheduleSync, value)),\n subscribe: (listener) => subscribeToDocumentStore(state, listener),\n updateRowFields: (id, patch, options) =>\n liveWrite(() =>\n updateRowInDocumentStore(state, scheduleSync, id, patch, options),\n ),\n updateRuntime: (runtime: DocumentsRuntime) =>\n updateDocumentStoreRuntime(state, runtime, scheduleSync),\n };\n return registerBackingStoreInternalRelink({ ...context, store });\n}\n\nexport function createDocumentStore(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStoreFacade {\n return createDocumentStoreFacade(\n createBackingDocumentStore(\n localId,\n initialRuntime,\n persistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n ),\n );\n}\n\nexport function getOrCreateDocumentStore(\n domainScope: DomainScope,\n localId: string,\n runtime: DocumentsRuntime,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const createBacking = () =>\n createBackingDocumentStore(\n localId,\n runtime,\n defaultDocumentsPersistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n );\n const existingStore = takeRegisteredDocumentStore(\n registry,\n resolveDocumentStoreKey(registry, localId, initialDocumentId),\n createBacking,\n );\n if (existingStore) {\n registerDocumentStore(\n domainScope,\n localId,\n existingStore,\n initialDocumentId,\n );\n return existingStore;\n }\n\n const nextStore = createDocumentStoreFacade(createBacking());\n registerDocumentStore(domainScope, localId, nextStore, initialDocumentId);\n return nextStore;\n}\n\nexport function openDocumentStore(\n domainScope: DomainScope,\n localId: string,\n runtime: DocumentsRuntime,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const store = getOrCreateDocumentStore(\n domainScope,\n localId,\n runtime,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n );\n store.updateRuntime(runtime);\n return store;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAGlF,OAAO,EACL,uCAAuC,EAEvC,2BAA2B,EAC3B,qCAAqC,EACrC,0BAA0B,EAC1B,8BAA8B,GAC/B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,gCAAgC,EAChC,qBAAqB,EACrB,6BAA6B,EAC7B,wBAAwB,EACxB,uBAAuB,EACvB,2BAA2B,GAC5B,MAAM,aAAa,CAAC;AAQrB,OAAO,EACL,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AAE;IAEtC,MAAM,KAAK,GAAG,wBAAwB,CACpC,WAAW,EACX,OAAO,EACP,OAAO,EACP,iBAAiB,EACjB,WAAW,EACX,mBAAmB,EACnB,OAAO,CACR,CAAC;IACF,KAAK,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;IAC7B,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../../data/documents/documentKinds\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n createDocumentProjectionUserKeyResolver,\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n didDocumentProjectionKeyRuntimeChange,\n didRegainSyncPrerequisites,\n requestDocumentSyncLaneAndWait,\n} from \"../../../workflows/documents\";\nimport {\n createDocumentStoreFacade,\n emitPersistedDocument,\n getOrCreateDocumentStoreRegistry,\n registerDocumentStore,\n registerDocumentStoreIdentity,\n requestDocumentStoreSync,\n resolveDocumentStoreKey,\n takeRegisteredDocumentStore,\n} from \"../registry\";\nimport type {\n DocumentAttachmentUpload,\n DocumentStore,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentsRuntime,\n} from \"../types\";\nimport {\n attachFilesToDocumentStore,\n replaceAttachmentInDocumentStore,\n} from \"./attachments\";\nimport { removeAttachmentFromDocumentStore } from \"./attachments/attachmentRemoval\";\nimport { discardDocumentStoreLocalState } from \"./discard\";\nimport { restoreDocumentStoreContent } from \"./history/restoreContent\";\nimport {\n ensureDocumentStoreInitialized,\n ensureDocumentStoreReady,\n relinkDocumentStore,\n} from \"./initialization\";\nimport { assertInitialContentFitsKind } from \"./initialization/initialContent\";\nimport { registerInternalDocumentRelink } from \"./internalRelink\";\nimport { countQueuedWrite } from \"./localWriteQueue\";\nimport { setDocumentStructuredFields, setDocumentText } from \"./mutations\";\nimport { assertLoadedDocumentStoreCanRotate } from \"./rotation/rotationPreflight\";\nimport { createRowWrites } from \"./rows\";\nimport {\n createDocumentStoreState,\n type DocumentStoreState,\n refreshAttachabilitySnapshot,\n resetDocumentStore,\n subscribeToDocumentStore,\n} from \"./state\";\nimport { registerDocumentStoreSyncLane } from \"./sync\";\nimport { logRevalidationScheduled } from \"./sync/remoteRevalidationTelemetry\";\nimport { settleDeferredStartupProbe } from \"./sync/startupProbeDeferral\";\nimport {\n allowDocumentStoreRemoteSync,\n captureDocumentStoreRemoteSyncRequestGeneration,\n captureDocumentStoreSyncLaneGeneration,\n type DocumentStoreRemoteSyncRequestGeneration,\n type DocumentStoreSyncLaneGeneration,\n didDocumentStoreRemoteSyncRequestComplete,\n hasPendingIndependentDocumentStoreRemoteSync,\n invalidateDocumentStoreRemoteSync,\n invalidateDocumentStoreSyncLane,\n isDocumentStoreRemoteSyncBlocked,\n isDocumentStoreRemoteSyncRequestGenerationCurrent,\n markDocumentStoreRemoteSyncPending,\n registerDocumentStoreRemoteSyncWaiter,\n} from \"./sync/syncGeneration\";\nimport { handleDocumentRemoteEvents } from \"./sync/syncRemoteSignals\";\n\nexport {\n discardRegisteredDocumentLocalState,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"../registry\";\n\nfunction refreshDocumentStoreSyncLane(\n state: DocumentStoreState,\n force = false,\n): void {\n if (!force && state.syncLane && !state.syncLane.isDisposed?.()) {\n return;\n }\n if (state.syncLane) {\n invalidateDocumentStoreSyncLane(state);\n }\n let syncLaneGeneration: DocumentStoreSyncLaneGeneration | null = null;\n state.syncLane = registerDocumentStoreSyncLane(\n state,\n () => syncLaneGeneration,\n );\n syncLaneGeneration = captureDocumentStoreSyncLaneGeneration(state);\n}\n\nfunction updateDocumentStoreRuntime(\n state: DocumentStoreState,\n nextRuntime: DocumentsRuntime,\n scheduleSync: () => void,\n) {\n const previousRuntime = state.runtime;\n const serverEventsReconnected =\n (nextRuntime.state.serverEventsConnectionGeneration ?? 0) >\n (previousRuntime.state.serverEventsConnectionGeneration ?? 0);\n const domainScopeChanged =\n previousRuntime.state.domainScope !== nextRuntime.state.domainScope;\n const projectionKeyRuntimeChanged = didDocumentProjectionKeyRuntimeChange(\n previousRuntime,\n nextRuntime,\n );\n if (projectionKeyRuntimeChanged) {\n state.resolveProjectionUserKey =\n createDocumentProjectionUserKeyResolver(nextRuntime);\n state.writerProjection = null;\n }\n state.runtime = nextRuntime;\n refreshDocumentStoreSyncLane(state, domainScopeChanged);\n if (domainScopeChanged) {\n state.locallyAcceptedUpdateIds = new Set();\n state.remoteUpdatePending = false;\n state.writerProjection = null;\n }\n\n if (nextRuntime.infra.dbStatus !== \"ready\") {\n if (state.snapshot.ready || state.initialized || state.initializePromise) {\n resetDocumentStore(state);\n }\n state.lastEventCount = nextRuntime.state.events.length;\n return;\n }\n\n refreshAttachabilitySnapshot(state);\n ensureDocumentStoreInitialized(state, scheduleSync);\n handleDocumentRemoteEvents(state, scheduleSync);\n\n if (state.snapshot.ready) {\n settleDeferredStartupProbe(state, serverEventsReconnected, scheduleSync);\n if (serverEventsReconnected) {\n // The invalidation stream is lossy while disconnected. Once the server\n // has acknowledged this socket's authoritative interest declaration,\n // every already-open remote document needs one HTTP probe to cover peer\n // writes made during the gap. This also closes iOS background/resume reconnects where the\n // native network source remained online throughout.\n requestRemoteDocumentStoreSync(state, scheduleSync);\n logRevalidationScheduled(state.runtime, \"reconnect\");\n } else if (didRegainSyncPrerequisites(previousRuntime, state.runtime)) {\n scheduleSync();\n }\n }\n}\n\nfunction requestRemoteDocumentStoreSync(\n state: DocumentStoreState,\n scheduleSync: () => void,\n owner: \"independent\" | \"waiter\" = \"independent\",\n): number {\n allowDocumentStoreRemoteSync(state);\n const signalSequence = markDocumentStoreRemoteSyncPending(state, owner);\n scheduleSync();\n return signalSequence;\n}\n\nfunction requestOrdinaryDocumentStoreSync(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): void {\n // A normal UI reopen is a fresh owner for remote-only work. It may recover\n // a probe that an earlier, now-unmounted owner aborted.\n if (isDocumentStoreRemoteSyncBlocked(state)) {\n requestRemoteDocumentStoreSync(state, scheduleSync);\n return;\n }\n scheduleSync();\n}\n\nfunction requestRemoteDocumentStoreSyncAndWait(\n state: DocumentStoreState,\n scheduleSync: () => void,\n signal?: AbortSignal,\n): Promise<boolean> {\n let requestGeneration: DocumentStoreRemoteSyncRequestGeneration | null = null;\n let requestedSignalSequence = 0;\n let releaseWaiter: (() => boolean) | null = null;\n const releaseRemoteSyncWaiter = (invalidate: boolean) => {\n const releasedLastWaiter = releaseWaiter?.() ?? false;\n if (\n invalidate &&\n releasedLastWaiter &&\n requestGeneration !== null &&\n isDocumentStoreRemoteSyncRequestGenerationCurrent(\n state,\n requestGeneration,\n ) &&\n !hasPendingIndependentDocumentStoreRemoteSync(state)\n ) {\n invalidateDocumentStoreRemoteSync(state);\n }\n };\n // A coordinator can be disposed and recreated while this same-scope store\n // remains registered. Refresh its handle before requesting work.\n refreshDocumentStoreSyncLane(state);\n return requestDocumentSyncLaneAndWait({\n didCompleteRequest: () =>\n requestGeneration !== null &&\n didDocumentStoreRemoteSyncRequestComplete(\n state,\n requestGeneration,\n requestedSignalSequence,\n ),\n domainScope: state.runtime.state.domainScope,\n localId: state.localId,\n request: () => {\n requestGeneration =\n captureDocumentStoreRemoteSyncRequestGeneration(state);\n releaseWaiter = registerDocumentStoreRemoteSyncWaiter(\n state,\n requestGeneration,\n );\n requestedSignalSequence = requestRemoteDocumentStoreSync(\n state,\n scheduleSync,\n \"waiter\",\n );\n },\n onInvalidated: () => releaseRemoteSyncWaiter(true),\n signal,\n }).then(\n (completed) => {\n releaseRemoteSyncWaiter(!completed);\n return completed;\n },\n (error: unknown) => {\n releaseRemoteSyncWaiter(true);\n throw error;\n },\n );\n}\n\nasync function discardBackingDocumentStoreLocalState(\n state: DocumentStoreState,\n scheduleSync: () => void,\n expectedDocumentId: string,\n) {\n try {\n return await discardDocumentStoreLocalState(state, expectedDocumentId);\n } finally {\n // Restart hydration whenever the attempt reset the store. This runs outside\n // its identity-chained task because initialization also chains writes.\n ensureDocumentStoreInitialized(state, scheduleSync);\n scheduleSync();\n }\n}\n\nfunction createLiveSyncLaneRequest(state: DocumentStoreState) {\n return <Result>(request: () => Result): Result => {\n refreshDocumentStoreSyncLane(state);\n return request();\n };\n}\n\nfunction registerBackingStoreInternalRelink(input: {\n scheduleSync: () => void;\n state: DocumentStoreState;\n store: DocumentStore;\n withLiveSyncLane: ReturnType<typeof createLiveSyncLaneRequest>;\n}): DocumentStore {\n registerInternalDocumentRelink(input.store, (relinkInput, commitSideEffect) =>\n input.withLiveSyncLane(() =>\n relinkDocumentStore(\n input.state,\n relinkInput,\n input.scheduleSync,\n commitSideEffect,\n ),\n ),\n );\n return input.store;\n}\n\nfunction createBackingStoreContext(\n localId: string,\n runtime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n documentId: string | null,\n text: string,\n documentKind: StoredDocumentKind,\n options: DocumentStoreOpenOptions,\n) {\n const state = createDocumentStoreState(\n localId,\n runtime,\n persistence,\n {\n emitPersistedDocument,\n registerDocumentIdentity: registerDocumentStoreIdentity,\n },\n documentId,\n text,\n documentKind,\n (options.remoteSyncMode ?? \"startup\") === \"startup\",\n );\n if (options.deferInitialUpdate) state.deferInitialUpdate = true;\n const { initialRows, initialStructuredFields } = options;\n assertInitialContentFitsKind({ initialStructuredFields }, documentKind);\n state.initialContent = { initialRows, initialStructuredFields };\n refreshDocumentStoreSyncLane(state);\n const scheduleSync = () => requestDocumentStoreSync(state);\n return {\n scheduleSync,\n state,\n withLiveSyncLane: createLiveSyncLaneRequest(state),\n };\n}\n\nfunction createBackingDocumentStore(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n openOptions: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const context = createBackingStoreContext(\n localId,\n initialRuntime,\n persistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n openOptions,\n );\n\n const { scheduleSync, state, withLiveSyncLane } = context;\n // Local writes count as queued from the call, readiness wait included.\n const liveWrite = <Result>(write: () => Promise<Result>) =>\n withLiveSyncLane(() => countQueuedWrite(state, write()));\n const store: DocumentStore = {\n ...createRowWrites(state, scheduleSync, liveWrite),\n assertCanRotateContentKey: (proof) =>\n withLiveSyncLane(() =>\n assertLoadedDocumentStoreCanRotate(state, scheduleSync, proof),\n ),\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) =>\n liveWrite(() => attachFilesToDocumentStore(state, scheduleSync, files)),\n discardLocalState: (expectedDocumentId: string) =>\n withLiveSyncLane(() =>\n discardBackingDocumentStoreLocalState(\n state,\n scheduleSync,\n expectedDocumentId,\n ),\n ),\n ensureInitialized: () =>\n withLiveSyncLane(() => ensureDocumentStoreReady(state, scheduleSync)),\n getSnapshot: () => state.snapshot,\n hasQueuedWrites: () => state.queuedWrites > 0,\n hasUnsavedLocalEdits: () => state.unsavedLocalEdits,\n removeAttachment: (slotId: string) =>\n liveWrite(() =>\n removeAttachmentFromDocumentStore(state, scheduleSync, slotId),\n ),\n replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) =>\n liveWrite(() =>\n replaceAttachmentInDocumentStore(state, scheduleSync, slotId, file),\n ),\n requestRemoteSync: () =>\n withLiveSyncLane(() =>\n requestRemoteDocumentStoreSync(state, scheduleSync),\n ),\n restoreContent: (content, options) =>\n liveWrite(() =>\n restoreDocumentStoreContent(state, scheduleSync, content, options),\n ),\n requestRemoteSyncAndWait: (signal) =>\n requestRemoteDocumentStoreSyncAndWait(state, scheduleSync, signal),\n requestSync: () =>\n withLiveSyncLane(() =>\n requestOrdinaryDocumentStoreSync(state, scheduleSync),\n ),\n relink: (input) =>\n withLiveSyncLane(() => relinkDocumentStore(state, input, scheduleSync)),\n setStructuredFields: (kind, patch, options) =>\n liveWrite(() =>\n setDocumentStructuredFields(state, scheduleSync, kind, patch, options),\n ),\n setText: (value: string) =>\n liveWrite(() => setDocumentText(state, scheduleSync, value)),\n subscribe: (listener) => subscribeToDocumentStore(state, listener),\n updateRuntime: (runtime: DocumentsRuntime) =>\n updateDocumentStoreRuntime(state, runtime, scheduleSync),\n };\n return registerBackingStoreInternalRelink({ ...context, store });\n}\n\nexport function createDocumentStore(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStoreFacade {\n return createDocumentStoreFacade(\n createBackingDocumentStore(\n localId,\n initialRuntime,\n persistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n ),\n );\n}\n\nexport function getOrCreateDocumentStore(\n domainScope: DomainScope,\n localId: string,\n runtime: DocumentsRuntime,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const createBacking = () =>\n createBackingDocumentStore(\n localId,\n runtime,\n defaultDocumentsPersistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n );\n const existingStore = takeRegisteredDocumentStore(\n registry,\n resolveDocumentStoreKey(registry, localId, initialDocumentId),\n createBacking,\n );\n if (existingStore) {\n registerDocumentStore(\n domainScope,\n localId,\n existingStore,\n initialDocumentId,\n );\n return existingStore;\n }\n\n const nextStore = createDocumentStoreFacade(createBacking());\n registerDocumentStore(domainScope, localId, nextStore, initialDocumentId);\n return nextStore;\n}\n\nexport function openDocumentStore(\n domainScope: DomainScope,\n localId: string,\n runtime: DocumentsRuntime,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const store = getOrCreateDocumentStore(\n domainScope,\n localId,\n runtime,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n );\n store.updateRuntime(runtime);\n return store;\n}\n"]}
@@ -23,7 +23,7 @@ function structuredMutationDurabilityOptions(options, update) {
23
23
  function isDocumentLocalWriteCurrent(state, writeGeneration, writeDoc) {
24
24
  return (state.localWriteGeneration === writeGeneration && state.doc === writeDoc);
25
25
  }
26
- function settleDocumentLocalWrite(state, writeGeneration) {
26
+ export function settleDocumentLocalWrite(state, writeGeneration) {
27
27
  // Reset/reinitialization owns the new generation's counter. A write queued
28
28
  // against the prior document must touch neither it nor the replacement doc.
29
29
  if (state.localWriteGeneration !== writeGeneration) {
@@ -1 +1 @@
1
- {"version":3,"file":"mutations.js","sourceRoot":"","sources":["mutations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpE,OAAO,EACL,0BAA0B,EAE1B,yBAAyB,GAC1B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAKvD,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,GACzB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,GAGtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AACpF,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,eAAe,GAChB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,+BAA+B,EAAE,MAAM,sBAAsB,CAAC;AACvE,OAAO,EACL,gBAAgB,EAIhB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,kCAAkC,EAAE,MAAM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C,CAAC;AAC9C,CAAC;AAED,MAAM,UAAU,2BAA2B,CACzC,KAAyB,EACzB,YAAwB,EACxB,IAAyC,EACzC,KAAmC,EACnC,UAAmC,EAAE;IAErC,8BAA8B,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;IAEpD,IAAI,CAAC,KAAK,CAAC,WAAW,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC;QACrC,OAAO,wBAAwB,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE;YAClE,IAAI,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC;gBACrD,OAAO;YACT,CAAC;YAED,OAAO,iCAAiC,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;QACxE,CAAC,CAAC,CAAC;IACL,CAAC;IAED,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC;QAC7B,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,OAAO,iCAAiC,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;AACxE,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport { encodeVersionVector, getTextValue } from \"@tearleads/loro\";\nimport {\n projectStoredDocumentState,\n type StoredDocumentKind,\n writeStoredDocumentFields,\n} from \"../../../data/documents/documentKinds\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport type {\n DocumentMutationOptions,\n DocumentStructuredFieldPatch,\n} from \"../types\";\nimport {\n ensureDocumentStoreInitialized,\n ensureDocumentStoreReady,\n} from \"./initialization\";\nimport {\n chainQueuedWrite,\n isLocalWriteSuperseded,\n issueLocalWriteTicket,\n type LocalWriteKey,\n type LocalWriteTicket,\n} from \"./localWriteQueue\";\nimport { revalidateDocumentMutationIdentity } from \"./mutationIdentityRevalidation\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"./persistence\";\nimport { reportDocumentStoreWriteFailure } from \"./reportWriteFailure\";\nimport {\n canWriteDocument,\n type DocumentState,\n type DocumentStoreState,\n type SaveDocumentRecordOptions,\n setDocumentSnapshot,\n setReadySnapshot,\n} from \"./state\";\nimport { captureDocumentStoreSyncGeneration } from \"./sync/syncGeneration\";\n\n// Fixed literals: a reported message must never carry document text or ids.\nconst TEXT_FAILURE_MESSAGE = \"Documents: local text persist failed\";\nconst FIELD_FAILURE_MESSAGE = \"Documents: local field persist failed\";\n\nfunction structuredMutationDurabilityOptions(\n options: DocumentMutationOptions,\n update: Uint8Array,\n): Pick<SaveDocumentRecordOptions, \"historyUpdates\" | \"pendingUpdate\"> | null {\n if (options.deferRemoteSync) {\n return { historyUpdates: [bytesToBase64(update)] };\n }\n const pendingUpdate = createPendingUpdateFields(update);\n return pendingUpdate ? { pendingUpdate } : null;\n}\n\nfunction isDocumentLocalWriteCurrent(\n state: DocumentStoreState,\n writeGeneration: number,\n writeDoc: DocumentState,\n): boolean {\n return (\n state.localWriteGeneration === writeGeneration && state.doc === writeDoc\n );\n}\n\nfunction settleDocumentLocalWrite(\n state: DocumentStoreState,\n writeGeneration: number,\n): void {\n // Reset/reinitialization owns the new generation's counter. A write queued\n // against the prior document must touch neither it nor the replacement doc.\n if (state.localWriteGeneration !== writeGeneration) {\n return;\n }\n\n state.pendingLocalWrites = Math.max(0, state.pendingLocalWrites - 1);\n if (state.pendingLocalWrites !== 0 || !state.doc) {\n return;\n }\n\n // A sync pass or rotation may merge remote content while preserving the\n // controlled editor value. Publish the authoritative doc once typing drains;\n // setReadySnapshot is a no-op when the optimistic projection already matches.\n setReadySnapshot(state, state.doc, state.snapshot.syncing);\n}\n\nfunction publishDocumentTextSnapshot(\n state: DocumentStoreState,\n value: string,\n): void {\n setDocumentSnapshot(state, {\n ...state.snapshot,\n text: value,\n title: projectStoredDocumentState(\n {\n documentKind: state.snapshot.documentKind,\n structuredFields: state.snapshot.structuredFields,\n text: value,\n rows: state.snapshot.rows.map((row) => ({\n id: row.id,\n fields: row.fields,\n })),\n },\n state.runtime.infra.documentProjectors,\n ).title,\n });\n}\n\nasync function writeDocumentText(\n state: DocumentStoreState,\n writeGeneration: number,\n ticket: LocalWriteTicket,\n value: string,\n): Promise<void> {\n // A newer queued setText carries the whole latest value, and its persist\n // exports every op since pendingBaseVersion: this one has nothing to add.\n if (\n isLocalWriteSuperseded(state, ticket) ||\n state.localWriteGeneration !== writeGeneration ||\n !state.doc ||\n !canWriteDocument(state)\n ) {\n return;\n }\n const writeDoc = state.doc;\n const syncGeneration = captureDocumentStoreSyncGeneration(state, writeDoc);\n if (!syncGeneration) {\n return;\n }\n\n const textChanged = getTextValue(writeDoc) !== value;\n // Equal text still persists when an earlier write applied ops that never\n // became durable (its save failed, and the write in between was superseded):\n // this write is the last one queued to carry them. Without such edits it\n // only revalidates, so a deferred birth keeps riding the next real edit.\n if (!textChanged && !state.unsavedLocalEdits) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n if (textChanged) {\n writeDoc.getText(\"text\").update(value);\n }\n const update = pendingDeltaSinceBase(state, writeDoc);\n // Captured at delta time: the enqueued row proves durable coverage up\n // to exactly this version, so this is the frontier the persist may\n // publish (a raced later edit publishes its own on its own persist).\n const coveredVersion = encodeVersionVector(writeDoc);\n const pendingUpdate = createPendingUpdateFields(update);\n if (!pendingUpdate) {\n // Nothing outstanding to enqueue: still adopt a relinked identity.\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n const persisted = await persistDocument(\n state,\n writeDoc,\n { snapshotEndVersion: coveredVersion },\n { pendingUpdate, preserveSnapshotText: true },\n syncGeneration,\n );\n if (\n !persisted ||\n !isDocumentLocalWriteCurrent(state, writeGeneration, writeDoc)\n ) {\n return;\n }\n advancePendingBaseVersion(state, writeDoc);\n requestDocumentStoreSync(state);\n}\n\nfunction queueDocumentTextWrite(\n state: DocumentStoreState,\n value: string,\n): Promise<void> {\n if (!state.doc) {\n return Promise.resolve();\n }\n const writeGeneration = state.localWriteGeneration;\n // Supersedes every text write still queued: only the newest reaches SQLite.\n // Field, row, and attachment writes never supersede a text write.\n const ticket = issueLocalWriteTicket(state, [\"text\"]);\n\n // Mark a local edit as in flight SYNCHRONOUSLY, before chaining, so a sync\n // pass that runs during this burst sees pendingLocalWrites > 0 and preserves\n // the optimistic snapshot instead of regressing it to a stale doc read.\n state.pendingLocalWrites += 1;\n return chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(() => writeDocumentText(state, writeGeneration, ticket, value))\n // The user is already looking at this text: publishDocumentTextSnapshot ran\n // before the chain, and nothing downstream surfaces a failed persist.\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, TEXT_FAILURE_MESSAGE, error);\n })\n // Always settle, even on supersession, the value-equality short-circuit,\n // or a throw, so the current document's counter cannot stick non-zero.\n // The generation guard keeps a reset write from decrementing a\n // replacement generation.\n .finally(() => {\n settleDocumentLocalWrite(state, writeGeneration);\n }),\n );\n}\n\nfunction publishDocumentStructuredFieldSnapshot(\n state: DocumentStoreState,\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n): void {\n const nextStructuredFields: Record<string, unknown> = {\n ...state.snapshot.structuredFields,\n };\n for (const [field, value] of Object.entries(patch)) {\n if (value === undefined) {\n delete nextStructuredFields[field];\n } else {\n nextStructuredFields[field] = value;\n }\n }\n const projectedState = projectStoredDocumentState(\n {\n documentKind: kind,\n structuredFields: nextStructuredFields,\n text: state.snapshot.text,\n rows: state.snapshot.rows.map((row) => ({\n id: row.id,\n fields: row.fields,\n })),\n },\n state.runtime.infra.documentProjectors,\n );\n\n setDocumentSnapshot(state, {\n ...state.snapshot,\n documentKind: projectedState.documentKind,\n fieldValidationIssues: projectedState.fieldValidationIssues,\n structuredFields: projectedState.structuredFields,\n title: projectedState.title,\n });\n}\n\ninterface StructuredFieldWrite {\n readonly kind: Exclude<StoredDocumentKind, \"note\">;\n readonly options: DocumentMutationOptions;\n readonly patch: DocumentStructuredFieldPatch;\n /** Deferred or guarded writes neither supersede nor coalesce. */\n readonly ticket: LocalWriteTicket | null;\n readonly writeGeneration: number;\n}\n\nasync function writeDocumentStructuredFields(\n state: DocumentStoreState,\n write: StructuredFieldWrite,\n): Promise<void> {\n const { kind, options, patch, ticket, writeGeneration } = write;\n // Newer queued patches set every field of this one, and the one persisting\n // them exports every op since pendingBaseVersion: nothing to add here.\n if (\n isLocalWriteSuperseded(state, ticket) ||\n state.localWriteGeneration !== writeGeneration ||\n !state.doc ||\n !canWriteDocument(state)\n ) {\n return;\n }\n const writeDoc = state.doc;\n const syncGeneration = captureDocumentStoreSyncGeneration(state, writeDoc);\n if (!syncGeneration) {\n return;\n }\n\n if (options.stillCurrent?.() === false) return;\n writeStoredDocumentFields(\n writeDoc,\n kind,\n patch,\n state.runtime.infra.documentProjectors,\n );\n const update = pendingDeltaSinceBase(state, writeDoc);\n if (update.byteLength === 0) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n // Captured at delta time: the durable row written below (queue\n // dual-write or in-mutation tail append) proves coverage up to exactly\n // this version, so it is the frontier this persist may publish.\n const coveredVersion = encodeVersionVector(writeDoc);\n const durabilityOptions = structuredMutationDurabilityOptions(\n options,\n update,\n );\n if (!durabilityOptions) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n // A deferred write advances the record's content frontier AHEAD of the\n // outgoing queue (the op is re-derived by the next edit). Its delta\n // rides in the persist's own claimed mutation as a durable-history tail\n // row written before the record — the tail is the only content store,\n // so the record frontier must never durably lead the tail row that\n // holds its content. Passed as an option (no pre-persist await) so this\n // write adds no extra hop that would change cross-store interleaving.\n const persisted = await persistDocument(\n state,\n writeDoc,\n { snapshotEndVersion: coveredVersion },\n {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n ...durabilityOptions,\n },\n syncGeneration,\n );\n if (\n !persisted ||\n !isDocumentLocalWriteCurrent(state, writeGeneration, writeDoc)\n ) {\n return;\n }\n if (options.deferRemoteSync) {\n // The history tail now holds the delta; the next edit enqueues it.\n state.unsavedLocalEdits = false;\n return;\n }\n advancePendingBaseVersion(state, writeDoc);\n requestDocumentStoreSync(state);\n}\n\nfunction queueDocumentStructuredFieldWrite(\n state: DocumentStoreState,\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options: DocumentMutationOptions = {},\n): Promise<void> {\n if (!state.doc) {\n return Promise.resolve();\n }\n try {\n if (options.stillCurrent?.() === false) return Promise.resolve();\n } catch (error) {\n reportDocumentStoreWriteFailure(state, FIELD_FAILURE_MESSAGE, error);\n return Promise.resolve();\n }\n // Guarded writes publish only after admission, never while still queued.\n if (!options.stillCurrent) {\n publishDocumentStructuredFieldSnapshot(state, kind, patch);\n }\n const write: StructuredFieldWrite = {\n kind,\n options,\n patch,\n // A guarded write may later refuse, and a deferred persist is history-only:\n // neither can stand in for another write's enqueue or be coalesced away.\n ticket:\n options.deferRemoteSync || options.stillCurrent\n ? null\n : issueLocalWriteTicket(\n state,\n Object.keys(patch).map((field): LocalWriteKey => `field:${field}`),\n ),\n writeGeneration: state.localWriteGeneration,\n };\n\n // See queueDocumentTextWrite: gate sync-lane text/field republish on the same\n // in-flight-write counter so structured edits get the identical protection.\n state.pendingLocalWrites += 1;\n return chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(() => writeDocumentStructuredFields(state, write))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, FIELD_FAILURE_MESSAGE, error);\n })\n // See queueDocumentTextWrite: the final current-generation write also\n // republishes any remote content that was held during the optimistic burst.\n .finally(() => {\n settleDocumentLocalWrite(state, write.writeGeneration);\n }),\n );\n}\n\nexport function setDocumentText(\n state: DocumentStoreState,\n scheduleSync: () => void,\n value: string,\n): Promise<void> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (!state.initialized || !state.doc) {\n return ensureDocumentStoreReady(state, scheduleSync).then((ready) => {\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n publishDocumentTextSnapshot(state, value);\n return queueDocumentTextWrite(state, value);\n });\n }\n\n if (!canWriteDocument(state)) {\n return Promise.resolve();\n }\n\n publishDocumentTextSnapshot(state, value);\n return queueDocumentTextWrite(state, value);\n}\n\nexport function setDocumentStructuredFields(\n state: DocumentStoreState,\n scheduleSync: () => void,\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options: DocumentMutationOptions = {},\n): Promise<void> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (!state.initialized || !state.doc) {\n return ensureDocumentStoreReady(state, scheduleSync).then((ready) => {\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n return queueDocumentStructuredFieldWrite(state, kind, patch, options);\n });\n }\n\n if (!canWriteDocument(state)) {\n return Promise.resolve();\n }\n\n return queueDocumentStructuredFieldWrite(state, kind, patch, options);\n}\n"]}
1
+ {"version":3,"file":"mutations.js","sourceRoot":"","sources":["mutations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpE,OAAO,EACL,0BAA0B,EAE1B,yBAAyB,GAC1B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;A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,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;AACxE,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport { encodeVersionVector, getTextValue } from \"@tearleads/loro\";\nimport {\n projectStoredDocumentState,\n type StoredDocumentKind,\n writeStoredDocumentFields,\n} from \"../../../data/documents/documentKinds\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport type {\n DocumentMutationOptions,\n DocumentStructuredFieldPatch,\n} from \"../types\";\nimport {\n ensureDocumentStoreInitialized,\n ensureDocumentStoreReady,\n} from \"./initialization\";\nimport {\n chainQueuedWrite,\n isLocalWriteSuperseded,\n issueLocalWriteTicket,\n type LocalWriteKey,\n type LocalWriteTicket,\n} from \"./localWriteQueue\";\nimport { revalidateDocumentMutationIdentity } from \"./mutationIdentityRevalidation\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"./persistence\";\nimport { reportDocumentStoreWriteFailure } from \"./reportWriteFailure\";\nimport {\n canWriteDocument,\n type DocumentState,\n type DocumentStoreState,\n type SaveDocumentRecordOptions,\n setDocumentSnapshot,\n setReadySnapshot,\n} from \"./state\";\nimport { captureDocumentStoreSyncGeneration } from \"./sync/syncGeneration\";\n\n// Fixed literals: a reported message must never carry document text or ids.\nconst TEXT_FAILURE_MESSAGE = \"Documents: local text persist failed\";\nconst FIELD_FAILURE_MESSAGE = \"Documents: local field persist failed\";\n\nfunction structuredMutationDurabilityOptions(\n options: DocumentMutationOptions,\n update: Uint8Array,\n): Pick<SaveDocumentRecordOptions, \"historyUpdates\" | \"pendingUpdate\"> | null {\n if (options.deferRemoteSync) {\n return { historyUpdates: [bytesToBase64(update)] };\n }\n const pendingUpdate = createPendingUpdateFields(update);\n return pendingUpdate ? { pendingUpdate } : null;\n}\n\nfunction isDocumentLocalWriteCurrent(\n state: DocumentStoreState,\n writeGeneration: number,\n writeDoc: DocumentState,\n): boolean {\n return (\n state.localWriteGeneration === writeGeneration && state.doc === writeDoc\n );\n}\n\nexport function settleDocumentLocalWrite(\n state: DocumentStoreState,\n writeGeneration: number,\n): void {\n // Reset/reinitialization owns the new generation's counter. A write queued\n // against the prior document must touch neither it nor the replacement doc.\n if (state.localWriteGeneration !== writeGeneration) {\n return;\n }\n\n state.pendingLocalWrites = Math.max(0, state.pendingLocalWrites - 1);\n if (state.pendingLocalWrites !== 0 || !state.doc) {\n return;\n }\n\n // A sync pass or rotation may merge remote content while preserving the\n // controlled editor value. Publish the authoritative doc once typing drains;\n // setReadySnapshot is a no-op when the optimistic projection already matches.\n setReadySnapshot(state, state.doc, state.snapshot.syncing);\n}\n\nfunction publishDocumentTextSnapshot(\n state: DocumentStoreState,\n value: string,\n): void {\n setDocumentSnapshot(state, {\n ...state.snapshot,\n text: value,\n title: projectStoredDocumentState(\n {\n documentKind: state.snapshot.documentKind,\n structuredFields: state.snapshot.structuredFields,\n text: value,\n rows: state.snapshot.rows.map((row) => ({\n id: row.id,\n fields: row.fields,\n })),\n },\n state.runtime.infra.documentProjectors,\n ).title,\n });\n}\n\nasync function writeDocumentText(\n state: DocumentStoreState,\n writeGeneration: number,\n ticket: LocalWriteTicket,\n value: string,\n): Promise<void> {\n // A newer queued setText carries the whole latest value, and its persist\n // exports every op since pendingBaseVersion: this one has nothing to add.\n if (\n isLocalWriteSuperseded(state, ticket) ||\n state.localWriteGeneration !== writeGeneration ||\n !state.doc ||\n !canWriteDocument(state)\n ) {\n return;\n }\n const writeDoc = state.doc;\n const syncGeneration = captureDocumentStoreSyncGeneration(state, writeDoc);\n if (!syncGeneration) {\n return;\n }\n\n const textChanged = getTextValue(writeDoc) !== value;\n // Equal text still persists when an earlier write applied ops that never\n // became durable (its save failed, and the write in between was superseded):\n // this write is the last one queued to carry them. Without such edits it\n // only revalidates, so a deferred birth keeps riding the next real edit.\n if (!textChanged && !state.unsavedLocalEdits) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n if (textChanged) {\n writeDoc.getText(\"text\").update(value);\n }\n const update = pendingDeltaSinceBase(state, writeDoc);\n // Captured at delta time: the enqueued row proves durable coverage up\n // to exactly this version, so this is the frontier the persist may\n // publish (a raced later edit publishes its own on its own persist).\n const coveredVersion = encodeVersionVector(writeDoc);\n const pendingUpdate = createPendingUpdateFields(update);\n if (!pendingUpdate) {\n // Nothing outstanding to enqueue: still adopt a relinked identity.\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n const persisted = await persistDocument(\n state,\n writeDoc,\n { snapshotEndVersion: coveredVersion },\n { pendingUpdate, preserveSnapshotText: true },\n syncGeneration,\n );\n if (\n !persisted ||\n !isDocumentLocalWriteCurrent(state, writeGeneration, writeDoc)\n ) {\n return;\n }\n advancePendingBaseVersion(state, writeDoc);\n requestDocumentStoreSync(state);\n}\n\nfunction queueDocumentTextWrite(\n state: DocumentStoreState,\n value: string,\n): Promise<void> {\n if (!state.doc) {\n return Promise.resolve();\n }\n const writeGeneration = state.localWriteGeneration;\n // Supersedes every text write still queued: only the newest reaches SQLite.\n // Field, row, and attachment writes never supersede a text write.\n const ticket = issueLocalWriteTicket(state, [\"text\"]);\n\n // Mark a local edit as in flight SYNCHRONOUSLY, before chaining, so a sync\n // pass that runs during this burst sees pendingLocalWrites > 0 and preserves\n // the optimistic snapshot instead of regressing it to a stale doc read.\n state.pendingLocalWrites += 1;\n return chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(() => writeDocumentText(state, writeGeneration, ticket, value))\n // The user is already looking at this text: publishDocumentTextSnapshot ran\n // before the chain, and nothing downstream surfaces a failed persist.\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, TEXT_FAILURE_MESSAGE, error);\n })\n // Always settle, even on supersession, the value-equality short-circuit,\n // or a throw, so the current document's counter cannot stick non-zero.\n // The generation guard keeps a reset write from decrementing a\n // replacement generation.\n .finally(() => {\n settleDocumentLocalWrite(state, writeGeneration);\n }),\n );\n}\n\nfunction publishDocumentStructuredFieldSnapshot(\n state: DocumentStoreState,\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n): void {\n const nextStructuredFields: Record<string, unknown> = {\n ...state.snapshot.structuredFields,\n };\n for (const [field, value] of Object.entries(patch)) {\n if (value === undefined) {\n delete nextStructuredFields[field];\n } else {\n nextStructuredFields[field] = value;\n }\n }\n const projectedState = projectStoredDocumentState(\n {\n documentKind: kind,\n structuredFields: nextStructuredFields,\n text: state.snapshot.text,\n rows: state.snapshot.rows.map((row) => ({\n id: row.id,\n fields: row.fields,\n })),\n },\n state.runtime.infra.documentProjectors,\n );\n\n setDocumentSnapshot(state, {\n ...state.snapshot,\n documentKind: projectedState.documentKind,\n fieldValidationIssues: projectedState.fieldValidationIssues,\n structuredFields: projectedState.structuredFields,\n title: projectedState.title,\n });\n}\n\ninterface StructuredFieldWrite {\n readonly kind: Exclude<StoredDocumentKind, \"note\">;\n readonly options: DocumentMutationOptions;\n readonly patch: DocumentStructuredFieldPatch;\n /** Deferred or guarded writes neither supersede nor coalesce. */\n readonly ticket: LocalWriteTicket | null;\n readonly writeGeneration: number;\n}\n\nasync function writeDocumentStructuredFields(\n state: DocumentStoreState,\n write: StructuredFieldWrite,\n): Promise<void> {\n const { kind, options, patch, ticket, writeGeneration } = write;\n // Newer queued patches set every field of this one, and the one persisting\n // them exports every op since pendingBaseVersion: nothing to add here.\n if (\n isLocalWriteSuperseded(state, ticket) ||\n state.localWriteGeneration !== writeGeneration ||\n !state.doc ||\n !canWriteDocument(state)\n ) {\n return;\n }\n const writeDoc = state.doc;\n const syncGeneration = captureDocumentStoreSyncGeneration(state, writeDoc);\n if (!syncGeneration) {\n return;\n }\n\n if (options.stillCurrent?.() === false) return;\n writeStoredDocumentFields(\n writeDoc,\n kind,\n patch,\n state.runtime.infra.documentProjectors,\n );\n const update = pendingDeltaSinceBase(state, writeDoc);\n if (update.byteLength === 0) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n // Captured at delta time: the durable row written below (queue\n // dual-write or in-mutation tail append) proves coverage up to exactly\n // this version, so it is the frontier this persist may publish.\n const coveredVersion = encodeVersionVector(writeDoc);\n const durabilityOptions = structuredMutationDurabilityOptions(\n options,\n update,\n );\n if (!durabilityOptions) {\n await revalidateDocumentMutationIdentity({\n currentDoc: writeDoc,\n generation: syncGeneration,\n state,\n });\n return;\n }\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n // A deferred write advances the record's content frontier AHEAD of the\n // outgoing queue (the op is re-derived by the next edit). Its delta\n // rides in the persist's own claimed mutation as a durable-history tail\n // row written before the record — the tail is the only content store,\n // so the record frontier must never durably lead the tail row that\n // holds its content. Passed as an option (no pre-persist await) so this\n // write adds no extra hop that would change cross-store interleaving.\n const persisted = await persistDocument(\n state,\n writeDoc,\n { snapshotEndVersion: coveredVersion },\n {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n ...durabilityOptions,\n },\n syncGeneration,\n );\n if (\n !persisted ||\n !isDocumentLocalWriteCurrent(state, writeGeneration, writeDoc)\n ) {\n return;\n }\n if (options.deferRemoteSync) {\n // The history tail now holds the delta; the next edit enqueues it.\n state.unsavedLocalEdits = false;\n return;\n }\n advancePendingBaseVersion(state, writeDoc);\n requestDocumentStoreSync(state);\n}\n\nfunction queueDocumentStructuredFieldWrite(\n state: DocumentStoreState,\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options: DocumentMutationOptions = {},\n): Promise<void> {\n if (!state.doc) {\n return Promise.resolve();\n }\n try {\n if (options.stillCurrent?.() === false) return Promise.resolve();\n } catch (error) {\n reportDocumentStoreWriteFailure(state, FIELD_FAILURE_MESSAGE, error);\n return Promise.resolve();\n }\n // Guarded writes publish only after admission, never while still queued.\n if (!options.stillCurrent) {\n publishDocumentStructuredFieldSnapshot(state, kind, patch);\n }\n const write: StructuredFieldWrite = {\n kind,\n options,\n patch,\n // A guarded write may later refuse, and a deferred persist is history-only:\n // neither can stand in for another write's enqueue or be coalesced away.\n ticket:\n options.deferRemoteSync || options.stillCurrent\n ? null\n : issueLocalWriteTicket(\n state,\n Object.keys(patch).map((field): LocalWriteKey => `field:${field}`),\n ),\n writeGeneration: state.localWriteGeneration,\n };\n\n // See queueDocumentTextWrite: gate sync-lane text/field republish on the same\n // in-flight-write counter so structured edits get the identical protection.\n state.pendingLocalWrites += 1;\n return chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(() => writeDocumentStructuredFields(state, write))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, FIELD_FAILURE_MESSAGE, error);\n })\n // See queueDocumentTextWrite: the final current-generation write also\n // republishes any remote content that was held during the optimistic burst.\n .finally(() => {\n settleDocumentLocalWrite(state, write.writeGeneration);\n }),\n );\n}\n\nexport function setDocumentText(\n state: DocumentStoreState,\n scheduleSync: () => void,\n value: string,\n): Promise<void> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (!state.initialized || !state.doc) {\n return ensureDocumentStoreReady(state, scheduleSync).then((ready) => {\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n publishDocumentTextSnapshot(state, value);\n return queueDocumentTextWrite(state, value);\n });\n }\n\n if (!canWriteDocument(state)) {\n return Promise.resolve();\n }\n\n publishDocumentTextSnapshot(state, value);\n return queueDocumentTextWrite(state, value);\n}\n\nexport function setDocumentStructuredFields(\n state: DocumentStoreState,\n scheduleSync: () => void,\n kind: Exclude<StoredDocumentKind, \"note\">,\n patch: DocumentStructuredFieldPatch,\n options: DocumentMutationOptions = {},\n): Promise<void> {\n ensureDocumentStoreInitialized(state, scheduleSync);\n\n if (!state.initialized || !state.doc) {\n return ensureDocumentStoreReady(state, scheduleSync).then((ready) => {\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n return queueDocumentStructuredFieldWrite(state, kind, patch, options);\n });\n }\n\n if (!canWriteDocument(state)) {\n return Promise.resolve();\n }\n\n return queueDocumentStructuredFieldWrite(state, kind, patch, options);\n}\n"]}
@@ -131,4 +131,12 @@ export async function removeRowFromDocumentStore(state, scheduleSync, id, option
131
131
  }
132
132
  await queueRowMutation(state, (doc) => removeDocumentRow(doc, id), options);
133
133
  }
134
+ /** The store's row writes, each counted and run on the live sync lane. */
135
+ export function createRowWrites(state, scheduleSync, liveWrite) {
136
+ return {
137
+ addRow: (fields, options) => liveWrite(() => addRowToDocumentStore(state, scheduleSync, fields, options)),
138
+ removeRow: (id, options) => liveWrite(() => removeRowFromDocumentStore(state, scheduleSync, id, options)),
139
+ updateRowFields: (id, patch, options) => liveWrite(() => updateRowInDocumentStore(state, scheduleSync, id, patch, options)),
140
+ };
141
+ }
134
142
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,GACrB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAE1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,kCAAkC,EAAE,MAAM,iCAAiC,CAAC;AACrF,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,eAAe,GAChB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,+BAA+B,EAAE,MAAM,uB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G,KAAK,CAAC;IACxD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,+BAA+B,CAAC,KAAK,EAAE,mBAAmB,EAAE,KAAK,CAAC,CAAC;QACnE,OAAO;IACT,CAAC;IAED,IAAI,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC;QACrD,OAAO;IACT,CAAC;IAED,MAAM,gBAAgB,CACpB,KAAK,EACL,CAAC,GAAG,EAAE,EAAE,CAAC,oBAAoB,CAAC,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,qBAAqB,CAAC,KAAK,CAAC,CAAC,EAC3E,OAAO,CACR,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC9C,KAAyB,EACzB,YAAwB,EACxB,EAAU,EACV,UAAiC,EAAE;IAEnC,IAAI,KAAc,CAAC;IACnB,IAAI,CAAC;QACH,KAAK,GAAG,MAAM,wBAAwB,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;QAC5D,IAAI,OAAO,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;YAAE,KAAK,GAAG,KAAK,CAAC;IACxD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,+BAA+B,CAAC,KAAK,EAAE,mBAAmB,EAAE,KAAK,CAAC,CAAC;QACnE,OAAO;IACT,CAAC;IAED,IAAI,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC;QACrD,OAAO;IACT,CAAC;IAED,MAAM,gBAAgB,CAAC,KAAK,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,iBAAiB,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import { encodeVersionVector } from \"@tearleads/loro\";\nimport {\n addDocumentRow,\n createDocumentRowId,\n removeDocumentRow,\n setDocumentRowFields,\n} from \"../../../../data/documents/documentRowList\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport type { DocumentMutationGuard } from \"../../types\";\nimport { ensureDocumentStoreReady } from \"../initialization\";\nimport { chainQueuedWrite } from \"../localWriteQueue\";\nimport { revalidateDocumentMutationIdentity } from \"../mutationIdentityRevalidation\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"../persistence\";\nimport { reportDocumentStoreWriteFailure } from \"../reportWriteFailure\";\nimport {\n canWriteDocument,\n type DocumentState,\n type DocumentStoreState,\n} from \"../state\";\nimport {\n captureDocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { resolveRowAttribution } from \"./rowAttribution\";\n\n// Fixed literal: a reported message must never carry row ids or field values.\nconst ROW_FAILURE_MESSAGE = \"Documents: row mutation failed\";\n\nasync function persistRowMutation(\n state: DocumentStoreState,\n expectedLocalWriteGeneration: number,\n mutate: (doc: DocumentState) => boolean,\n options: DocumentMutationGuard,\n): Promise<void> {\n if (state.localWriteGeneration !== expectedLocalWriteGeneration) {\n return;\n }\n const currentDoc = state.doc;\n if (!currentDoc || !canWriteDocument(state)) {\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n if (options.stillCurrent?.() === false) return;\n if (!mutate(currentDoc)) {\n await revalidateDocumentMutationIdentity({ currentDoc, generation, state });\n return;\n }\n\n const update = pendingDeltaSinceBase(state, currentDoc);\n if (update.byteLength === 0) {\n await revalidateDocumentMutationIdentity({ currentDoc, generation, state });\n return;\n }\n // Captured at delta time: the enqueued row proves coverage up to exactly\n // this version, so it is the frontier the persist below may publish.\n const coveredVersion = encodeVersionVector(currentDoc);\n\n const pendingUpdate = createPendingUpdateFields(update);\n if (!pendingUpdate) {\n await revalidateDocumentMutationIdentity({ currentDoc, generation, state });\n return;\n }\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n // Row writes change neither prose nor structured fields; setReadySnapshot\n // always re-derives rows from the doc, so preserve the text/structured fields\n // in case this write overlaps an in-flight keystroke elsewhere.\n const persisted = await persistDocument(\n state,\n currentDoc,\n { snapshotEndVersion: coveredVersion },\n {\n pendingUpdate,\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n },\n generation,\n );\n if (\n !persisted ||\n persisted.pullContinuationSuperseded ||\n persisted.syncIdentitySuperseded ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n // Refused: the document was deleted while this persist was queued\n // and the store is cleared — no state advance, no sync request.\n return;\n }\n advancePendingBaseVersion(state, currentDoc);\n requestDocumentStoreSync(state);\n}\n\nfunction queueRowMutation(\n state: DocumentStoreState,\n mutate: (doc: DocumentState) => boolean,\n options: DocumentMutationGuard,\n): Promise<void> {\n const writeGeneration = state.localWriteGeneration;\n // Unlike text/structured-field writes, row writes intentionally do NOT bump\n // `state.pendingLocalWrites`: rows are never in the optimistic-preserve set —\n // `setReadySnapshot` always re-derives them from the doc — so there is no\n // optimistic snapshot for a concurrent sync pass to clobber. Input smoothness\n // during rapid edits is handled in the app layer (useDocumentRowEditing).\n return chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(() => persistRowMutation(state, writeGeneration, mutate, options))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n }),\n );\n}\n\nexport async function addRowToDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n fields: Readonly<Record<string, string>>,\n options: DocumentMutationGuard = {},\n): Promise<string> {\n const id = createDocumentRowId();\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n return id;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return id;\n }\n\n await queueRowMutation(\n state,\n (doc) => {\n addDocumentRow(doc, id, fields, resolveRowAttribution(state));\n return true;\n },\n options,\n );\n return id;\n}\n\nexport async function updateRowInDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n id: string,\n patch: Readonly<Record<string, string>>,\n options: DocumentMutationGuard = {},\n): Promise<void> {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n await queueRowMutation(\n state,\n (doc) => setDocumentRowFields(doc, id, patch, resolveRowAttribution(state)),\n options,\n );\n}\n\nexport async function removeRowFromDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n id: string,\n options: DocumentMutationGuard = {},\n): Promise<void> {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n await queueRowMutation(state, (doc) => removeDocumentRow(doc, id), options);\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,GACrB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAE1D,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE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CAAC,GAAG,EAAE,EAAE,CAAC,iBAAiB,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;AAC9E,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,eAAe,CAC7B,KAAyB,EACzB,YAAwB,EACxB,SAAoE;IAEpE,OAAO;QACL,MAAM,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,CAC1B,SAAS,CAAC,GAAG,EAAE,CACb,qBAAqB,CAAC,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,CAC5D;QACH,SAAS,EAAE,CAAC,EAAE,EAAE,OAAO,EAAE,EAAE,CACzB,SAAS,CAAC,GAAG,EAAE,CACb,0BAA0B,CAAC,KAAK,EAAE,YAAY,EAAE,EAAE,EAAE,OAAO,CAAC,CAC7D;QACH,eAAe,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CACtC,SAAS,CAAC,GAAG,EAAE,CACb,wBAAwB,CAAC,KAAK,EAAE,YAAY,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,CAClE;KACJ,CAAC;AACJ,CAAC","sourcesContent":["import { encodeVersionVector } from \"@tearleads/loro\";\nimport {\n addDocumentRow,\n createDocumentRowId,\n removeDocumentRow,\n setDocumentRowFields,\n} from \"../../../../data/documents/documentRowList\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport type { DocumentMutationGuard, DocumentStore } from \"../../types\";\nimport { ensureDocumentStoreReady } from \"../initialization\";\nimport { chainQueuedWrite } from \"../localWriteQueue\";\nimport { revalidateDocumentMutationIdentity } from \"../mutationIdentityRevalidation\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"../persistence\";\nimport { reportDocumentStoreWriteFailure } from \"../reportWriteFailure\";\nimport {\n canWriteDocument,\n type DocumentState,\n type DocumentStoreState,\n} from \"../state\";\nimport {\n captureDocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { resolveRowAttribution } from \"./rowAttribution\";\n\n// Fixed literal: a reported message must never carry row ids or field values.\nconst ROW_FAILURE_MESSAGE = \"Documents: row mutation failed\";\n\nasync function persistRowMutation(\n state: DocumentStoreState,\n expectedLocalWriteGeneration: number,\n mutate: (doc: DocumentState) => boolean,\n options: DocumentMutationGuard,\n): Promise<void> {\n if (state.localWriteGeneration !== expectedLocalWriteGeneration) {\n return;\n }\n const currentDoc = state.doc;\n if (!currentDoc || !canWriteDocument(state)) {\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n if (options.stillCurrent?.() === false) return;\n if (!mutate(currentDoc)) {\n await revalidateDocumentMutationIdentity({ currentDoc, generation, state });\n return;\n }\n\n const update = pendingDeltaSinceBase(state, currentDoc);\n if (update.byteLength === 0) {\n await revalidateDocumentMutationIdentity({ currentDoc, generation, state });\n return;\n }\n // Captured at delta time: the enqueued row proves coverage up to exactly\n // this version, so it is the frontier the persist below may publish.\n const coveredVersion = encodeVersionVector(currentDoc);\n\n const pendingUpdate = createPendingUpdateFields(update);\n if (!pendingUpdate) {\n await revalidateDocumentMutationIdentity({ currentDoc, generation, state });\n return;\n }\n // From here until a persist covers it, the doc holds edits SQLite lacks.\n state.unsavedLocalEdits = true;\n // Row writes change neither prose nor structured fields; setReadySnapshot\n // always re-derives rows from the doc, so preserve the text/structured fields\n // in case this write overlaps an in-flight keystroke elsewhere.\n const persisted = await persistDocument(\n state,\n currentDoc,\n { snapshotEndVersion: coveredVersion },\n {\n pendingUpdate,\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n },\n generation,\n );\n if (\n !persisted ||\n persisted.pullContinuationSuperseded ||\n persisted.syncIdentitySuperseded ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n // Refused: the document was deleted while this persist was queued\n // and the store is cleared — no state advance, no sync request.\n return;\n }\n advancePendingBaseVersion(state, currentDoc);\n requestDocumentStoreSync(state);\n}\n\nfunction queueRowMutation(\n state: DocumentStoreState,\n mutate: (doc: DocumentState) => boolean,\n options: DocumentMutationGuard,\n): Promise<void> {\n const writeGeneration = state.localWriteGeneration;\n // Unlike text/structured-field writes, row writes intentionally do NOT bump\n // `state.pendingLocalWrites`: rows are never in the optimistic-preserve set —\n // `setReadySnapshot` always re-derives them from the doc — so there is no\n // optimistic snapshot for a concurrent sync pass to clobber. Input smoothness\n // during rapid edits is handled in the app layer (useDocumentRowEditing).\n return chainQueuedWrite(\n state,\n state.writeChain\n .catch(() => undefined)\n .then(() => persistRowMutation(state, writeGeneration, mutate, options))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n }),\n );\n}\n\nexport async function addRowToDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n fields: Readonly<Record<string, string>>,\n options: DocumentMutationGuard = {},\n): Promise<string> {\n const id = createDocumentRowId();\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n return id;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return id;\n }\n\n await queueRowMutation(\n state,\n (doc) => {\n addDocumentRow(doc, id, fields, resolveRowAttribution(state));\n return true;\n },\n options,\n );\n return id;\n}\n\nexport async function updateRowInDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n id: string,\n patch: Readonly<Record<string, string>>,\n options: DocumentMutationGuard = {},\n): Promise<void> {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n await queueRowMutation(\n state,\n (doc) => setDocumentRowFields(doc, id, patch, resolveRowAttribution(state)),\n options,\n );\n}\n\nexport async function removeRowFromDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n id: string,\n options: DocumentMutationGuard = {},\n): Promise<void> {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n if (options.stillCurrent?.() === false) ready = false;\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ROW_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n await queueRowMutation(state, (doc) => removeDocumentRow(doc, id), options);\n}\n\n/** The store's row writes, each counted and run on the live sync lane. */\nexport function createRowWrites(\n state: DocumentStoreState,\n scheduleSync: () => void,\n liveWrite: <Result>(write: () => Promise<Result>) => Promise<Result>,\n): Pick<DocumentStore, \"addRow\" | \"removeRow\" | \"updateRowFields\"> {\n return {\n addRow: (fields, options) =>\n liveWrite(() =>\n addRowToDocumentStore(state, scheduleSync, fields, options),\n ),\n removeRow: (id, options) =>\n liveWrite(() =>\n removeRowFromDocumentStore(state, scheduleSync, id, options),\n ),\n updateRowFields: (id, patch, options) =>\n liveWrite(() =>\n updateRowInDocumentStore(state, scheduleSync, id, patch, options),\n ),\n };\n}\n"]}
@@ -207,6 +207,7 @@ export function createDocumentStoreFacade(initialStore) {
207
207
  requestSync: () => targetStore.requestSync(),
208
208
  relink: (input) => targetStore.relink(input),
209
209
  rebindTo: (store) => connectTarget(store),
210
+ restoreContent: (content, options) => targetStore.restoreContent(content, options),
210
211
  setStructuredFields: (kind, patch, options) => targetStore.setStructuredFields(kind, patch, options),
211
212
  setText: (value) => targetStore.setText(value),
212
213
  subscribe: (listener) => {