@vrtmrz/livesync-commonlib 0.4.1 → 0.4.3

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 (70) hide show
  1. package/README.md +16 -2
  2. package/dist/API/DirectFileManipulatorV2.d.ts +1 -0
  3. package/dist/API/DirectFileManipulatorV2.js +3 -1
  4. package/dist/API/processSetting.d.ts +1 -0
  5. package/dist/API/processSetting.js +3 -0
  6. package/dist/common/models/setting.const.defaults.js +1 -0
  7. package/dist/common/models/setting.const.qr.js +2 -1
  8. package/dist/common/models/setting.encryption.d.ts +2 -0
  9. package/dist/common/models/setting.encryption.js +6 -0
  10. package/dist/common/models/setting.lifecycle.js +7 -2
  11. package/dist/common/models/setting.policy.d.ts +4 -0
  12. package/dist/common/models/setting.policy.js +9 -0
  13. package/dist/common/models/setting.type.d.ts +2 -0
  14. package/dist/common/models/shared.definition.configNames.js +5 -0
  15. package/dist/common/models/tweak.definition.d.ts +1 -0
  16. package/dist/common/settingConstants.d.ts +1 -0
  17. package/dist/common/utils.js +5 -4
  18. package/dist/diagnostics/couchdb.js +4 -2
  19. package/dist/interfaces/FileHandler.d.ts +59 -0
  20. package/dist/interfaces/FileReflectionProvenance.d.ts +15 -1
  21. package/dist/interfaces/FileReflectionProvenance.js +11 -1
  22. package/dist/managers/ChunkFetcher.js +27 -4
  23. package/dist/managers/chunkFetcher.helper.js +1 -1
  24. package/dist/pouchdb/StreamingFetch.d.ts +1 -2
  25. package/dist/pouchdb/encryption.d.ts +5 -10
  26. package/dist/pouchdb/encryption.eden.d.ts +11 -0
  27. package/dist/pouchdb/encryption.eden.js +37 -0
  28. package/dist/pouchdb/encryption.js +67 -63
  29. package/dist/pouchdb/encryption.policy.d.ts +9 -0
  30. package/dist/pouchdb/encryption.policy.js +125 -0
  31. package/dist/replication/UnencryptedContentRejectedError.d.ts +16 -0
  32. package/dist/replication/UnencryptedContentRejectedError.js +44 -0
  33. package/dist/replication/couchdb/LiveSyncReplicator.js +41 -4
  34. package/dist/replication/index.d.ts +2 -0
  35. package/dist/replication/index.js +3 -0
  36. package/dist/replication/trystero/TrysteroReplicator.d.ts +2 -0
  37. package/dist/replication/unencryptedContentMessages.d.ts +8 -0
  38. package/dist/replication/unencryptedContentMessages.js +12 -0
  39. package/dist/serviceFeatures/offlineScanner/fileStatus.d.ts +61 -0
  40. package/dist/serviceFeatures/offlineScanner/fileStatus.js +85 -0
  41. package/dist/serviceFeatures/offlineScanner/files.d.ts +47 -0
  42. package/dist/serviceFeatures/offlineScanner/files.js +218 -0
  43. package/dist/serviceFeatures/offlineScanner/metadata.d.ts +56 -0
  44. package/dist/serviceFeatures/offlineScanner/metadata.js +320 -0
  45. package/dist/serviceFeatures/offlineScanner/paths.d.ts +20 -0
  46. package/dist/serviceFeatures/offlineScanner/paths.js +16 -0
  47. package/dist/serviceFeatures/offlineScanner/scan.d.ts +35 -0
  48. package/dist/serviceFeatures/offlineScanner/scan.js +358 -0
  49. package/dist/serviceFeatures/offlineScanner/types.d.ts +134 -0
  50. package/dist/serviceFeatures/offlineScanner/types.js +66 -0
  51. package/dist/serviceFeatures/offlineScanner.d.ts +25 -251
  52. package/dist/serviceFeatures/offlineScanner.js +36 -860
  53. package/dist/serviceModules/Rebuilder.js +28 -4
  54. package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.d.ts +13 -0
  55. package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.js +194 -0
  56. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +22 -1
  57. package/dist/serviceModules/ServiceFileHandlerBase.js +29 -0
  58. package/dist/services/base/KeyValueDBService.d.ts +9 -0
  59. package/dist/services/base/KeyValueDBService.js +11 -1
  60. package/dist/services/base/RemoteConnection.d.ts +2 -0
  61. package/dist/services/base/RemoteService.js +2 -1
  62. package/dist/services/base/SettingService.js +2 -0
  63. package/dist/settings.d.ts +2 -1
  64. package/dist/settings.js +2 -0
  65. package/dist/worker/bgWorker.js +1 -1
  66. package/docs/development.md +4 -0
  67. package/docs/offline-scanner.md +22 -0
  68. package/docs/settings-lifecycle.md +4 -0
  69. package/docs/storage-events-and-reflection.md +16 -10
  70. package/package.json +1 -1
