@vrtmrz/livesync-commonlib 0.6.1 → 0.8.0

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 (124) hide show
  1. package/README.md +29 -19
  2. package/dist/common/models/shared.definition.d.ts +10 -1
  3. package/dist/common/models/shared.definition.js +4 -3
  4. package/dist/events/coreEvents.d.ts +3 -0
  5. package/dist/events/coreEvents.js +2 -0
  6. package/dist/interfaces/FileReflectionProvenance.js +1 -0
  7. package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
  8. package/dist/managers/EntryManager/EntryManager.d.ts +1 -1
  9. package/dist/managers/EntryManager/EntryManager.js +2 -2
  10. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +1 -1
  11. package/dist/managers/EntryManager/EntryManagerImpls.js +80 -8
  12. package/dist/managers/StorageEventManager/admission.d.ts +16 -3
  13. package/dist/managers/StorageEventManager/admission.js +18 -4
  14. package/dist/managers/StorageEventManager/processing.d.ts +2 -2
  15. package/dist/managers/StorageEventManager/processing.js +3 -3
  16. package/dist/managers/StorageEventManager/queue.d.ts +23 -14
  17. package/dist/managers/StorageEventManager/queue.js +70 -30
  18. package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
  19. package/dist/managers/StorageEventManager/snapshot.js +74 -0
  20. package/dist/managers/StorageEventManager/state.d.ts +27 -5
  21. package/dist/managers/StorageEventManager/state.js +9 -7
  22. package/dist/managers/StorageEventManager.d.ts +8 -0
  23. package/dist/managers/StorageEventManager.js +136 -18
  24. package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
  25. package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
  26. package/dist/managers/adapters/index.d.ts +1 -1
  27. package/dist/pouchdb/LiveSyncLocalDB.d.ts +1 -1
  28. package/dist/pouchdb/LiveSyncLocalDB.js +2 -2
  29. package/dist/replication/LiveSyncAbstractReplicator.d.ts +7 -0
  30. package/dist/replication/LiveSyncAbstractReplicator.js +5 -2
  31. package/dist/replication/ReplicatorInstance.d.ts +3 -0
  32. package/dist/replication/ReplicatorProvider.d.ts +23 -2
  33. package/dist/replication/ReplicatorProvider.js +10 -0
  34. package/dist/replication/SyncParamsHandler.js +26 -25
  35. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +14 -2
  36. package/dist/replication/couchdb/LiveSyncReplicator.js +247 -122
  37. package/dist/replication/index.d.ts +4 -2
  38. package/dist/replication/index.js +6 -0
  39. package/dist/replication/remoteTransportFailure.d.ts +24 -0
  40. package/dist/replication/remoteTransportFailure.js +80 -0
  41. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +1 -1
  42. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +2 -2
  43. package/dist/replication/trystero/TrysteroRpcRoom.d.ts +14 -0
  44. package/dist/replication/trystero/TrysteroRpcRoom.js +168 -0
  45. package/dist/replication/trystero/rpcCompat.d.ts +1 -0
  46. package/dist/replication/trystero/rpcCompat.js +15 -0
  47. package/dist/rpc/RpcRoom.d.ts +1 -0
  48. package/dist/rpc/RpcRoom.js +21 -9
  49. package/dist/rpc/RpcSession.d.ts +8 -13
  50. package/dist/rpc/RpcSession.js +14 -35
  51. package/dist/rpc/commonlibRpcRoom.d.ts +1 -0
  52. package/dist/rpc/commonlibRpcRoom.js +4 -0
  53. package/dist/rpc/errors.d.ts +9 -3
  54. package/dist/rpc/errors.js +13 -16
  55. package/dist/rpc/index.d.ts +10 -1
  56. package/dist/rpc/index.js +2 -1
  57. package/dist/rpc/pouchdb/RpcPouchDBProxy.d.ts +1 -1
  58. package/dist/rpc/pouchdb/RpcPouchDBServer.d.ts +1 -1
  59. package/dist/serviceFeatures/targetFilter.d.ts +3 -1
  60. package/dist/serviceFeatures/targetFilter.js +2 -2
  61. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +5 -2
  62. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -4
  63. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +28 -0
  64. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +53 -0
  65. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +59 -3
  66. package/dist/services/base/IService.d.ts +9 -6
  67. package/dist/services/base/KeyValueDBService.d.ts +6 -6
  68. package/dist/services/base/ReadinessEvaluator.d.ts +7 -6
  69. package/dist/services/base/ReadinessEvaluator.js +4 -2
  70. package/dist/services/base/RemoteConnection.d.ts +4 -0
  71. package/dist/services/base/RemoteService.d.ts +5 -3
  72. package/dist/services/base/RemoteService.js +85 -33
  73. package/dist/services/base/ReplicationService.d.ts +10 -2
  74. package/dist/services/base/ReplicationService.js +13 -7
  75. package/dist/services/base/ReplicationService.readiness.d.ts +14 -4
  76. package/dist/services/base/ReplicationService.readiness.js +29 -2
  77. package/dist/services/base/ReplicationService.typedReplication.d.ts +5 -2
  78. package/dist/services/base/ReplicationService.typedReplication.js +67 -6
  79. package/dist/services/base/ReplicationStaticsOwner.d.ts +18 -0
  80. package/dist/services/base/ReplicationStaticsOwner.js +33 -0
  81. package/dist/services/base/ReplicatorService.d.ts +2 -10
  82. package/dist/services/base/ReplicatorService.js +6 -3
  83. package/dist/services/base/VaultService.d.ts +1 -0
  84. package/dist/string_and_binary/chunks.d.ts +1 -1
  85. package/dist/string_and_binary/chunks.js +63 -50
  86. package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
  87. package/dist/worker/WorkerPushStreamProducer.js +299 -0
  88. package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
  89. package/dist/worker/WorkerPushStreamReader.js +179 -0
  90. package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
  91. package/dist/worker/backgroundWorkerRpcContract.js +24 -0
  92. package/dist/worker/bg.worker.js +2 -14
  93. package/dist/worker/bg.worker.splitting.d.ts +3 -6
  94. package/dist/worker/bg.worker.splitting.js +65 -30
  95. package/dist/worker/bgWorker.d.ts +9 -11
  96. package/dist/worker/bgWorker.direct.d.ts +5 -28
  97. package/dist/worker/bgWorker.direct.js +32 -2
  98. package/dist/worker/bgWorker.errors.d.ts +1 -0
  99. package/dist/worker/bgWorker.errors.js +12 -0
  100. package/dist/worker/bgWorker.js +718 -268
  101. package/dist/worker/bgWorker.splitting.d.ts +12 -27
  102. package/dist/worker/bgWorker.splitting.js +114 -110
  103. package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
  104. package/dist/worker/outOfBandCancelIterator.js +8 -0
  105. package/dist/worker/serveBackgroundWorker.d.ts +3 -0
  106. package/dist/worker/serveBackgroundWorker.js +35 -0
  107. package/dist/worker/splitConnectionTracker.d.ts +25 -0
  108. package/dist/worker/splitConnectionTracker.js +73 -0
  109. package/dist/worker/splitGate.d.ts +19 -0
  110. package/dist/worker/splitGate.js +71 -0
  111. package/dist/worker/universalTypes.d.ts +1 -19
  112. package/dist/worker/universalTypes.js +0 -4
  113. package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
  114. package/dist/worker/workerPushStreamProtocol.js +143 -0
  115. package/docs/development.md +75 -32
  116. package/docs/p2p-transport-lifecycle.md +2 -3
  117. package/docs/storage-events-and-reflection.md +40 -5
  118. package/package.json +3 -2
  119. package/dist/worker/bg.common.d.ts +0 -2
  120. package/dist/worker/bg.common.js +0 -6
  121. package/dist/worker/bg.worker.encryption.d.ts +0 -7
  122. package/dist/worker/bg.worker.encryption.js +0 -30
  123. package/dist/worker/bgWorker.encryption.d.ts +0 -22
  124. 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
