@vrtmrz/livesync-commonlib 0.6.1 → 0.7.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 (78) 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/managers/EntryManager/EntryManager.d.ts +1 -1
  7. package/dist/managers/EntryManager/EntryManager.js +2 -2
  8. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +1 -1
  9. package/dist/managers/EntryManager/EntryManagerImpls.js +4 -4
  10. package/dist/managers/StorageEventManager/admission.d.ts +1 -0
  11. package/dist/managers/StorageEventManager/admission.js +5 -1
  12. package/dist/managers/StorageEventManager.d.ts +2 -0
  13. package/dist/managers/StorageEventManager.js +1 -0
  14. package/dist/pouchdb/LiveSyncLocalDB.d.ts +1 -1
  15. package/dist/pouchdb/LiveSyncLocalDB.js +2 -2
  16. package/dist/replication/LiveSyncAbstractReplicator.d.ts +7 -0
  17. package/dist/replication/LiveSyncAbstractReplicator.js +5 -2
  18. package/dist/replication/ReplicatorInstance.d.ts +3 -0
  19. package/dist/replication/ReplicatorProvider.d.ts +23 -2
  20. package/dist/replication/ReplicatorProvider.js +10 -0
  21. package/dist/replication/SyncParamsHandler.js +26 -25
  22. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +14 -2
  23. package/dist/replication/couchdb/LiveSyncReplicator.js +247 -122
  24. package/dist/replication/index.d.ts +4 -2
  25. package/dist/replication/index.js +6 -0
  26. package/dist/replication/remoteTransportFailure.d.ts +24 -0
  27. package/dist/replication/remoteTransportFailure.js +80 -0
  28. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +1 -1
  29. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +2 -2
  30. package/dist/replication/trystero/TrysteroRpcRoom.d.ts +14 -0
  31. package/dist/replication/trystero/TrysteroRpcRoom.js +168 -0
  32. package/dist/replication/trystero/rpcCompat.d.ts +1 -0
  33. package/dist/replication/trystero/rpcCompat.js +15 -0
  34. package/dist/rpc/RpcRoom.d.ts +1 -0
  35. package/dist/rpc/RpcRoom.js +21 -9
  36. package/dist/rpc/RpcSession.d.ts +8 -13
  37. package/dist/rpc/RpcSession.js +14 -35
  38. package/dist/rpc/commonlibRpcRoom.d.ts +1 -0
  39. package/dist/rpc/commonlibRpcRoom.js +4 -0
  40. package/dist/rpc/errors.d.ts +9 -3
  41. package/dist/rpc/errors.js +13 -16
  42. package/dist/rpc/index.d.ts +10 -1
  43. package/dist/rpc/index.js +2 -1
  44. package/dist/rpc/pouchdb/RpcPouchDBProxy.d.ts +1 -1
  45. package/dist/rpc/pouchdb/RpcPouchDBServer.d.ts +1 -1
  46. package/dist/serviceFeatures/targetFilter.d.ts +3 -1
  47. package/dist/serviceFeatures/targetFilter.js +2 -2
  48. package/dist/services/base/IService.d.ts +9 -6
  49. package/dist/services/base/ReadinessEvaluator.d.ts +7 -6
  50. package/dist/services/base/ReadinessEvaluator.js +4 -2
  51. package/dist/services/base/RemoteConnection.d.ts +4 -0
  52. package/dist/services/base/RemoteService.d.ts +5 -3
  53. package/dist/services/base/RemoteService.js +85 -33
  54. package/dist/services/base/ReplicationService.d.ts +10 -2
  55. package/dist/services/base/ReplicationService.js +13 -7
  56. package/dist/services/base/ReplicationService.readiness.d.ts +14 -4
  57. package/dist/services/base/ReplicationService.readiness.js +29 -2
  58. package/dist/services/base/ReplicationService.typedReplication.d.ts +5 -2
  59. package/dist/services/base/ReplicationService.typedReplication.js +67 -6
  60. package/dist/services/base/ReplicationStaticsOwner.d.ts +18 -0
  61. package/dist/services/base/ReplicationStaticsOwner.js +33 -0
  62. package/dist/services/base/ReplicatorService.d.ts +2 -10
  63. package/dist/services/base/ReplicatorService.js +6 -3
  64. package/dist/services/base/VaultService.d.ts +1 -0
  65. package/dist/string_and_binary/chunks.d.ts +1 -1
  66. package/dist/string_and_binary/chunks.js +63 -50
  67. package/dist/worker/bg.worker.js +3 -1
  68. package/dist/worker/bg.worker.splitting.d.ts +1 -0
  69. package/dist/worker/bg.worker.splitting.js +42 -6
  70. package/dist/worker/bgWorker.d.ts +4 -0
  71. package/dist/worker/bgWorker.js +87 -57
  72. package/dist/worker/bgWorker.splitting.d.ts +2 -3
  73. package/dist/worker/bgWorker.splitting.js +48 -52
  74. package/dist/worker/universalTypes.d.ts +13 -1
  75. package/docs/development.md +69 -32
  76. package/docs/p2p-transport-lifecycle.md +2 -3
  77. package/docs/storage-events-and-reflection.md +10 -3
  78. package/package.json +3 -2
@@ -38,7 +38,7 @@ export declare class RpcPouchDBProxy extends EventEmitter {
38
38
  };
