@vrtmrz/livesync-commonlib 0.8.0 → 0.8.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 (39) hide show
  1. package/README.md +4 -0
  2. package/dist/common/models/diff.definition.d.ts +4 -0
  3. package/dist/common/utils.d.ts +1 -1
  4. package/dist/common/utils.doc.d.ts +5 -0
  5. package/dist/common/utils.doc.js +8 -0
  6. package/dist/common/utils.js +1 -3
  7. package/dist/conflicts/filenameCaseConflict.d.ts +8 -0
  8. package/dist/conflicts/filenameCaseConflict.js +26 -0
  9. package/dist/conflicts.d.ts +1 -0
  10. package/dist/conflicts.js +9 -1
  11. package/dist/interfaces/DatabaseFileAccess.d.ts +12 -1
  12. package/dist/managers/ConflictManager.d.ts +6 -2
  13. package/dist/managers/ConflictManager.js +73 -22
  14. package/dist/managers/EntryManager/EntryManager.d.ts +5 -0
  15. package/dist/managers/EntryManager/EntryManager.js +5 -0
  16. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +5 -1
  17. package/dist/managers/EntryManager/EntryManagerImpls.js +16 -2
  18. package/dist/managers/LiveSyncManagers.js +2 -1
  19. package/dist/pouchdb/LiveSyncLocalDB.js +3 -4
  20. package/dist/replication/index.d.ts +2 -0
  21. package/dist/replication/index.js +2 -0
  22. package/dist/replication/replicationResultQueueStore.d.ts +101 -0
  23. package/dist/replication/replicationResultQueueStore.js +140 -0
  24. package/dist/serviceFeatures/offlineScanner/files.js +15 -3
  25. package/dist/serviceFeatures/offlineScanner/scan.js +1 -4
  26. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +5 -4
  27. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +28 -7
  28. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +3 -0
  29. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +29 -6
  30. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +2 -0
  31. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +29 -10
  32. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +61 -11
  33. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +32 -8
  34. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +2 -8
  35. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +4 -5
  36. package/docs/conflict-resolution.md +22 -8
  37. package/docs/offline-scanner.md +2 -0
  38. package/docs/storage-events-and-reflection.md +141 -0
  39. package/package.json +1 -1
package/README.md CHANGED
@@ -59,6 +59,10 @@ remote objects remain available and readable. See the
59
59
  [Journal receive failures and recovery](docs/journal-receive-recovery.md) for
60
60
  the receive, skip, and replay boundaries.
61
61
 
