@vrtmrz/livesync-commonlib 0.7.0 → 0.8.1

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 (93) hide show
  1. package/README.md +4 -0
  2. package/dist/common/models/diff.definition.d.ts +4 -0
  3. package/dist/common/utils.d.ts +1 -1
  4. package/dist/common/utils.doc.d.ts +5 -0
  5. package/dist/common/utils.doc.js +8 -0
  6. package/dist/common/utils.js +1 -3
  7. package/dist/conflicts/filenameCaseConflict.d.ts +8 -0
  8. package/dist/conflicts/filenameCaseConflict.js +26 -0
  9. package/dist/conflicts.d.ts +1 -0
  10. package/dist/conflicts.js +9 -1
  11. package/dist/interfaces/DatabaseFileAccess.d.ts +12 -1
  12. package/dist/interfaces/FileReflectionProvenance.js +1 -0
  13. package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
  14. package/dist/managers/ConflictManager.d.ts +6 -2
  15. package/dist/managers/ConflictManager.js +73 -22
  16. package/dist/managers/EntryManager/EntryManager.d.ts +5 -0
  17. package/dist/managers/EntryManager/EntryManager.js +5 -0
  18. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +5 -1
  19. package/dist/managers/EntryManager/EntryManagerImpls.js +92 -6
  20. package/dist/managers/LiveSyncManagers.js +2 -1
  21. package/dist/managers/StorageEventManager/admission.d.ts +15 -3
  22. package/dist/managers/StorageEventManager/admission.js +13 -3
  23. package/dist/managers/StorageEventManager/processing.d.ts +2 -2
  24. package/dist/managers/StorageEventManager/processing.js +3 -3
  25. package/dist/managers/StorageEventManager/queue.d.ts +23 -14
  26. package/dist/managers/StorageEventManager/queue.js +70 -30
  27. package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
  28. package/dist/managers/StorageEventManager/snapshot.js +74 -0
  29. package/dist/managers/StorageEventManager/state.d.ts +27 -5
  30. package/dist/managers/StorageEventManager/state.js +9 -7
  31. package/dist/managers/StorageEventManager.d.ts +6 -0
  32. package/dist/managers/StorageEventManager.js +135 -18
  33. package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
  34. package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
  35. package/dist/managers/adapters/index.d.ts +1 -1
  36. package/dist/pouchdb/LiveSyncLocalDB.js +3 -4
  37. package/dist/replication/index.d.ts +2 -0
  38. package/dist/replication/index.js +2 -0
  39. package/dist/replication/replicationResultQueueStore.d.ts +101 -0
  40. package/dist/replication/replicationResultQueueStore.js +140 -0
  41. package/dist/serviceFeatures/offlineScanner/files.js +15 -3
  42. package/dist/serviceFeatures/offlineScanner/scan.js +1 -4
  43. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +5 -4
  44. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +28 -7
  45. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +8 -2
  46. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +52 -9
  47. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +30 -0
  48. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +82 -10
  49. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +118 -12
  50. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +32 -8
  51. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +2 -8
  52. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +4 -5
  53. package/dist/services/base/KeyValueDBService.d.ts +6 -6
  54. package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
  55. package/dist/worker/WorkerPushStreamProducer.js +299 -0
  56. package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
  57. package/dist/worker/WorkerPushStreamReader.js +179 -0
  58. package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
  59. package/dist/worker/backgroundWorkerRpcContract.js +24 -0
  60. package/dist/worker/bg.worker.js +2 -16
  61. package/dist/worker/bg.worker.splitting.d.ts +3 -7
  62. package/dist/worker/bg.worker.splitting.js +46 -47
  63. package/dist/worker/bgWorker.d.ts +8 -14
  64. package/dist/worker/bgWorker.direct.d.ts +5 -28
  65. package/dist/worker/bgWorker.direct.js +32 -2
  66. package/dist/worker/bgWorker.errors.d.ts +1 -0
  67. package/dist/worker/bgWorker.errors.js +12 -0
  68. package/dist/worker/bgWorker.js +716 -296
  69. package/dist/worker/bgWorker.splitting.d.ts +12 -26
  70. package/dist/worker/bgWorker.splitting.js +115 -107
  71. package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
  72. package/dist/worker/outOfBandCancelIterator.js +8 -0
  73. package/dist/worker/serveBackgroundWorker.d.ts +3 -0
  74. package/dist/worker/serveBackgroundWorker.js +35 -0
  75. package/dist/worker/splitConnectionTracker.d.ts +25 -0
  76. package/dist/worker/splitConnectionTracker.js +73 -0
  77. package/dist/worker/splitGate.d.ts +19 -0
  78. package/dist/worker/splitGate.js +71 -0
  79. package/dist/worker/universalTypes.d.ts +0 -30
  80. package/dist/worker/universalTypes.js +0 -4
  81. package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
  82. package/dist/worker/workerPushStreamProtocol.js +143 -0
  83. package/docs/conflict-resolution.md +22 -8
  84. package/docs/development.md +6 -0
  85. package/docs/offline-scanner.md +2 -0
  86. package/docs/storage-events-and-reflection.md +171 -2
  87. package/package.json +1 -1
  88. package/dist/worker/bg.common.d.ts +0 -2
  89. package/dist/worker/bg.common.js +0 -6
  90. package/dist/worker/bg.worker.encryption.d.ts +0 -7
  91. package/dist/worker/bg.worker.encryption.js +0 -30
  92. package/dist/worker/bgWorker.encryption.d.ts +0 -22
  93. package/dist/worker/bgWorker.encryption.js +0 -40