+ };
@@ -46,17 +46,17 @@ class and its existing import path. Its implementation lives in the sibling
46
46
  `ServiceFileHandlerBase/` directory. These modules are package-private; they do
47
47
  not add consumer entry points.
48
48
 
49
- | Modules | Responsibility |
50
- | --- | --- |
51
- | `context.ts`, `storage.ts` | Capture injected services, own per-instance state, retain host method dispatch, and resolve file paths, stubs, and bodies. |
52
- | `locking.ts` | Acquire sorted document locks and run deferred conflict hooks after releasing them. |
53
- | `provenance.ts`, `scanning.ts` | Track the displayed revision and content evidence, classify storage, revalidate snapshots, and inspect scan hints. |
54
- | `saving.ts` | Save ordinary or reconciled storage content and handle explicit base-revision selection. |
55
- | `deletion.ts`, `renaming.ts` | Apply deletion, revision removal, and source-preserving rename operations. |
56
- | `deletionRecovery.ts` | Recover retained logical deletions and interrupted cleanup under opt-in provenance and shared file admission. |
57
- | `reflection.ts`, `protection.ts` | Reflect database revisions while protecting unsynchronised storage content. |
58
- | `events.ts`, `selection.ts` | Interpret ordinary, restored, retried, and replicated events against current selection and storage. |
59
- | `chunks.ts` | Repair chunks through the host's save method with bounded concurrency. |
49
+ | Modules | Responsibility |
50
+ | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
51
+ | `context.ts`, `storage.ts` | Capture injected services, own per-instance state, retain host method dispatch, and resolve file paths, stubs, and bodies. |
52
+ | `locking.ts` | Acquire sorted document locks and run deferred conflict hooks after releasing them. |
53
+ | `provenance.ts`, `scanning.ts` | Track the displayed revision and content evidence, classify storage, revalidate snapshots, and inspect scan hints. |
54
+ | `saving.ts` | Save ordinary or reconciled storage content and handle explicit base-revision selection. |
55
+ | `deletion.ts`, `renaming.ts` | Apply deletion, revision removal, and source-preserving rename operations. |
56
+ | `deletionRecovery.ts` | Recover retained logical deletions and interrupted cleanup under opt-in provenance and shared file admission. |
57
+ | `reflection.ts`, `protection.ts` | Reflect database revisions while protecting unsynchronised storage content. |
58
+ | `events.ts`, `selection.ts` | Interpret ordinary, restored, retried, and replicated events against current selection and storage. |
59
+ | `chunks.ts` | Repair chunks through the host's save method with bounded concurrency. |
60
60
 