@@ -0,0 +1,358 @@
1
+ import { unique } from "octagonal-wheels/collection";
2
+ import { withConcurrency } from "octagonal-wheels/iterable/map";
3
+ import { withLock } from "octagonal-wheels/concurrency/lock.scoped";
4
+ import {
5
+ LOG_LEVEL_INFO,
6
+ LOG_LEVEL_NOTICE,
7
+ LOG_LEVEL_VERBOSE
8
+ } from "../../common/types.js";
9
+ import { compareMTime } from "../../common/utils.js";
10
+ import { BASE_IS_NEW, EVEN, TARGET_IS_NEW } from "../../common/models/shared.const.symbols.js";
11
+ import { stripAllPrefixes } from "../../string_and_binary/path.js";
12
+ import { VaultScanResults } from "../../services/base/VaultScanResult.js";
13
+ import { getPathFromEntry, convertCase } from "./paths.js";
14
+ import {
15
+ fileStatus,
16
+ loadFileStatus,
17
+ flushFileStatus,
18
+ saveFileStatus,
19
+ updateFileMTimeInMap,
20
+ getFileMTimeFromMap
21
+ } from "./fileStatus.js";
22
+ import {
23
+ collectFilesOnStorage,
24
+ collectDatabaseFiles,
25
+ updateToDatabase,
26
+ updateToStorage,
27
+ syncStorageAndDatabase
28
+ } from "./files.js";
29
+ import {
30
+ FullScanModes,
31
+ ExtraOnLocal,
32
+ ExtraOnRemote,
33
+ FilePairProcessResults
34
+ } from "./types.js";
35
+ function isDeletedEntry(entry) {
36
+ return entry.deleted || entry._deleted || false;
37
+ }
38
+ function getFilePairState(pair) {
39
+ const { file, doc } = pair;
40
+ if (file && doc) {
41
+ return isDeletedEntry(doc) ? "both-db-deleted" : "both";
42
+ }
43
+ if (file) {
44
+ return "storage-only";
45
+ }
46
+ if (doc) {
47
+ return isDeletedEntry(doc) ? "db-only-deleted" : "db-only";
48
+ }
49
+ throw new Error("Corrupted file pair");
50
+ }
51
+ function shouldDeleteLocalWhenRemoteMissing(options) {
52
+ return options.extraOnRemote === ExtraOnRemote.DELETE_LOCAL_MISSING || options.extraOnLocal === ExtraOnLocal.DELETE_DB_MISSING;
53
+ }
54
+ function shouldDeleteLocalWhenRemoteDeleted(options) {
55
+ return options.extraOnRemote === ExtraOnRemote.DELETE_LOCAL_MISSING || options.extraOnLocal === ExtraOnLocal.DELETE_DB_DELETED || options.extraOnLocal === ExtraOnLocal.DELETE_DB_MISSING;
56
+ }
57
+ function resolveFilePairAction(state, options) {
58
+ switch (options.mode) {
59
+ case FullScanModes.DB_APPLY:
60
+ switch (state) {
61
+ case "both":
62
+ case "db-only":
63
+ return "update-storage";
64
+ case "storage-only":
65
+ return shouldDeleteLocalWhenRemoteMissing(options) ? "delete-local" : "skip";
66
+ case "both-db-deleted":
67
+ return shouldDeleteLocalWhenRemoteDeleted(options) ? "delete-local" : "skip";
68
+ case "db-only-deleted":
69
+ return "skip";
70
+ }
71
+ break;
72
+ case FullScanModes.NEWER_WINS:
73
+ switch (state) {
74
+ case "both":
75
+ return "sync-newer";
76
+ case "storage-only":
77
+ return shouldDeleteLocalWhenRemoteMissing(options) ? "delete-local" : "update-db";
78
+ case "db-only":
79
+ return "update-storage";
80
+ case "both-db-deleted":
81
+ if (shouldDeleteLocalWhenRemoteDeleted(options)) {
82
+ return "delete-local";
83
+ }
84
+ return options.extraOnLocal === ExtraOnLocal.APPEND_STORAGE_ONLY ? "update-db" : "skip";
85
+ case "db-only-deleted":
86
+ return "skip";
87
+ }
88
+ break;
89
+ }
90
+ return "skip";
91
+ }
92
+ async function processFilePair(host, log, pair, options) {
93
+ const fileMaps = fileStatus(host).map;
94
+ const { file, doc } = pair;
95
+ const canonicalPath = doc ? getPathFromEntry(host, doc) : file?.path;
96
+ if (!canonicalPath) {
97
+ throw new Error("Corrupted file pair");
98
+ }
99
+ const path = canonicalPath;
100
+ const fileMapKey = convertCase(host.services.setting.currentSettings(), canonicalPath);
101
+ if (file) {
102
+ updateFileMTimeInMap(host, fileMapKey, file.stat.mtime);
103
+ }
104
+ if (doc && (doc._conflicts?.length ?? 0) > 0) {
105
+ log(`SKIP ${options.mode}: ${path} has conflicts`, LOG_LEVEL_INFO);
106
+ return FilePairProcessResults.SKIPPED;
107
+ }
108
+ const state = getFilePairState(pair);
109
+ let action = resolveFilePairAction(state, options);
110
+ if (options.mode === FullScanModes.NEWER_WINS && state === "db-only" && doc) {
111
+ const lastSeenMTime = getFileMTimeFromMap(host, fileMapKey);
112
+ if (lastSeenMTime !== void 0) {
113
+ const recency = compareMTime(lastSeenMTime, doc.mtime);
114
+ if (recency === BASE_IS_NEW || recency === EVEN) {
115
+ action = "delete-db";
116
+ log(`NEWER_WINS: Treating missing local file as deletion (${path})`, LOG_LEVEL_VERBOSE);
117
+ }
118
+ }
119
+ }
120
+ try {
121
+ switch (action) {
122
+ case "update-db":
123
+ if (!file) {
124
+ throw new Error(`Missing storage file for ${path}`);
125
+ }
126
+ return await updateToDatabase(host, log, LOG_LEVEL_INFO, file);
127
+ case "update-storage":
128
+ if (!doc) {
129
+ throw new Error(`Missing database entry for ${path}`);
130
+ }
131
+ const updateStorageResult = await updateToStorage(host, log, LOG_LEVEL_INFO, doc);
132
+ if (updateStorageResult === FilePairProcessResults.COMPLETED) {
133
+ updateFileMTimeInMap(host, fileMapKey, doc.mtime);
134
+ }
135
+ return updateStorageResult;
136
+ case "sync-newer":
137
+ if (!file || !doc) {
138
+ throw new Error(`Cannot compare freshness for ${path}`);
139
+ }
140
+ const syncResult = await syncStorageAndDatabase(host, log, file, LOG_LEVEL_INFO, doc, options);
141
+ if (syncResult === FilePairProcessResults.COMPLETED) {
142
+ updateFileMTimeInMap(host, fileMapKey, Math.max(file.stat.mtime, doc.mtime));
143
+ }
144
+ return syncResult;
145
+ case "delete-local":
146
+ if (!file) {
147
+ log(`DELETE LOCAL: ${path} is already absent from storage`, LOG_LEVEL_VERBOSE);
148
+ return FilePairProcessResults.COMPLETED;
149
+ }
150
+ log(`DELETE LOCAL: ${file.path}`, LOG_LEVEL_INFO);
151
+ await host.serviceModules.storageAccess.delete(file.path, true);
152
+ fileMaps.delete(fileMapKey);
153
+ saveFileStatus(host);
154
+ return FilePairProcessResults.COMPLETED;
155
+ case "delete-db": {
156
+ if (!doc) {
157
+ throw new Error(`Missing database entry for ${path}`);
158
+ }
159
+ log(`DELETE DATABASE: ${path}`, LOG_LEVEL_INFO);
160
+ const dbDeleted = await host.serviceModules.fileHandler.deleteFileFromDB(stripAllPrefixes(path));
161
+ if (dbDeleted) {
162
+ fileMaps.delete(fileMapKey);
163
+ saveFileStatus(host);
164
+ return FilePairProcessResults.COMPLETED;
165
+ } else {
166
+ log(
167
+ `DELETE DATABASE did not delete ${path}; keeping last-seen record to avoid resurrecting the file`,
168
+ LOG_LEVEL_NOTICE
169
+ );
170
+ return FilePairProcessResults.FAILED;
171
+ }
172
+ }
173
+ case "skip":
174
+ log(`SKIP ${options.mode}: ${path} (${state})`, LOG_LEVEL_VERBOSE);
175
+ return FilePairProcessResults.SKIPPED;
176
+ }
177
+ } catch (ex) {
178
+ log(`Error processing ${path} with action ${action}`, LOG_LEVEL_NOTICE);
179
+ log(ex, LOG_LEVEL_VERBOSE);
180
+ return FilePairProcessResults.FAILED;
181
+ }
182
+ }
183
+ async function synchroniseAllFilesBetweenDBandStorage(host, log, errorManager, options) {
184
+ return await withLock(fileStatus(host).scanLock, () => synchroniseFilePairs(host, log, errorManager, options));
185
+ }
186
+ async function collectScanPairs(host, settings, log, showingNotice) {
187
+ const { storageFileNameMap, storageFileNameCI2CS } = await collectFilesOnStorage(host, settings, log);
188
+ const { databaseFileNameMap, databaseFileNameCI2CS, quarantinedFileNamesLC } = await collectDatabaseFiles(
189
+ host,
190
+ settings,
191
+ log,
192
+ showingNotice
193
+ );
194
+ const pairs = [];
195
+ for (const fileNameLC of unique([
196
+ ...Object.keys(storageFileNameCI2CS),
197
+ ...Object.keys(databaseFileNameCI2CS)
198
+ ])) {
199
+ if (quarantinedFileNamesLC.has(fileNameLC)) {
200
+ continue;
201
+ }
202
+ const fileName = fileNameLC in storageFileNameCI2CS ? storageFileNameCI2CS[fileNameLC] : void 0;
203
+ const file = fileName ? storageFileNameMap[fileName] : void 0;
204
+ const databaseName = fileNameLC in databaseFileNameCI2CS ? databaseFileNameCI2CS[fileNameLC] : void 0;
205
+ const doc = databaseName ? databaseFileNameMap[databaseName] : void 0;
206
+ const pair = { file, doc };
207
+ pairs.push(pair);
208
+ }
209
+ return pairs;
210
+ }
211
+ async function planDeletionRecovery(host, pairs, options, log) {
212
+ const handler = host.serviceModules.fileHandler;
213
+ const settings = host.services.setting.currentSettings();
214
+ const enabled = options.mode === FullScanModes.NEWER_WINS && !options.extraOnLocal && !options.extraOnRemote && handler.supportsDeletionRecovery?.() === true;
215
+ const recoveries = /* @__PURE__ */ new Set();
216
+ const cleanup = /* @__PURE__ */ new Set();
217
+ let maintenanceFailures = 0;
218
+ if (!enabled) return { enabled, recoveries, cleanup, maintenanceFailures };
219
+ const absent = [];
220
+ for (const pair of pairs) {
221
+ const { file, doc } = pair;
222
+ if (!doc?.deleted || doc._deleted || doc._conflicts?.length) continue;
223
+ if (!file) {
224
+ absent.push(pair);
225
+ } else if (host.services.path.compareFileFreshness(file, doc) === TARGET_IS_NEW) {
226
+ recoveries.add(pair);
227
+ }
228
+ }
229
+ if (absent.length) {
230
+ try {
231
+ const keys = new Set((await handler.listDeletionRecoveryPaths()).map((p) => convertCase(settings, p)));
232
+ const fileMaps = fileStatus(host).map;
233
+ for (const pair of absent) {
234
+ const key = convertCase(settings, getPathFromEntry(host, pair.doc));
235
+ if (keys.has(key) || fileMaps.has(key)) cleanup.add(pair);
236
+ }
237
+ } catch (error) {
238
+ maintenanceFailures++;
239
+ log("Deletion recovery could not enumerate provenance; bookkeeping remains incomplete.", LOG_LEVEL_NOTICE);
240
+ log(error, LOG_LEVEL_VERBOSE);
241
+ }
242
+ }
243
+ return { enabled, recoveries, cleanup, maintenanceFailures };
244
+ }
245
+ async function synchroniseFilePairs(host, log, errorManager, options) {
246
+ const settings = host.services.setting.currentSettings();
247
+ const showingNotice = options.showingNotice ?? false;
248
+ await loadFileStatus(host);
249
+ const fileMaps = fileStatus(host).map;
250
+ const pairs = await collectScanPairs(host, settings, log, showingNotice);
251
+ log(`Total files to synchronise: ${pairs.length}`, LOG_LEVEL_VERBOSE, "syncAll");
252
+ let completedCount = 0;
253
+ let skippedCount = 0;
254
+ let failedCount = 0;
255
+ let processedCount = 0;
256
+ const handler = host.serviceModules.fileHandler;
257
+ const plan = await planDeletionRecovery(host, pairs, options, log);
258
+ const { enabled, recoveries, cleanup } = plan;
259
+ let maintenanceFailures = plan.maintenanceFailures;
260
+ let recoveryApplied = 0;
261
+ let recoveryDeferred = 0;
262
+ let recoveryPending = 0;
263
+ const phases = [cleanup, pairs.filter((pair) => !cleanup.has(pair))];
264
+ const processPair = async (e) => {
265
+ if (!recoveries.has(e) && !cleanup.has(e)) return await processFilePair(host, log, e, options);
266
+ if (!options.ignoreSuspending && host.services.setting.currentSettings().suspendFileWatching) {
267
+ return FilePairProcessResults.SKIPPED;
268
+ }
269
+ const key = convertCase(settings, getPathFromEntry(host, e.doc));
270
+ if (e.file) fileMaps.set(key, e.file.stat.mtime);
271
+ const result = await handler.recoverDatabaseDeletion(e.doc, cleanup.has(e));
272
+ if (result.file === "absent") {
273
+ fileMaps.delete(key);
274
+ } else if (e.file) {
275
+ fileMaps.set(key, e.file.stat.mtime);
276
+ }
277
+ if (result.file === "absent" && !cleanup.has(e)) recoveryApplied++;
278
+ if (result.status === "deferred") recoveryDeferred++;
279
+ if (result.provenance === "pending") recoveryPending++;
280
+ if (result.warning || result.status !== "applied") {
281
+ const detail = result.warning ? `${result.reason}; ${result.warning}` : result.reason;
282
+ log(`Deletion recovery ${result.status}: ${e.doc.path} (${detail})`, LOG_LEVEL_VERBOSE);
283
+ if (result.error) log(result.error, LOG_LEVEL_VERBOSE);
284
+ }
285
+ if (result.status === "failed") return FilePairProcessResults.FAILED;
286
+ return result.status === "deferred" ? FilePairProcessResults.SKIPPED : FilePairProcessResults.COMPLETED;
287
+ };
288
+ async function* processPhases() {
289
+ for (const phase of phases) {
290
+ yield* withConcurrency(
291
+ phase,
292
+ async (e) => {
293
+ const path = e.file?.path ?? getPathFromEntry(host, e.doc);
294
+ try {
295
+ return { path, result: await processPair(e) };
296
+ } catch (error) {
297
+ log(`Error while synchronising files`, LOG_LEVEL_NOTICE);
298
+ log(error, LOG_LEVEL_VERBOSE);
299
+ return { path, result: FilePairProcessResults.FAILED };
300
+ }
301
+ },
302
+ 10
303
+ );
304
+ }
305
+ }
306
+ for await (const { path, result } of processPhases()) {
307
+ processedCount++;
308
+ switch (result) {
309
+ case FilePairProcessResults.COMPLETED:
310
+ completedCount++;
311
+ break;
312
+ case FilePairProcessResults.SKIPPED:
313
+ skippedCount++;
314
+ break;
315
+ case FilePairProcessResults.FAILED:
316
+ failedCount++;
317
+ log(
318
+ `Offline scan failed to synchronise ${path} between storage and the local database; this path remains eligible for a later scan.`,
319
+ LOG_LEVEL_VERBOSE
320
+ );
321
+ break;
322
+ }
323
+ if (processedCount % 25 === 0) {
324
+ log(
325
+ `Processing: ${processedCount}/${pairs.length}`,
326
+ showingNotice ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
327
+ "syncAll"
328
+ );
329
+ }
330
+ }
331
+ log(
332
+ `Synchronisation completed: ${processedCount} files processed (${completedCount} completed, ${skippedCount} skipped, ${failedCount} failed)`,
333
+ showingNotice ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO,
334
+ "syncAll"
335
+ );
336
+ if (enabled) {
337
+ log(
338
+ `Deletion recovery: ${recoveryApplied} applied, ${recoveryDeferred} deferred, ${recoveryPending} cleanup pending`,
339
+ showingNotice ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO
340
+ );
341
+ try {
342
+ await flushFileStatus(host);
343
+ } catch (error) {
344
+ maintenanceFailures++;
345
+ log("Deletion recovery bookkeeping could not be persisted; the scan remains incomplete.", LOG_LEVEL_NOTICE);
346
+ log(error, LOG_LEVEL_VERBOSE);
347
+ }
348
+ } else {
349
+ saveFileStatus(host, true);
350
+ }
351
+ if (failedCount === 0 && maintenanceFailures === 0) return VaultScanResults.COMPLETED;
352
+ return options.continueOnFileFailure === true ? VaultScanResults.COMPLETED_WITH_FILE_FAILURES : VaultScanResults.FAILED;
353
+ }
354
+ export {
355
+ getFilePairState,
356
+ resolveFilePairAction,
357
+ synchroniseAllFilesBetweenDBandStorage
358
+ };
@@ -0,0 +1,134 @@
1
+ import type { DocumentID, FilePathWithPrefix, MetaEntry, UXFileInfoStub } from "../../common/types.js";
2
+ import type { VaultScanOptions } from "../../services/base/VaultScanResult.js";
3
+ /**
4
+ * Outcome of processing one storage/database pair during an offline scan.
5
+ *
6
+ * A skipped pair is intentionally left unchanged by scanner policy. It is not
7
+ * a scan failure, but it must not receive success side effects which would
8
+ * claim that database content was reflected to storage.
9
+ */
10
+ export declare const FilePairProcessResults: {
11
+ readonly COMPLETED: "completed";
12
+ readonly SKIPPED: "skipped";
13
+ readonly FAILED: "failed";
14
+ };
15
+ export type FilePairProcessResult = (typeof FilePairProcessResults)[keyof typeof FilePairProcessResults];
16
+ export declare const MetadataDocumentNamespaces: {
17
+ readonly NORMAL: "normal";
18
+ readonly INTERNAL: "internal";
19
+ readonly CUSTOMISATION: "customisation";
20
+ readonly PLUGIN_STORAGE: "plugin-storage";
21
+ };
22
+ export type MetadataDocumentNamespace = (typeof MetadataDocumentNamespaces)[keyof typeof MetadataDocumentNamespaces];
23
+ export declare const MetadataDocumentIdentityStatuses: {
24
+ readonly CONSISTENT: "consistent";
25
+ readonly EXCLUDED: "excluded";
26
+ readonly UNRESOLVED: "unresolved";
27
+ };
28
+ export declare const OfflineScanUnresolvedReasons: {
29
+ readonly DOCUMENT_ID_MISMATCH: "document-id-mismatch";
30
+ readonly NAMESPACE_MISMATCH: "namespace-mismatch";
31
+ };
32
+ export interface OfflineScanUnresolvedDiagnostic {
33
+ reason: (typeof OfflineScanUnresolvedReasons)[keyof typeof OfflineScanUnresolvedReasons];
34
+ actualDocumentId: DocumentID;
35
+ declaredPath: FilePathWithPrefix;
36
+ expectedDocumentId?: DocumentID;
37
+ actualNamespace: MetadataDocumentNamespace;
38
+ declaredPathNamespace: MetadataDocumentNamespace;
39
+ }
40
+ export type MetadataDocumentIdentityInspection = {
41
+ status: typeof MetadataDocumentIdentityStatuses.CONSISTENT;
42
+ actualDocumentId: DocumentID;
43
+ declaredPath: FilePathWithPrefix;
44
+ expectedDocumentId: DocumentID;
45
+ } | {
46
+ status: typeof MetadataDocumentIdentityStatuses.EXCLUDED;
47
+ actualDocumentId: DocumentID;
48
+ declaredPath: FilePathWithPrefix;
49
+ namespace: Exclude<MetadataDocumentNamespace, "normal">;
50
+ } | {
51
+ status: typeof MetadataDocumentIdentityStatuses.UNRESOLVED;
52
+ diagnostic: OfflineScanUnresolvedDiagnostic;
53
+ };
54
+ export interface MetadataDocumentIdentityIssue {
55
+ inspection: Extract<MetadataDocumentIdentityInspection, {
56
+ status: typeof MetadataDocumentIdentityStatuses.UNRESOLVED;
57
+ }>;
58
+ sourceRevision: string | null;
59
+ logicallyDeleted: boolean;
60
+ conflictRevisions: string[];
61
+ repairAvailable: boolean;
62
+ targetAlreadyPresent: boolean;
63
+ ordinaryPathAvailable: boolean;
64
+ }
65
+ export declare const MetadataDocumentRepairResults: {
66
+ readonly COMPLETED: "completed";
67
+ readonly STALE: "stale";
68
+ readonly BLOCKED: "blocked";
69
+ readonly FAILED: "failed";
70
+ };
71
+ export interface MetadataDocumentRepairRequest {
72
+ actualDocumentId: DocumentID;
73
+ expectedDocumentId: DocumentID;
74
+ sourceRevision: string;
75
+ }
76
+ export type MetadataDocumentRepairResult = {
77
+ status: (typeof MetadataDocumentRepairResults)[keyof typeof MetadataDocumentRepairResults];
78
+ actualDocumentId: DocumentID;
79
+ expectedDocumentId: DocumentID;
80
+ sourceRevision: string;
81
+ targetCreated: boolean;
82
+ message?: string;
83
+ };
84
+ export declare const FullScanModes: {
85
+ readonly DB_APPLY: "db-apply";
86
+ readonly NEWER_WINS: "newer-wins";
87
+ };
88
+ export declare const ExtraOnRemote: {
89
+ /**
90
+ * Delete database entries if they are missing on storage.
91
+ */
92
+ readonly DELETE_LOCAL_MISSING: "delete-local-missing";
93
+ };
94
+ export declare const ExtraOnLocal: {
95
+ /**
96
+ * Delete local files if they were deleted on database.
97
+ */
98
+ readonly DELETE_DB_DELETED: "delete-db-deleted";
99
+ /**
100
+ * Delete local files if they are missing on database or were deleted on database.
101
+ */
102
+ readonly DELETE_DB_MISSING: "delete-db-missing";
103
+ /**
104
+ * Merge local files to database
105
+ */
106
+ readonly APPEND_STORAGE_ONLY: "append-storage-only";
107
+ };
108
+ export interface FullScanOptions extends VaultScanOptions {
109
+ mode: FullScanMode;
110
+ extraOnLocal?: (typeof ExtraOnLocal)[keyof typeof ExtraOnLocal];
111
+ extraOnRemote?: (typeof ExtraOnRemote)[keyof typeof ExtraOnRemote];
112
+ omitEvents?: boolean;
113
+ showingNotice?: boolean;
114
+ ignoreSuspending?: boolean;
115
+ /**
116
+ * Allow a completed scan containing individual file-pair failures to
117
+ * satisfy ordinary application readiness. Scan preconditions remain
118
+ * strict, and failed pairs remain retryable.
119
+ */
120
+ continueOnFileFailure?: boolean;
121
+ }
122
+ export type FullScanMode = (typeof FullScanModes)[keyof typeof FullScanModes];
123
+ export type FilePair = {
124
+ file: UXFileInfoStub;
125
+ doc: MetaEntry;
126
+ } | {
127
+ file: undefined;
128
+ doc: MetaEntry;
129
+ } | {
130
+ file: UXFileInfoStub;
131
+ doc: undefined;
132
+ };
133
+ export type FilePairState = "storage-only" | "db-only" | "db-only-deleted" | "both" | "both-db-deleted";
134
+ export type FilePairAction = "update-db" | "update-storage" | "sync-newer" | "delete-local" | "delete-db" | "skip";
@@ -0,0 +1,66 @@
1
+ const FilePairProcessResults = {
2
+ COMPLETED: "completed",
3
+ SKIPPED: "skipped",
4
+ FAILED: "failed"
5
+ };
6
+ const MetadataDocumentNamespaces = {
7
+ NORMAL: "normal",
8
+ INTERNAL: "internal",
9
+ CUSTOMISATION: "customisation",
10
+ PLUGIN_STORAGE: "plugin-storage"
11
+ };
12
+ const MetadataDocumentIdentityStatuses = {
13
+ CONSISTENT: "consistent",
14
+ EXCLUDED: "excluded",
15
+ UNRESOLVED: "unresolved"
16
+ };
17
+ const OfflineScanUnresolvedReasons = {
18
+ DOCUMENT_ID_MISMATCH: "document-id-mismatch",
19
+ NAMESPACE_MISMATCH: "namespace-mismatch"
20
+ };
21
+ const MetadataDocumentRepairResults = {
22
+ COMPLETED: "completed",
23
+ STALE: "stale",
24
+ BLOCKED: "blocked",
25
+ FAILED: "failed"
26
+ };
27
+ const FullScanModes = {
28
+ // SAFE: "safe",
29
+ DB_APPLY: "db-apply",
30
+ NEWER_WINS: "newer-wins"
31
+ // STORAGE_ONLY: "local-only",
32
+ };
33
+ const ExtraOnRemote = {
34
+ /**
35
+ * Delete database entries if they are missing on storage.
36
+ */
37
+ DELETE_LOCAL_MISSING: "delete-local-missing"
38
+ /**
39
+ * Apply changes from database to storage.
40
+ */
41
+ // APPEND_DB_ONLY: "append-db-only",
42
+ };
43
+ const ExtraOnLocal = {
44
+ /**
45
+ * Delete local files if they were deleted on database.
46
+ */
47
+ DELETE_DB_DELETED: "delete-db-deleted",
48
+ /**
49
+ * Delete local files if they are missing on database or were deleted on database.
50
+ */
51
+ DELETE_DB_MISSING: "delete-db-missing",
52
+ /**
53
+ * Merge local files to database
54
+ */
55
+ APPEND_STORAGE_ONLY: "append-storage-only"
56
+ };
57
+ export {
58
+ ExtraOnLocal,
59
+ ExtraOnRemote,
60
+ FilePairProcessResults,
61
+ FullScanModes,
62
+ MetadataDocumentIdentityStatuses,
63
+ MetadataDocumentNamespaces,
64
+ MetadataDocumentRepairResults,
65
+ OfflineScanUnresolvedReasons
66
+ };