@vrtmrz/livesync-commonlib 0.7.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 (93) 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/interfaces/FileReflectionProvenance.js +1 -0
  13. package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
  14. package/dist/managers/ConflictManager.d.ts +6 -2
  15. package/dist/managers/ConflictManager.js +73 -22
  16. package/dist/managers/EntryManager/EntryManager.d.ts +5 -0
  17. package/dist/managers/EntryManager/EntryManager.js +5 -0
  18. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +5 -1
  19. package/dist/managers/EntryManager/EntryManagerImpls.js +92 -6
  20. package/dist/managers/LiveSyncManagers.js +2 -1
  21. package/dist/managers/StorageEventManager/admission.d.ts +15 -3
  22. package/dist/managers/StorageEventManager/admission.js +13 -3
  23. package/dist/managers/StorageEventManager/processing.d.ts +2 -2
  24. package/dist/managers/StorageEventManager/processing.js +3 -3
  25. package/dist/managers/StorageEventManager/queue.d.ts +23 -14
  26. package/dist/managers/StorageEventManager/queue.js +70 -30
  27. package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
  28. package/dist/managers/StorageEventManager/snapshot.js +74 -0
  29. package/dist/managers/StorageEventManager/state.d.ts +27 -5
  30. package/dist/managers/StorageEventManager/state.js +9 -7
  31. package/dist/managers/StorageEventManager.d.ts +6 -0
  32. package/dist/managers/StorageEventManager.js +135 -18
  33. package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
  34. package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
  35. package/dist/managers/adapters/index.d.ts +1 -1
  36. package/dist/pouchdb/LiveSyncLocalDB.js +3 -4
  37. package/dist/replication/index.d.ts +2 -0
  38. package/dist/replication/index.js +2 -0
  39. package/dist/replication/replicationResultQueueStore.d.ts +101 -0
  40. package/dist/replication/replicationResultQueueStore.js +140 -0
  41. package/dist/serviceFeatures/offlineScanner/files.js +15 -3
  42. package/dist/serviceFeatures/offlineScanner/scan.js +1 -4
  43. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +5 -4
  44. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +28 -7
  45. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +8 -2
  46. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +52 -9
  47. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +30 -0
  48. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +82 -10
  49. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +118 -12
  50. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +32 -8
  51. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +2 -8
  52. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +4 -5
  53. package/dist/services/base/KeyValueDBService.d.ts +6 -6
  54. package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
  55. package/dist/worker/WorkerPushStreamProducer.js +299 -0
  56. package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
  57. package/dist/worker/WorkerPushStreamReader.js +179 -0
  58. package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
  59. package/dist/worker/backgroundWorkerRpcContract.js +24 -0
  60. package/dist/worker/bg.worker.js +2 -16
  61. package/dist/worker/bg.worker.splitting.d.ts +3 -7
  62. package/dist/worker/bg.worker.splitting.js +46 -47
  63. package/dist/worker/bgWorker.d.ts +8 -14
  64. package/dist/worker/bgWorker.direct.d.ts +5 -28
  65. package/dist/worker/bgWorker.direct.js +32 -2
  66. package/dist/worker/bgWorker.errors.d.ts +1 -0
  67. package/dist/worker/bgWorker.errors.js +12 -0
  68. package/dist/worker/bgWorker.js +716 -296
  69. package/dist/worker/bgWorker.splitting.d.ts +12 -26
  70. package/dist/worker/bgWorker.splitting.js +115 -107
  71. package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
  72. package/dist/worker/outOfBandCancelIterator.js +8 -0
  73. package/dist/worker/serveBackgroundWorker.d.ts +3 -0
  74. package/dist/worker/serveBackgroundWorker.js +35 -0
  75. package/dist/worker/splitConnectionTracker.d.ts +25 -0
  76. package/dist/worker/splitConnectionTracker.js +73 -0
  77. package/dist/worker/splitGate.d.ts +19 -0
  78. package/dist/worker/splitGate.js +71 -0
  79. package/dist/worker/universalTypes.d.ts +0 -30
  80. package/dist/worker/universalTypes.js +0 -4
  81. package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
  82. package/dist/worker/workerPushStreamProtocol.js +143 -0
  83. package/docs/conflict-resolution.md +22 -8
  84. package/docs/development.md +6 -0
  85. package/docs/offline-scanner.md +2 -0
  86. package/docs/storage-events-and-reflection.md +171 -2
  87. package/package.json +1 -1
  88. package/dist/worker/bg.common.d.ts +0 -2
  89. package/dist/worker/bg.common.js +0 -6
  90. package/dist/worker/bg.worker.encryption.d.ts +0 -7
  91. package/dist/worker/bg.worker.encryption.js +0 -30
  92. package/dist/worker/bgWorker.encryption.d.ts +0 -22
  93. package/dist/worker/bgWorker.encryption.js +0 -40