@@ -0,0 +1,143 @@
1
+ import {
2
+ RpcError,
3
+ serialiseRpcError
4
+ } from "@vrtmrz/rpc";
5
+ import { OUT_OF_BAND_CANCEL_ITERATOR } from "./outOfBandCancelIterator.js";
6
+ const VERSION = 1;
7
+ const DEFAULT_BATCH_TARGET_BYTES = 128 * 1024;
8
+ const DEFAULT_MAX_BATCH_ITEMS = 256;
9
+ const DEFAULT_INITIAL_CREDIT_BYTES = 512 * 1024;
10
+ const DEFAULT_CLAIM_TIMEOUT_MS = 3e4;
11
+ const ITEM_OVERHEAD_BYTES = 64;
12
+ const measureStringItem = (item) => ITEM_OVERHEAD_BYTES + 2 * item.length;
13
+ const isStringItem = (item) => typeof item === "string";
14
+ const STREAM_ERROR_CODES = /* @__PURE__ */ new Set([
15
+ "aborted",
16
+ "disconnected",
17
+ "timeout",
18
+ "stream-protocol-error",
19
+ "remote-error"
20
+ ]);
21
+ function isRecord(value) {
22
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23
+ }
24
+ function isWireError(value) {
25
+ return isRecord(value) && typeof value.code === "string" && STREAM_ERROR_CODES.has(value.code) && typeof value.message === "string" && (value.remoteName === void 0 || typeof value.remoteName === "string");
26
+ }
27
+ function serialiseError(error) {
28
+ try {
29
+ const wire = serialiseRpcError(error);
30
+ const streamError = STREAM_ERROR_CODES.has(wire.code) ? wire : { ...wire, code: "remote-error" };
31
+ if (isWireError(streamError)) {
32
+ return streamError;
33
+ }
34
+ } catch {
35
+ }
36
+ return { code: "remote-error", message: "Worker stream failed." };
37
+ }
38
+ function deserialiseError(error) {
39
+ return new RpcError(error.code, error.message, { remoteName: error.remoteName });
40
+ }
41
+ function protocolError(message) {
42
+ return new RpcError("stream-protocol-error", message);
43
+ }
44
+ function isPositiveSafeInteger(value) {
45
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
46
+ }
47
+ function measureItem(options, item) {
48
+ try {
49
+ if (options.isItem(item)) {
50
+ const charge = options.chargeItem(item);
51
+ if (isPositiveSafeInteger(charge) && charge <= options.maxItemBytes) {
52
+ return charge;
53
+ }
54
+ }
55
+ } catch (cause) {
56
+ throw new RpcError("stream-protocol-error", "Could not measure Worker stream item.", { cause });
57
+ }
58
+ throw protocolError("Invalid Worker stream item or item charge.");
59
+ }
60
+ function canSend(chargeBytes, inFlightBytes, initialGrant) {
61
+ return inFlightBytes === 0 || chargeBytes <= initialGrant - inFlightBytes;
62
+ }
63
+ function checkLimits(...limits) {
64
+ if (!limits.every(isPositiveSafeInteger)) {
65
+ throw new RangeError("Worker stream limits must be positive safe integers.");
66
+ }
67
+ }
68
+ function disconnected(signal) {
69
+ return signal.reason ?? new RpcError("disconnected", "Worker stream connection ended.");
70
+ }
71
+ const asyncDispose = Symbol.asyncDispose ?? /* @__PURE__ */ Symbol("workerStreamAsyncDispose");
72
+ function stopGeneratorOnReturn(iterator, stop) {
73
+ const wrapped = {
74
+ // Interrupt pending reads before the generator queues return or throw.
75
+ [OUT_OF_BAND_CANCEL_ITERATOR]: true,
76
+ next: (...args) => iterator.next(...args),
77
+ return(value) {
78
+ stop();
79
+ return iterator.return(value);
80
+ },
81
+ throw(error) {
82
+ stop();
83
+ return iterator.throw(error);
84
+ },
85
+ [Symbol.asyncIterator]() {
86
+ return this;
87
+ },
88
+ async [asyncDispose]() {
89
+ await this.return(void 0);
90
+ }
91
+ };
92
+ return wrapped;
93
+ }
94
+ function cancelWorkerPushStream(port, failure) {
95
+ try {
96
+ const message = failure ? { version: VERSION, type: "cancel", error: serialiseError(failure.error) } : { version: VERSION, type: "cancel" };
97
+ port.postMessage(message);
98
+ } catch {
99
+ } finally {
100
+ port.close();
101
+ }
102
+ }
103
+ function validateBatch(options, data, maxBatchItems, inFlightBytes, initialCreditBytes) {
104
+ const { items, chargeBytes } = data;
105
+ if (!Array.isArray(items) || items.length === 0 || items.length > maxBatchItems || !isPositiveSafeInteger(chargeBytes) || !canSend(chargeBytes, inFlightBytes, initialCreditBytes) || chargeBytes > initialCreditBytes - inFlightBytes && items.length !== 1) {
106
+ throw protocolError("Invalid Worker stream batch or credit usage.");
107
+ }
108
+ let measured = 0;
109
+ for (const item of items) {
110
+ const charge = measureItem(options, item);
111
+ if (charge > chargeBytes - measured) {
112
+ throw protocolError("Worker stream batch charge does not match its items.");
113
+ }
114
+ measured += charge;
115
+ }
116
+ if (measured !== chargeBytes) {
117
+ throw protocolError("Worker stream batch charge does not match its items.");
118
+ }
119
+ return { items, chargeBytes };
120
+ }
121
+ export {
122
+ DEFAULT_BATCH_TARGET_BYTES,
123
+ DEFAULT_CLAIM_TIMEOUT_MS,
124
+ DEFAULT_INITIAL_CREDIT_BYTES,
125
+ DEFAULT_MAX_BATCH_ITEMS,
126
+ ITEM_OVERHEAD_BYTES,
127
+ VERSION,
128
+ canSend,
129
+ cancelWorkerPushStream,
130
+ checkLimits,
131
+ deserialiseError,
132
+ disconnected,
133
+ isPositiveSafeInteger,
134
+ isRecord,
135
+ isStringItem,
136
+ isWireError,
137
+ measureItem,
138
+ measureStringItem,
139
+ protocolError,
140
+ serialiseError,
141
+ stopGeneratorOnReturn,
142
+ validateBatch
143
+ };
@@ -16,7 +16,7 @@ A1
16
16
 
