loro-repo 0.24.0 → 0.25.0

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/dist/index.cjs +65 -289
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.js +21 -245
  4. package/dist/index.js.map +1 -1
  5. package/dist/meta-snapshot.cjs.map +1 -1
  6. package/dist/meta-snapshot.js.map +1 -1
  7. package/dist/storage/indexeddb.cjs +76 -25
  8. package/dist/storage/indexeddb.cjs.map +1 -1
  9. package/dist/storage/indexeddb.d.cts +39 -5
  10. package/dist/storage/indexeddb.d.ts +39 -5
  11. package/dist/storage/indexeddb.js +76 -25
  12. package/dist/storage/indexeddb.js.map +1 -1
  13. package/dist/storage/sqlite.cjs +36 -19
  14. package/dist/storage/sqlite.cjs.map +1 -1
  15. package/dist/storage/sqlite.d.cts +23 -1
  16. package/dist/storage/sqlite.d.ts +23 -1
  17. package/dist/storage/sqlite.js +37 -20
  18. package/dist/storage/sqlite.js.map +1 -1
  19. package/dist/streams.d.cts +54 -3
  20. package/dist/streams.d.ts +54 -3
  21. package/dist/transport/streams.cjs +159 -26
  22. package/dist/transport/streams.cjs.map +1 -1
  23. package/dist/transport/streams.js +157 -24
  24. package/dist/transport/streams.js.map +1 -1
  25. package/dist/types.d.cts +10 -5
  26. package/dist/types.d.ts +10 -5
  27. package/dist/utils.cjs +446 -0
  28. package/dist/utils.cjs.map +1 -0
  29. package/dist/utils.js +375 -0
  30. package/dist/utils.js.map +1 -0
  31. package/dist/write-failure.cjs +47 -0
  32. package/dist/write-failure.cjs.map +1 -0
  33. package/dist/write-failure.js +42 -0
  34. package/dist/write-failure.js.map +1 -0
  35. package/package.json +1 -1
  36. package/dist/flock-persistence-journal.cjs +0 -170
  37. package/dist/flock-persistence-journal.cjs.map +0 -1
  38. package/dist/flock-persistence-journal.js +0 -159
  39. package/dist/flock-persistence-journal.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,141 +1,15 @@
1
1
  const require_chunk = require('./chunk.cjs');
2
2
  const require_replica_checkpoints = require('./replica-checkpoints.cjs');
3
3
  const require_meta_snapshot = require('./meta-snapshot.cjs');
4
+ const require_utils = require('./utils.cjs');
4
5
  const require_doc_updates = require('./doc-updates.cjs');
5
6
  const require_logging = require('./logging.cjs');
6
7
  const require_flock_snapshot = require('./flock-snapshot.cjs');
7
- const require_flock_persistence_journal = require('./flock-persistence-journal.cjs');
8
8
  let __loro_dev_flock_wasm = require("@loro-dev/flock-wasm");
9
9
  __loro_dev_flock_wasm = require_chunk.__toESM(__loro_dev_flock_wasm);
10
10
  let loro_crdt = require("loro-crdt");
11
11
  loro_crdt = require_chunk.__toESM(loro_crdt);
12
12
 
