@jr2804/livesync-cli 1.0.24-cli.1 → 1.0.28-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 +1851 -1431
  2. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -126,49 +126,71 @@ var EventHub = class {
126
126
  });
127
127
  this._emitter = emitter ?? new EventTarget();
128
128
  }
129
- _issueSignal(key, callback) {
130
- let assigned = this._assigned.get(key);
131
- if (assigned === void 0) assigned = /* @__PURE__ */ new WeakMap();
132
- let controller = assigned.get(callback)?.deref();
133
- if (!controller || controller.signal.aborted) {
134
- controller = new AbortController();
135
- const refController = new FallbackWeakRef(controller);
136
- controller.signal.addEventListener("abort", () => {
137
- this._assigned.get(key)?.delete(callback);
138
- this._allAssigned.get(key)?.delete(refController);
139
- }, { once: true });
140
- assigned.set(callback, refController);
141
- this._assigned.set(key, assigned);
142
- const allAssigned = this._allAssigned.get(key) ?? /* @__PURE__ */ new Set();
143
- allAssigned.add(refController);
144
- this._allAssigned.set(key, allAssigned);
145
- return controller;
129
+ _issueSignal(key, callback, sourceSignal) {
130
+ const controller = new AbortController();
131
+ const controllerRef = new FallbackWeakRef(controller);
132
+ const assigned = this._assigned.get(key) ?? /* @__PURE__ */ new WeakMap();
133
+ const callbackControllers = assigned.get(callback) ?? /* @__PURE__ */ new Set();
134
+ const allAssigned = this._allAssigned.get(key) ?? /* @__PURE__ */ new Set();
135
+ const abortFromSource = () => controller.abort();
136
+ controller.signal.addEventListener("abort", () => {
137
+ sourceSignal?.removeEventListener("abort", abortFromSource);
138
+ callbackControllers.delete(controllerRef);
139
+ if (callbackControllers.size === 0) assigned.delete(callback);
140
+ allAssigned.delete(controllerRef);
141
+ if (allAssigned.size === 0) {
142
+ this._assigned.delete(key);
143
+ this._allAssigned.delete(key);
144
+ }
145
+ }, { once: true });
146
+ callbackControllers.add(controllerRef);
147
+ assigned.set(callback, callbackControllers);
148
+ this._assigned.set(key, assigned);
149
+ allAssigned.add(controllerRef);
150
+ this._allAssigned.set(key, allAssigned);
151
+ if (sourceSignal) {
152
+ sourceSignal.addEventListener("abort", abortFromSource, { once: true });
153
+ if (sourceSignal.aborted) controller.abort();
146
154
  }
147
155
  return controller;
148
156
  }
157
+ _listen(key, callback, listener, options) {
158
+ const controller = this._issueSignal(key, callback, options?.signal);
159
+ const controlledListener = options?.once ? (event) => {
160
+ try {
161
+ listener(event);
162
+ } finally {
163
+ controller.abort();
164
+ }
165
+ } : listener;
166
+ this._emitter.addEventListener(key, controlledListener, {
167
+ ...options,
168
+ signal: controller.signal
169
+ });
170
+ return controller;
171
+ }
149
172
  emitEvent(event, data) {
150
173
  this._emitter.dispatchEvent(new CustomEvent(`${event.toString()}`, { detail: data ?? void 0 }));
151
174
  }
152
175
  on(event, callback, options) {
153
176
  const onEvent = (e) => void callback(e, e instanceof CustomEvent ? e?.detail : void 0);
154
177
  const key = event;
155
- const controller = this._issueSignal(key, callback);
156
- this._emitter.addEventListener(key, onEvent, {
157
- ...options,
158
- signal: controller.signal
159
- });
160
- return () => this.off(event, callback);
178
+ const controller = this._listen(key, callback, onEvent, options);
179
+ return () => controller.abort();
161
180
  }
162
181
  /**
163
- * Removes an event listener for a specific event.
164
- * @param event
165
- * @param callback
182
+ * Removes current event registrations in bulk.
183
+ *
184
+ * Prefer the disposer returned by `on`, `onEvent`, `once`, or `onceEvent` when removing one registration.
185
+ *
186
+ * @param event - The event whose registrations should be removed.
187
+ * @param callback - The callback whose registrations should be removed. Omit it to remove every registration for the event.
166
188
  */
167
189
  off(event, callback) {
168
190
  const key = event;
169
- if (callback) ((this._assigned.get(key)?.get(callback))?.deref())?.abort();
170
- else this._allAssigned.get(key)?.forEach((w) => {
171
- w.deref()?.abort();
191
+ if (callback) (this._assigned.get(key)?.get(callback))?.forEach((controllerRef) => controllerRef.deref()?.abort());
192
+ else this._allAssigned.get(key)?.forEach((controllerRef) => {
193
+ controllerRef.deref()?.abort();
172
194
  });
173
195
  }
174
196
  /**
@@ -180,18 +202,20 @@ var EventHub = class {
180
202
  onEvent(event, callback, options) {
181
203
  const onEvent = (e) => void callback(e instanceof CustomEvent ? e?.detail : void 0);
182
204
  const key = event;
183
- const controller = this._issueSignal(key, callback);
184
- this._emitter.addEventListener(key, onEvent, {
205
+ const controller = this._listen(key, callback, onEvent, options);
206
+ return () => controller.abort();
207
+ }
208
+ once(event, callback, options) {
209
+ return this.on(event, callback, {
185
210
  ...options,
186
- signal: controller.signal
211
+ once: true
187
212
  });
188
- return () => this.off(event, callback);
189
213
  }
190
- once(event, callback) {
191
- return this.on(event, callback, { once: true });
192
- }
193
- onceEvent(event, callback) {
194
- return this.on(event, (_, data) => callback(data), { once: true });
214
+ onceEvent(event, callback, options) {
215
+ return this.on(event, (_, data) => callback(data), {
216
+ ...options,
217
+ once: true
218
+ });
195
219
  }
196
220
  waitFor(event) {
197
221
  return new Promise((resolve) => {
@@ -909,7 +933,6 @@ function isLockAcquired(key) {
909
933
  var RESULT_TIMED_OUT = Symbol("timed out");
910
934
  //#endregion
911
935
  //#region ../../../node_modules/octagonal-wheels/dist/bureau/SlipBoard.js
912
- var GENERIC_COMPATIBILITY_VALUE = "x-compatibility-value";
913
936
  var SlipBoard = class {
914
937
  constructor() {
915
938
  Object.defineProperty(this, "_clip", {
@@ -1035,15 +1058,7 @@ var SlipBoard = class {
1035
1058
  if (taskPromise) taskPromise.reject(reason);
1036
1059
  }
1037
1060
  };
1038
- var globalSlipBoard = new SlipBoard();
1039
- /**
1040
- * Sends a value to the specified ID.
1041
- * @param id - The ID to send the value to.
1042
- * @param result - The value to send.
1043
- */
1044
- function sendValue(id, result) {
1045
- globalSlipBoard.submit(GENERIC_COMPATIBILITY_VALUE, id, result);
1046
- }
1061
+ new SlipBoard();
1047
1062
  //#endregion
1048
1063
  //#region ../../../node_modules/octagonal-wheels/dist/concurrency/task.js
1049
1064
  function unwrapTaskResult(result) {
@@ -4612,38 +4627,114 @@ var DEFAULT_SYNC_PARAMETERS = {
4612
4627
  };
4613
4628
  //#endregion
4614
4629
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/models/tweak.definition.js
4615
- var TweakValuesShouldMatchedTemplate = {
4616
- minimumChunkSize: 20,
4617
- longLineThreshold: 250,
4618
- encrypt: false,
4619
- usePathObfuscation: false,
4620
- enableCompression: false,
4621
- useEden: false,
4622
- customChunkSize: 0,
4623
- useDynamicIterationCount: false,
4624
- hashAlg: "xxhash64",
4625
- enableChunkSplitterV2: false,
4626
- maxChunksInEden: 10,
4627
- maxTotalLengthInEden: 1024,
4628
- maxAgeInEden: 10,
4629
- usePluginSyncV2: false,
4630
- handleFilenameCaseSensitive: false,
4631
- useSegmenter: false,
4632
- E2EEAlgorithm: E2EEAlgorithms.V2,
4633
- chunkSplitterVersion: ChunkAlgorithms.RabinKarp
4634
- };
4635
- var IncompatibleChanges = [
4636
- "encrypt",
4637
- "usePathObfuscation",
4638
- "useDynamicIterationCount",
4639
- "handleFilenameCaseSensitive"
4640
- ];
4641
- var CompatibleButLossyChanges = [
4642
- "hashAlg",
4643
- "customChunkSize",
4644
- "chunkSplitterVersion"
4645
- ];
4646
- var IncompatibleChangesInSpecificPattern = [];
4630
+ var TweakCompatibilityRules = Object.freeze([
4631
+ {
4632
+ key: "minimumChunkSize",
4633
+ templateValue: 20,
4634
+ reconstruction: "none"
4635
+ },
4636
+ {
4637
+ key: "longLineThreshold",
4638
+ templateValue: 250,
4639
+ reconstruction: "none"
4640
+ },
4641
+ {
4642
+ key: "encrypt",
4643
+ templateValue: false,
4644
+ reconstruction: "required"
4645
+ },
4646
+ {
4647
+ key: "usePathObfuscation",
4648
+ templateValue: false,
4649
+ reconstruction: "required"
4650
+ },
4651
+ {
4652
+ key: "enableCompression",
4653
+ templateValue: false,
4654
+ reconstruction: "none"
4655
+ },
4656
+ {
4657
+ key: "useEden",
4658
+ templateValue: false,
4659
+ reconstruction: "none"
4660
+ },
4661
+ {
4662
+ key: "customChunkSize",
4663
+ templateValue: 0,
4664
+ reconstruction: "recommended",
4665
+ compatibleLossyOrder: 1
4666
+ },
4667
+ {
4668
+ key: "useDynamicIterationCount",
4669
+ templateValue: false,
4670
+ reconstruction: "required"
4671
+ },
4672
+ {
4673
+ key: "hashAlg",
4674
+ templateValue: "xxhash64",
4675
+ reconstruction: "recommended",
4676
+ compatibleLossyOrder: 0
4677
+ },
4678
+ {
4679
+ key: "enableChunkSplitterV2",
4680
+ templateValue: false,
4681
+ reconstruction: "none"
4682
+ },
4683
+ {
4684
+ key: "maxChunksInEden",
4685
+ templateValue: 10,
4686
+ reconstruction: "none"
4687
+ },
4688
+ {
4689
+ key: "maxTotalLengthInEden",
4690
+ templateValue: 1024,
4691
+ reconstruction: "none"
4692
+ },
4693
+ {
4694
+ key: "maxAgeInEden",
4695
+ templateValue: 10,
4696
+ reconstruction: "none"
4697
+ },
4698
+ {
4699
+ key: "usePluginSyncV2",
4700
+ templateValue: false,
4701
+ reconstruction: "none",
4702
+ knownDefault: false
4703
+ },
4704
+ {
4705
+ key: "handleFilenameCaseSensitive",
4706
+ templateValue: false,
4707
+ reconstruction: "required",
4708
+ knownDefault: false
4709
+ },
4710
+ {
4711
+ key: "useSegmenter",
4712
+ templateValue: false,
4713
+ reconstruction: "none"
4714
+ },
4715
+ {
4716
+ key: "E2EEAlgorithm",
4717
+ templateValue: E2EEAlgorithms.V2,
4718
+ reconstruction: "none",
4719
+ knownDefault: DEFAULT_SETTINGS.E2EEAlgorithm
4720
+ },
4721
+ {
4722
+ key: "chunkSplitterVersion",
4723
+ templateValue: ChunkAlgorithms.RabinKarp,
4724
+ reconstruction: "recommended",
4725
+ knownDefault: DEFAULT_SETTINGS.chunkSplitterVersion,
4726
+ compatibleLossyOrder: 2
4727
+ }
4728
+ ]);
4729
+ var TweakValuesShouldMatchedTemplate = Object.fromEntries(TweakCompatibilityRules.map(({ key, templateValue }) => [key, templateValue]));
4730
+ [...TweakCompatibilityRules.filter(({ reconstruction }) => reconstruction === "required").map(({ key }) => key)];
4731
+ TweakCompatibilityRules.filter((rule) => "compatibleLossyOrder" in rule).slice().sort((left, right) => left.compatibleLossyOrder - right.compatibleLossyOrder).map(({ key }) => key);
4732
+ TweakCompatibilityRules.flatMap((rule) => (rule.specificPatterns ?? []).map((pattern) => ({
4733
+ key: rule.key,
4734
+ ...Object.prototype.hasOwnProperty.call(pattern, "from") ? { from: pattern.from } : {},
4735
+ ...Object.prototype.hasOwnProperty.call(pattern, "to") ? { to: pattern.to } : {},
4736
+ ...pattern.reconstruction === "recommended" ? { isRecommendation: true } : {}
4737
+ })));
4647
4738
  var TweakValuesRecommendedTemplate = {
4648
4739
  useIgnoreFiles: false,
4649
4740
  useCustomRequestHandler: false,
@@ -4663,12 +4754,7 @@ var TweakValuesRecommendedTemplate = {
4663
4754
  E2EEAlgorithm: E2EEAlgorithms.V2,
4664
4755
  chunkSplitterVersion: ChunkAlgorithms.RabinKarp
4665
4756
  };
4666
- var TweakValuesDefault = {
4667
- usePluginSyncV2: false,
4668
- E2EEAlgorithm: DEFAULT_SETTINGS.E2EEAlgorithm,
4669
- chunkSplitterVersion: DEFAULT_SETTINGS.chunkSplitterVersion,
4670
- tweakModified: DEFAULT_SETTINGS.tweakModified
4671
- };
4757
+ ({ ...Object.fromEntries(TweakCompatibilityRules.filter((rule) => "knownDefault" in rule && rule.key !== "handleFilenameCaseSensitive").map(({ key, knownDefault }) => [key, knownDefault])) }), DEFAULT_SETTINGS.tweakModified;
4672
4758
  var TweakValuesTemplate = {
4673
4759
  ...TweakValuesRecommendedTemplate,
4674
4760
  ...TweakValuesShouldMatchedTemplate,
@@ -6526,6 +6612,28 @@ var AllHandler = class extends BooleanHandlerBase {
6526
6612
  return true;
6527
6613
  }
6528
6614
  };
6615
+ var AllWithResultHandler = class extends MultiBinder {
6616
+ /**
6617
+ * Invokes every handler in order. The first non-boolean continuation result
6618
+ * is retained, but every remaining handler can still reject the operation.
6619
+ * @param args The arguments to pass to the handlers.
6620
+ * @returns False after any failure, otherwise the retained result or true.
6621
+ */
6622
+ async invoke(...args) {
6623
+ let aggregateResult = true;
6624
+ const callbacks = [...this._callbacks];
6625
+ for (const callback of callbacks) try {
6626
+ const result = await Promise.resolve(callback(...args));
6627
+ if (result === false) return false;
6628
+ if (aggregateResult === true && result !== true) aggregateResult = result;
6629
+ } catch (error) {
6630
+ Logger(`AllWithResultHandler ${this._name} treated error as failure!`, 16);
6631
+ Logger(error, 16);
6632
+ return false;
6633
+ }
6634
+ return aggregateResult;
6635
+ }
6636
+ };
6529
6637
  var SettledAllHandler = class extends BooleanHandlerBase {
6530
6638
  /**
6531
6639
  * Invokes every handler in order, treating a false result or an exception
@@ -6619,6 +6727,9 @@ function allSettledFunction(name) {
6619
6727
  function bailFirstFailureFunction(name) {
6620
6728
  return getMultipleBound(new AllHandler(name ?? "bailFirstFailureFunction"));
6621
6729
  }
6730
+ function bailFirstFailureWithResultFunction(name) {
6731
+ return getMultipleBound(new AllWithResultHandler(name ?? "bailFirstFailureWithResultFunction"));
6732
+ }
6622
6733
  function allParallelFunction(name) {
6623
6734
  return getMultipleBound(new ParallelAllHandler(name ?? "allParallelFunction"));
6624
6735
  }
@@ -6683,6 +6794,16 @@ function handlers() {
6683
6794
  return bailFirstFailureFunction(String(name));
6684
6795
  },
6685
6796
  /**
6797
+ * Create a handler that preserves a non-boolean continuation result, but
6798
+ * still invokes later handlers so that false results and exceptions
6799
+ * can reject the operation.
6800
+ * @param name
6801
+ * @returns
6802
+ */
6803
+ bailFirstFailureWithResult(name) {
6804
+ return bailFirstFailureWithResultFunction(String(name));
6805
+ },
6806
+ /**
6686
6807
  * Create a handler that invokes all added handler functions sequentially until one returns true.
6687
6808
  * @param name
6688
6809
  * @returns
@@ -6925,7 +7046,7 @@ var DatabaseEventService = class extends ServiceBase {
6925
7046
  * @param reopenDatabase Whether to reopen the database if it is already open.
6926
7047
  * @param ignoreSuspending Whether to ignore any suspending state.
6927
7048
  */
6928
- initialiseDatabase = handlers().bailFirstFailure("initialiseDatabase");
7049
+ initialiseDatabase = handlers().bailFirstFailureWithResult("initialiseDatabase");
6929
7050
  };
6930
7051
  //#endregion
6931
7052
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/services/implements/injectable/InjectableDatabaseEventService.js
@@ -7132,7 +7253,7 @@ function createReplicationReadinessEvaluator(dependencies) {
7132
7253
  name: "application-ready",
7133
7254
  evaluate: () => {
7134
7255
  if (gates.isApplicationReady()) return true;
7135
- diagnostics.log("Not ready");
7256
+ diagnostics.log("Replication is not ready because application initialisation has not completed.");
7136
7257
  return false;
7137
7258
  }
7138
7259
  },
@@ -7623,29 +7744,32 @@ var ReplicationService = class extends ServiceBase {
7623
7744
  *
7624
7745
  * Each attempt owns a separate reservation. Compatibility recovery runs
7625
7746
  * between those reservations, and a retry is admitted only when the exact
7626
- * first-attempt context remains active. Both attempts use one detached
7627
- * settings snapshot.
7747
+ * first-attempt context remains active. Each attempt uses a detached settings
7748
+ * snapshot, and a compatibility retry captures its snapshot after recovery.
7628
7749
  */
7629
7750
  async performDirectionalReplication(direction, showingNotice, admission = DIRECTIONAL_REPLICATION_ADMISSION.ORDINARY) {
7630
7751
  if (direction === DIRECTIONAL_REPLICATION.UPLOAD && !await this.onBeforeReplicate(showingNotice)) {
7631
7752
  this._log(this.context.translate("Replicator.Message.SomeModuleFailed"), 64);
7632
7753
  return false;
7633
7754
  }
7634
- const detachedSetting = asCopy(this.settingService.currentSettings());
7635
- if (admission === DIRECTIONAL_REPLICATION_ADMISSION.EXPLICIT_REBUILD) detachedSetting.versionUpFlash = "";
7636
- const setting = Object.freeze(detachedSetting);
7755
+ const captureSetting = () => {
7756
+ const detachedSetting = asCopy(this.settingService.currentSettings());
7757
+ if (admission === DIRECTIONAL_REPLICATION_ADMISSION.EXPLICIT_REBUILD) detachedSetting.versionUpFlash = "";
7758
+ return Object.freeze(detachedSetting);
7759
+ };
7760
+ const setting = captureSetting();
7637
7761
  let expectedContext;
7638
- const run = async () => {
7762
+ const run = async (attemptSetting) => {
7639
7763
  const admitted = await this.replicatorService.runWithActiveReplicatorContext((context) => {
7640
7764
  if (expectedContext && context !== expectedContext) return replicationBlocked("not-ready");
7641
7765
  expectedContext ??= context;
7642
- return runDirectionalReplication(context, setting, direction, showingNotice);
7766
+ return runDirectionalReplication(context, attemptSetting, direction, showingNotice);
7643
7767
  });
7644
7768
  if (admitted) return admitted;
7645
7769
  this._log(`Active replicator not found during directional ${direction}`, 64);
7646
7770
  return replicationBlocked("no-active-replicator");
7647
7771
  };
7648
- const outcome = await run();
7772
+ const outcome = await run(setting);
7649
7773
  if (isReplicationCompleted(outcome)) return true;
7650
7774
  if (outcome.status !== "failed") return false;
7651
7775
  const failedContext = expectedContext;
@@ -7655,7 +7779,7 @@ var ReplicationService = class extends ServiceBase {
7655
7779
  setting,
7656
7780
  outcome
7657
7781
  });
7658
- return await this.checkConnectionFailure(failure) === "CHECKAGAIN" && isReplicationCompleted(await run());
7782
+ return await this.checkConnectionFailure(failure) === "CHECKAGAIN" && isReplicationCompleted(await run(captureSetting()));
7659
7783
  }
7660
7784
  async replicateAllToRemote(showingNotice = false) {
7661
7785
  if (!this.appLifecycleService.isReady()) return false;
@@ -8285,7 +8409,7 @@ var VaultService = class extends ServiceBase {
8285
8409
  * @param showingNotice Whether to show a notice to the user.
8286
8410
  * @param ignoreSuspending Whether to ignore any suspending state.
8287
8411
  */
8288
- scanVault = handlers().bailFirstFailure("scanVault");
8412
+ scanVault = handlers().bailFirstFailureWithResult("scanVault");
8289
8413
  /**
8290
8414
  * Check if a file is ignored by the ignore file (e.g., .gitignore, .obsidianignore).
8291
8415
  * @param file The file path or file info stub to check.
@@ -8294,7 +8418,7 @@ var VaultService = class extends ServiceBase {
8294
8418
  /**
8295
8419
  * Check if a file is a target file for synchronisation.
8296
8420
  * @param file The file path or file info stub to check.
8297
- * @param keepFileCheckList Whether to keep the file in the check list.
8421
+ * @param options Optional selection inspection without filename collision rejection.
8298
8422
  */
8299
8423
  isTargetFile = handlers().bailFirstFailure("isTargetFile");
8300
8424
  /**
@@ -8466,10 +8590,18 @@ var PathServiceCompat = class extends PathService {
8466
8590
  //#endregion
8467
8591
  //#region ../../../node_modules/fflate/lib/node.cjs
8468
8592
  var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((exports) => {
8593
+ exports.deflate = deflate;
8594
+ exports.inflate = inflate;
8595
+ exports.gzip = gzip;
8596
+ exports.compress = gzip;
8597
+ exports.gzip = gzip;
8598
+ exports.compress = gzip;
8599
+ var _a;
8469
8600
  var Worker;
8601
+ var isMarkedAsUntransferable;
8470
8602
  var workerAdd = ";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global";
8471
8603
  try {
8472
- Worker = require("worker_threads").Worker;
8604
+ _a = require("worker_threads"), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable;
8473
8605
  } catch (e) {}
8474
8606
  var node_worker_1 = {};
8475
8607
  node_worker_1["default"] = Worker ? function(c, _, msg, transfer, cb) {
@@ -8481,6 +8613,9 @@ var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((expo
8481
8613
  }).on("exit", function(c) {
8482
8614
  if (c && !done) cb(/* @__PURE__ */ new Error("exited with code " + c), null);
8483
8615
  });
8616
+ if (isMarkedAsUntransferable) transfer = transfer.filter(function(t) {
8617
+ return !isMarkedAsUntransferable(t);
8618
+ });
8484
8619
  w.postMessage(msg, transfer);
8485
8620
  w.terminate = function() {
8486
8621
  done = true;
@@ -9099,6 +9234,28 @@ var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((expo
9099
9234
  }
9100
9235
  return slc(o, 0, pre + shft(pos) + post);
9101
9236
  };
9237
+ var crct = /*#__PURE__*/ (function() {
9238
+ var t = new Int32Array(256);
9239
+ for (var i = 0; i < 256; ++i) {
9240
+ var c = i, k = 9;
9241
+ while (--k) c = (c & 1 && -306674912) ^ c >>> 1;
9242
+ t[i] = c;
9243
+ }
9244
+ return t;
9245
+ })();
9246
+ var crc = function() {
9247
+ var c = -1;
9248
+ return {
9249
+ p: function(d) {
9250
+ var cr = c;
9251
+ for (var i = 0; i < d.length; ++i) cr = crct[cr & 255 ^ d[i]] ^ cr >>> 8;
9252
+ c = cr;
9253
+ },
9254
+ d: function() {
9255
+ return ~c;
9256
+ }
9257
+ };
9258
+ };
9102
9259
  var dopt = function(dat, opt, pre, post, st) {
9103
9260
  if (!st) {
9104
9261
  st = { l: 1 };
@@ -9219,6 +9376,15 @@ var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((expo
9219
9376
  pbf
9220
9377
  ];
9221
9378
  };
9379
+ var gze = function() {
9380
+ return [
9381
+ gzh,
9382
+ gzhl,
9383
+ wbytes,
9384
+ crc,
9385
+ crct
9386
+ ];
9387
+ };
9222
9388
  var pbf = function(msg) {
9223
9389
  return postMessage(msg, [msg.buffer]);
9224
9390
  };
@@ -9238,6 +9404,21 @@ var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((expo
9238
9404
  w.terminate();
9239
9405
  };
9240
9406
  };
9407
+ var wbytes = function(d, b, v) {
9408
+ for (; v; ++b) d[b] = v, v >>>= 8;
9409
+ };
9410
+ var gzh = function(c, o) {
9411
+ var fn = o.filename;
9412
+ c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3;
9413
+ if (o.mtime != 0) wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1e3));
9414
+ if (fn) {
9415
+ c[3] = 8;
9416
+ for (var i = 0; i <= fn.length; ++i) c[i + 10] = fn.charCodeAt(i);
9417
+ }
9418
+ };
9419
+ var gzhl = function(o) {
9420
+ return 10 + (o.filename ? o.filename.length + 1 : 0);
9421
+ };
9241
9422
  function deflate(data, opts, cb) {
9242
9423
  if (!cb) cb = opts, opts = {};
9243
9424
  if (typeof cb != "function") err(7);
@@ -9245,7 +9426,6 @@ var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((expo
9245
9426
  return pbf(deflateSync(ev.data[0], ev.data[1]));
9246
9427
  }, 0, cb);
9247
9428
  }
9248
- exports.deflate = deflate;
9249
9429
  /**
9250
9430
  * Compresses data with DEFLATE without any wrapper
9251
9431
  * @param data The data to compress
@@ -9262,16 +9442,35 @@ var require_node = /* @__PURE__ */ require_stream_collector.__commonJSMin(((expo
9262
9442
  return pbf(inflateSync(ev.data[0], gopt(ev.data[1])));
9263
9443
  }, 1, cb);
9264
9444
  }
9265
- exports.inflate = inflate;
9266
- /**
9267
- * Expands DEFLATE data with no wrapper
9268
- * @param data The data to decompress
9269
- * @param opts The decompression options
9270
- * @returns The decompressed version of the data
9271
- */
9272
9445
  function inflateSync(data, opts) {
9273
9446
  return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
9274
9447
  }
9448
+ function gzip(data, opts, cb) {
9449
+ if (!cb) cb = opts, opts = {};
9450
+ if (typeof cb != "function") err(7);
9451
+ return cbify(data, opts, [
9452
+ bDflt,
9453
+ gze,
9454
+ function() {
9455
+ return [gzipSync];
9456
+ }
9457
+ ], function(ev) {
9458
+ return pbf(gzipSync(ev.data[0], ev.data[1]));
9459
+ }, 2, cb);
9460
+ }
9461
+ /**
9462
+ * Compresses data with GZIP
9463
+ * @param data The data to compress
9464
+ * @param opts The compression options
9465
+ * @returns The gzipped version of the data
9466
+ */
9467
+ function gzipSync(data, opts) {
9468
+ if (!opts) opts = {};
9469
+ var c = crc(), l = data.length;
9470
+ c.p(data);
9471
+ var d = dopt(data, opts, gzhl(opts), 8), s = d.length;
9472
+ return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;
9473
+ }
9275
9474
  var td = typeof TextDecoder != "undefined" && /*#__PURE__*/ new TextDecoder();
9276
9475
  try {
9277
9476
  td.decode(et, { stream: true });
@@ -11360,10 +11559,10 @@ var HeadlessAPIService = class extends InjectableAPIService {
11360
11559
  return "headless-app";
11361
11560
  }
11362
11561
  getAppVersion() {
11363
- return `1.0.24`;
11562
+ return `1.0.28`;
11364
11563
  }
11365
11564
  getPluginVersion() {
11366
- return `1.0.24`;
11565
+ return `1.0.28`;
11367
11566
  }
11368
11567
  getPlatform() {
11369
11568
  return "server";
@@ -24667,6 +24866,7 @@ var allMessages = {
24667
24866
  zh: "等待就绪...",
24668
24867
  "zh-tw": "正在等待就緒⋯"
24669
24868
  },
24869
+ "moduleLog.pathComponentTooLong": { def: "This path contains a file or folder name longer than ${maxBytes} UTF-8 bytes. It may not work on some Android and Linux file systems." },
24670
24870
  "moduleLog.showLog": {
24671
24871
  def: "Show Log",
24672
24872
  es: "Mostrar registro",
@@ -30781,6 +30981,7 @@ var allMessages = {
30781
30981
  zh: "Use Remote Configuration",
30782
30982
  "zh-tw": "使用遠端設定"
30783
30983
  },
30984
+ "Ui.Common.LocalDatabaseInitialisationFailed": { def: "Self-hosted LiveSync cannot synchronise. Generate a report to review the detailed log." },
30784
30985
  "Ui.Common.Signal.Caution": {
30785
30986
  def: "CAUTION",
30786
30987
  es: "PRECAUCIÓN",
@@ -30809,6 +31010,7 @@ var allMessages = {
30809
31010
  zh: "警告",
30810
31011
  "zh-tw": "警告"
30811
31012
  },
31013
+ "Ui.Common.SomeFilesCouldNotBeSynchronised": { def: "Not all files could be synchronised. Check the affected files. Generate a report to review the detailed log." },
30812
31014
  "Ui.Settings.Advanced.LocalDatabaseTweak": {
30813
31015
  def: "Local Database Tweak",
30814
31016
  es: "Ajuste fino de la base de datos local",
@@ -33520,7 +33722,8 @@ function isAcceptedInFilenameDuplicationFactory(host, log) {
33520
33722
  return true;
33521
33723
  }
33522
33724
  });
33523
- return async function isAcceptedInFilenameDuplication(file) {
33725
+ return async function isAcceptedInFilenameDuplication(file, options) {
33726
+ if (options?.skipCaseCollisionCheck) return true;
33524
33727
  const fileCountMap = (await fileCountMapComputed.update(host.services.fileProcessing.totalStorageFileEventCount)).value;
33525
33728
  const filepath = getStoragePathFromUXFileInfo(file);
33526
33729
  const lc = filepath.toLowerCase();
@@ -33702,62 +33905,119 @@ var AbstractModule = class {
33702
33905
  }
33703
33906
  };
33704
33907
  //#endregion
33705
- //#region ../../modules/coreFeatures/ModuleConflictChecker.ts
33706
- var ModuleConflictChecker = class extends AbstractModule {
33707
- constructor(..._args) {
33708
- super(..._args);
33709
- this.conflictResolveQueue = new QueueProcessor(async (filenames) => {
33710
- const filename = filenames[0];
33711
- return await this.services.conflict.resolve(filename);
33712
- }, {
33713
- suspended: false,
33714
- batchSize: 1,
33715
- concurrentLimit: 10,
33716
- delay: 0,
33717
- keepResultUntilDownstreamConnected: false
33718
- }).replaceEnqueueProcessor((queue, newEntity) => {
33719
- sendValue("cancel-resolve-conflict:" + newEntity, true);
33720
- return [...[...queue].filter((e) => e != newEntity), newEntity];
33721
- });
33722
- this.conflictCheckQueue = new QueueProcessor((files) => {
33723
- const filename = files[0];
33724
- return Promise.resolve([filename]);
33725
- }, {
33726
- suspended: false,
33727
- batchSize: 1,
33728
- concurrentLimit: 10,
33729
- delay: 0,
33730
- keepResultUntilDownstreamConnected: true,
33731
- pipeTo: this.conflictResolveQueue,
33732
- totalRemainingReactiveSource: this.services.conflict.conflictProcessQueueCount
33908
+ //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/models/tweak.compatibility.js
33909
+ var hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
33910
+ function snapshotTweakValues(values) {
33911
+ const snapshot = {};
33912
+ for (const key of Object.keys(TweakValuesTemplate)) if (hasOwn(values, key)) snapshot[key] = values[key];
33913
+ return Object.freeze(snapshot);
33914
+ }
33915
+ function assessedValue(values, key, knownDefault) {
33916
+ const present = hasOwn(values, key);
33917
+ const rawValue = values[key];
33918
+ return Object.freeze({
33919
+ present,
33920
+ rawValue,
33921
+ effectiveValue: rawValue === void 0 ? knownDefault : rawValue
33922
+ });
33923
+ }
33924
+ function highestReconstruction(current, next) {
33925
+ if (current === "required" || next === "required") return "required";
33926
+ return "recommended";
33927
+ }
33928
+ function reconstructionForTransition(key, from, to) {
33929
+ const rule = TweakCompatibilityRules.find((candidate) => candidate.key === key);
33930
+ if (!rule) return "none";
33931
+ let reconstruction = rule.reconstruction;
33932
+ const extensibleRule = rule;
33933
+ for (const pattern of extensibleRule.specificPatterns ?? []) {
33934
+ const matchesFrom = hasOwn(pattern, "from") && pattern.from === from;
33935
+ const matchesTo = hasOwn(pattern, "to") && pattern.to === to;
33936
+ if (matchesFrom || matchesTo) reconstruction = highestReconstruction(reconstruction, pattern.reconstruction);
33937
+ }
33938
+ return reconstruction;
33939
+ }
33940
+ function transition(entries, sourceSide, targetSide) {
33941
+ const changes = {};
33942
+ const reasons = [];
33943
+ let reconstruction = "none";
33944
+ for (const entry of entries) {
33945
+ const source = entry[sourceSide];
33946
+ const target = entry[targetSide];
33947
+ const sourceAdvertised = source.present && source.rawValue !== void 0;
33948
+ const targetAdvertised = target.present && target.rawValue !== void 0;
33949
+ const effectiveValueDiffers = source.effectiveValue !== target.effectiveValue;
33950
+ const shouldFillMissingTarget = !targetAdvertised && sourceAdvertised;
33951
+ if (source.effectiveValue === void 0 || !effectiveValueDiffers && !shouldFillMissingTarget) continue;
33952
+ changes[entry.key] = source.effectiveValue;
33953
+ if (entry.relation === "equal") continue;
33954
+ const effect = reconstructionForTransition(entry.key, target.effectiveValue, source.effectiveValue);
33955
+ if (effect === "none") continue;
33956
+ const reason = Object.freeze({
33957
+ key: entry.key,
33958
+ reconstruction: effect
33733
33959
  });
33960
+ reasons.push(reason);
33961
+ reconstruction = highestReconstruction(reconstruction, reason.reconstruction);
33734
33962
  }
33735
- async _queueConflictCheckIfOpen(file) {
33736
- const path = file;
33737
- if (this.settings.checkConflictOnlyOnOpen) {
33738
- const af = this.services.vault.getActiveFilePath();
33739
- if (af && af != path) {
33740
- this._log(`${file} is conflicted, merging process has been postponed.`, 64);
33741
- return;
33742
- }
33743
- }
33744
- await this.services.conflict.queueCheckFor(path);
33745
- }
33746
- async _queueConflictCheck(file) {
33747
- const optionalConflictResult = await this.services.conflict.getOptionalConflictCheckMethod(file);
33748
- if (optionalConflictResult == true) return;
33749
- else if (optionalConflictResult === "newer") await this.services.conflict.resolveByNewest(file);
33750
- else this.conflictCheckQueue.enqueue(file);
33751
- }
33752
- _waitForAllConflictProcessed() {
33753
- return this.conflictResolveQueue.waitForAllProcessed();
33754
- }
33755
- onBindFunction(core, services) {
33756
- services.conflict.queueCheckForIfOpen.setHandler(this._queueConflictCheckIfOpen.bind(this));
33757
- services.conflict.queueCheckFor.setHandler(this._queueConflictCheck.bind(this));
33758
- services.conflict.ensureAllProcessed.setHandler(this._waitForAllConflictProcessed.bind(this));
33963
+ return Object.freeze({
33964
+ changes: Object.freeze(changes),
33965
+ reconstruction,
33966
+ reasons: Object.freeze(reasons)
33967
+ });
33968
+ }
33969
+ function assessTweakCompatibility(current, preferred) {
33970
+ const currentValues = snapshotTweakValues(current);
33971
+ const preferredValues = snapshotTweakValues(preferred);
33972
+ let representationDiffers = false;
33973
+ const entries = TweakCompatibilityRules.map((rule) => {
33974
+ const knownDefault = "knownDefault" in rule ? rule.knownDefault : void 0;
33975
+ const currentValue = assessedValue(currentValues, rule.key, knownDefault);
33976
+ const preferredValue = assessedValue(preferredValues, rule.key, knownDefault);
33977
+ const currentAdvertised = currentValue.present && currentValue.rawValue !== void 0;
33978
+ const preferredAdvertised = preferredValue.present && preferredValue.rawValue !== void 0;
33979
+ let relation;
33980
+ if ((!currentAdvertised || !preferredAdvertised) && knownDefault === void 0) relation = "unadvertised";
33981
+ else relation = currentValue.effectiveValue === preferredValue.effectiveValue ? "equal" : "different";
33982
+ if (currentValue.present !== preferredValue.present || currentValue.rawValue !== preferredValue.rawValue) representationDiffers = true;
33983
+ return Object.freeze({
33984
+ key: rule.key,
33985
+ current: currentValue,
33986
+ preferred: preferredValue,
33987
+ relation
33988
+ });
33989
+ });
33990
+ const frozenEntries = Object.freeze(entries);
33991
+ const differences = frozenEntries.filter(({ relation }) => relation === "different");
33992
+ const compatibleLossyKeys = new Set(TweakCompatibilityRules.filter((rule) => "compatibleLossyOrder" in rule).map(({ key }) => key));
33993
+ return Object.freeze({
33994
+ alignment: differences.length === 0 ? "matched" : "mismatched",
33995
+ representationDiffers,
33996
+ entries: frozenEntries,
33997
+ adoptPreferred: transition(frozenEntries, "preferred", "current"),
33998
+ adoptCurrent: transition(frozenEntries, "current", "preferred"),
33999
+ onlyCompatibleLossyDifferences: differences.length > 0 && differences.every(({ key }) => compatibleLossyKeys.has(key)) && !frozenEntries.some(({ relation }) => relation === "unadvertised"),
34000
+ currentValues,
34001
+ preferredValues
34002
+ });
34003
+ }
34004
+ //#endregion
34005
+ //#region ../../common/ownedRemoteResource.ts
34006
+ /**
34007
+ * Run a finite operation with a flow-owned remote resource and release it
34008
+ * after either success or failure.
34009
+ *
34010
+ * Resource implementations make `dispose()` idempotent. This helper makes the
34011
+ * caller's ownership boundary explicit and prevents finite flows from leaking
34012
+ * a provider-owned resource when their operation rejects.
34013
+ */
34014
+ async function withOwnedRemoteResource(resource, operation) {
34015
+ try {
34016
+ return await operation(resource);
34017
+ } finally {
34018
+ await resource.dispose();
33759
34019
  }
33760
- };
34020
+ }
33761
34021
  //#endregion
33762
34022
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/replication/RemoteResource.js
33763
34023
  var REMOTE_RESOURCE_KINDS = Object.freeze({
@@ -33787,184 +34047,23 @@ var CENTRAL_COMPATIBILITY_REJECTION_REASONS = Object.freeze({
33787
34047
  });
33788
34048
  var CENTRAL_COMPATIBILITY_NOT_ASSESSED = Object.freeze({ status: CENTRAL_COMPATIBILITY_STATUSES.NOT_ASSESSED });
33789
34049
  var CENTRAL_COMPATIBILITY_ACCEPTED = Object.freeze({ status: CENTRAL_COMPATIBILITY_STATUSES.ACCEPTED });
33790
- function centralCompatibilityRejected(reason, preferredTweakValue) {
34050
+ function centralCompatibilityRejected(reason, preferredTweakValue, tweakAssessment) {
33791
34051
  return Object.freeze({
33792
34052
  status: CENTRAL_COMPATIBILITY_STATUSES.REJECTED,
33793
34053
  reason,
33794
- ...preferredTweakValue === void 0 ? {} : { preferredTweakValue: Object.freeze({ ...preferredTweakValue }) }
34054
+ ...preferredTweakValue === void 0 ? {} : { preferredTweakValue: Object.freeze({ ...preferredTweakValue }) },
34055
+ ...tweakAssessment === void 0 ? {} : { tweakAssessment }
33795
34056
  });
33796
34057
  }
33797
34058
  function centralCompatibilityRecoveryHint(decision) {
33798
34059
  if (decision.status !== CENTRAL_COMPATIBILITY_STATUSES.REJECTED) return void 0;
33799
34060
  return Object.freeze({
33800
34061
  reason: decision.reason,
33801
- ...decision.preferredTweakValue === void 0 ? {} : { preferredTweakValue: decision.preferredTweakValue }
34062
+ ...decision.preferredTweakValue === void 0 ? {} : { preferredTweakValue: decision.preferredTweakValue },
34063
+ ...decision.tweakAssessment === void 0 ? {} : { tweakAssessment: decision.tweakAssessment }
33802
34064
  });
33803
34065
  }
33804
34066
  //#endregion
33805
- //#region ../../modules/coreFeatures/ModuleConflictResolver.ts
33806
- var ModuleConflictResolver = class extends AbstractModule {
33807
- async _resolveConflictByDeletingRev(path, deleteRevision, subTitle = "", showNotice = true) {
33808
- const title = `Resolving ${subTitle ? `[${subTitle}]` : ""}:`;
33809
- if (!await this.core.fileHandler.deleteRevisionFromDB(path, deleteRevision)) {
33810
- this._log(`${title} Could not delete conflicted revision ${displayRev(deleteRevision)} of ${path}`, 64);
33811
- return MISSING_OR_ERROR;
33812
- }
33813
- eventHub.emitEvent(EVENT_CONFLICT_CANCELLED, path);
33814
- this._log(`${title} Conflicted revision has been deleted ${displayRev(deleteRevision)} ${path}`, 32);
33815
- if ((await this.core.databaseFileAccess.getConflictedRevs(path)).length != 0) {
33816
- this._log(`${title} some conflicts are left in ${path}`, 32);
33817
- return AUTO_MERGED;
33818
- }
33819
- if (isPluginMetadata(path) || isCustomisationSyncMetadata(path)) {
33820
- this._log(`${title} ${path} is a plugin metadata file, no need to write to storage`, 32);
33821
- return AUTO_MERGED;
33822
- }
33823
- if (!await this.core.fileHandler.dbToStorage(path, stripAllPrefixes(path), true)) {
33824
- this._log(`Could not write the resolved content to the storage: ${path}`, 64);
33825
- return MISSING_OR_ERROR;
33826
- }
33827
- const level = subTitle.indexOf("same") !== -1 || !showNotice ? 32 : 64;
33828
- this._log(`${path} has been merged automatically`, level);
33829
- return AUTO_MERGED;
33830
- }
33831
- async checkConflictAndPerformAutoMerge(path) {
33832
- const ret = await this.localDatabase.tryAutoMerge(path, !this.settings.disableMarkdownAutoMerge);
33833
- if ("ok" in ret) return ret.ok;
33834
- if ("result" in ret) {
33835
- const p = ret.result;
33836
- if (!await this.core.databaseFileAccess.storeContent(path, p)) {
33837
- this._log(`Merged content cannot be stored:${path}`, 64);
33838
- return MISSING_OR_ERROR;
33839
- }
33840
- return await this.services.conflict.resolveByDeletingRevision(path, ret.conflictedRev, "Sensible");
33841
- }
33842
- const { rightRev, leftLeaf, rightLeaf } = ret;
33843
- if (leftLeaf == false) {
33844
- this._log(`could not get current revisions:${path}`, 64);
33845
- return MISSING_OR_ERROR;
33846
- }
33847
- if (rightLeaf == false) {
33848
- this._log(`could not read conflicted revision ${rightRev}:${path}`, 64);
33849
- return MISSING_OR_ERROR;
33850
- }
33851
- const isSame = leftLeaf.data == rightLeaf.data && leftLeaf.deleted == rightLeaf.deleted;
33852
- const isBinary = !isPlainText(path);
33853
- const alwaysNewer = this.settings.resolveConflictsByNewerFile;
33854
- if (isSame || isBinary || alwaysNewer) {
33855
- const result = compareMTime(leftLeaf.mtime, rightLeaf.mtime);
33856
- let loser = leftLeaf;
33857
- if (result != TARGET_IS_NEW) loser = rightLeaf;
33858
- const subTitle = [
33859
- `${isSame ? "same" : ""}`,
33860
- `${isBinary ? "binary" : ""}`,
33861
- `${alwaysNewer ? "alwaysNewer" : ""}`
33862
- ].filter((e) => e.trim()).join(",");
33863
- return await this.services.conflict.resolveByDeletingRevision(path, loser.rev, subTitle);
33864
- }
33865
- const dmp = new import_diff_match_patch.default();
33866
- const diff = dmp.diff_main(leftLeaf.data, rightLeaf.data);
33867
- dmp.diff_cleanupSemantic(diff);
33868
- this._log(`conflict(s) found:${path}`);
33869
- return {
33870
- left: leftLeaf,
33871
- right: rightLeaf,
33872
- diff
33873
- };
33874
- }
33875
- async _resolveConflict(filename) {
33876
- return await serialized(`conflict-resolve:${filename}`, async () => {
33877
- const conflictCheckResult = await this.checkConflictAndPerformAutoMerge(filename);
33878
- if (conflictCheckResult === NOT_CONFLICTED) {
33879
- eventHub.emitEvent(EVENT_CONFLICT_CANCELLED, filename);
33880
- this._log(`[conflict] Not conflicted or cancelled: ${filename}`, 16);
33881
- return;
33882
- }
33883
- if (conflictCheckResult === MISSING_OR_ERROR || conflictCheckResult === CANCELLED) {
33884
- this._log(`[conflict] Not conflicted or cancelled: ${filename}`, 16);
33885
- return;
33886
- }
33887
- if (conflictCheckResult === AUTO_MERGED) {
33888
- if (this.settings.syncAfterMerge && !this.services.appLifecycle.isSuspended()) await this.services.replication.replicateUnattendedByEvent({
33889
- trigger: "merge",
33890
- interaction: NO_INTERACTION
33891
- });
33892
- this._log("[conflict] Automatically merged, but we have to check it again");
33893
- await this.services.conflict.queueCheckFor(filename);
33894
- return;
33895
- }
33896
- if (this.settings.showMergeDialogOnlyOnActive) {
33897
- const af = this.services.vault.getActiveFilePath();
33898
- if (af && af != filename) {
33899
- this._log(`[conflict] ${filename} is conflicted. Merging process has been postponed to the file have got opened.`, 64);
33900
- return;
33901
- }
33902
- }
33903
- this._log("[conflict] Manual merge required!");
33904
- eventHub.emitEvent(EVENT_CONFLICT_CANCELLED, filename);
33905
- await this.services.conflict.resolveByUserInteraction(filename, conflictCheckResult);
33906
- });
33907
- }
33908
- async _anyResolveConflictByNewest(filename, showNotice = true) {
33909
- const currentRev = await this.core.databaseFileAccess.fetchEntryMeta(filename, void 0, true);
33910
- if (currentRev == false) {
33911
- this._log(`Could not get current revision of ${filename}`);
33912
- return Promise.resolve(false);
33913
- }
33914
- const revs = await this.core.databaseFileAccess.getConflictedRevs(filename);
33915
- if (revs.length == 0) return Promise.resolve(true);
33916
- const mTimeAndRev = [[currentRev.mtime, currentRev._rev], ...await Promise.all(revs.map(async (rev) => {
33917
- const leaf = await this.core.databaseFileAccess.fetchEntryMeta(filename, rev);
33918
- if (leaf == false) return [0, rev];
33919
- return [leaf.mtime, rev];
33920
- }))].sort((a, b) => {
33921
- const diff = b[0] - a[0];
33922
- if (diff == 0) return a[1].localeCompare(b[1], "en", { numeric: true });
33923
- return diff;
33924
- });
33925
- this._log(`Resolving conflict by newest: ${filename} (Newest: ${new Date(mTimeAndRev[0][0]).toLocaleString()}) (${mTimeAndRev.length} revisions exists)`);
33926
- for (let i = 1; i < mTimeAndRev.length; i++) {
33927
- this._log(`conflict: Deleting the older revision ${mTimeAndRev[i][1]} (${new Date(mTimeAndRev[i][0]).toLocaleString()}) of ${filename}`);
33928
- await this._resolveConflictByDeletingRev(filename, mTimeAndRev[i][1], "NEWEST", showNotice);
33929
- }
33930
- return true;
33931
- }
33932
- async _resolveAllConflictedFilesByNewerOnes() {
33933
- this._log(`Resolving conflicts by newer ones`, 64);
33934
- const files = await this.core.storageAccess.getFileNames();
33935
- let i = 0;
33936
- for (const file of files) {
33937
- i++;
33938
- if (i % 10 === 0) this._log(`Check and Processing ${i} / ${files.length}`, 64, "resolveAllConflictedFilesByNewerOnes");
33939
- await this._anyResolveConflictByNewest(file, false);
33940
- }
33941
- this._log(`Done!`, 64, "resolveAllConflictedFilesByNewerOnes");
33942
- }
33943
- onBindFunction(core, services) {
33944
- services.conflict.resolveByDeletingRevision.setHandler(this._resolveConflictByDeletingRev.bind(this));
33945
- services.conflict.resolve.setHandler(this._resolveConflict.bind(this));
33946
- services.conflict.resolveByNewest.setHandler(this._anyResolveConflictByNewest.bind(this));
33947
- services.conflict.resolveAllConflictedFilesByNewerOnes.setHandler(this._resolveAllConflictedFilesByNewerOnes.bind(this));
33948
- }
33949
- };
33950
- //#endregion
33951
- //#region ../../common/ownedRemoteResource.ts
33952
- /**
33953
- * Run a finite operation with a flow-owned remote resource and release it
33954
- * after either success or failure.
33955
- *
33956
- * Resource implementations make `dispose()` idempotent. This helper makes the
33957
- * caller's ownership boundary explicit and prevents finite flows from leaking
33958
- * a provider-owned resource when their operation rejects.
33959
- */
33960
- async function withOwnedRemoteResource(resource, operation) {
33961
- try {
33962
- return await operation(resource);
33963
- } finally {
33964
- await resource.dispose();
33965
- }
33966
- }
33967
- //#endregion
33968
34067
  //#region ../../modules/coreFeatures/ModuleResolveMismatchedTweaks.ts
33969
34068
  function canSetPreferredRemoteTweakSettings$1(replicator) {
33970
34069
  return "setPreferredRemoteTweakSettings" in replicator && typeof replicator.setPreferredRemoteTweakSettings === "function";
@@ -33983,10 +34082,37 @@ function valueToString(value) {
33983
34082
  if (typeof value === "object") return JSON.stringify(value);
33984
34083
  return `${value}`;
33985
34084
  }
34085
+ function definedTweaks(values) {
34086
+ return Object.fromEntries(Object.entries(values).filter(([key, value]) => key in TweakValuesTemplate && value !== void 0));
34087
+ }
34088
+ function settingsAfterAdoption(assessment, direction) {
34089
+ const comparedKeys = new Set(assessment.entries.map((entry) => entry.key));
34090
+ const source = direction === "adoptPreferred" ? assessment.preferredValues : assessment.currentValues;
34091
+ const target = direction === "adoptPreferred" ? assessment.currentValues : assessment.preferredValues;
34092
+ const recommendations = Object.fromEntries(Object.entries(source).filter(([key, value]) => !comparedKeys.has(key) && value !== void 0));
34093
+ return {
34094
+ ...definedTweaks(target),
34095
+ ...recommendations,
34096
+ ...assessment[direction].changes
34097
+ };
34098
+ }
34099
+ function mismatchTable(assessment, direction) {
34100
+ const reasons = direction ? assessment[direction].reasons : [...assessment.adoptPreferred.reasons, ...assessment.adoptCurrent.reasons];
34101
+ const consequenceKeys = new Set(reasons.map((reason) => reason.key));
34102
+ return $msg("TweakMismatchResolve.Table", { rows: assessment.entries.filter((entry) => entry.relation === "different" || consequenceKeys.has(entry.key)).map((entry) => $msg("TweakMismatchResolve.Table.Row", {
34103
+ name: localisedConfName(entry.key),
34104
+ self: valueToString(escapeMarkdownValue(entry.current.effectiveValue)),
34105
+ remote: valueToString(escapeMarkdownValue(entry.preferred.effectiveValue))
34106
+ })).join("\n") });
34107
+ }
34108
+ /** Kept only while resolving a decision; this can contain credentials and must never be logged. */
34109
+ function resolutionSettingsSignature(settings) {
34110
+ return JSON.stringify({
34111
+ ...settings,
34112
+ autoAcceptCompatibleTweak: settings.autoAcceptCompatibleTweak ?? true
34113
+ });
34114
+ }
33986
34115
  var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
33987
- _collectMismatchedTweakKeys(current, preferred) {
33988
- return Object.keys(TweakValuesShouldMatchedTemplate).filter((key) => current[key] !== preferred[key]);
33989
- }
33990
34116
  _selectNewerTweakSide(current, preferred) {
33991
34117
  Logger(`Modified: ${current.tweakModified} (current) vs ${preferred.tweakModified} (preferred)`);
33992
34118
  const currentModified = current.tweakModified;
@@ -33999,9 +34125,8 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
33999
34125
  if (preferredModified >= currentModified) return "REMOTE";
34000
34126
  return "CURRENT";
34001
34127
  }
34002
- async _shouldAutoAcceptCompatibleLossy(current, preferred, mismatchedKeys) {
34003
- if (mismatchedKeys.length === 0) return void 0;
34004
- if (!mismatchedKeys.every((key) => CompatibleButLossyChanges.indexOf(key) !== -1)) return void 0;
34128
+ async _shouldAutoAcceptCompatibleLossy(assessment) {
34129
+ if (!assessment.onlyCompatibleLossyDifferences) return void 0;
34005
34130
  let autoAcceptCompatibleTweak = this.settings.autoAcceptCompatibleTweak;
34006
34131
  if (this.settings.autoAcceptCompatibleTweak === void 0) {
34007
34132
  this.settings.autoAcceptCompatibleTweak = true;
@@ -34010,7 +34135,7 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
34010
34135
  Logger("Automatic alignment of compatible chunk settings has been enabled.");
34011
34136
  }
34012
34137
  if (autoAcceptCompatibleTweak !== true) return void 0;
34013
- return this._selectNewerTweakSide(current, preferred);
34138
+ return this._selectNewerTweakSide(assessment.currentValues, assessment.preferredValues);
34014
34139
  }
34015
34140
  /**
34016
34141
  * Hook before saving settings, to check if there are changes in tweak values, and if so,
@@ -34031,6 +34156,8 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
34031
34156
  async _anyAfterConnectCheckFailed(failure) {
34032
34157
  const recovery = failure.outcome.recoveryHint;
34033
34158
  if (recovery?.reason !== CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH || !recovery.preferredTweakValue) return false;
34159
+ if (!await this.services.replicator.runWithActiveReplicatorContext((activeContext) => activeContext === failure.context) || resolutionSettingsSignature(failure.setting) !== resolutionSettingsSignature(this.settings)) return true;
34160
+ const assessment = recovery.tweakAssessment ?? assessTweakCompatibility(failure.setting, recovery.preferredTweakValue);
34034
34161
  const ret = await this.services.tweakValue.askResolvingMismatched({ ...recovery.preferredTweakValue }, async (setting) => {
34035
34162
  let updated = false;
34036
34163
  await this.services.replicator.runWithActiveReplicatorContext(async (activeContext) => {
@@ -34040,103 +34167,83 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
34040
34167
  updated = true;
34041
34168
  });
34042
34169
  return updated;
34043
- });
34170
+ }, assessment);
34044
34171
  if (ret == "OK") return false;
34045
34172
  if (ret == "CHECKAGAIN") return "CHECKAGAIN";
34046
34173
  if (ret == "IGNORE") return true;
34047
34174
  }
34048
- async _checkAndAskResolvingMismatchedTweaks(preferred) {
34049
- const mine = extractObject(TweakValuesTemplate, this.settings);
34050
- const mismatchedKeys = this._collectMismatchedTweakKeys(mine, preferred);
34051
- const autoAcceptSide = await this._shouldAutoAcceptCompatibleLossy(mine, preferred, mismatchedKeys);
34052
- if (autoAcceptSide === "REMOTE") return [{
34053
- ...mine,
34054
- ...preferred
34055
- }, false];
34175
+ async _checkAndAskResolvingMismatchedTweaks(preferred, assessment = assessTweakCompatibility(this.settings, preferred)) {
34176
+ if (assessment.alignment === "matched") return [false, false];
34177
+ const acceptedSettings = settingsAfterAdoption(assessment, "adoptPreferred");
34178
+ const autoAcceptSide = await this._shouldAutoAcceptCompatibleLossy(assessment);
34179
+ if (autoAcceptSide === "REMOTE") return [acceptedSettings, false];
34056
34180
  if (autoAcceptSide === "CURRENT") return [true, false];
34057
- const items = Object.entries(TweakValuesShouldMatchedTemplate);
34058
- let rebuildRequired = false;
34059
- let rebuildRecommended = false;
34060
- const tableRows = [];
34061
- for (const v of items) {
34062
- const key = v[0];
34063
- const valueMine = escapeMarkdownValue(mine[key]);
34064
- const valuePreferred = escapeMarkdownValue(preferred[key]);
34065
- if (valueMine == valuePreferred) continue;
34066
- if (IncompatibleChanges.indexOf(key) !== -1) rebuildRequired = true;
34067
- for (const pattern of IncompatibleChangesInSpecificPattern) {
34068
- if (pattern.key !== key) continue;
34069
- const isFromConditionMet = "from" in pattern ? pattern.from === mine[key] : false;
34070
- const isToConditionMet = "to" in pattern ? pattern.to === preferred[key] : false;
34071
- if (isFromConditionMet || isToConditionMet) if (pattern.isRecommendation) rebuildRecommended = true;
34072
- else rebuildRequired = true;
34073
- }
34074
- if (CompatibleButLossyChanges.indexOf(key) !== -1) rebuildRecommended = true;
34075
- tableRows.push($msg("TweakMismatchResolve.Table.Row", {
34076
- name: localisedConfName(key),
34077
- self: valueToString(valueMine),
34078
- remote: valueToString(valuePreferred)
34079
- }));
34080
- }
34081
- const additionalMessage = rebuildRequired && this.core.settings.isConfigured ? $msg("TweakMismatchResolve.Message.WarningIncompatibleRebuildRequired") : "";
34082
- const additionalMessage2 = rebuildRecommended && this.core.settings.isConfigured ? $msg("TweakMismatchResolve.Message.WarningIncompatibleRebuildRecommended") : "";
34181
+ const localImpact = assessment.adoptPreferred.reconstruction;
34182
+ const remoteImpact = assessment.adoptCurrent.reconstruction;
34183
+ const requiresRebuild = localImpact === "required" || remoteImpact === "required";
34184
+ const recommendsRebuild = localImpact === "recommended" || remoteImpact === "recommended";
34185
+ const additionalMessage = requiresRebuild && this.settings.isConfigured ? $msg("TweakMismatchResolve.Message.WarningIncompatibleRebuildRequired") : "";
34186
+ const additionalMessage2 = recommendsRebuild && this.settings.isConfigured ? $msg("TweakMismatchResolve.Message.WarningIncompatibleRebuildRecommended") : "";
34083
34187
  const message = $msg("TweakMismatchResolve.Message.MainTweakResolving", {
34084
- table: $msg("TweakMismatchResolve.Table", { rows: tableRows.join("\n") }),
34085
- additionalMessage: [additionalMessage, additionalMessage2].filter((v) => v).join("\n")
34188
+ table: mismatchTable(assessment),
34189
+ additionalMessage: [additionalMessage, additionalMessage2].filter(Boolean).join("\n")
34086
34190
  });
34087
- const CHOICE_USE_REMOTE = $msg("TweakMismatchResolve.Action.UseRemote");
34088
- const CHOICE_USE_REMOTE_WITH_REBUILD = $msg("TweakMismatchResolve.Action.UseRemoteWithRebuild");
34089
- const CHOICE_USE_REMOTE_PREVENT_REBUILD = $msg("TweakMismatchResolve.Action.UseRemoteAcceptIncompatible");
34090
- const CHOICE_USE_MINE = $msg("TweakMismatchResolve.Action.UseMine");
34091
- const CHOICE_USE_MINE_WITH_REBUILD = $msg("TweakMismatchResolve.Action.UseMineWithRebuild");
34092
- const CHOICE_USE_MINE_PREVENT_REBUILD = $msg("TweakMismatchResolve.Action.UseMineAcceptIncompatible");
34093
- const CHOICE_DISMISS = $msg("TweakMismatchResolve.Action.Dismiss");
34094
- const CHOICE_AND_VALUES = [];
34095
- if (rebuildRequired) {
34096
- CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE_WITH_REBUILD, [preferred, true]]);
34097
- CHOICE_AND_VALUES.push([CHOICE_USE_MINE_WITH_REBUILD, [true, true]]);
34098
- CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE_PREVENT_REBUILD, [preferred, false]]);
34099
- CHOICE_AND_VALUES.push([CHOICE_USE_MINE_PREVENT_REBUILD, [true, false]]);
34100
- } else if (rebuildRecommended) {
34101
- CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE, [preferred, false]]);
34102
- CHOICE_AND_VALUES.push([CHOICE_USE_MINE, [true, false]]);
34103
- CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE_WITH_REBUILD, [preferred, true]]);
34104
- CHOICE_AND_VALUES.push([CHOICE_USE_MINE_WITH_REBUILD, [true, true]]);
34105
- } else {
34106
- CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE, [preferred, false]]);
34107
- CHOICE_AND_VALUES.push([CHOICE_USE_MINE, [true, false]]);
34108
- }
34109
- CHOICE_AND_VALUES.push([CHOICE_DISMISS, [false, false]]);
34110
- const CHOICES = Object.fromEntries(CHOICE_AND_VALUES);
34111
- const retKey = await this.core.confirm.askSelectStringDialogue(message, Object.keys(CHOICES), {
34191
+ const choices = {};
34192
+ const remoteChoices = {
34193
+ ordinary: $msg("TweakMismatchResolve.Action.UseRemote"),
34194
+ rebuild: $msg("TweakMismatchResolve.Action.UseRemoteWithRebuild"),
34195
+ accept: $msg("TweakMismatchResolve.Action.UseRemoteAcceptIncompatible")
34196
+ };
34197
+ const localChoices = {
34198
+ ordinary: $msg("TweakMismatchResolve.Action.UseMine"),
34199
+ rebuild: $msg("TweakMismatchResolve.Action.UseMineWithRebuild"),
34200
+ accept: $msg("TweakMismatchResolve.Action.UseMineAcceptIncompatible")
34201
+ };
34202
+ choices[localImpact === "required" ? remoteChoices.rebuild : remoteChoices.ordinary] = [acceptedSettings, localImpact === "required"];
34203
+ choices[remoteImpact === "required" ? localChoices.rebuild : localChoices.ordinary] = [true, remoteImpact === "required"];
34204
+ if (localImpact !== "none") choices[localImpact === "required" ? remoteChoices.accept : remoteChoices.rebuild] = [acceptedSettings, localImpact !== "required"];
34205
+ if (remoteImpact !== "none") choices[remoteImpact === "required" ? localChoices.accept : localChoices.rebuild] = [true, remoteImpact !== "required"];
34206
+ const dismiss = $msg("TweakMismatchResolve.Action.Dismiss");
34207
+ choices[dismiss] = [false, false];
34208
+ const retKey = await this.core.confirm.askSelectStringDialogue(message, Object.keys(choices), {
34112
34209
  title: $msg("TweakMismatchResolve.Title.TweakResolving"),
34113
34210
  timeout: 60,
34114
- defaultAction: CHOICE_DISMISS
34211
+ defaultAction: dismiss
34115
34212
  });
34116
- if (!retKey) return [false, false];
34117
- return CHOICES[retKey];
34118
- }
34119
- async _askResolvingMismatchedTweaks(preferredSource, updatePreferredRemote) {
34120
- const [conf, rebuildRequired] = await this.services.tweakValue.checkAndAskResolvingMismatched(preferredSource);
34213
+ return retKey && choices[retKey] || [false, false];
34214
+ }
34215
+ async _askResolvingMismatchedTweaks(preferredSource, updatePreferredRemote, assessment = assessTweakCompatibility(this.settings, preferredSource)) {
34216
+ const signature = resolutionSettingsSignature(this.settings);
34217
+ const publication = await this.services.replicator.acquireActiveReplicatorContext();
34218
+ if (resolutionSettingsSignature(this.settings) !== signature) return "IGNORE";
34219
+ const currentTweaks = JSON.stringify(extractObject(TweakValuesTemplate, this.settings));
34220
+ if (JSON.stringify(extractObject(TweakValuesTemplate, assessment.currentValues)) !== currentTweaks) return "IGNORE";
34221
+ const [conf, rebuildRequired] = await this.services.tweakValue.checkAndAskResolvingMismatched(preferredSource, assessment);
34121
34222
  if (!conf) return "IGNORE";
34122
- const updateRemote = async () => {
34123
- if (updatePreferredRemote) return await updatePreferredRemote(this.settings);
34223
+ if (await this.services.replicator.acquireActiveReplicatorContext() !== publication || resolutionSettingsSignature(this.settings) !== signature) return "IGNORE";
34224
+ const updateRemote = async (tweaks) => {
34225
+ const setting = {
34226
+ ...this.settings,
34227
+ ...definedTweaks(assessment.preferredValues),
34228
+ ...definedTweaks(tweaks)
34229
+ };
34230
+ if (updatePreferredRemote) return await updatePreferredRemote(setting);
34124
34231
  const candidate = this.core.replicator;
34125
34232
  if (typeof candidate.setPreferredRemoteTweakSettings !== "function") return false;
34126
- await candidate.setPreferredRemoteTweakSettings(this.settings);
34233
+ await candidate.setPreferredRemoteTweakSettings(setting);
34127
34234
  return true;
34128
34235
  };
34129
34236
  if (conf === true) {
34130
- if (!await updateRemote()) return "IGNORE";
34237
+ if (!await updateRemote(settingsAfterAdoption(assessment, "adoptCurrent"))) return "IGNORE";
34131
34238
  if (rebuildRequired) await this.core.rebuilder.$rebuildRemote();
34132
34239
  Logger($msg("TweakMismatchResolve.Message.remoteUpdated"), 64);
34133
34240
  return "CHECKAGAIN";
34134
34241
  }
34135
34242
  if (conf) {
34136
- Object.assign(this.settings, extractObject(TweakValuesTemplate, conf));
34243
+ Object.assign(this.settings, definedTweaks(conf));
34137
34244
  await this.services.setting.saveSettingData();
34138
34245
  if (!rebuildRequired) await this.localDatabase.managers.reinitialise();
34139
- if (!await updateRemote()) return "IGNORE";
34246
+ if (!await updateRemote(this.settings)) return "IGNORE";
34140
34247
  if (rebuildRequired) await this.core.rebuilder.$fetchLocal();
34141
34248
  Logger($msg("TweakMismatchResolve.Message.mineUpdated"), 64);
34142
34249
  return "CHECKAGAIN";
@@ -34164,7 +34271,12 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
34164
34271
  result: false,
34165
34272
  requireFetch: false
34166
34273
  };
34274
+ const signature = JSON.stringify(trialSetting);
34167
34275
  const preferred = await this.services.tweakValue.fetchRemotePreferred(trialSetting);
34276
+ if (JSON.stringify(trialSetting) !== signature) return {
34277
+ result: false,
34278
+ requireFetch: false
34279
+ };
34168
34280
  if (preferred.status === RemotePreferredTweakStatuses.AVAILABLE) return await this.services.tweakValue.askUseRemoteConfiguration(trialSetting, preferred.values);
34169
34281
  return {
34170
34282
  result: false,
@@ -34172,87 +34284,61 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
34172
34284
  };
34173
34285
  }
34174
34286
  async _askUseRemoteConfiguration(trialSetting, preferred) {
34175
- const localTweaks = extractObject(TweakValuesTemplate, this.settings);
34176
- const mismatchedKeys = this._collectMismatchedTweakKeys(localTweaks, preferred);
34177
- const autoAcceptSide = await this._shouldAutoAcceptCompatibleLossy(localTweaks, preferred, mismatchedKeys);
34178
- if (autoAcceptSide === "REMOTE") return {
34179
- result: {
34180
- ...trialSetting,
34181
- ...preferred
34182
- },
34183
- requireFetch: false
34184
- };
34185
- if (autoAcceptSide === "CURRENT") return {
34186
- result: false,
34187
- requireFetch: false
34188
- };
34189
- const items = Object.entries(TweakValuesShouldMatchedTemplate);
34190
- let rebuildRequired = false;
34191
- let rebuildRecommended = false;
34192
- let differenceCount = 0;
34193
- const tableRows = [];
34194
- for (const v of items) {
34195
- const key = v[0];
34196
- const remoteValueForDisplay = escapeMarkdownValue(valueToString(preferred[key]));
34197
- const currentValueForDisplay = escapeMarkdownValue(valueToString(trialSetting?.[key]));
34198
- if (trialSetting?.[key] !== preferred[key]) {
34199
- if (IncompatibleChanges.indexOf(key) !== -1) rebuildRequired = true;
34200
- for (const pattern of IncompatibleChangesInSpecificPattern) {
34201
- if (pattern.key !== key) continue;
34202
- const isFromConditionMet = "from" in pattern ? pattern.from === trialSetting?.[key] : false;
34203
- const isToConditionMet = "to" in pattern ? pattern.to === preferred[key] : false;
34204
- if (isFromConditionMet || isToConditionMet) if (pattern.isRecommendation) rebuildRecommended = true;
34205
- else rebuildRequired = true;
34206
- }
34207
- if (CompatibleButLossyChanges.indexOf(key) !== -1) rebuildRecommended = true;
34208
- } else continue;
34209
- tableRows.push($msg("TweakMismatchResolve.Table.Row", {
34210
- name: localisedConfName(key),
34211
- self: currentValueForDisplay,
34212
- remote: remoteValueForDisplay
34213
- }));
34214
- differenceCount++;
34215
- }
34216
- if (differenceCount === 0) {
34287
+ const trialSignature = JSON.stringify(trialSetting);
34288
+ const currentSignature = resolutionSettingsSignature(this.settings);
34289
+ const assessment = assessTweakCompatibility(trialSetting, preferred);
34290
+ if (assessment.alignment === "matched") {
34217
34291
  this._log("The settings in the remote database are the same as the local database.", 64);
34218
34292
  return {
34219
34293
  result: false,
34220
34294
  requireFetch: false
34221
34295
  };
34222
34296
  }
34223
- const additionalMessage = rebuildRequired && this.core.settings.isConfigured ? $msg("TweakMismatchResolve.Message.UseRemote.WarningRebuildRequired") : "";
34224
- const additionalMessage2 = rebuildRecommended && this.core.settings.isConfigured ? $msg("TweakMismatchResolve.Message.UseRemote.WarningRebuildRecommended") : "";
34225
- const message = $msg("TweakMismatchResolve.Message.Main", {
34226
- table: $msg("TweakMismatchResolve.Table", { rows: tableRows.join("\n") }),
34227
- additionalMessage: [additionalMessage, additionalMessage2].filter((v) => v).join("\n")
34228
- });
34229
- const CHOICE_USE_REMOTE = $msg("TweakMismatchResolve.Action.UseConfigured");
34230
- const CHOICE_DISMISS = $msg("TweakMismatchResolve.Action.Dismiss");
34231
- const CHOICES = [CHOICE_USE_REMOTE, CHOICE_DISMISS];
34232
- const retKey = await this.core.confirm.askSelectStringDialogue(message, CHOICES, {
34233
- title: $msg("TweakMismatchResolve.Title.UseRemoteConfig"),
34234
- timeout: 0,
34235
- defaultAction: CHOICE_DISMISS
34236
- });
34237
- if (!retKey) return {
34297
+ const publication = await this.services.replicator.acquireActiveReplicatorContext();
34298
+ const settingsStillCurrent = () => JSON.stringify(trialSetting) === trialSignature && resolutionSettingsSignature(this.settings) === currentSignature;
34299
+ if (!settingsStillCurrent()) return {
34238
34300
  result: false,
34239
34301
  requireFetch: false
34240
34302
  };
34241
- if (retKey === CHOICE_DISMISS) return {
34303
+ const stillCurrent = async () => await this.services.replicator.acquireActiveReplicatorContext() === publication && settingsStillCurrent();
34304
+ const acceptedSettings = {
34305
+ ...trialSetting,
34306
+ ...settingsAfterAdoption(assessment, "adoptPreferred")
34307
+ };
34308
+ const autoAcceptSide = await this._shouldAutoAcceptCompatibleLossy(assessment);
34309
+ if (!await stillCurrent()) return {
34242
34310
  result: false,
34243
34311
  requireFetch: false
34244
34312
  };
34245
- if (retKey === CHOICE_USE_REMOTE) return {
34246
- result: {
34247
- ...trialSetting,
34248
- ...preferred
34249
- },
34250
- requireFetch: rebuildRequired
34313
+ if (autoAcceptSide === "REMOTE") return {
34314
+ result: acceptedSettings,
34315
+ requireFetch: false
34251
34316
  };
34252
- return {
34317
+ if (autoAcceptSide === "CURRENT") return {
34318
+ result: false,
34319
+ requireFetch: false
34320
+ };
34321
+ const impact = assessment.adoptPreferred.reconstruction;
34322
+ const additionalMessage = impact === "required" && this.settings.isConfigured ? $msg("TweakMismatchResolve.Message.UseRemote.WarningRebuildRequired") : "";
34323
+ const additionalMessage2 = impact === "recommended" && this.settings.isConfigured ? $msg("TweakMismatchResolve.Message.UseRemote.WarningRebuildRecommended") : "";
34324
+ const message = $msg("TweakMismatchResolve.Message.Main", {
34325
+ table: mismatchTable(assessment, "adoptPreferred"),
34326
+ additionalMessage: [additionalMessage, additionalMessage2].filter(Boolean).join("\n")
34327
+ });
34328
+ const useRemote = $msg("TweakMismatchResolve.Action.UseConfigured");
34329
+ const dismiss = $msg("TweakMismatchResolve.Action.Dismiss");
34330
+ if (await this.core.confirm.askSelectStringDialogue(message, [useRemote, dismiss], {
34331
+ title: $msg("TweakMismatchResolve.Title.UseRemoteConfig"),
34332
+ timeout: 0,
34333
+ defaultAction: dismiss
34334
+ }) !== useRemote || !await stillCurrent()) return {
34253
34335
  result: false,
34254
34336
  requireFetch: false
34255
34337
  };
34338
+ return {
34339
+ result: acceptedSettings,
34340
+ requireFetch: impact === "required"
34341
+ };
34256
34342
  }
34257
34343
  onBindFunction(core, services) {
34258
34344
  services.setting.onBeforeSaveSettingData.addHandler(this._onBeforeSaveSettingData.bind(this));
@@ -34266,407 +34352,710 @@ var ModuleResolvingMismatchedTweaks = class extends AbstractModule {
34266
34352
  };
34267
34353
  //#endregion
34268
34354
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/coreEnvVars.js
34269
- var manifestVersion = "1.0.24";
34270
- var packageVersion = "1.0.24";
34355
+ var manifestVersion = "1.0.28";
34356
+ var packageVersion = "1.0.28";
34271
34357
  //#endregion
34272
- //#region ../../modules/main/ModuleLiveSyncMain.ts
34273
- var ModuleLiveSyncMain = class extends AbstractModule {
34274
- async _onLiveSyncReady() {
34275
- if (!await this.core.services.appLifecycle.onLayoutReady()) return false;
34276
- eventHub.emitEvent(EVENT_LAYOUT_READY);
34277
- if (this.settings.suspendFileWatching || this.settings.suspendParseReplicationResult) {
34278
- const ANSWER_KEEP = $msg("moduleLiveSyncMain.optionKeepLiveSyncDisabled");
34279
- const ANSWER_RESUME = $msg("moduleLiveSyncMain.optionResumeAndRestart");
34280
- const message = $msg("moduleLiveSyncMain.msgScramEnabled", {
34281
- fileWatchingStatus: this.settings.suspendFileWatching ? "suspended" : "active",
34282
- parseReplicationStatus: this.settings.suspendParseReplicationResult ? "suspended" : "active"
34283
- });
34284
- if (await this.core.confirm.askSelectStringDialogue(message, [ANSWER_KEEP, ANSWER_RESUME], {
34285
- defaultAction: ANSWER_KEEP,
34286
- title: $msg("moduleLiveSyncMain.titleScramEnabled")
34287
- }) == ANSWER_RESUME) {
34288
- this.settings.suspendFileWatching = false;
34289
- this.settings.suspendParseReplicationResult = false;
34290
- await this.saveSettings();
34291
- this.services.appLifecycle.scheduleRestart();
34292
- return false;
34358
+ //#region ../../../node_modules/octagonal-wheels/dist/iterable/map.js
34359
+ /**
34360
+ * apply a function to each element of an iterable asynchronously with a concurrency limit.
34361
+ * Note that the order of the elements is not guaranteed.
34362
+ * @param iterable An iterable items to be processed.
34363
+ * @param callback A function to be applied to each element of the iterable.
34364
+ * @param concurrency The number of concurrent processes.
34365
+ */
34366
+ async function* withConcurrency(iterable, callback, concurrency) {
34367
+ const processes = /* @__PURE__ */ new Set();
34368
+ const mapTaskToPromise = /* @__PURE__ */ new Map();
34369
+ let serial = 0;
34370
+ const enqueue = (item) => {
34371
+ const idx = serial++;
34372
+ const promise = (async () => [idx, await callback(item)])();
34373
+ processes.add(promise);
34374
+ mapTaskToPromise.set(idx, promise);
34375
+ };
34376
+ const consume = async () => {
34377
+ const r = await Promise.race(processes);
34378
+ const item = mapTaskToPromise.get(r[0]);
34379
+ processes.delete(item);
34380
+ mapTaskToPromise.delete(r[0]);
34381
+ return r[1];
34382
+ };
34383
+ for await (const t of iterable) {
34384
+ while (processes.size >= concurrency) yield await consume();
34385
+ enqueue(t);
34386
+ }
34387
+ while (processes.size > 0) yield await consume();
34388
+ }
34389
+ //#endregion
34390
+ //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/services/base/VaultScanResult.js
34391
+ var VaultScanResults = {
34392
+ FAILED: false,
34393
+ COMPLETED: true,
34394
+ COMPLETED_WITH_FILE_FAILURES: "completed-with-file-failures"
34395
+ };
34396
+ //#endregion
34397
+ //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/serviceFeatures/offlineScanner.js
34398
+ var FilePairProcessResults = {
34399
+ COMPLETED: "completed",
34400
+ SKIPPED: "skipped",
34401
+ FAILED: "failed"
34402
+ };
34403
+ var MetadataDocumentNamespaces = {
34404
+ NORMAL: "normal",
34405
+ INTERNAL: "internal",
34406
+ CUSTOMISATION: "customisation",
34407
+ PLUGIN_STORAGE: "plugin-storage"
34408
+ };
34409
+ var MetadataDocumentIdentityStatuses = {
34410
+ CONSISTENT: "consistent",
34411
+ EXCLUDED: "excluded",
34412
+ UNRESOLVED: "unresolved"
34413
+ };
34414
+ var OfflineScanUnresolvedReasons = {
34415
+ DOCUMENT_ID_MISMATCH: "document-id-mismatch",
34416
+ NAMESPACE_MISMATCH: "namespace-mismatch"
34417
+ };
34418
+ function getMetadataDocumentNamespace(value) {
34419
+ if (value.startsWith("ix:")) return MetadataDocumentNamespaces.CUSTOMISATION;
34420
+ if (value.startsWith("i:")) return MetadataDocumentNamespaces.INTERNAL;
34421
+ if (value.startsWith("ps:")) return MetadataDocumentNamespaces.PLUGIN_STORAGE;
34422
+ return MetadataDocumentNamespaces.NORMAL;
34423
+ }
34424
+ async function inspectMetadataDocumentIdentity(host, doc) {
34425
+ const actualDocumentId = doc._id;
34426
+ const declaredPath = getPathFromEntry(host, doc);
34427
+ const actualNamespace = getMetadataDocumentNamespace(actualDocumentId);
34428
+ const declaredPathNamespace = getMetadataDocumentNamespace(declaredPath);
34429
+ if (actualNamespace !== MetadataDocumentNamespaces.NORMAL || declaredPathNamespace !== MetadataDocumentNamespaces.NORMAL) {
34430
+ if (actualNamespace === declaredPathNamespace) return {
34431
+ status: MetadataDocumentIdentityStatuses.EXCLUDED,
34432
+ actualDocumentId,
34433
+ declaredPath,
34434
+ namespace: actualNamespace
34435
+ };
34436
+ return {
34437
+ status: MetadataDocumentIdentityStatuses.UNRESOLVED,
34438
+ diagnostic: {
34439
+ reason: OfflineScanUnresolvedReasons.NAMESPACE_MISMATCH,
34440
+ actualDocumentId,
34441
+ declaredPath,
34442
+ actualNamespace,
34443
+ declaredPathNamespace
34293
34444
  }
34294
- }
34295
- if (!await this.services.databaseEvents.initialiseDatabase(false, false)) return false;
34296
- if (!await this.core.services.appLifecycle.onFirstInitialise()) return false;
34297
- await this.services.control.applySettings();
34298
- fireAndForget(async () => {
34299
- this._log($msg("moduleLiveSyncMain.logAdditionalSafetyScan"), 16);
34300
- if (!await this.services.appLifecycle.onScanningStartupIssues()) this._log($msg("moduleLiveSyncMain.logSafetyScanFailed"), 64);
34301
- else this._log($msg("moduleLiveSyncMain.logSafetyScanCompleted"), 16);
34302
- });
34303
- return true;
34445
+ };
34304
34446
  }
34305
- _wireUpEvents() {
34306
- eventHub.onEvent(EVENT_SETTING_SAVED, (settings) => {
34307
- fireAndForget(async () => {
34308
- try {
34309
- const lang = this.core.services.setting.currentSettings()?.displayLanguage;
34310
- if (lang !== void 0) setLang(lang);
34311
- if (this.core.services.database.isDatabaseReady()) await this.core.services.control.applySettings();
34312
- eventHub.emitEvent(EVENT_REQUEST_RELOAD_SETTING_TAB);
34313
- } catch (e) {
34314
- this._log(`Error in Setting Save Event`, 64);
34315
- this._log(e, 16);
34447
+ const expectedDocumentId = await host.services.path.path2id(declaredPath);
34448
+ if (actualDocumentId !== expectedDocumentId) return {
34449
+ status: MetadataDocumentIdentityStatuses.UNRESOLVED,
34450
+ diagnostic: {
34451
+ reason: OfflineScanUnresolvedReasons.DOCUMENT_ID_MISMATCH,
34452
+ actualDocumentId,
34453
+ declaredPath,
34454
+ expectedDocumentId,
34455
+ actualNamespace,
34456
+ declaredPathNamespace
34457
+ }
34458
+ };
34459
+ return {
34460
+ status: MetadataDocumentIdentityStatuses.CONSISTENT,
34461
+ actualDocumentId,
34462
+ declaredPath,
34463
+ expectedDocumentId
34464
+ };
34465
+ }
34466
+ async function collectDeletedFiles(host, log) {
34467
+ const limitDays = host.services.setting.currentSettings().automaticallyDeleteMetadataOfDeletedFiles;
34468
+ if (limitDays <= 0) return;
34469
+ log(`Checking expired file history`);
34470
+ const limit = Date.now() - 86400 * 1e3 * limitDays;
34471
+ const notes = [];
34472
+ for await (const doc of host.services.database.localDatabase.findAllDocs({ conflicts: true })) if (isAnyNote(doc)) {
34473
+ if (doc.deleted && doc.mtime - limit < 0) {
34474
+ if (isMetaEntry(doc)) {
34475
+ const identity = await inspectMetadataDocumentIdentity(host, doc);
34476
+ if (identity.status === MetadataDocumentIdentityStatuses.UNRESOLVED) {
34477
+ log(`Expired deletion history has an unresolved Metadata identity and will be left unchanged: ${identity.diagnostic.declaredPath} (${identity.diagnostic.reason})`, 32);
34478
+ continue;
34316
34479
  }
34480
+ }
34481
+ notes.push({
34482
+ path: doc.path,
34483
+ mtime: doc.mtime,
34484
+ ttl: (doc.mtime - limit) / 1e3 / 86400,
34485
+ doc
34317
34486
  });
34318
- });
34319
- return Promise.resolve(true);
34320
- }
34321
- async _onLiveSyncLoad() {
34322
- this.services.context.events;
34323
- await this.services.appLifecycle.onWireUpEvents();
34324
- eventHub.emitEvent(EVENT_PLUGIN_LOADED);
34325
- this._log($msg("moduleLiveSyncMain.logLoadingPlugin"));
34326
- if (!await this.services.appLifecycle.onInitialise()) {
34327
- this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"), 64);
34328
- return false;
34329
- }
34330
- this._log($msg("moduleLiveSyncMain.logPluginVersion", {
34331
- manifestVersion,
34332
- packageVersion
34333
- }));
34334
- await this.services.setting.loadSettings();
34335
- if (!await this.services.appLifecycle.onSettingLoaded()) {
34336
- this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"), 64);
34337
- return false;
34338
34487
  }
34339
- await this.services.database.openDatabase({
34340
- databaseEvents: this.services.databaseEvents,
34341
- replicator: this.services.replicator
34342
- });
34343
- await this.core.services.appLifecycle.onLoaded();
34344
- await Promise.all(this.core.addOns.map((e) => Promise.resolve(e.onload())));
34345
- return true;
34346
34488
  }
34347
- onBindFunction(core, services) {
34348
- super.onBindFunction(core, services);
34349
- services.appLifecycle.onReady.addHandler(this._onLiveSyncReady.bind(this));
34350
- services.appLifecycle.onWireUpEvents.addHandler(this._wireUpEvents.bind(this));
34351
- services.appLifecycle.onLoad.addHandler(this._onLiveSyncLoad.bind(this));
34489
+ if (notes.length === 0) {
34490
+ log("There are no old documents");
34491
+ log(`Checking expired file history done`);
34492
+ return;
34352
34493
  }
34353
- };
34354
- //#endregion
34355
- //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/utils.doc.js
34356
- function isErrorOf(ex, statusCode) {
34357
- if (!ex || typeof ex !== "object") throw new Error(`Expected an object error, but got ${typeof ex}`);
34358
- if ("status" in ex && typeof ex.status === "number" && ex.status == statusCode) return true;
34359
- return false;
34494
+ for (const v of notes) {
34495
+ log(`Deletion history expired: ${v.path}`);
34496
+ const delDoc = v.doc;
34497
+ delDoc._deleted = true;
34498
+ await host.services.database.localDatabase.putRaw(delDoc);
34499
+ }
34500
+ log(`Checking expired file history done`);
34360
34501
  }
34361
- function isNotFoundError(ex) {
34362
- return isErrorOf(ex, 404);
34502
+ function getPathFromEntry(host, doc) {
34503
+ return host.services.path.getPath(doc);
34363
34504
  }
34364
- function isEntryWithPath(entry) {
34365
- if (!entry || typeof entry !== "object") return false;
34366
- return "path" in entry && typeof entry.path === "string";
34505
+ async function syncFileBetweenDBandStorage(host, log, file, doc) {
34506
+ const docPath = getPathFromEntry(host, doc);
34507
+ if (!doc) throw new Error(`Missing doc:${docPath}`);
34508
+ switch (host.services.path.compareFileFreshness(file, doc)) {
34509
+ case BASE_IS_NEW: if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
34510
+ log("STORAGE -> DB :" + file.path);
34511
+ await host.serviceModules.fileHandler.storeFileToDB(file);
34512
+ return FilePairProcessResults.COMPLETED;
34513
+ } else {
34514
+ log(`STORAGE -> DB : ${file.path} has been skipped due to file size exceeding the limit`, 64);
34515
+ return FilePairProcessResults.SKIPPED;
34516
+ }
34517
+ case TARGET_IS_NEW: if (!host.services.vault.isFileSizeTooLarge(doc.size)) {
34518
+ log("STORAGE <- DB :" + docPath);
34519
+ if (await host.serviceModules.fileHandler.dbToStorage(doc, stripAllPrefixes(docPath), false)) {
34520
+ host.services.context.events.emitEvent("event-file-changed", {
34521
+ file: file.path,
34522
+ automated: true
34523
+ });
34524
+ return FilePairProcessResults.COMPLETED;
34525
+ } else {
34526
+ log(`STORAGE <- DB : Cloud not read ${file.path}, possibly deleted`, 64);
34527
+ return FilePairProcessResults.FAILED;
34528
+ }
34529
+ } else {
34530
+ log(`STORAGE <- DB : ${file.path} has been skipped due to file size exceeding the limit`, 64);
34531
+ return FilePairProcessResults.SKIPPED;
34532
+ }
34533
+ case EVEN:
34534
+ log("STORAGE == DB :" + file.path, -1);
34535
+ return FilePairProcessResults.COMPLETED;
34536
+ default:
34537
+ log("STORAGE ?? DB :" + file.path + " Something got weird");
34538
+ return FilePairProcessResults.FAILED;
34539
+ }
34367
34540
  }
34368
- function tryGetFilePath(entry) {
34369
- if (isEntryWithPath(entry)) return entry.path;
34541
+ function canProceedScan(host, errorManager, log, showingNotice = false, ignoreSuspending = false) {
34542
+ const settings = host.services.setting.currentSettings();
34543
+ const ERR_NOT_CONFIGURED = "LiveSync is not configured yet. Synchronising between the storage and the local database is now prevented.";
34544
+ if (!settings.isConfigured) {
34545
+ errorManager.showError(ERR_NOT_CONFIGURED, showingNotice ? 64 : 32);
34546
+ return false;
34547
+ }
34548
+ errorManager.clearError(ERR_NOT_CONFIGURED);
34549
+ const ERR_SUSPENDING = "Now suspending file watching. Synchronising between the storage and the local database is now prevented.";
34550
+ if (!ignoreSuspending && settings.suspendFileWatching) {
34551
+ errorManager.showError(ERR_SUSPENDING, showingNotice ? 64 : 32);
34552
+ return false;
34553
+ }
34554
+ errorManager.clearError(ERR_SUSPENDING);
34555
+ const MSG_IN_REMEDIATION = `Started in remediation Mode! (Max mtime for reflect events is set). Synchronising between the storage and the local database is now prevented.`;
34556
+ if (settings.maxMTimeForReflectEvents > 0) {
34557
+ errorManager.showError(MSG_IN_REMEDIATION, 64);
34558
+ return false;
34559
+ }
34560
+ errorManager.clearError(MSG_IN_REMEDIATION);
34561
+ return true;
34370
34562
  }
34371
- //#endregion
34372
- //#region ../../serviceFeatures/fileDatabaseInfo.ts
34373
- var REPORT_WARNING = "All revisions and chunk availability below are a snapshot of this device's local database; the remote is not queried. Review the Vault-relative path, document identifier, content-derived chunk identifiers, and metadata before sharing this report. File contents are omitted.";
34374
- function toDatabasePath(path) {
34375
- if (path.startsWith(".")) return addPrefix(path, "i:");
34376
- return path;
34563
+ function convertCase(settings, path) {
34564
+ if (settings.handleFilenameCaseSensitive) return path;
34565
+ return path.toLowerCase();
34377
34566
  }
34378
- async function getLocalDatabaseMeta(core, path, options) {
34379
- const documentId = await core.services.path.path2id(path);
34380
- let raw;
34381
- try {
34382
- raw = await core.localDatabase.localDatabase.get(documentId, options);
34383
- } catch (error) {
34384
- if (isNotFoundError(error)) return false;
34385
- throw error;
34567
+ async function collectFilesOnStorage(host, settings, log) {
34568
+ log("Collecting local files on the storage", 16);
34569
+ const filesStorageSrc = await host.serviceModules.storageAccess.getFiles();
34570
+ const _filesStorage = [];
34571
+ for (const f of filesStorageSrc) {
34572
+ if (shouldBeIgnored(f.path)) continue;
34573
+ if (await host.services.vault.isTargetFile(f.path)) _filesStorage.push(f);
34386
34574
  }
34387
- if (raw.type === "leaf") return false;
34388
- if (raw.type && raw.type !== "notes" && raw.type !== "newnote" && raw.type !== "plain") return false;
34389
- const rawStorageType = raw.type ?? null;
34390
- const legacy = rawStorageType === null || rawStorageType === "notes";
34391
- const type = legacy ? "notes" : rawStorageType;
34392
- const legacyBodyPresent = legacy && (typeof raw.data === "string" || Array.isArray(raw.data) && raw.data.every((item) => typeof item === "string"));
34575
+ const storageFileNameMap = Object.fromEntries(_filesStorage.map((e) => [e.path, e]));
34576
+ const storageFileNames = Object.keys(storageFileNameMap);
34577
+ const storageFileNameCapsPair = storageFileNames.map((e) => [e, convertCase(settings, e)]);
34393
34578
  return {
34394
- _id: raw._id,
34395
- _rev: raw._rev,
34396
- _conflicts: raw._conflicts,
34397
- _revs_info: raw._revs_info,
34398
- path,
34399
- data: legacyBodyPresent ? raw.data : "",
34400
- ctime: raw.ctime ?? 0,
34401
- mtime: raw.mtime ?? 0,
34402
- size: raw.size ?? 0,
34403
- children: type === "newnote" || type === "plain" ? raw.children ?? [] : [],
34404
- datatype: type === "newnote" ? "newnote" : "plain",
34405
- deleted: raw.deleted ?? raw._deleted,
34406
- type,
34407
- eden: raw.eden ?? {},
34408
- _rawStorageType: rawStorageType,
34409
- _legacyBodyPresent: legacyBodyPresent
34579
+ storageFileNameMap,
34580
+ storageFileNames,
34581
+ storageFileNameCI2CS: Object.fromEntries(storageFileNameCapsPair.map((e) => [e[1], e[0]]))
34410
34582
  };
34411
34583
  }
34412
- async function collectRevisionDatabaseInfo(core, meta, current) {
34413
- const legacy = meta._rawStorageType === null || meta._rawStorageType === "notes";
34414
- const children = legacy ? [] : "children" in meta ? meta.children : [];
34415
- const uniqueChildren = [...new Set(children)];
34416
- const referenceCounts = /* @__PURE__ */ new Map();
34417
- for (const child of children) referenceCounts.set(child, (referenceCounts.get(child) ?? 0) + 1);
34418
- const embeddedChildren = new Set(Object.keys("eden" in meta && meta.eden ? meta.eden : {}).filter((id) => uniqueChildren.includes(id)));
34419
- const localRows = uniqueChildren.length === 0 ? [] : (await core.localDatabase.allDocsRaw({
34420
- keys: uniqueChildren,
34421
- include_docs: false
34422
- })).rows;
34423
- const localChunkStates = new Map(localRows.filter((row) => "value" in row).map((row) => [row.key, {
34424
- state: row.value.deleted ? "deleted" : "available",
34425
- revision: row.value.rev
34426
- }]));
34584
+ async function collectDatabaseFiles(host, settings, log, showingNotice) {
34585
+ log("Collecting local files on the DB", 16);
34586
+ const _DBEntries = [];
34587
+ const unresolvedFileNamesLC = /* @__PURE__ */ new Set();
34588
+ const resolvableFileNamesLC = /* @__PURE__ */ new Set();
34589
+ let count = 0;
34590
+ for await (const doc of host.services.database.localDatabase.findAllNormalDocs({ conflicts: true }) || []) {
34591
+ count++;
34592
+ if (count % 25 === 0) log(`Collecting local files on the DB: ${count}`, showingNotice ? 64 : 32, "syncAll");
34593
+ if (!isMetaEntry(doc)) {
34594
+ log(`Invalid Metadata entry: ${doc._id ?? "unknown"}`, 32);
34595
+ continue;
34596
+ }
34597
+ const identity = await inspectMetadataDocumentIdentity(host, doc);
34598
+ if (identity.status === MetadataDocumentIdentityStatuses.EXCLUDED) continue;
34599
+ if (identity.status === MetadataDocumentIdentityStatuses.UNRESOLVED) {
34600
+ const { diagnostic } = identity;
34601
+ const unresolvedKey = convertCase(settings, stripAllPrefixes(diagnostic.declaredPath));
34602
+ unresolvedFileNamesLC.add(unresolvedKey);
34603
+ log(`Metadata identity is unresolved and will be left unchanged: ${diagnostic.declaredPath} (${diagnostic.reason})`, 32);
34604
+ continue;
34605
+ }
34606
+ const path = identity.declaredPath;
34607
+ if (host.services.vault.isValidPath(path) && !shouldBeIgnored(path) && await host.services.vault.isTargetFile(path)) {
34608
+ _DBEntries.push(doc);
34609
+ resolvableFileNamesLC.add(convertCase(settings, stripAllPrefixes(path)));
34610
+ }
34611
+ }
34612
+ const databaseFileNameMap = Object.fromEntries(_DBEntries.map((e) => [getPathFromEntry(host, e), e]));
34613
+ const databaseFileNames = Object.keys(databaseFileNameMap);
34614
+ const databaseFileNameCapsPair = databaseFileNames.map((e) => [e, convertCase(settings, e)]);
34427
34615
  return {
34428
- documentId: meta._id,
34429
- revision: meta._rev ?? null,
34430
- current,
34431
- deleted: Boolean(meta.deleted ?? meta._deleted),
34432
- storageType: meta._rawStorageType ?? "absent",
34433
- storageLayout: legacy ? "legacy-inline" : "chunked",
34434
- ctime: meta.ctime,
34435
- mtime: meta.mtime,
34436
- recordedSize: meta.size,
34437
- revisionHistory: (meta._revs_info ?? []).map(({ rev, status }) => ({
34438
- revision: rev,
34439
- status
34440
- })),
34441
- chunkReferences: children.length,
34442
- uniqueChunkReferences: uniqueChildren.length,
34443
- embeddedChunkReferences: children.filter((id) => embeddedChildren.has(id)).length,
34444
- locallyStoredChunkReferences: children.filter((id) => localChunkStates.get(id)?.state === "available").length,
34445
- contentAvailableLocally: legacy ? meta._legacyBodyPresent : uniqueChildren.every((id) => embeddedChildren.has(id) || localChunkStates.get(id)?.state === "available"),
34446
- chunks: uniqueChildren.map((id) => {
34447
- const localState = localChunkStates.get(id);
34448
- return {
34449
- id,
34450
- referenceCount: referenceCounts.get(id) ?? 0,
34451
- embedded: embeddedChildren.has(id),
34452
- storedInLocalDatabase: localState?.state === "available",
34453
- localDatabaseState: localState?.state ?? "missing",
34454
- localDatabaseRevision: localState?.revision ?? null
34455
- };
34456
- })
34616
+ databaseFileNameMap,
34617
+ databaseFileNames,
34618
+ databaseFileNameCI2CS: Object.fromEntries(databaseFileNameCapsPair.map((e) => [e[1], e[0]])),
34619
+ quarantinedFileNamesLC: new Set([...unresolvedFileNamesLC].filter((path) => !resolvableFileNamesLC.has(path)))
34457
34620
  };
34458
34621
  }
34459
- function revisionHistory(meta) {
34460
- const history = (meta._revs_info ?? []).map(({ rev, status }) => ({
34461
- revision: rev,
34462
- status
34463
- }));
34464
- if (meta._rev && !history.some(({ revision }) => revision === meta._rev)) history.unshift({
34465
- revision: meta._rev,
34466
- status: "available"
34467
- });
34468
- return history;
34469
- }
34470
- function missingChunkIds(info) {
34471
- return info.chunks.filter(({ embedded, localDatabaseState }) => !embedded && localDatabaseState !== "available").map(({ id }) => id);
34622
+ async function updateToDatabase(host, log, logLevel, file) {
34623
+ if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
34624
+ const path = file.path;
34625
+ await host.serviceModules.fileHandler.storeFileToDB(file);
34626
+ host.services.context.events.emitEvent("event-file-changed", {
34627
+ file: path,
34628
+ automated: true
34629
+ });
34630
+ return FilePairProcessResults.COMPLETED;
34631
+ } else {
34632
+ log(`UPDATE DATABASE: ${file.path} has been skipped due to file size exceeding the limit`, logLevel);
34633
+ return FilePairProcessResults.SKIPPED;
34634
+ }
34472
34635
  }
34473
- async function inspectFileDatabaseInfo(core, path) {
34474
- const storageStat = await core.storageAccess.isExistsIncludeHidden(path) ? await core.storageAccess.statHidden(path) : null;
34475
- const databasePath = toDatabasePath(path);
34476
- const currentMeta = await getLocalDatabaseMeta(core, databasePath, {
34477
- conflicts: true,
34478
- revs: true,
34479
- revs_info: true
34480
- });
34481
- const revisions = [];
34482
- const conflictRevisions = currentMeta === false ? [] : currentMeta._conflicts ?? [];
34483
- const unavailableConflictRevisions = [];
34484
- const mergeBases = [];
34485
- const metadataByRevision = /* @__PURE__ */ new Map();
34486
- if (currentMeta !== false && currentMeta._rev) metadataByRevision.set(currentMeta._rev, currentMeta);
34487
- const getRevisionMeta = async (revision) => {
34488
- const cached = metadataByRevision.get(revision);
34489
- if (cached !== void 0) return cached;
34490
- const meta = await getLocalDatabaseMeta(core, databasePath, {
34491
- rev: revision,
34492
- revs: true,
34493
- revs_info: true
34636
+ async function updateToStorage(host, log, logLevel, w) {
34637
+ const path = getPathFromEntry(host, w);
34638
+ if (w && !(w.deleted || w._deleted)) if (!host.services.vault.isFileSizeTooLarge(w.size)) {
34639
+ if ((w._conflicts?.length ?? 0) > 0) {
34640
+ log(`UPDATE STORAGE: ${path} has conflicts. skipped (x)`, 32);
34641
+ return FilePairProcessResults.SKIPPED;
34642
+ }
34643
+ if (!await host.serviceModules.fileHandler.dbToStorage(path, null, true)) return FilePairProcessResults.FAILED;
34644
+ host.services.context.events.emitEvent("event-file-changed", {
34645
+ file: path,
34646
+ automated: true
34494
34647
  });
34495
- metadataByRevision.set(revision, meta);
34496
- return meta;
34497
- };
34498
- if (currentMeta) {
34499
- revisions.push(await collectRevisionDatabaseInfo(core, currentMeta, true));
34500
- for (const revision of conflictRevisions) {
34501
- const conflictMeta = await getRevisionMeta(revision);
34502
- if (conflictMeta) {
34503
- revisions.push(await collectRevisionDatabaseInfo(core, conflictMeta, false));
34504
- const winnerHistory = revisionHistory(currentMeta);
34505
- const conflictHistory = revisionHistory(conflictMeta);
34506
- const conflictHistoryByRevision = new Map(conflictHistory.map(({ revision: historyRevision, status }) => [historyRevision, status]));
34507
- const sharedHistory = winnerHistory.filter(({ revision: historyRevision }) => conflictHistoryByRevision.has(historyRevision));
34508
- const sharedRevision = sharedHistory[0]?.revision ?? null;
34509
- const unavailableSharedRevisions = sharedHistory.filter(({ revision: historyRevision, status }) => status !== "available" || conflictHistoryByRevision.get(historyRevision) !== "available").map(({ revision: historyRevision }) => historyRevision);
34510
- const sharedMeta = sharedRevision ? await getRevisionMeta(sharedRevision) : false;
34511
- const sharedInfo = sharedMeta ? await collectRevisionDatabaseInfo(core, sharedMeta, false) : void 0;
34512
- mergeBases.push({
34513
- winnerRevision: currentMeta._rev ?? "",
34514
- conflictRevision: revision,
34515
- revision: sharedRevision,
34516
- metadataAvailableLocally: Boolean(sharedMeta),
34517
- contentAvailableLocally: sharedInfo?.contentAvailableLocally ?? false,
34518
- missingChunkIds: sharedInfo ? missingChunkIds(sharedInfo) : [],
34519
- unavailableSharedRevisions
34520
- });
34521
- } else unavailableConflictRevisions.push(revision);
34522
- }
34648
+ log(`Check or pull from db:${path} OK`);
34649
+ return FilePairProcessResults.COMPLETED;
34650
+ } else {
34651
+ log(`UPDATE STORAGE: ${path} has been skipped due to file size exceeding the limit`, logLevel);
34652
+ return FilePairProcessResults.SKIPPED;
34653
+ }
34654
+ else if (w) {
34655
+ log(`Deletion history skipped: ${path}`, 16);
34656
+ return FilePairProcessResults.SKIPPED;
34657
+ } else {
34658
+ log(`entry not found: ${path}`);
34659
+ return FilePairProcessResults.FAILED;
34523
34660
  }
34524
- return {
34525
- path,
34526
- databasePath,
34527
- storage: storageStat ? {
34528
- exists: true,
34529
- ctime: storageStat.ctime,
34530
- mtime: storageStat.mtime,
34531
- size: storageStat.size
34532
- } : { exists: false },
34533
- database: {
34534
- source: "local database on this device",
34535
- remoteQueried: false,
34536
- exists: currentMeta !== false,
34537
- currentRevision: currentMeta ? currentMeta._rev ?? null : null,
34538
- conflictCount: conflictRevisions.length,
34539
- conflictRevisions,
34540
- unavailableConflictRevisions,
34541
- revisions,
34542
- mergeBases
34543
- }
34544
- };
34545
34661
  }
34546
- async function buildFileDatabaseInfoReport(core, path) {
34547
- const report = await inspectFileDatabaseInfo(core, path);
34548
- return `${$msg(REPORT_WARNING)}
34549
-
34550
- \`\`\`json
34551
- ${JSON.stringify(report, null, 2)}
34552
- \`\`\``;
34662
+ async function syncStorageAndDatabase(host, log, file, logLevel, doc) {
34663
+ if ((doc._conflicts?.length ?? 0) > 0) {
34664
+ log(`SYNC DATABASE AND STORAGE: ${file.path} has conflicts. skipped`, 32);
34665
+ return FilePairProcessResults.SKIPPED;
34666
+ }
34667
+ if (!host.services.vault.isFileSizeTooLarge(file.stat.size) && !host.services.vault.isFileSizeTooLarge(doc.size)) return await syncFileBetweenDBandStorage(host, log, file, doc);
34668
+ else {
34669
+ log(`SYNC DATABASE AND STORAGE: ${getPathFromEntry(host, doc)} has been skipped due to file size exceeding the limit`, logLevel);
34670
+ return FilePairProcessResults.SKIPPED;
34671
+ }
34553
34672
  }
34554
- async function copyFileDatabaseInfo(core, path) {
34555
- const report = await buildFileDatabaseInfoReport(core, path);
34556
- return await core.services.UI.promptCopyToClipboard($msg("Database information for ${FILE}", { FILE: path }), report);
34673
+ var FullScanModes = {
34674
+ DB_APPLY: "db-apply",
34675
+ NEWER_WINS: "newer-wins"
34676
+ };
34677
+ var ExtraOnRemote = {
34678
+ /**
34679
+ * Delete database entries if they are missing on storage.
34680
+ */
34681
+ DELETE_LOCAL_MISSING: "delete-local-missing" };
34682
+ var ExtraOnLocal = {
34683
+ /**
34684
+ * Delete local files if they were deleted on database.
34685
+ */
34686
+ DELETE_DB_DELETED: "delete-db-deleted",
34687
+ /**
34688
+ * Delete local files if they are missing on database or were deleted on database.
34689
+ */
34690
+ DELETE_DB_MISSING: "delete-db-missing",
34691
+ /**
34692
+ * Merge local files to database
34693
+ */
34694
+ APPEND_STORAGE_ONLY: "append-storage-only"
34695
+ };
34696
+ function isDeletedEntry(entry) {
34697
+ return entry.deleted || entry._deleted || false;
34557
34698
  }
34558
- //#endregion
34559
- //#region ../../modules/essential/ModuleBasicMenu.ts
34560
- var ModuleBasicMenu = class extends AbstractModule {
34561
- _everyOnloadStart() {
34562
- this.addCommand({
34563
- id: "livesync-replicate",
34564
- name: $msg("Sync now"),
34565
- callback: async () => {
34566
- await this.services.replication.replicateUserInitiated({
34567
- trigger: "manual",
34568
- progressPresentation: REPLICATION_PROGRESS_PRESENTATIONS.QUIET,
34569
- interaction: USER_INITIATED_REPLICATION_AUTHORITY
34570
- });
34699
+ function getFilePairState(pair) {
34700
+ const { file, doc } = pair;
34701
+ if (file && doc) return isDeletedEntry(doc) ? "both-db-deleted" : "both";
34702
+ if (file) return "storage-only";
34703
+ if (doc) return isDeletedEntry(doc) ? "db-only-deleted" : "db-only";
34704
+ throw new Error("Corrupted file pair");
34705
+ }
34706
+ function shouldDeleteLocalWhenRemoteMissing(options) {
34707
+ return options.extraOnRemote === ExtraOnRemote.DELETE_LOCAL_MISSING || options.extraOnLocal === ExtraOnLocal.DELETE_DB_MISSING;
34708
+ }
34709
+ function shouldDeleteLocalWhenRemoteDeleted(options) {
34710
+ return options.extraOnRemote === ExtraOnRemote.DELETE_LOCAL_MISSING || options.extraOnLocal === ExtraOnLocal.DELETE_DB_DELETED || options.extraOnLocal === ExtraOnLocal.DELETE_DB_MISSING;
34711
+ }
34712
+ function resolveFilePairAction(state, options) {
34713
+ switch (options.mode) {
34714
+ case FullScanModes.DB_APPLY:
34715
+ switch (state) {
34716
+ case "both":
34717
+ case "db-only": return "update-storage";
34718
+ case "storage-only": return shouldDeleteLocalWhenRemoteMissing(options) ? "delete-local" : "skip";
34719
+ case "both-db-deleted": return shouldDeleteLocalWhenRemoteDeleted(options) ? "delete-local" : "skip";
34720
+ case "db-only-deleted": return "skip";
34571
34721
  }
34572
- });
34573
- this.addCommand({
34574
- id: "livesync-dump",
34575
- name: $msg("Copy database information for the active file"),
34576
- checkCallback: (checking) => {
34577
- const file = this.services.vault.getActiveFilePath();
34578
- if (!file) return false;
34579
- if (!checking) fireAndForget(() => copyFileDatabaseInfo(this.core, file));
34580
- return true;
34722
+ break;
34723
+ case FullScanModes.NEWER_WINS:
34724
+ switch (state) {
34725
+ case "both": return "sync-newer";
34726
+ case "storage-only": return shouldDeleteLocalWhenRemoteMissing(options) ? "delete-local" : "update-db";
34727
+ case "db-only": return "update-storage";
34728
+ case "both-db-deleted":
34729
+ if (shouldDeleteLocalWhenRemoteDeleted(options)) return "delete-local";
34730
+ return options.extraOnLocal === ExtraOnLocal.APPEND_STORAGE_ONLY ? "update-db" : "skip";
34731
+ case "db-only-deleted": return "skip";
34581
34732
  }
34582
- });
34583
- this.addCommand({
34584
- id: "livesync-toggle",
34585
- name: "Toggle LiveSync",
34586
- callback: async () => {
34587
- if (this.settings.liveSync) {
34588
- this.settings.liveSync = false;
34589
- this._log("LiveSync Disabled.", 64);
34590
- } else {
34591
- this.settings.liveSync = true;
34592
- this._log("LiveSync Enabled.", 64);
34593
- }
34594
- await this.services.control.applySettings();
34595
- await this.services.setting.saveSettingData();
34733
+ break;
34734
+ }
34735
+ return "skip";
34736
+ }
34737
+ async function processFilePair(host, log, pair, options) {
34738
+ const { file, doc } = pair;
34739
+ const canonicalPath = doc ? getPathFromEntry(host, doc) : file?.path;
34740
+ if (!canonicalPath) throw new Error("Corrupted file pair");
34741
+ const path = canonicalPath;
34742
+ const fileMapKey = convertCase(host.services.setting.currentSettings(), canonicalPath);
34743
+ if (file) updateFileMTimeInMap(host, fileMapKey, file.stat.mtime);
34744
+ if (doc && (doc._conflicts?.length ?? 0) > 0) {
34745
+ log(`SKIP ${options.mode}: ${path} has conflicts`, 32);
34746
+ return FilePairProcessResults.SKIPPED;
34747
+ }
34748
+ const state = getFilePairState(pair);
34749
+ let action = resolveFilePairAction(state, options);
34750
+ if (options.mode === FullScanModes.NEWER_WINS && state === "db-only" && doc) {
34751
+ const lastSeenMTime = getFileMTimeFromMap(fileMapKey);
34752
+ if (lastSeenMTime !== void 0) {
34753
+ const recency = compareMTime(lastSeenMTime, doc.mtime);
34754
+ if (recency === BASE_IS_NEW || recency === EVEN) {
34755
+ action = "delete-db";
34756
+ log(`NEWER_WINS: Treating missing local file as deletion (${path})`, 16);
34596
34757
  }
34597
- });
34598
- this.addCommand({
34599
- id: "livesync-suspendall",
34600
- name: "Toggle All Sync.",
34601
- callback: async () => {
34602
- if (this.services.appLifecycle.isSuspended()) {
34603
- this.services.appLifecycle.setSuspended(false);
34604
- this._log("Self-hosted LiveSync resumed", 64);
34758
+ }
34759
+ }
34760
+ try {
34761
+ switch (action) {
34762
+ case "update-db":
34763
+ if (!file) throw new Error(`Missing storage file for ${path}`);
34764
+ return await updateToDatabase(host, log, 32, file);
34765
+ case "update-storage":
34766
+ if (!doc) throw new Error(`Missing database entry for ${path}`);
34767
+ const updateStorageResult = await updateToStorage(host, log, 32, doc);
34768
+ if (updateStorageResult === FilePairProcessResults.COMPLETED) updateFileMTimeInMap(host, fileMapKey, doc.mtime);
34769
+ return updateStorageResult;
34770
+ case "sync-newer":
34771
+ if (!file || !doc) throw new Error(`Cannot compare freshness for ${path}`);
34772
+ const syncResult = await syncStorageAndDatabase(host, log, file, 32, doc);
34773
+ if (syncResult === FilePairProcessResults.COMPLETED) updateFileMTimeInMap(host, fileMapKey, Math.max(file.stat.mtime, doc.mtime));
34774
+ return syncResult;
34775
+ case "delete-local":
34776
+ if (!file) {
34777
+ log(`DELETE LOCAL: ${path} is already absent from storage`, 16);
34778
+ return FilePairProcessResults.COMPLETED;
34779
+ }
34780
+ log(`DELETE LOCAL: ${file.path}`, 32);
34781
+ await host.serviceModules.storageAccess.delete(file.path, true);
34782
+ fileMaps.delete(fileMapKey);
34783
+ saveFileStatus(host);
34784
+ return FilePairProcessResults.COMPLETED;
34785
+ case "delete-db":
34786
+ if (!doc) throw new Error(`Missing database entry for ${path}`);
34787
+ log(`DELETE DATABASE: ${path}`, 32);
34788
+ if (await host.serviceModules.fileHandler.deleteFileFromDB(stripAllPrefixes(path))) {
34789
+ fileMaps.delete(fileMapKey);
34790
+ saveFileStatus(host);
34791
+ return FilePairProcessResults.COMPLETED;
34605
34792
  } else {
34606
- this.services.appLifecycle.setSuspended(true);
34607
- this._log("Self-hosted LiveSync suspended", 64);
34793
+ log(`DELETE DATABASE did not delete ${path}; keeping last-seen record to avoid resurrecting the file`, 64);
34794
+ return FilePairProcessResults.FAILED;
34608
34795
  }
34609
- await this.services.control.applySettings();
34610
- await this.services.setting.saveSettingData();
34611
- }
34612
- });
34613
- this.addCommand({
34614
- id: "livesync-scan-files",
34615
- name: "Scan storage and database again",
34616
- checkCallback: (checking) => {
34617
- if (!this.settings.useAdvancedMode) return false;
34618
- if (!checking) fireAndForget(() => this.services.vault.scanVault(true));
34619
- return true;
34620
- }
34621
- });
34622
- this.addCommand({
34623
- id: "livesync-runbatch",
34624
- name: $msg("Apply pending changes now"),
34625
- callback: async () => {
34626
- await this.services.fileProcessing.commitPendingFileEvents();
34796
+ case "skip":
34797
+ log(`SKIP ${options.mode}: ${path} (${state})`, 16);
34798
+ return FilePairProcessResults.SKIPPED;
34799
+ }
34800
+ } catch (ex) {
34801
+ log(`Error processing ${path} with action ${action}`, 64);
34802
+ log(ex, 16);
34803
+ return FilePairProcessResults.FAILED;
34804
+ }
34805
+ }
34806
+ async function synchroniseAllFilesBetweenDBandStorage(host, log, errorManager, options) {
34807
+ const settings = host.services.setting.currentSettings();
34808
+ const showingNotice = options.showingNotice ?? false;
34809
+ await loadFileStatus(host);
34810
+ const { storageFileNameMap, storageFileNameCI2CS } = await collectFilesOnStorage(host, settings, log);
34811
+ const { databaseFileNameMap, databaseFileNameCI2CS, quarantinedFileNamesLC } = await collectDatabaseFiles(host, settings, log, showingNotice);
34812
+ const pairs = [];
34813
+ for (const fileNameLC of unique([...Object.keys(storageFileNameCI2CS), ...Object.keys(databaseFileNameCI2CS)])) {
34814
+ if (quarantinedFileNamesLC.has(fileNameLC)) continue;
34815
+ const fileName = fileNameLC in storageFileNameCI2CS ? storageFileNameCI2CS[fileNameLC] : void 0;
34816
+ const file = fileName ? storageFileNameMap[fileName] : void 0;
34817
+ const databaseName = fileNameLC in databaseFileNameCI2CS ? databaseFileNameCI2CS[fileNameLC] : void 0;
34818
+ const pair = {
34819
+ file,
34820
+ doc: databaseName ? databaseFileNameMap[databaseName] : void 0
34821
+ };
34822
+ pairs.push(pair);
34823
+ }
34824
+ log(`Total files to synchronise: ${pairs.length}`, 16, "syncAll");
34825
+ let completedCount = 0;
34826
+ let skippedCount = 0;
34827
+ let failedCount = 0;
34828
+ let processedCount = 0;
34829
+ for await (const { path, result } of withConcurrency(pairs, async (e) => {
34830
+ const path2 = e.file?.path ?? getPathFromEntry(host, e.doc);
34831
+ try {
34832
+ return {
34833
+ path: path2,
34834
+ result: await processFilePair(host, log, e, options)
34835
+ };
34836
+ } catch (ex) {
34837
+ log(`Error while synchronising files`, 64);
34838
+ log(ex, 16);
34839
+ return {
34840
+ path: path2,
34841
+ result: FilePairProcessResults.FAILED
34842
+ };
34843
+ }
34844
+ }, 10)) {
34845
+ processedCount++;
34846
+ switch (result) {
34847
+ case FilePairProcessResults.COMPLETED:
34848
+ completedCount++;
34849
+ break;
34850
+ case FilePairProcessResults.SKIPPED:
34851
+ skippedCount++;
34852
+ break;
34853
+ case FilePairProcessResults.FAILED:
34854
+ failedCount++;
34855
+ log(`Offline scan failed to synchronise ${path} between storage and the local database; this path remains eligible for a later scan.`, 16);
34856
+ break;
34857
+ }
34858
+ if (processedCount % 25 === 0) log(`Processing: ${processedCount}/${pairs.length}`, showingNotice ? 64 : 32, "syncAll");
34859
+ }
34860
+ log(`Synchronisation completed: ${processedCount} files processed (${completedCount} completed, ${skippedCount} skipped, ${failedCount} failed)`, showingNotice ? 64 : 32, "syncAll");
34861
+ saveFileStatus(host, true);
34862
+ if (failedCount === 0) return VaultScanResults.COMPLETED;
34863
+ return options.continueOnFileFailure === true ? VaultScanResults.COMPLETED_WITH_FILE_FAILURES : VaultScanResults.FAILED;
34864
+ }
34865
+ function normaliseFullScanOptions(showingNoticeOrOptions, ignoreSuspending = false) {
34866
+ if (typeof showingNoticeOrOptions === "object") return {
34867
+ mode: FullScanModes.NEWER_WINS,
34868
+ ...showingNoticeOrOptions
34869
+ };
34870
+ return {
34871
+ mode: FullScanModes.NEWER_WINS,
34872
+ showingNotice: showingNoticeOrOptions ?? false,
34873
+ ignoreSuspending
34874
+ };
34875
+ }
34876
+ var fileMaps = /* @__PURE__ */ new Map();
34877
+ var FILE_STATUS_MAP_KEY = "fileStatusMap";
34878
+ var FILE_STATUS_MAP_LOCK = "offlineScanner-fileStatusMap";
34879
+ async function loadFileStatus(host) {
34880
+ await serialized(FILE_STATUS_MAP_LOCK, async () => {
34881
+ const kvDB = host.services.keyValueDB.kvDB;
34882
+ if (!kvDB?.get) {
34883
+ fileMaps = /* @__PURE__ */ new Map();
34884
+ return;
34885
+ }
34886
+ const mapItems = await kvDB.get(FILE_STATUS_MAP_KEY) || {};
34887
+ fileMaps = new Map(Object.entries(mapItems));
34888
+ });
34889
+ }
34890
+ async function _saveFileStatus(host) {
34891
+ await serialized(FILE_STATUS_MAP_LOCK, async () => {
34892
+ const kvDB = host.services.keyValueDB.kvDB;
34893
+ if (!kvDB?.set) return;
34894
+ await kvDB.set(FILE_STATUS_MAP_KEY, Object.fromEntries(fileMaps));
34895
+ });
34896
+ }
34897
+ var saveFileStatusTimeout = null;
34898
+ function saveFileStatus(host, immediate = false) {
34899
+ if (immediate) {
34900
+ if (saveFileStatusTimeout !== null) compatGlobal.clearTimeout(saveFileStatusTimeout);
34901
+ saveFileStatusTimeout = compatGlobal.setTimeout(() => {
34902
+ saveFileStatusTimeout = null;
34903
+ _saveFileStatus(host);
34904
+ }, 0);
34905
+ return;
34906
+ }
34907
+ if (saveFileStatusTimeout === null) saveFileStatusTimeout = compatGlobal.setTimeout(() => {
34908
+ saveFileStatusTimeout = null;
34909
+ _saveFileStatus(host);
34910
+ }, 1e3);
34911
+ }
34912
+ function updateFileMTimeInMap(host, key, mtime) {
34913
+ fileMaps.set(key, mtime);
34914
+ saveFileStatus(host);
34915
+ }
34916
+ function getFileMTimeFromMap(key) {
34917
+ return fileMaps.get(key);
34918
+ }
34919
+ async function performFullScan(host, log, errorManager, showingNoticeOrOptions = false, ignoreSuspending = false) {
34920
+ const options = normaliseFullScanOptions(showingNoticeOrOptions, ignoreSuspending);
34921
+ const showingNotice = options.showingNotice ?? false;
34922
+ if (!canProceedScan(host, errorManager, log, showingNotice, options.ignoreSuspending ?? false)) return false;
34923
+ log("Opening the key-value database", 16);
34924
+ const isInitialized = await host.services.keyValueDB.kvDB.get("initialized") || false;
34925
+ if (showingNotice) log("Initializing", 64, "syncAll");
34926
+ if (isInitialized) {
34927
+ log("Restoring storage state", 16);
34928
+ await host.serviceModules.storageAccess.restoreState();
34929
+ }
34930
+ log("Initialize and checking database files");
34931
+ log("Checking deleted files");
34932
+ await collectDeletedFiles(host, log);
34933
+ const scanResult = await synchroniseAllFilesBetweenDBandStorage(host, log, errorManager, options);
34934
+ log("Initialized, NOW TRACKING!");
34935
+ if (!isInitialized) await host.services.keyValueDB.kvDB.set("initialized", true);
34936
+ if (showingNotice) log("Initialize done!", 64, "syncAll");
34937
+ return scanResult;
34938
+ }
34939
+ //#endregion
34940
+ //#region ../../modules/main/ModuleLiveSyncMain.ts
34941
+ var ModuleLiveSyncMain = class extends AbstractModule {
34942
+ async _onLiveSyncReady() {
34943
+ if (!await this.core.services.appLifecycle.onLayoutReady()) return false;
34944
+ eventHub.emitEvent(EVENT_LAYOUT_READY);
34945
+ if (this.settings.suspendFileWatching || this.settings.suspendParseReplicationResult) {
34946
+ const ANSWER_KEEP = $msg("moduleLiveSyncMain.optionKeepLiveSyncDisabled");
34947
+ const ANSWER_RESUME = $msg("moduleLiveSyncMain.optionResumeAndRestart");
34948
+ const message = $msg("moduleLiveSyncMain.msgScramEnabled", {
34949
+ fileWatchingStatus: this.settings.suspendFileWatching ? "suspended" : "active",
34950
+ parseReplicationStatus: this.settings.suspendParseReplicationResult ? "suspended" : "active"
34951
+ });
34952
+ if (await this.core.confirm.askSelectStringDialogue(message, [ANSWER_KEEP, ANSWER_RESUME], {
34953
+ defaultAction: ANSWER_KEEP,
34954
+ title: $msg("moduleLiveSyncMain.titleScramEnabled")
34955
+ }) == ANSWER_RESUME) {
34956
+ this.settings.suspendFileWatching = false;
34957
+ this.settings.suspendParseReplicationResult = false;
34958
+ await this.saveSettings();
34959
+ this.services.appLifecycle.scheduleRestart();
34960
+ return false;
34627
34961
  }
34962
+ }
34963
+ const initialisationResult = await this.services.databaseEvents.initialiseDatabase(false, false, false, true);
34964
+ if (initialisationResult === VaultScanResults.FAILED) {
34965
+ this._log($msg("Ui.Common.LocalDatabaseInitialisationFailed"), 64);
34966
+ return false;
34967
+ }
34968
+ if (initialisationResult === VaultScanResults.COMPLETED_WITH_FILE_FAILURES) this._log($msg("Ui.Common.SomeFilesCouldNotBeSynchronised"), 64);
34969
+ if (!await this.core.services.appLifecycle.onFirstInitialise()) return false;
34970
+ await this.services.control.applySettings();
34971
+ fireAndForget(async () => {
34972
+ this._log($msg("moduleLiveSyncMain.logAdditionalSafetyScan"), 16);
34973
+ if (!await this.services.appLifecycle.onScanningStartupIssues()) this._log($msg("moduleLiveSyncMain.logSafetyScanFailed"), 64);
34974
+ else this._log($msg("moduleLiveSyncMain.logSafetyScanCompleted"), 16);
34628
34975
  });
34629
- this.addCommand({
34630
- id: "livesync-abortsync",
34631
- name: "Abort synchronization immediately",
34632
- checkCallback: (checking) => {
34633
- if (!this.settings.useAdvancedMode) return false;
34634
- if (!checking) fireAndForget(() => this.services.replication.stopActiveTransfer());
34635
- return true;
34636
- }
34976
+ return true;
34977
+ }
34978
+ _wireUpEvents() {
34979
+ eventHub.onEvent(EVENT_SETTING_SAVED, (settings) => {
34980
+ fireAndForget(async () => {
34981
+ try {
34982
+ const lang = this.core.services.setting.currentSettings()?.displayLanguage;
34983
+ if (lang !== void 0) setLang(lang);
34984
+ if (this.core.services.database.isDatabaseReady()) await this.core.services.control.applySettings();
34985
+ eventHub.emitEvent(EVENT_REQUEST_RELOAD_SETTING_TAB);
34986
+ } catch (e) {
34987
+ this._log(`Error in Setting Save Event`, 64);
34988
+ this._log(e, 16);
34989
+ }
34990
+ });
34637
34991
  });
34638
34992
  return Promise.resolve(true);
34639
34993
  }
34994
+ async _onLiveSyncLoad() {
34995
+ this.services.context.events;
34996
+ await this.services.appLifecycle.onWireUpEvents();
34997
+ eventHub.emitEvent(EVENT_PLUGIN_LOADED);
34998
+ this._log($msg("moduleLiveSyncMain.logLoadingPlugin"));
34999
+ if (!await this.services.appLifecycle.onInitialise()) {
35000
+ this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"), 64);
35001
+ return false;
35002
+ }
35003
+ this._log($msg("moduleLiveSyncMain.logPluginVersion", {
35004
+ manifestVersion,
35005
+ packageVersion
35006
+ }));
35007
+ await this.services.setting.loadSettings();
35008
+ if (!await this.services.appLifecycle.onSettingLoaded()) {
35009
+ this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"), 64);
35010
+ return false;
35011
+ }
35012
+ await this.services.database.openDatabase({
35013
+ databaseEvents: this.services.databaseEvents,
35014
+ replicator: this.services.replicator
35015
+ });
35016
+ await this.core.services.appLifecycle.onLoaded();
35017
+ await Promise.all(this.core.addOns.map((e) => Promise.resolve(e.onload())));
35018
+ return true;
35019
+ }
34640
35020
  onBindFunction(core, services) {
34641
- services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this));
35021
+ super.onBindFunction(core, services);
35022
+ services.appLifecycle.onReady.addHandler(this._onLiveSyncReady.bind(this));
35023
+ services.appLifecycle.onWireUpEvents.addHandler(this._wireUpEvents.bind(this));
35024
+ services.appLifecycle.onLoad.addHandler(this._onLiveSyncLoad.bind(this));
34642
35025
  }
34643
35026
  };
34644
35027
  //#endregion
34645
35028
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/serviceFeatures/prepareDatabaseForUse.js
34646
- async function prepareDatabaseForUse(host, log, errorManager, showingNotice = false, reopenDatabase = true, ignoreSuspending = false) {
35029
+ function reportPreparationFailure(log, message) {
35030
+ log(message, 16);
35031
+ return false;
35032
+ }
35033
+ async function prepareDatabaseForUse(host, log, errorManager, showingNotice = false, reopenDatabase = true, ignoreSuspending = false, continueOnFileFailure = false) {
34647
35034
  const appLifecycle = host.services.appLifecycle;
34648
35035
  appLifecycle.resetIsReady();
34649
- if (reopenDatabase && !await host.services.database.openDatabase({
34650
- databaseEvents: host.services.databaseEvents,
34651
- replicator: host.services.replicator
34652
- })) return false;
34653
- if (!host.services.database.isDatabaseReady()) return false;
34654
- if (!await host.services.vault.scanVault(showingNotice, ignoreSuspending)) return false;
34655
- const ERR_INITIALISATION_FAILED = `Initializing database has been failed on some module!`;
34656
- if (!await host.services.databaseEvents.onDatabaseInitialised(showingNotice)) {
34657
- errorManager.showError(ERR_INITIALISATION_FAILED, 64);
34658
- return false;
35036
+ try {
35037
+ if (reopenDatabase && !await host.services.database.openDatabase({
35038
+ databaseEvents: host.services.databaseEvents,
35039
+ replicator: host.services.replicator
35040
+ })) return reportPreparationFailure(log, "Database preparation stopped because the local database could not be opened.");
35041
+ if (!host.services.database.isDatabaseReady()) return reportPreparationFailure(log, "Database preparation stopped because the local database is not ready.");
35042
+ const scanResult = await host.services.vault.scanVault(showingNotice, ignoreSuspending, continueOnFileFailure);
35043
+ if (scanResult === VaultScanResults.FAILED) return reportPreparationFailure(log, "Database preparation stopped because the Vault scan failed.");
35044
+ if (scanResult === VaultScanResults.COMPLETED_WITH_FILE_FAILURES && continueOnFileFailure !== true) return reportPreparationFailure(log, "Database preparation stopped because the Vault scan could not process every file.");
35045
+ if (!await host.services.databaseEvents.onDatabaseInitialised(showingNotice)) return reportPreparationFailure(log, "Database preparation stopped because an initialisation handler failed.");
35046
+ if (!await host.services.fileProcessing.commitPendingFileEvents()) return reportPreparationFailure(log, "Database preparation stopped because pending file events could not be committed.");
35047
+ appLifecycle.markIsReady();
35048
+ return scanResult;
35049
+ } catch (error) {
35050
+ log(error, 16);
35051
+ throw error;
34659
35052
  }
34660
- errorManager.clearError(ERR_INITIALISATION_FAILED);
34661
- if (!await host.services.fileProcessing.commitPendingFileEvents()) return false;
34662
- appLifecycle.markIsReady();
34663
- return true;
34664
35053
  }
34665
35054
  function usePrepareDatabaseForUse(host) {
34666
35055
  const log = createInstanceLogFunction("SF:prepareDatabaseForUse", host.services.API);
34667
35056
  const errorManager = new UnresolvedErrorManager(host.services.appLifecycle, host.services.context.events);
34668
- const initialiseDatabaseHandler = async (showingNotice = false, reopenDatabase = true, ignoreSuspending = false) => {
34669
- return await prepareDatabaseForUse(host, log, errorManager, showingNotice, reopenDatabase, ignoreSuspending);
35057
+ const initialiseDatabaseHandler = async (showingNotice = false, reopenDatabase = true, ignoreSuspending = false, continueOnFileFailure = false) => {
35058
+ return await prepareDatabaseForUse(host, log, errorManager, showingNotice, reopenDatabase, ignoreSuspending, continueOnFileFailure);
34670
35059
  };
34671
35060
  host.services.databaseEvents.initialiseDatabase.addHandler(initialiseDatabaseHandler);
34672
35061
  }
@@ -34975,7 +35364,7 @@ async function countCompromisedChunks(db) {
34975
35364
  }
34976
35365
  //#endregion
34977
35366
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/pouchdb/LiveSyncDBFunctions.js
34978
- async function ensureRemoteIsCompatible(infoSrc, setting, deviceNodeID, currentVersionRange, nodeDeviceInfo, updateCallback) {
35367
+ async function ensureRemoteIsCompatible(infoSrc, setting, deviceNodeID, currentVersionRange, nodeDeviceInfo, updateCallback, recordTweakAssessment) {
34979
35368
  const now = Date.now();
34980
35369
  const baseMilestone = {
34981
35370
  _id: MILESTONE_DOCID,
@@ -35051,14 +35440,9 @@ async function ensureRemoteIsCompatible(infoSrc, setting, deviceNodeID, currentV
35051
35440
  }
35052
35441
  if (!setting.disableCheckingConfigMismatch) {
35053
35442
  const preferred_tweak = remoteMilestone.tweak_values?.["PREFERRED"] ?? currentTweakValues;
35054
- const current_tweak = currentTweakValues;
35055
- if (isObjectDifferent(extractObject(TweakValuesShouldMatchedTemplate, {
35056
- ...TweakValuesDefault,
35057
- ...preferred_tweak
35058
- }), extractObject(TweakValuesShouldMatchedTemplate, {
35059
- ...TweakValuesDefault,
35060
- ...current_tweak
35061
- }), true)) return ["MISMATCHED", preferred_tweak];
35443
+ const tweakAssessment = assessTweakCompatibility(currentTweakValues, preferred_tweak);
35444
+ recordTweakAssessment?.(tweakAssessment);
35445
+ if (tweakAssessment.alignment === "mismatched") return ["MISMATCHED", preferred_tweak];
35062
35446
  }
35063
35447
  if (remoteMilestone.locked) {
35064
35448
  if (remoteMilestone.accepted_nodes.indexOf(deviceNodeID) == -1) {
@@ -35069,10 +35453,10 @@ async function ensureRemoteIsCompatible(infoSrc, setting, deviceNodeID, currentV
35069
35453
  }
35070
35454
  return "OK";
35071
35455
  }
35072
- async function ensureDatabaseIsCompatible(db, setting, deviceNodeID, currentVersionRange, nodeDeviceInfo) {
35456
+ async function ensureDatabaseIsCompatible(db, setting, deviceNodeID, currentVersionRange, nodeDeviceInfo, recordTweakAssessment) {
35073
35457
  return await ensureRemoteIsCompatible(await resolveWithIgnoreKnownError(db.get(MILESTONE_DOCID), false), setting, deviceNodeID, currentVersionRange, nodeDeviceInfo, async (info) => {
35074
35458
  await db.put(info);
35075
- });
35459
+ }, recordTweakAssessment);
35076
35460
  }
35077
35461
  //#endregion
35078
35462
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/replication/LiveSyncAbstractReplicator.js
@@ -36257,7 +36641,10 @@ ${sendingDocs}/(${sentDocsCount} done)`, showResult ? 64 : 32, "send");
36257
36641
  device_name: this.env.services.vault.getVaultName(),
36258
36642
  progress
36259
36643
  };
36260
- const ensure = await ensureDatabaseIsCompatible(dbRet.db, setting, this.nodeid, currentVersionRange$1, info);
36644
+ let tweakAssessment;
36645
+ const ensure = await ensureDatabaseIsCompatible(dbRet.db, setting, this.nodeid, currentVersionRange$1, info, (assessment) => {
36646
+ tweakAssessment = assessment;
36647
+ });
36261
36648
  if (ensure == "INCOMPATIBLE") {
36262
36649
  recordCompatibilityDecision?.(centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.INCOMPATIBLE_VERSION));
36263
36650
  Logger("The remote database has no compatibility with the running version. Please upgrade the plugin.", 64);
@@ -36279,7 +36666,7 @@ ${sendingDocs}/(${sentDocsCount} done)`, showResult ? 64 : 32, "send");
36279
36666
  return false;
36280
36667
  }
36281
36668
  else if (ensure == "OK") {} else if (ensure[0] == "MISMATCHED") {
36282
- recordCompatibilityDecision?.(centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH, ensure[1]));
36669
+ recordCompatibilityDecision?.(centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH, ensure[1], tweakAssessment));
36283
36670
  Logger(this.translate("liveSyncReplicator.mismatchedTweakDetected"), 64);
36284
36671
  this.tweakSettingsMismatched = true;
36285
36672
  this.preferredTweakValue = ensure[1];
@@ -55673,7 +56060,7 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
55673
56060
  else this._client = new JournalSyncCore(settings, this.simpleStore, this.env, new MinioStorageAdapter(settings, this.env));
55674
56061
  return this._client;
55675
56062
  }
55676
- async ensureBucketIsCompatible(deviceNodeID, currentVersionRange2, setting = this.currentSettings, client = this.setupJournalSyncClient(setting)) {
56063
+ async ensureBucketIsCompatible(deviceNodeID, currentVersionRange2, setting = this.currentSettings, client = this.setupJournalSyncClient(setting), recordTweakAssessment) {
55677
56064
  const milestoneResult = await client.downloadJsonWithResult(MILSTONE_DOCID);
55678
56065
  if (milestoneResult.status === JournalStorageReadStatuses.UNAVAILABLE) throw milestoneResult.error;
55679
56066
  const downloadedMilestone = milestoneResult.status === JournalStorageReadStatuses.AVAILABLE ? milestoneResult.value : false;
@@ -55686,7 +56073,7 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
55686
56073
  progress
55687
56074
  }, async (info) => {
55688
56075
  if (!await client.uploadJson(MILSTONE_DOCID, info)) throw new Error("Could not upload remote milestone");
55689
- });
56076
+ }, recordTweakAssessment);
55690
56077
  }
55691
56078
  constructor(env) {
55692
56079
  super(env);
@@ -55806,7 +56193,10 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
55806
56193
  this.remoteLockedAndDeviceNotAccepted = false;
55807
56194
  this.tweakSettingsMismatched = false;
55808
56195
  this.preferredTweakValue = void 0;
55809
- const ensure = await this.ensureBucketIsCompatible(this.nodeid, currentVersionRange, setting, client);
56196
+ let tweakAssessment;
56197
+ const ensure = await this.ensureBucketIsCompatible(this.nodeid, currentVersionRange, setting, client, (assessment) => {
56198
+ tweakAssessment = assessment;
56199
+ });
55810
56200
  if (ensure == "INCOMPATIBLE") {
55811
56201
  recordCompatibilityDecision?.(centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.INCOMPATIBLE_VERSION));
55812
56202
  Logger("The remote database has no compatibility with the running version. Please upgrade the plugin.", 64);
@@ -55828,7 +56218,7 @@ var LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
55828
56218
  return false;
55829
56219
  }
55830
56220
  else if (ensure == "OK") {} else if (ensure[0] == "MISMATCHED") {
55831
- recordCompatibilityDecision?.(centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH, ensure[1]));
56221
+ recordCompatibilityDecision?.(centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH, ensure[1], tweakAssessment));
55832
56222
  Logger(this.translate("liveSyncReplicator.mismatchedTweakDetected"), 64);
55833
56223
  this.tweakSettingsMismatched = true;
55834
56224
  this.preferredTweakValue = ensure[1];
@@ -56482,6 +56872,23 @@ function createAutomaticReplicationTriggers(context) {
56482
56872
  };
56483
56873
  }
56484
56874
  //#endregion
56875
+ //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/common/utils.doc.js
56876
+ function isErrorOf(ex, statusCode) {
56877
+ if (!ex || typeof ex !== "object") throw new Error(`Expected an object error, but got ${typeof ex}`);
56878
+ if ("status" in ex && typeof ex.status === "number" && ex.status == statusCode) return true;
56879
+ return false;
56880
+ }
56881
+ function isNotFoundError(ex) {
56882
+ return isErrorOf(ex, 404);
56883
+ }
56884
+ function isEntryWithPath(entry) {
56885
+ if (!entry || typeof entry !== "object") return false;
56886
+ return "path" in entry && typeof entry.path === "string";
56887
+ }
56888
+ function tryGetFilePath(entry) {
56889
+ if (isEntryWithPath(entry)) return entry.path;
56890
+ }
56891
+ //#endregion
56485
56892
  //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/pouchdb/chunks.js
56486
56893
  async function purgeUnreferencedChunks(db, dryRun, connSetting, performCompact = false) {
56487
56894
  const info = await db.info();
@@ -56788,6 +57195,8 @@ Even if you choose to clean up, you will see this option again if you exit Obsid
56788
57195
  const recovery = outcome.recoveryHint;
56789
57196
  if (!recovery) return false;
56790
57197
  if (recovery.reason === CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH && recovery.preferredTweakValue) {
57198
+ if (!await context.services.replicator.runWithActiveReplicatorContext((activeContext) => activeContext === failedContext) || JSON.stringify(setting) !== JSON.stringify(context.services.setting.currentSettings())) return false;
57199
+ const assessment = recovery.tweakAssessment ?? assessTweakCompatibility(setting, recovery.preferredTweakValue);
56791
57200
  await context.services.tweakValue.askResolvingMismatched(recovery.preferredTweakValue, async (effectiveSetting) => {
56792
57201
  let updated = false;
56793
57202
  await context.services.replicator.runWithActiveReplicatorContext(async (activeContext) => {
@@ -56797,7 +57206,7 @@ Even if you choose to clean up, you will see this option again if you exit Obsid
56797
57206
  updated = true;
56798
57207
  });
56799
57208
  return updated;
56800
- });
57209
+ }, assessment);
56801
57210
  return false;
56802
57211
  }
56803
57212
  if (recovery.reason !== CENTRAL_COMPATIBILITY_REJECTION_REASONS.NODE_LOCKED && recovery.reason !== CENTRAL_COMPATIBILITY_REJECTION_REASONS.NODE_CLEANED) return false;
@@ -56898,6 +57307,11 @@ var ReplicateResultProcessor = class {
56898
57307
  logError(e) {
56899
57308
  Logger(e, 16);
56900
57309
  }
57310
+ reportVaultReflectionFailure(entry, cause) {
57311
+ this.log(`Live replication could not reflect ${this.getPath(entry)} from the local database to the Vault; this path remains eligible for a later Vault scan.`, 16);
57312
+ if (cause !== void 0) this.logError(cause);
57313
+ Logger($msg("Ui.Common.SomeFilesCouldNotBeSynchronised"), 64);
57314
+ }
56901
57315
  constructor(context) {
56902
57316
  this.context = context;
56903
57317
  this._suspended = false;
@@ -57199,10 +57613,16 @@ var ReplicateResultProcessor = class {
57199
57613
  return;
57200
57614
  }
57201
57615
  if (await this.services.replication.processOptionalSynchroniseResult(dbDoc)) this.log(`Processed by other processor: ${docNote}`, -1);
57202
- else if (this.services.vault.isValidPath(this.getPath(doc))) {
57203
- await this.applyToStorage(doc);
57616
+ else if (this.services.vault.isValidPath(this.getPath(doc))) try {
57617
+ if (!await this.applyToStorage(doc)) {
57618
+ this.reportVaultReflectionFailure(doc);
57619
+ return;
57620
+ }
57204
57621
  this.log(`Processed: ${docNote}`, -1);
57205
- } else this.log(`Unprocessed (Invalid path): ${docNote}`, 16);
57622
+ } catch (error) {
57623
+ this.reportVaultReflectionFailure(doc, error);
57624
+ }
57625
+ else this.log(`Unprocessed (Invalid path): ${docNote}`, 16);
57206
57626
  });
57207
57627
  }
57208
57628
  /**
@@ -57211,9 +57631,7 @@ var ReplicateResultProcessor = class {
57211
57631
  * @returns
57212
57632
  */
57213
57633
  applyToStorage(entry) {
57214
- return this.withCounting(async () => {
57215
- await this.services.replication.processSynchroniseResult(entry);
57216
- }, this.services.replication.storageApplyingCount);
57634
+ return this.withCounting(() => this.services.replication.processSynchroniseResult(entry), this.services.replication.storageApplyingCount);
57217
57635
  }
57218
57636
  /**
57219
57637
  * Check whether processing is required for the given document.
@@ -57302,6 +57720,7 @@ function useReplicationFeature(core) {
57302
57720
  API: services.API,
57303
57721
  appLifecycle: services.appLifecycle,
57304
57722
  replicator: services.replicator,
57723
+ setting: services.setting,
57305
57724
  tweakValue: services.tweakValue
57306
57725
  }
57307
57726
  });
@@ -57328,6 +57747,531 @@ function useReplicationFeature(core) {
57328
57747
  services.replication.onReplicationFailed.addHandler(centralCompatibilityRecovery.handleReplicationFailure);
57329
57748
  }
57330
57749
  //#endregion
57750
+ //#region ../../serviceFeatures/conflictResolution/checker.ts
57751
+ /** Create conflict-checking handlers while retaining scheduling state privately. */
57752
+ function createConflictCheckingHandlers(dependencies) {
57753
+ const conflictQueue = new QueueProcessor(async (filenames) => {
57754
+ const filename = filenames[0];
57755
+ return await dependencies.conflict.resolve(filename);
57756
+ }, {
57757
+ suspended: false,
57758
+ batchSize: 1,
57759
+ concurrentLimit: 10,
57760
+ delay: 0,
57761
+ keepResultUntilDownstreamConnected: false,
57762
+ totalRemainingReactiveSource: dependencies.conflictProcessQueueCount
57763
+ }).replaceEnqueueProcessor((queue, newEntity) => {
57764
+ return [...[...queue].filter((entry) => entry != newEntity), newEntity];
57765
+ });
57766
+ const queueCheckForIfOpen = async (file) => {
57767
+ const path = file;
57768
+ if (dependencies.currentSettings().checkConflictOnlyOnOpen) {
57769
+ const activeFile = dependencies.vault.getActiveFilePath();
57770
+ if (activeFile && activeFile != path) {
57771
+ dependencies.log(`${file} is conflicted, merging process has been postponed.`, 64);
57772
+ return;
57773
+ }
57774
+ }
57775
+ await dependencies.conflict.queueCheckFor(path);
57776
+ };
57777
+ const queueCheckFor = async (file) => {
57778
+ const optionalConflictResult = await dependencies.conflict.getOptionalConflictCheckMethod(file);
57779
+ if (optionalConflictResult == true) return;
57780
+ else if (optionalConflictResult === "newer") await dependencies.conflict.resolveByNewest(file);
57781
+ else conflictQueue.enqueue(file);
57782
+ };
57783
+ const ensureAllProcessed = () => conflictQueue.waitForAllProcessed();
57784
+ return {
57785
+ queueCheckForIfOpen,
57786
+ queueCheckFor,
57787
+ ensureAllProcessed
57788
+ };
57789
+ }
57790
+ //#endregion
57791
+ //#region ../../serviceFeatures/conflictResolution/operations.ts
57792
+ function createConflictResolutionOperations(dependencies) {
57793
+ const latestResolveRequestByFilename = /* @__PURE__ */ new Map();
57794
+ let nextResolveRequestId = 0;
57795
+ const resolveByDeletingRevision = async (path, deleteRevision, subTitle = "", showNotice = true) => {
57796
+ const title = `Resolving ${subTitle ? `[${subTitle}]` : ""}:`;
57797
+ if (!await dependencies.fileHandler.deleteRevisionFromDB(path, deleteRevision)) {
57798
+ dependencies.log(`${title} Could not delete conflicted revision ${displayRev(deleteRevision)} of ${path}`, 64);
57799
+ return MISSING_OR_ERROR;
57800
+ }
57801
+ dependencies.events.emitEvent(EVENT_CONFLICT_CANCELLED, path);
57802
+ dependencies.log(`${title} Conflicted revision has been deleted ${displayRev(deleteRevision)} ${path}`, 32);
57803
+ if ((await dependencies.databaseFileAccess.getConflictedRevs(path)).length != 0) {
57804
+ dependencies.log(`${title} some conflicts are left in ${path}`, 32);
57805
+ return AUTO_MERGED;
57806
+ }
57807
+ if (isPluginMetadata(path) || isCustomisationSyncMetadata(path)) {
57808
+ dependencies.log(`${title} ${path} is a plugin metadata file, no need to write to storage`, 32);
57809
+ return AUTO_MERGED;
57810
+ }
57811
+ if (!await dependencies.fileHandler.dbToStorage(path, stripAllPrefixes(path), true)) {
57812
+ dependencies.log(`Could not write the resolved content to the storage: ${path}`, 64);
57813
+ return MISSING_OR_ERROR;
57814
+ }
57815
+ const level = subTitle.indexOf("same") !== -1 || !showNotice ? 32 : 64;
57816
+ dependencies.log(`${path} has been merged automatically`, level);
57817
+ return AUTO_MERGED;
57818
+ };
57819
+ const checkConflictAndPerformAutoMerge = async (path) => {
57820
+ const ret = await dependencies.localDatabase().tryAutoMerge(path, !dependencies.currentSettings().disableMarkdownAutoMerge);
57821
+ if ("ok" in ret) return ret.ok;
57822
+ if ("result" in ret) {
57823
+ const p = ret.result;
57824
+ if (!await dependencies.databaseFileAccess.storeContent(path, p)) {
57825
+ dependencies.log(`Merged content cannot be stored:${path}`, 64);
57826
+ return MISSING_OR_ERROR;
57827
+ }
57828
+ return await dependencies.conflict.resolveByDeletingRevision(path, ret.conflictedRev, "Sensible");
57829
+ }
57830
+ const { rightRev, leftLeaf, rightLeaf } = ret;
57831
+ if (leftLeaf == false) {
57832
+ dependencies.log(`could not get current revisions:${path}`, 64);
57833
+ return MISSING_OR_ERROR;
57834
+ }
57835
+ if (rightLeaf == false) {
57836
+ dependencies.log(`could not read conflicted revision ${rightRev}:${path}`, 64);
57837
+ return MISSING_OR_ERROR;
57838
+ }
57839
+ const isSame = leftLeaf.data == rightLeaf.data && leftLeaf.deleted == rightLeaf.deleted;
57840
+ const isBinary = !isPlainText(path);
57841
+ const alwaysNewer = dependencies.currentSettings().resolveConflictsByNewerFile;
57842
+ if (isSame || isBinary || alwaysNewer) {
57843
+ const result = compareMTime(leftLeaf.mtime, rightLeaf.mtime);
57844
+ let loser = leftLeaf;
57845
+ if (result != TARGET_IS_NEW) loser = rightLeaf;
57846
+ const subTitle = [
57847
+ `${isSame ? "same" : ""}`,
57848
+ `${isBinary ? "binary" : ""}`,
57849
+ `${alwaysNewer ? "alwaysNewer" : ""}`
57850
+ ].filter((e) => e.trim()).join(",");
57851
+ return await dependencies.conflict.resolveByDeletingRevision(path, loser.rev, subTitle);
57852
+ }
57853
+ const dmp = new import_diff_match_patch.default();
57854
+ const diff = dmp.diff_main(leftLeaf.data, rightLeaf.data);
57855
+ dmp.diff_cleanupSemantic(diff);
57856
+ dependencies.log(`conflict(s) found:${path}`);
57857
+ return {
57858
+ left: leftLeaf,
57859
+ right: rightLeaf,
57860
+ diff
57861
+ };
57862
+ };
57863
+ const resolve = async (filename) => {
57864
+ const requestId = ++nextResolveRequestId;
57865
+ latestResolveRequestByFilename.set(filename, requestId);
57866
+ const serialisationKey = `conflict-resolve:${filename}`;
57867
+ if (isLockAcquired(serialisationKey)) dependencies.events.emitEvent(EVENT_CONFLICT_CANCELLED, filename);
57868
+ return await serialized(serialisationKey, async () => {
57869
+ if (latestResolveRequestByFilename.get(filename) !== requestId) return;
57870
+ try {
57871
+ const conflictCheckResult = await checkConflictAndPerformAutoMerge(filename);
57872
+ if (latestResolveRequestByFilename.get(filename) !== requestId) return;
57873
+ if (conflictCheckResult === NOT_CONFLICTED) {
57874
+ dependencies.events.emitEvent(EVENT_CONFLICT_CANCELLED, filename);
57875
+ dependencies.log(`[conflict] Not conflicted or cancelled: ${filename}`, 16);
57876
+ return;
57877
+ }
57878
+ if (conflictCheckResult === MISSING_OR_ERROR || conflictCheckResult === CANCELLED) {
57879
+ dependencies.log(`[conflict] Not conflicted or cancelled: ${filename}`, 16);
57880
+ return;
57881
+ }
57882
+ if (conflictCheckResult === AUTO_MERGED) {
57883
+ if (dependencies.currentSettings().syncAfterMerge && !dependencies.appLifecycle.isSuspended()) await dependencies.replication.replicateUnattendedByEvent({
57884
+ trigger: "merge",
57885
+ interaction: NO_INTERACTION
57886
+ });
57887
+ dependencies.log("[conflict] Automatically merged, but we have to check it again");
57888
+ await dependencies.conflict.queueCheckFor(filename);
57889
+ return;
57890
+ }
57891
+ if (dependencies.currentSettings().showMergeDialogOnlyOnActive) {
57892
+ const activeFile = dependencies.vault.getActiveFilePath();
57893
+ if (activeFile && activeFile != filename) {
57894
+ dependencies.log(`[conflict] ${filename} is conflicted. Merging process has been postponed to the file have got opened.`, 64);
57895
+ return;
57896
+ }
57897
+ }
57898
+ dependencies.log("[conflict] Manual merge required!");
57899
+ dependencies.events.emitEvent(EVENT_CONFLICT_CANCELLED, filename);
57900
+ await dependencies.conflict.resolveByUserInteraction(filename, conflictCheckResult);
57901
+ } finally {
57902
+ if (latestResolveRequestByFilename.get(filename) === requestId) latestResolveRequestByFilename.delete(filename);
57903
+ }
57904
+ });
57905
+ };
57906
+ const resolveByNewest = async (filename, showNotice = true) => {
57907
+ const currentRev = await dependencies.databaseFileAccess.fetchEntryMeta(filename, void 0, true);
57908
+ if (currentRev == false) {
57909
+ dependencies.log(`Could not get current revision of ${filename}`);
57910
+ return Promise.resolve(false);
57911
+ }
57912
+ const revs = await dependencies.databaseFileAccess.getConflictedRevs(filename);
57913
+ if (revs.length == 0) return Promise.resolve(true);
57914
+ const mTimeAndRev = [[currentRev.mtime, currentRev._rev], ...await Promise.all(revs.map(async (rev) => {
57915
+ const leaf = await dependencies.databaseFileAccess.fetchEntryMeta(filename, rev);
57916
+ if (leaf == false) return [0, rev];
57917
+ return [leaf.mtime, rev];
57918
+ }))].sort((a, b) => {
57919
+ const diff = b[0] - a[0];
57920
+ if (diff == 0) return a[1].localeCompare(b[1], "en", { numeric: true });
57921
+ return diff;
57922
+ });
57923
+ dependencies.log(`Resolving conflict by newest: ${filename} (Newest: ${new Date(mTimeAndRev[0][0]).toLocaleString()}) (${mTimeAndRev.length} revisions exists)`);
57924
+ for (let i = 1; i < mTimeAndRev.length; i++) {
57925
+ dependencies.log(`conflict: Deleting the older revision ${mTimeAndRev[i][1]} (${new Date(mTimeAndRev[i][0]).toLocaleString()}) of ${filename}`);
57926
+ await resolveByDeletingRevision(filename, mTimeAndRev[i][1], "NEWEST", showNotice);
57927
+ }
57928
+ return true;
57929
+ };
57930
+ const resolveAllConflictedFilesByNewerOnes = async () => {
57931
+ dependencies.log(`Resolving conflicts by newer ones`, 64);
57932
+ const files = await dependencies.storageAccess.getFileNames();
57933
+ let i = 0;
57934
+ for (const file of files) {
57935
+ i++;
57936
+ if (i % 10 === 0) dependencies.log(`Check and Processing ${i} / ${files.length}`, 64, "resolveAllConflictedFilesByNewerOnes");
57937
+ await resolveByNewest(file, false);
57938
+ }
57939
+ dependencies.log(`Done!`, 64, "resolveAllConflictedFilesByNewerOnes");
57940
+ };
57941
+ return {
57942
+ resolveByDeletingRevision,
57943
+ checkConflictAndPerformAutoMerge,
57944
+ resolve,
57945
+ resolveByNewest,
57946
+ resolveAllConflictedFilesByNewerOnes
57947
+ };
57948
+ }
57949
+ //#endregion
57950
+ //#region ../../serviceFeatures/conflictResolution/index.ts
57951
+ /** Compose the host-neutral conflict checker and resolver handlers. */
57952
+ function useConflictResolutionFeature(host) {
57953
+ const { services, serviceModules } = host;
57954
+ const log = createInstanceLogFunction("SF:ConflictResolution", services.API);
57955
+ const operations = createConflictResolutionOperations({
57956
+ events: services.context.events,
57957
+ databaseFileAccess: serviceModules.databaseFileAccess,
57958
+ fileHandler: serviceModules.fileHandler,
57959
+ localDatabase: () => services.database.localDatabase,
57960
+ conflict: services.conflict,
57961
+ replication: services.replication,
57962
+ appLifecycle: services.appLifecycle,
57963
+ vault: services.vault,
57964
+ storageAccess: serviceModules.storageAccess,
57965
+ currentSettings: () => services.setting.currentSettings(),
57966
+ log
57967
+ });
57968
+ const checking = createConflictCheckingHandlers({
57969
+ conflict: services.conflict,
57970
+ conflictProcessQueueCount: services.conflict.conflictProcessQueueCount,
57971
+ currentSettings: () => services.setting.currentSettings(),
57972
+ vault: services.vault,
57973
+ log
57974
+ });
57975
+ services.conflict.queueCheckForIfOpen.setHandler(checking.queueCheckForIfOpen);
57976
+ services.conflict.queueCheckFor.setHandler(checking.queueCheckFor);
57977
+ services.conflict.ensureAllProcessed.setHandler(checking.ensureAllProcessed);
57978
+ services.conflict.resolveByDeletingRevision.setHandler(operations.resolveByDeletingRevision);
57979
+ services.conflict.resolve.setHandler(operations.resolve);
57980
+ services.conflict.resolveByNewest.setHandler(operations.resolveByNewest);
57981
+ services.conflict.resolveAllConflictedFilesByNewerOnes.setHandler(operations.resolveAllConflictedFilesByNewerOnes);
57982
+ }
57983
+ //#endregion
57984
+ //#region ../../serviceFeatures/fileDatabaseInfo.ts
57985
+ var REPORT_WARNING = "All revisions and chunk availability below are a snapshot of this device's local database; the remote is not queried. Review the Vault-relative path, document identifier, content-derived chunk identifiers, and metadata before sharing this report. File contents are omitted.";
57986
+ function toDatabasePath(path) {
57987
+ if (path.startsWith(".")) return addPrefix(path, "i:");
57988
+ return path;
57989
+ }
57990
+ async function getLocalDatabaseMeta(core, path, options) {
57991
+ const documentId = await core.services.path.path2id(path);
57992
+ let raw;
57993
+ try {
57994
+ raw = await core.localDatabase.localDatabase.get(documentId, options);
57995
+ } catch (error) {
57996
+ if (isNotFoundError(error)) return false;
57997
+ throw error;
57998
+ }
57999
+ if (raw.type === "leaf") return false;
58000
+ if (raw.type && raw.type !== "notes" && raw.type !== "newnote" && raw.type !== "plain") return false;
58001
+ const rawStorageType = raw.type ?? null;
58002
+ const legacy = rawStorageType === null || rawStorageType === "notes";
58003
+ const type = legacy ? "notes" : rawStorageType;
58004
+ const legacyBodyPresent = legacy && (typeof raw.data === "string" || Array.isArray(raw.data) && raw.data.every((item) => typeof item === "string"));
58005
+ return {
58006
+ _id: raw._id,
58007
+ _rev: raw._rev,
58008
+ _conflicts: raw._conflicts,
58009
+ _revs_info: raw._revs_info,
58010
+ path,
58011
+ data: legacyBodyPresent ? raw.data : "",
58012
+ ctime: raw.ctime ?? 0,
58013
+ mtime: raw.mtime ?? 0,
58014
+ size: raw.size ?? 0,
58015
+ children: type === "newnote" || type === "plain" ? raw.children ?? [] : [],
58016
+ datatype: type === "newnote" ? "newnote" : "plain",
58017
+ deleted: raw.deleted ?? raw._deleted,
58018
+ type,
58019
+ eden: raw.eden ?? {},
58020
+ _rawStorageType: rawStorageType,
58021
+ _legacyBodyPresent: legacyBodyPresent
58022
+ };
58023
+ }
58024
+ async function collectRevisionDatabaseInfo(core, meta, current) {
58025
+ const legacy = meta._rawStorageType === null || meta._rawStorageType === "notes";
58026
+ const children = legacy ? [] : "children" in meta ? meta.children : [];
58027
+ const uniqueChildren = [...new Set(children)];
58028
+ const referenceCounts = /* @__PURE__ */ new Map();
58029
+ for (const child of children) referenceCounts.set(child, (referenceCounts.get(child) ?? 0) + 1);
58030
+ const embeddedChildren = new Set(Object.keys("eden" in meta && meta.eden ? meta.eden : {}).filter((id) => uniqueChildren.includes(id)));
58031
+ const localRows = uniqueChildren.length === 0 ? [] : (await core.localDatabase.allDocsRaw({
58032
+ keys: uniqueChildren,
58033
+ include_docs: false
58034
+ })).rows;
58035
+ const localChunkStates = new Map(localRows.filter((row) => "value" in row).map((row) => [row.key, {
58036
+ state: row.value.deleted ? "deleted" : "available",
58037
+ revision: row.value.rev
58038
+ }]));
58039
+ return {
58040
+ documentId: meta._id,
58041
+ revision: meta._rev ?? null,
58042
+ current,
58043
+ deleted: Boolean(meta.deleted ?? meta._deleted),
58044
+ storageType: meta._rawStorageType ?? "absent",
58045
+ storageLayout: legacy ? "legacy-inline" : "chunked",
58046
+ ctime: meta.ctime,
58047
+ mtime: meta.mtime,
58048
+ recordedSize: meta.size,
58049
+ revisionHistory: (meta._revs_info ?? []).map(({ rev, status }) => ({
58050
+ revision: rev,
58051
+ status
58052
+ })),
58053
+ chunkReferences: children.length,
58054
+ uniqueChunkReferences: uniqueChildren.length,
58055
+ embeddedChunkReferences: children.filter((id) => embeddedChildren.has(id)).length,
58056
+ locallyStoredChunkReferences: children.filter((id) => localChunkStates.get(id)?.state === "available").length,
58057
+ contentAvailableLocally: legacy ? meta._legacyBodyPresent : uniqueChildren.every((id) => embeddedChildren.has(id) || localChunkStates.get(id)?.state === "available"),
58058
+ chunks: uniqueChildren.map((id) => {
58059
+ const localState = localChunkStates.get(id);
58060
+ return {
58061
+ id,
58062
+ referenceCount: referenceCounts.get(id) ?? 0,
58063
+ embedded: embeddedChildren.has(id),
58064
+ storedInLocalDatabase: localState?.state === "available",
58065
+ localDatabaseState: localState?.state ?? "missing",
58066
+ localDatabaseRevision: localState?.revision ?? null
58067
+ };
58068
+ })
58069
+ };
58070
+ }
58071
+ function revisionHistory(meta) {
58072
+ const history = (meta._revs_info ?? []).map(({ rev, status }) => ({
58073
+ revision: rev,
58074
+ status
58075
+ }));
58076
+ if (meta._rev && !history.some(({ revision }) => revision === meta._rev)) history.unshift({
58077
+ revision: meta._rev,
58078
+ status: "available"
58079
+ });
58080
+ return history;
58081
+ }
58082
+ function missingChunkIds(info) {
58083
+ return info.chunks.filter(({ embedded, localDatabaseState }) => !embedded && localDatabaseState !== "available").map(({ id }) => id);
58084
+ }
58085
+ async function inspectFileDatabaseInfo(core, path) {
58086
+ const storageStat = await core.storageAccess.isExistsIncludeHidden(path) ? await core.storageAccess.statHidden(path) : null;
58087
+ const databasePath = toDatabasePath(path);
58088
+ const currentMeta = await getLocalDatabaseMeta(core, databasePath, {
58089
+ conflicts: true,
58090
+ revs: true,
58091
+ revs_info: true
58092
+ });
58093
+ const revisions = [];
58094
+ const conflictRevisions = currentMeta === false ? [] : currentMeta._conflicts ?? [];
58095
+ const unavailableConflictRevisions = [];
58096
+ const mergeBases = [];
58097
+ const metadataByRevision = /* @__PURE__ */ new Map();
58098
+ if (currentMeta !== false && currentMeta._rev) metadataByRevision.set(currentMeta._rev, currentMeta);
58099
+ const getRevisionMeta = async (revision) => {
58100
+ const cached = metadataByRevision.get(revision);
58101
+ if (cached !== void 0) return cached;
58102
+ const meta = await getLocalDatabaseMeta(core, databasePath, {
58103
+ rev: revision,
58104
+ revs: true,
58105
+ revs_info: true
58106
+ });
58107
+ metadataByRevision.set(revision, meta);
58108
+ return meta;
58109
+ };
58110
+ if (currentMeta) {
58111
+ revisions.push(await collectRevisionDatabaseInfo(core, currentMeta, true));
58112
+ for (const revision of conflictRevisions) {
58113
+ const conflictMeta = await getRevisionMeta(revision);
58114
+ if (conflictMeta) {
58115
+ revisions.push(await collectRevisionDatabaseInfo(core, conflictMeta, false));
58116
+ const winnerHistory = revisionHistory(currentMeta);
58117
+ const conflictHistory = revisionHistory(conflictMeta);
58118
+ const conflictHistoryByRevision = new Map(conflictHistory.map(({ revision: historyRevision, status }) => [historyRevision, status]));
58119
+ const sharedHistory = winnerHistory.filter(({ revision: historyRevision }) => conflictHistoryByRevision.has(historyRevision));
58120
+ const sharedRevision = sharedHistory[0]?.revision ?? null;
58121
+ const unavailableSharedRevisions = sharedHistory.filter(({ revision: historyRevision, status }) => status !== "available" || conflictHistoryByRevision.get(historyRevision) !== "available").map(({ revision: historyRevision }) => historyRevision);
58122
+ const sharedMeta = sharedRevision ? await getRevisionMeta(sharedRevision) : false;
58123
+ const sharedInfo = sharedMeta ? await collectRevisionDatabaseInfo(core, sharedMeta, false) : void 0;
58124
+ mergeBases.push({
58125
+ winnerRevision: currentMeta._rev ?? "",
58126
+ conflictRevision: revision,
58127
+ revision: sharedRevision,
58128
+ metadataAvailableLocally: Boolean(sharedMeta),
58129
+ contentAvailableLocally: sharedInfo?.contentAvailableLocally ?? false,
58130
+ missingChunkIds: sharedInfo ? missingChunkIds(sharedInfo) : [],
58131
+ unavailableSharedRevisions
58132
+ });
58133
+ } else unavailableConflictRevisions.push(revision);
58134
+ }
58135
+ }
58136
+ return {
58137
+ path,
58138
+ databasePath,
58139
+ storage: storageStat ? {
58140
+ exists: true,
58141
+ ctime: storageStat.ctime,
58142
+ mtime: storageStat.mtime,
58143
+ size: storageStat.size
58144
+ } : { exists: false },
58145
+ database: {
58146
+ source: "local database on this device",
58147
+ remoteQueried: false,
58148
+ exists: currentMeta !== false,
58149
+ currentRevision: currentMeta ? currentMeta._rev ?? null : null,
58150
+ conflictCount: conflictRevisions.length,
58151
+ conflictRevisions,
58152
+ unavailableConflictRevisions,
58153
+ revisions,
58154
+ mergeBases
58155
+ }
58156
+ };
58157
+ }
58158
+ async function buildFileDatabaseInfoReport(core, path) {
58159
+ const report = await inspectFileDatabaseInfo(core, path);
58160
+ return `${$msg(REPORT_WARNING)}
58161
+
58162
+ \`\`\`json
58163
+ ${JSON.stringify(report, null, 2)}
58164
+ \`\`\``;
58165
+ }
58166
+ async function copyFileDatabaseInfo(core, path) {
58167
+ const report = await buildFileDatabaseInfoReport(core, path);
58168
+ return await core.services.UI.promptCopyToClipboard($msg("Database information for ${FILE}", { FILE: path }), report);
58169
+ }
58170
+ //#endregion
58171
+ //#region ../../serviceFeatures/basicCommands.ts
58172
+ function createFileDatabaseInfoCore(host) {
58173
+ const { services, serviceModules } = host;
58174
+ return {
58175
+ localDatabase: services.database.localDatabase,
58176
+ services: {
58177
+ path: services.path,
58178
+ UI: services.UI
58179
+ },
58180
+ settings: services.setting.currentSettings(),
58181
+ storageAccess: serviceModules.storageAccess
58182
+ };
58183
+ }
58184
+ /**
58185
+ * Register the platform-independent command palette actions.
58186
+ *
58187
+ * Registration remains tied to `onInitialise`, matching the legacy module's
58188
+ * timing and allowing hosts to compose the feature before the lifecycle runs.
58189
+ */
58190
+ function useBasicCommandsFeature(host) {
58191
+ const { services } = host;
58192
+ const log = createInstanceLogFunction("SF:BasicCommands", services.API);
58193
+ services.appLifecycle.onInitialise.addHandler(() => {
58194
+ services.API.addCommand({
58195
+ id: "livesync-replicate",
58196
+ name: $msg("Sync now"),
58197
+ callback: async () => {
58198
+ await services.replication.replicateUserInitiated({
58199
+ trigger: "manual",
58200
+ progressPresentation: REPLICATION_PROGRESS_PRESENTATIONS.QUIET,
58201
+ interaction: USER_INITIATED_REPLICATION_AUTHORITY
58202
+ });
58203
+ }
58204
+ });
58205
+ services.API.addCommand({
58206
+ id: "livesync-dump",
58207
+ name: $msg("Copy database information for the active file"),
58208
+ checkCallback: (checking) => {
58209
+ const file = services.vault.getActiveFilePath();
58210
+ if (!file) return false;
58211
+ if (!checking) fireAndForget(() => copyFileDatabaseInfo(createFileDatabaseInfoCore(host), file));
58212
+ return true;
58213
+ }
58214
+ });
58215
+ services.API.addCommand({
58216
+ id: "livesync-toggle",
58217
+ name: "Toggle LiveSync",
58218
+ callback: async () => {
58219
+ const settings = services.setting.currentSettings();
58220
+ if (settings.liveSync) {
58221
+ settings.liveSync = false;
58222
+ log("LiveSync Disabled.", 64);
58223
+ } else {
58224
+ settings.liveSync = true;
58225
+ log("LiveSync Enabled.", 64);
58226
+ }
58227
+ await services.control.applySettings();
58228
+ await services.setting.saveSettingData();
58229
+ }
58230
+ });
58231
+ services.API.addCommand({
58232
+ id: "livesync-suspendall",
58233
+ name: "Toggle All Sync.",
58234
+ callback: async () => {
58235
+ if (services.appLifecycle.isSuspended()) {
58236
+ services.appLifecycle.setSuspended(false);
58237
+ log("Self-hosted LiveSync resumed", 64);
58238
+ } else {
58239
+ services.appLifecycle.setSuspended(true);
58240
+ log("Self-hosted LiveSync suspended", 64);
58241
+ }
58242
+ await services.control.applySettings();
58243
+ await services.setting.saveSettingData();
58244
+ }
58245
+ });
58246
+ services.API.addCommand({
58247
+ id: "livesync-scan-files",
58248
+ name: "Scan storage and database again",
58249
+ checkCallback: (checking) => {
58250
+ if (!services.setting.currentSettings().useAdvancedMode) return false;
58251
+ if (!checking) fireAndForget(() => services.vault.scanVault(true));
58252
+ return true;
58253
+ }
58254
+ });
58255
+ services.API.addCommand({
58256
+ id: "livesync-runbatch",
58257
+ name: $msg("Apply pending changes now"),
58258
+ callback: async () => {
58259
+ await services.fileProcessing.commitPendingFileEvents();
58260
+ }
58261
+ });
58262
+ services.API.addCommand({
58263
+ id: "livesync-abortsync",
58264
+ name: "Abort synchronization immediately",
58265
+ checkCallback: (checking) => {
58266
+ if (!services.setting.currentSettings().useAdvancedMode) return false;
58267
+ if (!checking) fireAndForget(() => services.replication.stopActiveTransfer());
58268
+ return true;
58269
+ }
58270
+ });
58271
+ return Promise.resolve(true);
58272
+ });
58273
+ }
58274
+ //#endregion
57331
58275
  //#region ../../LiveSyncBaseCore.ts
57332
58276
  var LiveSyncBaseCore = class {
57333
58277
  /**
@@ -57361,6 +58305,7 @@ var LiveSyncBaseCore = class {
57361
58305
  const addOns = addOnsInitialiser(this);
57362
58306
  for (const addOn of addOns) this._registerAddOn(addOn);
57363
58307
  useReplicationFeature(this);
58308
+ useBasicCommandsFeature(this);
57364
58309
  this.bindModuleFunctions();
57365
58310
  }
57366
58311
  get services() {
@@ -57393,10 +58338,7 @@ var LiveSyncBaseCore = class {
57393
58338
  }
57394
58339
  registerModules(extraModules = []) {
57395
58340
  this._registerModule(new ModuleLiveSyncMain(this));
57396
- this._registerModule(new ModuleConflictChecker(this));
57397
- this._registerModule(new ModuleConflictResolver(this));
57398
58341
  this._registerModule(new ModuleResolvingMismatchedTweaks(this));
57399
- this._registerModule(new ModuleBasicMenu(this));
57400
58342
  for (const module of extraModules) this._registerModule(module);
57401
58343
  }
57402
58344
  /**
@@ -57501,6 +58443,7 @@ var LiveSyncBaseCore = class {
57501
58443
  * (Please refer `serviceFeatures` for more details)
57502
58444
  */
57503
58445
  initialiseServiceFeatures() {
58446
+ useConflictResolutionFeature(this);
57504
58447
  useTargetFilters(this);
57505
58448
  usePrepareDatabaseForUse(this);
57506
58449
  useRemoteConfigurationMigration(this);
@@ -58787,12 +59730,15 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
58787
59730
  this._log(`Rename event for ${path} has no source path`, 16);
58788
59731
  return false;
58789
59732
  }
58790
- const eventPaths = type === "RENAME" ? [path, eventItem.oldPath] : [path];
59733
+ const relatedPath = type === "RENAME" ? eventItem.oldPath : type === "DELETE" ? eventItem.renameTarget : void 0;
59734
+ const eventPaths = relatedPath === void 0 ? [path] : [path, relatedPath];
58791
59735
  return await this.serializedByFileEventPaths(eventPaths, async () => {
58792
59736
  switch (type) {
58793
59737
  case "CREATE":
58794
59738
  case "CHANGED": return await this.storeFileToDB(item.args.file);
58795
- case "DELETE": return await this.deleteFileFromDB(item.args.file);
59739
+ case "DELETE":
59740
+ if (!await this.canRecordStorageDeletion(item)) return true;
59741
+ return await this.deleteFileFromDB(item.args.file);
58796
59742
  case "RENAME": return await this.renameFileInDB(item.args.file, item.args.oldPath);
58797
59743
  case "INTERNAL": return false;
58798
59744
  default:
@@ -58801,6 +59747,39 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
58801
59747
  }
58802
59748
  });
58803
59749
  }
59750
+ async canRecordStorageDeletion(item) {
59751
+ const path = item.args.file.path;
59752
+ try {
59753
+ const current = await this.storage.getStub(path);
59754
+ let excludedRenameTarget = null;
59755
+ if (item.args.renameTarget !== void 0) {
59756
+ const targetPath = item.args.renameTarget;
59757
+ const targetItem = await this.storage.getStub(targetPath);
59758
+ const target = this.getExactCurrentFile(targetItem, targetPath);
59759
+ if (targetItem !== null && !target) {
59760
+ this._log(`Preserved ${path}: the rename target no longer resolves to ${targetPath}`, 64);
59761
+ return false;
59762
+ }
59763
+ if (!shouldBeIgnored(targetPath) && await this.vault.isTargetFile(targetPath, { skipCaseCollisionCheck: true }) && !(target && this.vault.isFileSizeTooLarge(target.stat.size))) {
59764
+ this._log(`Preserved ${path}: rename target ${targetPath} is still selected`, 64);
59765
+ return false;
59766
+ }
59767
+ excludedRenameTarget = target;
59768
+ }
59769
+ if (current === null) return true;
59770
+ if (!isFolderInfo(current)) {
59771
+ const [currentId, deletedId] = await Promise.all([this.path.path2id(current.path), this.path.path2id(path)]);
59772
+ if (currentId !== deletedId) return true;
59773
+ if (excludedRenameTarget && this.storage.normalisePath(current.path) !== this.storage.normalisePath(path) && this.storage.normalisePath(current.path) === this.storage.normalisePath(excludedRenameTarget.path)) return true;
59774
+ }
59775
+ this._log(`Preserved ${path}: a current storage item contradicts its deletion event`, 64);
59776
+ return false;
59777
+ } catch (ex) {
59778
+ this._log(`Could not validate deletion of ${path}; preserved the database entry`, 64);
59779
+ this._log(ex, 16);
59780
+ return false;
59781
+ }
59782
+ }
58804
59783
  async serializedByFileEventPaths(eventPaths, callback) {
58805
59784
  const documentIds = await Promise.all(eventPaths.map((eventPath) => this.path.path2id(eventPath)));
58806
59785
  return await serializedByKeys([...new Set(documentIds)].sort().map((documentId) => `processFileEvent-${documentId}`), () => callback(documentIds.length === 2 && documentIds[0] === documentIds[1]));
@@ -58821,7 +59800,8 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
58821
59800
  this._log(`Rename event for ${path} has no source path`, 16);
58822
59801
  return true;
58823
59802
  }
58824
- const eventPaths = type === "RENAME" ? [path, eventItem.oldPath] : [path];
59803
+ const relatedPath = type === "RENAME" ? eventItem.oldPath : type === "DELETE" ? eventItem.renameTarget : void 0;
59804
+ const eventPaths = relatedPath === void 0 ? [path] : [path, relatedPath];
58825
59805
  return await this.serializedByFileEventPaths(eventPaths, async (isSameDocument) => {
58826
59806
  let action;
58827
59807
  try {
@@ -58849,10 +59829,15 @@ var ServiceFileHandlerBase = class extends ServiceModuleBase {
58849
59829
  file: current
58850
59830
  } : { kind: "none" };
58851
59831
  }
58852
- case "DELETE": return await this.storage.getStub(path) === null && await this.canApplyRestoredDeletion(path) ? {
58853
- kind: "delete",
58854
- path
58855
- } : { kind: "none" };
59832
+ case "DELETE":
59833
+ if (item.args.renameTarget !== void 0) return await this.canRecordStorageDeletion(item) && await this.canApplyRestoredDeletion(path) ? {
59834
+ kind: "delete",
59835
+ path
59836
+ } : { kind: "none" };
59837
+ return await this.storage.getStub(path) === null && await this.canApplyRestoredDeletion(path) ? {
59838
+ kind: "delete",
59839
+ path
59840
+ } : { kind: "none" };
58856
59841
  case "RENAME": return await this._planRestoredRename(path, item.args.oldPath, isSameDocument);
58857
59842
  case "INTERNAL": return { kind: "none" };
58858
59843
  default:
@@ -60240,6 +61225,7 @@ var StorageEventManagerBase = class extends StorageEventManager {
60240
61225
  args: {
60241
61226
  file,
60242
61227
  oldPath: type === "RENAME" ? oldPath : void 0,
61228
+ ...param.type === "RENAME" && type === "DELETE" ? { renameTarget: param.file.path } : {},
60243
61229
  cache,
60244
61230
  ctx
60245
61231
  },
@@ -63617,572 +64603,6 @@ async function openP2PHost(core, p2pService) {
63617
64603
  return service;
63618
64604
  }
63619
64605
  //#endregion
63620
- //#region ../../../node_modules/octagonal-wheels/dist/iterable/map.js
63621
- /**
63622
- * apply a function to each element of an iterable asynchronously with a concurrency limit.
63623
- * Note that the order of the elements is not guaranteed.
63624
- * @param iterable An iterable items to be processed.
63625
- * @param callback A function to be applied to each element of the iterable.
63626
- * @param concurrency The number of concurrent processes.
63627
- */
63628
- async function* withConcurrency(iterable, callback, concurrency) {
63629
- const processes = /* @__PURE__ */ new Set();
63630
- const mapTaskToPromise = /* @__PURE__ */ new Map();
63631
- let serial = 0;
63632
- const enqueue = (item) => {
63633
- const idx = serial++;
63634
- const promise = (async () => [idx, await callback(item)])();
63635
- processes.add(promise);
63636
- mapTaskToPromise.set(idx, promise);
63637
- };
63638
- const consume = async () => {
63639
- const r = await Promise.race(processes);
63640
- const item = mapTaskToPromise.get(r[0]);
63641
- processes.delete(item);
63642
- mapTaskToPromise.delete(r[0]);
63643
- return r[1];
63644
- };
63645
- for await (const t of iterable) {
63646
- while (processes.size >= concurrency) yield await consume();
63647
- enqueue(t);
63648
- }
63649
- while (processes.size > 0) yield await consume();
63650
- }
63651
- //#endregion
63652
- //#region ../../../node_modules/@vrtmrz/livesync-commonlib/dist/serviceFeatures/offlineScanner.js
63653
- var FilePairProcessResults = {
63654
- COMPLETED: "completed",
63655
- SKIPPED: "skipped",
63656
- FAILED: "failed"
63657
- };
63658
- var MetadataDocumentNamespaces = {
63659
- NORMAL: "normal",
63660
- INTERNAL: "internal",
63661
- CUSTOMISATION: "customisation",
63662
- PLUGIN_STORAGE: "plugin-storage"
63663
- };
63664
- var MetadataDocumentIdentityStatuses = {
63665
- CONSISTENT: "consistent",
63666
- EXCLUDED: "excluded",
63667
- UNRESOLVED: "unresolved"
63668
- };
63669
- var OfflineScanUnresolvedReasons = {
63670
- DOCUMENT_ID_MISMATCH: "document-id-mismatch",
63671
- NAMESPACE_MISMATCH: "namespace-mismatch"
63672
- };
63673
- function getMetadataDocumentNamespace(value) {
63674
- if (value.startsWith("ix:")) return MetadataDocumentNamespaces.CUSTOMISATION;
63675
- if (value.startsWith("i:")) return MetadataDocumentNamespaces.INTERNAL;
63676
- if (value.startsWith("ps:")) return MetadataDocumentNamespaces.PLUGIN_STORAGE;
63677
- return MetadataDocumentNamespaces.NORMAL;
63678
- }
63679
- async function inspectMetadataDocumentIdentity(host, doc) {
63680
- const actualDocumentId = doc._id;
63681
- const declaredPath = getPathFromEntry(host, doc);
63682
- const actualNamespace = getMetadataDocumentNamespace(actualDocumentId);
63683
- const declaredPathNamespace = getMetadataDocumentNamespace(declaredPath);
63684
- if (actualNamespace !== MetadataDocumentNamespaces.NORMAL || declaredPathNamespace !== MetadataDocumentNamespaces.NORMAL) {
63685
- if (actualNamespace === declaredPathNamespace) return {
63686
- status: MetadataDocumentIdentityStatuses.EXCLUDED,
63687
- actualDocumentId,
63688
- declaredPath,
63689
- namespace: actualNamespace
63690
- };
63691
- return {
63692
- status: MetadataDocumentIdentityStatuses.UNRESOLVED,
63693
- diagnostic: {
63694
- reason: OfflineScanUnresolvedReasons.NAMESPACE_MISMATCH,
63695
- actualDocumentId,
63696
- declaredPath,
63697
- actualNamespace,
63698
- declaredPathNamespace
63699
- }
63700
- };
63701
- }
63702
- const expectedDocumentId = await host.services.path.path2id(declaredPath);
63703
- if (actualDocumentId !== expectedDocumentId) return {
63704
- status: MetadataDocumentIdentityStatuses.UNRESOLVED,
63705
- diagnostic: {
63706
- reason: OfflineScanUnresolvedReasons.DOCUMENT_ID_MISMATCH,
63707
- actualDocumentId,
63708
- declaredPath,
63709
- expectedDocumentId,
63710
- actualNamespace,
63711
- declaredPathNamespace
63712
- }
63713
- };
63714
- return {
63715
- status: MetadataDocumentIdentityStatuses.CONSISTENT,
63716
- actualDocumentId,
63717
- declaredPath,
63718
- expectedDocumentId
63719
- };
63720
- }
63721
- async function collectDeletedFiles(host, log) {
63722
- const limitDays = host.services.setting.currentSettings().automaticallyDeleteMetadataOfDeletedFiles;
63723
- if (limitDays <= 0) return;
63724
- log(`Checking expired file history`);
63725
- const limit = Date.now() - 86400 * 1e3 * limitDays;
63726
- const notes = [];
63727
- for await (const doc of host.services.database.localDatabase.findAllDocs({ conflicts: true })) if (isAnyNote(doc)) {
63728
- if (doc.deleted && doc.mtime - limit < 0) {
63729
- if (isMetaEntry(doc)) {
63730
- const identity = await inspectMetadataDocumentIdentity(host, doc);
63731
- if (identity.status === MetadataDocumentIdentityStatuses.UNRESOLVED) {
63732
- log(`Expired deletion history has an unresolved Metadata identity and will be left unchanged: ${identity.diagnostic.declaredPath} (${identity.diagnostic.reason})`, 32);
63733
- continue;
63734
- }
63735
- }
63736
- notes.push({
63737
- path: doc.path,
63738
- mtime: doc.mtime,
63739
- ttl: (doc.mtime - limit) / 1e3 / 86400,
63740
- doc
63741
- });
63742
- }
63743
- }
63744
- if (notes.length === 0) {
63745
- log("There are no old documents");
63746
- log(`Checking expired file history done`);
63747
- return;
63748
- }
63749
- for (const v of notes) {
63750
- log(`Deletion history expired: ${v.path}`);
63751
- const delDoc = v.doc;
63752
- delDoc._deleted = true;
63753
- await host.services.database.localDatabase.putRaw(delDoc);
63754
- }
63755
- log(`Checking expired file history done`);
63756
- }
63757
- function getPathFromEntry(host, doc) {
63758
- return host.services.path.getPath(doc);
63759
- }
63760
- async function syncFileBetweenDBandStorage(host, log, file, doc) {
63761
- const docPath = getPathFromEntry(host, doc);
63762
- if (!doc) throw new Error(`Missing doc:${docPath}`);
63763
- switch (host.services.path.compareFileFreshness(file, doc)) {
63764
- case BASE_IS_NEW: if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
63765
- log("STORAGE -> DB :" + file.path);
63766
- await host.serviceModules.fileHandler.storeFileToDB(file);
63767
- return FilePairProcessResults.COMPLETED;
63768
- } else {
63769
- log(`STORAGE -> DB : ${file.path} has been skipped due to file size exceeding the limit`, 64);
63770
- return FilePairProcessResults.SKIPPED;
63771
- }
63772
- case TARGET_IS_NEW: if (!host.services.vault.isFileSizeTooLarge(doc.size)) {
63773
- log("STORAGE <- DB :" + docPath);
63774
- if (await host.serviceModules.fileHandler.dbToStorage(doc, stripAllPrefixes(docPath), false)) {
63775
- host.services.context.events.emitEvent("event-file-changed", {
63776
- file: file.path,
63777
- automated: true
63778
- });
63779
- return FilePairProcessResults.COMPLETED;
63780
- } else {
63781
- log(`STORAGE <- DB : Cloud not read ${file.path}, possibly deleted`, 64);
63782
- return FilePairProcessResults.FAILED;
63783
- }
63784
- } else {
63785
- log(`STORAGE <- DB : ${file.path} has been skipped due to file size exceeding the limit`, 64);
63786
- return FilePairProcessResults.SKIPPED;
63787
- }
63788
- case EVEN:
63789
- log("STORAGE == DB :" + file.path, -1);
63790
- return FilePairProcessResults.COMPLETED;
63791
- default:
63792
- log("STORAGE ?? DB :" + file.path + " Something got weird");
63793
- return FilePairProcessResults.FAILED;
63794
- }
63795
- }
63796
- function canProceedScan(host, errorManager, log, showingNotice = false, ignoreSuspending = false) {
63797
- const settings = host.services.setting.currentSettings();
63798
- const ERR_NOT_CONFIGURED = "LiveSync is not configured yet. Synchronising between the storage and the local database is now prevented.";
63799
- if (!settings.isConfigured) {
63800
- errorManager.showError(ERR_NOT_CONFIGURED, showingNotice ? 64 : 32);
63801
- return false;
63802
- }
63803
- errorManager.clearError(ERR_NOT_CONFIGURED);
63804
- const ERR_SUSPENDING = "Now suspending file watching. Synchronising between the storage and the local database is now prevented.";
63805
- if (!ignoreSuspending && settings.suspendFileWatching) {
63806
- errorManager.showError(ERR_SUSPENDING, showingNotice ? 64 : 32);
63807
- return false;
63808
- }
63809
- errorManager.clearError(ERR_SUSPENDING);
63810
- const MSG_IN_REMEDIATION = `Started in remediation Mode! (Max mtime for reflect events is set). Synchronising between the storage and the local database is now prevented.`;
63811
- if (settings.maxMTimeForReflectEvents > 0) {
63812
- errorManager.showError(MSG_IN_REMEDIATION, 64);
63813
- return false;
63814
- }
63815
- errorManager.clearError(MSG_IN_REMEDIATION);
63816
- return true;
63817
- }
63818
- function convertCase(settings, path) {
63819
- if (settings.handleFilenameCaseSensitive) return path;
63820
- return path.toLowerCase();
63821
- }
63822
- async function collectFilesOnStorage(host, settings, log) {
63823
- log("Collecting local files on the storage", 16);
63824
- const filesStorageSrc = await host.serviceModules.storageAccess.getFiles();
63825
- const _filesStorage = [];
63826
- for (const f of filesStorageSrc) {
63827
- if (shouldBeIgnored(f.path)) continue;
63828
- if (await host.services.vault.isTargetFile(f.path)) _filesStorage.push(f);
63829
- }
63830
- const storageFileNameMap = Object.fromEntries(_filesStorage.map((e) => [e.path, e]));
63831
- const storageFileNames = Object.keys(storageFileNameMap);
63832
- const storageFileNameCapsPair = storageFileNames.map((e) => [e, convertCase(settings, e)]);
63833
- return {
63834
- storageFileNameMap,
63835
- storageFileNames,
63836
- storageFileNameCI2CS: Object.fromEntries(storageFileNameCapsPair.map((e) => [e[1], e[0]]))
63837
- };
63838
- }
63839
- async function collectDatabaseFiles(host, settings, log, showingNotice) {
63840
- log("Collecting local files on the DB", 16);
63841
- const _DBEntries = [];
63842
- const unresolvedFileNamesLC = /* @__PURE__ */ new Set();
63843
- const resolvableFileNamesLC = /* @__PURE__ */ new Set();
63844
- let count = 0;
63845
- for await (const doc of host.services.database.localDatabase.findAllNormalDocs({ conflicts: true }) || []) {
63846
- count++;
63847
- if (count % 25 === 0) log(`Collecting local files on the DB: ${count}`, showingNotice ? 64 : 32, "syncAll");
63848
- if (!isMetaEntry(doc)) {
63849
- log(`Invalid Metadata entry: ${doc._id ?? "unknown"}`, 32);
63850
- continue;
63851
- }
63852
- const identity = await inspectMetadataDocumentIdentity(host, doc);
63853
- if (identity.status === MetadataDocumentIdentityStatuses.EXCLUDED) continue;
63854
- if (identity.status === MetadataDocumentIdentityStatuses.UNRESOLVED) {
63855
- const { diagnostic } = identity;
63856
- const unresolvedKey = convertCase(settings, stripAllPrefixes(diagnostic.declaredPath));
63857
- unresolvedFileNamesLC.add(unresolvedKey);
63858
- log(`Metadata identity is unresolved and will be left unchanged: ${diagnostic.declaredPath} (${diagnostic.reason})`, 32);
63859
- continue;
63860
- }
63861
- const path = identity.declaredPath;
63862
- if (host.services.vault.isValidPath(path) && !shouldBeIgnored(path) && await host.services.vault.isTargetFile(path)) {
63863
- _DBEntries.push(doc);
63864
- resolvableFileNamesLC.add(convertCase(settings, stripAllPrefixes(path)));
63865
- }
63866
- }
63867
- const databaseFileNameMap = Object.fromEntries(_DBEntries.map((e) => [getPathFromEntry(host, e), e]));
63868
- const databaseFileNames = Object.keys(databaseFileNameMap);
63869
- const databaseFileNameCapsPair = databaseFileNames.map((e) => [e, convertCase(settings, e)]);
63870
- return {
63871
- databaseFileNameMap,
63872
- databaseFileNames,
63873
- databaseFileNameCI2CS: Object.fromEntries(databaseFileNameCapsPair.map((e) => [e[1], e[0]])),
63874
- quarantinedFileNamesLC: new Set([...unresolvedFileNamesLC].filter((path) => !resolvableFileNamesLC.has(path)))
63875
- };
63876
- }
63877
- async function updateToDatabase(host, log, logLevel, file) {
63878
- if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
63879
- const path = file.path;
63880
- await host.serviceModules.fileHandler.storeFileToDB(file);
63881
- host.services.context.events.emitEvent("event-file-changed", {
63882
- file: path,
63883
- automated: true
63884
- });
63885
- return FilePairProcessResults.COMPLETED;
63886
- } else {
63887
- log(`UPDATE DATABASE: ${file.path} has been skipped due to file size exceeding the limit`, logLevel);
63888
- return FilePairProcessResults.SKIPPED;
63889
- }
63890
- }
63891
- async function updateToStorage(host, log, logLevel, w) {
63892
- const path = getPathFromEntry(host, w);
63893
- if (w && !(w.deleted || w._deleted)) if (!host.services.vault.isFileSizeTooLarge(w.size)) {
63894
- if ((w._conflicts?.length ?? 0) > 0) {
63895
- log(`UPDATE STORAGE: ${path} has conflicts. skipped (x)`, 32);
63896
- return FilePairProcessResults.SKIPPED;
63897
- }
63898
- if (!await host.serviceModules.fileHandler.dbToStorage(path, null, true)) return FilePairProcessResults.FAILED;
63899
- host.services.context.events.emitEvent("event-file-changed", {
63900
- file: path,
63901
- automated: true
63902
- });
63903
- log(`Check or pull from db:${path} OK`);
63904
- return FilePairProcessResults.COMPLETED;
63905
- } else {
63906
- log(`UPDATE STORAGE: ${path} has been skipped due to file size exceeding the limit`, logLevel);
63907
- return FilePairProcessResults.SKIPPED;
63908
- }
63909
- else if (w) {
63910
- log(`Deletion history skipped: ${path}`, 16);
63911
- return FilePairProcessResults.SKIPPED;
63912
- } else {
63913
- log(`entry not found: ${path}`);
63914
- return FilePairProcessResults.FAILED;
63915
- }
63916
- }
63917
- async function syncStorageAndDatabase(host, log, file, logLevel, doc) {
63918
- if ((doc._conflicts?.length ?? 0) > 0) {
63919
- log(`SYNC DATABASE AND STORAGE: ${file.path} has conflicts. skipped`, 32);
63920
- return FilePairProcessResults.SKIPPED;
63921
- }
63922
- if (!host.services.vault.isFileSizeTooLarge(file.stat.size) && !host.services.vault.isFileSizeTooLarge(doc.size)) return await syncFileBetweenDBandStorage(host, log, file, doc);
63923
- else {
63924
- log(`SYNC DATABASE AND STORAGE: ${getPathFromEntry(host, doc)} has been skipped due to file size exceeding the limit`, logLevel);
63925
- return FilePairProcessResults.SKIPPED;
63926
- }
63927
- }
63928
- var FullScanModes = {
63929
- DB_APPLY: "db-apply",
63930
- NEWER_WINS: "newer-wins"
63931
- };
63932
- var ExtraOnRemote = {
63933
- /**
63934
- * Delete database entries if they are missing on storage.
63935
- */
63936
- DELETE_LOCAL_MISSING: "delete-local-missing" };
63937
- var ExtraOnLocal = {
63938
- /**
63939
- * Delete local files if they were deleted on database.
63940
- */
63941
- DELETE_DB_DELETED: "delete-db-deleted",
63942
- /**
63943
- * Delete local files if they are missing on database or were deleted on database.
63944
- */
63945
- DELETE_DB_MISSING: "delete-db-missing",
63946
- /**
63947
- * Merge local files to database
63948
- */
63949
- APPEND_STORAGE_ONLY: "append-storage-only"
63950
- };
63951
- function isDeletedEntry(entry) {
63952
- return entry.deleted || entry._deleted || false;
63953
- }
63954
- function getFilePairState(pair) {
63955
- const { file, doc } = pair;
63956
- if (file && doc) return isDeletedEntry(doc) ? "both-db-deleted" : "both";
63957
- if (file) return "storage-only";
63958
- if (doc) return isDeletedEntry(doc) ? "db-only-deleted" : "db-only";
63959
- throw new Error("Corrupted file pair");
63960
- }
63961
- function shouldDeleteLocalWhenRemoteMissing(options) {
63962
- return options.extraOnRemote === ExtraOnRemote.DELETE_LOCAL_MISSING || options.extraOnLocal === ExtraOnLocal.DELETE_DB_MISSING;
63963
- }
63964
- function shouldDeleteLocalWhenRemoteDeleted(options) {
63965
- return options.extraOnRemote === ExtraOnRemote.DELETE_LOCAL_MISSING || options.extraOnLocal === ExtraOnLocal.DELETE_DB_DELETED || options.extraOnLocal === ExtraOnLocal.DELETE_DB_MISSING;
63966
- }
63967
- function resolveFilePairAction(state, options) {
63968
- switch (options.mode) {
63969
- case FullScanModes.DB_APPLY:
63970
- switch (state) {
63971
- case "both":
63972
- case "db-only": return "update-storage";
63973
- case "storage-only": return shouldDeleteLocalWhenRemoteMissing(options) ? "delete-local" : "skip";
63974
- case "both-db-deleted": return shouldDeleteLocalWhenRemoteDeleted(options) ? "delete-local" : "skip";
63975
- case "db-only-deleted": return "skip";
63976
- }
63977
- break;
63978
- case FullScanModes.NEWER_WINS:
63979
- switch (state) {
63980
- case "both": return "sync-newer";
63981
- case "storage-only": return shouldDeleteLocalWhenRemoteMissing(options) ? "delete-local" : "update-db";
63982
- case "db-only": return "update-storage";
63983
- case "both-db-deleted":
63984
- if (shouldDeleteLocalWhenRemoteDeleted(options)) return "delete-local";
63985
- return options.extraOnLocal === ExtraOnLocal.APPEND_STORAGE_ONLY ? "update-db" : "skip";
63986
- case "db-only-deleted": return "skip";
63987
- }
63988
- break;
63989
- }
63990
- return "skip";
63991
- }
63992
- async function processFilePair(host, log, pair, options) {
63993
- const { file, doc } = pair;
63994
- const canonicalPath = doc ? getPathFromEntry(host, doc) : file?.path;
63995
- if (!canonicalPath) throw new Error("Corrupted file pair");
63996
- const path = canonicalPath;
63997
- const fileMapKey = convertCase(host.services.setting.currentSettings(), canonicalPath);
63998
- if (file) updateFileMTimeInMap(host, fileMapKey, file.stat.mtime);
63999
- if (doc && (doc._conflicts?.length ?? 0) > 0) {
64000
- log(`SKIP ${options.mode}: ${path} has conflicts`, 32);
64001
- return FilePairProcessResults.SKIPPED;
64002
- }
64003
- const state = getFilePairState(pair);
64004
- let action = resolveFilePairAction(state, options);
64005
- if (options.mode === FullScanModes.NEWER_WINS && state === "db-only" && doc) {
64006
- const lastSeenMTime = getFileMTimeFromMap(fileMapKey);
64007
- if (lastSeenMTime !== void 0) {
64008
- const recency = compareMTime(lastSeenMTime, doc.mtime);
64009
- if (recency === BASE_IS_NEW || recency === EVEN) {
64010
- action = "delete-db";
64011
- log(`NEWER_WINS: Treating missing local file as deletion (${path})`, 16);
64012
- }
64013
- }
64014
- }
64015
- try {
64016
- switch (action) {
64017
- case "update-db":
64018
- if (!file) throw new Error(`Missing storage file for ${path}`);
64019
- return await updateToDatabase(host, log, 32, file);
64020
- case "update-storage":
64021
- if (!doc) throw new Error(`Missing database entry for ${path}`);
64022
- const updateStorageResult = await updateToStorage(host, log, 32, doc);
64023
- if (updateStorageResult === FilePairProcessResults.COMPLETED) updateFileMTimeInMap(host, fileMapKey, doc.mtime);
64024
- return updateStorageResult;
64025
- case "sync-newer":
64026
- if (!file || !doc) throw new Error(`Cannot compare freshness for ${path}`);
64027
- const syncResult = await syncStorageAndDatabase(host, log, file, 32, doc);
64028
- if (syncResult === FilePairProcessResults.COMPLETED) updateFileMTimeInMap(host, fileMapKey, Math.max(file.stat.mtime, doc.mtime));
64029
- return syncResult;
64030
- case "delete-local":
64031
- if (!file) {
64032
- log(`DELETE LOCAL: ${path} is already absent from storage`, 16);
64033
- return FilePairProcessResults.COMPLETED;
64034
- }
64035
- log(`DELETE LOCAL: ${file.path}`, 32);
64036
- await host.serviceModules.storageAccess.delete(file.path, true);
64037
- fileMaps.delete(fileMapKey);
64038
- saveFileStatus(host);
64039
- return FilePairProcessResults.COMPLETED;
64040
- case "delete-db":
64041
- if (!doc) throw new Error(`Missing database entry for ${path}`);
64042
- log(`DELETE DATABASE: ${path}`, 32);
64043
- if (await host.serviceModules.fileHandler.deleteFileFromDB(stripAllPrefixes(path))) {
64044
- fileMaps.delete(fileMapKey);
64045
- saveFileStatus(host);
64046
- return FilePairProcessResults.COMPLETED;
64047
- } else {
64048
- log(`DELETE DATABASE did not delete ${path}; keeping last-seen record to avoid resurrecting the file`, 64);
64049
- return FilePairProcessResults.FAILED;
64050
- }
64051
- case "skip":
64052
- log(`SKIP ${options.mode}: ${path} (${state})`, 16);
64053
- return FilePairProcessResults.SKIPPED;
64054
- }
64055
- } catch (ex) {
64056
- log(`Error processing ${path} with action ${action}`, 64);
64057
- log(ex, 16);
64058
- return FilePairProcessResults.FAILED;
64059
- }
64060
- }
64061
- async function synchroniseAllFilesBetweenDBandStorage(host, log, errorManager, options) {
64062
- const settings = host.services.setting.currentSettings();
64063
- const showingNotice = options.showingNotice ?? false;
64064
- await loadFileStatus(host);
64065
- const { storageFileNameMap, storageFileNameCI2CS } = await collectFilesOnStorage(host, settings, log);
64066
- const { databaseFileNameMap, databaseFileNameCI2CS, quarantinedFileNamesLC } = await collectDatabaseFiles(host, settings, log, showingNotice);
64067
- const pairs = [];
64068
- for (const fileNameLC of unique([...Object.keys(storageFileNameCI2CS), ...Object.keys(databaseFileNameCI2CS)])) {
64069
- if (quarantinedFileNamesLC.has(fileNameLC)) continue;
64070
- const fileName = fileNameLC in storageFileNameCI2CS ? storageFileNameCI2CS[fileNameLC] : void 0;
64071
- const file = fileName ? storageFileNameMap[fileName] : void 0;
64072
- const databaseName = fileNameLC in databaseFileNameCI2CS ? databaseFileNameCI2CS[fileNameLC] : void 0;
64073
- const pair = {
64074
- file,
64075
- doc: databaseName ? databaseFileNameMap[databaseName] : void 0
64076
- };
64077
- pairs.push(pair);
64078
- }
64079
- log(`Total files to synchronise: ${pairs.length}`, 16, "syncAll");
64080
- let completedCount = 0;
64081
- let skippedCount = 0;
64082
- let failedCount = 0;
64083
- let processedCount = 0;
64084
- for await (const result of withConcurrency(pairs, async (e) => {
64085
- try {
64086
- return await processFilePair(host, log, e, options);
64087
- } catch (ex) {
64088
- log(`Error while synchronising files`, 64);
64089
- log(ex, 16);
64090
- return FilePairProcessResults.FAILED;
64091
- }
64092
- }, 10)) {
64093
- processedCount++;
64094
- switch (result) {
64095
- case FilePairProcessResults.COMPLETED:
64096
- completedCount++;
64097
- break;
64098
- case FilePairProcessResults.SKIPPED:
64099
- skippedCount++;
64100
- break;
64101
- case FilePairProcessResults.FAILED:
64102
- failedCount++;
64103
- break;
64104
- }
64105
- if (processedCount % 25 === 0) log(`Processing: ${processedCount}/${pairs.length}`, showingNotice ? 64 : 32, "syncAll");
64106
- }
64107
- log(`Synchronisation completed: ${processedCount} files processed (${completedCount} completed, ${skippedCount} skipped, ${failedCount} failed)`, showingNotice ? 64 : 32, "syncAll");
64108
- saveFileStatus(host, true);
64109
- return failedCount === 0;
64110
- }
64111
- function normaliseFullScanOptions(showingNoticeOrOptions, ignoreSuspending = false) {
64112
- if (typeof showingNoticeOrOptions === "object") return {
64113
- mode: FullScanModes.NEWER_WINS,
64114
- ...showingNoticeOrOptions
64115
- };
64116
- return {
64117
- mode: FullScanModes.NEWER_WINS,
64118
- showingNotice: showingNoticeOrOptions ?? false,
64119
- ignoreSuspending
64120
- };
64121
- }
64122
- var fileMaps = /* @__PURE__ */ new Map();
64123
- var FILE_STATUS_MAP_KEY = "fileStatusMap";
64124
- var FILE_STATUS_MAP_LOCK = "offlineScanner-fileStatusMap";
64125
- async function loadFileStatus(host) {
64126
- await serialized(FILE_STATUS_MAP_LOCK, async () => {
64127
- const kvDB = host.services.keyValueDB.kvDB;
64128
- if (!kvDB?.get) {
64129
- fileMaps = /* @__PURE__ */ new Map();
64130
- return;
64131
- }
64132
- const mapItems = await kvDB.get(FILE_STATUS_MAP_KEY) || {};
64133
- fileMaps = new Map(Object.entries(mapItems));
64134
- });
64135
- }
64136
- async function _saveFileStatus(host) {
64137
- await serialized(FILE_STATUS_MAP_LOCK, async () => {
64138
- const kvDB = host.services.keyValueDB.kvDB;
64139
- if (!kvDB?.set) return;
64140
- await kvDB.set(FILE_STATUS_MAP_KEY, Object.fromEntries(fileMaps));
64141
- });
64142
- }
64143
- var saveFileStatusTimeout = null;
64144
- function saveFileStatus(host, immediate = false) {
64145
- if (immediate) {
64146
- if (saveFileStatusTimeout !== null) compatGlobal.clearTimeout(saveFileStatusTimeout);
64147
- saveFileStatusTimeout = compatGlobal.setTimeout(() => {
64148
- saveFileStatusTimeout = null;
64149
- _saveFileStatus(host);
64150
- }, 0);
64151
- return;
64152
- }
64153
- if (saveFileStatusTimeout === null) saveFileStatusTimeout = compatGlobal.setTimeout(() => {
64154
- saveFileStatusTimeout = null;
64155
- _saveFileStatus(host);
64156
- }, 1e3);
64157
- }
64158
- function updateFileMTimeInMap(host, key, mtime) {
64159
- fileMaps.set(key, mtime);
64160
- saveFileStatus(host);
64161
- }
64162
- function getFileMTimeFromMap(key) {
64163
- return fileMaps.get(key);
64164
- }
64165
- async function performFullScan(host, log, errorManager, showingNoticeOrOptions = false, ignoreSuspending = false) {
64166
- const options = normaliseFullScanOptions(showingNoticeOrOptions, ignoreSuspending);
64167
- const showingNotice = options.showingNotice ?? false;
64168
- if (!canProceedScan(host, errorManager, log, showingNotice, options.ignoreSuspending ?? false)) return false;
64169
- log("Opening the key-value database", 16);
64170
- const isInitialized = await host.services.keyValueDB.kvDB.get("initialized") || false;
64171
- if (showingNotice) log("Initializing", 64, "syncAll");
64172
- if (isInitialized) {
64173
- log("Restoring storage state", 16);
64174
- await host.serviceModules.storageAccess.restoreState();
64175
- }
64176
- log("Initialize and checking database files");
64177
- log("Checking deleted files");
64178
- await collectDeletedFiles(host, log);
64179
- const scanResult = await synchroniseAllFilesBetweenDBandStorage(host, log, errorManager, options);
64180
- log("Initialized, NOW TRACKING!");
64181
- if (!isInitialized) await host.services.keyValueDB.kvDB.set("initialized", true);
64182
- if (showingNotice) log("Initialize done!", 64, "syncAll");
64183
- return scanResult;
64184
- }
64185
- //#endregion
64186
64606
  //#region cliOutput.ts
64187
64607
  function formatValue(value) {
64188
64608
  if (typeof value === "string") return value;
@@ -64603,7 +65023,7 @@ async function runCommand(options, context) {
64603
65023
  if (options.command === "mirror") {
64604
65024
  writeStderrLine(standardIo, "[Command] mirror");
64605
65025
  const log = (msg) => writeStderrLine(standardIo, `[Mirror] ${String(msg)}`);
64606
- return await performFullScan(core, log, new UnresolvedErrorManager(core.services.appLifecycle, core.services.context.events), false, true);
65026
+ return await performFullScan(core, log, new UnresolvedErrorManager(core.services.appLifecycle, core.services.context.events), false, true) === VaultScanResults.COMPLETED;
64607
65027
  }
64608
65028
  if (options.command === "remote-add") {
64609
65029
  if (options.commandArgs.length < 2) throw new Error("remote-add requires two arguments: <name> <connstr>");
@@ -70844,11 +71264,11 @@ ${info.lastSeq} / ${info.maxSeqInBatch})`, logLevel, "p2p-replicator");
70844
71264
  const tweakValues = await this.server.getConnection(peerId).invokeRemoteObjectFunction("getTweakSettings", [this.server.serverPeerId], 5e3, signal);
70845
71265
  if (signal?.aborted) return false;
70846
71266
  const thisTweakValues = await this.getTweakSettings("");
70847
- if (!isObjectDifferent(thisTweakValues, tweakValues)) return true;
70848
71267
  if (thisTweakValues.passphrase !== tweakValues.passphrase) {
70849
71268
  Logger("Replication cancelled: Passphrase is not matched\nCannot replicate to a remote database until the problem is resolved.", logLevel);
70850
71269
  return false;
70851
71270
  }
71271
+ if (!assessTweakCompatibility(thisTweakValues, tweakValues).representationDiffers) return true;
70852
71272
  Logger("Some mismatched configuration have been detected... Please check settings for efficient replication.", logLevel);
70853
71273
  return true;
70854
71274
  }