17
17
  `D1` and `C2` are the leaves to compare. Their nearest common ancestor is `A1`, not `B1` or `B2`. Automatic three-way merge may proceed only when the same `available` revision is present in both leaf histories. A matching generation number alone does not establish ancestry.
18
18
 
19
- Resolving a conflict writes the selected or merged result on one branch and deletes every losing live leaf which the resolver has observed. Deleted leaves remain part of the tree until compaction removes their bodies. A stale client can therefore receive the resolved branch and the tombstone for a branch whose old content is still present in its storage.
19
+ Selecting an existing revision keeps it as a live leaf. A resolver retires the competing leaves it has reviewed. Combining text creates a new content revision. Deleted leaves remain part of the tree until compaction removes their bodies. A stale client can therefore receive the resolved branch and the tombstone for a branch whose old content is still present in its storage.
20
20
 
21
21
  Metadata reads which explicitly include deleted entries also return a current PouchDB `_deleted` winner. An ordinary read still excludes deleted entries, and a request for an unavailable specific revision does not fall back to the current winner. A deleted-winner lookup rechecks the winning revision after fetching its body. If it changes, the lookup follows the new winner for at most three attempts and returns no entry if it cannot establish a stable revision. Incoming file reflection uses the current winner and rechecks it before deleting storage, so an older deletion notification does not override a subsequent restoration. Existing conflict and unsynchronised-edit protection still applies.
22
22
 
@@ -44,17 +44,19 @@ After a resolution has propagated, an exact recorded revision can still identify
44
44
 
45
45
  ## Resolution classes
46
46
 
47
+ A whole-file logical deletion is a separate revision state. If one leaf is deleted and the other is live, the conservative text merge leaves the choice to the host.
48
+
47
49
  | State | Safe automatic action |
48
50
  | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
49
- | Both leaves contain identical bytes | Collapse the duplicate leaf without creating merged content. |
50
- | Text or structured data has a shared available base and non-overlapping changes | Perform a conservative three-way merge. |
51
- | One side deletes content which the other leaves unchanged | Preserve the deletion. |
52
- | One side deletes content which the other modifies | Retain a manual conflict. |
51
+ | Both leaves have matching names, identical bytes, and the same deletion state | Collapse the duplicate leaf without creating merged content. |
52
+ | Both names match and text or structured data has a shared available base and non-overlapping changes | Perform a conservative three-way merge. |
53
+ | In a three-way text merge, one side removes a line the other leaves unchanged | Keep the line removed from the merged text. |
54
+ | One side removes a line which the other modifies | Retain a manual conflict. |
53
55
  | A receiving file matches its exact readable recorded revision | Apply the propagated result under the existing conflict policy. |
54
56
  | A receiving file matches its saved content hash and byte length | Apply the propagated result under the existing conflict policy, even after its recorded revision is pruned. |
