@vrtmrz/livesync-commonlib 0.5.0 → 0.6.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 (73) hide show
  1. package/dist/common/LSError.d.ts +13 -0
  2. package/dist/common/LSError.js +19 -1
  3. package/dist/diagnostics/local.d.ts +7 -2
  4. package/dist/interfaces/DatabaseFileAccess.d.ts +20 -4
  5. package/dist/interfaces/FileHandler.d.ts +67 -1
  6. package/dist/interfaces/FileHandler.js +16 -0
  7. package/dist/interfaces/StorageEventManager.d.ts +7 -0
  8. package/dist/managers/ChunkFetcher.d.ts +16 -0
  9. package/dist/managers/ChunkFetcher.js +190 -112
  10. package/dist/managers/EntryManager/EntryManager.d.ts +7 -0
  11. package/dist/managers/EntryManager/EntryManager.js +6 -0
  12. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +9 -5
  13. package/dist/managers/EntryManager/EntryManagerImpls.js +103 -76
  14. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.d.ts +7 -3
  15. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.js +83 -16
  16. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.d.ts +3 -2
  17. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.js +38 -36
  18. package/dist/managers/LayeredChunkManager/types.d.ts +15 -1
  19. package/dist/managers/LayeredChunkManager.d.ts +4 -0
  20. package/dist/managers/LayeredChunkManager.js +19 -6
  21. package/dist/managers/LiveSyncManagers.d.ts +2 -0
  22. package/dist/managers/LiveSyncManagers.js +6 -0
  23. package/dist/managers/StorageEventManager.d.ts +22 -0
  24. package/dist/managers/StorageEventManager.js +48 -1
  25. package/dist/pouchdb/LiveSyncLocalDB.d.ts +32 -0
  26. package/dist/pouchdb/LiveSyncLocalDB.js +72 -18
  27. package/dist/pouchdb/LocalDatabaseReadScope.d.ts +24 -0
  28. package/dist/pouchdb/LocalDatabaseReadScope.js +62 -0
  29. package/dist/pouchdb/pathIdentityCompatibility.d.ts +6 -2
  30. package/dist/pouchdb/pathIdentityCompatibility.js +15 -10
  31. package/dist/replication/contentRead.d.ts +3 -0
  32. package/dist/replication/contentRead.js +4 -0
  33. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +8 -1
  34. package/dist/replication/couchdb/LiveSyncReplicator.js +187 -119
  35. package/dist/replication/index.d.ts +5 -1
  36. package/dist/replication/index.js +18 -1
  37. package/dist/serviceFeatures/offlineScanner/files.d.ts +1 -1
  38. package/dist/serviceFeatures/offlineScanner/files.js +27 -7
  39. package/dist/serviceFeatures/offlineScanner/scan.d.ts +5 -1
  40. package/dist/serviceFeatures/offlineScanner/scan.js +2 -1
  41. package/dist/serviceFeatures/offlineScanner.d.ts +1 -1
  42. package/dist/serviceFeatures/offlineScanner.js +10 -2
  43. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +13 -0
  44. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +190 -123
  45. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +17 -7
  46. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +3 -2
  47. package/dist/serviceModules/ServiceFileHandlerBase/events.js +9 -9
  48. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -9
  49. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +10 -0
  50. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +28 -4
  51. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +11 -5
  52. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +144 -58
  53. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +16 -2
  54. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +1 -0
  55. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +7 -2
  56. package/dist/serviceModules/ServiceFileHandlerBase.js +13 -4
  57. package/dist/services/base/ControlService.js +1 -5
  58. package/dist/services/base/DatabaseEventService.d.ts +3 -0
  59. package/dist/services/base/DatabaseEventService.js +3 -0
  60. package/dist/services/base/DatabaseService.d.ts +15 -0
  61. package/dist/services/base/DatabaseService.js +85 -4
  62. package/dist/services/base/IService.d.ts +18 -1
  63. package/dist/services/base/KeyValueDBService.d.ts +5 -4
  64. package/dist/services/base/KeyValueDBService.js +46 -48
  65. package/dist/services/base/ReplicationService.d.ts +3 -1
  66. package/dist/services/base/ReplicationService.js +3 -1
  67. package/dist/services/base/VaultScanResult.d.ts +5 -0
  68. package/dist/services/lib/HandlerUtils.d.ts +40 -5
  69. package/dist/services/lib/HandlerUtils.js +52 -4
  70. package/docs/development.md +8 -0
  71. package/docs/offline-scanner.md +46 -0
  72. package/docs/releasing.md +42 -0
  73. package/package.json +1 -1