@@ -6,22 +6,31 @@ import {
6
6
  isReflectionCancelled
7
7
  } from "../../interfaces/FileHandler.js";
8
8
  import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
9
- import { infoToStub, isFolderInfo, getParentPath } from "./storage.js";
9
+ import { infoToStub, isFileAtExactPath, isFolderInfo } from "./storage.js";
10
10
  import {
11
+ captureRenameProvenance,
12
+ commitRenamedProvenance,
11
13
  deleteProvenance,
14
+ getProvenancePath,
12
15
  contentEvidence,
13
16
  currentStorageSnapshotMatches,
14
17
  sameProvenance,
15
18
  readProvenanceSnapshot,
16
19
  setProvenance
17
20
  } from "./provenance.js";
18
- import { preserveUnsyncedStorageAsConflict, recheckIncomingStorage } from "./protection.js";
21
+ import { preserveUnsyncedStorageAsConflict, preserveUnobservedFilename, recheckIncomingStorage } from "./protection.js";
19
22
  import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
20
- import { createBlob, isDocContentSame, readContent } from "../../common/utils.js";
23
+ import { createBlob, isDeletedEntry, isDocContentSame, readContent } from "../../common/utils.js";
21
24
  import { getStoragePathFromUXFileInfo } from "../../common/typeUtils.js";
22
25
  import { EVEN } from "../../common/models/shared.const.symbols.js";
23
26
  import { tryGetFilePath } from "../../common/utils.doc.js";
24
27
  import { getPathNormalizationVersion, normalisePathForIdentity } from "../../common/pathNormalization.js";
28
+ import {
29
+ getParentPath,
30
+ hasFilenameCaseConflict,
31
+ hasSameParentFilenameCaseConflict,
32
+ haveMatchingRevisionPaths
33
+ } from "../../conflicts/filenameCaseConflict.js";
25
34
  class IncompleteFileReflectionError extends Error {
26
35
  }
27
36
  async function dbToStorageWithSpecificRev(ctx, info, rev, force) {
@@ -67,7 +76,8 @@ async function dbToStorageWithSpecificRevCore(ctx, info, rev, force) {
67
76
  );
68
77
  return false;
69
78
  }
70
- return !isReflectionCancelled(await applyDatabaseEntryToStorage(ctx, docEntry, file, force, true));
79
+ const entry = await withStoredFilename(ctx, docEntry);
80
+ return !isReflectionCancelled(await applyDatabaseEntryToStorage(ctx, entry, file, force, true));
71
81
  }
72
82
  async function dbToStorage(ctx, entryInfo, info, force) {
73
83
  const path = typeof entryInfo === "string" ? entryInfo : ctx.host.getPath(entryInfo);
@@ -102,7 +112,23 @@ async function dbToStorageCore(ctx, entryInfo, info, force, operation) {
102
112
  ctx.host.log(`File ${pathFromEntryInfo} is not exist on the database`, LOG_LEVEL_VERBOSE);
103
113
  throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
104
114
  }
105
- return await applyDatabaseEntryToStorage(ctx, docEntry, file, force, false, 0, operation);
115
+ const entry = force ? docEntry : await withStoredFilename(ctx, docEntry);
116
+ return await applyDatabaseEntryToStorage(ctx, entry, file, force, false, 0, operation);
117
+ }
118
+ async function withStoredFilename(ctx, entry) {
119
+ const settings = ctx.setting.currentSettings();
120
+ if (settings.handleFilenameCaseSensitive || !entry._rev || isDeletedEntry(entry)) {
121
+ return entry;
122
+ }
123
+ const stored = await ctx.host.db().readRevisionPath?.(entry._id, entry._rev);
124
+ if (stored && hasSameParentFilenameCaseConflict(entry.path, stored, getPathNormalizationVersion(settings))) {
125
+ const target = await ctx.host.db().readEntryMeta(stored, entry._rev, true);
126
+ if (!target || target._id !== entry._id || target._rev !== entry._rev) {
127
+ throw new IncompleteFileReflectionError("Could not confirm the stored filename as a reflection target");
128
+ }
129
+ return target;
130
+ }
131
+ return entry;
106
132
  }