55
57
  | A receiving file differs from its readable recorded revision | Preserve the edit as a child of that revision. |
56
58
  | Origin is unknown and no current non-deleted leaf matches | Preserve a fresh independent root for host conflict resolution. |
57
- | Origin is unknown and current non-deleted leaves already contain the bytes | Avoid duplicate storage; infer provenance only for a unique match. |
59
+ | Origin is unknown and current non-deleted leaves already contain the observed spelling and bytes | Avoid duplicate storage; infer provenance only for a unique match. |
58
60
  | A required merge body or common ancestor is missing or compacted | Retain a manual conflict. |
59
61
  | Content is binary or otherwise not semantically mergeable | Leave the selection policy to the host; Commonlib cannot infer user intent. |
60
62
 
@@ -193,6 +195,18 @@ A1
193
195
 
194
196
  `D2` remains a live metadata branch. The host can therefore ask whether to retain `C1` or the deletion. A PouchDB `_deleted` tombstone would remove that decision from the live conflict and is not used for this operation.
195
197
 
198
+ ### Filename case in ordinary synchronisation
199
+
200
+ With case-insensitive document IDs, `Notes/Plan.md` and `Notes/plan.md` can identify the same document. The spelling belongs to each revision. When the receiver can identify the revision and spelling it previously reflected, an incoming case-only rename updates an unchanged file. A local edit based on that recorded revision is preserved as its child.
201
+
202
+ If the actual spelling in storage has no confirmed base, ordinary synchronisation preserves the file before renaming or overwriting it. A live leaf with the same spelling and bytes already represents the file. Otherwise, the file becomes an independent root under the same document ID. A repeated scan leaves the pending choices intact. This also applies when the two spellings contain identical bytes. This protection applies with the default conflict-write policy. Explicit forced reflection and the `writeDocumentsIfConflicted` overwrite setting retain their existing behaviour.
203
+
204
+ Automatic content resolution requires both compared revisions to record the same full path, including case. Path identity version `0` compares the recorded spelling directly. Version `1` applies NFC before comparison. Different or unknown names require a host decision. A successful three-way merge returns the recorded spelling as its save path when that spelling still identifies the reviewed document. If it identifies a different document under the current settings, the save path is the original lookup path. After selection, the host reflects the surviving revision using its recorded spelling, or the document's effective path when no name was recorded.
205
+
206
+ The built-in `DatabaseFileAccess` reads the original spelling directly from revision metadata. Custom adapters can provide `readRevisionPath(documentId, revision)` and honour the filename filter on `readLiveContentRevisions`. Return `undefined` when the revision or its stored path is absent, and propagate I/O errors. The filename filter runs before loading candidate chunks.
207
+
208
+ A host offering concatenation with a choice of filename can use `storeWithLiveBaseRevision(file, displayedWinnerRev)`. Before saving, the host checks that the chosen name still identifies the reviewed document. If the name identifies another document, both revisions remain available. The chosen name goes on a new child of the displayed winner. The two versions can have independent roots. Retire the other reviewed leaf only after the write succeeds. If the displayed parent has advanced, the write is refused and the current versions remain available for review.
209
+
196
210
  ### Renaming while a conflict is visible
197
211
 
198
212
  For a case-only rename, such as `Note.md` to `note.md`, the renamed entry is written as a child of the displayed revision in the same document tree. The other live branch remains available for resolution.
@@ -201,9 +215,9 @@ For a cross-path rename, such as `draft.md` to `published.md`, Commonlib stores
201
215
 
202
216
  ### Reconstructing provenance after local state is unavailable
203
217
 
204
- Suppose a local-database reset removed the device-local record, but the storage file still has exactly the bytes held by current non-deleted leaf `C2`. If `C2` is the only matching current leaf, ordinary saving or reflection can reconstruct `C2` as the displayed base and a later edit extends it normally. An unchanged-time scan alone does not guarantee reconstruction.
218
+ Suppose a local-database reset removed the device-local record, but the storage file still has exactly the bytes held by current non-deleted leaf `C2`. If `C2` is the only current leaf with that spelling and those bytes, ordinary saving or reflection can reconstruct `C2` as the displayed base and a later edit extends it normally. An unchanged-time scan alone does not guarantee reconstruction.
205
219
 
206
- If both current leaves contain the same bytes, ordinary saving avoids duplicate storage without selecting either as provenance. If neither contains the storage bytes, those bytes are preserved on an independent root. An unproven deletion preserves both existing branches, and a cross-path rename preserves unproven source branches after storing the target. These outcomes may require user review, but they do not guess that the deterministic winner was displayed.
220
+ If both current leaves contain the same spelling and bytes, ordinary saving avoids duplicate storage without selecting either as provenance. If neither has the observed spelling and bytes, the file is preserved on an independent root. An unproven deletion preserves both existing branches, and a cross-path rename preserves unproven source branches after storing the target. These outcomes may require user review, but they do not guess that the deterministic winner was displayed.
207
221
 