13
- //#region src/internal/resource-ownership.ts
14
- var ResourceOwnership = class {
15
- owners = /* @__PURE__ */ new Map();
16
- generations = /* @__PURE__ */ new Map();
17
- /**
18
- * Ids currently being evicted, with a count of overlapping evictions. New
19
- * leases are refused while an id is here, which closes the window between a
20
- * purge's pre-flight check and its destructive steps: `forgetFlockDoc`
21
- * deletes the durable remote cursor before the final check runs, so a lease
22
- * taken in between would fail the purge only *after* that cursor was
23
- * already gone. Counted rather than a set so one purge finishing cannot
24
- * drop the fence a concurrent purge of the same id still relies on.
25
- */
26
- evicting = /* @__PURE__ */ new Map();
27
- /** Current generation for `id`. Ids never dropped are generation 0. */
28
- generation(id) {
29
- return this.generations.get(id) ?? 0;
30
- }
31
- /** Total live owners of `id`, in both roles. */
32
- ownerCount(id) {
33
- return this.owners.get(id)?.size ?? 0;
34
- }
35
- /**
36
- * Registers one owner of `id` and returns its release callback. The token
37
- * is per-acquisition, so releasing twice only decrements once and one
38
- * owner's release cannot cancel another's.
39
- */
40
- acquire(id, role, label) {
41
- if (role === "lease" && this.evicting.has(id)) throw new ResourceBusyError("resource", id, ["eviction in progress"], `Cannot acquire resource "${id}": it is currently being evicted (unload or purge in progress). Retry after the eviction settles.`);
42
- const token = Symbol(label);
43
- let map = this.owners.get(id);
44
- if (!map) {
45
- map = /* @__PURE__ */ new Map();
46
- this.owners.set(id, map);
47
- }
48
- map.set(token, {
49
- role,
50
- label
51
- });
52
- let released = false;
53
- return () => {
54
- if (released) return;
55
- released = true;
56
- const current = this.owners.get(id);
57
- if (!current) return;
58
- current.delete(token);
59
- if (current.size === 0) this.owners.delete(id);
60
- };
61
- }
62
- /**
63
- * Labels of the owners that block eviction (explicit leases), for error
64
- * messages that need to tell a caller *why* an unload or purge was refused.
65
- * Live rooms are deliberately excluded: the repository detaches those
66
- * itself rather than failing the call.
67
- */
68
- blockingOwners(id) {
69
- const map = this.owners.get(id);
70
- if (!map) return [];
71
- return [...map.values()].filter((owner) => owner.role === "lease").map((owner) => owner.label);
72
- }
73
- /**
74
- * Invalidates the instance currently bound to `id`: bumps the generation so
75
- * holders of the previous one can tell that the replica they reference is
76
- * no longer the repository's current replica. Called when the instance
77
- * backing an id is dropped (unload, purge) — never on ordinary edits.
78
- */
79
- invalidate(id) {
80
- const next = this.generation(id) + 1;
81
- this.generations.set(id, next);
82
- return next;
83
- }
84
- /**
85
- * Marks `id` as being evicted, refusing new leases until the returned
86
- * callback runs. Call it in a `finally`.
87
- */
88
- beginEviction(id) {
89
- this.evicting.set(id, (this.evicting.get(id) ?? 0) + 1);
90
- let ended = false;
91
- return () => {
92
- if (ended) return;
93
- ended = true;
94
- const count = this.evicting.get(id);
95
- if (count === void 0) return;
96
- if (count <= 1) this.evicting.delete(id);
97
- else this.evicting.set(id, count - 1);
98
- };
99
- }
100
- clear() {
101
- this.owners.clear();
102
- this.generations.clear();
103
- this.evicting.clear();
104
- }
105
- };
106
- /**
107
- * Raised when an unload or purge would evict a replica that an explicit lease
108
- * still holds. Carrying the owner labels makes the failure actionable — the
109
- * usual cause is an `acquire*()` the caller forgot to `release()`.
110
- */
111
- var ResourceBusyError = class extends Error {
112
- resourceId;
113
- owners;
114
- constructor(kind, resourceId, owners, message) {
115
- super(message ?? `Cannot evict ${kind} "${resourceId}": ${owners.length} active lease(s) still hold it (${owners.join(", ")}). Release them first, or pass { force: true } to evict anyway and invalidate the replica.`);
116
- this.name = "ResourceBusyError";
117
- this.resourceId = resourceId;
118
- this.owners = owners;
119
- }
120
- };
121
- /**
122
- * Raised when a durability barrier is asked to persist a replica the
123
- * repository has already replaced.
124
- *
125
- * Surfacing this rather than returning quietly is what keeps a remote cursor
126
- * from advancing past state nothing wrote: the barrier fails, so the cursor
127
- * save fails with it.
128
- */
129
- var StaleReplicaError = class extends Error {
130
- resourceId;
131
- constructor(kind, resourceId) {
132
- super(`Cannot persist ${kind} "${resourceId}": the repository has replaced this replica, so the state held here is no longer the one it tracks.`);
133
- this.name = "StaleReplicaError";
134
- this.resourceId = resourceId;
135
- }
136
- };
137
-
138
- //#endregion
139
13
  //#region src/internal/flock-debounce.ts
140
14
  /**
141
15
  * Configure debounce on a Flock instance using built-in autoDebounceCommit.
@@ -243,7 +117,7 @@ var DocManager = class {
243
117
  * Shared with `SyncRunner`, which registers live rooms as `"room"` owners
244
118
  * so eviction can detach and rebind them instead of forking the replica.
245
119
  */
246
- ownership = new ResourceOwnership();
120
+ ownership = new require_utils.ResourceOwnership();
247
121
  storage;
248
122
  ensureDocExists;
249
123
  eventBus;