107
133
  async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExistingConflicts = false, incomingRetry = 0, operation) {
108
134
  const mode = file == null ? "create" : "modify";
@@ -116,12 +142,19 @@ async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExis
116
142
  return FILE_REFLECTION_POLICY;
117
143
  }
118
144
  }
145
+ const existOnDB = !isDeletedEntry(docEntry);
119
146
  let existDoc = await ctx.host.storage().getStub(path);
147
+ if (existOnDB && !force && !settings.handleFilenameCaseSensitive && file && file.path !== existDoc?.path && hasSameParentFilenameCaseConflict(file.path, path, getPathNormalizationVersion(settings))) {
148
+ const observed = await ctx.host.storage().getStub(file.path);
149
+ if (existDoc && observed && existDoc.path !== observed.path) {
150
+ throw new IncompleteFileReflectionError("Both filename spellings exist in storage");
151
+ }
152
+ existDoc ??= observed;
153
+ }
120
154
  if (isFolderInfo(existDoc)) {
121
155
  ctx.host.log(`Folder ${path} is already exist on the storage as a folder`, LOG_LEVEL_VERBOSE);
122
156
  return FILE_REFLECTION_POLICY;
123
157
  }
124
- const existOnDB = !(docEntry._deleted || docEntry.deleted || false);
125
158
  if (!existOnDB && !existDoc) {
126
159
  ctx.host.log(`File ${path} seems to be deleted, but already not on storage`, LOG_LEVEL_VERBOSE);
127
160
  await deleteProvenance(ctx, path);
@@ -141,10 +174,13 @@ async function applyDatabaseEntryToStorage(ctx, docEntry, file, force, allowExis
141
174
  );
142
175
  }
143
176
  if (existDoc && existDoc.path !== path) {
144
- const current = await reconcileStoragePath(ctx, existDoc, path, settings);
177
+ const current = await reconcileStoragePath(ctx, existDoc, path, settings, docEntry, force);
145
178
  if (current === false) {
146
179
  throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
147
180
  }
181
+ if ("status" in current) {
182
+ return current;
183
+ }
148
184
  existDoc = current;
149
185
  }
150
186
  const docRead = await ctx.host.db().readEntryFromMeta(docEntry);
@@ -200,7 +236,7 @@ async function reconcileAdvancedIncomingRevision(ctx, incomingEntry, path, force
200
236
  }
201
237
  return await applyDatabaseEntryToStorage(
202
238
  ctx,
203
- current,
239
+ await withStoredFilename(ctx, current),
204
240
  storage,
205
241
  force,
206
242
  allowExistingConflicts,
@@ -209,6 +245,19 @@ async function reconcileAdvancedIncomingRevision(ctx, incomingEntry, path, force
209
245
  );
210
246
  }