208
222
  ### Receiving a resolution while showing the losing branch
209
223
 
@@ -251,6 +251,12 @@ npm run test:package
251
251
 
252
252
  `test:package` builds the compiled package, packs it, installs the tarball into a clean consumer fixture, exercises Node imports, type-checks public entry points, and creates representative browser bundles. It also verifies that browser and context entry points do not pull in Node-only code, Svelte, or the complete language catalogue unintentionally.
253
253
 
254
+ The browser Worker bundle uses one RPC pool for chunking, encryption, and decryption. The Self-hosted LiveSync plug-in initialises it with the event hub for its own lifecycle. The package check exercises the existing compatibility entry and verifies that it and Commonlib's internal alias resolve to the same implementation for each runtime. Both runtimes return a synchronous factory for each Worker splitter. Node consumers can still `await` the factory and should use `await` when migrating a call that chained `.then()` on the former direct V1 or V2 result.
255
+
256
+ Browser splitters send ordered arrays of whole chunks over a dedicated `MessagePort` transferred by RPC. The consumer returns byte credit when it advances past each array. A chunk larger than the initial grant travels alone once all earlier batches have been refunded. The public split iterator still yields individual chunks.
257
+
258
+ The browser pool permits as many active splits as it has Worker slots, and encryption and decryption RPCs bypass this limit.
259
+
254
260
  `test:contracts` runs the host-neutral result contracts which are intended to be reusable while implementations move:
255
261
 
256
262
  - `test:contract:context` verifies event delivery, default instance isolation, translation results, and host extension of `ServiceContextContract`;
@@ -46,6 +46,8 @@ The tables below cover only paths which remain after identity validation, the ho
46
46
 
47
47
  `VaultScanOptions.strictContentCheck` is optional. `initialiseDatabase` accepts `VaultScanOptions` as its optional fifth argument, and `scanVault` accepts it as its optional fourth argument and forwards it. `performFullScan` exposes the same option through `FullScanOptions`. Omitting the option, or setting it to `true`, retains strict content comparison. Only an explicit `false` permits the scanner to pass the `canSkipUnchangedFile` hint to the file handler. Commonlib does not read a host setting or global storage; a host may select this option from a per-installation startup preference.
48
48
 