61
61
  The facade acquires document locks at public operation boundaries. Internal
62
62
  operations reuse the caller's locks; routing them back through a public wrapper
@@ -82,15 +82,15 @@ from the file handler's database and storage effects.
82
82
  interface, wire command assembly, peer-arrival policy, and host lifecycle. Its
83
83
  internal modules use narrow capabilities rather than the complete replicator:
84
84
 
85
- | Module under `TrysteroReplicator/` | Responsibility |
86
- | --- | --- |
87
- | `changeRelay.ts` | Own the changes feed, broadcast state, followed peers, and last sequence; schedule notifications and request pulls. |
88
- | `peerAgreement.ts` | Request authentication and compare tweak, path-identity, and ID-derivation agreement without exposing the ID key. |
89
- | `configurationExchange.ts` | Prepare shared settings, obtain passphrases, encrypt or decrypt configuration, and validate imported ID settings. |
90
- | `progress.ts` | Own acknowledged-attempt state and module-realm attempt numbering, project progress events, and report progress to the peer. |
91
- | `configuredTargets.ts` | Resolve configured peer names, wait for discovery with listener cleanup, and aggregate sequential baseline synchronisation results. |
92
- | `transfers.ts` | Own available and active peer sets, apply transfer gates, run the shared replication engine, and finalise progress. |
93
- | `relayControl.ts` | Adapt shared Trystero relay controls and disconnect a captured socket set without changing host-stop ordering. |
85
+ | Module under `TrysteroReplicator/` | Responsibility |
86
+ | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
87
+ | `changeRelay.ts` | Own the changes feed, broadcast state, followed peers, and last sequence; schedule notifications and request pulls. |
88
+ | `peerAgreement.ts` | Request authentication and compare tweak, path-identity, and ID-derivation agreement without exposing the ID key. |
89
+ | `configurationExchange.ts` | Prepare shared settings, obtain passphrases, encrypt or decrypt configuration, and validate imported ID settings. |
90
+ | `progress.ts` | Own acknowledged-attempt state and module-realm attempt numbering, project progress events, and report progress to the peer. |
91
+ | `configuredTargets.ts` | Resolve configured peer names, wait for discovery with listener cleanup, and aggregate sequential baseline synchronisation results. |
92
+ | `transfers.ts` | Own available and active peer sets, apply transfer gates, run the shared replication engine, and finalise progress. |
93
+ | `relayControl.ts` | Adapt shared Trystero relay controls and disconnect a captured socket set without changing host-stop ordering. |
94
94
 