211
247
  async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, force, allowExistingConflicts, incomingRetry, operation) {
248
+ if (existDoc.path !== path) {
249
+ const [existingDocumentId, targetDocumentId] = await Promise.all([
250
+ ctx.path.path2id(existDoc.path),
251
+ ctx.path.path2id(path)
252
+ ]);
253
+ if (existingDocumentId !== targetDocumentId) {
254
+ ctx.host.log(
255
+ `Refusing to delete ${existDoc.path} while applying deletion for the distinct path ${path}`,
256
+ LOG_LEVEL_NOTICE
257
+ );
258
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
259
+ }
260
+ }
212
261
  let safeDeletionSnapshot;
213
262
  if (!force && !settings.writeDocumentsIfConflicted) {
214
263
  let protection = await preserveUnsyncedStorageAsConflict(ctx, path, existDoc, docEntry, void 0);
@@ -259,14 +308,40 @@ async function applyIncomingDeletion(ctx, docEntry, existDoc, path, settings, fo
259
308
  throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
260
309
  }
261
310
  }
311
+ const observedPath = safeDeletionSnapshot?.file.path ?? existDoc.path;
312
+ if (observedPath !== path) {
313
+ if (safeDeletionSnapshot) {
314
+ if (!sameProvenance(await readProvenanceSnapshot(ctx, observedPath), safeDeletionSnapshot.revision)) {
315
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
316
+ }
317
+ const resolvedForRead = await ctx.host.storage().getStub(path);
318
+ if (!isFileAtExactPath(resolvedForRead, observedPath)) {
319
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
320
+ }
321
+ const readResolved = await ctx.host.readFileFromStub(resolvedForRead);
322
+ if (readResolved.path !== observedPath || readResolved.stat.mtime !== safeDeletionSnapshot.file.stat.mtime || readResolved.stat.size !== safeDeletionSnapshot.file.stat.size || !await isDocContentSame(readResolved.body, safeDeletionSnapshot.file.body)) {
323
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
324
+ }
325
+ }
326
+ const resolvedTarget = await ctx.host.storage().getStub(path);
327
+ if (!isFileAtExactPath(resolvedTarget, observedPath) || safeDeletionSnapshot && (resolvedTarget.stat.mtime !== safeDeletionSnapshot.file.stat.mtime || resolvedTarget.stat.size !== safeDeletionSnapshot.file.stat.size)) {
328
+ throw new IncompleteFileReflectionError("Reflection could not establish a safe current result");
329
+ }
330
+ }
262
331
  if (operation?.checkpoint?.() === false) {
263
332
  return FILE_REFLECTION_CANCELLED;
264
333
  }
265
334
  await ctx.host.storage().deleteVaultItem(path);
266
- await deleteProvenance(ctx, path);
335
+ const clearedKeys = /* @__PURE__ */ new Set();
336
+ for (const candidate of [observedPath, existDoc.path, path]) {
337
+ const key = getProvenancePath(ctx, candidate);
338
+ if (clearedKeys.has(key)) continue;
339
+ clearedKeys.add(key);
340
+ await deleteProvenance(ctx, candidate);
341
+ }
267
342
  return FILE_REFLECTION_COMPLETED;
268
343
  }
