@jr2804/livesync-cli 1.0.28-cli.1 → 1.0.30-cli.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.cjs +1217 -193
  2. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -66,6 +66,339 @@ let buffer = require("buffer");
66
66
  let node_zlib = require("node:zlib");
67
67
  node_zlib = require_stream_collector.__toESM(node_zlib);
68
68
  let chokidar = require("chokidar");
69
+ //#region ../../integrations/cloudflare/settings.ts
70
+ /** The lifetime requested from Cloudflare for each issued credential set. */
71
+ var CLOUDFLARE_TURN_CREDENTIAL_TTL_SECONDS = 86400;
72
+ /** The Cloudflare TURN credential-generation endpoint. */
73
+ var CLOUDFLARE_TURN_CREDENTIAL_ENDPOINT = "https://rtc.live.cloudflare.com/v1/turn/keys";
74
+ var TURN_KEY_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,255}$/;
75
+ var BEARER_TOKEN_PATTERN = /^[A-Za-z0-9._~+/-]+={0,2}$/;
76
+ var MAX_BEARER_TOKEN_LENGTH = 4096;
77
+ /**
78
+ * Returns a safe validation message for a Cloudflare TURN configuration.
79
+ * The result never includes the supplied Key ID or API token.
80
+ */
81
+ function validateCloudflareTurnConfiguration(value) {
82
+ const turnKeyId = value.turnKeyId;
83
+ if (typeof turnKeyId !== "string" || turnKeyId.length === 0) return "Enter a TURN Key ID.";
84
+ if (!TURN_KEY_ID_PATTERN.test(turnKeyId)) return "TURN Key ID contains unsupported characters.";
85
+ const apiToken = value.apiToken;
86
+ if (typeof apiToken !== "string" || apiToken.length === 0) return "Enter a TURN Key API Token.";
87
+ if (apiToken.length > MAX_BEARER_TOKEN_LENGTH || !BEARER_TOKEN_PATTERN.test(apiToken)) return "TURN Key API Token must use Bearer token syntax.";
88
+ }
89
+ //#endregion
90
+ //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/coreEnvFunctions.js
91
+ var _getLanguage = () => "en";
92
+ function getLanguage() {
93
+ return _getLanguage();
94
+ }
95
+ var compatGlobal = typeof window !== "undefined" ? window : globalThis;
96
+ var _fetch = compatGlobal.fetch.bind(compatGlobal);
97
+ var activeDocumentWindow = compatGlobal;
98
+ var _activeDocument = activeDocumentWindow.activeDocument ?? activeDocumentWindow.document;
99
+ var FAILURE_MESSAGES = {
100
+ configuration: "The Cloudflare TURN configuration is invalid.",
101
+ authentication: "The Cloudflare TURN credential request was not authorised.",
102
+ unavailable: "The Cloudflare TURN service is unavailable.",
103
+ "invalid-response": "The Cloudflare TURN service returned an invalid response."
104
+ };
105
+ function credentialFailure(code, retryable) {
106
+ return Object.assign(new Error(FAILURE_MESSAGES[code]), {
107
+ code,
108
+ retryable
109
+ });
110
+ }
111
+ function isRecord$2(value) {
112
+ return typeof value === "object" && value !== null && !Array.isArray(value);
113
+ }
114
+ function abortError() {
115
+ try {
116
+ return new DOMException("The operation was aborted.", "AbortError");
117
+ } catch {
118
+ const error = /* @__PURE__ */ new Error("The operation was aborted.");
119
+ error.name = "AbortError";
120
+ return error;
121
+ }
122
+ }
123
+ function throwIfAborted$1(signal) {
124
+ if (signal.aborted) throw abortError();
125
+ }
126
+ function isControlCharacter(value) {
127
+ return Array.from(value).some((character) => {
128
+ const code = character.charCodeAt(0);
129
+ return code <= 31 || code === 127;
130
+ });
131
+ }
132
+ function isPort(value) {
133
+ if (!/^\d{1,5}$/.test(value)) return false;
134
+ const port = Number(value);
135
+ return port >= 1 && port <= 65535;
136
+ }
137
+ function isHost(value) {
138
+ return value.length > 0 && /^[A-Za-z0-9._-]+$/.test(value);
139
+ }
140
+ /**
141
+ * Validates the URL forms accepted by WebRTC's ICE server configuration.
142
+ * TURN URLs may carry only the standard transport query parameter; userinfo,
143
+ * paths, fragments, and arbitrary query values are not accepted.
144
+ */
145
+ function isSupportedIceServerUrl(value) {
146
+ if (value.length === 0 || value.length > 2048 || isControlCharacter(value)) return false;
147
+ const schemeMatch = /^(stun|stuns|turn|turns):(.+)$/i.exec(value);
148
+ if (!schemeMatch) return false;
149
+ const remainder = schemeMatch[2];
150
+ const queryIndex = remainder.indexOf("?");
151
+ const authority = queryIndex >= 0 ? remainder.slice(0, queryIndex) : remainder;
152
+ const query = queryIndex >= 0 ? remainder.slice(queryIndex + 1) : "";
153
+ if (authority.length === 0 || authority.includes("/") || authority.includes("#") || authority.includes("@")) return false;
154
+ if (authority.includes("%")) return false;
155
+ if (authority.startsWith("[")) {
156
+ const closingBracket = authority.indexOf("]");
157
+ if (closingBracket < 0) return false;
158
+ const host = authority.slice(1, closingBracket);
159
+ if (!/^[0-9A-Fa-f:.]+$/.test(host) || !host.includes(":")) return false;
160
+ const suffix = authority.slice(closingBracket + 1);
161
+ if (suffix !== "" && (!suffix.startsWith(":") || !isPort(suffix.slice(1)))) return false;
162
+ } else {
163
+ const colonIndex = authority.lastIndexOf(":");
164
+ const host = colonIndex >= 0 ? authority.slice(0, colonIndex) : authority;
165
+ if (!isHost(host) || colonIndex >= 0 && !isPort(authority.slice(colonIndex + 1))) return false;
166
+ if (colonIndex >= 0 && host.includes(":")) return false;
167
+ }
168
+ if (query.length === 0) return true;
169
+ const queryParts = query.split("&");
170
+ return queryParts.length === 1 && /^transport=(udp|tcp)$/i.test(queryParts[0]);
171
+ }
172
+ function isTurnUrl(value) {
173
+ return /^(turn|turns):/i.test(value);
174
+ }
175
+ function isCredential(value) {
176
+ return typeof value === "string" && value.length > 0 && value.length <= 4096 && !isControlCharacter(value);
177
+ }
178
+ function normaliseIceServers(value) {
179
+ if (!isRecord$2(value) || !Array.isArray(value.iceServers)) throw credentialFailure("invalid-response", false);
180
+ if (value.iceServers.length === 0 || value.iceServers.length > 16) throw credentialFailure("invalid-response", false);
181
+ const servers = [];
182
+ let urlCount = 0;
183
+ let hasTurnServer = false;
184
+ for (const candidate of value.iceServers) {
185
+ if (!isRecord$2(candidate)) throw credentialFailure("invalid-response", false);
186
+ const rawUrls = candidate.urls;
187
+ const urls = typeof rawUrls === "string" ? [rawUrls] : Array.isArray(rawUrls) && rawUrls.every((url) => typeof url === "string") ? [...rawUrls] : void 0;
188
+ if (!urls || urls.length === 0) throw credentialFailure("invalid-response", false);
189
+ urlCount += urls.length;
190
+ if (urlCount > 32 || urls.some((url) => !isSupportedIceServerUrl(url))) throw credentialFailure("invalid-response", false);
191
+ const turnEntry = urls.some(isTurnUrl);
192
+ hasTurnServer ||= turnEntry;
193
+ const normalised = { urls };
194
+ if (turnEntry) {
195
+ if (!isCredential(candidate.username) || !isCredential(candidate.credential)) throw credentialFailure("invalid-response", false);
196
+ normalised.username = candidate.username;
197
+ normalised.credential = candidate.credential;
198
+ }
199
+ servers.push(normalised);
200
+ }
201
+ if (!hasTurnServer) throw credentialFailure("invalid-response", false);
202
+ return Object.freeze(servers);
203
+ }
204
+ var BoundedResponseError = class extends Error {
205
+ constructor(kind) {
206
+ super(kind);
207
+ this.kind = kind;
208
+ }
209
+ };
210
+ async function readResponseBody(response) {
211
+ const contentLength = response.headers.get("content-length");
212
+ if (contentLength !== null) {
213
+ const declaredLength = Number(contentLength);
214
+ if (!Number.isFinite(declaredLength) || declaredLength < 0) throw new BoundedResponseError("invalid-length");
215
+ if (declaredLength > 32768) throw new BoundedResponseError("too-large");
216
+ }
217
+ if (!response.body) try {
218
+ const text = await response.text();
219
+ if (new TextEncoder().encode(text).byteLength > 32768) throw new BoundedResponseError("too-large");
220
+ return text;
221
+ } catch (error) {
222
+ if (error instanceof BoundedResponseError) throw error;
223
+ throw new BoundedResponseError("read-failed");
224
+ }
225
+ const reader = response.body.getReader();
226
+ const chunks = [];
227
+ let totalBytes = 0;
228
+ try {
229
+ while (true) {
230
+ const result = await reader.read();
231
+ if (result.done) break;
232
+ totalBytes += result.value.byteLength;
233
+ if (totalBytes > 32768) {
234
+ try {
235
+ await reader.cancel();
236
+ } catch {}
237
+ throw new BoundedResponseError("too-large");
238
+ }
239
+ chunks.push(result.value);
240
+ }
241
+ } catch (error) {
242
+ if (error instanceof BoundedResponseError) throw error;
243
+ throw new BoundedResponseError("read-failed");
244
+ } finally {
245
+ reader.releaseLock();
246
+ }
247
+ const bytes = new Uint8Array(totalBytes);
248
+ let offset = 0;
249
+ for (const chunk of chunks) {
250
+ bytes.set(chunk, offset);
251
+ offset += chunk.byteLength;
252
+ }
253
+ return new TextDecoder().decode(bytes);
254
+ }
255
+ function classifyHttpFailure(status) {
256
+ if (status === 401 || status === 403) return credentialFailure("authentication", false);
257
+ if (status === 408 || status === 429 || status >= 500) return credentialFailure("unavailable", true);
258
+ return credentialFailure("unavailable", false);
259
+ }
260
+ function parseResponseBody(body) {
261
+ let value;
262
+ try {
263
+ value = JSON.parse(body);
264
+ } catch {
265
+ throw credentialFailure("invalid-response", false);
266
+ }
267
+ return normaliseIceServers(value);
268
+ }
269
+ /** Acquire one temporary ICE configuration for a new room connection. */
270
+ async function acquireCloudflareTurnCredentials(configuration, dependencies, signal) {
271
+ if (validateCloudflareTurnConfiguration(configuration)) throw credentialFailure("configuration", false);
272
+ const now = dependencies.now ?? Date.now;
273
+ const requestDeadlineMs = dependencies.requestDeadlineMs ?? 15e3;
274
+ throwIfAborted$1(signal);
275
+ const requestStartedAt = now();
276
+ if (!Number.isFinite(requestStartedAt)) throw credentialFailure("unavailable", true);
277
+ const requestController = new AbortController();
278
+ let cancelledByCaller = false;
279
+ let rejectCaller;
280
+ const callerAbort = new Promise((_resolve, reject) => {
281
+ rejectCaller = reject;
282
+ });
283
+ let timedOut = false;
284
+ const onAbort = () => {
285
+ cancelledByCaller = true;
286
+ requestController.abort();
287
+ rejectCaller?.(abortError());
288
+ };
289
+ signal.addEventListener("abort", onAbort, { once: true });
290
+ if (signal.aborted) {
291
+ signal.removeEventListener("abort", onAbort);
292
+ requestController.abort();
293
+ throw abortError();
294
+ }
295
+ let timeoutId;
296
+ const deadline = new Promise((_resolve, reject) => {
297
+ timeoutId = compatGlobal.setTimeout(() => {
298
+ timedOut = true;
299
+ requestController.abort();
300
+ reject(credentialFailure("unavailable", true));
301
+ }, requestDeadlineMs);
302
+ });
303
+ const cleanup = () => {
304
+ if (timeoutId !== void 0) compatGlobal.clearTimeout(timeoutId);
305
+ signal.removeEventListener("abort", onAbort);
306
+ };
307
+ const endpoint = `${CLOUDFLARE_TURN_CREDENTIAL_ENDPOINT}/${configuration.turnKeyId}/credentials/generate-ice-servers`;
308
+ let response;
309
+ try {
310
+ response = await Promise.race([
311
+ dependencies.fetch(endpoint, {
312
+ method: "POST",
313
+ headers: {
314
+ Authorization: `Bearer ${configuration.apiToken}`,
315
+ "Content-Type": "application/json"
316
+ },
317
+ body: JSON.stringify({ ttl: CLOUDFLARE_TURN_CREDENTIAL_TTL_SECONDS }),
318
+ signal: requestController.signal,
319
+ redirect: "error",
320
+ credentials: "omit",
321
+ cache: "no-store"
322
+ }),
323
+ callerAbort,
324
+ deadline
325
+ ]);
326
+ } catch {
327
+ cleanup();
328
+ if (cancelledByCaller || signal.aborted) throw abortError();
329
+ if (timedOut) throw credentialFailure("unavailable", true);
330
+ throw credentialFailure("unavailable", true);
331
+ }
332
+ if (cancelledByCaller || signal.aborted) {
333
+ cleanup();
334
+ throw abortError();
335
+ }
336
+ if (timedOut || requestController.signal.aborted) {
337
+ cleanup();
338
+ throw credentialFailure("unavailable", true);
339
+ }
340
+ if (response.status !== 201) {
341
+ cleanup();
342
+ throw classifyHttpFailure(response.status);
343
+ }
344
+ let body;
345
+ try {
346
+ body = await Promise.race([
347
+ readResponseBody(response),
348
+ callerAbort,
349
+ deadline
350
+ ]);
351
+ } catch (error) {
352
+ cleanup();
353
+ if (cancelledByCaller || signal.aborted) throw abortError();
354
+ if (timedOut) throw credentialFailure("unavailable", true);
355
+ if (error instanceof BoundedResponseError && error.kind === "read-failed") throw credentialFailure("unavailable", true);
356
+ throw credentialFailure("invalid-response", false);
357
+ }
358
+ try {
359
+ throwIfAborted$1(signal);
360
+ const iceServers = parseResponseBody(body);
361
+ const expiresAt = requestStartedAt + CLOUDFLARE_TURN_CREDENTIAL_TTL_SECONDS * 1e3;
362
+ if (!Number.isFinite(expiresAt) || expiresAt <= now() + 3e4) throw credentialFailure("invalid-response", false);
363
+ return {
364
+ iceServers,
365
+ expiresAt
366
+ };
367
+ } finally {
368
+ cleanup();
369
+ }
370
+ }
371
+ //#endregion
372
+ //#region ../../integrations/turnSettings.ts
373
+ /** Validate provider inputs without requesting credentials. */
374
+ function validateManagedTurnSettings(settings) {
375
+ if (settings.P2P_managedType === void 0 || settings.P2P_managedType === "") return void 0;
376
+ if (settings.P2P_managedType !== "CF") return "The selected TURN configuration is not supported.";
377
+ return validateCloudflareTurnConfiguration({
378
+ turnKeyId: settings.P2P_managedId ?? "",
379
+ apiToken: settings.P2P_managedToken ?? ""
380
+ });
381
+ }
382
+ //#endregion
383
+ //#region ../../serviceFeatures/useP2PSettingsPreparation.ts
384
+ /** Prepare a connection copy using the host's HTTP adapter. */
385
+ function useP2PSettingsPreparation(fetch) {
386
+ return async (settings, signal) => {
387
+ const error = validateManagedTurnSettings(settings);
388
+ if (error) throw new Error(error);
389
+ if (!settings.P2P_managedType) return { ...settings };
390
+ const { iceServers, expiresAt } = await acquireCloudflareTurnCredentials({
391
+ turnKeyId: settings.P2P_managedId ?? "",
392
+ apiToken: settings.P2P_managedToken ?? ""
393
+ }, { fetch }, signal);
394
+ return {
395
+ ...settings,
396
+ P2P_iceServers: iceServers,
397
+ P2P_iceServersExpiresAt: expiresAt
398
+ };
399
+ };
400
+ }
401
+ //#endregion
69
402
  //#region ../../../node_modules/octagonal-wheels/dist/common/polyfill.js
70
403
  var _a$1;