95
95
  The facade's existing relay accessors refer to the relay's single state object.
96
96
  Agreement and configuration operations obtain snapshot settings and current
@@ -132,19 +132,33 @@ database, room, or complete host environment. Decision types remain available
132
132
  through their previous Server exports.
133
133
 
134
134
  The Server's optional third constructor argument accepts `createRoom`, defaulting
135
- to Trystero's `joinRoom`. It is called at the original point after diagnostic
136
- subscriptions, and real `RpcRoom` instances still own message and peer-event
137
- subscriptions. Registration and the synchronous `beforeAdvertisement` hook
138
- precede advertisement sending. A separate boundary spec uses real RPC rooms and
139
- paired fake Trystero rooms to verify calls, notifications, cancellation, and close.
135
+ to Trystero's `joinRoom`. The server subscribes to diagnostics before joining.
136
+ Starting with [Commonlib 0.7.0](../updates.md#070), it creates a Fancy Kit
137
+ room over the `rpc2` action through `TrysteroRpcRoom`.
138
+ The adapter uses a native `AbortController` by default and converts handler
139
+ cancellation reasons to Commonlib `RpcError` instances before aborting.
140
+ The RPC room owns its message and peer-event subscriptions. Commonlib supplies peer admission,
141
+ method binding, and room shutdown. The adapter uses the decoded request to
142
+ retain the full method name in notification warnings and redacts callback
143
+ errors from those warnings. Response-bearing calls carry the original
144
+ structured errors when they can be normalised. The public
145
+ Commonlib `RpcRoom` retains the standalone room constructor. An
146
+ `instanceof RpcRoom` check recognises standalone Commonlib rooms and hosted
147
+ `TrysteroRpcRoom` instances. Both rooms use Fancy Kit's `RpcSession`.
148
+ Registration and the synchronous `beforeAdvertisement` hook precede
149
+ advertisement sending. The boundary spec uses real RPC rooms and paired fake
150
+ Trystero rooms to verify calls, notifications, cancellation, errors, and close.
151
+ It also verifies the PouchDB helpers against an in-memory database over those rooms.
152
+ The packed-consumer check composes the hosted room and session with the
153
+ Commonlib PouchDB helpers.
140
154
  The replicator facade's optional fourth constructor argument supplies relay
141
155
  controls, preserving its third finite-operation-owner argument. Disconnection
142
156
  reads sockets, pauses reconnection, closes the captured set, and starts the public
143
157
  host-stop operation in the original order. Default controls use the shared
144
158
  Trystero registry.
145
159
 
146
- `src/rpc/RpcRoom.ts` retains registrations, inbound request routing, transport,
147
- and chunk state. `RpcRoom/pendingInvocations.ts` owns outbound response waits,
160
+ The standalone `src/rpc/RpcRoom.ts` retains registrations, inbound request
161
+ routing, transport, and chunk state. `RpcRoom/pendingInvocations.ts` owns outbound response waits,
148
162
  deadlines, abort subscriptions, settlement, and request-before-cancel ordering.
149
163
  The room supplies transport, request IDs, timing, and warning callbacks, and
150
164
  forwards peer departure and close events. Notifications bypass this coordinator.
@@ -237,6 +251,12 @@ npm run test:package
237
251
 
238
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.
239
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
+
240
260
  `test:contracts` runs the host-neutral result contracts which are intended to be reusable while implementations move:
241
261
 
242
262
  - `test:contract:context` verifies event delivery, default instance isolation, translation results, and host extension of `ServiceContextContract`;
@@ -251,7 +271,7 @@ The multiple-remote profile contract has focused unit coverage in `src/serviceFe
251
271
 
252
272
  The full offline scanner applies both the host's target-file policy and Commonlib's built-in `shouldBeIgnored` policy before constructing storage/database pairs. This keeps legacy LiveSync log files and flag files outside ordinary create, restore, and delete decisions even when a host accepts their file extension. Lower-level write guards remain a defence for direct calls; they are not the normal full-scan filter. The complete pair-state decision matrix and database-to-storage reflection result contract are documented in [Full offline scan](offline-scanner.md). Extend that document, the Cartesian action test, and both collection-side tests whenever the policy changes.
253
273
 
254
- The unreleased watcher deletion checks and the separate database-to-storage reflection path are recorded in [Storage events and database-to-storage reflection](storage-events-and-reflection.md).
274
+ The watcher deletion checks and the separate database-to-storage reflection path are documented in [Storage events and database-to-storage reflection](storage-events-and-reflection.md).
255
275
 
256
276
  File-path parsing recognises only the leading `i:`, `ix:`, and `ps:` namespaces. Colons elsewhere belong to the path, including the complete remainder after one namespace. Document-ID parsing additionally recognises `h:` and `f:`; those document IDs are not ordinary storage paths. Keep normalisation, selection patterns, and database lookup on the complete path. `pathPrefixes.unit.spec.ts`, `typeUtils.unit.spec.ts`, and `PathService.unit.spec.ts` cover these conversions, and `ServiceFileHandlerBase.colonPaths.unit.spec.ts` exercises storage and reflection with real PouchDB Metadata and Chunks. Host filename restrictions remain a separate contract: a host must not interpret an unsupported name as permission to write a shortened one.
257
277
 
@@ -281,6 +301,30 @@ The active local database identity, settings-selected reset sequence, and lifecy
281
301
 
282
302
  `TypedReplicationCoordinator` keeps user-initiated, unattended, continuous, and stop roles as explicit control flows. Their interaction authority, readiness position, activity accounting, and failure handling differ, so these roles must not be collapsed into a flag-driven capability table. Share only mechanics whose lifecycle meaning is identical, such as atomic context acquisition and finite activity accounting, and retain a focused sequencing test for each role.
283
303
 
304
+ Starting with [Commonlib 0.7.0](../updates.md#070), a host may supply
305
+ `ContinuousReplicationRequest.onStartSettled` to observe the result of one
306
+ continuous start. The ordinary `startContinuous()` result
307
+ still reports admission. CouchDB settles the observer when it hands off a
308
+ live PouchDB handle, when preparation or the initial finite pull fails, or
309
+ when the start is cancelled. Requests that join the same CouchDB start
310
+ observe the same handoff or failure. A later transport interruption belongs
311
+ to the live handle's reconnect behaviour.
312
+
313
+ An attributed failure carries the host's online state and the timestamp
314
+ observed at the failing gate or request. The `networkFailure` field is
315
+ present for an offline readiness refusal or a confirmed transport failure
316
+ which prevents handoff after any internal fallback. Preparation handlers return
317
+ `true` to continue, `false` to refuse, or the network failure observed by
318
+ the rejecting operation. Legacy callers of the preparation hooks still receive
319
+ a boolean. The readiness evaluator carries the first rejection to the start
320
+ request. Hosts own the decision and lifecycle for requesting another start.
321
+
322
+ An explicit call to `stopActiveTransfer()` emits
323
+ `EVENT_REPLICATION_ABORT_REQUESTED` on the service context when the request
324
+ arrives, including when the provider has no active transfer. A host can then
325
+ withdraw a pending automatic start before the current transfer finishes
326
+ stopping.
327
+
284
328
  ### P2P composition ownership
285
329
 
286
330
  `useP2PReplicatorFeature` composes one stable P2P service owner, one room-session owner, and their lifecycle bindings. The service exposes focused views, including owner-arbitrated connection-probe admission, over that same state. When `ReplicatorService` requests a P2P Replicator, the provider returns a fresh non-owning adapter. Replacing or disposing that active adapter does not cancel service-owned work or retire the room; the explicit stop capability and transport lifecycle view own those distinct operations. Database reset and explicit close reach the stable service through their pre-destruction lifecycle hooks, so non-ownership by the active adapter cannot leave a room using an unavailable local database.
@@ -310,7 +354,7 @@ The [maintained-host examples and evidence](proven-in-use.md) are optional conte
310
354
 
311
355
  ### Testing an unpublished Octagonal Wheels dependency
312
356
 
313
- The current integration pins the published Octagonal Wheels 0.1.56 release and
357
+ The current integration pins the published Octagonal Wheels 0.1.57 release and
314
358
  uses the ordinary package gate. The override below is for future unpublished
315
359
  dependency changes.
316
360
 
@@ -382,7 +426,7 @@ Resolve these questions before describing the corresponding behaviour as stable:
382
426
  The platform and RPC ownership decisions are accepted:
383
427
 
384
428
  - `/node` and `/browser` are supported platform façades. They deliberately hide platform-specific imports, adapters, and review exceptions behind package-owned boundaries. The selected Node built-in re-exports are part of that boundary; package tests must continue to prove that browser-capable entries do not reach Node-only code.
385
- - `/rpc` is transitional and is not part of the stable Commonlib 1.0 contract. Keep it only while the maintained LiveSync P2P composition requires the existing implementation. The RPC core, transport integration, wire protocol, and PouchDB bridge are planned for an independently owned rewrite in Fancy Kit; do not encourage new Commonlib consumers to adopt the current entry.
429
+ - `/rpc` is transitional and is not part of the stable Commonlib 1.0 contract. Keep it only while the maintained LiveSync P2P composition requires it. The hosted P2P composition uses the Fancy Kit RPC core through the adapter described above. New consumers should use the supported Commonlib entry points.
386
430
  - The high-level composition target is a narrow asynchronous `createLiveSyncFileClient` factory, not a general Service Hub factory. It must keep the context, service graph, database implementation, protocol setup, watches, reconnect work, and shutdown order private. It resolves only after readiness and returns a small file façade with `list`, `get`, `put`, `delete`, `watch`, and `close`. Full Obsidian, CLI, and browser applications retain host-specific composition because they own UI, persistence, permissions, storage events, and process policy.
387
431
  - `DirectFileManipulator` is a migration source for that file client rather than the stable target contract. Do not carry its fire-and-forget constructor initialisation, exposed service graph and database documents, incomplete enumeration, implicit watch retry, or deprecated settings options into the new public API. Define the exact result, conflict, concurrency, watch checkpoint, retry, and error semantics only after the LiveSync 1.0 work rather than making that future client a release gate.
388
432
 
@@ -390,7 +434,7 @@ The platform and RPC ownership decisions are accepted:
390
434
 
391
435
  The package build records each compatibility path explicitly. Do not add a wildcard export. A new compatibility path requires a real downstream import, a packed-consumer or downstream test, and a migration plan towards a focused public entry or the owning package.
392
436
 
393
- For the unreleased reflection integration, service composition uses
437
+ For the reflection integration introduced in Commonlib 0.6.0, service composition uses
394
438
  `handlers<T>().firstApplicable()` to select the first non-`undefined` result and
395
439
  `handlers<T>().allOrThrow()` to run boolean callbacks until one returns `false`.
396
440
  Both propagate callback exceptions unchanged and retain the existing registration,
@@ -412,7 +456,6 @@ The classification in `docs/migration/compatibility-classification.json` is acce
412
456
 
413
457
  Release preparation and staged-publication checks are documented in [the maintainer runbook](releasing.md).
414
458
 
415
-
416
459
  The shared value extraction uses the declared Octagonal Wheels dependency. Its
417
460
  `utils.runtime-tools.unit.spec.ts` tests preserve the legacy adapter contracts;
418
461
  `runtime-tools-types.ts` and `runtime-tools-runtime.mjs` check the installed
@@ -128,9 +128,8 @@ persistent replication state is added.
128
128
 
129
129
  ## Best-effort change notifications
130
130
 
131
- Implementation note: this notification path is unreleased, reviewed against
132
- Commonlib 0.4.3 and Self-hosted LiveSync 1.0.49. It does not change the published
133
- status of the lifecycle and diagnostics described elsewhere in this document.
131
+ This notification path is available in [Commonlib 0.5.0](../updates.md#050).
132
+ The original review used Commonlib 0.4.3 and Self-hosted LiveSync 1.0.49.
134
133
 
135
134
  P2P change notifications ask a following peer to fetch database changes; they do
136
135
  not carry Vault data or confirm that a transfer has succeeded. The sender uses
@@ -157,9 +157,16 @@ saved stub, cache, and event label cannot establish completion by themselves.
157
157
  ## Processing directions
158
158
 
159
159
  `StorageEventManager.appendQueue` receives watcher events, applies target and
160
- ignore policies, and queues `CREATE`, `CHANGED`, `DELETE`, or `RENAME` work. A
161
- rename from a selected path to a rejected path becomes a `DELETE` with an
162
- old-path deleted stub and the destination in `FileEventArgs.renameTarget`.
160
+ ignore policies, and queues `CREATE`, `CHANGED`, `DELETE`, or `RENAME` work.
161
+ Starting with [Commonlib 0.7.0](../updates.md#070), a host can provide
162
+ `isTargetInternalFile` in `StorageEventManagerBaseDependencies` to admit
163
+ `INTERNAL` events separately from the ordinary `syncOnlyRegEx` allow-list
164
+ and `syncInternalFiles` gate. The host callback determines internal-file
165
+ eligibility within the manager's protected-path checks. For example, it can use
166
+ `vaultService.isTargetFile(path, { internalFileEvent: true })`. Hosts without the
167
+ callback use the ordinary admission path. A rename from a selected path to a
168
+ rejected path becomes a `DELETE` with an old-path deleted stub and the destination
169
+ in `FileEventArgs.renameTarget`.
163
170
  A rename from an excluded path to a selected path becomes a `CREATE`.
164
171
 
165
172
  `renameTarget` is recorded only when one incoming `RENAME` is converted in
@@ -237,8 +244,8 @@ waiting, or already in a handler. It waits for each actual handler result and
237
244
  for the ordered snapshot update which records that result; releasing a timer is
238
245
  not completion. Later events do not extend that captured boundary. A newer
239
246
  coalesced operation satisfies an earlier one only when its successful result
240
- covers the earlier intent. A failed handler or snapshot update is reported to
241
- 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
242
249
  local completion under the selected handler contract only; it does not prove replication or receipt by another
243
250
  Vault.
244
251
 
@@ -252,6 +259,34 @@ timers do not occupy a processing slot, and time spent waiting for a slot does
252
259
  not restart the maximum delay. Once due, the operation acquires a slot and reads
253
260
  current content for processing.
254
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
+
255
290
  ## Retrying ordinary file operations
256
291
 
257
292
  The following extension is available in Commonlib 0.4.1. A failed ordinary
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vrtmrz/livesync-commonlib",
3
- "version": "0.6.1",
3
+ "version": "0.8.0",
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",
@@ -1021,6 +1021,7 @@
1021
1021
  "@smithy/types": "^4.14.3",
1022
1022
  "@smithy/util-retry": "^4.4.5",
1023
1023
  "@trystero-p2p/nostr": "0.26.0",
1024
+ "@vrtmrz/rpc": "0.1.0",
1024
1025
  "@vrtmrz/value-store": "0.1.0",
1025
1026
  "diff-match-patch": "^1.0.5",
1026
1027
  "events": "^3.3.0",
@@ -1028,7 +1029,7 @@
1028
1029
  "idb": "^8.0.3",
1029
1030
  "markdown-it": "^14.3.3",
1030
1031
  "minimatch": "^11.0.3",
1031
- "octagonal-wheels": "0.1.56",
1032
+ "octagonal-wheels": "0.1.57",
1032
1033
  "pouchdb-adapter-http": "^9.0.0",
1033
1034
  "pouchdb-adapter-idb": "^9.0.0",
1034
1035
  "pouchdb-adapter-indexeddb": "^9.0.0",
@@ -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
- };