@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
@@ -40,6 +40,7 @@ import {
40
40
  LiveSyncAbstractReplicator
41
41
  } from "../LiveSyncAbstractReplicator.js";
42
42
  import { shareRunningResult } from "octagonal-wheels/concurrency/lock";
43
+ import { promiseWithResolvers } from "octagonal-wheels/promises";
43
44
  import { Semaphore } from "octagonal-wheels/concurrency/semaphore";
44
45
  import { Trench } from "octagonal-wheels/memory/memutil";
45
46
  import { StreamInbox } from "octagonal-wheels/bureau/StreamInbox";
@@ -63,6 +64,10 @@ import {
63
64
  replicationBlocked,
64
65
  replicationFailed
65
66
  } from "../ReplicatorProvider.js";
67
+ import {
68
+ getReplicationNetworkFailure,
69
+ OneShotConnectivityPreflightTimeoutError
70
+ } from "../remoteTransportFailure.js";
66
71
  import {
67
72
  forgetJoinedDevice as forgetJoinedDeviceFromStore,
68
73
  projectJoinedDevices
@@ -75,11 +80,12 @@ const currentVersionRange = {
75
80
  const selectorOnDemandPull = { selector: { type: { $ne: "leaf" } } };
76
81
  const DEFAULT_ONE_SHOT_CONNECTIVITY_TIMEOUT_MS = 6e4;
77
82
  const ONE_SHOT_REPLICATION_ALREADY_RUNNING = /* @__PURE__ */ Symbol("one-shot-replication-already-running");
78
- class OneShotConnectivityPreflightTimeoutError extends Error {
79
- constructor(timeoutMs) {
80
- super(`Remote connectivity preflight exceeded ${timeoutMs} ms.`);
81
- this.name = "OneShotConnectivityPreflightTimeoutError";
82
- }
83
+ const COUCHDB_REPLICATION_FAILED = { status: "failed" };
84
+ function couchDBReplicationFailure(networkFailure) {
85
+ return networkFailure ? { status: "failed", networkFailure } : COUCHDB_REPLICATION_FAILED;
86
+ }
87
+ function couchDBReplicationFailureFromError(error) {
88
+ return couchDBReplicationFailure(getReplicationNetworkFailure(error));
83
89
  }
84
90
  async function* genReplication(s, signal, log) {
85
91
  const inbox = new StreamInbox({ capacity: 1e4 });
@@ -137,6 +143,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
137
143
  * controller, so a stop request cannot be lost during catch-up.
138
144
  */
139
145
  continuousTask;
146
+ continuousStart;
140
147
  continuousStopWaiter;
141
148
  continuousStopRequested = false;
142
149
  continuousPhase;
@@ -284,6 +291,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
284
291
  const task = this.continuousTask;
285
292
  if (task) {
286
293
  this.continuousStopRequested = true;
294
+ this.continuousStart?.resolve({ status: "cancelled" });
287
295
  }
288
296
  this.abortController();
289
297
  this.finishReplicationProgress();
@@ -303,6 +311,10 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
303
311
  return this.openOneShotReplication(setting, showResult, false, "sync", ignoreCleanLock);
304
312
  }
305
313
  }
314
+ async startContinuousReplication(setting, onStartSettled) {
315
+ if (!this.nodeid) return false;
316
+ void this.openContinuousReplication(setting, false, false, onStartSettled);
317
+ }
306
318
  /**
307
319
  * Run one finite CouchDB attempt and retain only its own compatibility result.
308
320
  *
@@ -333,7 +345,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
333
345
  if (result instanceof UnsupportedEncryptedDocumentFormatError) {
334
346
  return replicationFailed(result);
335
347
  }
336
- return outcomeFromFiniteOpenReplication(result, centralCompatibilityRecoveryHint(decision));
348
+ return outcomeFromFiniteOpenReplication(result === true, centralCompatibilityRecoveryHint(decision));
337
349
  } catch (error) {
338
350
  return replicationFailed(error, centralCompatibilityRecoveryHint(decision));
339
351
  }
@@ -385,7 +397,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
385
397
  }
386
398
  /** Ask the current owner to inspect ambiguous managed-operation failures without joining its drain. */
387
399
  requestCurrentDatabaseInspection(error, database) {
388
- if (error instanceof RemoteRequestError || error instanceof ContentReadError && !error.failure.resources.includes("local-database")) {
400
+ if (error instanceof RemoteRequestError || getReplicationNetworkFailure(error) || error instanceof ContentReadError && !error.failure.resources.includes("local-database")) {
389
401
  return;
390
402
  }
391
403
  const service = this.env.services.database;
@@ -437,6 +449,25 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
437
449
  this.log("Replication paused", LOG_LEVEL_VERBOSE, "sync");
438
450
  }
439
451
  async processSync(syncHandler, showResult, docSentOnStart, docArrivedOnStart, syncMode, retrying, reportCancelledAsDone = true) {
452
+ const outcome = await this.runSyncTransfer(
453
+ syncHandler,
454
+ showResult,
455
+ docSentOnStart,
456
+ docArrivedOnStart,
457
+ syncMode,
458
+ retrying,
459
+ reportCancelledAsDone
460
+ );
461
+ return outcome instanceof UnsupportedEncryptedDocumentFormatError ? outcome : outcome.action;
462
+ }
463
+ async processSyncWithOutcome(...args) {
464
+ if (this.processSync !== LiveSyncCouchDBReplicator.prototype.processSync) {
465
+ const outcome = await this.processSync(...args);
466
+ return outcome instanceof UnsupportedEncryptedDocumentFormatError ? outcome : { action: outcome };
467
+ }
468
+ return await this.runSyncTransfer(...args);
469
+ }
470
+ async runSyncTransfer(syncHandler, showResult, docSentOnStart, docArrivedOnStart, syncMode, retrying, reportCancelledAsDone = true) {
440
471
  const databaseOwner = this.env.services.database?.localDatabaseDirect;
441
472
  const controller = new AbortController();
442
473
  if (this.controller) {
@@ -460,7 +491,7 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
460
491
  const releaser = await globalConcurrencyController.tryAcquire(1, REPLICATION_BUSY_TIMEOUT);
461
492
  if (releaser === false) {
462
493
  this.log("Replication stopped for busy.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
463
- return "FAILED";
494
+ return { action: "FAILED" };
464
495
  }
465
496
  releaser();
466
497
  if (controller.signal.aborted || this.controller !== controller) break;
@@ -495,24 +526,25 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
495
526
  }
496
527
  if (retrying) {
497
528
  if (this.docSent - docSentOnStart + (this.docArrived - docArrivedOnStart) > this.originalSetting.batch_size * 2) {
498
- return "NEED_RESURRECT";
529
+ return { action: "NEED_RESURRECT" };
499
530
  }
500
531
  }
501
532
  break;
502
533
  case "complete":
503
534
  this.replicationCompleted(showResult);
504
- return "DONE";
535
+ return { action: "DONE" };
505
536
  case "active":
506
537
  this.replicationActivated(showResult);
507
538
  break;
508
539
  case "denied":
509
540
  this.replicationDenied(e);
510
- return "FAILED";
541
+ return { action: "FAILED" };
511
542
  case "error": {
512
543
  const unsupportedFormat = UnsupportedEncryptedDocumentFormatError.findIn(e);
513
544
  this.replicationErrored(unsupportedFormat ?? e, databaseOwner);
514
545
  if (unsupportedFormat) return unsupportedFormat;
515
- if (isUnencryptedContentRejectedError(e)) return "FAILED";
546
+ if (isUnencryptedContentRejectedError(e)) return { action: "FAILED" };
547
+ const networkFailure = getReplicationNetworkFailure(e);
516
548
  this.log("Replication stopped.", showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
517
549
  if (this.env.services.remote.hadLastPostFailedBySize) {
518
550
  if (e && e.status == 413) {
@@ -520,14 +552,14 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
520
552
  `Something went wrong during synchronisation. Please check the log!`,
521
553
  LOG_LEVEL_NOTICE
522
554
  );
523
- return "FAILED";
555
+ return { action: "FAILED", networkFailure };
524
556
  }
525
- return "NEED_RETRY";
557
+ return { action: "NEED_RETRY", networkFailure };
526
558
  } else {
527
559
  this.log("Replication error", LOG_LEVEL_NOTICE, "sync");
528
560
  this.log(e, LOG_LEVEL_VERBOSE);
529
561
  }
530
- return "FAILED";
562
+ return { action: "FAILED", networkFailure };
531
563
  }
532
564
  case "paused":
533
565
  this.replicationPaused();
@@ -539,19 +571,19 @@ class LiveSyncCouchDBReplicator extends LiveSyncAbstractReplicator {
539
571
  }
540
572
  }
541
573
  if (reportCancelledAsDone) {
542
- return "DONE";
574
+ return { action: "DONE" };
543
575
  }
544
- return "CANCELLED";
576
+ return { action: "CANCELLED" };
545
577
  } catch (ex) {
546
578
  const unsupportedFormat = UnsupportedEncryptedDocumentFormatError.findIn(ex);
547
579
  if (unsupportedFormat || isUnencryptedContentRejectedError(ex)) {
548
580
  this.replicationErrored(unsupportedFormat ?? ex, databaseOwner);
549
- return unsupportedFormat ?? "FAILED";
581
+ return unsupportedFormat ?? { action: "FAILED" };
550
582
  }
551
583
  this.requestCurrentDatabaseInspection(ex, databaseOwner);
552
584
  this.log(`Unexpected synchronization exception`);
553
585
  this.log(ex, LOG_LEVEL_VERBOSE);
554
- return "FAILED";
586
+ return { action: "FAILED", networkFailure: getReplicationNetworkFailure(ex) };
555
587
  } finally {
556
588
  progress.dispose();
557
589
  controller.abort();
@@ -793,7 +825,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
793
825
  */
794
826
  async runOneShotReplication(setting, showResult, retrying, syncMode, ignoreCleanLock = false, recordCompatibilityDecision, cancellationRequested = () => false) {
795
827
  if (cancellationRequested()) {
796
- return false;
828
+ return COUCHDB_REPLICATION_FAILED;
797
829
  }
798
830
  let ownsSharedAttempt = false;
799
831
  let next;
@@ -801,10 +833,14 @@ ${sendingDocs}/(${sentDocsCount} done)`,
801
833
  next = await shareRunningResult("oneShotReplication", async () => {
802
834
  ownsSharedAttempt = true;
803
835
  if (cancellationRequested()) {
804
- return false;
836
+ return COUCHDB_REPLICATION_FAILED;
837
+ }
838
+ const seed = await this.prepareOneShotSecuritySeed(setting, showResult);
839
+ if (cancellationRequested()) {
840
+ return COUCHDB_REPLICATION_FAILED;
805
841
  }
806
- if (await this.ensurePBKDF2Salt(setting, showResult, false) === false || cancellationRequested()) {
807
- return false;
842
+ if (seed.ready === false) {
843
+ return couchDBReplicationFailureFromError(seed.error);
808
844
  }
809
845
  if (this.controller) {
810
846
  this.log(
@@ -812,7 +848,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
812
848
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
813
849
  "sync"
814
850
  );
815
- return false;
851
+ return COUCHDB_REPLICATION_FAILED;
816
852
  }
817
853
  const localOwner = this.env.services.database.localDatabase;
818
854
  const localDB = localOwner.localDatabase;
@@ -824,7 +860,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
824
860
  ignoreCleanLock,
825
861
  recordCompatibilityDecision
826
862
  );
827
- if (ret === false) {
863
+ if ("status" in ret) {
828
864
  if (!cancellationRequested()) {
829
865
  this.log(
830
866
  this.translate("liveSyncReplicator.couldNotConnectToServer"),
@@ -832,12 +868,12 @@ ${sendingDocs}/(${sentDocsCount} done)`,
832
868
  "sync"
833
869
  );
834
870
  }
835
- return false;
871
+ return ret;
836
872
  }
837
873
  const { db, syncOptionBase } = ret;
838
874
  try {
839
875
  if (cancellationRequested()) {
840
- return false;
876
+ return COUCHDB_REPLICATION_FAILED;
841
877
  }
842
878
  this.maxPullSeq = Number(`${ret.info.update_seq}`.split("-")[0]);
843
879
  this.maxPushSeq = Number(
@@ -846,7 +882,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
846
882
  )[0]
847
883
  );
848
884
  if (cancellationRequested()) {
849
- return false;
885
+ return COUCHDB_REPLICATION_FAILED;
850
886
  }
851
887
  if (showResult) {
852
888
  this.log(this.translate("liveSyncReplicator.checkingLastSyncPoint"), LOG_LEVEL_NOTICE, "sync");
@@ -860,13 +896,13 @@ ${sendingDocs}/(${sentDocsCount} done)`,
860
896
  }
861
897
  this.abortController();
862
898
  if (cancellationRequested()) {
863
- return false;
899
+ return COUCHDB_REPLICATION_FAILED;
864
900
  }
865
901
  const syncHandler = syncMode == "sync" ? localDB.sync(db, { ...syncOptionBase }) : syncMode == "pullOnly" ? localDB.replicate.from(db, {
866
902
  ...syncOptionBase,
867
903
  ...setting.readChunksOnline ? selectorOnDemandPull : {}
868
904
  }) : syncMode == "pushOnly" ? localDB.replicate.to(db, { ...syncOptionBase }) : void 0;
869
- const syncResult = await this.processSync(
905
+ const syncResult = await this.processSyncWithOutcome(
870
906
  syncHandler,
871
907
  showResult,
872
908
  docSentOnStart,
@@ -876,21 +912,24 @@ ${sendingDocs}/(${sentDocsCount} done)`,
876
912
  false
877
913
  );
878
914
  if (cancellationRequested()) {
879
- return false;
915
+ return COUCHDB_REPLICATION_FAILED;
880
916
  }
881
- if (syncResult == "DONE") {
917
+ if (syncResult instanceof UnsupportedEncryptedDocumentFormatError) {
918
+ return syncResult;
919
+ }
920
+ if (syncResult.action === "DONE") {
882
921
  if (syncMode !== "pushOnly") {
883
922
  await this.notifyFiniteReplicationCompleted();
884
923
  }
885
924
  return true;
886
925
  }
887
- if (syncResult instanceof UnsupportedEncryptedDocumentFormatError) {
888
- return syncResult;
926
+ if (syncResult.action === "CANCELLED") {
927
+ return COUCHDB_REPLICATION_FAILED;
889
928
  }
890
- if (syncResult == "CANCELLED" || syncResult == "FAILED") {
891
- return false;
929
+ if (syncResult.action === "FAILED") {
930
+ return couchDBReplicationFailure(syncResult.networkFailure);
892
931
  }
893
- if (syncResult == "NEED_RESURRECT") {
932
+ if (syncResult.action === "NEED_RESURRECT") {
894
933
  this.abortController();
895
934
  return async () => await this.runOneShotReplication(
896
935
  this.originalSetting,
@@ -902,7 +941,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
902
941
  cancellationRequested
903
942
  );
904
943
  }
905
- if (syncResult == "NEED_RETRY") {
944
+ if (syncResult.action === "NEED_RETRY") {
906
945
  const tempSetting = JSON.parse(JSON.stringify(setting));
907
946
  tempSetting.batch_size = Math.ceil(tempSetting.batch_size / 2) + 2;
908
947
  tempSetting.batches_limit = Math.ceil(tempSetting.batches_limit / 2) + 2;
@@ -911,7 +950,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
911
950
  this.translate("liveSyncReplicator.cantReplicateLowerValue"),
912
951
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO
913
952
  );
914
- return false;
953
+ return couchDBReplicationFailure(syncResult.networkFailure);
915
954
  } else {
916
955
  this.log(
917
956
  this.translate("liveSyncReplicator.retryLowerBatchSize", {
@@ -931,7 +970,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
931
970
  );
932
971
  }
933
972
  }
934
- return false;
973
+ return COUCHDB_REPLICATION_FAILED;
935
974
  } finally {
936
975
  await this.closeRemoteConnection(ret);
937
976
  }
@@ -947,12 +986,25 @@ ${sendingDocs}/(${sentDocsCount} done)`,
947
986
  }
948
987
  return typeof next === "function" ? await next() : next;
949
988
  }
989
+ async prepareOneShotSecuritySeed(setting, showResult) {
990
+ if (this.ensurePBKDF2Salt !== LiveSyncAbstractReplicator.prototype.ensurePBKDF2Salt) {
991
+ const ready = await this.ensurePBKDF2Salt(setting, showResult, false);
992
+ return ready ? { ready } : { ready, error: void 0 };
993
+ }
994
+ return await this.prepareSecuritySeed(setting, showResult, false);
995
+ }
950
996
  async checkOneShotReplicationConnectivity(setting, skipCheck, showResult, ignoreCleanLock, recordCompatibilityDecision) {
951
997
  if (setting.useRequestAPI) {
952
998
  if (!recordCompatibilityDecision) {
953
- return await this.checkReplicationConnectivity(setting, false, skipCheck, showResult, ignoreCleanLock);
999
+ return await this.checkReplicationConnectivityWithOutcome(
1000
+ setting,
1001
+ false,
1002
+ skipCheck,
1003
+ showResult,
1004
+ ignoreCleanLock
1005
+ );
954
1006
  }
955
- return await this.checkReplicationConnectivity(
1007
+ return await this.checkReplicationConnectivityWithOutcome(
956
1008
  setting,
957
1009
  false,
958
1010
  skipCheck,
@@ -969,7 +1021,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
969
1021
  timeoutMs
970
1022
  );
971
1023
  try {
972
- return await this.checkReplicationConnectivity(
1024
+ return await this.checkReplicationConnectivityWithOutcome(
973
1025
  setting,
974
1026
  false,
975
1027
  skipCheck,
@@ -1035,19 +1087,38 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1035
1087
  return true;
1036
1088
  }
1037
1089
  async checkReplicationConnectivity(setting, keepAlive, skipCheck, showResult, ignoreCleanLock = false, connectionOptions, recordCompatibilityDecision) {
1090
+ const opened = await this.openReplicationConnection(
1091
+ setting,
1092
+ keepAlive,
1093
+ skipCheck,
1094
+ showResult,
1095
+ ignoreCleanLock,
1096
+ connectionOptions,
1097
+ recordCompatibilityDecision
1098
+ );
1099
+ return "status" in opened ? false : opened;
1100
+ }
1101
+ async checkReplicationConnectivityWithOutcome(...args) {
1102
+ if (this.checkReplicationConnectivity !== LiveSyncCouchDBReplicator.prototype.checkReplicationConnectivity) {
1103
+ const connection = await this.checkReplicationConnectivity(...args);
1104
+ return connection === false ? COUCHDB_REPLICATION_FAILED : connection;
1105
+ }
1106
+ return await this.openReplicationConnection(...args);
1107
+ }
1108
+ async openReplicationConnection(setting, keepAlive, skipCheck, showResult, ignoreCleanLock = false, connectionOptions, recordCompatibilityDecision) {
1038
1109
  recordCompatibilityDecision?.(CENTRAL_COMPATIBILITY_NOT_ASSESSED);
1039
1110
  if (setting.versionUpFlash != "") {
1040
1111
  this.log(this.translate("Replicator.Message.VersionUpFlash"), LOG_LEVEL_NOTICE);
1041
- return false;
1112
+ return COUCHDB_REPLICATION_FAILED;
1042
1113
  }
1043
1114
  const uri = setting.couchDB_URI.replace(/\/+$/, "") + (setting.couchDB_DBNAME == "" ? "" : "/" + setting.couchDB_DBNAME);
1044
1115
  if (this.controller) {
1045
1116
  this.log("Another replication running.");
1046
- return false;
1117
+ return COUCHDB_REPLICATION_FAILED;
1047
1118
  }
1048
1119
  let dbRet;
1049
1120
  try {
1050
- dbRet = await this.connectRemoteCouchDBWithSetting(
1121
+ dbRet = await this.connectRemoteCouchDBWithOutcome(
1051
1122
  setting,
1052
1123
  this.isMobile(),
1053
1124
  true,
@@ -1056,19 +1127,18 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1056
1127
  );
1057
1128
  } catch (ex) {
1058
1129
  if (this.reportConnectivityPreflightTimeout(connectionOptions, showResult, ex)) {
1059
- return false;
1130
+ return couchDBReplicationFailureFromError(ex);
1060
1131
  }
1061
1132
  throw ex;
1062
1133
  }
1063
- if (typeof dbRet === "string") {
1064
- if (this.reportConnectivityPreflightTimeout(connectionOptions, showResult)) {
1065
- return false;
1134
+ if ("error" in dbRet) {
1135
+ if (!this.reportConnectivityPreflightTimeout(connectionOptions, showResult)) {
1136
+ this.log(
1137
+ this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet: dbRet.error.message }),
1138
+ showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO
1139
+ );
1066
1140
  }
1067
- this.log(
1068
- this.translate("liveSyncReplicator.couldNotConnectToURI", { uri, dbRet }),
1069
- showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO
1070
- );
1071
- return false;
1141
+ return couchDBReplicationFailureFromError(dbRet.error);
1072
1142
  }
1073
1143
  let ownershipTransferred = false;
1074
1144
  try {
@@ -1086,7 +1156,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1086
1156
  centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.INCOMPATIBLE_VERSION)
1087
1157
  );
1088
1158
  this.log(error, LOG_LEVEL_NOTICE);
1089
- return false;
1159
+ return couchDBReplicationFailureFromError(error);
1090
1160
  }
1091
1161
  if (!skipCheck) {
1092
1162
  this.remoteCleaned = false;
@@ -1104,7 +1174,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1104
1174
  centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.ID_DERIVATION_MISMATCH)
1105
1175
  );
1106
1176
  this.log("The remote document IDs do not match the configured ID key.", LOG_LEVEL_NOTICE);
1107
- return false;
1177
+ return COUCHDB_REPLICATION_FAILED;
1108
1178
  }
1109
1179
  if (idCompatibility === "unverified" && setting.idDerivationVersion === 1 && setting.usePathObfuscation) {
1110
1180
  this.log("No remote document was available to verify the configured ID key.", LOG_LEVEL_INFO);
@@ -1114,7 +1184,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1114
1184
  centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.INCOMPATIBLE_VERSION)
1115
1185
  );
1116
1186
  this.log(this.translate("liveSyncReplicator.remoteDbCorrupted"), LOG_LEVEL_NOTICE);
1117
- return false;
1187
+ return COUCHDB_REPLICATION_FAILED;
1118
1188
  }
1119
1189
  const progress = `${dbRet.info.update_seq}`;
1120
1190
  const info = {
@@ -1144,7 +1214,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1144
1214
  "The remote database has no compatibility with the running version. Please upgrade the plugin.",
1145
1215
  LOG_LEVEL_NOTICE
1146
1216
  );
1147
- return false;
1217
+ return COUCHDB_REPLICATION_FAILED;
1148
1218
  } else if (ensure == "NODE_LOCKED") {
1149
1219
  recordCompatibilityDecision?.(
1150
1220
  centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.NODE_LOCKED)
@@ -1155,7 +1225,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1155
1225
  );
1156
1226
  this.remoteLockedAndDeviceNotAccepted = true;
1157
1227
  this.remoteLocked = true;
1158
- return false;
1228
+ return COUCHDB_REPLICATION_FAILED;
1159
1229
  } else if (ensure == "LOCKED") {
1160
1230
  this.remoteLocked = true;
1161
1231
  } else if (ensure == "NODE_CLEANED") {
@@ -1172,13 +1242,13 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1172
1242
  this.remoteLockedAndDeviceNotAccepted = true;
1173
1243
  this.remoteLocked = true;
1174
1244
  this.remoteCleaned = true;
1175
- return false;
1245
+ return COUCHDB_REPLICATION_FAILED;
1176
1246
  }
1177
1247
  } else if (ensure == "ID_KEY_MISMATCH") {
1178
1248
  recordCompatibilityDecision?.(
1179
1249
  centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.ID_DERIVATION_MISMATCH)
1180
1250
  );
1181
- return false;
1251
+ return COUCHDB_REPLICATION_FAILED;
1182
1252
  } else if (ensure == "OK") {
1183
1253
  } else if (ensure[0] == "MISMATCHED") {
1184
1254
  recordCompatibilityDecision?.(
@@ -1191,14 +1261,14 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1191
1261
  this.log(this.translate("liveSyncReplicator.mismatchedTweakDetected"), LOG_LEVEL_NOTICE);
1192
1262
  this.tweakSettingsMismatched = true;
1193
1263
  this.preferredTweakValue = ensure[1];
1194
- return false;
1264
+ return COUCHDB_REPLICATION_FAILED;
1195
1265
  }
1196
1266
  const requiredFeatures = requiredRemoteFeatures(setting);
1197
1267
  if (requiredFeatures.length > 0 && !await declareRemoteFeatures(dbRet.db, requiredFeatures)) {
1198
1268
  recordCompatibilityDecision?.(
1199
1269
  centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.INCOMPATIBLE_VERSION)
1200
1270
  );
1201
- return false;
1271
+ return COUCHDB_REPLICATION_FAILED;
1202
1272
  }
1203
1273
  recordCompatibilityDecision?.(CENTRAL_COMPATIBILITY_ACCEPTED);
1204
1274
  }
@@ -1211,7 +1281,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1211
1281
  syncOptionBase.pull = { ...selectorOnDemandPull };
1212
1282
  }
1213
1283
  if (this.reportConnectivityPreflightTimeout(connectionOptions, showResult)) {
1214
- return false;
1284
+ return COUCHDB_REPLICATION_FAILED;
1215
1285
  }
1216
1286
  const syncOption = keepAlive ? { live: true, retry: true, heartbeat: setting.useTimeouts ? false : 3e4, ...syncOptionBase } : { ...syncOptionBase };
1217
1287
  const connection = {
@@ -1223,7 +1293,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1223
1293
  return connection;
1224
1294
  } catch (ex) {
1225
1295
  if (this.reportConnectivityPreflightTimeout(connectionOptions, showResult, ex)) {
1226
- return false;
1296
+ return couchDBReplicationFailureFromError(ex);
1227
1297
  }
1228
1298
  throw ex;
1229
1299
  } finally {
@@ -1232,25 +1302,45 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1232
1302
  }
1233
1303
  }
1234
1304
  }
1235
- openContinuousReplication(setting, showResult, retrying) {
1236
- if (this.continuousTask) {
1305
+ openContinuousReplication(setting, showResult, retrying, onStartSettled) {
1306
+ if (this.continuousTask && this.continuousStart) {
1307
+ const start2 = this.continuousStopRequested ? Promise.resolve({ status: "cancelled" }) : this.continuousStart.promise;
1308
+ this.observeContinuousStart(start2, onStartSettled);
1237
1309
  return this.continuousTask;
1238
1310
  }
1239
1311
  this.continuousStopRequested = false;
1240
1312
  this.continuousStopWaiter = void 0;
1241
- let resolveTask;
1242
- let rejectTask;
1243
- const task = new Promise((resolve, reject) => {
1244
- resolveTask = resolve;
1245
- rejectTask = reject;
1246
- });
1247
- this.continuousTask = task;
1248
- void task.then(
1249
- () => this.clearContinuousTask(task),
1250
- () => this.clearContinuousTask(task)
1313
+ const start = promiseWithResolvers();
1314
+ const task = promiseWithResolvers();
1315
+ this.continuousTask = task.promise;
1316
+ this.continuousStart = start;
1317
+ this.observeContinuousStart(start.promise, onStartSettled);
1318
+ void task.promise.then(
1319
+ () => this.clearContinuousTask(task.promise),
1320
+ () => this.clearContinuousTask(task.promise)
1251
1321
  );
1252
- void this.runContinuousReplication(setting, showResult, retrying).then(resolveTask, rejectTask);
1253
- return task;
1322
+ const reportIncompleteStart = (failure) => {
1323
+ start.resolve(this.continuousStopRequested ? { status: "cancelled" } : failure);
1324
+ };
1325
+ void this.runContinuousReplication(setting, showResult, retrying, start.resolve).then(
1326
+ (result) => {
1327
+ task.resolve(result === true);
1328
+ if (result !== true) {
1329
+ reportIncompleteStart(result);
1330
+ }
1331
+ },
1332
+ (error) => {
1333
+ task.reject(error);
1334
+ reportIncompleteStart(couchDBReplicationFailureFromError(error));
1335
+ }
1336
+ );
1337
+ return task.promise;
1338
+ }
1339
+ observeContinuousStart(start, onStartSettled) {
1340
+ if (!onStartSettled) return;
1341
+ void start.then(onStartSettled).catch((error) => {
1342
+ this.log(error, LOG_LEVEL_VERBOSE, "sync");
1343
+ });
1254
1344
  }
1255
1345
  clearContinuousTask(task) {
1256
1346
  if (this.continuousTask !== task) {
@@ -1259,57 +1349,65 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1259
1349
  this.finishReplicationProgress();
1260
1350
  this.continuousPhase = void 0;
1261
1351
  this.continuousTask = void 0;
1352
+ this.continuousStart = void 0;
1262
1353
  this.continuousStopWaiter = void 0;
1263
1354
  this.continuousStopRequested = false;
1264
1355
  }
1265
- async runContinuousReplication(setting, showResult, retrying) {
1266
- const next = await shareRunningResult("continuousReplication", async () => {
1356
+ async runContinuousCatchUp(setting, showResult) {
1357
+ const args = [
1358
+ setting,
1359
+ showResult,
1360
+ false,
1361
+ "pullOnly",
1362
+ false,
1363
+ void 0,
1364
+ () => this.continuousStopRequested
1365
+ ];
1366
+ if (this.openOneShotReplication !== LiveSyncCouchDBReplicator.prototype.openOneShotReplication) {
1367
+ const caughtUp = await this.openOneShotReplication(...args);
1368
+ return caughtUp ? true : COUCHDB_REPLICATION_FAILED;
1369
+ }
1370
+ return await this.runOneShotReplication(...args);
1371
+ }
1372
+ async runContinuousReplication(setting, showResult, retrying, settleStart) {
1373
+ let ownsSharedAttempt = false;
1374
+ const shared = shareRunningResult("continuousReplication", async () => {
1375
+ ownsSharedAttempt = true;
1267
1376
  if (this.continuousStopRequested || this.controller) {
1268
1377
  this.log(
1269
1378
  this.translate("liveSyncReplicator.replicationInProgress"),
1270
1379
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO
1271
1380
  );
1272
- return false;
1381
+ return COUCHDB_REPLICATION_FAILED;
1273
1382
  }
1274
1383
  this.publishPreparationPhase("catch-up");
1275
1384
  const localOwner = this.env.services.database.localDatabase;
1276
1385
  const localDB = localOwner.localDatabase;
1277
1386
  this.log(this.translate("liveSyncReplicator.beforeLiveSync"));
1278
1387
  const caughtUp = await this.env.services.replicator.runFiniteReplicationActivity(
1279
- () => this.openOneShotReplication(
1280
- setting,
1281
- showResult,
1282
- false,
1283
- "pullOnly",
1284
- false,
1285
- void 0,
1286
- () => this.continuousStopRequested
1287
- ),
1388
+ () => this.runContinuousCatchUp(setting, showResult),
1288
1389
  { label: "replication" }
1289
1390
  );
1290
- if (caughtUp && !this.continuousStopRequested) {
1391
+ if (caughtUp === true && !this.continuousStopRequested) {
1291
1392
  this.publishPreparationPhase("continuous");
1292
1393
  this.log(this.translate("liveSyncReplicator.liveSyncBegin"));
1293
- const ret = await this.checkReplicationConnectivity(setting, true, false, showResult);
1294
- if (ret === false || this.continuousStopRequested) {
1295
- if (ret !== false) {
1296
- await this.closeRemoteConnection(ret);
1297
- }
1298
- if (ret === false && !this.continuousStopRequested) {
1394
+ const ret = await this.checkReplicationConnectivityWithOutcome(setting, true, false, showResult);
1395
+ if ("status" in ret) {
1396
+ if (!this.continuousStopRequested) {
1299
1397
  this.log(
1300
1398
  this.translate("liveSyncReplicator.couldNotConnectToServer"),
1301
1399
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO
1302
1400
  );
1303
1401
  }
1304
- return false;
1305
- }
1306
- if (showResult) {
1307
- this.log(this.translate("liveSyncReplicator.checkingLastSyncPoint"), LOG_LEVEL_NOTICE, "sync");
1402
+ return ret;
1308
1403
  }
1309
1404
  const { db, syncOption } = ret;
1310
1405
  try {
1311
1406
  if (this.continuousStopRequested) {
1312
- return false;
1407
+ return COUCHDB_REPLICATION_FAILED;
1408
+ }
1409
+ if (showResult) {
1410
+ this.log(this.translate("liveSyncReplicator.checkingLastSyncPoint"), LOG_LEVEL_NOTICE, "sync");
1313
1411
  }
1314
1412
  this.syncStatus = "STARTED";
1315
1413
  this.maxPullSeq = Number(`${ret.info.update_seq}`.split("-")[0]);
@@ -1319,7 +1417,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1319
1417
  )[0]
1320
1418
  );
1321
1419
  if (this.continuousStopRequested) {
1322
- return false;
1420
+ return COUCHDB_REPLICATION_FAILED;
1323
1421
  }
1324
1422
  this.updateInfo();
1325
1423
  const docArrivedOnStart = this.docArrived;
@@ -1329,11 +1427,12 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1329
1427
  }
1330
1428
  this.abortController();
1331
1429
  if (this.continuousStopRequested) {
1332
- return false;
1430
+ return COUCHDB_REPLICATION_FAILED;
1333
1431
  }
1334
1432
  const syncHandler = localDB.sync(db, {
1335
1433
  ...syncOption
1336
1434
  });
1435
+ settleStart?.({ status: "started" });
1337
1436
  const syncMode = "sync";
1338
1437
  const syncResult = await this.processSync(
1339
1438
  syncHandler,
@@ -1344,19 +1443,19 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1344
1443
  retrying
1345
1444
  );
1346
1445
  if (this.continuousStopRequested) {
1347
- return false;
1446
+ return COUCHDB_REPLICATION_FAILED;
1348
1447
  }
1349
1448
  if (syncResult == "DONE") {
1350
1449
  return true;
1351
1450
  }
1352
1451
  if (syncResult == "FAILED") {
1353
- return false;
1452
+ return COUCHDB_REPLICATION_FAILED;
1354
1453
  }
1355
1454
  if (syncResult == "NEED_RESURRECT") {
1356
1455
  this.abortController();
1357
1456
  return async () => {
1358
1457
  if (this.continuousStopRequested) {
1359
- return false;
1458
+ return COUCHDB_REPLICATION_FAILED;
1360
1459
  }
1361
1460
  return await this.runContinuousReplication(this.originalSetting, showResult, false);
1362
1461
  };
@@ -1370,7 +1469,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1370
1469
  this.translate("liveSyncReplicator.cantReplicateLowerValue"),
1371
1470
  showResult ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO
1372
1471
  );
1373
- return false;
1472
+ return COUCHDB_REPLICATION_FAILED;
1374
1473
  } else {
1375
1474
  this.log(
1376
1475
  this.translate("liveSyncReplicator.retryLowerBatchSize", {
@@ -1381,7 +1480,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1381
1480
  );
1382
1481
  return async () => {
1383
1482
  if (this.continuousStopRequested) {
1384
- return false;
1483
+ return COUCHDB_REPLICATION_FAILED;
1385
1484
  }
1386
1485
  return await this.runContinuousReplication(tempSetting, showResult, true);
1387
1486
  };
@@ -1391,12 +1490,13 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1391
1490
  await this.closeRemoteConnection(ret);
1392
1491
  }
1393
1492
  }
1394
- return false;
1493
+ return caughtUp === true || caughtUp === ONE_SHOT_REPLICATION_ALREADY_RUNNING || caughtUp instanceof UnsupportedEncryptedDocumentFormatError ? COUCHDB_REPLICATION_FAILED : caughtUp;
1395
1494
  });
1396
- if (typeof next === "boolean") {
1397
- return next;
1495
+ if (!ownsSharedAttempt) {
1496
+ return COUCHDB_REPLICATION_FAILED;
1398
1497
  }
1399
- return await next();
1498
+ const next = await shared;
1499
+ return typeof next === "function" ? await next() : next;
1400
1500
  }
1401
1501
  closeReplication() {
1402
1502
  const hadController = !!this.controller;
@@ -1521,8 +1621,25 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1521
1621
  });
1522
1622
  }
1523
1623
  async connectRemoteCouchDBWithSetting(settings, isMobile, performSetup = false, skipInfo = false, connectionOptions) {
1524
- if (settings.encrypt && settings.passphrase == "" && !settings.permitEmptyPassphrase) {
1525
- return "Empty passphrases cannot be used without explicit permission";
1624
+ const opened = await this.openRemoteCouchDBWithSetting(
1625
+ settings,
1626
+ isMobile,
1627
+ performSetup,
1628
+ skipInfo,
1629
+ connectionOptions
1630
+ );
1631
+ return "error" in opened ? opened.error.message : opened;
1632
+ }
1633
+ async connectRemoteCouchDBWithOutcome(...args) {
1634
+ if (this.connectRemoteCouchDBWithSetting !== LiveSyncCouchDBReplicator.prototype.connectRemoteCouchDBWithSetting) {
1635
+ const opened = await this.connectRemoteCouchDBWithSetting(...args);
1636
+ return typeof opened === "string" ? { error: new Error(opened) } : opened;
1637
+ }
1638
+ return await this.openRemoteCouchDBWithSetting(...args);
1639
+ }
1640
+ async openRemoteCouchDBWithSetting(settings, isMobile, performSetup = false, skipInfo = false, connectionOptions) {
1641
+ if (settings.encrypt && settings.passphrase === "" && !settings.permitEmptyPassphrase) {
1642
+ return { error: new Error("Empty passphrases cannot be used without explicit permission") };
1526
1643
  }
1527
1644
  const customHeaders = parseHeaderValues(settings.couchDB_CustomHeaders);
1528
1645
  const auth = settings.useJWT ? {
@@ -1537,7 +1654,7 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1537
1654
  password: settings.couchDB_PASSWORD,
1538
1655
  type: "basic"
1539
1656
  };
1540
- return this.env.services.remote.connect(
1657
+ const args = [
1541
1658
  settings.couchDB_URI.replace(/\/+$/, "") + (settings.couchDB_DBNAME == "" ? "" : "/" + settings.couchDB_DBNAME),
1542
1659
  auth,
1543
1660
  settings.disableRequestURI || isMobile,
@@ -1556,12 +1673,20 @@ ${sendingDocs}/(${sentDocsCount} done)`,
1556
1673
  acceptUnencryptedContent: settings.acceptUnencryptedContent === true,
1557
1674
  useCouchDBCacheControlHeadersOnly: settings.useCouchDBCacheControlHeadersOnly === true
1558
1675
  }
1559
- );
1676
+ ];
1677
+ const remote = this.env.services.remote;
1678
+ if (remote.openCouchDBConnection) {
1679
+ return await remote.openCouchDBConnection(...args);
1680
+ }
1681
+ const opened = await remote.connect(...args);
1682
+ return typeof opened === "string" ? { error: new Error(opened) } : opened;
1560
1683
  }
1561
1684
  async openOwnedConnection(settings, performSetup = false) {
1562
- const ret = await this.connectRemoteCouchDBWithSetting(settings, this.isMobile(), performSetup, true);
1563
- if (typeof ret === "string") {
1564
- throw new Error(`${this.translate("liveSyncReplicator.couldNotConnectToServer")}:${ret}`);
1685
+ const ret = await this.connectRemoteCouchDBWithOutcome(settings, this.isMobile(), performSetup, true);
1686
+ if ("error" in ret) {
1687
+ throw new Error(`${this.translate("liveSyncReplicator.couldNotConnectToServer")}:${ret.error.message}`, {
1688
+ cause: ret.error
1689
+ });
1565
1690
  }
1566
1691
  return ret;
1567
1692
  }