71
404
  var FallbackWeakRef = "WeakRef" in globalThis ? globalThis.WeakRef : (_a$1 = class WeakRef {
@@ -3961,16 +4294,6 @@ minimatch.Minimatch = Minimatch;
3961
4294
  minimatch.escape = escape;
3962
4295
  minimatch.unescape = unescape;
3963
4296
  //#endregion
3964
- //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/coreEnvFunctions.js
3965
- var _getLanguage = () => "en";
3966
- function getLanguage() {
3967
- return _getLanguage();
3968
- }
3969
- var compatGlobal = typeof window !== "undefined" ? window : globalThis;
3970
- var _fetch = compatGlobal.fetch.bind(compatGlobal);
3971
- var activeDocumentWindow = compatGlobal;
3972
- var _activeDocument = activeDocumentWindow.activeDocument ?? activeDocumentWindow.document;
3973
- //#endregion
3974
4297
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/mods.js
3975
4298
  var webcrypto$5;
3976
4299
  async function getWebCrypto() {
@@ -4078,6 +4401,13 @@ var ChunkAlgorithms = {
4078
4401
  };
4079
4402
  //#endregion
4080
4403
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/models/setting.p2p.js
4404
+ function hasManagedP2PTurnConfiguration(settings) {
4405
+ return typeof settings.P2P_managedType === "string" && settings.P2P_managedType.trim().length > 0;
4406
+ }
4407
+ function omitP2PRuntimeSettings(settings) {
4408
+ const { P2P_iceServers: _iceServers, P2P_iceServersExpiresAt: _expiresAt, ...persistable } = settings;
4409
+ return persistable;
4410
+ }
4081
4411
  function normaliseP2PMaxWirePayloadBytes(value) {
4082
4412
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < P2PMessageSizePresets.MaximumCompatibility || value > P2PMessageSizePresets.Standard) return P2PMessageSizePresets.Standard;
4083
4413
  return value;
@@ -4337,13 +4667,14 @@ var SETTINGS_MIGRATIONS = [{
4337
4667
  } : void 0
4338
4668
  }];
4339
4669
  function cloneSettings$1(source, fallbacks) {
4670
+ const persistableSource = omitP2PRuntimeSettings(source);
4340
4671
  return {
4341
4672
  ...fallbacks,
4342
- ...source,
4343
- remoteConfigurations: Object.fromEntries(Object.entries(source.remoteConfigurations ?? fallbacks.remoteConfigurations).map(([id, config]) => [id, { ...config }])),
4673
+ ...persistableSource,
4674
+ remoteConfigurations: Object.fromEntries(Object.entries(persistableSource.remoteConfigurations ?? fallbacks.remoteConfigurations).map(([id, config]) => [id, { ...config }])),
4344
4675
  pluginSyncExtendedSetting: {
4345
4676
  ...fallbacks.pluginSyncExtendedSetting,
4346
- ...source.pluginSyncExtendedSetting
4677
+ ...persistableSource.pluginSyncExtendedSetting
4347
4678
  }
4348
4679
  };
4349
4680
  }
@@ -7122,6 +7453,7 @@ var REPLICATION_PROGRESS_PRESENTATIONS = Object.freeze({
7122
7453
  var REPLICATION_COMPLETED = Object.freeze({ status: "completed" });
7123
7454
  var REPLICATION_CANCELLED = Object.freeze({ status: "cancelled" });
7124
7455
  var CENTRAL_REMOTE_REPLICATION_READINESS = Object.freeze({ centralRemotePreparation: "required" });
7456
+ var PROVIDER_OWNED_CENTRAL_REMOTE_REPLICATION_READINESS = Object.freeze({ centralRemotePreparation: "provider-owned" });
7125
7457
  var PEER_REPLICATION_READINESS = Object.freeze({ centralRemotePreparation: "not-applicable" });
7126
7458
  function isReplicationCompleted(outcome) {
7127
7459
  return outcome.status === "completed";
@@ -11559,10 +11891,10 @@ var HeadlessAPIService = class extends InjectableAPIService {
11559
11891
  return "headless-app";
11560
11892
  }
11561
11893
  getAppVersion() {
11562
- return `1.0.28`;
11894
+ return `1.0.30`;
11563
11895
  }
11564
11896
  getPluginVersion() {
11565
- return `1.0.28`;
11897
+ return `1.0.30`;
11566
11898
  }
11567
11899
  getPlatform() {
11568
11900
  return "server";
@@ -12048,7 +12380,7 @@ async function decryptString(encrypted, passphrase) {
12048
12380
  var PROXY_SCHEME = "https";
12049
12381
  function parseSlsUri(uriString) {
12050
12382
  const match = uriString.match(/^sls\+([^:]+):(.*)$/);
12051
- if (!match) throw new Error(`Unsupported URI: ${uriString}`);
12383
+ if (!match) throw new Error("Unsupported URI");
12052
12384
  const subscheme = match[1];
12053
12385
  const rest = match[2];
12054
12386
  return {
@@ -12065,7 +12397,7 @@ var ConnectionStringParser = class {
12065
12397
  */
12066
12398
  static parse(uriString) {
12067
12399
  const match = uriString.match(/^sls\+([^:]+):/);
12068
- if (!match) throw new Error(`Unsupported URI: ${uriString}`);
12400
+ if (!match) throw new Error("Unsupported URI");
12069
12401
  const subscheme = match[1];
12070
12402
  if (subscheme === "p2p") return {
12071
12403
  type: "p2p",
@@ -12082,7 +12414,7 @@ var ConnectionStringParser = class {
12082
12414
  type: "s3",
12083
12415
  settings: this.parseS3(url)
12084
12416
  };
12085
- default: throw new Error(`Unsupported protocol: sls+${subscheme}`);
12417
+ default: throw new Error("Unsupported protocol");
12086
12418
  }
12087
12419
  }
12088
12420
  /**
@@ -12161,7 +12493,7 @@ var ConnectionStringParser = class {
12161
12493
  }
12162
12494
  static parseP2P(uriString) {
12163
12495
  const match = uriString.match(/^sls\+p2p:\/\/([^?#]+)(?:\?([^#]*))?(?:#(.*))?$/);
12164
- if (!match) throw new Error(`Invalid P2P URI: ${uriString}`);
12496
+ if (!match) throw new Error("Invalid P2P URI");
12165
12497
  const authority = match[1];
12166
12498
  const queryString = match[2] || "";
12167
12499
  let userinfo = "";
@@ -12189,7 +12521,10 @@ var ConnectionStringParser = class {
12189
12521
  P2P_turnUsername: searchParams.get("turnUser") || "",
12190
12522
  P2P_turnCredential: searchParams.get("turnPass") || "",
12191
12523
  P2P_maxWirePayloadBytes: normaliseP2PMaxWirePayloadBytes(Number(searchParams.get("maxWirePayloadBytes"))),
12192
- P2P_connectionPath: normaliseP2PConnectionPath(searchParams.get("connectionPath"))
12524
+ P2P_connectionPath: normaliseP2PConnectionPath(searchParams.get("connectionPath")),
12525
+ P2P_managedType: searchParams.get("managedType") || void 0,
12526
+ P2P_managedId: searchParams.get("managedId") || void 0,
12527
+ P2P_managedToken: searchParams.get("token") || void 0
12193
12528
  };
12194
12529
  }
12195
12530
  static serializeP2P(settings) {
@@ -12204,6 +12539,9 @@ var ConnectionStringParser = class {
12204
12539
  if (settings.P2P_turnCredential) searchParams.set("turnPass", settings.P2P_turnCredential);
12205
12540
  searchParams.set("maxWirePayloadBytes", String(normaliseP2PMaxWirePayloadBytes(settings.P2P_maxWirePayloadBytes)));
12206
12541
  searchParams.set("connectionPath", normaliseP2PConnectionPath(settings.P2P_connectionPath));
12542
+ if (settings.P2P_managedType) searchParams.set("managedType", settings.P2P_managedType);
12543
+ if (settings.P2P_managedId) searchParams.set("managedId", settings.P2P_managedId);
12544
+ if (settings.P2P_managedToken) searchParams.set("token", settings.P2P_managedToken);
12207
12545
  return `sls+p2p://${settings.P2P_passphrase ? `:${encodeURIComponent(settings.P2P_passphrase)}@` : ""}${encodeURIComponent(settings.P2P_roomID)}${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;
12208
12546
  }
12209
12547
  };
@@ -12260,6 +12598,7 @@ function migrateLegacyRemoteConfigurationsInPlace(settings, log) {
12260
12598
  if (createdIds.length === 0) return false;
12261
12599
  const preferredId = settings.remoteType === REMOTE_MINIO ? "legacy-s3" : settings.remoteType === REMOTE_P2P ? "legacy-p2p" : "legacy-couchdb";
12262
12600
  settings.activeConfigurationId = settings.remoteConfigurations[preferredId] ? preferredId : createdIds[0];
12601
+ if (settings.remoteConfigurations["legacy-p2p"]) settings.P2P_ActiveRemoteConfigurationId = "legacy-p2p";
12263
12602
  return true;
12264
12603
  }
12265
12604
  function createRemoteConfigurationId() {
@@ -12447,10 +12786,7 @@ var SettingService = class extends ServiceBase {
12447
12786
  async saveSettingData() {
12448
12787
  this.saveDeviceAndVaultName();
12449
12788
  const previousSettings = this._lastPersistedSettings ?? this.cloneSettings(this.settings);
12450
- const settings = {
12451
- ...this.settings,
12452
- remoteConfigurations: Object.fromEntries(Object.entries(this.settings.remoteConfigurations || {}).map(([id, config]) => [id, { ...config }]))
12453
- };
12789
+ const settings = this.cloneSettings(this.settings);
12454
12790
  const hookResults = await this.onBeforeSaveSettingData(settings, previousSettings);
12455
12791
  for (const patch of hookResults) {
12456
12792
  if (patch instanceof Error || !patch) continue;
@@ -12463,8 +12799,17 @@ var SettingService = class extends ServiceBase {
12463
12799
  this.setSmallConfig(SETTING_KEY_P2P_DEVICE_NAME, settings.P2P_DevicePeerName.trim());
12464
12800
  settings.P2P_DevicePeerName = "";
12465
12801
  }
12466
- if (this.usedPassphrase == "" && !await this.getPassphrase(settings)) this._log("Failed to retrieve passphrase. data.json contains unencrypted items!", 64);
12467
- else {
12802
+ delete settings.P2P_managedType;
12803
+ delete settings.P2P_managedId;
12804
+ delete settings.P2P_managedToken;
12805
+ if (this.usedPassphrase == "" && !await this.getPassphrase(settings)) {
12806
+ if (Object.values(settings.remoteConfigurations).some((config) => this.hasManagedP2PProfileURI(config.uri))) {
12807
+ const message = "Failed to retrieve a passphrase for managed P2P source data. Settings were not saved.";
12808
+ this._log(message, 128);
12809
+ throw new Error(message);
12810
+ }
12811
+ this._log("Failed to retrieve passphrase. data.json contains unencrypted items!", 64);
12812
+ } else {
12468
12813
  if (settings.couchDB_PASSWORD != "" || settings.couchDB_URI != "" || settings.couchDB_USER != "" || settings.couchDB_DBNAME) {
12469
12814
  const connectionSetting = {
12470
12815
  couchDB_DBNAME: settings.couchDB_DBNAME,
@@ -12514,8 +12859,24 @@ var SettingService = class extends ServiceBase {
12514
12859
  const configs = settings.remoteConfigurations || {};
12515
12860
  for (const [id, config] of Object.entries(configs)) {
12516
12861
  if (config.isEncrypted || config.uri.trim() === "") continue;
12517
- const encryptedURI = await this.encryptConfigurationItem(config.uri, settings);
12862
+ const managedP2PProfile = this.hasManagedP2PProfileURI(config.uri);
12863
+ let encryptedURI;
12864
+ try {
12865
+ encryptedURI = await this.encryptConfigurationItem(config.uri, settings);
12866
+ } catch (error) {
12867
+ if (managedP2PProfile) {
12868
+ const message = `Failed to encrypt managed P2P remote configuration '${id}'. Settings were not saved.`;
12869
+ this._log(message, 128);
12870
+ throw new Error(message);
12871
+ }
12872
+ throw error;
12873
+ }
12518
12874
  if (encryptedURI === "") {
12875
+ if (managedP2PProfile) {
12876
+ const message = `Failed to encrypt managed P2P remote configuration '${id}'. Settings were not saved.`;
12877
+ this._log(message, 128);
12878
+ throw new Error(message);
12879
+ }
12519
12880
  this._log(`Failed to encrypt remote configuration '${id}'. This entry will be saved in plain text.`, 128);
12520
12881
  continue;
12521
12882
  }
@@ -12526,6 +12887,14 @@ var SettingService = class extends ServiceBase {
12526
12887
  };
12527
12888
  }
12528
12889
  }
12890
+ hasManagedP2PProfileURI(uri) {
12891
+ const trimmed = uri.trim();
12892
+ if (!trimmed.startsWith("sls+p2p://")) return false;
12893
+ const queryStart = trimmed.indexOf("?");
12894
+ if (queryStart < 0) return false;
12895
+ const query = trimmed.slice(queryStart + 1).split("#", 1)[0];
12896
+ return (new URLSearchParams(query).get("managedType") ?? "").trim().length > 0;
12897
+ }
12529
12898
  async decryptRemoteConfigurationUris(settings, passphrase) {
12530
12899
  const configs = settings.remoteConfigurations || {};
12531
12900
  for (const [id, config] of Object.entries(configs)) {
@@ -12603,7 +12972,7 @@ var SettingService = class extends ServiceBase {
12603
12972
  try {
12604
12973
  this.settings = await this.adjustSettings({
12605
12974
  ...this.settings,
12606
- ...partial
12975
+ ...omitP2PRuntimeSettings(partial)
12607
12976
  });
12608
12977
  } catch (ex) {
12609
12978
  this._log("Error in applying external settings: ", 128);
@@ -12769,7 +13138,7 @@ var SettingService = class extends ServiceBase {
12769
13138
  }
12770
13139
  cloneSettings(settings) {
12771
13140
  return {
12772
- ...settings,
13141
+ ...omitP2PRuntimeSettings(settings),
12773
13142
  remoteConfigurations: Object.fromEntries(Object.entries(settings.remoteConfigurations || {}).map(([id, config]) => [id, { ...config }]))
12774
13143
  };
12775
13144
  }
@@ -15791,6 +16160,9 @@ async function putDBEntryWithLiveBaseRevision(host, managers, note, baseRevision
15791
16160
  throw ex;
15792
16161
  }
15793
16162
  }
16163
+ async function putDBEntryAsIndependentRoot(host, managers, note) {
16164
+ return await putDBEntryInternal(host, managers, note, false, { mode: "independent-root" });
16165
+ }
15794
16166
  async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarget) {
15795
16167
  const { localDatabase, chunkManager, splitter } = managers;
15796
16168
  const filename = host.services.path.id2path(note._id, note);
@@ -15824,12 +16196,30 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
15824
16196
  eden: {}
15825
16197
  };
15826
16198
  return await serialized("file:" + filename, async () => {
15827
- if (revisionTarget.mode !== "latest") newDoc._rev = revisionTarget.baseRevision;
15828
- else try {
16199
+ if (revisionTarget.mode === "force-base" || revisionTarget.mode === "live-base") newDoc._rev = revisionTarget.baseRevision;
16200
+ else if (revisionTarget.mode === "latest") try {
15829
16201
  newDoc._rev = (await localDatabase.get(newDoc._id))._rev;
15830
16202
  } catch (ex) {
15831
16203
  if (isErrorOfMissingDoc(ex)) {} else throw ex;
15832
16204
  }
16205
+ if (revisionTarget.mode === "independent-root") {
16206
+ const randomBytes = compatGlobal.crypto.getRandomValues(new Uint8Array(16));
16207
+ const rootId = Array.from(randomBytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
16208
+ newDoc._rev = `1-${rootId}`;
16209
+ const imported = {
16210
+ ...newDoc,
16211
+ _revisions: {
16212
+ start: 1,
16213
+ ids: [rootId]
16214
+ }
16215
+ };
16216
+ await localDatabase.bulkDocs([imported], { new_edits: false });
16217
+ return (await localDatabase.get(newDoc._id, { rev: newDoc._rev }))._rev === newDoc._rev ? {
16218
+ id: newDoc._id,
16219
+ ok: true,
16220
+ rev: newDoc._rev
16221
+ } : false;
16222
+ }
15833
16223
  const r = revisionTarget.mode === "live-base" ? await localDatabase.put(newDoc) : await localDatabase.put(newDoc, { force: true });
15834
16224
  if (r.ok) return r;
15835
16225
  else return false;
@@ -15955,7 +16345,11 @@ function canFetchRemotely(settings) {
15955
16345
  if (settings.remoteType === RemoteTypes.REMOTE_MINIO) return false;
15956
16346
  return true;
15957
16347
  }
15958
- function computeChunkRetrievalMethod(waitForReady, settings) {
16348
+ function computeChunkRetrievalMethod(waitForReady, settings, localOnly = false) {
16349
+ if (localOnly) return {
16350
+ waitForDelivery: false,
16351
+ preventRemoteRequest: true
16352
+ };
15959
16353
  const isOnDemandFetchEnabled = canFetchRemotely(settings);
15960
16354
  if (!waitForReady) {
15961
16355
  if (isOnDemandFetchEnabled) return {
@@ -15972,7 +16366,7 @@ function computeChunkRetrievalMethod(waitForReady, settings) {
15972
16366
  preventRemoteRequest: !isOnDemandFetchEnabled
15973
16367
  };
15974
16368
  }
15975
- async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, filename, meta, dump, waitForReady) {
16369
+ async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, filename, meta, dump, waitForReady, localOnly = false) {
15976
16370
  const dispFilename = stripAllPrefixes(filename);
15977
16371
  const deleted = meta.deleted ?? meta._deleted ?? void 0;
15978
16372
  if (dump) {
@@ -16000,7 +16394,7 @@ async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, f
16000
16394
  }));
16001
16395
  edenChunks = Object.fromEntries(chunks2.map((e) => [e._id, e]));
16002
16396
  }
16003
- const { waitForDelivery, preventRemoteRequest } = computeChunkRetrievalMethod(waitForReady, settings);
16397
+ const { waitForDelivery, preventRemoteRequest } = computeChunkRetrievalMethod(waitForReady, settings, localOnly);
16004
16398
  const childrenKeys = [...meta.children];
16005
16399
  const chunks = await chunkManager.read(childrenKeys, {
16006
16400
  skipCache: false,
@@ -16038,7 +16432,7 @@ async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, f
16038
16432
  }
16039
16433
  return false;
16040
16434
  }
16041
- async function getDBEntryFromMeta(host, { localDatabase, chunkManager }, meta, dump = false, waitForReady = true) {
16435
+ async function getDBEntryFromMeta(host, { localDatabase, chunkManager }, meta, dump = false, waitForReady = true, localOnly = false) {
16042
16436
  const filename = host.services.path.id2path(meta._id, meta);
16043
16437
  if (!isTargetFile(host, filename)) return false;
16044
16438
  const settings = host.services.setting.currentSettings();
@@ -16046,12 +16440,12 @@ async function getDBEntryFromMeta(host, { localDatabase, chunkManager }, meta, d
16046
16440
  if (meta.type == "newnote" || meta.type == "plain") return await respondEntryFromMeta({
16047
16441
  localDatabase,
16048
16442
  chunkManager
16049
- }, settings, filename, meta, dump, waitForReady);
16443
+ }, settings, filename, meta, dump, waitForReady, localOnly);
16050
16444
  return false;
16051
16445
  }
16052
- async function getDBEntryByPath(host, managers, path, opt, dump = false, waitForReady = true, includeDeleted = false) {
16446
+ async function getDBEntryByPath(host, managers, path, opt, dump = false, waitForReady = true, includeDeleted = false, localOnly = false) {
16053
16447
  const meta = await getDBEntryMetaByPath(host, managers, path, opt, includeDeleted);
16054
- if (meta) return await getDBEntryFromMeta(host, managers, meta, dump, waitForReady);
16448
+ if (meta) return await getDBEntryFromMeta(host, managers, meta, dump, waitForReady, localOnly);
16055
16449
  else return false;
16056
16450
  }
16057
16451
  async function deleteDBEntryByPath(host, { localDatabase }, path, opt) {
@@ -16150,11 +16544,11 @@ var EntryManager = class {
16150
16544
  async getDBEntryMeta(path, opt, includeDeleted = false) {
16151
16545
  return await getDBEntryMetaByPath(this.serviceHost, this, path, opt, includeDeleted);
16152
16546
  }
16153
- async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false) {
16154
- return await getDBEntryByPath(this.serviceHost, this, path, opt, dump, waitForReady, includeDeleted);
16547
+ async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false, localOnly = false) {
16548
+ return await getDBEntryByPath(this.serviceHost, this, path, opt, dump, waitForReady, includeDeleted, localOnly);
16155
16549
  }
16156
- async getDBEntryFromMeta(meta, dump = false, waitForReady = true) {
16157
- return await getDBEntryFromMeta(this.serviceHost, this, meta, dump, waitForReady);
16550
+ async getDBEntryFromMeta(meta, dump = false, waitForReady = true, localOnly = false) {
16551
+ return await getDBEntryFromMeta(this.serviceHost, this, meta, dump, waitForReady, localOnly);
16158
16552
  }
16159
16553
  async deleteDBEntry(path, opt) {
16160
16554
  return await deleteDBEntryByPath(this.serviceHost, this, path, opt);
@@ -16168,6 +16562,10 @@ var EntryManager = class {
16168
16562
  async putDBEntryWithLiveBaseRevision(note, baseRevision, onlyChunks) {
16169
16563
  return await putDBEntryWithLiveBaseRevision(this.serviceHost, this, note, baseRevision, onlyChunks);
16170
16564
  }
16565
+ /** Store unknown ancestry as a fresh root; return the Metadata write result or `false`. */
16566
+ async putDBEntryAsIndependentRoot(note) {
16567
+ return await putDBEntryAsIndependentRoot(this.serviceHost, this, note);
16568
+ }
16171
16569
  };
16172
16570
  //#endregion
16173
16571
  //#region ../../../node_modules/octagonal-wheels/dist/hash/purejs.js
@@ -20384,11 +20782,11 @@ var LiveSyncLocalDB = class {
20384
20782
  async getDBEntryMeta(path, opt, includeDeleted = false) {
20385
20783
  return await this.managers.entryManager.getDBEntryMeta(path, opt, includeDeleted);
20386
20784
  }
20387
- async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false) {
20388
- return await this.managers.entryManager.getDBEntry(path, opt, dump, waitForReady, includeDeleted);
20785
+ async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false, localOnly = false) {
20786
+ return await this.managers.entryManager.getDBEntry(path, opt, dump, waitForReady, includeDeleted, localOnly);
20389
20787
  }
20390
- async getDBEntryFromMeta(meta, dump = false, waitForReady = true) {
20391
- return await this.managers.entryManager.getDBEntryFromMeta(meta, dump, waitForReady);
20788
+ async getDBEntryFromMeta(meta, dump = false, waitForReady = true, localOnly = false) {
20789
+ return await this.managers.entryManager.getDBEntryFromMeta(meta, dump, waitForReady, localOnly);
20392
20790
  }
20393
20791
  async deleteDBEntry(path, opt) {
20394
20792
  return await this.managers.entryManager.deleteDBEntry(path, opt);
@@ -20402,6 +20800,10 @@ var LiveSyncLocalDB = class {
20402
20800
  async putDBEntryWithLiveBaseRevision(note, baseRevision, onlyChunks) {
20403
20801
  return await this.managers.entryManager.putDBEntryWithLiveBaseRevision(note, baseRevision, onlyChunks);
20404
20802
  }
20803
+ /** Preserve existing branches and delegate a fresh root write to the entry manager. */
20804
+ async putDBEntryAsIndependentRoot(note) {
20805
+ return await this.managers.entryManager.putDBEntryAsIndependentRoot(note);
20806
+ }
20405
20807
  async getConflictedDoc(path, rev) {
20406
20808
  return await this.managers.conflictManager.getConflictedDoc(path, rev);
20407
20809
  }
@@ -33317,6 +33719,21 @@ var allMessages = {
33317
33719
  * remove it from this map in the same change.
33318
33720
  */
33319
33721
  var liveSyncProvisionalEnglishMessages = {
33722
+ "Configure TURN when a direct connection cannot be established or when you select TURN relay only.": "Configure TURN when a direct connection cannot be established or when you select TURN relay only.",
33723
+ "TURN configuration": "TURN configuration",
33724
+ Manual: "Manual",
33725
+ "Managed (Cloudflare)": "Managed (Cloudflare)",
33726
+ "TURN Key ID": "TURN Key ID",
33727
+ "TURN Key API Token": "TURN Key API Token",
33728
+ "Unsupported TURN configuration": "Unsupported TURN configuration",
33729
+ "The API token is saved with this profile and included in Setup URI and QR code sharing. Temporary TURN credentials are kept in memory only.": "The API token is saved with this profile and included in Setup URI and QR code sharing. Temporary TURN credentials are kept in memory only.",
33730
+ "TURN relay only requires a TURN server or a configured credential source under Advanced Settings.": "TURN relay only requires a TURN server or a configured credential source under Advanced Settings.",
33731
+ "TURN relay only requires TURN configuration. Connection path has been restored to Automatic.": "TURN relay only requires TURN configuration. Connection path has been restored to Automatic.",
33732
+ "Enter a TURN Key ID.": "Enter a TURN Key ID.",
33733
+ "TURN Key ID contains unsupported characters.": "TURN Key ID contains unsupported characters.",
33734
+ "Enter a TURN Key API Token.": "Enter a TURN Key API Token.",
33735
+ "TURN Key API Token must use Bearer token syntax.": "TURN Key API Token must use Bearer token syntax.",
33736
+ "The selected TURN configuration is not supported.": "The selected TURN configuration is not supported.",
33320
33737
  "Setup Complete: Preparing to Fetch from Another Device": "Setup Complete: Preparing to Fetch from Another Device",
33321
33738
  "The P2P connection has been configured successfully. The initial synchronisation data must now be fetched from an online source device.": "The P2P connection has been configured successfully. The initial synchronisation data must now be fetched from an online source device.",
33322
33739
  "After restarting, select an online source device for the initial Fetch. The local LiveSync database on this device will be rebuilt from that source. Unsynchronised files in this Vault may conflict with the fetched data.": "After restarting, select an online source device for the initial Fetch. The local LiveSync database on this device will be rebuilt from that source. Unsynchronised files in this Vault may conflict with the fetched data.",
@@ -33331,7 +33748,7 @@ var liveSyncProvisionalEnglishMessages = {
33331
33748
  "The project's public signalling relay is a best-effort convenience operated by the project author. It does not store Vault contents, but signalling metadata may be visible to the relay. Availability and log retention are not guaranteed. You can replace it with your own Nostr-compatible relay.": "The project's public signalling relay is a best-effort convenience operated by the project author. It does not store Vault contents, but signalling metadata may be visible to the relay. Availability and log retention are not guaranteed. You can replace it with your own Nostr-compatible relay.",
33332
33749
  "Learn more about P2P connections": "Learn more about P2P connections",
33333
33750
  "Learn more about signalling and TURN": "Learn more about signalling and TURN",
33334
- "TURN relays the encrypted WebRTC connection only when a direct path cannot be established. A TURN provider cannot read encrypted Vault contents, but it can observe connection metadata and traffic volume. Use a provider you trust.": "TURN relays the encrypted WebRTC connection only when a direct path cannot be established. A TURN provider cannot read encrypted Vault contents, but it can observe connection metadata and traffic volume. Use a provider you trust.",
33751
+ "WebRTC encrypts data between your devices, including when it passes through TURN. The TURN provider cannot read the transferred data. It can see network addresses and traffic volume.": "WebRTC encrypts data between your devices, including when it passes through TURN. The TURN provider cannot read the transferred data. It can see network addresses and traffic volume.",
33335
33752
  "Connection compatibility": "Connection compatibility",
33336
33753
  "P2P message size": "P2P message size",
33337
33754
  Standard: "Standard",
@@ -34352,8 +34769,8 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
34352
34769
  };
34353
34770
  //#endregion
34354
34771
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/coreEnvVars.js
34355
- var manifestVersion = "1.0.28";
34356
- var packageVersion = "1.0.28";
34772
+ var manifestVersion = "1.0.30";
34773
+ var packageVersion = "1.0.30";
34357
34774
  //#endregion
34358
34775
  //#region ../../../node_modules/octagonal-wheels/dist/iterable/map.js
34359
34776
  /**
@@ -34936,6 +35353,18 @@ async function performFullScan(host, log, errorManager, showingNoticeOrOptions =
34936
35353
  if (showingNotice) log("Initialize done!", 64, "syncAll");
34937
35354
  return scanResult;
34938
35355
  }
35356
+ function useOfflineScanner(host) {
35357
+ const log = createInstanceLogFunction("SF:OfflineScanner", host.services.API);
35358
+ const errorManager = new UnresolvedErrorManager(host.services.appLifecycle, host.services.context.events);
35359
+ const handleScanVault = async (showingNotice, ignoreSuspending = false, continueOnFileFailure = false) => {
35360
+ return await performFullScan(host, log, errorManager, {
35361
+ showingNotice,
35362
+ ignoreSuspending,
35363
+ continueOnFileFailure
35364
+ });
35365
+ };
35366
+ host.services.vault.scanVault.addHandler(handleScanVault);
35367
+ }
34939
35368
  //#endregion
34940
35369
  //#region ../../modules/main/ModuleLiveSyncMain.ts
34941
35370
  var ModuleLiveSyncMain = class extends AbstractModule {
@@ -34960,7 +35389,8 @@ var ModuleLiveSyncMain = class extends AbstractModule {
34960
35389
  return false;
34961
35390
  }
34962
35391
  }
34963
- const initialisationResult = await this.services.databaseEvents.initialiseDatabase(false, false, false, true);
35392
+ const { ignoreSuspending = false, continueOnFileFailure = true } = this.core.startupDatabaseOptions;
35393
+ const initialisationResult = await this.services.databaseEvents.initialiseDatabase(false, false, ignoreSuspending, continueOnFileFailure);
34964
35394
  if (initialisationResult === VaultScanResults.FAILED) {
34965
35395
  this._log($msg("Ui.Common.LocalDatabaseInitialisationFailed"), 64);
34966
35396
  return false;
@@ -37249,6 +37679,7 @@ var JournalSyncCore = class {
37249
37679
  env;
37250
37680
  store;
37251
37681
  requestedStop = false;
37682
+ syncParamsHandler;
37252
37683
  getInitialSyncParameters() {
37253
37684
  return Promise.resolve({
37254
37685
  ...DEFAULT_SYNC_PARAMETERS,
@@ -37292,7 +37723,6 @@ var JournalSyncCore = class {
37292
37723
  this.store = store;
37293
37724
  this.hash = this.getHash(settings);
37294
37725
  this.storage = storage;
37295
- clearHandlers();
37296
37726
  }
37297
37727
  async downloadJson(key) {
37298
37728
  try {
@@ -37339,7 +37769,7 @@ var JournalSyncCore = class {
37339
37769
  this.store = store;
37340
37770
  this.hash = this.getHash(settings);
37341
37771
  this.storage.applyNewConfig(settings);
37342
- clearHandlers();
37772
+ this.resetAllCaches();
37343
37773
  }
37344
37774
  updateInfo(info) {
37345
37775
  const old = this.env.services.replicator.replicationStatics.value;
@@ -37390,23 +37820,18 @@ var JournalSyncCore = class {
37390
37820
  return this._currentCheckPointInfo;
37391
37821
  }
37392
37822
  resetAllCaches() {
37393
- clearHandlers();
37823
+ this.syncParamsHandler = void 0;
37394
37824
  }
37395
37825
  async resetCheckpointInfo() {
37396
37826
  await this.updateCheckPointInfo((info) => ({ ...CheckPointInfoDefault }));
37397
- clearHandlers();
37398
37827
  }
37399
37828
  getJournalEpochFromSyncParams(params) {
37400
37829
  return `${params.protocolVersion}:${params.pbkdf2salt}`;
37401
37830
  }
37402
37831
  async ensureCheckpointCachesAreFresh() {
37403
- let journalEpoch = "";
37404
- try {
37405
- const params = await this.getSyncParameters();
37406
- journalEpoch = this.getJournalEpochFromSyncParams(params);
37407
- } catch {
37408
- return;
37409
- }
37832
+ const params = await this.getSyncParamsHandler().fetch(true);
37833
+ if (!params) throw new SyncParamsFetchError("Could not prepare Journal synchronisation parameters");
37834
+ const journalEpoch = this.getJournalEpochFromSyncParams(params);
37410
37835
  const current = await this.getCheckpointInfo();
37411
37836
  if (current.journalEpoch === journalEpoch) return;
37412
37837
  const lastSentFile = [...current.sentFiles].sort().pop();
@@ -37440,12 +37865,12 @@ var JournalSyncCore = class {
37440
37865
  receivedFiles: /* @__PURE__ */ new Set(),
37441
37866
  sentFiles: /* @__PURE__ */ new Set()
37442
37867
  }));
37443
- clearHandlers();
37444
37868
  }
37445
37869
  async isAvailable() {
37446
37870
  return await this.storage.isAvailable();
37447
37871
  }
37448
37872
  async resetBucket() {
37873
+ this.resetAllCaches();
37449
37874
  let files = [];
37450
37875
  try {
37451
37876
  do {
@@ -37453,7 +37878,6 @@ var JournalSyncCore = class {
37453
37878
  if (files.length == 0) break;
37454
37879
  if (!await this.storage.deleteFiles(files)) return false;
37455
37880
  } while (files.length != 0);
37456
- clearHandlers();
37457
37881
  } catch (ex) {
37458
37882
  Logger(`WARNING! Could not delete files.`, 64, "reset-bucket");
37459
37883
  Logger(ex, 16);
@@ -37473,11 +37897,14 @@ var JournalSyncCore = class {
37473
37897
  return this.getHash(this._settings);
37474
37898
  }
37475
37899
  async getReplicationPBKDF2Salt(refresh) {
37476
- return await createSyncParamsHanderForServer(this.getRemoteKey(), {
37900
+ return await this.getSyncParamsHandler().getPBKDF2Salt(refresh);
37901
+ }
37902
+ getSyncParamsHandler() {
37903
+ return this.syncParamsHandler ??= createSyncParamsHandler({
37477
37904
  put: (params) => this.putSyncParameters(params),
37478
37905
  get: () => this.getSyncParameters(),
37479
37906
  create: () => this.getInitialSyncParameters()
37480
- }).getPBKDF2Salt(refresh);
37907
+ });
37481
37908
  }
37482
37909
  isEncryptionPrevented(fileName) {
37483
37910
  if (fileName.endsWith("_obsidian_livesync_journal_sync_parameters.json")) return true;
@@ -37887,6 +38314,7 @@ var JournalSyncCore = class {
37887
38314
  /** Stop this Journal operation owner and release its storage transport. */
37888
38315
  dispose() {
37889
38316
  this.requestStop();
38317
+ this.resetAllCaches();
37890
38318
  this.storage.dispose?.();
37891
38319
  }
37892
38320
  };
@@ -56125,11 +56553,15 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
56125
56553
  async openReplication(setting, _, showResult, ignoreCleanLock = false, recordCompatibilityDecision) {
56126
56554
  return await this.runJournalTransfer(async (stopGeneration) => {
56127
56555
  const client = this.setupJournalSyncClient(setting);
56128
- stopGeneration = this.journalTransferStopGeneration;
56129
- if (!await this.checkReplicationConnectivity(false, ignoreCleanLock, showResult, setting, client, recordCompatibilityDecision)) return false;
56130
- if (stopGeneration !== this.journalTransferStopGeneration) return false;
56131
- this.hasEnteredReplication = true;
56132
- return await client.sync(showResult);
56556
+ try {
56557
+ stopGeneration = this.journalTransferStopGeneration;
56558
+ if (!await this.checkReplicationConnectivity(false, ignoreCleanLock, showResult, setting, client, recordCompatibilityDecision)) return false;
56559
+ if (stopGeneration !== this.journalTransferStopGeneration) return false;
56560
+ this.hasEnteredReplication = true;
56561
+ return await client.sync(showResult);
56562
+ } finally {
56563
+ client.resetAllCaches();
56564
+ }
56133
56565
  });
56134
56566
  }
56135
56567
  /**
@@ -56152,11 +56584,15 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
56152
56584
  async runDirectionalReplication(setting, showingNotice, transfer, recordCompatibilityDecision) {
56153
56585
  return await this.runJournalTransfer(async (stopGeneration) => {
56154
56586
  const client = this.setupJournalSyncClient(setting);
56155
- stopGeneration = this.journalTransferStopGeneration;
56156
- if (!await this.checkReplicationConnectivity(false, false, !!showingNotice, setting, client, recordCompatibilityDecision)) return false;
56157
- if (stopGeneration !== this.journalTransferStopGeneration) return false;
56158
- this.hasEnteredReplication = true;
56159
- return await transfer(client);
56587
+ try {
56588
+ stopGeneration = this.journalTransferStopGeneration;
56589
+ if (!await this.checkReplicationConnectivity(false, false, !!showingNotice, setting, client, recordCompatibilityDecision)) return false;
56590
+ if (stopGeneration !== this.journalTransferStopGeneration) return false;
56591
+ this.hasEnteredReplication = true;
56592
+ return await transfer(client);
56593
+ } finally {
56594
+ client.resetAllCaches();
56595
+ }
56160
56596
  });
56161
56597
  }
56162
56598
  /** Capture only the compatibility decision made by this exact borrowed client. */
@@ -56242,7 +56678,6 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
56242
56678
  this.closeReplication();
56243
56679
  try {
56244
56680
  if (!await this.client.resetBucket()) throw new Error("Could not reset remote bucket");
56245
- clearHandlers();
56246
56681
  Logger("Remote Bucket Cleared", 64);
56247
56682
  await this.tryCreateRemoteDatabase(setting);
56248
56683
  } catch (ex) {
@@ -56254,7 +56689,6 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
56254
56689
  async tryCreateRemoteDatabase(setting) {
56255
56690
  this.closeReplication();
56256
56691
  Logger("Remote Database Created or Connected", 64);
56257
- clearHandlers();
56258
56692
  if (!await this.ensurePBKDF2Salt(setting, true, false)) throw new Error("Could not ensure PBKDF2 salt (Security Seed)");
56259
56693
  return await Promise.resolve();
56260
56694
  }
@@ -56593,8 +57027,18 @@ function createSecuritySeedResourceFactory(createReplicator) {
56593
57027
  return (setting) => {
56594
57028
  const snapshot = snapshotRemoteSettings(setting);
56595
57029
  const replicator = createReplicator();
57030
+ let readPromise;
57031
+ const read = () => {
57032
+ if (readPromise) return readPromise;
57033
+ const pending = Promise.resolve().then(() => replicator.getReplicationPBKDF2Salt(snapshot, true));
57034
+ readPromise = pending;
57035
+ pending.catch(() => {
57036
+ if (readPromise === pending) readPromise = void 0;
57037
+ });
57038
+ return pending;
57039
+ };
56596
57040
  return Promise.resolve({
56597
- read: () => replicator.getReplicationPBKDF2Salt(snapshot, true),
57041
+ read,
56598
57042
  dispose: createReplicatorDisposer(replicator)
56599
57043
  });
56600
57044
  };
@@ -56816,7 +57260,7 @@ function createCentralReplicatorProviderDefinitions(host) {
56816
57260
  [REMOTE_MINIO]: {
56817
57261
  kind: REMOTE_MINIO,
56818
57262
  diagnosticName: "Object Storage",
56819
- readiness: CENTRAL_REMOTE_REPLICATION_READINESS,
57263
+ readiness: PROVIDER_OWNED_CENTRAL_REMOTE_REPLICATION_READINESS,
56820
57264
  isConfigured: (settings) => settings.remoteType === REMOTE_MINIO && !!settings.endpoint?.trim() && !!settings.bucket?.trim(),
56821
57265
  configurationIdentity: getObjectStorageReplicatorConfigurationIdentity,
56822
57266
  create: () => Promise.resolve(new LiveSyncJournalReplicator(host)),
@@ -58291,7 +58735,8 @@ var LiveSyncBaseCore = class {
58291
58735
  getAddOn(cls) {
58292
58736
  for (const addon of this.addOns) if (addon.constructor.name == cls) return addon;
58293
58737
  }
58294
- constructor(serviceHub, serviceModuleInitialiser, extraModuleInitialiser, addOnsInitialiser, featuresInitialiser) {
58738
+ constructor(serviceHub, serviceModuleInitialiser, extraModuleInitialiser, addOnsInitialiser, featuresInitialiser, startupDatabaseOptions = {}) {
58739
+ this.startupDatabaseOptions = startupDatabaseOptions;
58295
58740
  this.addOns = [];
58296
58741
  this._services = void 0;
58297
58742
  this.modules = [];
@@ -59223,14 +59668,6 @@ Total bytes fetched: ${sizeToHumanReadable(progress.totalBytes)}`, 64, "fetch-in
59223
59668
  };
59224
59669
  //#endregion
59225
59670
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/serviceModules/ServiceFileHandlerBase.js
59226
- async function isIncomingTextClearExtension(incomingContent, localContent) {
59227
- const incomingBlob = createBlob(incomingContent);
59228
- const localBlob = createBlob(localContent);
59229
- if (!isTextBlob$1(incomingBlob) || !isTextBlob$1(localBlob)) return false;
59230
- const incomingText = await incomingBlob.text();
59231
- const localText = await localBlob.text();
59232
- return incomingText.startsWith(localText) || incomingText.endsWith(localText);
59233
- }
59234
59671
  async function serializedByKeys(keys, callback) {
59235
59672
  const [key, ...remainingKeys] = keys;
59236
59673
  if (key === void 0) return await callback();
@@ -59252,6 +59689,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59252
59689
  setting;
59253
59690
  vault;
59254
59691
  fileReflectionProvenance;
59692
+ deferredConflictChecks = /* @__PURE__ */ new Map();
59255
59693
  constructor(services) {
59256
59694
  super(services);
59257
59695
  this.events = services.events;
@@ -59325,6 +59763,93 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59325
59763
  return matched;
59326
59764
  }
59327
59765
  }
59766
+ /**
59767
+ * Classify a storage read against its displayed database branch.
59768
+ *
59769
+ * A recorded revision identifies the branch and therefore takes precedence
59770
+ * over byte matches. Without a readable base, only current live leaves are
59771
+ * considered. Any match avoids a duplicate write, but only a unique match
59772
+ * identifies provenance; no match is `unknown`.
59773
+ * `preferredPath` selects the provenance key during a rename, and
59774
+ * `currentLoaded` supplies an already decoded candidate body when available.
59775
+ * Missing chunks do not clear provenance unless their metadata is also
59776
+ * missing or deleted.
59777
+ */
59778
+ async classifyStorageContent(file, currentEntry, preferredPath, recordedRevision, currentLoaded) {
59779
+ const path = preferredPath ?? file.path;
59780
+ if (recordedRevision) {
59781
+ const loadedContentIsDecoded = currentLoaded?._rev === recordedRevision;
59782
+ const base = loadedContentIsDecoded ? currentLoaded : await this.db.fetchEntry(file, recordedRevision, true, true, true);
59783
+ if (base && base._rev === recordedRevision && !("deleted" in base && base.deleted) && !("_deleted" in base && base._deleted)) return await isDocContentSame(loadedContentIsDecoded ? base.data : readContent(base), file.body) ? {
59784
+ kind: "unchanged",
59785
+ revision: recordedRevision
59786
+ } : {
59787
+ kind: "edited",
59788
+ revision: recordedRevision
59789
+ };
59790
+ if (!base) {
59791
+ const meta = await this.db.fetchEntryMeta(file, recordedRevision, true);
59792
+ if (!meta || meta.deleted || meta._deleted) await this.deleteProvenance(path);
59793
+ }
59794
+ }
59795
+ const matches = currentEntry ? await this.db.findLiveContentRevisions(file, file.body) : [];
59796
+ if (matches.length) return {
59797
+ kind: "matching-leaf",
59798
+ revision: matches.length === 1 ? matches[0] : void 0
59799
+ };
59800
+ return { kind: "unknown" };
59801
+ }
59802
+ /** Record provenance only when storage matches one unambiguous live leaf. */
59803
+ async rememberMatchingLeaf(path, revision, mtime) {
59804
+ if (revision) await this.setProvenance(path, revision, mtime);
59805
+ }
59806
+ /**
59807
+ * Read the raw provenance value used by an optimistic storage snapshot.
59808
+ * Unlike `getProvenance`, this does not validate or remove the referenced
59809
+ * database revision; an unreadable value is represented as `undefined`.
59810
+ */
59811
+ async readProvenanceSnapshot(path) {
59812
+ try {
59813
+ return (await this.fileReflectionProvenance?.get(path))?.revision;
59814
+ } catch {
59815
+ return;
59816
+ }
59817
+ }
59818
+ /**
59819
+ * Check that storage still has the same path, bytes, timestamp, and
59820
+ * provenance as a previously captured snapshot.
59821
+ */
59822
+ async currentStorageSnapshotMatches(file, revision) {
59823
+ const current = await this.storage.getStub(file.path);
59824
+ if (!current || isFolderInfo(current) || current.path !== file.path) return false;
59825
+ const readCurrent = await this.readFileFromStub(current);
59826
+ return readCurrent.stat.mtime === file.stat.mtime && await isDocContentSame(readCurrent.body, file.body) && await this.readProvenanceSnapshot(file.path) === revision;
59827
+ }
59828
+ /**
59829
+ * Publish provenance after a durable database write if storage is unchanged.
59830
+ * A failed revalidation leaves the database revision stored and asks the
59831
+ * caller to reread storage before proceeding.
59832
+ */
59833
+ async finaliseStoredRevision(file, observedProvenance, storedRevision) {
59834
+ if (await this.currentStorageSnapshotMatches(file, observedProvenance)) {
59835
+ await this.setProvenance(file.path, storedRevision, file.stat.mtime);
59836
+ return true;
59837
+ } else return false;
59838
+ }
59839
+ /**
59840
+ * Reread storage after a restored startup snapshot changed and retry a save.
59841
+ * The bounded counter prevents an unstable file from causing an endless
59842
+ * startup loop; the next event or scan can reconcile a final refusal.
59843
+ */
59844
+ async retryCurrentStorage(path, preferredBasePath, snapshotRetry) {
59845
+ if (snapshotRetry >= 2) {
59846
+ this._log(`Storage kept changing while saving ${path}; a fresh event is required`, 64);
59847
+ return false;
59848
+ }
59849
+ const fresh = await this.storage.getStub(path);
59850
+ if (!fresh || isFolderInfo(fresh)) return false;
59851
+ return await this.storeFileToDBFromRevision(fresh, false, false, preferredBasePath, true, snapshotRetry + 1);
59852
+ }
59328
59853
  getPath(entry) {
59329
59854
  return this.path.getPath(entry);
59330
59855
  }
@@ -59342,9 +59867,17 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59342
59867
  return typeof info === "string" ? await this.storage.getFileStub(info) : info;
59343
59868
  }
59344
59869
  async storeFileToDB(info, force = false, onlyChunks = false) {
59345
- return await this.storeFileToDBFromRevision(info, force, onlyChunks);
59870
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.storeFileToDBFromRevision(info, force, onlyChunks));
59346
59871
  }
59347
59872
  async storeFileToDBWithBaseRevision(info, baseRevision, createIfDifferent = true) {
59873
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.storeFileToDBWithBaseRevisionCore(info, baseRevision, createIfDifferent));
59874
+ }
59875
+ /**
59876
+ * Store current storage content below an exact live revision. A differing
59877
+ * body is rejected when `createIfDifferent` is false; callers hold the
59878
+ * document lock for this core operation.
59879
+ */
59880
+ async storeFileToDBWithBaseRevisionCore(info, baseRevision, createIfDifferent) {
59348
59881
  const file = await this.infoToStub(info);
59349
59882
  if (file == null) {
59350
59883
  this._log(`File ${tryGetFilePath(info)} is not exist on the storage`, 16);
@@ -59369,7 +59902,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59369
59902
  const loadedBase = await this.db.fetchEntry(file, baseRevision, true, true);
59370
59903
  if (loadedBase && await isDocContentSame(getDocDataAsArray(loadedBase.data), readFile.body)) {
59371
59904
  await this.setProvenance(file.path, baseRevision, readFile.stat.mtime);
59372
- await this.conflict.queueCheckFor(file.path);
59905
+ await this.queueConflictCheckFor(file.path);
59373
59906
  return true;
59374
59907
  }
59375
59908
  }
@@ -59380,10 +59913,16 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59380
59913
  const storedRevision = await this.db.storeWithBaseRevision(readFile, baseRevision, true);
59381
59914
  if (storedRevision === false) return false;
59382
59915
  await this.setProvenance(file.path, storedRevision, readFile.stat.mtime);
59383
- await this.conflict.queueCheckFor(file.path);
59916
+ await this.queueConflictCheckFor(file.path);
59384
59917
  return true;
59385
59918
  }
59386
- async storeFileToDBFromRevision(info, force = false, onlyChunks = false, preferredBasePath) {
59919
+ /**
59920
+ * Save one storage snapshot while the caller holds its document lock.
59921
+ * Ordinary saves read once inside the lock and leave retries disabled.
59922
+ * Restored startup events retain bounded rereads because file watching has
59923
+ * not yet started and cannot supply a new event for a concurrent edit.
59924
+ */
59925
+ async storeFileToDBFromRevision(info, force = false, onlyChunks = false, preferredBasePath, retryIfStorageChanges = false, snapshotRetry = 0) {
59387
59926
  const file = await this.infoToStub(info);
59388
59927
  if (file == null) {
59389
59928
  this._log(`File ${tryGetFilePath(info)} is not exist on the storage`, 16);
@@ -59397,9 +59936,39 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59397
59936
  const readFile2 = await this.readFileFromStub(file);
59398
59937
  return await this.db.createChunks(readFile2, force, true);
59399
59938
  }
59939
+ const observedProvenance = await this.readProvenanceSnapshot(preferredBasePath ?? file.path);
59400
59940
  const readFile = await this.readFileFromStub(file);
59401
- const entry = await this.db.fetchEntry(file, void 0, true, true);
59402
- if ((await this.db.getConflictedRevs(file)).length > 0) {
59941
+ const entry = await this.db.fetchEntry(file, void 0, true, true, true);
59942
+ const currentEntry = entry || await this.db.fetchEntryMeta(file, void 0, true);
59943
+ const isConflicted = (await this.db.getConflictedRevs(file)).length > 0;
59944
+ if (!force && currentEntry && !currentEntry.deleted && !currentEntry._deleted) {
59945
+ const classification = await this.classifyStorageContent(readFile, currentEntry, preferredBasePath, observedProvenance, entry ? {
59946
+ _rev: entry._rev,
59947
+ data: readContent(entry)
59948
+ } : void 0);
59949
+ if (retryIfStorageChanges && !await this.currentStorageSnapshotMatches(readFile, observedProvenance)) return await this.retryCurrentStorage(file.path, preferredBasePath, snapshotRetry);
59950
+ if (classification.kind === "unchanged") {
59951
+ if (isConflicted) await this.queueConflictCheckFor(file.path);
59952
+ else if (classification.revision !== currentEntry._rev) {
59953
+ if (!entry) return false;
59954
+ return await this.dbToStorageCore(file.path, file);
59955
+ } else this.path.markChangesAreSame(readFile, readFile.stat.mtime, currentEntry.mtime);
59956
+ return true;
59957
+ }
59958
+ if (classification.kind === "matching-leaf") {
59959
+ await this.rememberMatchingLeaf(file.path, classification.revision, readFile.stat.mtime);
59960
+ if (isConflicted) await this.queueConflictCheckFor(file.path);
59961
+ return true;
59962
+ }
59963
+ const storedRevision2 = classification.kind === "edited" ? await this.db.storeWithBaseRevision(readFile, classification.revision, true) : await this.db.storeIndependentRevision(readFile, true);
59964
+ if (storedRevision2 === false) return false;
59965
+ if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
59966
+ if (retryIfStorageChanges && !await this.finaliseStoredRevision(readFile, observedProvenance, storedRevision2)) return await this.retryCurrentStorage(file.path, preferredBasePath, snapshotRetry);
59967
+ if (!retryIfStorageChanges) await this.setProvenance(file.path, storedRevision2, readFile.stat.mtime);
59968
+ if (isConflicted || classification.kind === "unknown") await this.queueConflictCheckFor(file.path);
59969
+ return true;
59970
+ }
59971
+ if (isConflicted) {
59403
59972
  const baseRevision = await this.getProvenBaseRevision(readFile, preferredBasePath);
59404
59973
  if (baseRevision) {
59405
59974
  const baseEntry = await this.db.fetchEntry(file, baseRevision, true, true);
@@ -59412,28 +59981,28 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59412
59981
  if (storedRevision3 === false) return false;
59413
59982
  if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
59414
59983
  await this.setProvenance(file.path, storedRevision3, readFile.stat.mtime);
59415
- await this.conflict.queueCheckFor(file.path);
59984
+ await this.queueConflictCheckFor(file.path);
59416
59985
  return true;
59417
59986
  }
59418
- const currentEntry = entry || await this.db.fetchEntryMeta(file, void 0, true);
59419
- const currentRevision = currentEntry && currentEntry._rev;
59987
+ const currentEntry2 = entry || await this.db.fetchEntryMeta(file, void 0, true);
59988
+ const currentRevision = currentEntry2 && currentEntry2._rev;
59420
59989
  if (!currentRevision) {
59421
59990
  this._log(`Could not preserve the unknown conflict branch for ${file.path}; no current revision is available`, 64);
59422
- await this.conflict.queueCheckFor(file.path);
59991
+ await this.queueConflictCheckFor(file.path);
59423
59992
  return false;
59424
59993
  }
59425
59994
  const storedRevision2 = await this.db.storeAsConflictedRevisionWithResult(readFile, currentRevision, true);
59426
59995
  if (storedRevision2 === false) {
59427
59996
  this._log(`Could not preserve the unknown conflict branch for ${file.path}`, 64);
59428
- await this.conflict.queueCheckFor(file.path);
59997
+ await this.queueConflictCheckFor(file.path);
59429
59998
  return false;
59430
59999
  }
59431
60000
  if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
59432
60001
  await this.setProvenance(file.path, storedRevision2, readFile.stat.mtime);
59433
- await this.conflict.queueCheckFor(file.path);
60002
+ await this.queueConflictCheckFor(file.path);
59434
60003
  return true;
59435
60004
  }
59436
- if (!entry || entry.deleted || entry._deleted) {
60005
+ if (!currentEntry || currentEntry.deleted || currentEntry._deleted) {
59437
60006
  const storedRevision2 = await this.db.storeWithBaseRevision(readFile, entry && entry._rev, true);
59438
60007
  if (storedRevision2 === false) return false;
59439
60008
  if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
@@ -59441,7 +60010,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59441
60010
  return true;
59442
60011
  }
59443
60012
  let shouldApplied = false;
59444
- if (!force && !onlyChunks) {
60013
+ if (!force && !onlyChunks && entry) {
59445
60014
  if (this.path.compareFileFreshness(file, entry) !== EVEN) shouldApplied = true;
59446
60015
  if (!shouldApplied) if (await isDocContentSame(getDocDataAsArray(entry.data), readFile.body)) this.path.markChangesAreSame(readFile, readFile.stat.mtime, entry.mtime);
59447
60016
  else shouldApplied = true;
@@ -59451,13 +60020,20 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59451
60020
  return true;
59452
60021
  }
59453
60022
  }
59454
- const storedRevision = await this.db.storeWithBaseRevision(readFile, entry._rev, true);
60023
+ const storedRevision = await this.db.storeWithBaseRevision(readFile, currentEntry._rev, true);
59455
60024
  if (storedRevision === false) return false;
59456
60025
  if (preferredBasePath && preferredBasePath !== file.path) await this.deleteProvenance(preferredBasePath);
59457
60026
  await this.setProvenance(file.path, storedRevision, readFile.stat.mtime);
59458
60027
  return true;
59459
60028
  }
59460
60029
  async deleteFileFromDB(info) {
60030
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.deleteFileFromDBCore(info));
60031
+ }
60032
+ /**
60033
+ * Record a storage deletion under the caller's document lock, preserving
60034
+ * the displayed conflict branch when its provenance is known.
60035
+ */
60036
+ async deleteFileFromDBCore(info) {
59461
60037
  const file = await this.infoToStub(info);
59462
60038
  const path = typeof info === "string" ? info : tryGetFilePath(info);
59463
60039
  if (file == null) {
@@ -59474,12 +60050,12 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59474
60050
  const provenance = await this.getProvenance(path);
59475
60051
  if (!provenance) {
59476
60052
  this._log(`The deleted storage file ${path} has conflicts, but its displayed revision is unknown; preserving every database branch`, 64);
59477
- await this.conflict.queueCheckFor(path);
60053
+ await this.queueConflictCheckFor(path);
59478
60054
  return true;
59479
60055
  }
59480
60056
  if (await this.db.storeDeletionWithBaseRevision(path, provenance.revision) === false) return false;
59481
60057
  await this.deleteProvenance(path);
59482
- await this.conflict.queueCheckFor(path);
60058
+ await this.queueConflictCheckFor(path);
59483
60059
  return true;
59484
60060
  }
59485
60061
  this._log(`File ${path} is missing on storage; deleting from the database by path`, 32);
@@ -59504,12 +60080,12 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59504
60080
  } catch {}
59505
60081
  if (!baseRevision) {
59506
60082
  this._log(`The deleted storage file ${file.path} has conflicts, but its displayed revision is unknown; preserving every database branch`, 64);
59507
- await this.conflict.queueCheckFor(file.path);
60083
+ await this.queueConflictCheckFor(file.path);
59508
60084
  return true;
59509
60085
  }
59510
60086
  if (await this.db.storeDeletionWithBaseRevision(file.path, baseRevision) === false) return false;
59511
60087
  await this.deleteProvenance(file.path);
59512
- await this.conflict.queueCheckFor(file.path);
60088
+ await this.queueConflictCheckFor(file.path);
59513
60089
  return true;
59514
60090
  }
59515
60091
  const deleted = await this.db.delete(file);
@@ -59517,11 +60093,20 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59517
60093
  return deleted;
59518
60094
  }
59519
60095
  async renameFileInDB(info, oldPath) {
60096
+ const newPath = getStoragePathFromUXFileInfo(info);
60097
+ return await this.serializedByFileEventPaths([oldPath, newPath], () => this.renameFileInDBCore(info, oldPath));
60098
+ }
60099
+ /**
60100
+ * Record a rename under the caller's source and target locks. Case-only
60101
+ * renames retain the source provenance while other renames handle the
60102
+ * source conflict before deleting its old path.
60103
+ */
60104
+ async renameFileInDBCore(info, oldPath, retryIfStorageChanges = false) {
59520
60105
  const newPath = getStoragePathFromUXFileInfo(info);
59521
60106
  const [oldDocumentId, newDocumentId] = await Promise.all([this.path.path2id(oldPath), this.path.path2id(newPath)]);
59522
60107
  if (oldDocumentId === newDocumentId) {
59523
60108
  this._log(`Updating the stored path for case-only rename: ${oldPath} -> ${newPath}`, 16);
59524
- return await this.storeFileToDBFromRevision(info, true, false, oldPath);
60109
+ return await this.storeFileToDBFromRevision(info, true, false, oldPath, retryIfStorageChanges);
59525
60110
  }
59526
60111
  const oldEntry = await this.db.fetchEntryMeta(oldPath, void 0, true);
59527
60112
  const newEntry = await this.db.fetchEntryMeta(newPath, void 0, true);
@@ -59529,7 +60114,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59529
60114
  this._log(`Refusing to overwrite the existing database entry while renaming ${oldPath} to ${newPath}`, 64);
59530
60115
  return false;
59531
60116
  }
59532
- if (!await this.storeFileToDB(info, true)) {
60117
+ if (!await this.storeFileToDBFromRevision(info, true, false, void 0, retryIfStorageChanges)) {
59533
60118
  this._log(`Failed to store rename target; preserving source in the database: ${oldPath}`, 64);
59534
60119
  return false;
59535
60120
  }
@@ -59546,12 +60131,12 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59546
60131
  }
59547
60132
  if (!baseRevision) {
59548
60133
  this._log(`Renamed ${oldPath} to ${newPath}, but preserved every conflicted source branch because the displayed source revision is unknown`, 64);
59549
- await this.conflict.queueCheckFor(oldPath);
60134
+ await this.queueConflictCheckFor(oldPath);
59550
60135
  return true;
59551
60136
  }
59552
60137
  if (await this.db.storeDeletionWithBaseRevision(oldPath, baseRevision) === false) return false;
59553
60138
  await this.deleteProvenance(oldPath);
59554
- await this.conflict.queueCheckFor(oldPath);
60139
+ await this.queueConflictCheckFor(oldPath);
59555
60140
  return true;
59556
60141
  }
59557
60142
  const deleted = await this.db.delete(oldPath);
@@ -59559,6 +60144,10 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59559
60144
  return deleted;
59560
60145
  }
59561
60146
  async deleteRevisionFromDB(info, rev) {
60147
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.deleteRevisionFromDBCore(info, rev));
60148
+ }
60149
+ /** Delete one selected revision and clear matching provenance under the caller's document lock. */
60150
+ async deleteRevisionFromDBCore(info, rev) {
59562
60151
  const path = getStoragePathFromUXFileInfo(info);
59563
60152
  const provenance = await this.getProvenance(path);
59564
60153
  const deleted = await this.db.delete(info, rev);
@@ -59566,6 +60155,13 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59566
60155
  return deleted;
59567
60156
  }
59568
60157
  async resolveConflictedByDeletingRevision(info, rev) {
60158
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.resolveConflictedByDeletingRevisionCore(info, rev));
60159
+ }
60160
+ /**
60161
+ * Apply the legacy resolve-by-delete sequence while holding one document
60162
+ * lock; metadata is captured before the selected revision is removed.
60163
+ */
60164
+ async resolveConflictedByDeletingRevisionCore(info, rev) {
59569
60165
  const path = getStoragePathFromUXFileInfo(info);
59570
60166
  const file = await this.infoToStub(info);
59571
60167
  const docEntry = await this.db.fetchEntryMeta(file ?? info, rev, true);
@@ -59573,7 +60169,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59573
60169
  this._log(`Failed to read the conflicted revision ${rev} of ${path}`, 16);
59574
60170
  return false;
59575
60171
  }
59576
- if (!await this.deleteRevisionFromDB(info, rev)) {
60172
+ if (!await this.deleteRevisionFromDBCore(info, rev)) {
59577
60173
  this._log(`Failed to delete the conflicted revision ${rev} of ${path}`, 16);
59578
60174
  return false;
59579
60175
  }
@@ -59588,6 +60184,13 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59588
60184
  this._log(`Cannot select database revision ${rev} without a file path`, 16);
59589
60185
  return false;
59590
60186
  }
60187
+ return await this.serializedByFileEventPaths([getStoragePathFromUXFileInfo(info)], () => this.dbToStorageWithSpecificRevCore(info, rev, force));
60188
+ }
60189
+ /**
60190
+ * Reflect a selected live revision under the caller's document lock.
60191
+ * The public wrapper performs the same lock acquisition before entering here.
60192
+ */
60193
+ async dbToStorageWithSpecificRevCore(info, rev, force) {
59591
60194
  const file = await this.infoToStub(info);
59592
60195
  const databaseTarget = file ?? info;
59593
60196
  const [docEntry, currentEntry, conflictedRevisions] = await Promise.all([
@@ -59606,6 +60209,11 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59606
60209
  return await this.applyDatabaseEntryToStorage(docEntry, file, force, true);
59607
60210
  }
59608
60211
  async dbToStorage(entryInfo, info, force) {
60212
+ const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : this.getPath(entryInfo);
60213
+ return await this.serializedByFileEventPaths([pathFromEntryInfo], () => this.dbToStorageCore(entryInfo, info, force));
60214
+ }
60215
+ /** Fetch the current metadata and reflect it while the caller holds its lock. */
60216
+ async dbToStorageCore(entryInfo, info, force) {
59609
60217
  const file = await this.infoToStub(info);
59610
60218
  const pathFromEntryInfo = typeof entryInfo === "string" ? entryInfo : this.getPath(entryInfo);
59611
60219
  const docEntry = await this.db.fetchEntryMeta(pathFromEntryInfo, void 0, true);
@@ -59615,12 +60223,18 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59615
60223
  }
59616
60224
  return await this.applyDatabaseEntryToStorage(docEntry, file, force);
59617
60225
  }
59618
- async applyDatabaseEntryToStorage(docEntry, file, force, allowExistingConflicts = false) {
60226
+ /**
60227
+ * Reflect one database revision while protecting concurrent storage edits.
60228
+ * Overwrite and deletion paths preserve changed bytes first, then revalidate
60229
+ * their snapshot and the current database revision immediately before the
60230
+ * destructive operation.
60231
+ */
60232
+ async applyDatabaseEntryToStorage(docEntry, file, force, allowExistingConflicts = false, incomingRetry = 0) {
59619
60233
  const mode = file == null ? "create" : "modify";
59620
60234
  const path = this.getPath(docEntry);
59621
60235
  const settings = this.setting.currentSettings();
59622
60236
  if ((await this.db.getConflictedRevs(path)).length > 0 && !allowExistingConflicts) if (settings.writeDocumentsIfConflicted) {} else {
59623
- await this.conflict.queueCheckForIfOpen(path);
60237
+ await this.queueConflictCheckFor(path, true);
59624
60238
  return true;
59625
60239
  }
59626
60240
  let existDoc = await this.storage.getStub(path);
@@ -59635,7 +60249,28 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59635
60249
  return true;
59636
60250
  }
59637
60251
  if (!existOnDB && existDoc) {
59638
- if (!force && !settings.writeDocumentsIfConflicted && await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry)) return true;
60252
+ let safeDeletionSnapshot;
60253
+ if (!force && !settings.writeDocumentsIfConflicted) {
60254
+ let protection = await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry);
60255
+ if (protection.preserved) return true;
60256
+ if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) {
60257
+ protection = await this.recheckIncomingStorage(path, docEntry, void 0, allowExistingConflicts);
60258
+ if (protection.preserved) return true;
60259
+ if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) return false;
60260
+ }
60261
+ safeDeletionSnapshot = protection.snapshot;
60262
+ }
60263
+ let latest2 = await this.reconcileAdvancedIncomingRevision(docEntry, path, force, allowExistingConflicts, incomingRetry);
60264
+ if (latest2 !== void 0) return latest2;
60265
+ if (safeDeletionSnapshot && !await this.currentStorageSnapshotMatches(safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) {
60266
+ const protection = await this.recheckIncomingStorage(path, docEntry, void 0, allowExistingConflicts);
60267
+ if (protection.preserved) return true;
60268
+ if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) return false;
60269
+ safeDeletionSnapshot = protection.snapshot;
60270
+ latest2 = await this.reconcileAdvancedIncomingRevision(docEntry, path, force, allowExistingConflicts, incomingRetry);
60271
+ if (latest2 !== void 0) return latest2;
60272
+ if (!await this.currentStorageSnapshotMatches(safeDeletionSnapshot.file, safeDeletionSnapshot.revision)) return false;
60273
+ }
59639
60274
  await this.storage.deleteVaultItem(path);
59640
60275
  await this.deleteProvenance(path);
59641
60276
  return true;
@@ -59677,6 +60312,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59677
60312
  return true;
59678
60313
  }
59679
60314
  }
60315
+ let safeSnapshot;
59680
60316
  if (existDoc && !force) {
59681
60317
  let shouldApplied = false;
59682
60318
  if (this.path.compareFileFreshness(existDoc, docEntry) !== EVEN) shouldApplied = true;
@@ -59689,9 +60325,27 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59689
60325
  this._log(`File ${docRead.path} is not changed`, 16);
59690
60326
  return true;
59691
60327
  }
59692
- if (!force && !settings.writeDocumentsIfConflicted && await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry, docData)) return true;
60328
+ if (!force && !settings.writeDocumentsIfConflicted) {
60329
+ let protection = await this.preserveUnsyncedStorageAsConflict(path, existDoc, docEntry, docData);
60330
+ if (protection.preserved) return true;
60331
+ if (!protection.snapshot) {
60332
+ protection = await this.recheckIncomingStorage(path, docEntry, docData, allowExistingConflicts);
60333
+ if (protection.preserved) return true;
60334
+ if (!protection.snapshot) return false;
60335
+ }
60336
+ safeSnapshot = protection.snapshot;
60337
+ }
59693
60338
  } else this._log(`File ${docRead.path} ${existDoc ? "(new) " : ""} ${force ? " (forced)" : ""}`, 16);
59694
60339
  await this.storage.ensureDir(path);
60340
+ if (safeSnapshot && !await this.currentStorageSnapshotMatches(safeSnapshot.file, safeSnapshot.revision)) {
60341
+ const protection = await this.recheckIncomingStorage(path, docEntry, docData, allowExistingConflicts);
60342
+ if (protection.preserved) return true;
60343
+ if (!protection.snapshot || !await this.currentStorageSnapshotMatches(protection.snapshot.file, protection.snapshot.revision)) return false;
60344
+ safeSnapshot = protection.snapshot;
60345
+ }
60346
+ const latest = await this.reconcileAdvancedIncomingRevision(docEntry, path, force, allowExistingConflicts, incomingRetry);
60347
+ if (latest !== void 0) return latest;
60348
+ if (safeSnapshot && !await this.currentStorageSnapshotMatches(safeSnapshot.file, safeSnapshot.revision)) return false;
59695
60349
  const ret = await this.storage.writeFileAuto(path, docData, {
59696
60350
  ctime: docRead.ctime,
59697
60351
  mtime: docRead.mtime
@@ -59700,32 +60354,97 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59700
60354
  this.storage.triggerFileEvent(mode, path);
59701
60355
  if (ret && this.fileReflectionProvenance) {
59702
60356
  const storedStat = await this.storage.stat(path);
60357
+ if (safeSnapshot && await this.readProvenanceSnapshot(path) !== safeSnapshot.revision) return ret;
59703
60358
  await this.setProvenance(path, docEntry._rev, storedStat?.mtime);
59704
60359
  }
59705
60360
  return ret;
59706
60361
  }
60362
+ /**
60363
+ * Preserve storage bytes before an incoming reflection can replace them.
60364
+ *
60365
+ * The initial read and provenance form one candidate snapshot. Classification
60366
+ * gives a recorded branch priority, deduplicates matching live leaves, or
60367
+ * creates an independent root for unknown origin. Optional `incomingContent` avoids
60368
+ * re-reading an already loaded incoming body. Storage is revalidated before
60369
+ * and after the database write; `preserved: true` stops the incoming write,
60370
+ * while a returned `snapshot` lets the caller continue only after revalidation.
60371
+ */
59707
60372
  async preserveUnsyncedStorageAsConflict(path, existDoc, incomingEntry, incomingContent) {
60373
+ const observedProvenance = await this.readProvenanceSnapshot(path);
59708
60374
  const readFile = await this.readFileFromStub(existDoc);
59709
- if (incomingContent && await isDocContentSame(incomingContent, readFile.body)) return false;
59710
- if (incomingContent && await isIncomingTextClearExtension(incomingContent, readFile.body)) return false;
59711
- if (!incomingEntry._rev) return false;
59712
- if (await this.db.hasContentInRevisionHistory(path, readFile.body, incomingEntry._rev)) return false;
59713
- const storedRevision = await this.db.storeAsConflictedRevisionWithResult(readFile, incomingEntry._rev, true);
60375
+ const snapshot = {
60376
+ file: readFile,
60377
+ revision: observedProvenance
60378
+ };
60379
+ if (incomingContent && await isDocContentSame(incomingContent, readFile.body)) return await this.currentStorageSnapshotMatches(readFile, observedProvenance) ? {
60380
+ preserved: false,
60381
+ snapshot
60382
+ } : { preserved: false };
60383
+ if (!incomingEntry._rev) return { preserved: false };
60384
+ const classification = await this.classifyStorageContent(readFile, incomingEntry, void 0, observedProvenance, incomingContent ? {
60385
+ _rev: incomingEntry._rev,
60386
+ data: incomingContent
60387
+ } : void 0);
60388
+ if (!await this.currentStorageSnapshotMatches(readFile, observedProvenance)) return { preserved: false };
60389
+ if (classification.kind === "unchanged") return {
60390
+ preserved: false,
60391
+ snapshot
60392
+ };
60393
+ if (classification.kind === "matching-leaf") {
60394
+ await this.rememberMatchingLeaf(path, classification.revision, readFile.stat.mtime);
60395
+ await this.queueConflictCheckFor(path);
60396
+ return { preserved: true };
60397
+ }
60398
+ const storedRevision = classification.kind === "edited" ? await this.db.storeWithBaseRevision(readFile, classification.revision, true) : await this.db.storeIndependentRevision(readFile, true);
59714
60399
  if (storedRevision === false) {
59715
60400
  this._log(`Prevented overwriting unsynchronised local changes for ${path}`, 64);
59716
- return true;
60401
+ return { preserved: true };
59717
60402
  }
59718
- await this.setProvenance(path, storedRevision, readFile.stat.mtime);
60403
+ if (!await this.finaliseStoredRevision(readFile, observedProvenance, storedRevision)) return { preserved: false };
59719
60404
  this._log(`Preserved unsynchronised local changes as a conflict for ${path}`, 64);
59720
- await this.conflict.queueCheckFor(path);
59721
- return true;
60405
+ await this.queueConflictCheckFor(path);
60406
+ return { preserved: true };
60407
+ }
60408
+ /**
60409
+ * Repeat overwrite protection from a fresh storage read after a snapshot
60410
+ * becomes stale. Existing conflicts may defer reflection and request an
60411
+ * open-only check while leaving the current storage untouched.
60412
+ */
60413
+ async recheckIncomingStorage(path, incomingEntry, incomingContent, allowExistingConflicts) {
60414
+ const current = await this.storage.getStub(path);
60415
+ if (!current || isFolderInfo(current)) return { preserved: false };
60416
+ const protection = await this.preserveUnsyncedStorageAsConflict(path, current, incomingEntry, incomingContent);
60417
+ if (protection.preserved || !protection.snapshot) return protection;
60418
+ if (!allowExistingConflicts && !this.setting.currentSettings().writeDocumentsIfConflicted && (await this.db.getConflictedRevs(path)).length > 0) {
60419
+ await this.queueConflictCheckFor(path, true);
60420
+ return { preserved: true };
60421
+ }
60422
+ return protection;
60423
+ }
60424
+ /**
60425
+ * Re-read database metadata immediately before reflecting an incoming entry.
60426
+ * If the current revision advanced, recurse with fresh storage; force and
60427
+ * explicitly allowed conflict writes retain the caller's selected entry.
60428
+ * `incomingRetry` bounds repeated database churn.
60429
+ */
60430
+ async reconcileAdvancedIncomingRevision(incomingEntry, path, force, allowExistingConflicts, incomingRetry) {
60431
+ if (force || allowExistingConflicts) return void 0;
60432
+ const current = await this.db.fetchEntryMeta(path, void 0, true);
60433
+ if (!current) return false;
60434
+ if (current._rev === incomingEntry._rev) return void 0;
60435
+ if (incomingRetry >= 2) {
60436
+ this._log(`Database kept changing while reflecting ${path}`, 64);
60437
+ return false;
60438
+ }
60439
+ const storage = await this.storage.getStub(path);
60440
+ if (isFolderInfo(storage)) return false;
60441
+ return await this.applyDatabaseEntryToStorage(current, storage, force, allowExistingConflicts, incomingRetry + 1);
59722
60442
  }
59723
60443
  async _anyHandlerProcessesFileEvent(item) {
59724
60444
  if (item.restoredFromPreviousRuntime) return await this._processRestoredFileEvent(item);
59725
60445
  const eventItem = item.args;
59726
60446
  const type = item.type;
59727
60447
  const path = eventItem.file.path;
59728
- if (!await this.isCurrentPathSelected(path)) return false;
59729
60448
  if (type === "RENAME" && !eventItem.oldPath) {
59730
60449
  this._log(`Rename event for ${path} has no source path`, 16);
59731
60450
  return false;
@@ -59733,13 +60452,14 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59733
60452
  const relatedPath = type === "RENAME" ? eventItem.oldPath : type === "DELETE" ? eventItem.renameTarget : void 0;
59734
60453
  const eventPaths = relatedPath === void 0 ? [path] : [path, relatedPath];
59735
60454
  return await this.serializedByFileEventPaths(eventPaths, async () => {
60455
+ if (!await this.isCurrentPathSelected(path)) return false;
59736
60456
  switch (type) {
59737
60457
  case "CREATE":
59738
- case "CHANGED": return await this.storeFileToDB(item.args.file);
60458
+ case "CHANGED": return await this.storeFileToDBFromRevision(item.args.file);
59739
60459
  case "DELETE":
59740
60460
  if (!await this.canRecordStorageDeletion(item)) return true;
59741
- return await this.deleteFileFromDB(item.args.file);
59742
- case "RENAME": return await this.renameFileInDB(item.args.file, item.args.oldPath);
60461
+ return await this.deleteFileFromDBCore(item.args.file);
60462
+ case "RENAME": return await this.renameFileInDBCore(item.args.file, item.args.oldPath);
59743
60463
  case "INTERNAL": return false;
59744
60464
  default:
59745
60465
  this._log(`Unsupported event type: ${type}`, 16);
@@ -59780,9 +60500,62 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59780
60500
  return false;
59781
60501
  }
59782
60502
  }
60503
+ /**
60504
+ * Serialise work by every document ID represented by the supplied paths.
60505
+ * IDs are deduplicated and sorted so aliases take one lock and cross-document renames have one order.
60506
+ * The callback runs under those locks and must use core methods; conflict
60507
+ * hooks requested inside it are deferred until all locks have been released.
60508
+ */
59783
60509
  async serializedByFileEventPaths(eventPaths, callback) {
59784
60510
  const documentIds = await Promise.all(eventPaths.map((eventPath) => this.path.path2id(eventPath)));
59785
- return await serializedByKeys([...new Set(documentIds)].sort().map((documentId) => `processFileEvent-${documentId}`), () => callback(documentIds.length === 2 && documentIds[0] === documentIds[1]));
60511
+ const uniqueIds = [...new Set(documentIds)].sort();
60512
+ const lockKeys = uniqueIds.map((documentId) => `processFileEvent-${documentId}`);
60513
+ const pending = [];
60514
+ let result;
60515
+ let failed = false;
60516
+ let failure;
60517
+ try {
60518
+ result = await serializedByKeys(lockKeys, async () => {
60519
+ for (const id of uniqueIds) this.deferredConflictChecks.set(id, pending);
60520
+ try {
60521
+ return await callback(documentIds.length === 2 && documentIds[0] === documentIds[1]);
60522
+ } finally {
60523
+ for (const id of uniqueIds) this.deferredConflictChecks.delete(id);
60524
+ }
60525
+ });
60526
+ } catch (ex) {
60527
+ failed = true;
60528
+ failure = ex;
60529
+ }
60530
+ for (const check of pending) try {
60531
+ if (check.ifOpen) await this.conflict.queueCheckForIfOpen(check.path);
60532
+ else await this.conflict.queueCheckFor(check.path);
60533
+ } catch (ex) {
60534
+ if (!failed) {
60535
+ failed = true;
60536
+ failure = ex;
60537
+ }
60538
+ break;
60539
+ }
60540
+ if (failed) throw failure;
60541
+ return result;
60542
+ }
60543
+ /**
60544
+ * Queue a conflict hook while its document lock is held, or run it directly
60545
+ * when no matching lock is active. Preserve `ifOpen` across deferral.
60546
+ */
60547
+ async queueConflictCheckFor(path, ifOpen = false) {
60548
+ const documentId = await this.path.path2id(path);
60549
+ const pending = this.deferredConflictChecks.get(documentId);
60550
+ if (pending) {
60551
+ pending.push({
60552
+ path,
60553
+ ifOpen
60554
+ });
60555
+ return;
60556
+ }
60557
+ if (ifOpen) await this.conflict.queueCheckForIfOpen(path);
60558
+ else await this.conflict.queueCheckFor(path);
59786
60559
  }
59787
60560
  /**
59788
60561
  * Revalidate a persisted storage operation against the current storage state.
@@ -59790,7 +60563,9 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59790
60563
  * Snapshot entries preserve operation intent and ordering only. Their file
59791
60564
  * stub, timestamps, and existence assumptions can be stale after a restart.
59792
60565
  * Current inclusion is therefore read from storage, while destructive work
59793
- * is allowed only after current absence has been observed.
60566
+ * is allowed only after current absence has been observed. Store and rename
60567
+ * actions use the fresh reread with bounded retry because no later watcher
60568
+ * event is guaranteed after startup reconciliation.
59794
60569
  */
59795
60570
  async _processRestoredFileEvent(item) {
59796
60571
  const eventItem = item.args;
@@ -59812,9 +60587,9 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59812
60587
  }
59813
60588
  switch (action.kind) {
59814
60589
  case "none": return true;
59815
- case "store": return await this.storeFileToDB(action.file);
59816
- case "delete": return await this.deleteFileFromDB(action.path);
59817
- case "rename": return await this.renameFileInDB(action.file, action.oldPath);
60590
+ case "store": return await this.storeFileToDBFromRevision(action.file, false, false, void 0, true);
60591
+ case "delete": return await this.deleteFileFromDBCore(action.path);
60592
+ case "rename": return await this.renameFileInDBCore(action.file, action.oldPath, true);
59818
60593
  }
59819
60594
  });
59820
60595
  }
@@ -59919,7 +60694,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59919
60694
  this._log(ex, 16);
59920
60695
  }
59921
60696
  async _anyProcessReplicatedDoc(entry) {
59922
- return await serialized(`processReplicatedDoc-${entry._id}`, async () => {
60697
+ return await this.serializedByFileEventPaths([this.getPath(entry)], async () => {
59923
60698
  if (!await this.vault.isTargetFile(entry.path)) {
59924
60699
  this._log(`File ${entry.path} is not the target file`, 16);
59925
60700
  return false;
@@ -59944,7 +60719,7 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
59944
60719
  }
59945
60720
  this._log(`Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Started...`, 16);
59946
60721
  this.events.emitEvent(EVENT_CONFLICT_CANCELLED, path);
59947
- const ret = await this.dbToStorage(entry, targetFile);
60722
+ const ret = await this.dbToStorageCore(entry, targetFile);
59948
60723
  this._log(`Processing ${path} (${entry._id.substring(0, 8)} :${entry._rev?.substring(0, 5)}) : Done`);
59949
60724
  return ret;
59950
60725
  }
@@ -60399,8 +61174,9 @@ var NodeFileSystemAdapter = class {
60399
61174
  return null;
60400
61175
  }
60401
61176
  async getFiles() {
60402
- if (this.fileCache.size === 0) await this.scanDirectory();
60403
- return Array.from(this.fileCache.values());
61177
+ const files = /* @__PURE__ */ new Map();
61178
+ await this.scanDirectoryInto("", files);
61179
+ return Array.from(files.values());
60404
61180
  }
60405
61181
  async renameFile(file, newPath) {
60406
61182
  const oldPath = file.path;
@@ -60442,6 +61218,9 @@ var NodeFileSystemAdapter = class {
60442
61218
  * Helper method to recursively scan directory and populate file cache
60443
61219
  */
60444
61220
  async scanDirectory(relativePath = "") {
61221
+ await this.scanDirectoryInto(relativePath, this.fileCache);
61222
+ }
61223
+ async scanDirectoryInto(relativePath, files) {
60445
61224
  const fullPath = this.resolvePath(relativePath);
60446
61225
  try {
60447
61226
  if ((await this.storage.stat(relativePath))?.type !== "folder") throw new Error(`Directory does not exist: ${fullPath}`);
@@ -60453,9 +61232,9 @@ var NodeFileSystemAdapter = class {
60453
61232
  path: entryPath,
60454
61233
  stat
60455
61234
  };
60456
- this.fileCache.set(entryPath, file);
61235
+ files.set(entryPath, file);
60457
61236
  }
60458
- for (const entryPath of entries.folders) await this.scanDirectory(entryPath);
61237
+ for (const entryPath of entries.folders) await this.scanDirectoryInto(entryPath, files);
60459
61238
  } catch (error) {
60460
61239
  this.reportDiagnostic(`Error scanning directory ${fullPath}:`, error);
60461
61240
  }
@@ -60813,6 +61592,7 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
60813
61592
  async store(file, force = false, skipCheck) {
60814
61593
  return await this.__store(file, force, skipCheck, false) !== false;
60815
61594
  }
61595
+ /** Force a child below the supplied base, even if advanced; an undefined base uses the winner. */
60816
61596
  async storeWithBaseRevision(file, baseRevision, skipCheck) {
60817
61597
  const result = await this.__store(file, true, skipCheck, false, {
60818
61598
  mode: "force-base",
@@ -60820,6 +61600,7 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
60820
61600
  });
60821
61601
  return result !== null && typeof result === "object" && "rev" in result ? result.rev : false;
60822
61602
  }
61603
+ /** Extend a current leaf with ordinary MVCC; an advanced base returns `false`. */
60823
61604
  async storeWithLiveBaseRevision(file, baseRevision, skipCheck) {
60824
61605
  const result = await this.__store(file, true, skipCheck, false, {
60825
61606
  mode: "live-base",
@@ -60827,9 +61608,18 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
60827
61608
  });
60828
61609
  return result !== null && typeof result === "object" && "rev" in result ? result.rev : false;
60829
61610
  }
61611
+ /**
61612
+ * Store Chunks and a fresh Metadata root for content with unknown ancestry.
61613
+ * Return its exact revision for provenance, or `false` if no Metadata write succeeded.
61614
+ */
61615
+ async storeIndependentRevision(file, skipCheck) {
61616
+ const result = await this.__store(file, true, skipCheck, false, { mode: "independent-root" });
61617
+ return result !== null && typeof result === "object" && "rev" in result ? result.rev : false;
61618
+ }
60830
61619
  async storeAsConflictedRevision(file, currentRev, skipCheck) {
60831
61620
  return await this.storeAsConflictedRevisionWithResult(file, currentRev, skipCheck) !== false;
60832
61621
  }
61622
+ /** Create a sibling of the selected revision; refuse when its parent cannot be found. */
60833
61623
  async storeAsConflictedRevisionWithResult(file, currentRev, skipCheck) {
60834
61624
  const conflictBaseRev = await this.getParentRev(file, currentRev);
60835
61625
  if (!conflictBaseRev) {
@@ -60838,6 +61628,7 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
60838
61628
  }
60839
61629
  return await this.storeWithBaseRevision(file, conflictBaseRev, skipCheck);
60840
61630
  }
61631
+ /** Record a logical deletion below the displayed branch and return its exact revision. */
60841
61632
  async storeDeletionWithBaseRevision(file, baseRevision) {
60842
61633
  if (!await this.checkIsTargetFile(file)) return false;
60843
61634
  const fullPath = getDatabasePathFromUXFileInfo(file);
@@ -60941,13 +61732,14 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
60941
61732
  this._log(msg + " Skip " + fullPath, 16);
60942
61733
  return true;
60943
61734
  }
60944
- const ret = revisionTarget.mode === "live-base" ? await this.database.localDatabase.putDBEntryWithLiveBaseRevision(d, revisionTarget.baseRevision, onlyChunks) : await this.database.localDatabase.putDBEntry(d, onlyChunks, revisionTarget.mode === "force-base" ? revisionTarget.baseRevision : void 0);
61735
+ const ret = revisionTarget.mode === "independent-root" ? await this.database.localDatabase.putDBEntryAsIndependentRoot(d) : revisionTarget.mode === "live-base" ? await this.database.localDatabase.putDBEntryWithLiveBaseRevision(d, revisionTarget.baseRevision, onlyChunks) : await this.database.localDatabase.putDBEntry(d, onlyChunks, revisionTarget.mode === "force-base" ? revisionTarget.baseRevision : void 0);
60945
61736
  if (ret !== false) {
60946
61737
  this._log(msg + fullPath);
60947
61738
  this.events.emitEvent(EVENT_FILE_SAVED$1);
60948
61739
  }
60949
61740
  return ret;
60950
61741
  }
61742
+ /** Reconstruct the immediate parent ID from revision history, or return `false` if unavailable. */
60951
61743
  async getParentRev(file, rev) {
60952
61744
  const filename = getDatabasePathFromUXFileInfo(file);
60953
61745
  try {
@@ -60965,6 +61757,11 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
60965
61757
  return false;
60966
61758
  }
60967
61759
  }
61760
+ /**
61761
+ * Search available revision bodies across branches and their ancestors.
61762
+ * `stopAfterFirstMatch` serves existence checks without decoding the remaining candidates.
61763
+ * Historical matches alone do not establish the origin of current storage content.
61764
+ */
60968
61765
  async findContentRevisionsInternal(file, content, currentRev, stopAfterFirstMatch = false) {
60969
61766
  const filename = getDatabasePathFromUXFileInfo(file);
60970
61767
  try {
@@ -61004,10 +61801,40 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61004
61801
  }
61005
61802
  return [];
61006
61803
  }
61804
+ /** Find matching content throughout available history, including non-leaf revisions. */
61007
61805
  async findContentRevisions(file, content, currentRev) {
61008
61806
  if (!await this.checkIsTargetFile(file)) return [];
61009
61807
  return await this.findContentRevisionsInternal(file, content, currentRev);
61010
61808
  }
61809
+ /**
61810
+ * Find live leaves which already represent these bytes, for deduplication when provenance
61811
+ * is unknown. `open_revs` includes conflicting branches; both deletion markers are excluded.
61812
+ * Unlike the historical search, ancestors cannot match and missing Chunks are not fetched.
61813
+ * A read failure yields no confirmed match. Callers decide whether the result identifies a
61814
+ * unique origin; this method does not mutate provenance or hold the revision tree stable.
61815
+ */
61816
+ async findLiveContentRevisions(file, content) {
61817
+ if (!await this.checkIsTargetFile(file)) return [];
61818
+ const filename = getDatabasePathFromUXFileInfo(file);
61819
+ try {
61820
+ const current = await this.database.localDatabase.getDBEntryMeta(filename, void 0, true);
61821
+ if (current === false) return [];
61822
+ const leaves = await this.database.localDatabase.getRaw(current._id, { open_revs: "all" });
61823
+ if (!Array.isArray(leaves)) return [];
61824
+ const matches = [];
61825
+ for (const leaf of leaves) {
61826
+ const rev = leaf.ok?._rev;
61827
+ if (!rev || leaf.ok?.deleted || leaf.ok?._deleted) continue;
61828
+ const entry = await this.database.localDatabase.getDBEntry(filename, { rev }, false, true, true, true);
61829
+ if (entry !== false && !entry.deleted && !entry._deleted && await isDocContentSame(readContent(entry), content)) matches.push(rev);
61830
+ }
61831
+ return matches;
61832
+ } catch (ex) {
61833
+ this._log(`Could not check live revision content for ${filename}`, 16);
61834
+ this._log(ex, 16);
61835
+ return [];
61836
+ }
61837
+ }
61011
61838
  async hasContentInRevisionHistory(file, content, currentRev) {
61012
61839
  if (!await this.checkIsTargetFile(file)) return true;
61013
61840
  return (await this.findContentRevisionsInternal(file, content, currentRev, true)).length > 0;
@@ -61047,17 +61874,17 @@ var ServiceDatabaseFileAccessBase = class extends ServiceModuleBase {
61047
61874
  if (doc === false) return false;
61048
61875
  return doc;
61049
61876
  }
61050
- async fetchEntryFromMeta(meta, waitForReady = true, skipCheck = false) {
61877
+ async fetchEntryFromMeta(meta, waitForReady = true, skipCheck = false, localOnly = false) {
61051
61878
  if (skipCheck && !await this.checkIsTargetFile(meta.path)) return false;
61052
- const doc = await this.database.localDatabase.getDBEntryFromMeta(meta, false, waitForReady);
61879
+ const doc = await this.database.localDatabase.getDBEntryFromMeta(meta, false, waitForReady, localOnly);
61053
61880
  if (doc === false) return false;
61054
61881
  return doc;
61055
61882
  }
61056
- async fetchEntry(file, rev, waitForReady = true, skipCheck = false) {
61883
+ async fetchEntry(file, rev, waitForReady = true, skipCheck = false, localOnly = false) {
61057
61884
  if (skipCheck && !await this.checkIsTargetFile(file)) return false;
61058
61885
  const entry = await this.fetchEntryMeta(file, rev, true);
61059
61886
  if (entry === false) return false;
61060
- return await this.fetchEntryFromMeta(entry, waitForReady, true);
61887
+ return await this.fetchEntryFromMeta(entry, waitForReady, true, localOnly);
61061
61888
  }
61062
61889
  async deleteFromDBbyPath(fullPath, rev) {
61063
61890
  if (!await this.checkIsTargetFile(fullPath)) {
@@ -64463,10 +65290,9 @@ async function decodeSettingsFromSetupURI(uri, passphrase) {
64463
65290
  const encryptedSetting = uri.substring(configURIBase.length);
64464
65291
  const decrypted = await decryptString(decodeURIComponent(encryptedSetting), passphrase);
64465
65292
  try {
64466
- return JSON.parse(decrypted);
64467
- } catch (e) {
65293
+ return omitP2PRuntimeSettings(JSON.parse(decrypted));
65294
+ } catch {
64468
65295
  Logger(`Failed to parse settings from decrypted data`, 64);
64469
- Logger(e, 16);
64470
65296
  return false;
64471
65297
  }
64472
65298
  }
@@ -64724,7 +65550,7 @@ async function runCommand(options, context) {
64724
65550
  const log = (msg) => writeStderrLine(standardIo, `[Daemon] ${String(msg)}`);
64725
65551
  replicationScheduling.setExternalPollingMode(!!options.interval);
64726
65552
  await core.services.setting.applyPartial({ disableCheckingConfigMismatch: true }, true);
64727
- log("Replicating from remote...");
65553
+ log("Replicating with remote...");
64728
65554
  if (!isReplicationCompleted(await core.services.replication.replicateUnattended({
64729
65555
  trigger: "daemon",
64730
65556
  interaction: NO_INTERACTION
@@ -64734,13 +65560,6 @@ async function runCommand(options, context) {
64734
65560
  }
64735
65561
  replicationScheduling.markInitialOneShotSatisfied();
64736
65562
  log("Initial replication complete");
64737
- const errorManager = new UnresolvedErrorManager(core.services.appLifecycle, core.services.context.events);
64738
- log("Running mirror scan...");
64739
- if (!await performFullScan(core, log, errorManager, false, true)) {
64740
- writeStderrLine(standardIo, "[Daemon] Mirror scan failed, cannot continue");
64741
- return false;
64742
- }
64743
- log("Mirror scan complete");
64744
65563
  const restoreSyncSettings = async () => {
64745
65564
  await core.services.setting.applyPartial({
64746
65565
  ...context.originalSyncSettings,
@@ -65022,8 +65841,7 @@ async function runCommand(options, context) {
65022
65841
  }
65023
65842
  if (options.command === "mirror") {
65024
65843
  writeStderrLine(standardIo, "[Command] mirror");
65025
- const log = (msg) => writeStderrLine(standardIo, `[Mirror] ${String(msg)}`);
65026
- return await performFullScan(core, log, new UnresolvedErrorManager(core.services.appLifecycle, core.services.context.events), false, true) === VaultScanResults.COMPLETED;
65844
+ return true;
65027
65845
  }
65028
65846
  if (options.command === "remote-add") {
65029
65847
  if (options.commandArgs.length < 2) throw new Error("remote-add requires two arguments: <name> <connstr>");
@@ -70075,11 +70893,29 @@ function createDiagRTCPeerConnectionConstructor() {
70075
70893
  }
70076
70894
  //#endregion
70077
70895
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/rpc/transports/trysteroUtils.js
70896
+ function containsTurnUrl(iceServers) {
70897
+ return iceServers.some((server) => {
70898
+ return (typeof server.urls === "string" ? [server.urls] : server.urls).some((url) => /^turns?:/iu.test(url));
70899
+ });
70900
+ }
70901
+ function copyIceServers(iceServers) {
70902
+ return iceServers.map((server) => ({
70903
+ urls: typeof server.urls === "string" ? server.urls : [...server.urls],
70904
+ ...server.username === void 0 ? {} : { username: server.username },
70905
+ ...server.credential === void 0 ? {} : { credential: server.credential }
70906
+ }));
70907
+ }
70078
70908
  function generateJoinRoomOptions(settings) {
70079
70909
  const passphraseNumbers = mixedHash(settings.P2P_passphrase, 0);
70080
70910
  const passphrase = passphraseNumbers[0].toString(36) + passphraseNumbers[1].toString(36);
70081
70911
  const relays = splitP2PRelayUrls(settings.P2P_relays);
70082
70912
  const turnServers = splitP2PTurnServerUrls(settings.P2P_turnServers);
70913
+ const managedTurnSelected = hasManagedP2PTurnConfiguration(settings);
70914
+ const preparedIceServers = settings.P2P_iceServers;
70915
+ if (preparedIceServers !== void 0 && preparedIceServers.length === 0) throw new Error("Prepared ICE servers must not be empty.");
70916
+ if (managedTurnSelected && preparedIceServers === void 0) throw new Error("The selected managed TURN configuration requires prepared ICE servers.");
70917
+ if (managedTurnSelected && preparedIceServers && !containsTurnUrl(preparedIceServers)) throw new Error("The prepared ICE servers do not contain a TURN route.");
70918
+ if (preparedIceServers !== void 0 && normaliseP2PConnectionPath(settings.P2P_connectionPath) === P2PConnectionPaths.Relay && !containsTurnUrl(preparedIceServers)) throw new Error("Relay-only P2P requires a prepared TURN route.");
70083
70919
  const relayConfig = {
70084
70920
  manualReconnection: true,
70085
70921
  urls: relays
@@ -70091,12 +70927,13 @@ function generateJoinRoomOptions(settings) {
70091
70927
  };
70092
70928
  if (settings.P2P_useDiagRTC) options.rtcPolyfill = createDiagRTCPeerConnectionConstructor();
70093
70929
  else if (typeof compatGlobal.RTCPeerConnection !== "undefined") options.rtcPolyfill = compatGlobal.RTCPeerConnection;
70094
- if (turnServers.length > 0) options.turnConfig = [{
70930
+ if (preparedIceServers !== void 0) options.turnConfig = copyIceServers(preparedIceServers);
70931
+ else if (!managedTurnSelected && turnServers.length > 0) options.turnConfig = [{
70095
70932
  urls: turnServers,
70096
70933
  username: settings.P2P_turnUsername,
70097
70934
  credential: settings.P2P_turnCredential
70098
70935
  }];
70099
- if (normaliseP2PConnectionPath(settings.P2P_connectionPath) === P2PConnectionPaths.Relay && hasValidP2PTurnServerUrl(settings.P2P_turnServers)) options.rtcConfig = { iceTransportPolicy: "relay" };
70936
+ if (normaliseP2PConnectionPath(settings.P2P_connectionPath) === P2PConnectionPaths.Relay && (preparedIceServers !== void 0 ? containsTurnUrl(preparedIceServers) : !managedTurnSelected && hasValidP2PTurnServerUrl(settings.P2P_turnServers))) options.rtcConfig = { iceTransportPolicy: "relay" };
70100
70937
  return options;
70101
70938
  }
70102
70939
  //#endregion
@@ -70200,7 +71037,7 @@ var TrysteroReplicatorP2PServer = class {
70200
71037
  await this._room?.leave();
70201
71038
  } catch (ex) {
70202
71039
  Logger(`Some error has been occurred while leaving the room, but possibly can be ignored`, 16);
70203
- Logger(ex, 16);
71040
+ this.logTransportError(ex);
70204
71041
  }
70205
71042
  this._room = void 0;
70206
71043
  this._env.events.emitEvent(EVENT_P2P_DISCONNECTED);
@@ -70218,7 +71055,7 @@ var TrysteroReplicatorP2PServer = class {
70218
71055
  this._rpcRoom = void 0;
70219
71056
  } catch (ex) {
70220
71057
  Logger(`Some error has been occurred while shutting down the server`, 32);
70221
- Logger(ex, 16);
71058
+ this.logTransportError(ex);
70222
71059
  }
70223
71060
  }
70224
71061
  /** Release subscriptions whose lifetime is the host object rather than one transport join. */
@@ -70547,7 +71384,7 @@ You can chose as follows:
70547
71384
  handshakeTimeoutMs: 3e4,
70548
71385
  onJoinError: (error) => {
70549
71386
  Logger("Some peer Failed to join Trystero room");
70550
- Logger(error, 16);
71387
+ this.logTransportError(error);
70551
71388
  }
70552
71389
  });
70553
71390
  await this.setRoom(room);
@@ -70556,6 +71393,13 @@ You can chose as follows:
70556
71393
  this.dispatchConnectionStatus();
70557
71394
  await this.startService(bindings, beforeAdvertisement);
70558
71395
  }
71396
+ logTransportError(error) {
71397
+ if (this.settings.P2P_iceServers !== void 0) {
71398
+ Logger("Managed P2P transport error details were omitted.", 16);
71399
+ return;
71400
+ }
71401
+ Logger(error, 16);
71402
+ }
70559
71403
  /**
70560
71404
  * @deprecated Use serveFunction or serveObject instead. This is only for backward compatibility and may be removed in the future.
70561
71405
  * @param type
@@ -70904,12 +71748,15 @@ var TrysteroReplicator = class {
70904
71748
  return await this.confirm.askString("Passphrase required", this.translate("P2P.AskPassphraseForShare"), "something you only know", true);
70905
71749
  });
70906
71750
  const setting = {
70907
- ...this.settings,
71751
+ ...omitP2PRuntimeSettings(this.settings),
70908
71752
  configPassphraseStore: "",
70909
71753
  encryptedCouchDBConnection: "",
70910
71754
  encryptedPassphrase: "",
70911
71755
  pluginSyncExtendedSetting: {}
70912
71756
  };
71757
+ delete setting.P2P_managedType;
71758
+ delete setting.P2P_managedId;
71759
+ delete setting.P2P_managedToken;
70913
71760
  if (!passphrase || passphrase.trim() == "") {
70914
71761
  Logger("Passphrase is required to transfer the configuration. The peer cannot be decrypt the config\nIf you repeatedly receive unintended configuration-sharing requests, change the RPC channel immediately. It allows you to leave the connection and disappear, while they are trying brute force attack for the decoy on their local.", 64);
70915
71762
  return encrypt(JSON.stringify(Object.fromEntries(Object.entries(setting).map(([key, value]) => {
@@ -71241,7 +72088,7 @@ ${info.lastSeq} / ${info.maxSeqInBatch})`, logLevel, "p2p-replicator");
71241
72088
  return false;
71242
72089
  }
71243
72090
  try {
71244
- return JSON.parse(await decrypt(encryptedConfig, passphrase));
72091
+ return omitP2PRuntimeSettings(JSON.parse(await decrypt(encryptedConfig, passphrase)));
71245
72092
  } catch (e) {
71246
72093
  Logger("Error while decrypting the configuration", 64);
71247
72094
  Logger(e, 16);
@@ -71489,18 +72336,24 @@ var P2PRoomSession = class {
71489
72336
  //#endregion
71490
72337
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/replication/trystero/p2pReplicatorConfigurationIdentity.js
71491
72338
  function getP2PReplicatorConfigurationIdentity(settings) {
72339
+ const managedTurnSelected = hasManagedP2PTurnConfiguration(settings);
71492
72340
  const turnServerValue = settings.P2P_turnServers ?? "";
71493
72341
  const turnServers = splitP2PTurnServerUrls(turnServerValue);
71494
- const effectivePath = normaliseP2PConnectionPath(settings.P2P_connectionPath) === P2PConnectionPaths.Relay && hasValidP2PTurnServerUrl(turnServerValue) ? P2PConnectionPaths.Relay : P2PConnectionPaths.Automatic;
71495
- const turnAuthentication = turnServers.length > 0 ? [settings.P2P_turnUsername, settings.P2P_turnCredential] : void 0;
72342
+ const effectivePath = normaliseP2PConnectionPath(settings.P2P_connectionPath) === P2PConnectionPaths.Relay && (managedTurnSelected || hasValidP2PTurnServerUrl(turnServerValue)) ? P2PConnectionPaths.Relay : P2PConnectionPaths.Automatic;
72343
+ const turnAuthentication = !managedTurnSelected && turnServers.length > 0 ? [settings.P2P_turnUsername, settings.P2P_turnCredential] : void 0;
71496
72344
  return JSON.stringify([
71497
72345
  "p2p",
71498
72346
  settings.P2P_AppID || "self-hosted-livesync",
71499
72347
  settings.P2P_roomID,
71500
72348
  settings.P2P_passphrase,
71501
72349
  splitP2PRelayUrls(settings.P2P_relays),
71502
- turnServers,
72350
+ managedTurnSelected ? void 0 : turnServers,
71503
72351
  turnAuthentication,
72352
+ managedTurnSelected ? [
72353
+ settings.P2P_managedType,
72354
+ settings.P2P_managedId,
72355
+ settings.P2P_managedToken
72356
+ ] : void 0,
71504
72357
  normaliseP2PMaxWirePayloadBytes(settings.P2P_maxWirePayloadBytes),
71505
72358
  effectivePath,
71506
72359
  settings.P2P_useDiagRTC ?? false
@@ -71515,19 +72368,26 @@ function activeP2PRelayBindingCovers(activeSettings, trialSettings) {
71515
72368
  }
71516
72369
  //#endregion
71517
72370
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/replication/trystero/P2PRoomSessionOwner.js
72371
+ var StaleRoomReconciliationError = class extends Error {};
72372
+ var P2P_ROOM_OPEN_TIMEOUT_MS = 3e4;
72373
+ var P2P_SETTINGS_PREPARATION_TIMEOUT_MS = 3e4;
71518
72374
  var P2PRoomSessionOwner = class {
71519
- constructor(env, createSession = (sessionEnv) => new P2PRoomSession(sessionEnv)) {
72375
+ constructor(env, createSession = (sessionEnv) => new P2PRoomSession(sessionEnv), options = {}) {
71520
72376
  this.env = env;
71521
72377
  this.createSession = createSession;
72378
+ this.options = options;
71522
72379
  }
71523
72380
  env;
71524
72381
  createSession;
72382
+ options;
71525
72383
  current;
71526
72384
  lifecycleOperation = Promise.resolve();
71527
72385
  persistentDemands = /* @__PURE__ */ new Set();
71528
72386
  finiteDemands = /* @__PURE__ */ new Set();
71529
72387
  automationCoordinator = new P2PAutomationCoordinator();
71530
72388
  activeBinding;
72389
+ pendingPreparation;
72390
+ runtimeGeneration = 0;
71531
72391
  get currentSession() {
71532
72392
  return this.current;
71533
72393
  }
@@ -71550,6 +72410,7 @@ var P2PRoomSessionOwner = class {
71550
72410
  if (active && enabled) this.persistentDemands.add(demand);
71551
72411
  else this.persistentDemands.delete(demand);
71552
72412
  if (active && !enabled) Logger(this.env.services.context.translate("P2P.NotEnabled"), 64);
72413
+ this.fencePreparationForCurrentSettings(enabled);
71553
72414
  await this.reconcileTransport();
71554
72415
  }
71555
72416
  /**
@@ -71562,6 +72423,7 @@ var P2PRoomSessionOwner = class {
71562
72423
  if (!this.env.services.setting.currentSettings().P2P_Enabled) throw new Error("P2P is not enabled.");
71563
72424
  const demand = /* @__PURE__ */ Symbol("p2p-finite-room-demand");
71564
72425
  this.finiteDemands.add(demand);
72426
+ this.fencePreparationForCurrentSettings(true);
71565
72427
  try {
71566
72428
  await this.reconcileTransport();
71567
72429
  if (!this.finiteDemands.has(demand)) throw new Error("The P2P room demand was retired before the operation started.");
@@ -71602,39 +72464,55 @@ var P2PRoomSessionOwner = class {
71602
72464
  return;
71603
72465
  }
71604
72466
  const binding = this.getEffectiveBinding();
71605
- if (this.current?.host.isServing && this.bindingsMatch(this.activeBinding, binding)) {
72467
+ if (this.current?.host.isServing && this.bindingsMatch(this.activeBinding, binding) && this.connectionSettingsRemainUsable(this.activeBinding?.settings)) {
71606
72468
  this.reconcileCurrentSessionPolicy(this.current);
71607
72469
  Logger("P2P replicator is already open.");
71608
72470
  return;
71609
72471
  }
71610
72472
  if (this.current) await this.closeTransport();
71611
72473
  let candidate;
72474
+ const operationGeneration = this.runtimeGeneration;
71612
72475
  try {
71613
- candidate = this.createSession(this.buildSessionEnv(binding));
71614
- await candidate.open();
72476
+ const connectionSettings = await this.prepareConnectionSettings(binding, operationGeneration);
72477
+ this.assertReconciliationCurrent(binding, operationGeneration, connectionSettings);
72478
+ const connectionBinding = {
72479
+ ...binding,
72480
+ settings: connectionSettings
72481
+ };
72482
+ candidate = this.createSession(this.buildSessionEnv(connectionBinding));
72483
+ if (hasManagedP2PTurnConfiguration(binding.settings)) await this.withRoomOpenDeadline(candidate.open());
72484
+ else await candidate.open();
71615
72485
  if (!candidate.host.isServing) throw new Error("The P2P room did not start serving.");
71616
72486
  const currentBinding = this.getEffectiveBinding();
71617
- if (!currentBinding.enabled || !this.hasRoomDemand() || !this.bindingsMatch(binding, currentBinding)) {
72487
+ if (!currentBinding.enabled || !this.hasRoomDemand() || !this.bindingsMatch(binding, currentBinding) || operationGeneration !== this.runtimeGeneration || !this.connectionSettingsRemainUsable(connectionSettings)) {
71618
72488
  await candidate.retire();
71619
72489
  return;
71620
72490
  }
71621
72491
  this.current = candidate;
71622
- this.activeBinding = binding;
72492
+ this.activeBinding = connectionBinding;
71623
72493
  this.reconcileCurrentSessionPolicy(candidate);
71624
72494
  } catch (error) {
71625
72495
  await candidate?.retire(error).catch((retirementError) => {
71626
- Logger(retirementError, 16);
72496
+ if (hasManagedP2PTurnConfiguration(binding.settings)) Logger("The managed P2P room could not be retired cleanly.", 16);
72497
+ else Logger(retirementError, 16);
71627
72498
  });
71628
- Logger(error instanceof Error ? error.message : "Error while opening P2P connection", 64);
71629
- Logger(error, 16);
71630
72499
  this.current = void 0;
71631
72500
  this.activeBinding = void 0;
72501
+ if (error instanceof StaleRoomReconciliationError || operationGeneration !== this.runtimeGeneration) return;
72502
+ if (hasManagedP2PTurnConfiguration(binding.settings)) {
72503
+ Logger("The managed P2P room could not be prepared or opened.", 64);
72504
+ Logger("Managed P2P room failure details were omitted.", 16);
72505
+ throw new Error("The managed P2P room could not be prepared or opened.");
72506
+ }
72507
+ Logger(error instanceof Error ? error.message : "Error while opening P2P connection", 64);
72508
+ Logger(error, 16);
71632
72509
  }
71633
72510
  });
71634
72511
  }
71635
72512
  async close() {
71636
72513
  this.persistentDemands.clear();
71637
72514
  this.finiteDemands.clear();
72515
+ this.invalidatePreparation();
71638
72516
  await this.enqueueLifecycleOperation(async () => {
71639
72517
  await this.closeTransport();
71640
72518
  });
@@ -71656,9 +72534,125 @@ var P2PRoomSessionOwner = class {
71656
72534
  bindingsMatch(current, candidate) {
71657
72535
  return current?.database === candidate.database && current.signature === candidate.signature;
71658
72536
  }
72537
+ connectionSettingsRemainUsable(settings) {
72538
+ if (!settings) return false;
72539
+ const managed = hasManagedP2PTurnConfiguration(settings);
72540
+ const iceServers = settings.P2P_iceServers;
72541
+ if (iceServers === void 0) return !managed;
72542
+ if (!this.hasUsableIceServer(iceServers)) return false;
72543
+ const hasTurnServer = this.hasUsableTurnServer(iceServers);
72544
+ if (managed && !hasTurnServer) return false;
72545
+ if (normaliseP2PConnectionPath(settings.P2P_connectionPath) === P2PConnectionPaths.Relay && !hasTurnServer) return false;
72546
+ const expiresAt = settings.P2P_iceServersExpiresAt;
72547
+ if (expiresAt === void 0) return !managed;
72548
+ return Number.isFinite(expiresAt) && expiresAt > Date.now() + 3e4;
72549
+ }
72550
+ fencePreparationForCurrentSettings(enabled) {
72551
+ if (!enabled) {
72552
+ this.invalidatePreparation();
72553
+ return;
72554
+ }
72555
+ if (this.pendingPreparation !== void 0 && this.pendingPreparation.signature !== this.getEffectiveBinding().signature) this.invalidatePreparation();
72556
+ }
72557
+ invalidatePreparation() {
72558
+ this.runtimeGeneration += 1;
72559
+ const pending = this.pendingPreparation;
72560
+ this.pendingPreparation = void 0;
72561
+ if (pending && !pending.controller.signal.aborted) pending.controller.abort(/* @__PURE__ */ new Error("The P2P settings preparation was cancelled."));
72562
+ }
72563
+ async prepareConnectionSettings(binding, operationGeneration) {
72564
+ const managed = hasManagedP2PTurnConfiguration(binding.settings);
72565
+ const prepare = this.options.prepareP2PSettings;
72566
+ if (!prepare) {
72567
+ if (managed) throw new Error("The selected managed TURN configuration is not supported by this host.");
72568
+ return binding.settings;
72569
+ }
72570
+ const controller = new AbortController();
72571
+ const pending = {
72572
+ signature: binding.signature,
72573
+ controller
72574
+ };
72575
+ this.pendingPreparation = pending;
72576
+ try {
72577
+ const prepared = await this.prepareWithDeadline(prepare, binding.settings, controller);
72578
+ if (prepared.P2P_iceServers === void 0 && prepared.P2P_iceServersExpiresAt === void 0) {
72579
+ if (managed) throw new Error("The prepared managed TURN settings do not include ICE servers.");
72580
+ return binding.settings;
72581
+ }
72582
+ const iceServers = this.copyPreparedIceServers(prepared.P2P_iceServers);
72583
+ const expiresAt = prepared.P2P_iceServersExpiresAt;
72584
+ const connectionSettings = {
72585
+ ...binding.settings,
72586
+ P2P_iceServers: iceServers,
72587
+ P2P_iceServersExpiresAt: expiresAt
72588
+ };
72589
+ if (!this.connectionSettingsRemainUsable(connectionSettings)) throw new Error("The prepared managed TURN settings are missing usable ICE servers or expiry.");
72590
+ this.assertReconciliationCurrent(binding, operationGeneration, connectionSettings);
72591
+ return connectionSettings;
72592
+ } finally {
72593
+ if (this.pendingPreparation === pending) this.pendingPreparation = void 0;
72594
+ }
72595
+ }
72596
+ prepareWithDeadline(prepare, settings, controller) {
72597
+ const preparation = Promise.resolve().then(() => prepare(Object.freeze({ ...settings }), controller.signal));
72598
+ return new Promise((resolve, reject) => {
72599
+ let settled = false;
72600
+ const finish = (operation) => {
72601
+ if (settled) return;
72602
+ settled = true;
72603
+ globalThis.clearTimeout(timeout);
72604
+ controller.signal.removeEventListener("abort", onAbort);
72605
+ operation();
72606
+ };
72607
+ const onAbort = () => finish(() => reject(controller.signal.reason instanceof Error ? controller.signal.reason : /* @__PURE__ */ new Error("The P2P settings preparation was cancelled.")));
72608
+ const timeout = globalThis.setTimeout(() => {
72609
+ controller.abort(/* @__PURE__ */ new Error("The P2P settings preparation timed out."));
72610
+ }, P2P_SETTINGS_PREPARATION_TIMEOUT_MS);
72611
+ controller.signal.addEventListener("abort", onAbort, { once: true });
72612
+ if (controller.signal.aborted) onAbort();
72613
+ preparation.then((prepared) => finish(() => resolve(prepared)), () => finish(() => reject(/* @__PURE__ */ new Error("The P2P settings preparation failed."))));
72614
+ });
72615
+ }
72616
+ copyPreparedIceServers(iceServers) {
72617
+ if (!Array.isArray(iceServers) || iceServers.length === 0) return [];
72618
+ return iceServers.map((server) => ({
72619
+ urls: typeof server.urls === "string" ? server.urls : [...server.urls],
72620
+ ...server.username === void 0 ? {} : { username: server.username },
72621
+ ...server.credential === void 0 ? {} : { credential: server.credential }
72622
+ }));
72623
+ }
72624
+ hasUsableIceServer(iceServers) {
72625
+ return Array.isArray(iceServers) && iceServers.some((server) => {
72626
+ const urls = typeof server?.urls === "string" ? [server.urls] : server?.urls;
72627
+ return Array.isArray(urls) && urls.some((url) => typeof url === "string" && url.trim().length > 0);
72628
+ });
72629
+ }
72630
+ hasUsableTurnServer(iceServers) {
72631
+ return Array.isArray(iceServers) && iceServers.some((server) => {
72632
+ const urls = typeof server?.urls === "string" ? [server.urls] : server?.urls;
72633
+ return Array.isArray(urls) && urls.some((url) => typeof url === "string" && /^turns?:/iu.test(url));
72634
+ });
72635
+ }
72636
+ async withRoomOpenDeadline(opening) {
72637
+ let timeout;
72638
+ try {
72639
+ await Promise.race([opening, new Promise((_resolve, reject) => {
72640
+ timeout = globalThis.setTimeout(() => reject(/* @__PURE__ */ new Error("The P2P room opening timed out.")), P2P_ROOM_OPEN_TIMEOUT_MS);
72641
+ })]);
72642
+ } finally {
72643
+ if (timeout !== void 0) globalThis.clearTimeout(timeout);
72644
+ }
72645
+ }
72646
+ assertReconciliationCurrent(binding, operationGeneration, connectionSettings) {
72647
+ if (operationGeneration !== this.runtimeGeneration || !this.hasRoomDemand()) throw new StaleRoomReconciliationError();
72648
+ const currentBinding = this.getEffectiveBinding();
72649
+ if (!currentBinding.enabled) throw new StaleRoomReconciliationError();
72650
+ if (binding && !this.bindingsMatch(binding, currentBinding)) throw new StaleRoomReconciliationError();
72651
+ if (connectionSettings && !this.connectionSettingsRemainUsable(connectionSettings)) throw new StaleRoomReconciliationError();
72652
+ }
71659
72653
  /** Capture immutable session inputs while keeping policy live. */
71660
72654
  getEffectiveBinding() {
71661
- const settings = { ...this.env.services.setting.currentSettings() };
72655
+ const settings = omitP2PRuntimeSettings({ ...this.env.services.setting.currentSettings() });
71662
72656
  const deviceName = this.env.services.config.getSmallConfig("p2p_device_name") || this.env.services.vault.getVaultName();
71663
72657
  const database = this.env.services.database.localDatabase.localDatabase;
71664
72658
  this.automationCoordinator.reconcileIdentity(JSON.stringify([
@@ -72035,10 +73029,15 @@ function closeForLifecycle(owner, state) {
72035
73029
  cancelDelayedAutomation(owner, state);
72036
73030
  return owner.close();
72037
73031
  }
72038
- function reconcileAutoStart(context, settings) {
72039
- if (!settings.P2P_Enabled || !settings.P2P_AutoStart) return context.roomSessionOwner.setPersistentDemand("automatic", false);
72040
- if (context.state.explicitDisconnectVeto || context.state.lifecycleClosed) return Promise.resolve();
72041
- return context.roomSessionOwner.setPersistentDemand("automatic", true);
73032
+ async function reconcileAutoStart(context, settings) {
73033
+ if (!settings.P2P_Enabled || !settings.P2P_AutoStart) {
73034
+ await context.roomSessionOwner.setPersistentDemand("automatic", false);
73035
+ return;
73036
+ }
73037
+ if (context.state.explicitDisconnectVeto || context.state.lifecycleClosed) return;
73038
+ try {
73039
+ await context.roomSessionOwner.setPersistentDemand("automatic", true);
73040
+ } catch {}
72042
73041
  }
72043
73042
  function scheduleAutoStart(context, delayMs = 100) {
72044
73043
  clearDelayedAutoStart(context.state);
@@ -72144,8 +73143,8 @@ function createServiceLifecycle(context) {
72144
73143
  scheduleAutoStart: (delayMs) => scheduleAutoStart(context, delayMs)
72145
73144
  };
72146
73145
  }
72147
- function createP2PService(env) {
72148
- const roomSessionOwner = new P2PRoomSessionOwner(env);
73146
+ function createP2PService(env, options = {}) {
73147
+ const roomSessionOwner = new P2PRoomSessionOwner(env, void 0, options);
72149
73148
  const state = {
72150
73149
  explicitDisconnectVeto: false,
72151
73150
  lifecycleClosed: false,
@@ -72226,8 +73225,8 @@ function addP2PEventHandlers(source, events) {
72226
73225
  }
72227
73226
  //#endregion
72228
73227
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/replication/trystero/useP2PReplicatorFeature.js
72229
- function useP2PReplicatorFeature(host, openReplicationUIFactory, openRebuildUIFactory) {
72230
- const service = createP2PService({ services: host.services });
73228
+ function useP2PReplicatorFeature(host, openReplicationUIFactory, openRebuildUIFactory, options = {}) {
73229
+ const service = createP2PService({ services: host.services }, options);
72231
73230
  const replicator = service.compatibilityReplicator;
72232
73231
  const { views, lifecycle } = service;
72233
73232
  const configureReplicator = (instance) => {
@@ -72406,6 +73405,24 @@ function applyStoredSetting(target, storedText, key) {
72406
73405
  //#endregion
72407
73406
  //#region main.ts
72408
73407
  var SETTINGS_FILE = ".livesync/settings.json";
73408
+ var VAULT_SYNC_MODES = {
73409
+ daemon: {
73410
+ watchFiles: true,
73411
+ reflectReplicationResults: true,
73412
+ startupDatabaseOptions: {
73413
+ ignoreSuspending: false,
73414
+ continueOnFileFailure: true
73415
+ }
73416
+ },
73417
+ mirror: {
73418
+ watchFiles: false,
73419
+ reflectReplicationResults: false,
73420
+ startupDatabaseOptions: {
73421
+ ignoreSuspending: true,
73422
+ continueOnFileFailure: false
73423
+ }
73424
+ }
73425
+ };
72409
73426
  ensureGlobalNodeLocalStorage();
72410
73427
  defaultLoggerEnv.minLogLevel = -1;
72411
73428
  function printHelp(standardIo) {
@@ -72627,6 +73644,7 @@ async function createDefaultSettingsFile(options, standardIo) {
72627
73644
  }
72628
73645
  async function main(standardIo = createNodeStandardIo(), commandRunner = runCommand) {
72629
73646
  const options = parseArgs(standardIo);
73647
+ const vaultSyncMode = VAULT_SYNC_MODES[options.command];
72630
73648
  if (options.interval && options.command !== "daemon") writeStderrLine(standardIo, `Warning: --interval is only used in daemon mode, ignored for '${options.command}'`);
72631
73649
  const avoidStdoutNoise = options.command === "cat" || options.command === "cat-rev" || options.command === "ls" || options.command === "remote-add" || options.command === "remote-ls" || options.command === "remote-export" || options.command === "p2p-peers" || options.command === "info" || options.command === "rm" || options.command === "resolve" || options.command === "mark-resolved" || options.command === "unlock-remote" || options.command === "lock-remote" || options.command === "remote-status";
72632
73650
  const infoLog = (...values) => {
@@ -72652,7 +73670,6 @@ async function main(standardIo = createNodeStandardIo(), commandRunner = runComm
72652
73670
  }
72653
73671
  const settingsPath = options.settingsPath ? path.resolve(options.settingsPath) : path.join(databasePath, SETTINGS_FILE);
72654
73672
  configureNodeLocalStorage(path.join(databasePath, ".livesync", "runtime", "local-storage.json"));
72655
- const watchEnabled = options.command === "daemon";
72656
73673
  const vaultPath = options.command === "mirror" && options.commandArgs[0] ? path.resolve(options.commandArgs[0]) : options.vaultPath ? path.resolve(options.vaultPath) : databasePath;
72657
73674
  try {
72658
73675
  if (!(await fsPromises.stat(vaultPath)).isDirectory()) {
@@ -72669,7 +73686,7 @@ async function main(standardIo = createNodeStandardIo(), commandRunner = runComm
72669
73686
  infoLog(`Settings: ${settingsPath}`);
72670
73687
  infoLog("");
72671
73688
  let ignoreRules;
72672
- if (options.command === "daemon" || options.command === "mirror") {
73689
+ if (vaultSyncMode) {
72673
73690
  ignoreRules = new IgnoreRules(vaultPath, (message, detail) => {
72674
73691
  if (detail === void 0) writeStderrLine(standardIo, message);
72675
73692
  else writeStderrLine(standardIo, message, detail);
@@ -72703,7 +73720,7 @@ async function main(standardIo = createNodeStandardIo(), commandRunner = runComm
72703
73720
  }
72704
73721
  writeStderrLine(standardIo, prefix, message);
72705
73722
  }, true);
72706
- if (options.command !== "daemon") serviceHubInstance.replication.processSynchroniseResult.addHandler(async () => {
73723
+ if (!vaultSyncMode?.reflectReplicationResults) serviceHubInstance.replication.processSynchroniseResult.addHandler(async () => {
72707
73724
  writeStderrLine(standardIo, `[Info] Replication result received, but not processed automatically in CLI mode.`);
72708
73725
  return await Promise.resolve(true);
72709
73726
  }, -100);
@@ -72741,10 +73758,11 @@ async function main(standardIo = createNodeStandardIo(), commandRunner = runComm
72741
73758
  let p2pReplicator;
72742
73759
  let replicationScheduling;
72743
73760
  const core = new LiveSyncBaseCore(serviceHubInstance, (core, serviceHub) => {
72744
- return initialiseServiceModulesCLI(vaultPath, core, serviceHub, ignoreRules, watchEnabled);
73761
+ return initialiseServiceModulesCLI(vaultPath, core, serviceHub, ignoreRules, vaultSyncMode?.watchFiles ?? false);
72745
73762
  }, (core) => [], () => [], (core, coreFeatureViews) => {
72746
73763
  replicationScheduling = coreFeatureViews.replicationScheduling;
72747
- p2pReplicator = useP2PReplicatorFeature(core);
73764
+ if (vaultSyncMode) useOfflineScanner(core);
73765
+ p2pReplicator = useP2PReplicatorFeature(core, void 0, void 0, { prepareP2PSettings: useP2PSettingsPreparation(core.services.API.webCompatFetch.bind(core.services.API)) });
72748
73766
  core.services.vault.isTargetFile.addHandler(async (target) => {
72749
73767
  const parts = stripAllPrefixes(getPathFromUXFileInfo(target)).split(path.sep);
72750
73768
  if (parts.some((part) => part.startsWith("."))) return await Promise.resolve(false);
@@ -72759,7 +73777,7 @@ async function main(standardIo = createNodeStandardIo(), commandRunner = runComm
72759
73777
  return true;
72760
73778
  }, 0);
72761
73779
  }
72762
- });
73780
+ }, vaultSyncMode?.startupDatabaseOptions);
72763
73781
  if (!replicationScheduling) throw new Error("Replication scheduling was not provided during core feature composition.");
72764
73782
  const shutdown = async (signal) => {
72765
73783
  writeStdoutLine(standardIo);
@@ -72809,7 +73827,13 @@ async function main(standardIo = createNodeStandardIo(), commandRunner = runComm
72809
73827
  };
72810
73828
  await core.services.setting.suspendAllSync();
72811
73829
  const settingsAfterSuspend = cloneSettings(core.services.setting.currentSettings());
72812
- await core.services.control.onReady();
73830
+ let readyResult = false;
73831
+ try {
73832
+ readyResult = await core.services.control.onReady();
73833
+ } finally {
73834
+ if (!readyResult) await core.services.control.onUnload();
73835
+ }
73836
+ if (!readyResult) throw new Error("Failed to initialise LiveSync.");
72813
73837
  const settingsBeforeCommand = cloneSettings(core.services.setting.currentSettings());
72814
73838
  const transientSettingKeys = changedSettingKeys(settingsBeforeSuspend, settingsAfterSuspend);
72815
73839
  for (const key of CLI_RUNTIME_ONLY_SETTING_KEYS) transientSettingKeys.add(key);