269
- async function reconcileStoragePath(ctx, existDoc, path, settings) {
344
+ async function reconcileStoragePath(ctx, existDoc, path, settings, incoming, force) {
270
345
  const [existingDocumentId, targetDocumentId] = await Promise.all([
271
346
  ctx.path.path2id(existDoc.path),
272
347
  ctx.path.path2id(path)
@@ -291,12 +366,43 @@ async function reconcileStoragePath(ctx, existDoc, path, settings) {
291
366
  );
292
367
  return false;
293
368
  }
369
+ const oldPath = existDoc.path;
370
+ const shouldVerifyLocalSpellingBeforeRename = !force && !settings.writeDocumentsIfConflicted && !settings.handleFilenameCaseSensitive && hasFilenameCaseConflict(oldPath, path, pathNormalizationVersion);
371
+ let recorded;
372
+ if (shouldVerifyLocalSpellingBeforeRename) {
373
+ recorded = await readProvenanceSnapshot(ctx, oldPath, true);
374
+ const recordedName = recorded && await ctx.host.db().readRevisionPath?.(incoming._id, recorded.revision);
375
+ if (!haveMatchingRevisionPaths(oldPath, recordedName, pathNormalizationVersion)) {
376
+ const protection = await preserveUnobservedFilename(ctx, path, existDoc, recorded);
377
+ return protection.preserved ? FILE_REFLECTION_POLICY : false;
378
+ }
379
+ }
380
+ const renameProvenance = await captureRenameProvenance(ctx, oldPath, path);
381
+ if (renameProvenance === false) {
382
+ return false;
383
+ }
384
+ if (recorded) {
385
+ const current = await ctx.host.storage().getStub(oldPath);
386
+ if (!isFileAtExactPath(current, oldPath) || !sameProvenance(renameProvenance?.sourceRecord, recorded)) {
387
+ return false;
388
+ }
389
+ existDoc = current;
390
+ }
294
391
  const renamedFile = await ctx.host.storage().renameFile(existDoc, path);
295
392
  if (!renamedFile) {
296
- ctx.host.log(`Could not apply the stored filename case: ${existDoc.path} -> ${path}`, LOG_LEVEL_NOTICE);
393
+ ctx.host.log(`Could not apply the stored filename case: ${oldPath} -> ${path}`, LOG_LEVEL_NOTICE);
394
+ return false;
395
+ }
396
+ if (getProvenancePath(ctx, renamedFile.path) !== getProvenancePath(ctx, path)) {
397
+ ctx.host.log(
398
+ `Could not align renamed filename identity: ${oldPath} -> ${renamedFile.path} (expected ${path})`,
399
+ LOG_LEVEL_NOTICE
400
+ );
401
+ return false;
402
+ }
403
+ if (renameProvenance && !await commitRenamedProvenance(ctx, renameProvenance, renamedFile.path)) {
297
404
  return false;
298
405
  }
299
- await deleteProvenance(ctx, existDoc.path);
300
406
  existDoc = renamedFile;
301
407
  }
302
408
  return existDoc;
@@ -1,6 +1,8 @@
1
1
  import { isReflectionCancelled } from "../../interfaces/FileHandler.js";
2
2
  import { ContentReadError } from "../../common/LSError.js";
3
3
  import { isFolderInfo, infoToStub } from "./storage.js";
4
+ import { getPathNormalizationVersion } from "../../common/pathNormalization.js";
5
+ import { hasSameParentFilenameCaseConflict, haveMatchingRevisionPaths } from "../../conflicts/filenameCaseConflict.js";
4
6
  import { withFileEventPaths, queueConflictCheckFor } from "./locking.js";
5
7
  import {
6
8
  setProvenance,
@@ -19,7 +21,7 @@ import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/log
19
21
  import { displayRev, getDocDataAsArray, isDocContentSame, readContent } from "../../common/utils.js";
20
22
  import { getStoragePathFromUXFileInfo } from "../../common/typeUtils.js";
21
23
  import { EVEN } from "../../common/models/shared.const.symbols.js";
22
- import { tryGetFilePath } from "../../common/utils.doc.js";
24
+ import { isDeletedEntry, tryGetFilePath } from "../../common/utils.doc.js";
23
25
  async function retryCurrentStorage(ctx, path, preferredBasePath, snapshotRetry) {
24
26
  if (snapshotRetry >= 2) {
25
27
  ctx.host.log(`Storage kept changing while saving ${path}; a fresh event is required`, LOG_LEVEL_NOTICE);
@@ -73,7 +75,7 @@ async function storeFileToDBWithBaseRevisionCore(ctx, info, baseRevision, create
73
75
  return false;
74
76
  }
75
77
  const readFile = await ctx.host.readFileFromStub(file);
76
- if (!baseEntry.deleted && !baseEntry._deleted) {
78
+ if (!isDeletedEntry(baseEntry)) {
77
79
  const loadedBase = await ctx.host.db().fetchEntry(file, baseRevision, true, true);
78
80
  if (loadedBase && await isDocContentSame(getDocDataAsArray(loadedBase.data), readFile.body)) {
79
81
  await setProvenance(ctx, file.path, baseRevision, readFile.stat.mtime, readFile.body);
@@ -115,12 +117,12 @@ async function storeFileToDBFromRevision(ctx, info, force = false, onlyChunks =
115
117
  }
116
118
  const save = await observeStorageSave(ctx, file, preferredBasePath, retryIfStorageChanges);
117
119
  const currentEntry = save.currentEntry;
118
- const currentIsLive = currentEntry && !currentEntry.deleted && !currentEntry._deleted;
120
+ const currentIsLive = currentEntry && !isDeletedEntry(currentEntry);
119
121
  if (!force && (currentIsLive || retryIfStorageChanges)) {
120
122
  return await saveClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges, snapshotRetry);
121
123
  }
122
124
  if (save.isConflicted) return await saveConflictedStorage(ctx, save, force, preferredBasePath);
123
- if (!currentEntry || currentEntry.deleted || currentEntry._deleted)
125
+ if (!currentEntry || isDeletedEntry(currentEntry))
124
126
  return await createStorageRevision(ctx, save, preferredBasePath);
125
127
  return await saveCurrentStorage(ctx, save, currentEntry, force, onlyChunks, preferredBasePath);
126
128
  }
@@ -139,7 +141,7 @@ async function observeStorageSave(ctx, file, preferredBasePath, retryIfStorageCh
139
141
  }
140
142
  async function saveClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges, snapshotRetry) {
141
143
  const { entry, currentEntry } = save;
142
- const currentIsLive = currentEntry && !currentEntry.deleted && !currentEntry._deleted;
144
+ const currentIsLive = currentEntry && !isDeletedEntry(currentEntry);
143
145
  if (retryIfStorageChanges && currentIsLive && !entry) {
144
146
  const revision = currentEntry._rev ? displayRev(currentEntry._rev) : "unknown";
145
147
  ctx.host.log(
@@ -251,12 +253,13 @@ async function saveCurrentStorage(ctx, save, currentEntry, force, onlyChunks, pr
251
253
  }
252
254
  async function observeClassifiedStorage(ctx, save, preferredBasePath, retryIfStorageChanges) {
253
255
  const { readFile, observedProvenance, entry, currentEntry } = save;
256
+ const recorded = preferredBasePath ? observedProvenance : await selectProvenanceForStorageFilename(ctx, save);
254
257
  const classification = await classifyStorageContent(
255
258
  ctx,
256
259
  readFile,
257
260
  currentEntry,
258
261
  preferredBasePath,
259
- observedProvenance,
262
+ recorded,
260
263
  entry ? { _rev: entry._rev, data: readContent(entry) } : void 0,
261
264
  retryIfStorageChanges
262
265
  );
@@ -264,9 +267,30 @@ async function observeClassifiedStorage(ctx, save, preferredBasePath, retryIfSto
264
267
  const evidence = upgradeCurrentRecord || classification.kind === "matching-leaf" && classification.revision ? await contentEvidence(ctx, readFile.body) : void 0;
265
268
  return { classification, upgradeCurrentRecord, evidence };
266
269
  }
270
+ function hasLiveRevision(entry) {
271
+ return !!entry && !!entry._rev && !isDeletedEntry(entry);
272
+ }
273
+ async function selectProvenanceForStorageFilename(ctx, save) {
274
+ const { readFile, observedProvenance, currentEntry } = save;
275
+ const settings = ctx.setting.currentSettings();
276
+ const db = ctx.host.db();
277
+ if (!observedProvenance || !hasLiveRevision(currentEntry)) {
278
+ return observedProvenance;
279
+ }
280
+ if (settings.handleFilenameCaseSensitive || !db.readRevisionPath) {
281
+ return observedProvenance;
282
+ }
283
+ const currentName = await db.readRevisionPath(currentEntry._id, currentEntry._rev);
284
+ const version = getPathNormalizationVersion(settings);
285
+ if (!currentName || !hasSameParentFilenameCaseConflict(readFile.path, currentName, version)) {
286
+ return observedProvenance;
287
+ }
288
+ const recordedName = observedProvenance.revision === currentEntry._rev ? currentName : await db.readRevisionPath(currentEntry._id, observedProvenance.revision);
289
+ return haveMatchingRevisionPaths(readFile.path, recordedName, version) ? observedProvenance : void 0;
290
+ }
267
291
  function shouldUpgradeSavedRecord(save, classification) {
268
292
  const { currentEntry, isConflicted, observedProvenance } = save;
269
- return classification.kind === "unchanged" && !isConflicted && currentEntry && !currentEntry.deleted && !currentEntry._deleted && classification.revision === currentEntry._rev && !hasContentHash(observedProvenance);
293
+ return classification.kind === "unchanged" && !isConflicted && currentEntry && !isDeletedEntry(currentEntry) && classification.revision === currentEntry._rev && !hasContentHash(observedProvenance);
270
294
  }
271
295
  async function finishUnchangedStorageSave(ctx, save, revision, details, recovery) {
272
296
  const { file, readFile, observedProvenance, currentEntry, isConflicted } = save;
@@ -277,7 +301,7 @@ async function finishUnchangedStorageSave(ctx, save, revision, details, recovery
277
301
  return await retryCurrentStorage(ctx, file.path, preferredBasePath, snapshotRetry);
278
302
  if (isConflicted) {
279
303
  await queueConflictCheckFor(ctx, file.path);
280
- } else if (!currentEntry || currentEntry.deleted || currentEntry._deleted || revision !== currentEntry._rev) {
304
+ } else if (!currentEntry || isDeletedEntry(currentEntry) || revision !== currentEntry._rev) {
281
305
  if (!currentEntry) return false;
282
306
  return !isReflectionCancelled(await dbToStorageCore(ctx, file.path, file));
283
307
  } else {
@@ -37,14 +37,6 @@ export declare function readStorageFile(ctx: FileHandlerContext, file: UXFileInf
37
37
  * @remarks This helper acquires no document lock. Storage and path access retain the dynamic public host seams where the original operation used them.
38
38
  */
39
39
  export declare function infoToStub<T extends UXFileInfoStub | UXFileInfo | UXInternalFileInfoStub>(ctx: FileHandlerContext, info: null | T | FilePathWithPrefix | FilePath): Promise<T | UXFileInfoStub | null>;
40
- /**
41
- * Extract a parent directory using storage path separators.
42
- *
43
- * @param path - The affected file or provenance path.
44
- * @returns The parent path, or the empty root path.
45
- * @remarks This helper acquires no document lock. Storage and path access retain the dynamic public host seams where the original operation used them.
46
- */
47
- export declare function getParentPath(path: string): string;
48
40
  /**
49
41
  * Narrow a nullable storage observation to a folder.
50
42
  *
@@ -53,3 +45,5 @@ export declare function getParentPath(path: string): string;
53
45
  * @remarks This helper acquires no document lock. Storage and path access retain the dynamic public host seams where the original operation used them.
54
46
  */
55
47
  export declare function isFolderInfo(info: UXFileInfoStub | UXFolderInfo | null): info is UXFolderInfo;
48
+ /** Check whether the observed storage item is a file with this exact path spelling. */
49
+ export declare function isFileAtExactPath(info: UXFileInfoStub | UXFolderInfo | null, path: FilePathWithPrefix): info is UXFileInfoStub;
@@ -20,18 +20,17 @@ async function infoToStub(ctx, info) {
20
20
  const file = typeof info === "string" ? await ctx.host.storage().getFileStub(info) : info;
21
21
  return file;
22
22
  }
23
- function getParentPath(path) {
24
- const lastSeparator = path.lastIndexOf("/");
25
- return lastSeparator < 0 ? "" : path.slice(0, lastSeparator);
26
- }
27
23
  function isFolderInfo(info) {
28
24
  return info?.isFolder === true;
29
25
  }
26
+ function isFileAtExactPath(info, path) {
27
+ return !!info && !isFolderInfo(info) && info.path === path;
28
+ }
30
29
  export {
31
30
  getFileEntryPath,
32
31
  getFileStoragePath,
33
- getParentPath,
34
32
  infoToStub,
33
+ isFileAtExactPath,
35
34
  isFolderInfo,
36
35
  readStorageFile
37
36
  };
@@ -4,8 +4,8 @@ import { ServiceBase, type ServiceContext } from "./ServiceBase.js";
4
4
  import type { KeyValueDatabase, KeyValueDatabaseFactory } from "../../interfaces/KeyValueDatabase.js";
5
5
  import type { InjectableDatabaseEventService } from "../implements/injectable/InjectableDatabaseEventService.js";
6
6
  import type { AppLifecycleServiceBase } from "../implements/injectable/InjectableAppLifecycleService.js";
7
- export interface KeyValueDBDependencies<T extends ServiceContext = ServiceContext> {
8
- openKeyValueDatabase: KeyValueDatabaseFactory;
7
+ export interface KeyValueDBDependencies<T extends ServiceContext = ServiceContext, TDatabase extends KeyValueDatabase = KeyValueDatabase> {
8
+ openKeyValueDatabase: KeyValueDatabaseFactory<TDatabase>;
9
9
  databaseEvents: InjectableDatabaseEventService<T>;
10
10
  vault: IVaultService;
11
11
  appLifecycle: AppLifecycleServiceBase<T>;
@@ -15,13 +15,13 @@ export interface KeyValueDBDependencies<T extends ServiceContext = ServiceContex
15
15
  * The KeyValueDBService provides methods for managing the local key-value database.
16
16
  * Please note that each event of database lifecycle is handled in DatabaseEventService.
17
17
  */
18
- export declare abstract class KeyValueDBService<T extends ServiceContext = ServiceContext> extends ServiceBase<T> implements IKeyValueDBService {
18
+ export declare abstract class KeyValueDBService<T extends ServiceContext = ServiceContext, TDatabase extends KeyValueDatabase = KeyValueDatabase> extends ServiceBase<T> implements IKeyValueDBService {
19
19
  private _kvDB;
20
20
  private databaseKey;
21
21
  private readonly lifecycleLock;
22
22
  private _simpleStore;
23
23
  get simpleStore(): SimpleStore<unknown, any>;
24
- get kvDB(): KeyValueDatabase;
24
+ get kvDB(): TDatabase;
25
25
  private databaseEvents;
26
26
  private vault;
27
27
  private appLifecycle;
@@ -33,7 +33,7 @@ export declare abstract class KeyValueDBService<T extends ServiceContext = Servi
33
33
  private openSelectedDatabase;
34
34
  private openKeyValueDB;
35
35
  private _everyOnloadAfterLoadSettings;
36
- constructor(context: T, dependencies: KeyValueDBDependencies<T>);
36
+ constructor(context: T, dependencies: KeyValueDBDependencies<T, TDatabase>);
37
37
  /**
38
38
  * Create an inert namespaced handle over the service's current database.
39
39
  * @param kind - Namespace identifier; stored keys receive this identifier and a trailing hyphen.
@@ -48,6 +48,6 @@ export declare abstract class KeyValueDBService<T extends ServiceContext = Servi
48
48
  set: (key: string, value: unknown) => Promise<void>;
49
49
  delete: (key: string) => Promise<void>;
50
50
  keys: (from: string | undefined, to: string | undefined, count?: number) => Promise<string[]>;
51
- readonly db: Promise<KeyValueDatabase>;
51
+ readonly db: Promise<Awaited<TDatabase>>;
52
52
  };
53
53
  }
@@ -0,0 +1,45 @@
1
+ import { type ServeOptions } from "./workerPushStreamProtocol.js";
2
+ export declare class WorkerPushStreamProducer<T> {
3
+ private readonly options;
4
+ readonly readerPort: MessagePort;
5
+ private readonly producerPort;
6
+ private readonly controller;
7
+ private readonly batchTargetBytes;
8
+ private readonly maxBatchItems;
9
+ private readonly signal;
10
+ private source;
11
+ private finished;
12
+ private pumping;
13
+ private initialGrant;
14
+ private inFlightBytes;
15
+ private oversizedInFlight;
16
+ private batch;
17
+ private batchCharge;
18
+ private stagedItem;
19
+ private flushTimer;
20
+ private yieldChannel;
21
+ private yieldAfterBatch;
22
+ private resolveYield;
23
+ private readonly claimTimer;
24
+ constructor(options: ServeOptions<T>);
25
+ private post;
26
+ /** Unblock the pump and close both ends of its scheduling channel. */
27
+ private clearYield;
28
+ /** Let pending port events run between batches without relying on a timer. */
29
+ private scheduleYield;
30
+ private finish;
31
+ private postBatch;
32
+ private flushWhileReading;
33
+ /** Flush a full batch before admitting the staged item against the remaining credit. */
34
+ private admitStagedItem;
35
+ /** Flush an accumulated batch if the source takes another task to produce an item. */
36
+ private readNextItem;
37
+ private pump;
38
+ private applyCancel;
39
+ private applyCredit;
40
+ private onMessage;
41
+ private onMessageError;
42
+ private onClose;
43
+ private onAbort;
44
+ }
45
+ export declare function serveWorkerPushStream<T>(options: ServeOptions<T>): import("@vrtmrz/rpc").WithTransfer<MessagePort, MessagePort>;