39
39
  private readonly session;
40
40
  private readonly ns;
41
- constructor(session: RpcSession, name: string, ns?: string);
41
+ constructor(session: Pick<RpcSession, "call">, name: string, ns?: string);
42
42
  /**
43
43
  * Invoke an RPC method and reconstruct PouchDB error shapes on the response.
44
44
  *
@@ -13,4 +13,4 @@ import type { RpcRoom } from "../RpcRoom.js";
13
13
  * @param db The PouchDB database instance to expose.
14
14
  * @param ns Method namespace prefix (default: `'pdb'`).
15
15
  */
16
- export declare function exposeDB(room: RpcRoom, db: PouchDB.Database<object>, ns?: string): void;
16
+ export declare function exposeDB(room: Pick<RpcRoom, "register">, db: PouchDB.Database<object>, ns?: string): void;
@@ -15,7 +15,9 @@ export declare function isAcceptedInFilenameDuplicationFactory(host: NecessarySe
15
15
  * Local database responsible for non-internal files, syncOnlyRegEx, syncIgnoreRegEx
16
16
  * This possibly should be separated.
17
17
  */
18
- export declare function isAcceptedByLocalDBFactory(host: NecessaryServices<"database" | "databaseEvents", never>, log: LogFunction): (file: string | UXFileInfoStub) => Promise<boolean>;
18
+ export declare function isAcceptedByLocalDBFactory(host: NecessaryServices<"database" | "databaseEvents", never>, log: LogFunction): (file: string | UXFileInfoStub, options?: {
19
+ internalFileEvent?: boolean;
20
+ }) => Promise<boolean>;
19
21
  /**
20
22
  * Factory function to create the isAcceptedByIgnoreFiles handler.
21
23
  * This handler checks if a file is ignored based on the ignore files specified in the settings.
@@ -39,10 +39,10 @@ function isAcceptedByLocalDBFactory(host, log) {
39
39
  isReady = promiseWithResolvers();
40
40
  return Promise.resolve(true);
41
41
  });
42
- return async (file) => {
42
+ return async (file, options) => {
43
43
  await isReady.promise;
44
44
  const filepath = getStoragePathFromUXFileInfo(file);
45
- if (!await Promise.resolve(database.localDatabase.isTargetFile(filepath))) {
45
+ if (!await Promise.resolve(database.localDatabase.isTargetFile(filepath, options?.internalFileEvent))) {
46
46
  log("File is not target by local DB: " + filepath);
47
47
  return false;
48
48
  }
@@ -7,12 +7,12 @@ import type { ReplicatorInstance } from "../../replication/ReplicatorInstance.js
7
7
  import type { SimpleStore } from "octagonal-wheels/databases/SimpleStoreBase";
8
8
  import type { Confirm } from "../../interfaces/Confirm.js";
9
9
  import type { ReactiveSource } from "octagonal-wheels/dataobject/reactive";
10
- import type { ReplicationStatics } from "../../common/models/shared.definition.js";
10
+ import type { ReplicationStaticsSource } from "./ReplicationStaticsOwner.js";
11
11
  import type { ReplicatorService } from "./ReplicatorService.js";
12
12
  import type { DatabaseEventService } from "./DatabaseEventService.js";
13
13
  import type { BASE_IS_NEW, EVEN, TARGET_IS_NEW } from "../../common/models/shared.const.symbols.js";
14
14
  import type { AsyncActivityOptions } from "../../interfaces/AsyncActivityRunner.js";
15
- import type { OwnedCouchDBConnection, RemoteConnectionOpenOptions } from "./RemoteConnection.js";
15
+ import type { CouchDBConnectionOpenResult, OwnedCouchDBConnection, RemoteConnectionOpenOptions } from "./RemoteConnection.js";
16
16
  import type { ActiveReplicatorContext, ContinuousReplicationRequest, ReplicationAttemptFailure, ReplicationFailureRequest, ReplicatorProviderDefinitionMap, ReplicationOutcome, ReplicationReadinessRequirements, UnattendedOneShotRequest, UserInitiatedOneShotRequest } from "../../replication/ReplicatorProvider.js";
17
17
  import type { RemoteResourceKind, RemoteResourceMap } from "../../replication/RemoteResource.js";
18
18
  import type { CentralRemoteAdministrationRequest, CentralRemoteAdministrationResult } from "../../replication/CentralRemoteAdministration.js";
@@ -188,7 +188,7 @@ export interface IReplicatorService {
188
188
  * `ActiveReplicatorContext` before using a Replicator.
189
189
  */
190
190
  hasActiveReplicator(): boolean;
191
- replicationStatics: ReactiveSource<ReplicationStatics>;
191
+ readonly replicationStatics: ReplicationStaticsSource;
192
192
  /** Number of finite remote operations currently in progress. */
193
193
  boundedRemoteActivityCount: ReactiveSource<number>;
194
194
  /** Number of finite replication operations which can still deliver database documents. */
@@ -283,6 +283,8 @@ export interface IRemoteService {
283
283
  * before a connection result can be produced.
284
284
  */
285
285
  connect(uri: string, auth: CouchDBCredentials, disableRequestURI: boolean, passphrase: string | false, useDynamicIterationCount: boolean, performSetup: boolean, skipInfo: boolean, compression: boolean, customHeaders: Record<string, string>, useRequestAPI: boolean, getPBKDF2Salt: () => Promise<Uint8Array<ArrayBuffer>>, options?: RemoteConnectionOpenOptions): Promise<string | OwnedCouchDBConnection<EntryDoc>>;
286
+ /** Open a remote connection with its original failure available to the caller. */
287
+ openCouchDBConnection?(...args: Parameters<IRemoteService["connect"]>): Promise<CouchDBConnectionOpenResult<EntryDoc>>;
286
288
  /**
287
289
  * State if the last POST request failed due to payload size.
288
290
  */
@@ -376,10 +378,11 @@ export interface IVaultService {
376
378
  getVaultName(): string;
377
379
  scanVault(showingNotice?: boolean, ignoreSuspending?: boolean, continueOnFileFailure?: boolean, scanOptions?: VaultScanOptions): Promise<VaultScanResult>;
378
380
  isIgnoredByIgnoreFile(file: string | UXFileInfoStub): Promise<boolean>;
379
- isTargetFile(file: string | UXFileInfoStub,
380
- /** Inspect selection policy without treating a filename collision as an exclusion. */
381
- options?: {
381
+ isTargetFile(file: string | UXFileInfoStub, options?: {
382
+ /** Inspect selection policy without treating a filename collision as an exclusion. */
382
383
  skipCaseCollisionCheck?: boolean;
384
+ /** Host-admitted internal file event. Preserve vetoes while omitting ordinary-file eligibility. */
385
+ internalFileEvent?: boolean;
383
386
  }): Promise<boolean>;
384
387
  isTargetFileInExtra(file: string | UXFileInfoStub): Promise<boolean>;
385
388
  isFileSizeTooLarge(size: number): boolean;
@@ -1,5 +1,5 @@
1
1
  /** One ordered condition in a readiness evaluation. */
2
- export interface ReadinessCondition<TContext> {
2
+ export interface ReadinessCondition<TContext, TRejection extends object = never> {
3
3
  /** Stable diagnostic name for the condition; it is not user-facing text. */
4
4
  readonly name: string;
5
5
  /**
@@ -10,25 +10,26 @@ export interface ReadinessCondition<TContext> {
10
10
  */
11
11
  readonly appliesTo?: (context: TContext) => boolean;
12
12
  /** Return whether the condition admits the requested operation. */
13
- readonly evaluate: (context: TContext) => boolean | Promise<boolean>;
13
+ readonly evaluate: (context: TContext) => boolean | TRejection | Promise<boolean | TRejection>;
14
14
  /** Perform condition-specific reporting after a false result. */
15
15
  readonly onRejected?: (context: TContext) => void | Promise<void>;
16
16
  }
17
17
  /** A purpose and its ordered readiness conditions. */
18
- export interface ReadinessEvaluationRequest<TContext> {
18
+ export interface ReadinessEvaluationRequest<TContext, TRejection extends object = never> {
19
19
  /** Stable diagnostic purpose; it is not user-facing text. */
20
20
  readonly purpose: string;
21
21
  readonly context: TContext;
22
- readonly conditions: readonly ReadinessCondition<TContext>[];
22
+ readonly conditions: readonly ReadinessCondition<TContext, TRejection>[];
23
23
  }
24
24
  /** Structured result from an ordered readiness evaluation. */
25
- export type ReadinessEvaluationResult = {
25
+ export type ReadinessEvaluationResult<TRejection extends object = never> = {
26
26
  readonly ready: true;
27
27
  readonly purpose: string;
28
28
  } | {
29
29
  readonly ready: false;
30
30
  readonly purpose: string;
31
31
  readonly rejectedCondition: string;
32
+ readonly rejection?: TRejection;
32
33
  };
33
34
  /**
34
35
  * Evaluate applicable conditions in declaration order until one rejects.
@@ -37,4 +38,4 @@ export type ReadinessEvaluationResult = {
37
38
  * from applicability, evaluation, or reporting callbacks propagate unchanged;
38
39
  * the evaluator does not reinterpret operational failures as policy results.
39
40
  */
40
- export declare function evaluateReadiness<TContext>(request: ReadinessEvaluationRequest<TContext>): Promise<ReadinessEvaluationResult>;
41
+ export declare function evaluateReadiness<TContext, TRejection extends object = never>(request: ReadinessEvaluationRequest<TContext, TRejection>): Promise<ReadinessEvaluationResult<TRejection>>;
@@ -1,12 +1,14 @@
1
1
  async function evaluateReadiness(request) {
2
2
  for (const condition of request.conditions) {
3
3
  if (condition.appliesTo && !condition.appliesTo(request.context)) continue;
4
- if (await condition.evaluate(request.context)) continue;
4
+ const decision = await condition.evaluate(request.context);
5
+ if (decision === true) continue;
5
6
  await condition.onRejected?.(request.context);
6
7
  return {
7
8
  ready: false,
8
9
  purpose: request.purpose,
9
- rejectedCondition: condition.name
10
+ rejectedCondition: condition.name,
11
+ ...decision !== false && { rejection: decision }
10
12
  };
11
13
  }
12
14
  return { ready: true, purpose: request.purpose };
@@ -51,3 +51,7 @@ export interface OwnedCouchDBConnection<T extends object> {
51
51
  /** Cancels scoped requests and closes the PouchDB handle exactly once. */
52
52
  close(): Promise<void>;
53
53
  }
54
+ /** The connection attempt preserves its refusal or opening error until the caller handles it. */
55
+ export type CouchDBConnectionOpenResult<T extends object> = OwnedCouchDBConnection<T> | {
56
+ readonly error: Error;
57
+ };
@@ -1,4 +1,4 @@
1
- import { type CouchDBCredentials, type EntryDoc } from "../../common/types.js";
1
+ import { type EntryDoc } from "../../common/types.js";
2
2
  import type { IRemoteService } from "./IService.js";
3
3
  import { ServiceBase, type ServiceContext } from "./ServiceBase.js";
4
4
  import { type LOG_LEVEL } from "../../common/types.js";
@@ -9,7 +9,7 @@ import type { SettingService } from "./SettingService.js";
9
9
  import { UnresolvedErrorManager } from "./UnresolvedErrorManager.js";
10
10
  import { type LogFunction } from "../lib/logUtils.js";
11
11
  import type { PouchDBConstructor } from "../../pouchdb/PouchDBConstructor.js";
12
- import type { OwnedCouchDBConnection, RemoteConnectionOpenOptions } from "./RemoteConnection.js";
12
+ import type { CouchDBConnectionOpenResult, OwnedCouchDBConnection } from "./RemoteConnection.js";
13
13
  export interface RemoteServiceDependencies {
14
14
  /** PouchDB with the HTTP adapter required by the host runtime already registered. */
15
15
  pouchDB: PouchDBConstructor;
@@ -60,6 +60,8 @@ export declare abstract class RemoteService<T extends ServiceContext = ServiceCo
60
60
  * @returns An error description, or the owned connection. The caller must
61
61
  * transfer ownership or call `close()`.
62
62
  */
63
- connect(uri: string, auth: CouchDBCredentials, disableRequestURI: boolean, passphrase: string | false, useDynamicIterationCount: boolean, performSetup: boolean, skipInfo: boolean, compression: boolean, customHeaders: Record<string, string>, useRequestAPI: boolean, getPBKDF2Salt: () => Promise<Uint8Array<ArrayBuffer>>, connectionOptions?: RemoteConnectionOpenOptions): Promise<string | OwnedCouchDBConnection<EntryDoc>>;
63
+ connect(...args: Parameters<IRemoteService["connect"]>): Promise<string | OwnedCouchDBConnection<EntryDoc>>;
64
+ openCouchDBConnection(...args: Parameters<IRemoteService["connect"]>): Promise<CouchDBConnectionOpenResult<EntryDoc>>;
65
+ private openConnection;
64
66
  }
65
67
  export {};
@@ -10,6 +10,8 @@ import { replicationFilter } from "../../pouchdb/compress.js";
10
10
  import { disableEncryption, enableEncryption } from "../../pouchdb/encryption.js";
11
11
  import { isCloudantURI, isValidRemoteCouchDBURI } from "../../pouchdb/utils_couchdb.js";
12
12
  import { AuthorizationHeaderGenerator } from "../../replication/httplib.js";
13
+ import { observedOfflineReplicationFailure } from "../../replication/ReplicatorProvider.js";
14
+ import { captureRemoteTransportFailure, ReplicationNetworkError } from "../../replication/remoteTransportFailure.js";
13
15
  import { UnresolvedErrorManager } from "./UnresolvedErrorManager.js";
14
16
  import { createInstanceLogFunction, MARK_LOG_NETWORK_ERROR } from "../lib/logUtils.js";
15
17
  import { runWithTrackedPhysicalRequest } from "../lib/remoteActivity.js";
@@ -88,6 +90,41 @@ function createCouchDBConnection(db, info, scope) {
88
90
  }
89
91
  };
90
92
  }
93
+ const responseBodyReaders = /* @__PURE__ */ new Set([
94
+ "arrayBuffer",
95
+ "blob",
96
+ "buffer",
97
+ "bytes",
98
+ "formData",
99
+ "json",
100
+ "text"
101
+ ]);
102
+ function observeResponseBody(response, captureFailure) {
103
+ if (!response.ok) {
104
+ return response;
105
+ }
106
+ return new Proxy(response, {
107
+ get(target, property) {
108
+ if (property === "clone") {
109
+ return () => observeResponseBody(target.clone(), captureFailure);
110
+ }
111
+ const member = Reflect.get(target, property);
112
+ if (typeof member !== "function" || property === "constructor") {
113
+ return member;
114
+ }
115
+ if (!responseBodyReaders.has(property)) {
116
+ return member.bind(target);
117
+ }
118
+ return async () => {
119
+ try {
120
+ return await Reflect.apply(member, target, []);
121
+ } catch (error) {
122
+ throw captureFailure(error);
123
+ }
124
+ };
125
+ }
126
+ });
127
+ }
91
128
  const FetchMethod = {
92
129
  webCompat: 0,
93
130
  native: 1
@@ -182,12 +219,27 @@ class RemoteService extends ServiceBase {
182
219
  * @returns An error description, or the owned connection. The caller must
183
220
  * transfer ownership or call `close()`.
184
221
  */
185
- async connect(uri, auth, disableRequestURI, passphrase, useDynamicIterationCount, performSetup, skipInfo, compression, customHeaders, useRequestAPI, getPBKDF2Salt, connectionOptions = {}) {
186
- if (!isValidRemoteCouchDBURI(uri)) return "Remote URI is not valid";
187
- if (uri.toLowerCase() != uri) return "Remote URI and database name could not contain capital letters.";
188
- if (uri.indexOf(" ") !== -1) return "Remote URI and database name could not contain spaces.";
222
+ async connect(...args) {
223
+ const opened = await this.openCouchDBConnection(...args);
224
+ return "error" in opened ? opened.error.message : opened;
225
+ }
226
+ async openCouchDBConnection(...args) {
227
+ return await this.openConnection(...args);
228
+ }
229
+ async openConnection(uri, auth, disableRequestURI, passphrase, useDynamicIterationCount, performSetup, skipInfo, compression, customHeaders, useRequestAPI, getPBKDF2Salt, connectionOptions = {}) {
230
+ if (!isValidRemoteCouchDBURI(uri)) {
231
+ return { error: new Error("Remote URI is not valid") };
232
+ }
233
+ if (uri.toLowerCase() !== uri) {
234
+ return { error: new Error("Remote URI and database name could not contain capital letters.") };
235
+ }
236
+ if (uri.includes(" ")) {
237
+ return { error: new Error("Remote URI and database name could not contain spaces.") };
238
+ }
189
239
  if (!this._APIService.isOnline) {
190
- return "Network is offline";
240
+ return {
241
+ error: new ReplicationNetworkError("Network is offline", observedOfflineReplicationFailure())
242
+ };
191
243
  }
192
244
  const connectionScope = createRemoteConnectionScope(connectionOptions.signal);
193
245
  const encryptionAlgorithm = connectionOptions.encryptionAlgorithm ?? this._settingService.currentSettings().E2EEAlgorithm;
@@ -231,44 +283,45 @@ class RemoteService extends ServiceBase {
231
283
  headers.append("authorization", authHeader);
232
284
  }
233
285
  const cachedRequest = await prepareCachedRequest(requestSrc, opts);
286
+ const signal = connectionScope.combine(opts?.signal);
287
+ const captureFailure = (error) => captureRemoteTransportFailure(error, signal, () => this._APIService.isOnline);
234
288
  try {
235
- const signal = connectionScope.combine(opts?.signal);
236
289
  const response = await this.performFetch(
237
290
  cachedRequest.request,
238
291
  { ...opts, headers, signal, cache: cachedRequest.cache },
239
292
  useRequestAPI ? FetchMethod.native : FetchMethod.webCompat
240
293
  );
241
- return response;
242
- } catch (ex) {
243
- if (ex instanceof TypeError) {
244
- if (connectionScope.signal.aborted || connectionOptions.allowNativeFallback === false) {
245
- throw ex;
246
- }
247
- if (useRequestAPI) {
294
+ return observeResponseBody(response, captureFailure);
295
+ } catch (error) {
296
+ if (!(error instanceof TypeError) || connectionScope.signal.aborted || connectionOptions.allowNativeFallback === false || useRequestAPI) {
297
+ if (useRequestAPI && error instanceof TypeError && !connectionScope.signal.aborted) {
248
298
  this._log("Failed to request by API.");
249
- throw ex;
250
299
  }
251
- this._log(
252
- "Failed to fetch by native fetch API. Trying to fetch by API to get more information."
253
- );
254
- const resp2 = await this.performFetch(
300
+ throw captureFailure(error);
301
+ }
302
+ this._log(
303
+ "Failed to fetch by native fetch API. Trying to fetch by API to get more information."
304
+ );
305
+ let response;
306
+ try {
307
+ response = await this.performFetch(
255
308
  cachedRequest.request,
256
309
  { ...opts, headers, cache: cachedRequest.cache },
257
310
  FetchMethod.native
258
311
  );
259
- if (resp2.status / 100 == 2) {
260
- this.showError(
261
- "The request was successful by API. But the native fetch API failed! Please check CORS settings on the remote database!. While this condition, you cannot enable LiveSync",
262
- LOG_LEVEL_NOTICE
263
- );
264
- return resp2;
265
- }
266
- const r2 = resp2.clone();
267
- const msg = await r2.text();
268
- this.showError(`Failed to fetch by API. ${resp2.status}: ${msg}`, LOG_LEVEL_NOTICE);
269
- return resp2;
312
+ } catch (fallbackError) {
313
+ throw captureFailure(fallbackError);
314
+ }
315
+ if (response.status / 100 == 2) {
316
+ this.showError(
317
+ "The request was successful by API. But the native fetch API failed! Please check CORS settings on the remote database!. While this condition, you cannot enable LiveSync",
318
+ LOG_LEVEL_NOTICE
319
+ );
320
+ } else {
321
+ const msg = await response.clone().text();
322
+ this.showError(`Failed to fetch by API. ${response.status}: ${msg}`, LOG_LEVEL_NOTICE);
270
323
  }
271
- throw ex;
324
+ return observeResponseBody(response, captureFailure);
272
325
  }
273
326
  } catch (ex) {
274
327
  this._log(`HTTP:${method}${size} to:${localURL} -> failed`, LOG_LEVEL_VERBOSE);
@@ -331,11 +384,10 @@ class RemoteService extends ServiceBase {
331
384
  const info = await db.info();
332
385
  return { ...connection, info };
333
386
  } catch (ex) {
334
- const exMsg = ex instanceof Error ? ex : LiveSyncError.fromError(ex);
335
- const msg = `${exMsg.name}:${exMsg.message}`;
387
+ const error = ex instanceof Error ? ex : LiveSyncError.fromError(ex);
336
388
  this._log(ex, LOG_LEVEL_VERBOSE);
337
389
  await closeAfterConnectionFailure();
338
- return msg;
390
+ return { error: new Error(`${error.name}:${error.message}`, { cause: ex }) };
339
391
  }
340
392
  }
341
393
  }
@@ -51,14 +51,22 @@ export declare abstract class ReplicationService<T extends ServiceContext = Serv
51
51
  * Process a virtual document (e.g., for customisation sync).
52
52
  */
53
53
  readonly processVirtualDocument: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(docs: PouchDB.Core.ExistingDocument<import("../../common/types.js").EntryDoc>) => Promise<boolean>>;
54
+ private readonly _beforeReplicate;
54
55
  /**
55
56
  * An event triggered before starting replication.
56
57
  */
57
- readonly onBeforeReplicate: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(showMessage: boolean) => Promise<boolean>>;
58
+ readonly onBeforeReplicate: ((showMessage: boolean) => Promise<boolean>) & {
59
+ addHandler: (callback: (showMessage: boolean) => import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult | Promise<import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult>, priority?: number, allowSwap?: boolean) => import("../lib/HandlerUtils.js").UnregisterFunction;
60
+ removeHandler: (callback: (showMessage: boolean) => import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult | Promise<import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult>) => void;
61
+ };
58
62
  readonly onFiniteReplicationCompleted: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<() => Promise<boolean>>;
59
63
  readonly onFileReflectionFailed: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(target: import("../../interfaces/FileHandler.js").ReflectionTarget, error: unknown) => Promise<boolean>>;
64
+ private readonly _prepareCentralRemote;
60
65
  /** Provider preparation which applies only to the central remote. */
61
- readonly onPrepareCentralRemoteReplication: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(showMessage: boolean) => Promise<boolean>>;
66
+ readonly onPrepareCentralRemoteReplication: ((showMessage: boolean) => Promise<boolean>) & {
67
+ addHandler: (callback: (showMessage: boolean) => import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult | Promise<import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult>, priority?: number, allowSwap?: boolean) => import("../lib/HandlerUtils.js").UnregisterFunction;
68
+ removeHandler: (callback: (showMessage: boolean) => import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult | Promise<import("../../replication/ReplicatorProvider.js").ReplicationPreparationResult>) => void;
69
+ };
62
70
  /**
63
71
  * Lightweight, repeatable policy checks shared by every replication entry point.
64
72
  * Handlers must remain idempotent because a high-level replication may cross
@@ -20,9 +20,11 @@ import {
20
20
  replicationFailed,
21
21
  outcomeFromFiniteOpenReplication
22
22
  } from "../../replication/ReplicatorProvider.js";
23
+ import { EVENT_REPLICATION_ABORT_REQUESTED } from "../../events/coreEvents.js";
23
24
  import { UnresolvedErrorManager } from "./UnresolvedErrorManager.js";
24
25
  import { isLockAcquired, shareRunningResult } from "octagonal-wheels/concurrency/lock";
25
26
  import {
27
+ createReplicationPreparation,
26
28
  createReplicationReadinessEvaluator
27
29
  } from "./ReplicationService.readiness.js";
28
30
  import { TypedReplicationCoordinator } from "./ReplicationService.typedReplication.js";
@@ -129,8 +131,8 @@ class ReplicationService extends ServiceBase {
129
131
  },
130
132
  preparation: {
131
133
  commitPendingFileEvents: () => this.fileProcessing.commitPendingFileEvents(),
132
- prepareCentralRemote: (showMessage) => this.onPrepareCentralRemoteReplication(showMessage),
133
- runBeforeReplicate: (showMessage) => this.onBeforeReplicate(showMessage)
134
+ prepareCentralRemote: (showMessage) => this.onPrepareCentralRemoteReplication === this._prepareCentralRemote.invoke ? this._prepareCentralRemote.evaluate(showMessage) : this.onPrepareCentralRemoteReplication(showMessage),
135
+ runBeforeReplicate: (showMessage) => this.onBeforeReplicate === this._beforeReplicate.invoke ? this._beforeReplicate.evaluate(showMessage) : this.onBeforeReplicate(showMessage)
134
136
  },
135
137
  diagnostics: {
136
138
  getUnresolvedMessages: () => this.appLifecycleService.getUnresolvedMessages(),
@@ -143,7 +145,10 @@ class ReplicationService extends ServiceBase {
143
145
  this._typedReplication = new TypedReplicationCoordinator({
144
146
  replicatorService: this.replicatorService,
145
147
  currentSettings: () => this.settingService.currentSettings(),
146
- checkReadiness: (showMessage, readiness) => this.isReplicationReady(showMessage, readiness),
148
+ checkReadiness: async (showMessage, requirements) => {
149
+ const decision = await this._evaluateReadiness({ showMessage, requirements });
150
+ return decision.ready === true ? true : decision.rejection ?? false;
151
+ },
147
152
  handleFailure: (request) => this.onReplicationFailed(request),
148
153
  recordFiniteAttempt: () => {
149
154
  this.previousReplicated = Date.now();
@@ -169,16 +174,16 @@ class ReplicationService extends ServiceBase {
169
174
  * Process a virtual document (e.g., for customisation sync).
170
175
  */
171
176
  processVirtualDocument = handlers().anySuccess("processVirtualDocument");
177
+ _beforeReplicate = createReplicationPreparation("onBeforeReplicate");
172
178
  /**
173
179
  * An event triggered before starting replication.
174
180
  */
175
- onBeforeReplicate = handlers().bailFirstFailure("onBeforeReplicate");
181
+ onBeforeReplicate = this._beforeReplicate.invoke;
176
182
  onFiniteReplicationCompleted = handlers().allSettled("onFiniteReplicationCompleted");
177
183
  onFileReflectionFailed = handlers().allOrThrow("onFileReflectionFailed");
184
+ _prepareCentralRemote = createReplicationPreparation("onPrepareCentralRemoteReplication");
178
185
  /** Provider preparation which applies only to the central remote. */
179
- onPrepareCentralRemoteReplication = handlers().bailFirstFailure(
180
- "onPrepareCentralRemoteReplication"
181
- );
186
+ onPrepareCentralRemoteReplication = this._prepareCentralRemote.invoke;
182
187
  /**
183
188
  * Lightweight, repeatable policy checks shared by every replication entry point.
184
189
  * Handlers must remain idempotent because a high-level replication may cross
@@ -240,6 +245,7 @@ class ReplicationService extends ServiceBase {
240
245
  * replication, so it does not invoke failure-recovery handlers.
241
246
  */
242
247
  async stopActiveTransfer() {
248
+ this.context.events.emitEvent(EVENT_REPLICATION_ABORT_REQUESTED);
243
249
  return await this._typedReplication.stopActiveTransfer();
244
250
  }
245
251
  async performReplicationRequest(showMessage) {
@@ -1,8 +1,17 @@
1
1
  import { type LOG_LEVEL, type ObsidianLiveSyncSettings } from "../../common/types.js";
2
- import { type ReplicationReadinessRequirements } from "../../replication/ReplicatorProvider.js";
2
+ import { type ContinuousReplicationNetworkFailure, type ReplicationReadinessRequirements, type ReplicationPreparationResult } from "../../replication/ReplicatorProvider.js";
3
3
  import { type LogFunction } from "../lib/logUtils.js";
4
4
  import type { MessageTranslator } from "./MessageTranslator.js";
5
5
  import { type ReadinessEvaluationResult } from "./ReadinessEvaluator.js";
6
+ type PreparationHandler = (showMessage: boolean) => ReplicationPreparationResult | Promise<ReplicationPreparationResult>;
7
+ /** Direct legacy callers receive a boolean. Readiness also receives the rejecting handler's observation. */
8
+ export declare function createReplicationPreparation(name: string): {
9
+ invoke: ((showMessage: boolean) => Promise<boolean>) & {
10
+ addHandler: (callback: PreparationHandler, priority?: number, allowSwap?: boolean) => import("../lib/HandlerUtils.js").UnregisterFunction;
11
+ removeHandler: (callback: PreparationHandler) => void;
12
+ };
13
+ evaluate: (showMessage: boolean) => Promise<ReplicationPreparationResult>;
14
+ };
6
15
  /** State and policy gates consulted without beginning remote preparation. */
7
16
  export interface ReplicationReadinessGates {
8
17
  readonly isApplicationReady: () => boolean;
@@ -14,8 +23,8 @@ export interface ReplicationReadinessGates {
14
23
  /** Ordered operational gates which may release or prepare replication work. */
15
24
  export interface ReplicationReadinessPreparation {
16
25
  readonly commitPendingFileEvents: () => Promise<boolean>;
17
- readonly prepareCentralRemote: (showMessage: boolean) => Promise<boolean>;
18
- readonly runBeforeReplicate: (showMessage: boolean) => Promise<boolean>;
26
+ readonly prepareCentralRemote: PreparationHandler;
27
+ readonly runBeforeReplicate: PreparationHandler;
19
28
  }
20
29
  /** Diagnostic state, presentation, and unresolved-error output for readiness. */
21
30
  export interface ReplicationReadinessDiagnostics {
@@ -40,7 +49,7 @@ export interface ReplicationReadinessRequest {
40
49
  readonly showMessage?: boolean;
41
50
  readonly requirements?: ReplicationReadinessRequirements;
42
51
  }
43
- export type ReplicationReadinessEvaluator = (context?: ReplicationReadinessRequest) => Promise<ReadinessEvaluationResult>;
52
+ export type ReplicationReadinessEvaluator = (context?: ReplicationReadinessRequest) => Promise<ReadinessEvaluationResult<ContinuousReplicationNetworkFailure>>;
44
53
  /**
45
54
  * Compose the ordered readiness conditions shared by replication entry points.
46
55
  *
@@ -50,3 +59,4 @@ export type ReplicationReadinessEvaluator = (context?: ReplicationReadinessReque
50
59
  * requirements while the common conditions retain their declaration order.
51
60
  */
52
61
  export declare function createReplicationReadinessEvaluator(dependencies: ReplicationReadinessDependencies): ReplicationReadinessEvaluator;
62
+ export {};
@@ -1,9 +1,35 @@
1
1
  import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE } from "../../common/types.js";
2
2
  import {
3
- CENTRAL_REMOTE_REPLICATION_READINESS
3
+ CENTRAL_REMOTE_REPLICATION_READINESS,
4
+ observedOfflineReplicationFailure
4
5
  } from "../../replication/ReplicatorProvider.js";
6
+ import { MultiBinder } from "../lib/HandlerUtils.js";
7
+ import { Logger, LOG_LEVEL_VERBOSE } from "../../common/logger.js";
5
8
  import { MARK_LOG_NETWORK_ERROR } from "../lib/logUtils.js";
6
9
  import { evaluateReadiness } from "./ReadinessEvaluator.js";
10
+ class ReplicationPreparationHandlers extends MultiBinder {
11
+ async evaluate(showMessage) {
12
+ for (const handler of [...this._callbacks]) {
13
+ try {
14
+ const decision = await handler(showMessage);
15
+ if (decision !== true) return decision;
16
+ } catch (error) {
17
+ Logger(error, LOG_LEVEL_VERBOSE);
18
+ return false;
19
+ }
20
+ }
21
+ return true;
22
+ }
23
+ }
24
+ function createReplicationPreparation(name) {
25
+ const handlers = new ReplicationPreparationHandlers(name);
26
+ const evaluate = handlers.evaluate.bind(handlers);
27
+ const invoke = Object.assign(async (showMessage) => await evaluate(showMessage) === true, {
28
+ addHandler: handlers.addHandler.bind(handlers),
29
+ removeHandler: handlers.removeHandler.bind(handlers)
30
+ });
31
+ return { invoke, evaluate };
32
+ }
7
33
  function createReplicationReadinessEvaluator(dependencies) {
8
34
  const { diagnostics, gates, preparation } = dependencies;
9
35
  const reportPreparationFailure = async () => {
@@ -52,7 +78,7 @@ function createReplicationReadinessEvaluator(dependencies) {
52
78
  },
53
79
  {
54
80
  name: "network-online",
55
- evaluate: () => gates.isOnline(),
81
+ evaluate: () => gates.isOnline() || observedOfflineReplicationFailure(),
56
82
  onRejected: ({ showMessage }) => {
57
83
  diagnostics.showError("Network is offline", showMessage ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
58
84
  }
@@ -83,5 +109,6 @@ function createReplicationReadinessEvaluator(dependencies) {
83
109
  };
84
110
  }
85
111
  export {
112
+ createReplicationPreparation,
86
113
  createReplicationReadinessEvaluator
87
114
  };
@@ -1,11 +1,11 @@
1
1
  import type { ObsidianLiveSyncSettings } from "../../common/types.js";
2
- import { type ContinuousReplicationRequest, type ReplicationFailureRequest, type ReplicationOutcome, type ReplicationReadinessRequirements, type UnattendedOneShotRequest, type UserInitiatedOneShotRequest } from "../../replication/ReplicatorProvider.js";
2
+ import { type ContinuousReplicationRequest, type ReplicationFailureRequest, type ReplicationPreparationResult, type ReplicationOutcome, type ReplicationReadinessRequirements, type UnattendedOneShotRequest, type UserInitiatedOneShotRequest } from "../../replication/ReplicatorProvider.js";
3
3
  import type { IReplicatorService } from "./IService.js";
4
4
  /** ReplicationService collaborators required to execute typed provider roles. */
5
5
  export interface TypedReplicationCoordinatorDependencies {
6
6
  readonly replicatorService: Pick<IReplicatorService, "acquireActiveReplicatorContext" | "hasActiveReplicator" | "runWithActiveReplicatorContext" | "runFiniteReplicationActivity">;
7
7
  readonly currentSettings: () => ObsidianLiveSyncSettings;
8
- readonly checkReadiness: (showMessage: boolean, readiness: ReplicationReadinessRequirements) => Promise<boolean>;
8
+ readonly checkReadiness: (showMessage: boolean, readiness: ReplicationReadinessRequirements) => Promise<ReplicationPreparationResult>;
9
9
  readonly handleFailure: (request: ReplicationFailureRequest) => Promise<boolean>;
10
10
  /**
11
11
  * Advance the host's finite-attempt clock after readiness admits dispatch.
@@ -30,6 +30,8 @@ export interface TypedReplicationCoordinatorDependencies {
30
30
  export declare class TypedReplicationCoordinator {
31
31
  private readonly dependencies;
32
32
  private oneShotInProgress;
33
+ private continuousStopGeneration;
34
+ private readonly cancelReadinessWaits;
33
35
  constructor(dependencies: TypedReplicationCoordinatorDependencies);
34
36
  /**
35
37
  * Execute a user-initiated finite role with the request's interaction authority.
@@ -60,6 +62,7 @@ export declare class TypedReplicationCoordinator {
60
62
  * recovery handler.
61
63
  */
62
64
  startContinuous(request: ContinuousReplicationRequest): Promise<ReplicationOutcome>;
65
+ private admitContinuous;
63
66
  /**
64
67
  * Request transfer cancellation on one atomically acquired active context.
65
68
  *