@@ -109,7 +109,7 @@ class MultiBinder {
109
109
  * Adds a handler function.
110
110
  * Note: The same function is only added once.
111
111
  * @param callback The handler function to add.
112
- * @param priority The priority of the handler, Do not use floating numbers to prevent confusion.
112
+ * @param priority Lower numbers run first; equal priorities retain registration order. Use integers.
113
113
  * @returns A function to unregister the added handler.
114
114
  *
115
115
  */
@@ -221,6 +221,16 @@ class AllHandler extends BooleanHandlerBase {
221
221
  return true;
222
222
  }
223
223
  }
224
+ class AllOrThrowHandler extends BooleanHandlerBase {
225
+ async invoke(...args) {
226
+ for (const callback of [...this._callbacks]) {
227
+ if (await callback(...args) === false) {
228
+ return false;
229
+ }
230
+ }
231
+ return true;
232
+ }
233
+ }
224
234
  class AllWithResultHandler extends MultiBinder {
225
235
  /**
226
236
  * Invokes every handler in order. The first non-boolean continuation result
@@ -320,9 +330,9 @@ class AnySuccessHandler extends BooleanHandlerBase {
320
330
  }
321
331
  class FirstResultHandler extends MultiBinder {
322
332
  /**
323
- * Invokes handlers sequentially until one returns a non-falsy value.
333
+ * Invokes handlers sequentially, skipping `false`, `undefined`, and callback failures.
324
334
  * @param args The arguments to pass to the handlers.
325
- * @returns The first non-falsy result from the handlers, or false if none found.
335
+ * @returns The first result other than `false` or `undefined`, or `false` when none applies.
326
336
  */
327
337
  async invoke(...args) {
328
338
  const _callbacks = [...this._callbacks];
@@ -340,6 +350,17 @@ class FirstResultHandler extends MultiBinder {
340
350
  return false;
341
351
  }
342
352
  }
353
+ class FirstApplicableHandler extends MultiBinder {
354
+ async invoke(...args) {
355
+ for (const callback of [...this._callbacks]) {
356
+ const result = await callback(...args);
357
+ if (result !== void 0) {
358
+ return result;
359
+ }
360
+ }
361
+ return void 0;
362
+ }
363
+ }
343
364
  class FirstHandledHandler extends MultiBinder {
344
365
  /**
345
366
  * Whether at least one callback is currently registered.
@@ -379,6 +400,10 @@ function allFunction(name) {
379
400
  const handler = new AllHandler(name ?? "handleAllFunc");
380
401
  return getMultipleBound(handler);
381
402
  }
403
+ function allOrThrowFunction(name) {
404
+ const handler = new AllOrThrowHandler(name ?? "allOrThrowFunction");
405
+ return getMultipleBound(handler);
406
+ }
382
407
  function allSettledFunction(name) {
383
408
  const handler = new SettledAllHandler(name ?? "allSettledFunction");
384
409
  return getMultipleBound(handler);
@@ -405,6 +430,12 @@ function firstResultFunction(name) {
405
430
  const handler = new FirstResultHandler(name ?? "firstResultFunction");
406
431
  return getMultipleBound(handler);
407
432
  }
433
+ function firstApplicableFunction(name) {
434
+ const handler = new FirstApplicableHandler(
435
+ name ?? "firstApplicableFunction"
436
+ );
437
+ return getMultipleBound(handler);
438
+ }
408
439
  function firstHandledFunction(name) {
409
440
  const handler = new FirstHandledHandler(
410
441
  name ?? "firstHandledFunction"
@@ -448,6 +479,10 @@ function handlers() {
448
479
  all(name) {
449
480
  return allFunction(String(name));
450
481
  },
482
+ /** Stop at a false result; propagate callback errors and rejections unchanged. */
483
+ allOrThrow(name) {
484
+ return allOrThrowFunction(String(name));
485
+ },
451
486
  /**
452
487
  * Create a handler that invokes every added handler sequentially and
453
488
  * returns true only if all of them succeed.
@@ -494,13 +529,22 @@ function handlers() {
494
529
  return anySuccessFunction(String(name));
495
530
  },
496
531
  /**
497
- * Create a handler that invokes all added handler functions sequentially until one returns a non-falsy value.
532
+ * Create a handler which skips `false`, `undefined`, and logged callback failures.
498
533
  * @param name
499
534
  * @returns
500
535
  */
501
536
  firstResult(name) {
502
537
  return firstResultFunction(String(name));
503
538
  },
539
+ /**
540
+ * Try handlers in priority and registration order until one returns a value.
541
+ * @param name - The callback on `T` whose invocation a handler may decline with `undefined`.
542
+ * @returns The first non-`undefined` result, or `undefined` when every handler declines.
543
+ * @remarks All other values stop dispatch. Callback failures propagate unchanged.
544
+ */
545
+ firstApplicable(name) {
546
+ return firstApplicableFunction(String(name));
547
+ },
504
548
  /**
505
549
  * Create a handler that invokes registered handlers until one completes or vetoes.
506
550
  * Callback errors and rejections propagate unchanged.
@@ -533,12 +577,14 @@ function handlers() {
533
577
  }
534
578
  export {
535
579
  AllHandler,
580
+ AllOrThrowHandler,
536
581
  AllWithResultHandler,
537
582
  AnySuccessHandler,
538
583
  Binder,
539
584
  BooleanHandlerBase,
540
585
  Dispatch,
541
586
  DispatchParallel,
587
+ FirstApplicableHandler,
542
588
  FirstHandledHandler,
543
589
  FirstResultHandler,
544
590
  LazyBinder,
@@ -546,6 +592,7 @@ export {
546
592
  ParallelAllHandler,
547
593
  SettledAllHandler,
548
594
  allFunction,
595
+ allOrThrowFunction,
549
596
  allParallelFunction,
550
597
  allSettledFunction,
551
598
  anySuccessFunction,
@@ -553,6 +600,7 @@ export {
553
600
  bailFirstFailureWithResultFunction,
554
601
  bindableFunction,
555
602
  dispatchParallelFunction,
603
+ firstApplicableFunction,
556
604
  firstHandledFunction,
557
605
  firstResultFunction,
558
606
  handlers,
@@ -390,6 +390,14 @@ The platform and RPC ownership decisions are accepted:
390
390
 
391
391
  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
392
 
393
+ For the unreleased reflection integration, service composition uses
394
+ `handlers<T>().firstApplicable()` to select the first non-`undefined` result and
395
+ `handlers<T>().allOrThrow()` to run boolean callbacks until one returns `false`.
396
+ Both propagate callback exceptions unchanged and retain the existing registration,
397
+ priority, and invocation-snapshot semantics. Reflection and snapshot failures can
398
+ therefore reach their owner without a service-specific dispatcher. The existing
399
+ `firstResult`, `all`, and other handler contracts retain their error handling.
400
+
393
401
  The existing `compat/services/lib` helpers `bindableFunction` and `lazyBindableFunction` return an `UnregisterFunction` from `setHandler()`. It removes only the assignment made by that registration while it remains current; a stale remover, including after an override with the same callback, and repeated removals are no-ops. Existing callers may ignore the return value, but implementations and test doubles of the handler interfaces must return a remover. Keep this contract within the existing compatibility boundary rather than presenting it as a general SDK pattern.
394
402
 
395
403
  After the reviewed Self-hosted LiveSync revision changes, inspect its current compatibility imports with:
@@ -201,3 +201,49 @@ bodies or invokes physical deletion. All affected paths are revalidated by their
201
201
  handler. See [Deletion recovery](deletion-recovery.md) for completion, error,
202
202
  concurrency, and cost contracts. This opt-in extension is published in
203
203
  [Commonlib 0.4.2](https://github.com/vrtmrz/livesync-commonlib/releases/tag/0.4.2).
204
+
205
+
206
+ ## Unreleased host recovery integration
207
+
208
+ The following extension was reviewed against Commonlib 0.5.0 and Self-hosted
209
+ LiveSync 1.0.50. It is implemented on the working branch and is not yet published.
210
+
211
+ `VaultScanOptions.onReflectionFailed(target, error)` receives a terminal ordinary DB-to-Vault reflection failure. The target is the selected input document ID and revision; a content error can separately identify the historical revision which could not be read. The scanner awaits the owner callback once. A callback rejection propagates as a persistence failure and is not converted into another content failure. Completed reflection, normal absence, and policy skips do not create failed work.
212
+
213
+ Strict internal reads propagate `ContentReadError` with directly observed `local-database` or `remote` resources and the original `cause`. An empty resource list conveys no automatic recovery prerequisite. The contract does not classify transient failures from names, messages, status defaults, or cause chains. Local Chunk absence is ordinary while a fallback or finite producer can still supply the content. A terminal error is reported after the existing recheck and retry rules finish; a successful fallback discards intermediate failure evidence.
214
+
215
+ `ReflectionOperationContext` carries the target, source policy, and optional checkpoint. `reflectDatabaseEntry` and `processSynchroniseResult` return `completed`, `policy`, or `cancelled`; uncontinuable failures reject the operation. Existing Boolean retrieval and `dbToStorage` facades retain their compatibility conversion at the outside boundary. They are not used to recover a lost cause from a second callback channel. `/replication` re-exports the neutral content and reflection contracts for consumers.
216
+
217
+ A `policy` result means that applicable policy intentionally withheld ordinary
218
+ file reflection, for example to preserve an unsynchronised edit as a conflict,
219
+ queue conflict resolution, or leave an existing folder untouched. A host may
220
+ also decline automatic file application. This is a normal policy decision;
221
+ it does not certify completed reflection or schedule an automatic retry.
222
+ Protection and conflict scheduling may already have occurred.
223
+
224
+ The reflection result keeps its `status` shape, with shared immutable
225
+ `FILE_REFLECTION_COMPLETED`, `FILE_REFLECTION_POLICY`, and
226
+ `FILE_REFLECTION_CANCELLED` values. `isReflectionCompleted` and
227
+ `isReflectionCancelled` express the corresponding caller decisions. The scanner
228
+ converts reflection outcomes to its own pair result once, before applying
229
+ completion events and observed-time bookkeeping.
230
+
231
+ A host can use `IReplicationService.onFiniteReplicationCompleted` to schedule
232
+ retained work after a successful, uncancelled CouchDB finite pull or bidirectional
233
+ transfer, including the initial pull before continuous replication. Zero changed
234
+ documents still qualify. Push-only operations, continuous events, failed attempts,
235
+ and Chunk fetch completion do not emit this signal. Observer errors are diagnostic
236
+ and do not change a successfully completed replication into a failed transfer.
237
+ The notification runs inside the transfer owner, whose finite delivery activity
238
+ may still be held. Handlers must acknowledge admission without awaiting file or
239
+ Chunk operations which depend on that activity ending. The service itself stores
240
+ no retry records and starts no additional replication.
241
+
242
+ For one previously selected ordinary content target, `processFilePair` reuses
243
+ existing scan policy without listing the Vault again. The host must supply fresh,
244
+ identity-validated Metadata, a current storage stub or absence, and ordinary scan
245
+ options; existing file-handler locking and revalidation still own writes. A retained retry passes its existing context through `VaultScanOptions.reflectionOperation`, including its pre-write checkpoint. Full
246
+ scan deletion-recovery planning remains separate. The optional
247
+ `fileHandler.inspectCurrentFileProvenance(path, revision)` checks current bytes against
248
+ existing device-local provenance and current Metadata without retrieving Chunks.
249
+ A missing or mismatched record is inconclusive; a failed inspection rejects instead of becoming a mismatch. Neither permits an overwrite. Hosts own retention, retry bounds, and user presentation.
package/docs/releasing.md CHANGED
@@ -79,6 +79,48 @@ on `ServiceFileAccessBase` inherit the adapter or listing fallback. The P2P
79
79
  client also exposes its closed provider state explicitly in its types. These
80
80
  source compatibility changes use the next minor version under the policy.
81
81
 
82
+ ### 0.6.0 integration changes
83
+
84
+ Version 0.6.0 is an unreleased candidate with source compatibility changes to
85
+ strict reads, file reflection, and database lifecycle integration. The standard
86
+ base implementations supply the new members. Custom overrides must also follow
87
+ the updated return and failure contracts.
88
+
89
+ Direct interface implementations must provide these additional members:
90
+
91
+ | Interface | Required members |
92
+ | --- | --- |
93
+ | `DatabaseFileAccess` | `readEntryMeta`, `readEntryFromMeta`, `readEntry`, `readConflictedRevs`, and `readLiveContentRevisions` |
94
+ | `IFileHandler` | `reflectDatabaseEntry` |
95
+ | `IDatabaseService` | `localDatabaseDirect`, `reopenDatabase`, `canReadCurrentDatabaseInfo`, and `closeDatabase` |
96
+ | `IDatabaseEventService` | `onBeforeDatabaseResume`, `onBeforeDatabaseRecovery`, and `onAfterDatabaseRecovery` |
97
+ | `IReplicationService` | `onFiniteReplicationCompleted` and `onFileReflectionFailed` |
98
+
99
+ `IReplicationService.processSynchroniseResult()` now returns
100
+ `Promise<FileReflectionResult | undefined>` instead of `Promise<boolean>`.
101
+ Handlers return one of `FILE_REFLECTION_COMPLETED`, `FILE_REFLECTION_POLICY`, or
102
+ `FILE_REFLECTION_CANCELLED`; `undefined` declines handling. These values and
103
+ `isReflectionCompleted()` are exported from `@vrtmrz/livesync-commonlib/replication`.
104
+ Only a completed result permits completion bookkeeping. Do not interpret every
105
+ returned object as success: policy and cancellation do not establish completed
106
+ reflection. Terminal failures reject to the operation owner.
107
+
108
+ The strict read methods preserve ordinary absence while rejecting failed I/O or
109
+ incomplete content. Existing Boolean and array-returning facades keep their
110
+ compatibility conversions; changing a call to a strict method therefore also
111
+ requires handling its rejection at the operation owner.
112
+
113
+ Direct reads through `LiveSyncLocalDB.localDatabase` bypass caller-wait retirement.
114
+ Use `readDBEntry()` for file content, `getRaw()` or `allDocsRaw()` for raw document
115
+ reads, and `readFromDatabase()` for other read-only operations. A read callback
116
+ must not perform writes or apply later results to application state: its underlying
117
+ I/O can continue after its caller wait ends. Raw replication, changes-feed, and
118
+ maintenance integrations retain responsibility for their own completion and lifetime.
119
+
120
+ See [Local database lifecycle](database-lifecycle.md) and
121
+ [Strict content reads and reflection](offline-scanner.md#unreleased-host-recovery-integration)
122
+ for operation ownership and host integration.
123
+
82
124
  ## Preparing a release
83
125
 
84
126
  Choose the version explicitly. For the 0.2 line, start at 0.2.0. A stable candidate can use its final version on the `next` dist-tag, then be checked by exact source revision and tarball SHA-256 before the same version is promoted to `latest`. No `-next.N` or `-rc.N` version is required; use a separate prerelease version only when it is useful for a distinct candidate. Package-proof versions are local artefacts and cannot be staged.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vrtmrz/livesync-commonlib",
3
- "version": "0.5.0",
3
+ "version": "0.6.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",