62
+ Commonlib 0.8.1 adds a host-backed result queue store to the `/replication` entry.
63
+ See [saving replication results in a CLI host](docs/storage-events-and-reflection.md#saving-replication-results-in-a-cli-host)
64
+ for SQLite integration, legacy queue migration, and reset handling.
65
+
62
66
  ## Package entry points
63
67
 
64
68
  | Entry point | Intended use | Current contract status |
@@ -1,10 +1,14 @@
1
1
  import type { AUTO_MERGED, CANCELLED, MISSING_OR_ERROR, NOT_CONFLICTED } from "./shared.const.symbols.js";
2
+ import type { EntryTypeNotes, FilePathWithPrefix } from "./db.type.js";
2
3
  export type diff_result_leaf = {
3
4
  rev: string;
4
5
  data: string;
5
6
  ctime: number;
6
7
  mtime: number;
7
8
  deleted?: boolean;
9
+ /** The path recorded on this revision, when available. */
10
+ path?: FilePathWithPrefix;
11
+ datatype?: EntryTypeNotes;
8
12
  };
9
13
  export type dmp_result = Array<[number, string]>;
10
14
  export type diff_result = {
@@ -113,7 +113,7 @@ export declare function isRemediationModeActive(settings: Pick<ObsidianLiveSyncS
113
113
  export declare function determineType(path: string, data: string | string[] | Uint8Array | ArrayBuffer | Blob): "newnote" | "plain";
114
114
  export declare function isAnyNote(doc: DatabaseEntry): doc is NewEntry | PlainEntry;
115
115
  export declare function isLoadedEntry(doc: DatabaseEntry): doc is LoadedEntry;
116
- export declare function isDeletedEntry(doc: LoadedEntry): boolean;
116
+ export { isDeletedEntry } from "./utils.doc.js";
117
117
  export declare function createSavingEntryFromLoadedEntry(doc: LoadedEntry): SavingEntry;
118
118
  export declare function setAllItems<T>(set: Set<T>, items: T[]): Set<T>;
119
119
  export declare function escapeNewLineFromString(str: string): string;
@@ -1,3 +1,8 @@
1
+ import type { DatabaseEntry, LoadedEntry } from "./models/db.type.js";
2
+ /** Check the CouchDB tombstone marker on a raw revision. */
3
+ export declare function isTombstoneRevision(revision: Pick<DatabaseEntry, "_deleted">): boolean;
4
+ /** Check whether CouchDB marked the revision as a tombstone or LiveSync marked the file as deleted. */
5
+ export declare function isDeletedEntry(entry: Pick<LoadedEntry, "_deleted" | "deleted">): boolean;
1
6
  export declare function isErrorOf(ex: unknown, statusCode: number): boolean;
2
7
  /**
3
8
  * Checks if the error is effectively a 404 error from CouchDB or PouchDB.
@@ -1,3 +1,9 @@
1
+ function isTombstoneRevision(revision) {
2
+ return !!revision._deleted;
3
+ }
4
+ function isDeletedEntry(entry) {
5
+ return isTombstoneRevision(entry) || entry.deleted || false;
6
+ }
1
7
  function isErrorOf(ex, statusCode) {
2
8
  if (!ex || typeof ex !== "object") {
3
9
  throw new Error(`Expected an object error, but got ${typeof ex}`);
@@ -28,8 +34,10 @@ function tryGetFilePath(entry) {
28
34
  }
29
35
  export {
30
36
  isConflictError,
37
+ isDeletedEntry,
31
38
  isErrorOf,
32
39
  isNotFoundError,
40
+ isTombstoneRevision,
33
41
  isUnauthorizedError,
34
42
  tryGetFilePath
35
43
  };
@@ -204,9 +204,7 @@ function isAnyNote(doc) {
204
204
  function isLoadedEntry(doc) {
205
205
  return "type" in doc && (doc.type == "newnote" || doc.type == "plain") && "data" in doc;
206
206
  }
207
- function isDeletedEntry(doc) {
208
- return doc._deleted || doc.deleted || false;
209
- }
207
+ import { isDeletedEntry } from "./utils.doc.js";
210
208
  function createSavingEntryFromLoadedEntry(doc) {
211
209
  const data = readAsBlob(doc);
212
210
  const type = determineType(doc.path, data);
@@ -0,0 +1,8 @@
1
+ /** Check whether both revisions record the same case-preserving path under the configured normalisation. */
2
+ export declare function haveMatchingRevisionPaths(leftPath: string | undefined, rightPath: string | undefined, version?: number): boolean;
3
+ /** Check whether two recorded paths differ only in case under the configured normalisation. */
4
+ export declare function hasFilenameCaseConflict(leftPath: string | undefined, rightPath: string | undefined, version?: number): boolean;
5
+ /** Return the parent directory of a Vault path, or the empty string for the Vault root. */
6
+ export declare function getParentPath(path: string): string;
7
+ /** Check for a filename casing difference within the same normalised parent directory. */
8
+ export declare function hasSameParentFilenameCaseConflict(left: string | undefined, right: string | undefined, version?: number): boolean;
@@ -0,0 +1,26 @@
1
+ import { normalisePathForIdentity } from "../common/pathNormalization.js";
2
+ function haveMatchingRevisionPaths(leftPath, rightPath, version) {
3
+ return !!leftPath && !!rightPath && normalisePathForIdentity(leftPath, version) === normalisePathForIdentity(rightPath, version);
4
+ }
5
+ function hasFilenameCaseConflict(leftPath, rightPath, version) {
6
+ if (!leftPath || !rightPath) {
7
+ return false;
8
+ }
9
+ const left = normalisePathForIdentity(leftPath, version);
10
+ const right = normalisePathForIdentity(rightPath, version);
11
+ return left !== right && left.toLowerCase() === right.toLowerCase();
12
+ }
13
+ function getParentPath(path) {
14
+ const lastSeparator = path.lastIndexOf("/");
15
+ return lastSeparator < 0 ? "" : path.slice(0, lastSeparator);
16
+ }
17
+ function hasSameParentFilenameCaseConflict(left, right, version) {
18
+ if (!left || !right || !hasFilenameCaseConflict(left, right, version)) return false;
19
+ return normalisePathForIdentity(getParentPath(left), version) === normalisePathForIdentity(getParentPath(right), version);
20
+ }
21
+ export {
22
+ getParentPath,
23
+ hasFilenameCaseConflict,
24
+ hasSameParentFilenameCaseConflict,
25
+ haveMatchingRevisionPaths
26
+ };
@@ -1,3 +1,4 @@
1
1
  export { createConflictCheckQueue } from "./conflicts/conflictCheckQueue.js";
2
2
  export type { ConflictCheckQueue, ConflictCheckQueueOptions } from "./conflicts/conflictCheckQueue.js";
3
3
  export type { FilePathWithPrefix } from "./common/types.js";
4
+ export { haveMatchingRevisionPaths, hasFilenameCaseConflict, hasSameParentFilenameCaseConflict, } from "./conflicts/filenameCaseConflict.js";
package/dist/conflicts.js CHANGED
@@ -1,4 +1,12 @@
1
1
  import { createConflictCheckQueue } from "./conflicts/conflictCheckQueue.js";
2
+ import {
3
+ haveMatchingRevisionPaths,
4
+ hasFilenameCaseConflict,
5
+ hasSameParentFilenameCaseConflict
6
+ } from "./conflicts/filenameCaseConflict.js";
2
7
  export {
3
- createConflictCheckQueue
8
+ createConflictCheckQueue,
9
+ hasFilenameCaseConflict,
10
+ hasSameParentFilenameCaseConflict,
11
+ haveMatchingRevisionPaths
4
12
  };
@@ -9,6 +9,11 @@ export interface ContentReadFailure {
9
9
  /** Original runtime diagnostics, which must not be persisted or inspected to choose recovery. */
10
10
  cause: unknown;
11
11
  }
12
+ /** Restrict live-content matching to an observed, case-preserving filename. */
13
+ export interface LiveContentFilename {
14
+ path: FilePathWithPrefix;
15
+ normalizationVersion: number;
16
+ }
12
17
  export interface DatabaseFileAccess {
13
18
  /** Strict reads preserve ordinary absence but reject failed I/O or incomplete content. */
14
19
  readEntryMeta: DatabaseFileAccess["fetchEntryMeta"];
@@ -16,6 +21,11 @@ export interface DatabaseFileAccess {
16
21
  readEntry: DatabaseFileAccess["fetchEntry"];
17
22
  readConflictedRevs: DatabaseFileAccess["getConflictedRevs"];
18
23
  readLiveContentRevisions: DatabaseFileAccess["findLiveContentRevisions"];
24
+ /**
25
+ * Read the spelling stored on an exact revision of a known document, without loading Chunks.
26
+ * Missing revisions and unrecorded names return undefined. Other read failures reject.
27
+ */
28
+ readRevisionPath?(documentId: DocumentID, revision: string): Promise<string | undefined>;
19
29
  delete: (file: UXFileInfoStub | FilePathWithPrefix, rev?: string) => Promise<boolean>;
20
30
  store: (file: UXFileInfo, force?: boolean, skipCheck?: boolean) => Promise<boolean>;
21
31
  /**
@@ -57,12 +67,13 @@ export interface DatabaseFileAccess {
57
67
  * Return current, non-deleted leaf revisions whose decoded content matches the supplied bytes.
58
68
  * Include the winning and conflicting leaves, but never their ancestors. Read only locally
59
69
  * available Chunks, without requesting remote data or waiting for missing Chunks to arrive.
70
+ * When a filename is supplied, inspect only leaves with that recorded case-preserving path.
60
71
  *
61
72
  * A unique match can recover provenance; several matches avoid a duplicate write but leave
62
73
  * its origin ambiguous. An empty result means no match was confirmed. The strict read rejects
63
74
  * failed I/O; this compatibility facade returns no matches on failure. This read neither records provenance nor reserves a leaf for a later write.
64
75
  */
65
- findLiveContentRevisions: (file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer) => Promise<string[]>;
76
+ findLiveContentRevisions: (file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer, filename?: LiveContentFilename) => Promise<string[]>;
66
77
  fetch: (file: UXFileInfoStub | FilePathWithPrefix, rev?: string, waitForReady?: boolean, skipCheck?: boolean) => Promise<UXFileInfo | false>;
67
78
  fetchEntryFromMeta: (meta: MetaEntry, waitForReady?: boolean, skipCheck?: boolean, localOnly?: boolean) => Promise<LoadedEntry | false>;
68
79
  fetchEntryMeta: (file: UXFileInfoStub | FilePathWithPrefix, rev?: string, skipCheck?: boolean) => Promise<MetaEntry | false>;
@@ -1,13 +1,14 @@
1
1
  import { type Diff } from "diff-match-patch";
2
2
  import { type EntryDoc, type FilePathWithPrefix, type diff_result_leaf, type LoadedEntry, type DIFF_CHECK_RESULT_AUTO } from "../common/types.js";
3
3
  import type { EntryManager } from "./EntryManager/EntryManager.js";
4
- import type { IPathService } from "../services/base/IService.js";
4
+ import type { IPathService, ISettingService } from "../services/base/IService.js";
5
5
  type AutoMergeOutcomeOK = {
6
6
  ok: DIFF_CHECK_RESULT_AUTO;
7
7
  };
8
8
  type AutoMergeCanBeDoneByDeletingRev = {
9
9
  result: string;
10
10
  conflictedRev: string;
11
+ path: FilePathWithPrefix;
11
12
  };
12
13
  type UserActionRequired = {
13
14
  leftRev: string;
@@ -17,20 +18,23 @@ type UserActionRequired = {
17
18
  };
18
19
  export type AutoMergeResult = Promise<AutoMergeOutcomeOK | AutoMergeCanBeDoneByDeletingRev | UserActionRequired>;
19
20
  export interface ConflictManagerOptions {
20
- entryManager: EntryManager;
21
+ entryManager: Pick<EntryManager, "getDBEntry" | "getConflictEntryMeta" | "getDBEntryFromMeta">;
21
22
  pathService: IPathService;
23
+ settingService: Pick<ISettingService, "currentSettings">;
22
24
  database: PouchDB.Database<EntryDoc>;
23
25
  }
24
26
  export declare class ConflictManager {
25
27
  options: ConflictManagerOptions;
26
28
  constructor(options: ConflictManagerOptions);
27
29
  get database(): PouchDB.Database<EntryDoc>;
30
+ private areRecordedRevisionPathsEqual;
28
31
  getConflictedDoc(path: FilePathWithPrefix, rev: string): Promise<false | diff_result_leaf>;
29
32
  mergeSensibly(path: FilePathWithPrefix, baseRev: string, currentRev: string, conflictedRev: string): Promise<Diff[] | false>;
30
33
  mergeObject(path: FilePathWithPrefix, baseRev: string, currentRev: string, conflictedRev: string): Promise<string | false>;
31
34
  tryAutoMergeSensibly(path: FilePathWithPrefix, test: LoadedEntry, conflicts: string[]): Promise<false | {
32
35
  result: string;
33
36
  conflictedRev: string;
37
+ path: FilePathWithPrefix;
34
38
  }>;
35
39
  tryAutoMerge(path: FilePathWithPrefix, enableMarkdownAutoMerge: boolean): AutoMergeResult;
36
40
  }
@@ -14,7 +14,8 @@ import {
14
14
  isSensibleMargeApplicable,
15
15
  isObjectMargeApplicable
16
16
  } from "../common/utils.js";
17
- import { isErrorOfMissingDoc } from "../pouchdb/utils_couchdb.js";
17
+ import { tryGetFilePath } from "../common/utils.doc.js";
18
+ import { haveMatchingRevisionPaths } from "../conflicts/filenameCaseConflict.js";
18
19
  function revisionGeneration(revision) {
19
20
  const generation = Number(revision.split("-", 1)[0]);
20
21
  return Number.isFinite(generation) ? generation : Number.MAX_SAFE_INTEGER;
@@ -30,6 +31,25 @@ function compareConflictCandidates(left, right) {
30
31
  if (left.revision > right.revision) return 1;
31
32
  return 0;
32
33
  }
34
+ function describeRevisionPathMismatch(currentPath, conflictedPath) {
35
+ const reason = currentPath && conflictedPath ? "the recorded paths differ" : "a recorded path is missing";
36
+ return `Skipping automatic merge because ${reason} (current=${JSON.stringify(currentPath)}, conflicted=${JSON.stringify(conflictedPath)}).`;
37
+ }
38
+ function createDiffResultLeafFromLoadedEntry(doc, { rev, recordedPath }) {
39
+ let data = getDocData(doc.data);
40
+ if (doc.datatype === "newnote") {
41
+ data = readString(new Uint8Array(decodeBinary(doc.data)));
42
+ }
43
+ return {
44
+ deleted: doc.deleted || doc._deleted,
45
+ ctime: doc.ctime,
46
+ mtime: doc.mtime,
47
+ rev,
48
+ data,
49
+ datatype: doc.datatype,
50
+ ...recordedPath ? { path: recordedPath } : {}
51
+ };
52
+ }
33
53
  class ConflictManager {
34
54
  options;
35
55
  constructor(options) {
@@ -38,28 +58,24 @@ class ConflictManager {
38
58
  get database() {
39
59
  return this.options.database;
40
60
  }
61
+ areRecordedRevisionPathsEqual(leftRecordedPath, rightRecordedPath) {
62
+ const { pathNormalizationVersion } = this.options.settingService.currentSettings();
63
+ return haveMatchingRevisionPaths(leftRecordedPath, rightRecordedPath, pathNormalizationVersion);
64
+ }
41
65
  async getConflictedDoc(path, rev) {
42
66
  try {
43
- const doc = await this.options.entryManager.getDBEntry(path, { rev }, false, true, true);
44
- if (doc === false) return false;
45
- let data = getDocData(doc.data);
46
- if (doc.datatype == "newnote") {
47
- data = readString(new Uint8Array(decodeBinary(doc.data)));
48
- } else if (doc.datatype == "plain") {
67
+ const entry = await this.options.entryManager.getConflictEntryMeta(path, { rev });
68
+ if (!entry) {
69
+ return false;
49
70
  }
50
- return {
51
- deleted: doc.deleted || doc._deleted,
52
- ctime: doc.ctime,
53
- mtime: doc.mtime,
54
- rev,
55
- data
56
- };
57
- } catch (ex) {
58
- if (isErrorOfMissingDoc(ex)) {
71
+ const doc = await this.options.entryManager.getDBEntryFromMeta(entry.metadata);
72
+ if (!doc) {
59
73
  return false;
60
74
  }
75
+ return createDiffResultLeafFromLoadedEntry(doc, { rev, recordedPath: entry.path });
76
+ } catch {
77
+ return false;
61
78
  }
62
- return false;
63
79
  }
64
80
  async mergeSensibly(path, baseRev, currentRev, conflictedRev) {
65
81
  const baseLeaf = await this.getConflictedDoc(path, baseRev);
@@ -72,6 +88,10 @@ class ConflictManager {
72
88
  if (leftLeaf.deleted || rightLeaf.deleted) {
73
89
  return false;
74
90
  }
91
+ if (!this.areRecordedRevisionPathsEqual(leftLeaf.path, rightLeaf.path)) {
92
+ Logger(describeRevisionPathMismatch(leftLeaf.path, rightLeaf.path), LOG_LEVEL_VERBOSE);
93
+ return false;
94
+ }
75
95
  const dmp = new diff_match_patch();
76
96
  const mapLeft = dmp.diff_linesToChars_(baseLeaf.data, leftLeaf.data);
77
97
  const diffLeftSrc = dmp.diff_main(mapLeft.chars1, mapLeft.chars2, false);
@@ -235,6 +255,10 @@ class ConflictManager {
235
255
  Logger(`Either is deleted`, LOG_LEVEL_VERBOSE);
236
256
  return false;
237
257
  }
258
+ if (!this.areRecordedRevisionPathsEqual(leftLeaf.path, rightLeaf.path)) {
259
+ Logger(describeRevisionPathMismatch(leftLeaf.path, rightLeaf.path), LOG_LEVEL_VERBOSE);
260
+ return false;
261
+ }
238
262
  const baseObj = { data: tryParseJSON(baseLeaf.data, {}) };
239
263
  const leftObj = { data: tryParseJSON(leftLeaf.data, {}) };
240
264
  const rightObj = { data: tryParseJSON(rightLeaf.data, {}) };
@@ -274,12 +298,27 @@ class ConflictManager {
274
298
  async tryAutoMergeSensibly(path, test, conflicts) {
275
299
  const conflictedRev = conflicts[0];
276
300
  let commonBase = "";
301
+ let mergePath;
302
+ const documentId = test._id;
277
303
  try {
278
- const documentId = await this.options.pathService.path2id(path);
279
304
  const [currentBranch, conflictedBranch] = await Promise.all([
280
305
  this.database.get(documentId, { rev: test._rev, revs_info: true }),
281
306
  this.database.get(documentId, { rev: conflictedRev, revs_info: true })
282
307
  ]);
308
+ const currentPath = tryGetFilePath(currentBranch);
309
+ if (!currentPath) {
310
+ Logger(
311
+ `Skipping automatic merge for ${JSON.stringify(path)} because the current revision has no recorded path.`,
312
+ LOG_LEVEL_VERBOSE
313
+ );
314
+ return false;
315
+ }
316
+ const conflictedPath = tryGetFilePath(conflictedBranch);
317
+ if (!this.areRecordedRevisionPathsEqual(currentPath, conflictedPath)) {
318
+ Logger(describeRevisionPathMismatch(currentPath, conflictedPath), LOG_LEVEL_VERBOSE);
319
+ return false;
320
+ }
321
+ mergePath = currentPath;
283
322
  const currentAvailable = new Set(
284
323
  (currentBranch._revs_info || []).filter((revision) => revision.status === "available").map((revision) => revision.rev)
285
324
  );
@@ -309,7 +348,10 @@ class ConflictManager {
309
348
  }
310
349
  }
311
350
  if (p !== void 0) {
312
- return { result: p, conflictedRev };
351
+ if (mergePath !== path && await this.options.pathService.path2id(mergePath) !== documentId) {
352
+ mergePath = path;
353
+ }
354
+ return { result: p, conflictedRev, path: mergePath };
313
355
  }
314
356
  }
315
357
  return false;
@@ -338,8 +380,17 @@ class ConflictManager {
338
380
  const conflicts = conflictCandidates.map(({ revision }) => revision);
339
381
  const leftLeaf = await this.getConflictedDoc(path, test._rev);
340
382
  const rightLeaf = conflictCandidates[0].leaf;
341
- if (leftLeaf !== false && rightLeaf !== false && leftLeaf.data == rightLeaf.data && leftLeaf.deleted == rightLeaf.deleted) {
342
- return { leftRev: test._rev, rightRev: conflicts[0], leftLeaf, rightLeaf };
383
+ const conflict = { leftRev: test._rev, rightRev: conflicts[0], leftLeaf, rightLeaf };
384
+ if (!leftLeaf || !rightLeaf) {
385
+ return conflict;
386
+ }
387
+ if (!this.areRecordedRevisionPathsEqual(leftLeaf.path, rightLeaf.path)) {
388
+ Logger(describeRevisionPathMismatch(leftLeaf.path, rightLeaf.path), LOG_LEVEL_VERBOSE);
389
+ return conflict;
390
+ }
391
+ const sameContentAndDeletionState = leftLeaf.data === rightLeaf.data && leftLeaf.deleted === rightLeaf.deleted;
392
+ if (sameContentAndDeletionState) {
393
+ return conflict;
343
394
  }
344
395
  if ((isSensibleMargeApplicable(path) || isObjectMargeApplicable(path)) && enableMarkdownAutoMerge) {
345
396
  const autoMergeResult = await this.tryAutoMergeSensibly(path, test, conflicts);
@@ -347,7 +398,7 @@ class ConflictManager {
347
398
  return autoMergeResult;
348
399
  }
349
400
  }
350
- return { leftRev: test._rev, rightRev: conflicts[0], leftLeaf, rightLeaf };
401
+ return conflict;
351
402
  }
352
403
  }
353
404
  export {
@@ -37,6 +37,11 @@ export declare class EntryManager {
37
37
  isTargetFile(filenameSrc: string, internalFileEvent?: boolean): boolean;
38
38
  prepareChunk(piece: string): Promise<GeneratedChunk>;
39
39
  getDBEntryMeta(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, includeDeleted?: boolean): Promise<false | LoadedEntry>;
40
+ /** Read a conflict candidate's metadata and its recorded path, including deleted revisions. */
41
+ getConflictEntryMeta(path: FilePathWithPrefix, opt: PouchDB.Core.GetOptions): Promise<false | {
42
+ metadata: LoadedEntry & PouchDB.Core.GetMeta;
43
+ path: FilePathWithPrefix | undefined;
44
+ }>;
40
45
  getDBEntry(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, dump?: boolean, waitForReady?: boolean, includeDeleted?: boolean, localOnly?: boolean): Promise<false | LoadedEntry>;
41
46
  getDBEntryFromMeta(meta: LoadedEntry | MetaEntry, dump?: boolean, waitForReady?: boolean, localOnly?: boolean): Promise<false | LoadedEntry>;
42
47
  deleteDBEntry(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions): Promise<boolean>;
@@ -8,6 +8,7 @@ import {
8
8
  getDBEntryByPath,
9
9
  getDBEntryFromMeta,
10
10
  getDBEntryMetaByPath,
11
+ getConflictEntryMetaByPath,
11
12
  isTargetFile,
12
13
  prepareChunk,
13
14
  putDBEntry,
@@ -65,6 +66,10 @@ class EntryManager {
65
66
  async getDBEntryMeta(path, opt, includeDeleted = false) {
66
67
  return await getDBEntryMetaByPath(this.serviceHost, this, path, opt, includeDeleted);
67
68
  }
69
+ /** Read a conflict candidate's metadata and its recorded path, including deleted revisions. */
70
+ async getConflictEntryMeta(path, opt) {
71
+ return await getConflictEntryMetaByPath(this.serviceHost, this, path, opt);
72
+ }
68
73
  async getDBEntry(path, opt, dump = false, waitForReady = true, includeDeleted = false, localOnly = false) {
69
74
  return await getDBEntryByPath(this.serviceHost, this, path, opt, dump, waitForReady, includeDeleted, localOnly);
70
75
  }
@@ -33,7 +33,11 @@ export declare function putDBEntryWithLiveBaseRevision(host: NecessaryServicesIn
33
33
  export declare function putDBEntryAsIndependentRoot(host: NecessaryServicesInterfaces<"path" | "setting", never>, managers: NecessaryManagers<"localDatabase" | "chunkManager" | "hashManager" | "splitter">, note: SavingEntry): Promise<false | PouchDB.Core.Response>;
34
34
  export declare function isTargetFile(host: NecessaryServicesInterfaces<"setting", never>, filenameSrc: string, internalFileEvent?: boolean): boolean;
35
35
  export declare function prepareChunk({ chunkManager, hashManager }: NecessaryManagers<"chunkManager" | "hashManager">, piece: string): Promise<GeneratedChunk>;
36
- export declare function getDBEntryMetaByPath(host: NecessaryServicesInterfaces<"path" | "setting", never>, { localDatabase, readScope }: NecessaryManagers<"localDatabase">, path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, includeDeleted?: boolean): Promise<false | LoadedEntry>;
36
+ export declare function getDBEntryMetaByPath(host: NecessaryServicesInterfaces<"path" | "setting", never>, managers: NecessaryManagers<"localDatabase">, path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, includeDeleted?: boolean): Promise<false | LoadedEntry>;
37
+ export declare function getConflictEntryMetaByPath(host: NecessaryServicesInterfaces<"path" | "setting", never>, managers: NecessaryManagers<"localDatabase">, path: FilePathWithPrefix, opt: PouchDB.Core.GetOptions): Promise<false | {
38
+ metadata: LoadedEntry & PouchDB.Core.GetMeta;
39
+ path: FilePathWithPrefix | undefined;
40
+ }>;
37
41
  export declare function isLegacyNote(meta: LoadedEntry | MetaEntry): boolean;
38
42
  export declare function canUseOnDemandChunking(settings: ObsidianLiveSyncSettings): boolean;
39
43
  /**
@@ -6,6 +6,7 @@ import {
6
6
  } from "../../common/types.js";
7
7
  import { serialized } from "octagonal-wheels/concurrency/lock";
8
8
  import { createTextBlob, getFileRegExp, isTextBlob } from "../../common/utils.js";
9
+ import { tryGetFilePath } from "../../common/utils.doc.js";
9
10
  import { compatGlobal } from "../../common/coreEnvFunctions.js";
10
11
  import { isErrorOfMissingDoc } from "../../pouchdb/utils_couchdb.js";
11
12
  import { stripAllPrefixes } from "../../string_and_binary/path.js";
@@ -320,7 +321,19 @@ async function prepareChunk({ chunkManager, hashManager }, piece) {
320
321
  const chunkId = await hashManager.computeHash(piece);
321
322
  return { isNew: true, id: `${IDPrefixes.Chunk}${chunkId}`, piece };
322
323
  }
323
- async function getDBEntryMetaByPath(host, { localDatabase, readScope }, path, opt, includeDeleted = false) {
324
+ async function getDBEntryMetaByPath(host, managers, path, opt, includeDeleted = false) {
325
+ const result = await readDBEntryMeta(host, managers, path, opt, includeDeleted);
326
+ return result && result.metadata;
327
+ }
328
+ async function getConflictEntryMetaByPath(host, managers, path, opt) {
329
+ const result = await readDBEntryMeta(host, managers, path, opt, true);
330
+ if (!result) {
331
+ return false;
332
+ }
333
+ const recordedPath = tryGetFilePath(result.document);
334
+ return { metadata: result.metadata, path: recordedPath || void 0 };
335
+ }
336
+ async function readDBEntryMeta(host, { localDatabase, readScope }, path, opt, includeDeleted = false) {
324
337
  if (!isTargetFile(host, path)) {
325
338
  return false;
326
339
  }
@@ -383,7 +396,7 @@ async function getDBEntryMetaByPath(host, { localDatabase, readScope }, path, op
383
396
  type,
384
397
  eden: "eden" in obj ? obj.eden : {}
385
398
  };
386
- return doc;
399
+ return { metadata: doc, document: obj };
387
400
  }
388
401
  } catch (ex) {
389
402
  if (isErrorOfMissingDoc(ex)) {
@@ -676,6 +689,7 @@ export {
676
689
  computeChunkRetrievalMethod,
677
690
  createChunks,
678
691
  deleteDBEntryByPath,
692
+ getConflictEntryMetaByPath,
679
693
  getDBEntryByPath,
680
694
  getDBEntryFromMeta,
681
695
  getDBEntryMetaByPath,
@@ -97,7 +97,8 @@ class LiveSyncManagers {
97
97
  const conflictManager = new ConflictManager({
98
98
  entryManager,
99
99
  database,
100
- pathService: this._pathService
100
+ pathService: this._pathService,
101
+ settingService: this.options.settingService
101
102
  });
102
103
  this.log("LiveSync Managers have been created");
103
104
  return {
@@ -5,6 +5,7 @@ import {
5
5
  SuffixDatabaseName
6
6
  } from "../common/types.js";
7
7
  import { isErrorOfMissingDoc } from "./utils_couchdb.js";
8
+ import { isTombstoneRevision } from "../common/utils.doc.js";
8
9
  import { EVENT_CHUNK_FETCHED } from "../managers/ChunkFetcher.js";
9
10
  import { FallbackWeakRef } from "octagonal-wheels/common/polyfill";
10
11
  import { LocalDatabaseReadScope } from "./LocalDatabaseReadScope.js";
@@ -288,10 +289,8 @@ class LiveSyncLocalDB {
288
289
  for (const change of changes.results) {
289
290
  const doc = change.doc;
290
291
  if (doc.type == "leaf") {
291
- if (doc._deleted) {
292
- if (!includeDeleted) {
293
- continue;
294
- }
292
+ if (isTombstoneRevision(doc) && !includeDeleted) {
293
+ continue;
295
294
  }
296
295
  existing.set(doc._id, doc);
297
296
  }
@@ -24,3 +24,5 @@ export type { JoinedDevice, JoinedDevicesSnapshot, ForgetJoinedDeviceResult } fr
24
24
  export type { ReplicationStatics, CouchDBReplicationPhase, CouchDBReplicationProgress, ReplicationCheckpointProgress, } from "../common/models/shared.definition.js";
25
25
  export { inspectDatabasePathIdentity } from "../pouchdb/pathIdentityCompatibility.js";
26
26
  export type { PathIdentityInspection } from "../pouchdb/pathIdentityCompatibility.js";
27
+ export { createReplicationResultQueueStore } from "./replicationResultQueueStore.js";
28
+ export type { ReplicationResultQueueBacking, ReplicationResultQueueDelta, ReplicationResultQueueRow, ReplicationResultQueueStore, ReplicationResultQueueWrite, } from "./replicationResultQueueStore.js";
@@ -60,6 +60,7 @@ import {
60
60
  usesEncryptedInternalMetadata
61
61
  } from "../pouchdb/remoteFeatureCompatibility.js";
62
62
  import { inspectDatabasePathIdentity } from "../pouchdb/pathIdentityCompatibility.js";
63
+ import { createReplicationResultQueueStore } from "./replicationResultQueueStore.js";
63
64
  export {
64
65
  CAPABILITY_NOT_APPLICABLE,
65
66
  CAPABILITY_NOT_IMPLEMENTED,
@@ -94,6 +95,7 @@ export {
94
95
  assessRemoteFeatureDocument,
95
96
  centralRemoteAdministrationVerificationFailed,
96
97
  centralRemoteAdministrationVerified,
98
+ createReplicationResultQueueStore,
97
99
  defineReplicatorProviderDefinitions,
98
100
  describeRemoteFeatureRejection,
99
101
  getReplicationNetworkFailure,
@@ -0,0 +1,101 @@
1
+ declare const ROW_KINDS: readonly ["processing", "queued", "pendingReflection", "recoveryAttempt"];
2
+ type RowKind = (typeof ROW_KINDS)[number];
3
+ type Row<Kind extends RowKind, Payload> = {
4
+ readonly kind: Kind;
5
+ /** An occurrence ID shared across phase changes. Reserve the 'legacy:' prefix for migration. */
6
+ readonly id: string;
7
+ /** Non-negative safe integer used to order rows within this kind. */
8
+ readonly order: number;
9
+ readonly payload: Payload;
10
+ };
11
+ export type ReplicationResultQueueRow<D, P, A> = Row<"queued", D> | Row<"processing", D> | Row<"pendingReflection", P> | Row<"recoveryAttempt", A>;
12
+ export type ReplicationResultQueueDelta<D, P, A> = {
13
+ readonly kind: "upsert";
14
+ readonly row: ReplicationResultQueueRow<D, P, A>;
15
+ } | {
16
+ readonly kind: "delete";
17
+ readonly id: string;
18
+ };
19
+ type StoredRow = ReplicationResultQueueRow<unknown, unknown, unknown>;
20
+ export type ReplicationResultQueueWrite = {
21
+ readonly kind: "upsert";
22
+ readonly key: string;
23
+ readonly value: StoredRow;
24
+ } | {
25
+ readonly kind: "delete";
26
+ readonly key: string;
27
+ };
28
+ /** Storage for one database and vault scope. The host supplies value encoding and decoding. */
29
+ export interface ReplicationResultQueueBacking {
30
+ /** Return undefined for an absent key and reject on any read or decoding failure. */
31
+ read(key: string): Promise<unknown>;
32
+ /** List every key with the literal prefix exactly once, in any order. */
33
+ listKeys(prefix: string): Promise<readonly string[]>;
34
+ /** Apply the entire ordered batch atomically and resolve after it commits. Deleting absent keys succeeds. */
35
+ writeBatch(operations: readonly ReplicationResultQueueWrite[]): Promise<void>;
36
+ }
37
+ /**
38
+ * The host serialises all calls and excludes other writers to the queue keys.
39
+ * The host owns payload validation, replay policy, and occurrence IDs. Keep an ID
40
+ * for the lifetime of the same occurrence and issue fresh IDs even across resets.
41
+ */
42
+ export interface ReplicationResultQueueStore<D, P, A> {
43
+ /**
44
+ * Migrate a legacy snapshot if present, then return rows by kind in replay
45
+ * order and by ascending order within each kind. Ties use ascending ID.
46
+ * Payloads require host validation before use.
47
+ */
48
+ load(): Promise<readonly StoredRow[]>;
49
+ /** Apply only these changes, in order, after a successful load or discard. Keep payloads stable until the call settles. */
50
+ commit(delta: readonly ReplicationResultQueueDelta<D, P, A>[]): Promise<void>;
51
+ /** Atomically delete queue rows and the legacy snapshot. May be called before load to skip replay. */
52
+ discard(): Promise<void>;
53
+ }
54
+ /**
55
+ * Convert a legacy snapshot to rows in replay order. Each array index determines
56
+ * the row's order and forms part of its migrated occurrence ID.
57
+ *
58
+ * @param snapshot - The decoded value of the legacy snapshot key.
59
+ * @returns Rows carrying their original payloads for the host to validate.
60
+ * @throws If the snapshot, a queue array, or an entry has an invalid storage format.
61
+ */
62
+ export declare function rowsFromLegacyReplicationResultSnapshot(snapshot: unknown): StoredRow[];
63
+ /**
64
+ * Compare rows by kind in replay order, then by ascending order within that
65
+ * kind and ascending occurrence ID using string comparison.
66
+ *
67
+ * @returns A negative number when `left` comes first, zero when the sort keys
68
+ * match, and a positive number when `right` comes first.
69
+ */
70
+ export declare function compareReplicationResultQueueRows(left: StoredRow, right: StoredRow): number;
71
+ /**
72
+ * Read stored rows in replay order. When a legacy snapshot is present, write
73
+ * its rows and delete the legacy key in the same atomic batch before returning.
74
+ *
75
+ * @param backing - Storage for one queue scope. Exclude other writers to its
76
+ * queue keys while this operation runs.
77
+ * @returns Rows with payloads that require host validation before use.
78
+ * @throws If stored data is invalid, both formats exist, or a backing operation fails.
79
+ */
80
+ export declare function loadReplicationResultQueueRows(backing: ReplicationResultQueueBacking): Promise<StoredRow[]>;
81
+ /**
82
+ * Validate row storage fields and translate queue changes to versioned key
83
+ * operations. Payloads pass through for the backing to encode.
84
+ *
85
+ * @param delta - Changes to translate in the order supplied by the host.
86
+ * @returns The corresponding writes in input order, ready for one atomic batch.
87
+ * @throws {@link TypeError} If a change has an invalid row, occurrence ID, or kind.
88
+ */
89
+ export declare function toReplicationResultQueueWrites(delta: readonly ReplicationResultQueueDelta<unknown, unknown, unknown>[]): ReplicationResultQueueWrite[];
90
+ /**
91
+ * Create a store for a single replication result queue. Construction performs
92
+ * no I/O. Call `load()` or `discard()` successfully before calling `commit()`.
93
+ *
94
+ * @typeParam D - Document payload written for queued and processing items.
95
+ * @typeParam P - Payload written for retained reflection failures.
96
+ * @typeParam A - Payload written for recovery attempts.
97
+ * @param backing - Host-owned storage that can commit an ordered batch atomically.
98
+ * @returns A queue store whose operations the host must serialise.
99
+ */
100
+ export declare function createReplicationResultQueueStore<D, P, A>(backing: ReplicationResultQueueBacking): ReplicationResultQueueStore<D, P, A>;
101
+ export {};