49
+ When a live database entry and a storage file have different spellings of the same filename, the scan preserves an untracked spelling before updating either side. A modification time or equal content alone cannot settle the choice. See [Filename case in ordinary synchronisation](conflict-resolution.md#filename-case-in-ordinary-synchronisation).
50
+
49
51
  The hint is considered only when the normal freshness comparison reaches `EVEN`, replacing the additional body comparison at that point. It never bypasses `BASE_IS_NEW` or `TARGET_IS_NEW`; those branches retain their timestamp-directed reflection and last-seen bookkeeping. Inside `EVEN`, the hint is allowed only for a tracked file whose raw modification time exactly equals the recorded provenance mtime (not merely a value in the same platform comparison bucket), whose byte size matches the recorded value, whose tracked revision is the current live database revision, and which has no live conflicts or related queued, running, or failed file work. If tracking evidence is missing, or the host cannot establish pending-work state, the existing strict byte-comparison path remains. When the hint is accepted, the pair result is `SKIPPED`; it does not compare or claim equal bytes, write provenance, or introduce Commonlib persistent state. Incoming content, conflict handling, and logical-deletion protection retain their existing rules.
50
52
 
51
53
  A local edit which preserves the tracked modification time and byte size may be missed by a scan using explicit `false`. Existing same-stat edit checks exercise the omitted-option strict path.
@@ -244,8 +244,8 @@ waiting, or already in a handler. It waits for each actual handler result and
244
244
  for the ordered snapshot update which records that result; releasing a timer is
245
245
  not completion. Later events do not extend that captured boundary. A newer
246
246
  coalesced operation satisfies an earlier one only when its successful result
247
- covers the earlier intent. A failed handler or snapshot update is reported to
248
- the caller and leaves unresolved work in the snapshot. This boundary covers
247
+ covers the earlier intent. A failed handler or acknowledgement is reported to
248
+ the caller and leaves the saved work pending. This boundary covers
249
249
  local completion under the selected handler contract only; it does not prove replication or receipt by another
250
250
  Vault.
251
251
 
@@ -259,6 +259,34 @@ timers do not occupy a processing slot, and time spent waiting for a slot does
259
259
  not restart the maximum delay. Once due, the operation acquires a slot and reads
260
260
  current content for processing.
261
261
 
262
+ ### Ordered pending buffers
263
+
264
+ This option is available in Commonlib 0.8.0.
265
+
266
+ A host can supply `pendingEventStore` on its storage-event manager adapter to
267
+ store ordered arrays of new event intents. The store returns buffers in replay
268
+ order, including any legacy snapshot as the first buffer. `append()` returns a
269
+ distinct key after commit. The manager groups requests for the next buffer and
270
+ waits for the append before handling its events. If the append fails, the
271
+ manager reports the failure once, discards that unsaved array, and lets later
272
+ arrays proceed. Calls already waiting for that array receive the failure.
273
+ Previously saved buffers remain available for replay.
274
+
275
+ The next full Vault scan compares selected paths with the local database. It
276
+ can recover the current contents of a renamed file. If the rename was never
277
+ saved, the scan evaluates the old and new paths independently. Without
278
+ sufficient evidence of an offline deletion, it may restore a live database
279
+ entry at the old path.
280
+
281
+ A saved array remains intact until every entry in it has completed. Each
282
+ successful operation releases its in-process dependants as soon as its own
283
+ local effect completes. The final successful operation deletes the whole
284
+ buffer. If an operation fails, other work can proceed where its dependencies
285
+ allow, and the failed buffer remains recoverable. A later application instance
286
+ loads that whole array and revalidates ordinary file events against current
287
+ storage and database state. Hosts must surface store failures to the manager
288
+ and resolve deletion only once the supplied key has been durably removed.
289
+
262
290
  ## Retrying ordinary file operations
263
291
 
264
292
  The following extension is available in Commonlib 0.4.1. A failed ordinary
@@ -379,6 +407,147 @@ policy. The storage lookup may be a host index rather than an operating-system
379
407
  existence check: the observation is made under the application lock, not in
380
408
  an atomic filesystem transaction.
381
409
 
410
+ ## Saving replication results in a CLI host
411
+
412
+ The `createReplicationResultQueueStore()` API, introduced in Commonlib 0.8.1, is available from
413
+ `@vrtmrz/livesync-commonlib/replication`. It stores each queued or processing item
414
+ under its own key. It also stores retained reflection failures and retry
415
+ reservations as individual records. Commonlib owns the versioned row format,
416
+ ordered reads, the legacy queue migration, and atomic delta submission. The
417
+ host owns the database connection, the value codec, and the processor's events
418
+ and recovery policy.
419
+
420
+ ### Convert an existing CLI JSON file
421
+
422
+ When a scoped `keyvalue-db.json` needs importing, run the conversion on its
423
+ own for that database and Vault. Preserve the existing tagged JSON encoding,
424
+ including `Set`, `Uint8Array`, and `ArrayBuffer`. Use the file whose owner is
425
+ known to match the selected scope. Preserve older files of unknown ownership
426
+ for inspection.
427
+
428
+ Commit the imported KV values and the import receipt in one SQLite transaction.
429
+ Rename the source JSON after that commit. If a prior invocation committed the
430
+ receipt, finish the rename without copying the values again. If the commit
431
+ result is uncertain, close the connection, report failure, and check the
432
+ receipt on the next conversion attempt. Close the connection and exit when
433
+ conversion completes. On the next normal invocation, Commonlib can migrate
434
+ the legacy queue key from SQLite to individual rows.
435
+
436
+ ### Connect the CLI-owned SQLite database
437
+
438
+ In LiveSync's `NodeKeyValueDBService`, open the SQLite database selected for the
439
+ current database and Vault. Use the same Fancy-kit 0.2.0 SQLite namespace and
440
+ prefix for the existing `replicationResultProcessorSnapshot` key and the new
441
+ queue prefix.
442
+
443
+ The following bridge uses the CLI's existing tagged JSON encoding for both the
444
+ imported legacy value and new rows. Each `setValue` writes one row.
445
+
446
+ ```ts
447
+ import {
448
+ createReplicationResultQueueStore,
449
+ type ReplicationResultQueueBacking,
450
+ } from '@vrtmrz/livesync-commonlib/replication';
451
+ import { createSqliteValueStore } from '@vrtmrz/value-store/node-sqlite';
452
+ import type { DatabaseSync } from 'node:sqlite';
453
+
454
+ declare const connection: DatabaseSync;
455
+ declare const cliKvScope: { namespace: string; prefix: string };
456
+ declare function encodeCliValue(value: unknown): string;
457
+ declare function decodeCliValue(value: string): unknown;
458
+
459
+ const kv = createSqliteValueStore(connection, cliKvScope);
460
+ const backing: ReplicationResultQueueBacking = {
461
+ async read(key) {
462
+ const value = await kv.getValue(key);
463
+ return value === null ? undefined : decodeCliValue(value);
464
+ },
465
+ listKeys: (prefix) => kv.listKeys({ prefix }),
466
+ writeBatch: (operations) =>
467
+ kv.writeBatch(
468
+ operations.map((operation) =>
469
+ operation.kind === 'delete'
470
+ ? { type: 'delete', key: operation.key }
471
+ : { type: 'setValue', key: operation.key, value: encodeCliValue(operation.value) }
472
+ )
473
+ ),
474
+ };
475
+ const results = createReplicationResultQueueStore(backing);
476
+ ```
477
+
478
+ Use one writer for the scope. Exclude other writers while `load()` or
479
+ `discard()` reads and changes that scope, and serialise those operations with
480
+ `commit()`. The backing `writeBatch()` must apply the whole batch atomically and
481
+ resolve after commit. The borrowed SQLite adapter starts its own transaction.
482
+ Call it outside any CLI-managed SQL transaction. Settle the submitted writes
483
+ and dispose the value store before closing. Put native connection closure in
484
+ a `finally` block that covers both steps. The CLI selects the SQLite durability
485
+ settings. See the
486
+ [Fancy-kit SQLite contract](https://github.com/vrtmrz/fancy-kit/blob/7bf325dddd6c7000d0ae2990146a538594a67f3b/docs/design/value-store-sqlite.md).
487
+
488
+ ### Connect the result processor
489
+
490
+ 1. Pass a getter for the current scoped store into `ReplicateResultProcessor`
491
+ from `createReplicationFeature` when the CLI opts in. Use `load()` at the
492
+ existing restore point. It commits any legacy rows and removes the old key in
493
+ the same transaction. The store validates the rows' storage format and returns
494
+ their payloads as `unknown`. Interpret them using the processor's existing
495
+ document and recovery validation. Restore recovery records and reservations
496
+ first. Then pass processing items followed by queued items through the current
497
+ recovery filter and replay rules, ahead of arrivals held during restore. If
498
+ loading fails, keep saves blocked until a load or explicit reset succeeds.
499
+ 2. Give every queue occurrence a stable ID and store its order explicitly. Keep
500
+ the ID when a row moves from `queued` to `processing` and use it to delete the
501
+ row on completion. Preserve separate IDs for multiple occurrences even when
502
+ `_id` and `_rev` match. Reserve `legacy:` for migrated IDs. Track changed
503
+ rows at each mutation and submit them at the processor's existing save points.
504
+ Submit a replacement's deletes and insert in the same batch. Commit a retry
505
+ reservation with its changed allowance before dispatch, and commit retirement
506
+ of that reservation with the corresponding result updates. Retain a reflection
507
+ failure before or in the same batch as removal of its processing row.
508
+ 3. Record the changes made by replay itself. Carry the loaded ID into each
509
+ surviving occurrence and record its resulting order and phase. Include
510
+ deletions for occurrences dropped by recovery filtering or duplicate
511
+ handling, and for reservations consumed by recovery. Include changes to
512
+ pending records moved to review. For hosts with recovery retries, a saved
513
+ reservation can filter out every runnable item. If replay changed rows,
514
+ request a save even when no work is runnable. Schedule that save after
515
+ restore completes, because the existing save path waits for restore.
516
+ 4. Capture the pending delta when a serialised write begins. Mark those changes
517
+ saved only after `commit()` succeeds and keep newer or failed changes pending.
518
+ Preserve the current response timing for ordinary arrivals. A Fancy-kit
519
+ error code can cover both a failed statement and an uncertain commit. If a
520
+ write's outcome remains unclear, check the durable state after reopening the
521
+ same scope before acknowledging or resubmitting the delta. Initialise a new
522
+ store with `load()` before accepting writes. During an in-process reconnect,
523
+ use that read to reconcile the durable state with the existing in-memory queue.
524
+ 5. In the pinned LiveSync CLI, `databaseEvents.onResetDatabase` runs before
525
+ database replacement. The `NodeServiceHub` and `NodeKeyValueDBService`
526
+ handlers can remove the runtime directory and the KV file at that point.
527
+ When wiring SQLite, keep the queue rows and legacy key through those early
528
+ handlers, including when the selected database's runtime directory contains
529
+ the SQLite file. Defer retiring that queue until the success event
530
+ `database.onDatabaseReset`. For a `fetch` or `rebuild` startup reset, resolve
531
+ the current scoped store there and await `discard()` before admitting new
532
+ work. Preserve the CLI's existing physical reset scope by retiring old queues
533
+ for every runtime Vault scope of the selected database. While reconstruction
534
+ is incomplete, let read-only commands inspect the database without migrating
535
+ or replaying the result queue. For a live logical reset, commit the delta
536
+ that retains the ordinary items selected by the processor. Use the database
537
+ scope and generation to drop stale mutations. A late completion may delete
538
+ only its own retained row. Keep occurrence IDs unique across reset while old
539
+ callbacks can finish.
540
+
541
+ Validate the CLI wiring by restarting after the first replay delta commits,
542
+ interrupting a write, and failing database replacement after the early reset
543
+ event. For legacy JSON conversion, interrupt the process after commit and
544
+ before renaming the JSON, then verify that the next attempt reuses the receipt.
545
+ Check that a later successful reset lets a new occurrence with the same document
546
+ and revision survive the old occurrence's completion. Compare system write
547
+ bytes on the same Vault and workload to measure SQLite and WAL overhead. The
548
+ Commonlib contract tests measure row operations and the bytes passed through the
549
+ test adapter's encoder.
550
+
382
551
  ## Verification and scope
383
552
 
384
553
  Focused unit tests cover a current canonical file, absence, lookup failure,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vrtmrz/livesync-commonlib",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "description": "Shared data, storage, and replication primitives for Self-hosted LiveSync clients.",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",
@@ -1,2 +0,0 @@
1
- import type { END_OF_DATA } from "./universalTypes.js";
2
- export declare function postBack(key: number, seq: number, data: string | END_OF_DATA): void;
@@ -1,6 +0,0 @@
1
- function postBack(key, seq, data) {
2
- self.postMessage({ key, seq, result: data });
3
- }
4
- export {
5
- postBack
6
- };
@@ -1,7 +0,0 @@
1
- import type { EncryptHKDFArguments } from "./universalTypes.js";
2
- import type { EncryptArguments } from "./universalTypes.js";
3
- /**
4
- * Processes the encryption of data.
5
- * @param data The data to be encrypted or decrypted.
6
- */
7
- export declare function processEncryption(data: EncryptArguments | EncryptHKDFArguments): Promise<void>;
@@ -1,30 +0,0 @@
1
- import { encrypt, decrypt } from "octagonal-wheels/encryption";
2
- import { encrypt as encryptHKDF, decrypt as decryptHKDF } from "octagonal-wheels/encryption/hkdf";
3
- async function processEncryption(data) {
4
- const key = data.key;
5
- const { type, input, passphrase } = data;
6
- try {
7
- if (type == "encrypt") {
8
- const autoCalculateIterations = data.autoCalculateIterations;
9
- const result = await encrypt(input, passphrase, autoCalculateIterations);
10
- self.postMessage({ key, result });
11
- } else if (type == "decrypt") {
12
- const autoCalculateIterations = data.autoCalculateIterations;
13
- const result = await decrypt(input, passphrase, autoCalculateIterations);
14
- self.postMessage({ key, result });
15
- } else if (type == "encryptHKDF") {
16
- const pbkdf2Salt = data.pbkdf2Salt;
17
- const result = await encryptHKDF(input, passphrase, pbkdf2Salt);
18
- self.postMessage({ key, result });
19
- } else if (type == "decryptHKDF") {
20
- const pbkdf2Salt = data.pbkdf2Salt;
21
- const result = await decryptHKDF(input, passphrase, pbkdf2Salt);
22
- self.postMessage({ key, result });
23
- }
24
- } catch (ex) {
25
- self.postMessage({ key, error: ex });
26
- }
27
- }
28
- export {
29
- processEncryption
30
- };
@@ -1,22 +0,0 @@
1
- import { type EncryptHKDFProcessItem, type ResultPayload } from "./universalTypes.js";
2
- import { type EncryptProcessItem } from "./universalTypes.js";
3
- import { type EncryptHKDFArguments } from "./universalTypes.js";
4
- import { type EncryptArguments } from "./universalTypes.js";
5
- /**
6
- * Offloads encryption to a web worker.
7
- * @param data The data to be encrypted.
8
- * @returns A promise that resolves with the encryption result.
9
- */
10
- export declare function encryptionOnWorker(data: Omit<EncryptArguments, "key">): Promise<string>;
11
- /**
12
- * Offloads HKDF encryption to a web worker.
13
- * @param data The data to be encrypted.
14
- * @returns A promise that resolves with the encryption result.
15
- */
16
- export declare function encryptionHKDFOnWorker(data: Omit<EncryptHKDFArguments, "key">): Promise<string>;
17
- /**
18
- * Handles the encryption callbacks
19
- * @param process The process item associated with the task.
20
- * @param data The data to be processed.
21
- */
22
- export declare function handleTaskEncrypt(process: EncryptProcessItem | EncryptHKDFProcessItem, data: ResultPayload): void;
@@ -1,40 +0,0 @@
1
- import { startWorker, removeTask } from "./bgWorker.js";
2
- import {} from "./universalTypes.js";
3
- import {} from "./universalTypes.js";
4
- import {} from "./universalTypes.js";
5
- import {} from "./universalTypes.js";
6
- function encryptionOnWorker(data) {
7
- const process = startWorker(data);
8
- return (async () => {
9
- const ret = await process.task.promise;
10
- process.finalize();
11
- return ret;
12
- })();
13
- }
14
- function encryptionHKDFOnWorker(data) {
15
- const process = startWorker(data);
16
- return (async () => {
17
- const ret = await process.task.promise;
18
- process.finalize();
19
- return ret;
20
- })();
21
- }
22
- function handleTaskEncrypt(process, data) {
23
- const key = data.key;
24
- const task = process.task;
25
- if ("result" in data) {
26
- task.resolve(data.result);
27
- } else {
28
- if (data.error) {
29
- task.reject(data.error);
30
- } else {
31
- task.reject(new Error("Unknown error in background encryption"));
32
- }
33
- }
34
- removeTask(key);
35
- }
36
- export {
37
- encryptionHKDFOnWorker,
38
- encryptionOnWorker,
39
- handleTaskEncrypt
40
- };