@@ -342,7 +216,7 @@ var DocManager = class {
342
216
  async persistDocChanges(docId, doc, options = {}) {
343
217
  await this.enqueueOperation(async () => {
344
218
  if (this.docs.get(docId) !== doc) {
345
- if (options.requireCurrent) throw new StaleReplicaError("document", docId);
219
+ if (options.requireCurrent) throw new require_utils.StaleReplicaError("document", docId);
346
220
  return;
347
221
  }
348
222
  await this.persistDocUpdate(docId, doc);
@@ -361,21 +235,25 @@ var DocManager = class {
361
235
  * old instance can tell it is stale. Callers holding an explicit lease
362
236
  * block the eviction unless `force` is set — that is what stops a reopen
363
237
  * from producing a second live replica behind a lease holder's back.
238
+ *
239
+ * Resolves with the evicted instance, or `undefined` when nothing was
240
+ * cached, so callers can stop whatever is still bound to exactly it.
364
241
  */
365
242
  async unloadDoc(docId, options = {}) {
366
- await this.enqueueOperation(async () => {
243
+ return await this.enqueueOperation(async () => {
367
244
  const doc = this.docs.get(docId);
368
- if (!doc) return;
245
+ if (!doc) return void 0;
369
246
  this.assertEvictable(docId, options.force);
370
247
  for (let attempt = 0; attempt < CAPTURE_MAX_ATTEMPTS; attempt++) {
371
248
  await this.persistDocUpdate(docId, doc);
372
249
  this.assertEvictable(docId, options.force);
373
250
  if (!this.dirtyDocs.has(docId)) break;
374
251
  }
375
- if (this.dirtyDocs.has(docId)) throw new ResourceBusyError("document", docId, ["writes during persistence"], `Cannot unload document "${docId}" after ${CAPTURE_MAX_ATTEMPTS} attempts: it kept changing during persistence`);
252
+ if (this.dirtyDocs.has(docId)) throw new require_utils.ResourceBusyError("document", docId, ["writes during persistence"], `Cannot unload document "${docId}" after ${CAPTURE_MAX_ATTEMPTS} attempts: it kept changing during persistence`);
376
253
  this.assertEvictable(docId, options.force);
377
254
  this.evict(docId);
378
255
  this.ownership.invalidate(docId);
256
+ return doc;
379
257
  });
380
258
  }
381
259
  async dropDoc(docId, options = {}) {
@@ -398,7 +276,7 @@ var DocManager = class {
398
276
  assertEvictable(docId, force) {
399
277
  if (force) return;
400
278
  const owners = this.ownership.blockingOwners(docId);
401
- if (owners.length > 0) throw new ResourceBusyError("document", docId, owners);
279
+ if (owners.length > 0) throw new require_utils.ResourceBusyError("document", docId, owners);
402
280
  }
403
281
  evict(docId) {
404
282
  this.docSubscriptions.get(docId)?.();
@@ -647,7 +525,7 @@ const DEFAULT_COMPACTION_BYTE_THRESHOLD = 100 * 1024;
647
525
  const nowMs = typeof globalThis.performance?.now === "function" ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
648
526
  var FlockDocManager = class {
649
527
  /** See `DocManager.ownership`. */
650
- ownership = new ResourceOwnership();
528
+ ownership = new require_utils.ResourceOwnership();
651
529
  storage;
652
530
  writer;
653
531
  ensureFlockDocExists;
@@ -656,7 +534,7 @@ var FlockDocManager = class {
656
534
  compactionByteThreshold;
657
535
  checkpoints = /* @__PURE__ */ new WeakMap();
658
536
  getCheckpointStore(flockDocId, flock) {
659
- if (this.destroyed || this.flocks.get(flockDocId) !== flock) throw new StaleReplicaError("Flock document", flockDocId);
537
+ if (this.destroyed || this.flocks.get(flockDocId) !== flock) throw new require_utils.StaleReplicaError("Flock document", flockDocId);
660
538
  return this.checkpoints.get(flock);
661
539
  }
662
540
  flocks = /* @__PURE__ */ new Map();
@@ -747,7 +625,7 @@ var FlockDocManager = class {
747
625
  const waiting = [];
748
626
  for (const request of requests) {
749
627
  if (this.flocks.get(request.flockDocId) !== request.flock) {
750
- if (request.requireCurrent) request.reject(new StaleReplicaError("Flock document", request.flockDocId));
628
+ if (request.requireCurrent) request.reject(new require_utils.StaleReplicaError("Flock document", request.flockDocId));
751
629
  else request.resolve();
752
630
  continue;
753
631
  }
@@ -785,9 +663,9 @@ var FlockDocManager = class {
785
663
  }
786
664
  }
787
665
  async unloadFlockDoc(flockDocId, options = {}) {
788
- await this.enqueueOperation(async () => {
666
+ return await this.enqueueOperation(async () => {
789
667
  const flock = this.flocks.get(flockDocId);
790
- if (!flock) return;
668
+ if (!flock) return void 0;
791
669
  this.assertEvictable(flockDocId, options.force);
792
670
  do
793
671
  await this.persistFlockDocUpdate(flockDocId, flock);
@@ -795,6 +673,7 @@ var FlockDocManager = class {
795
673
  this.assertEvictable(flockDocId, options.force);
796
674
  this.evict(flockDocId);
797
675
  this.ownership.invalidate(flockDocId);
676
+ return flock;
798
677
  });
799
678
  }
800
679
  async dropFlockDoc(flockDocId, options = {}) {
@@ -816,7 +695,7 @@ var FlockDocManager = class {
816
695
  assertEvictable(flockDocId, force) {
817
696
  if (force) return;
818
697
  const owners = this.ownership.blockingOwners(flockDocId);
819
- if (owners.length > 0) throw new ResourceBusyError("Flock document", flockDocId, owners);
698
+ if (owners.length > 0) throw new require_utils.ResourceBusyError("Flock document", flockDocId, owners);
820
699
  }
821
700
  evict(flockDocId) {
822
701
  this.journals.get(flockDocId)?.destroy();
@@ -890,7 +769,7 @@ var FlockDocManager = class {
890
769
  }
891
770
  ensureSubscription(flockDocId, flock) {
892
771
  if (this.journals.has(flockDocId)) return;
893
- this.journals.set(flockDocId, new require_flock_persistence_journal.FlockPersistenceJournal(flock, () => this.onFlockDocEvent(flockDocId)));
772
+ this.journals.set(flockDocId, new require_utils.FlockPersistenceJournal(flock, () => this.onFlockDocEvent(flockDocId)));
894
773
  }
895
774
  async persistFlockDocUpdate(flockDocId, flock, slot) {
896
775
  const journal = this.journals.get(flockDocId);
@@ -1055,96 +934,6 @@ var FlockDocManager = class {
1055
934
  }
1056
935
  };
1057
936
 
1058
- //#endregion
1059
- //#region src/utils.ts
1060
- /**
1061
- * Throws an AbortError if the signal is aborted.
1062
- * Use this to check for cancellation at safe points in long-running operations.
1063
- */
1064
- function throwIfAborted(signal) {
1065
- if (signal?.aborted) {
1066
- const error = /* @__PURE__ */ new Error("Operation was aborted");
1067
- error.name = "AbortError";
1068
- throw error;
1069
- }
1070
- }
1071
- function cloneJsonValue(value) {
1072
- if (value === null) return null;
1073
- if (typeof value === "string" || typeof value === "boolean") return value;
1074
- if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
1075
- if (Array.isArray(value)) {
1076
- const arr = [];
1077
- for (const entry of value) {
1078
- const cloned = cloneJsonValue(entry);
1079
- if (cloned !== void 0) arr.push(cloned);
1080
- }
1081
- return arr;
1082
- }
1083
- if (value && typeof value === "object") {
1084
- const input = value;
1085
- const obj = {};
1086
- for (const [key, entry] of Object.entries(input)) {
1087
- const cloned = cloneJsonValue(entry);
1088
- if (cloned !== void 0) obj[key] = cloned;
1089
- }
1090
- return obj;
1091
- }
1092
- }
1093
- function cloneJsonObject(value) {
1094
- const cloned = cloneJsonValue(value);
1095
- if (cloned && typeof cloned === "object" && !Array.isArray(cloned)) return cloned;
1096
- return {};
1097
- }
1098
- function asJsonObject(value) {
1099
- const cloned = cloneJsonValue(value);
1100
- if (cloned && typeof cloned === "object" && !Array.isArray(cloned)) return cloned;
1101
- }
1102
- function jsonEquals(a, b) {
1103
- if (a === b) return true;
1104
- if (a === void 0 || b === void 0) return false;
1105
- if (a === null || b === null) return a === b;
1106
- if (typeof a !== typeof b) return false;
1107
- if (typeof a !== "object") return a === b;
1108
- if (Array.isArray(a) !== Array.isArray(b)) return false;
1109
- if (Array.isArray(a)) {
1110
- const bArr = b;
1111
- if (a.length !== bArr.length) return false;
1112
- return a.every((v, i) => jsonEquals(v, bArr[i]));
1113
- }
1114
- const aObj = a;
1115
- const bObj = b;
1116
- const aKeys = Object.keys(aObj);
1117
- const bKeys = Object.keys(bObj);
1118
- if (aKeys.length !== bKeys.length) return false;
1119
- return aKeys.every((k) => jsonEquals(aObj[k], bObj[k]));
1120
- }
1121
- function diffJsonObjects(previous, next) {
1122
- const patch = {};
1123
- const keys = /* @__PURE__ */ new Set();
1124
- if (previous) for (const key of Object.keys(previous)) keys.add(key);
1125
- for (const key of Object.keys(next)) keys.add(key);
1126
- for (const key of keys) {
1127
- const prevValue = previous ? previous[key] : void 0;
1128
- const nextValue = next[key];
1129
- if (!jsonEquals(prevValue, nextValue)) {
1130
- if (nextValue === void 0 && previous && key in previous) {
1131
- patch[key] = null;
1132
- continue;
1133
- }
1134
- const cloned = cloneJsonValue(nextValue);
1135
- if (cloned !== void 0) patch[key] = cloned;
1136
- }
1137
- }
1138
- return patch;
1139
- }
1140
- function matchesQuery(docId, _metadata, query) {
1141
- if (!query) return true;
1142
- if (query.prefix && !docId.startsWith(query.prefix)) return false;
1143
- if (query.start && docId < query.start) return false;
1144
- if (query.end && docId > query.end) return false;
1145
- return true;
1146
- }
1147
-
1148
937
  //#endregion
1149
938
  //#region src/internal/lazy-metadata-cache.ts
1150
939
  /**
@@ -1250,10 +1039,10 @@ var LazyMetadataCache = class {
1250
1039
  sawRow = true;
1251
1040
  if (!Array.isArray(row.key) || row.key.length < 2) continue;
1252
1041
  if (row.key.length === 2) {
1253
- const obj = asJsonObject(row.value);
1042
+ const obj = require_utils.asJsonObject(row.value);
1254
1043
  if (!obj) continue;
1255
1044
  for (const [field, value] of Object.entries(obj)) {
1256
- const cloned = cloneJsonValue(value);
1045
+ const cloned = require_utils.cloneJsonValue(value);
1257
1046
  if (cloned !== void 0) {
1258
1047
  docMeta[field] = cloned;
1259
1048
  populated = true;
@@ -1263,7 +1052,7 @@ var LazyMetadataCache = class {
1263
1052
  }
1264
1053
  const fieldKey = row.key[2];
1265
1054
  if (typeof fieldKey !== "string") continue;
1266
- const jsonValue = cloneJsonValue(row.value);
1055
+ const jsonValue = require_utils.cloneJsonValue(row.value);
1267
1056
  if (jsonValue !== void 0) {
1268
1057
  docMeta[fieldKey] = jsonValue;
1269
1058
  populated = true;
@@ -1297,7 +1086,7 @@ var MetadataManager = class {
1297
1086
  const active = this.readExistsFromFlock(docId);
1298
1087
  if (active === void 0) return void 0;
1299
1088
  return {
1300
- meta: cloneJsonObject(this.cache.get(docId) ?? {}),
1089
+ meta: require_utils.cloneJsonObject(this.cache.get(docId) ?? {}),
1301
1090
  deleted: !active
1302
1091
  };
1303
1092
  }
@@ -1355,11 +1144,11 @@ var MetadataManager = class {
1355
1144
  const docId = row.key[1];
1356
1145
  if (typeof docId !== "string") continue;
1357
1146
  if (typeof row.value !== "boolean") continue;
1358
- if (!matchesQuery(docId, this.cache.get(docId) ?? {}, query)) continue;
1147
+ if (!require_utils.matchesQuery(docId, this.cache.get(docId) ?? {}, query)) continue;
1359
1148
  entries.push({
1360
1149
  docId,
1361
1150
  deleted: !row.value,
1362
- meta: cloneJsonObject(this.cache.get(docId) ?? {})
1151
+ meta: require_utils.cloneJsonObject(this.cache.get(docId) ?? {})
1363
1152
  });
1364
1153
  }
1365
1154
  return entries;
@@ -1367,7 +1156,7 @@ var MetadataManager = class {
1367
1156
  async upsert(docId, patch) {
1368
1157
  await this.ensureExists(docId);
1369
1158
  const base = this.cache.get(docId);
1370
- const next = base ? cloneJsonObject(base) : {};
1159
+ const next = base ? require_utils.cloneJsonObject(base) : {};
1371
1160
  const outPatch = {};
1372
1161
  let changed = false;
1373
1162
  const patchObject = patch;
@@ -1386,7 +1175,7 @@ var MetadataManager = class {
1386
1175
  changed = true;
1387
1176
  continue;
1388
1177
  }
1389
- if (jsonEquals(hadKey ? base[key] : void 0, rawValue)) continue;
1178
+ if (require_utils.jsonEquals(hadKey ? base[key] : void 0, rawValue)) continue;
1390
1179
  this.metaFlock.put([
1391
1180
  "m",
1392
1181
  docId,
@@ -1439,18 +1228,18 @@ var MetadataManager = class {
1439
1228
  computeMetadataPatch(previous, next, patchHint) {
1440
1229
  const hasPatchHint = Boolean(patchHint && Object.keys(patchHint).length > 0);
1441
1230
  if (next === void 0) {
1442
- if (hasPatchHint) return cloneJsonObject(patchHint);
1231
+ if (hasPatchHint) return require_utils.cloneJsonObject(patchHint);
1443
1232
  if (!previous) return void 0;
1444
- const patch$1 = diffJsonObjects(previous, {});
1233
+ const patch$1 = require_utils.diffJsonObjects(previous, {});
1445
1234
  return Object.keys(patch$1).length > 0 ? patch$1 : void 0;
1446
1235
  }
1447
1236
  if (!previous) {
1448
- if (hasPatchHint) return cloneJsonObject(patchHint);
1449
- return Object.keys(next).length > 0 ? cloneJsonObject(next) : void 0;
1237
+ if (hasPatchHint) return require_utils.cloneJsonObject(patchHint);
1238
+ return Object.keys(next).length > 0 ? require_utils.cloneJsonObject(next) : void 0;
1450
1239
  }
1451
- const patch = diffJsonObjects(previous, next);
1240
+ const patch = require_utils.diffJsonObjects(previous, next);
1452
1241
  if (Object.keys(patch).length > 0) return patch;
1453
- return hasPatchHint ? cloneJsonObject(patchHint) : void 0;
1242
+ return hasPatchHint ? require_utils.cloneJsonObject(patchHint) : void 0;
1454
1243
  }
1455
1244
  computeDocRangeKeys(query) {
1456
1245
  if (!query) return {};
@@ -1590,7 +1379,7 @@ var FlockDocRegistry = class {
1590
1379
  const flockDocId = row.key[1];
1591
1380
  if (typeof flockDocId !== "string") continue;
1592
1381
  if (typeof row.value !== "boolean") continue;
1593
- if (!matchesQuery(flockDocId, {}, query)) continue;
1382
+ if (!require_utils.matchesQuery(flockDocId, {}, query)) continue;
1594
1383
  entries.push({
1595
1384
  flockDocId,
1596
1385
  deleted: !row.value,
@@ -1738,16 +1527,16 @@ var FlockHydrator = class {
1738
1527
  const patch = metadataPatches.get(docId) ?? {};
1739
1528
  metadataPatches.set(docId, patch);
1740
1529
  if (key.length === 2) {
1741
- const value = asJsonObject(event.value);
1530
+ const value = require_utils.asJsonObject(event.value);
1742
1531
  if (value) for (const [field, entry] of Object.entries(value)) {
1743
- const cloned = cloneJsonValue(entry);
1532
+ const cloned = require_utils.cloneJsonValue(entry);
1744
1533
  if (cloned !== void 0) patch[field] = cloned;
1745
1534
  }
1746
1535
  continue;
1747
1536
  }
1748
1537
  const fieldKey = key[2];
1749
1538
  if (typeof fieldKey === "string") {
1750
- const cloned = cloneJsonValue(event.value);
1539
+ const cloned = require_utils.cloneJsonValue(event.value);
1751
1540
  patch[fieldKey] = cloned === void 0 ? null : cloned;
1752
1541
  }
1753
1542
  continue;
@@ -2514,7 +2303,7 @@ var SyncRunner = class {
2514
2303
  }
2515
2304
  async sync(options = {}) {
2516
2305
  const { signal } = options;
2517
- throwIfAborted(signal);
2306
+ require_utils.throwIfAborted(signal);
2518
2307
  const required = options.requireTransports ?? [];
2519
2308
  const missingRequired = required.filter((transportId) => !this.transports.has(transportId));
2520
2309
  if (missingRequired.length > 0) return {
@@ -2559,7 +2348,7 @@ var SyncRunner = class {
2559
2348
  const connect = async () => {
2560
2349
  if (!connected && !entry.adapter.isConnected()) await entry.adapter.connect();
2561
2350
  connected = true;
2562
- throwIfAborted(signal);
2351
+ require_utils.throwIfAborted(signal);
2563
2352
  };
2564
2353
  if (metaRoute.includes(transportId)) {
2565
2354
  attempted.add(transportId);
@@ -2572,7 +2361,7 @@ var SyncRunner = class {
2572
2361
  return;
2573
2362
  }
2574
2363
  }
2575
- throwIfAborted(signal);
2364
+ require_utils.throwIfAborted(signal);
2576
2365
  const plan = await this.buildSyncPlan(options);
2577
2366
  const docIds = plan.docIds.filter((docId) => this.resolveRoute("doc", docId).includes(transportId));
2578
2367
  let flockDocIds = plan.flockDocIds.filter((flockDocId) => this.resolveRoute("flock-doc", flockDocId).includes(transportId) && (explicitFlockIds || entry.adapter.syncFlockDoc !== void 0));
@@ -2590,7 +2379,7 @@ var SyncRunner = class {
2590
2379
  flockDocIds = [];
2591
2380
  }
2592
2381
  for (const docId of docIds) {
2593
- throwIfAborted(signal);
2382
+ require_utils.throwIfAborted(signal);
2594
2383
  try {
2595
2384
  const wasLoaded = this.docManager.isLoaded(docId);
2596
2385
  const acquired = await this.docManager.acquireDoc(docId, "room", `sync:doc:${docId}`);
@@ -2600,9 +2389,9 @@ var SyncRunner = class {
2600
2389
  try {
2601
2390
  this.eventBus.pushEventBy("sync");
2602
2391
  try {
2603
- throwIfAborted(signal);
2392
+ require_utils.throwIfAborted(signal);
2604
2393
  const result = await entry.adapter.syncDoc(docId, doc, signal ? { signal } : void 0);
2605
- throwIfAborted(signal);
2394
+ require_utils.throwIfAborted(signal);
2606
2395
  if (!result.ok) throw result.error ?? /* @__PURE__ */ new Error(`Document sync failed for ${docId}`);
2607
2396
  } finally {
2608
2397
  this.eventBus.popEventBy();
@@ -2618,7 +2407,7 @@ var SyncRunner = class {
2618
2407
  }
2619
2408
  }
2620
2409
  for (const flockDocId of flockDocIds) {
2621
- throwIfAborted(signal);
2410
+ require_utils.throwIfAborted(signal);
2622
2411
  try {
2623
2412
  const wasLoaded = this.flockDocManager.isLoaded(flockDocId);
2624
2413
  const acquired = await this.flockDocManager.acquireFlockDoc(flockDocId, "room", `sync:flock-doc:${flockDocId}`);
@@ -2628,9 +2417,9 @@ var SyncRunner = class {
2628
2417
  try {
2629
2418
  this.eventBus.pushEventBy("sync");
2630
2419
  try {
2631
- throwIfAborted(signal);
2420
+ require_utils.throwIfAborted(signal);
2632
2421
  const result = await entry.adapter.syncFlockDoc(flockDocId, flock, signal ? { signal } : void 0);
2633
- throwIfAborted(signal);
2422
+ require_utils.throwIfAborted(signal);
2634
2423
  if (!result.ok) throw result.error ?? /* @__PURE__ */ new Error(`Flock document sync failed for ${flockDocId}`);
2635
2424
  } finally {
2636
2425
  this.eventBus.popEventBy();
@@ -2655,7 +2444,7 @@ var SyncRunner = class {
2655
2444
  settled = await Promise.race([allSettledPromise, new Promise((_, reject) => {
2656
2445
  const onAbort = () => {
2657
2446
  try {
2658
- throwIfAborted(signal);
2447
+ require_utils.throwIfAborted(signal);
2659
2448
  } catch (error) {
2660
2449
  reject(error);
2661
2450
  }
@@ -2711,35 +2500,22 @@ var SyncRunner = class {
2711
2500
  });
2712
2501
  }
2713
2502
  }
2714
- /**
2715
- * Drops replicas that only this sync caused to be materialized.
2716
- *
2717
- * Anything an owner still holds — a lease, a live room — is left alone:
2718
- * post-sync cleanup must not evict a replica somebody is using. Failures
2719
- * are logged rather than propagated, since the sync itself already
2720
- * succeeded and retention is a memory concern, not a correctness one.
2721
- */
2722
- /**
2723
- * Asks every registered adapter to drop cached sessions bound to the
2724
- * current replica of `id`, without touching durable state.
2725
- */
2726
- async releaseTransportReplica(kind, id) {
2503
+ async releaseTransportReplica(kind, id, replica) {
2727
2504
  for (const entry of this.transports.values()) {
2728
- const release = kind === "doc" ? entry.adapter.releaseDocReplica : entry.adapter.releaseFlockDocReplica;
2729
- if (!release) continue;
2730
- await release.call(entry.adapter, id).catch(require_logging.logAsyncError(`release ${kind} replica ${id} on transport`));
2505
+ const { adapter } = entry;
2506
+ await (kind === "doc" ? adapter.releaseDocReplica?.(id, replica) : adapter.releaseFlockDocReplica?.(id, replica))?.catch(require_logging.logAsyncError(`release ${kind} replica ${id} on transport`));
2731
2507
  }
2732
2508
  }
2733
2509
  async releaseTransientReplicas(loaded) {
2734
2510
  for (const docId of loaded.docIds) {
2735
2511
  if (this.docManager.ownership.ownerCount(docId) > 0) continue;
2736
- await this.docManager.unloadDoc(docId).catch(require_logging.logAsyncError(`release doc ${docId} loaded for one-shot sync`));
2737
- await this.releaseTransportReplica("doc", docId);
2512
+ const evicted = await this.docManager.unloadDoc(docId).catch(require_logging.logAsyncError(`release doc ${docId} loaded for one-shot sync`));
2513
+ await this.releaseTransportReplica("doc", docId, evicted ?? void 0);
2738
2514
  }
2739
2515
  for (const flockDocId of loaded.flockDocIds) {
2740
2516
  if (this.flockDocManager.ownership.ownerCount(flockDocId) > 0) continue;
2741
- await this.flockDocManager.unloadFlockDoc(flockDocId).catch(require_logging.logAsyncError(`release Flock doc ${flockDocId} loaded for one-shot sync`));
2742
- await this.releaseTransportReplica("flock-doc", flockDocId);
2517
+ const evicted = await this.flockDocManager.unloadFlockDoc(flockDocId).catch(require_logging.logAsyncError(`release Flock doc ${flockDocId} loaded for one-shot sync`));
2518
+ await this.releaseTransportReplica("flock-doc", flockDocId, evicted ?? void 0);
2743
2519
  }
2744
2520
  }
2745
2521
  /**
@@ -2763,9 +2539,9 @@ var SyncRunner = class {
2763
2539
  await this.ensureMetaLiveMonitor();
2764
2540
  this.activeMetaSyncCount += 1;
2765
2541
  try {
2766
- throwIfAborted(signal);
2542
+ require_utils.throwIfAborted(signal);
2767
2543
  const result = await adapter.syncMeta(this.metaFlock, signal ? { signal } : void 0);
2768
- throwIfAborted(signal);
2544
+ require_utils.throwIfAborted(signal);
2769
2545
  if (!result.ok) throw result.error ?? /* @__PURE__ */ new Error("Metadata sync failed");
2770
2546
  this.metaFlock.commit();
2771
2547
  await this.metaHydrationQueue.catch(() => {});
@@ -3371,7 +3147,7 @@ var MetaPersister = class {
3371
3147
  this.compactionByteThreshold = typeof configuredCompactionByteThreshold === "number" && Number.isFinite(configuredCompactionByteThreshold) && configuredCompactionByteThreshold >= 0 ? Math.floor(configuredCompactionByteThreshold) : DEFAULT_META_COMPACTION_BYTE_THRESHOLD;
3372
3148
  }
3373
3149
  start() {
3374
- this.journal ??= new require_flock_persistence_journal.FlockPersistenceJournal(this.metaFlock, () => this.scheduleFlush());
3150
+ this.journal ??= new require_utils.FlockPersistenceJournal(this.metaFlock, () => this.scheduleFlush());
3375
3151
  }
3376
3152
  async destroy() {
3377
3153
  this.destroyed = true;
@@ -4061,7 +3837,7 @@ var LoroRepo = class LoroRepo {
4061
3837
  await this.purgeFlockDoc(flockDocId);
4062
3838
  purged.push(flockDocId);
4063
3839
  } catch (error) {
4064
- if (error instanceof ResourceBusyError) continue;
3840
+ if (error instanceof require_utils.ResourceBusyError) continue;
4065
3841
  firstError ??= error;
4066
3842
  }
4067
3843
  if (firstError !== void 0) throw firstError;
@@ -4133,8 +3909,8 @@ var LoroRepo = class LoroRepo {
4133
3909
  this.docManager.assertEvictableNow(docId, options.force);
4134
3910
  const rebind = await this.syncRunner.detachRoomsForResource("doc", docId);
4135
3911
  try {
4136
- await this.docManager.unloadDoc(docId, options);
4137
- await this.syncRunner.releaseTransportReplica("doc", docId);
3912
+ const evicted = await this.docManager.unloadDoc(docId, options);
3913
+ await this.syncRunner.releaseTransportReplica("doc", docId, evicted);
4138
3914
  } finally {
4139
3915
  await rebind();
4140
3916
  }
@@ -4147,8 +3923,8 @@ var LoroRepo = class LoroRepo {
4147
3923
  this.flockDocManager.assertEvictableNow(flockDocId, options.force);
4148
3924
  const rebind = await this.syncRunner.detachRoomsForResource("flock-doc", flockDocId);
4149
3925
  try {
4150
- await this.flockDocManager.unloadFlockDoc(flockDocId, options);
4151
- await this.syncRunner.releaseTransportReplica("flock-doc", flockDocId);
3926
+ const evicted = await this.flockDocManager.unloadFlockDoc(flockDocId, options);
3927
+ await this.syncRunner.releaseTransportReplica("flock-doc", flockDocId, evicted);
4152
3928
  } finally {
4153
3929
  await rebind();
4154
3930
  }
@@ -4172,7 +3948,7 @@ var LoroRepo = class LoroRepo {
4172
3948
  if (this._destroyed) throw new Error("Repository has been destroyed");
4173
3949
  const resolve = () => {
4174
3950
  if (target.kind === "meta") {
4175
- if (target.flock !== this.metaFlock) throw new StaleReplicaError("metadata", "meta");
3951
+ if (target.flock !== this.metaFlock) throw new require_utils.StaleReplicaError("metadata", "meta");
4176
3952
  if (this.metaCheckpointStore) return this.metaCheckpointStore;
4177
3953
  } else if (target.kind === "flock") {
4178
3954
  const store = this.flockDocManager.getCheckpointStore(target.flockDocId, target.flock);
@@ -4252,7 +4028,7 @@ exports.RepoStorageError = require_meta_snapshot.RepoStorageError;
4252
4028
  exports.RepoSyncError = require_meta_snapshot.RepoSyncError;
4253
4029
  exports.RepoTransportError = require_meta_snapshot.RepoTransportError;
4254
4030
  exports.RepoWriterLocked = require_meta_snapshot.RepoWriterLocked;
4255
- exports.ResourceBusyError = ResourceBusyError;
4256
- exports.StaleReplicaError = StaleReplicaError;
4031
+ exports.ResourceBusyError = require_utils.ResourceBusyError;
4032
+ exports.StaleReplicaError = require_utils.StaleReplicaError;
4257
4033
  exports.supportsEphemeralRooms = require_meta_snapshot.supportsEphemeralRooms;
4258
4034
  //# sourceMappingURL=index.cjs.map