@abraca/dabra 2.101.0 → 2.103.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 (151) hide show
  1. package/dist/abracadabra-provider.cjs +6673 -6543
  2. package/dist/abracadabra-provider.cjs.map +1 -1
  3. package/dist/esm/AbracadabraBaseProvider.js +558 -0
  4. package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
  5. package/dist/esm/AbracadabraClient.js +1424 -0
  6. package/dist/esm/AbracadabraClient.js.map +1 -0
  7. package/dist/esm/AbracadabraProvider.js +547 -0
  8. package/dist/esm/AbracadabraProvider.js.map +1 -0
  9. package/dist/esm/AbracadabraWS.js +398 -0
  10. package/dist/esm/AbracadabraWS.js.map +1 -0
  11. package/dist/esm/BackgroundSyncManager.js +571 -0
  12. package/dist/esm/BackgroundSyncManager.js.map +1 -0
  13. package/dist/esm/BackgroundSyncPersistence.js +62 -0
  14. package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
  15. package/dist/esm/ChatClient.js +176 -0
  16. package/dist/esm/ChatClient.js.map +1 -0
  17. package/dist/esm/CloseEvents.js +45 -0
  18. package/dist/esm/CloseEvents.js.map +1 -0
  19. package/dist/esm/ContentManager.js +153 -0
  20. package/dist/esm/ContentManager.js.map +1 -0
  21. package/dist/esm/CoverReconcile.js +124 -0
  22. package/dist/esm/CoverReconcile.js.map +1 -0
  23. package/dist/esm/CryptoIdentityKeystore.js +580 -0
  24. package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
  25. package/dist/esm/DeviceRegistrationService.js +158 -0
  26. package/dist/esm/DeviceRegistrationService.js.map +1 -0
  27. package/dist/esm/DocConverters.js +1300 -0
  28. package/dist/esm/DocConverters.js.map +1 -0
  29. package/dist/esm/DocKeyManager.js +145 -0
  30. package/dist/esm/DocKeyManager.js.map +1 -0
  31. package/dist/esm/DocTypes.js +792 -0
  32. package/dist/esm/DocTypes.js.map +1 -0
  33. package/dist/esm/DocUtils.js +180 -0
  34. package/dist/esm/DocUtils.js.map +1 -0
  35. package/dist/esm/DocumentCache.js +131 -0
  36. package/dist/esm/DocumentCache.js.map +1 -0
  37. package/dist/esm/DocumentManager.js +240 -0
  38. package/dist/esm/DocumentManager.js.map +1 -0
  39. package/dist/esm/E2EAbracadabraProvider.js +273 -0
  40. package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
  41. package/dist/esm/E2EOfflineStore.js +53 -0
  42. package/dist/esm/E2EOfflineStore.js.map +1 -0
  43. package/dist/esm/EncryptedChatClient.js +156 -0
  44. package/dist/esm/EncryptedChatClient.js.map +1 -0
  45. package/dist/esm/EncryptedY.js +115 -0
  46. package/dist/esm/EncryptedY.js.map +1 -0
  47. package/dist/esm/EventEmitter.js +40 -0
  48. package/dist/esm/EventEmitter.js.map +1 -0
  49. package/dist/esm/FileBlobStore.js +410 -0
  50. package/dist/esm/FileBlobStore.js.map +1 -0
  51. package/dist/esm/IdentityDoc.js +413 -0
  52. package/dist/esm/IdentityDoc.js.map +1 -0
  53. package/dist/esm/IncomingMessage.js +39 -0
  54. package/dist/esm/IncomingMessage.js.map +1 -0
  55. package/dist/esm/LifecycleGate.js +124 -0
  56. package/dist/esm/LifecycleGate.js.map +1 -0
  57. package/dist/esm/MessageReceiver.js +86 -0
  58. package/dist/esm/MessageReceiver.js.map +1 -0
  59. package/dist/esm/MessageSender.js +19 -0
  60. package/dist/esm/MessageSender.js.map +1 -0
  61. package/dist/esm/MetaManager.js +112 -0
  62. package/dist/esm/MetaManager.js.map +1 -0
  63. package/dist/esm/MnemonicKeyDerivation.js +137 -0
  64. package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
  65. package/dist/esm/NodeConnect.js +63 -0
  66. package/dist/esm/NodeConnect.js.map +1 -0
  67. package/dist/esm/NodeIdentity.js +212 -0
  68. package/dist/esm/NodeIdentity.js.map +1 -0
  69. package/dist/esm/NotificationsClient.js +136 -0
  70. package/dist/esm/NotificationsClient.js.map +1 -0
  71. package/dist/esm/OfflineStore.js +291 -0
  72. package/dist/esm/OfflineStore.js.map +1 -0
  73. package/dist/esm/OutgoingMessage.js +18 -0
  74. package/dist/esm/OutgoingMessage.js.map +1 -0
  75. package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
  76. package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
  77. package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
  78. package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
  79. package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
  80. package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
  81. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
  82. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
  83. package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
  84. package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
  85. package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
  86. package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
  87. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
  88. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
  89. package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
  90. package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
  91. package/dist/esm/PerfCounters.js +336 -0
  92. package/dist/esm/PerfCounters.js.map +1 -0
  93. package/dist/esm/QueryClient.js +117 -0
  94. package/dist/esm/QueryClient.js.map +1 -0
  95. package/dist/esm/RpcClient.js +456 -0
  96. package/dist/esm/RpcClient.js.map +1 -0
  97. package/dist/esm/SchemaTypes.js +38 -0
  98. package/dist/esm/SchemaTypes.js.map +1 -0
  99. package/dist/esm/SearchIndex.js +167 -0
  100. package/dist/esm/SearchIndex.js.map +1 -0
  101. package/dist/esm/ServerRegistry.js +139 -0
  102. package/dist/esm/ServerRegistry.js.map +1 -0
  103. package/dist/esm/ServerReset.js +170 -0
  104. package/dist/esm/ServerReset.js.map +1 -0
  105. package/dist/esm/TokenManager.js +236 -0
  106. package/dist/esm/TokenManager.js.map +1 -0
  107. package/dist/esm/TreeManager.js +655 -0
  108. package/dist/esm/TreeManager.js.map +1 -0
  109. package/dist/esm/TreeTimestamps.js +61 -0
  110. package/dist/esm/TreeTimestamps.js.map +1 -0
  111. package/dist/esm/auth.js +43 -0
  112. package/dist/esm/auth.js.map +1 -0
  113. package/dist/esm/awarenessStatesToArray.js +13 -0
  114. package/dist/esm/awarenessStatesToArray.js.map +1 -0
  115. package/dist/esm/docIds.js +53 -0
  116. package/dist/esm/docIds.js.map +1 -0
  117. package/dist/esm/encryptedContent.js +21 -0
  118. package/dist/esm/encryptedContent.js.map +1 -0
  119. package/dist/esm/index.js +61 -0
  120. package/dist/esm/messageRecord.js +64 -0
  121. package/dist/esm/messageRecord.js.map +1 -0
  122. package/dist/esm/sync/BroadcastChannelSync.js +160 -0
  123. package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
  124. package/dist/esm/types.js +54 -0
  125. package/dist/esm/types.js.map +1 -0
  126. package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
  127. package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
  128. package/dist/esm/webrtc/DataChannelRouter.js +124 -0
  129. package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
  130. package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
  131. package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
  132. package/dist/esm/webrtc/E2EEChannel.js +137 -0
  133. package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
  134. package/dist/esm/webrtc/FileTransferChannel.js +250 -0
  135. package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
  136. package/dist/esm/webrtc/ManualSignaling.js +161 -0
  137. package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
  138. package/dist/esm/webrtc/PeerConnection.js +96 -0
  139. package/dist/esm/webrtc/PeerConnection.js.map +1 -0
  140. package/dist/esm/webrtc/SignalingSocket.js +274 -0
  141. package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
  142. package/dist/esm/webrtc/YjsDataChannel.js +135 -0
  143. package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
  144. package/dist/esm/webrtc/types.js +29 -0
  145. package/dist/esm/webrtc/types.js.map +1 -0
  146. package/dist/esm/x25519Convert.js +69 -0
  147. package/dist/esm/x25519Convert.js.map +1 -0
  148. package/dist/index.d.ts +26 -11
  149. package/package.json +6 -4
  150. package/dist/abracadabra-provider.esm.js +0 -14860
  151. package/dist/abracadabra-provider.esm.js.map +0 -1
@@ -0,0 +1,655 @@
1
+ import { makeEntryMap, normalizeRootId, patchEntry, toPlain } from "./DocUtils.js";
2
+ import { resolvePageType } from "./DocTypes.js";
3
+ import { projectTreeEntry } from "./SchemaTypes.js";
4
+
5
+ //#region packages/provider/src/TreeManager.ts
6
+ /**
7
+ * Stable total order over tree siblings: `order` ascending, then `id`
8
+ * ascending as a deterministic tiebreak. The legacy scan sorted by
9
+ * `order` alone and left ties to insertion/iteration order — a superset
10
+ * change that makes cursor pagination well-defined.
11
+ */
12
+ function cmpKey(oa, ia, ob, ib) {
13
+ if (oa !== ob) return oa < ob ? -1 : 1;
14
+ return ia < ib ? -1 : ia > ib ? 1 : 0;
15
+ }
16
+ function cmpEntry(a, b) {
17
+ return cmpKey(a.order ?? 0, a.id, b.order ?? 0, b.id);
18
+ }
19
+ /**
20
+ * Deterministic, convergent cycle break for the parent-pointer forest.
21
+ *
22
+ * Concurrent offline reparents converge (Yjs LWW on each entry's *own*
23
+ * `parentId` key) to a state that can contain a directed cycle — e.g. peer A
24
+ * moves X under Y while peer B moves Y under X yields `X.parent=Y` AND
25
+ * `Y.parent=X`. Both writes touch different keys so both survive, and the
26
+ * whole subtree then floats unreachable from root (the "orphaned subtree"
27
+ * corruption — §3b of OFFLINE-FIRST-TREE-AUDIT). Yjs guarantees every replica
28
+ * converges to the SAME cyclic map, so any repair that is a pure function of
29
+ * that map is itself convergent: every replica picks the identical break and
30
+ * agrees on the result with no coordinator (a lightweight stand-in for the
31
+ * full Kleppmann fold — it loses one move's intent, but never corrupts).
32
+ *
33
+ * Rule: in each cycle, the node with the lexicographically-greatest id is
34
+ * logically reparented to root. Returns the set of such break-node ids — empty
35
+ * when the forest is already acyclic (the overwhelmingly common case, so the
36
+ * hot path adds one O(n) walk and changes no behavior).
37
+ *
38
+ * `parentOf` returns the effective *normalized* parent (null = root); a parent
39
+ * id absent from `ids` is a strand, not a cycle (Tier-0 does not auto-rescue
40
+ * strands). Self-loops (`parentId === id`) are a degenerate one-node cycle and
41
+ * are handled. The Rust provider mirrors this exactly (`cycle_break_ids`).
42
+ */
43
+ function cycleBreakIds(ids, parentOf) {
44
+ const idSet = new Set(ids);
45
+ const done = /* @__PURE__ */ new Set();
46
+ const breaks = /* @__PURE__ */ new Set();
47
+ for (const start of idSet) {
48
+ if (done.has(start)) continue;
49
+ const path = [];
50
+ const onPath = /* @__PURE__ */ new Map();
51
+ let cur = start;
52
+ while (cur !== null && idSet.has(cur) && !done.has(cur)) {
53
+ const seenAt = onPath.get(cur);
54
+ if (seenAt !== void 0) {
55
+ let maxId = path[seenAt];
56
+ for (let i = seenAt + 1; i < path.length; i++) if (path[i] > maxId) maxId = path[i];
57
+ breaks.add(maxId);
58
+ break;
59
+ }
60
+ onPath.set(cur, path.length);
61
+ path.push(cur);
62
+ cur = parentOf(cur);
63
+ }
64
+ for (const id of path) done.add(id);
65
+ }
66
+ return breaks;
67
+ }
68
+ /** Opaque, dependency-free cursor over the (order,id) sibling order. */
69
+ function encodeCursor(order, id) {
70
+ return encodeURIComponent(JSON.stringify([order ?? 0, id]));
71
+ }
72
+ function decodeCursor(c) {
73
+ try {
74
+ const v = JSON.parse(decodeURIComponent(c));
75
+ if (Array.isArray(v) && typeof v[0] === "number" && typeof v[1] === "string") return {
76
+ order: v[0],
77
+ id: v[1]
78
+ };
79
+ } catch {}
80
+ return null;
81
+ }
82
+ var TreeManager = class {
83
+ constructor(dm) {
84
+ this.dm = dm;
85
+ this._idxMap = null;
86
+ this._idxObserver = null;
87
+ this._idxDirty = true;
88
+ this._byId = /* @__PURE__ */ new Map();
89
+ this._childrenByParent = /* @__PURE__ */ new Map();
90
+ }
91
+ /**
92
+ * Ensure the index is enabled, bound to the current root doc's tree
93
+ * map, and fresh. Returns `false` when the index is disabled or there
94
+ * is no tree map yet — callers then use the legacy scan path.
95
+ */
96
+ ensureIndex() {
97
+ if (!this.dm.treeIndexEnabled) return false;
98
+ const treeMap = this.dm.getTreeMap();
99
+ if (!treeMap) {
100
+ this.unbindIndex();
101
+ return false;
102
+ }
103
+ if (treeMap !== this._idxMap) {
104
+ this.unbindIndex();
105
+ const obs = () => {
106
+ this._idxDirty = true;
107
+ };
108
+ treeMap.observeDeep(obs);
109
+ this._idxMap = treeMap;
110
+ this._idxObserver = obs;
111
+ this._idxDirty = true;
112
+ }
113
+ if (this._idxDirty) this.rebuildIndex(treeMap);
114
+ return true;
115
+ }
116
+ unbindIndex() {
117
+ if (this._idxMap && this._idxObserver) this._idxMap.unobserveDeep(this._idxObserver);
118
+ this._idxMap = null;
119
+ this._idxObserver = null;
120
+ this._byId = /* @__PURE__ */ new Map();
121
+ this._childrenByParent = /* @__PURE__ */ new Map();
122
+ this._idxDirty = true;
123
+ }
124
+ rebuildIndex(treeMap) {
125
+ const root = this.dm.rootDocId;
126
+ const byId = /* @__PURE__ */ new Map();
127
+ treeMap.forEach((raw, id) => {
128
+ const value = toPlain(raw);
129
+ if (typeof value !== "object" || value === null) return;
130
+ byId.set(id, {
131
+ id,
132
+ label: value.label || "Untitled",
133
+ parentId: normalizeRootId(value.parentId ?? null, root),
134
+ order: value.order ?? 0,
135
+ type: value.type,
136
+ meta: value.meta,
137
+ createdAt: value.createdAt,
138
+ updatedAt: value.updatedAt
139
+ });
140
+ });
141
+ const breaks = cycleBreakIds(byId.keys(), (id) => byId.get(id)?.parentId ?? null);
142
+ for (const id of breaks) {
143
+ const e = byId.get(id);
144
+ if (e) e.parentId = null;
145
+ }
146
+ const childrenByParent = /* @__PURE__ */ new Map();
147
+ for (const entry of byId.values()) {
148
+ let bucket = childrenByParent.get(entry.parentId);
149
+ if (!bucket) {
150
+ bucket = [];
151
+ childrenByParent.set(entry.parentId, bucket);
152
+ }
153
+ bucket.push(entry);
154
+ }
155
+ for (const bucket of childrenByParent.values()) bucket.sort(cmpEntry);
156
+ this._byId = byId;
157
+ this._childrenByParent = childrenByParent;
158
+ this._idxDirty = false;
159
+ }
160
+ /**
161
+ * Release the deep observer. Optional — the observer is auto-rebound
162
+ * on space switch and becomes moot when the root Y.Doc is GC'd — but
163
+ * available for consumers that want deterministic teardown.
164
+ */
165
+ dispose() {
166
+ this.unbindIndex();
167
+ }
168
+ /** Read all tree entries as plain objects. */
169
+ readEntries() {
170
+ const treeMap = this.dm.getTreeMap();
171
+ if (!treeMap) return [];
172
+ const entries = [];
173
+ treeMap.forEach((raw, id) => {
174
+ const value = toPlain(raw);
175
+ if (typeof value !== "object" || value === null) return;
176
+ entries.push({
177
+ id,
178
+ label: value.label || "Untitled",
179
+ parentId: value.parentId ?? null,
180
+ order: value.order ?? 0,
181
+ type: value.type,
182
+ meta: value.meta,
183
+ createdAt: value.createdAt,
184
+ updatedAt: value.updatedAt
185
+ });
186
+ });
187
+ return entries;
188
+ }
189
+ /**
190
+ * Like {@link readEntries} but with every entry's *stored* parentId
191
+ * run through {@link normalizeRootId} (parentId === rootDocId → null),
192
+ * so a cou-sh / orphan-rescue top-level doc (parentId === spaceRoot)
193
+ * resolves to top-level identically to a provider-created one
194
+ * (parentId: null). Without this, the raw `parentId === spaceRoot`
195
+ * form never matches the normalized `null` query and such docs are
196
+ * silently invisible cross-client. Mirrors the Rust provider's
197
+ * `normalized_entries`. readEntries/get keep raw values for
198
+ * round-trip consumers; only tree-walk reads use this.
199
+ */
200
+ normalizedEntries() {
201
+ if (this.ensureIndex()) return Array.from(this._byId.values());
202
+ const root = this.dm.rootDocId;
203
+ const entries = this.readEntries().map((e) => ({
204
+ ...e,
205
+ parentId: normalizeRootId(e.parentId, root)
206
+ }));
207
+ const byId = new Map(entries.map((e) => [e.id, e]));
208
+ const breaks = cycleBreakIds(byId.keys(), (id) => byId.get(id)?.parentId ?? null);
209
+ for (const id of breaks) {
210
+ const e = byId.get(id);
211
+ if (e) e.parentId = null;
212
+ }
213
+ return entries;
214
+ }
215
+ /** Get immediate children of a parent (sorted by order). */
216
+ childrenOf(parentId) {
217
+ const normalized = normalizeRootId(parentId, this.dm.rootDocId);
218
+ if (this.ensureIndex()) {
219
+ const bucket = this._childrenByParent.get(normalized);
220
+ return bucket ? bucket.slice() : [];
221
+ }
222
+ return this.normalizedEntries().filter((e) => e.parentId === normalized).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
223
+ }
224
+ /**
225
+ * Paginated immediate children — the Path-1 surface for large fan-out
226
+ * parents. Walks the same stable (order,id) sibling order as
227
+ * {@link childrenOf}; `cursor` is opaque (round-trip `nextCursor`).
228
+ * `limit` defaults to 100. A stale/garbage cursor restarts from the
229
+ * head rather than throwing. Cursor stability is exact when the index
230
+ * is enabled; on the legacy scan path siblings with equal `order`
231
+ * may shift between calls.
232
+ */
233
+ childrenOfPage(parentId, opts = {}) {
234
+ const all = this.childrenOf(parentId);
235
+ const limit = opts.limit != null && opts.limit > 0 ? Math.floor(opts.limit) : 100;
236
+ let start = 0;
237
+ if (opts.cursor) {
238
+ const dec = decodeCursor(opts.cursor);
239
+ if (dec) {
240
+ const at = all.findIndex((e) => cmpKey(e.order ?? 0, e.id, dec.order, dec.id) > 0);
241
+ start = at < 0 ? all.length : at;
242
+ }
243
+ }
244
+ const entries = all.slice(start, start + limit);
245
+ const last = entries[entries.length - 1];
246
+ return {
247
+ entries,
248
+ nextCursor: last && start + limit < all.length ? encodeCursor(last.order ?? 0, last.id) : null
249
+ };
250
+ }
251
+ /** Get all descendants recursively. */
252
+ descendantsOf(parentId) {
253
+ const normalized = normalizeRootId(parentId, this.dm.rootDocId);
254
+ if (this.ensureIndex()) {
255
+ const result = [];
256
+ const visited = /* @__PURE__ */ new Set();
257
+ const walk = (pid) => {
258
+ if (pid !== null) {
259
+ if (visited.has(pid)) return;
260
+ visited.add(pid);
261
+ }
262
+ const bucket = this._childrenByParent.get(pid);
263
+ if (!bucket) return;
264
+ for (const child of bucket) {
265
+ result.push(child);
266
+ walk(child.id);
267
+ }
268
+ };
269
+ walk(normalized);
270
+ return result;
271
+ }
272
+ const entries = this.normalizedEntries();
273
+ const result = [];
274
+ const visited = /* @__PURE__ */ new Set();
275
+ const collect = (pid) => {
276
+ if (pid !== null && visited.has(pid)) return;
277
+ if (pid !== null) visited.add(pid);
278
+ for (const child of entries.filter((e) => e.parentId === pid).sort((a, b) => (a.order ?? 0) - (b.order ?? 0))) {
279
+ result.push(child);
280
+ collect(child.id);
281
+ }
282
+ };
283
+ collect(normalized);
284
+ return result;
285
+ }
286
+ /** Build nested tree JSON. */
287
+ buildTree(rootId, maxDepth = 3) {
288
+ const normalized = normalizeRootId(rootId ?? null, this.dm.rootDocId);
289
+ if (this.ensureIndex()) return this._buildTreeIndexed(normalized, maxDepth, 0, /* @__PURE__ */ new Set());
290
+ const entries = this.normalizedEntries();
291
+ return this._buildTree(entries, normalized, maxDepth, 0, /* @__PURE__ */ new Set());
292
+ }
293
+ _buildTreeIndexed(rootId, maxDepth, currentDepth, visited) {
294
+ if (maxDepth >= 0 && currentDepth >= maxDepth) return [];
295
+ return (this._childrenByParent.get(rootId) ?? []).filter((e) => !visited.has(e.id)).map((entry) => {
296
+ const next = new Set(visited);
297
+ next.add(entry.id);
298
+ return {
299
+ id: entry.id,
300
+ label: entry.label,
301
+ type: entry.type,
302
+ meta: entry.meta,
303
+ order: entry.order,
304
+ children: this._buildTreeIndexed(entry.id, maxDepth, currentDepth + 1, next)
305
+ };
306
+ });
307
+ }
308
+ _buildTree(entries, rootId, maxDepth, currentDepth, visited) {
309
+ if (maxDepth >= 0 && currentDepth >= maxDepth) return [];
310
+ return entries.filter((e) => e.parentId === rootId).sort((a, b) => (a.order ?? 0) - (b.order ?? 0)).filter((e) => !visited.has(e.id)).map((entry) => {
311
+ const next = new Set(visited);
312
+ next.add(entry.id);
313
+ return {
314
+ id: entry.id,
315
+ label: entry.label,
316
+ type: entry.type,
317
+ meta: entry.meta,
318
+ order: entry.order,
319
+ children: this._buildTree(entries, entry.id, maxDepth, currentDepth + 1, next)
320
+ };
321
+ });
322
+ }
323
+ /**
324
+ * Schema-typed lookup. Returns a `TypedTreeEntry<TMap, N>` when the
325
+ * entry's `type` matches `expectedType`, else `null`. Pure projection
326
+ * over the existing untyped tree — no schema validation is performed
327
+ * here (the entry's data is whatever was last synced; meta correctness
328
+ * is the writer's responsibility, optionally enforced via
329
+ * `MetaManager.setSchema`).
330
+ *
331
+ * Rule 4 alignment: when the entry's type doesn't match, returns null
332
+ * rather than throwing — callers branch on the result.
333
+ */
334
+ getTyped(_schema, expectedType, docId) {
335
+ return projectTreeEntry(this.get(docId), expectedType);
336
+ }
337
+ /** Find a single entry by ID. */
338
+ get(docId) {
339
+ const treeMap = this.dm.getTreeMap();
340
+ if (!treeMap) return null;
341
+ const raw = treeMap.get(docId);
342
+ if (!raw) return null;
343
+ const value = toPlain(raw);
344
+ if (typeof value !== "object" || value === null) return null;
345
+ return {
346
+ id: docId,
347
+ label: value.label || "Untitled",
348
+ parentId: value.parentId ?? null,
349
+ order: value.order ?? 0,
350
+ type: value.type,
351
+ meta: value.meta,
352
+ createdAt: value.createdAt,
353
+ updatedAt: value.updatedAt
354
+ };
355
+ }
356
+ /** Search by label (case-insensitive substring match). */
357
+ find(query, rootId) {
358
+ const entries = this.normalizedEntries();
359
+ const lowerQuery = query.toLowerCase();
360
+ const normalized = normalizeRootId(rootId ?? null, this.dm.rootDocId);
361
+ const matches = (normalized ? this.descendantsOf(normalized) : entries).filter((e) => e.label.toLowerCase().includes(lowerQuery));
362
+ const byId = new Map(entries.map((e) => [e.id, e]));
363
+ return matches.map((entry) => {
364
+ const path = [];
365
+ let current = entry.parentId;
366
+ const visited = /* @__PURE__ */ new Set();
367
+ while (current && !visited.has(current)) {
368
+ visited.add(current);
369
+ const parent = byId.get(current);
370
+ if (!parent) break;
371
+ path.unshift(parent.label);
372
+ current = parent.parentId;
373
+ }
374
+ return {
375
+ id: entry.id,
376
+ label: entry.label,
377
+ type: entry.type,
378
+ meta: entry.meta,
379
+ path
380
+ };
381
+ });
382
+ }
383
+ /** Create a new document in the tree. Returns the new entry. */
384
+ create(opts) {
385
+ const treeMap = this.dm.getTreeMap();
386
+ const rootDoc = this.dm.rootDocument;
387
+ if (!treeMap || !rootDoc) throw new Error("Not connected");
388
+ const id = crypto.randomUUID();
389
+ const normalizedParent = normalizeRootId(opts.parentId ?? null, this.dm.rootDocId);
390
+ const now = Date.now();
391
+ rootDoc.transact(() => {
392
+ treeMap.set(id, makeEntryMap({
393
+ label: opts.label,
394
+ parentId: normalizedParent,
395
+ order: now,
396
+ type: opts.type,
397
+ meta: opts.meta,
398
+ createdAt: now,
399
+ updatedAt: now
400
+ }));
401
+ });
402
+ return {
403
+ id,
404
+ label: opts.label,
405
+ parentId: normalizedParent,
406
+ order: now,
407
+ type: opts.type,
408
+ meta: opts.meta,
409
+ createdAt: now,
410
+ updatedAt: now
411
+ };
412
+ }
413
+ /**
414
+ * Create a document and auto-apply renderer defaults from the page type's
415
+ * `defaultMetaFields` (toggle fields with `default` values).
416
+ */
417
+ createWithTypeDefaults(opts) {
418
+ const typeInfo = resolvePageType(opts.type);
419
+ const autoMeta = {};
420
+ if (typeInfo?.defaultMetaFields) {
421
+ for (const field of typeInfo.defaultMetaFields) if (field.type === "toggle" && field.key && field.default !== void 0) autoMeta[field.key] = field.default;
422
+ }
423
+ const mergedMeta = Object.keys(autoMeta).length > 0 || opts.extraMeta ? {
424
+ ...autoMeta,
425
+ ...opts.extraMeta ?? {}
426
+ } : void 0;
427
+ return this.create({
428
+ parentId: opts.parentId,
429
+ label: opts.label,
430
+ type: opts.type,
431
+ meta: mergedMeta
432
+ });
433
+ }
434
+ /** Rename a document. */
435
+ rename(docId, label) {
436
+ const treeMap = this.dm.getTreeMap();
437
+ const rootDoc = this.dm.rootDocument;
438
+ if (!treeMap || !rootDoc) throw new Error("Not connected");
439
+ if (!treeMap.get(docId)) throw new Error(`Document ${docId} not found`);
440
+ rootDoc.transact(() => {
441
+ patchEntry(treeMap, docId, {
442
+ label,
443
+ updatedAt: Date.now()
444
+ });
445
+ });
446
+ }
447
+ /** Move a document to a new parent. */
448
+ move(docId, newParentId, order) {
449
+ const treeMap = this.dm.getTreeMap();
450
+ const rootDoc = this.dm.rootDocument;
451
+ if (!treeMap || !rootDoc) throw new Error("Not connected");
452
+ if (!treeMap.get(docId)) throw new Error(`Document ${docId} not found`);
453
+ rootDoc.transact(() => {
454
+ patchEntry(treeMap, docId, {
455
+ parentId: normalizeRootId(newParentId ?? null, this.dm.rootDocId),
456
+ order: order ?? Date.now(),
457
+ updatedAt: Date.now()
458
+ });
459
+ });
460
+ }
461
+ /**
462
+ * Heal converged move-cycles in the stored tree itself.
463
+ *
464
+ * The read paths already present a cycle-free, fully-reachable tree
465
+ * without writing (see {@link cycleBreakIds}); this *persists* that repair
466
+ * into the CRDT so the stored structure is acyclic too — useful as a
467
+ * one-shot on load, or behind a "repair tree" action. Deterministic and
468
+ * convergent: every replica computes the identical break set, so even
469
+ * concurrent calls from multiple peers write the same `parentId: null` and
470
+ * converge. Returns the number of nodes reparented to root (0 when already
471
+ * acyclic — the common case, where no transaction is opened). Optional —
472
+ * the always-on read guard already makes the corruption invisible.
473
+ */
474
+ repairTree() {
475
+ const treeMap = this.dm.getTreeMap();
476
+ const rootDoc = this.dm.rootDocument;
477
+ if (!treeMap || !rootDoc) throw new Error("Not connected");
478
+ const root = this.dm.rootDocId;
479
+ const parentById = /* @__PURE__ */ new Map();
480
+ treeMap.forEach((raw, id) => {
481
+ const value = toPlain(raw);
482
+ if (typeof value !== "object" || value === null) return;
483
+ parentById.set(id, normalizeRootId(value.parentId ?? null, root));
484
+ });
485
+ const breaks = cycleBreakIds(parentById.keys(), (id) => parentById.get(id) ?? null);
486
+ if (!breaks.size) return 0;
487
+ rootDoc.transact(() => {
488
+ for (const id of breaks) if (treeMap.get(id)) patchEntry(treeMap, id, {
489
+ parentId: null,
490
+ updatedAt: Date.now()
491
+ });
492
+ });
493
+ return breaks.size;
494
+ }
495
+ /** Change the page type of a document. */
496
+ changeType(docId, type) {
497
+ const treeMap = this.dm.getTreeMap();
498
+ const rootDoc = this.dm.rootDocument;
499
+ if (!treeMap || !rootDoc) throw new Error("Not connected");
500
+ if (!treeMap.get(docId)) throw new Error(`Document ${docId} not found`);
501
+ rootDoc.transact(() => {
502
+ patchEntry(treeMap, docId, {
503
+ type,
504
+ updatedAt: Date.now()
505
+ });
506
+ });
507
+ }
508
+ /**
509
+ * Soft-delete a document and descendants (move to trash).
510
+ * @returns count of deleted documents
511
+ */
512
+ delete(docId) {
513
+ const treeMap = this.dm.getTreeMap();
514
+ const trashMap = this.dm.getTrashMap();
515
+ const rootDoc = this.dm.rootDocument;
516
+ if (!treeMap || !trashMap || !rootDoc) throw new Error("Not connected");
517
+ const now = Date.now();
518
+ let deletedCount = 0;
519
+ rootDoc.transact(() => {
520
+ const entries = this.readEntries();
521
+ const toDelete = [docId, ...this._descendantIds(entries, docId)];
522
+ deletedCount = toDelete.length;
523
+ for (const nid of toDelete) {
524
+ const raw = treeMap.get(nid);
525
+ if (!raw) continue;
526
+ const entry = toPlain(raw);
527
+ trashMap.set(nid, {
528
+ label: entry.label || "Untitled",
529
+ parentId: entry.parentId ?? null,
530
+ order: entry.order ?? 0,
531
+ type: entry.type,
532
+ meta: entry.meta,
533
+ deletedAt: now
534
+ });
535
+ treeMap.delete(nid);
536
+ }
537
+ });
538
+ return deletedCount;
539
+ }
540
+ /** Duplicate a document (shallow clone). Returns the new entry. */
541
+ duplicate(docId) {
542
+ const treeMap = this.dm.getTreeMap();
543
+ if (!treeMap) throw new Error("Not connected");
544
+ const raw = treeMap.get(docId);
545
+ if (!raw) throw new Error(`Document ${docId} not found`);
546
+ const entry = toPlain(raw);
547
+ const newId = crypto.randomUUID();
548
+ const now = Date.now();
549
+ const newLabel = (entry.label || "Untitled") + " (copy)";
550
+ treeMap.set(newId, makeEntryMap({
551
+ ...entry,
552
+ label: newLabel,
553
+ order: now,
554
+ createdAt: now,
555
+ updatedAt: now
556
+ }));
557
+ return {
558
+ id: newId,
559
+ label: newLabel,
560
+ parentId: entry.parentId ?? null,
561
+ order: now,
562
+ type: entry.type,
563
+ meta: entry.meta,
564
+ createdAt: now,
565
+ updatedAt: now
566
+ };
567
+ }
568
+ /** Restore a document from trash back into the tree. */
569
+ restore(docId) {
570
+ const treeMap = this.dm.getTreeMap();
571
+ const trashMap = this.dm.getTrashMap();
572
+ const rootDoc = this.dm.rootDocument;
573
+ if (!treeMap || !trashMap || !rootDoc) throw new Error("Not connected");
574
+ if (!trashMap.get(docId)) throw new Error(`Document ${docId} not found in trash`);
575
+ const now = Date.now();
576
+ rootDoc.transact(() => {
577
+ const trashed = /* @__PURE__ */ new Map();
578
+ trashMap.forEach((raw, id) => {
579
+ const v = toPlain(raw);
580
+ if (typeof v === "object" && v !== null) trashed.set(id, v);
581
+ });
582
+ const toRestore = [];
583
+ const visited = /* @__PURE__ */ new Set();
584
+ const collect = (id) => {
585
+ if (visited.has(id)) return;
586
+ visited.add(id);
587
+ if (!trashed.has(id)) return;
588
+ toRestore.push(id);
589
+ for (const [cid, v] of trashed) if ((v.parentId ?? null) === id) collect(cid);
590
+ };
591
+ collect(docId);
592
+ for (const id of toRestore) {
593
+ const entry = trashed.get(id);
594
+ treeMap.set(id, makeEntryMap({
595
+ label: entry.label || "Untitled",
596
+ parentId: entry.parentId ?? null,
597
+ order: entry.order ?? now,
598
+ type: entry.type,
599
+ meta: entry.meta,
600
+ createdAt: entry.createdAt ?? now,
601
+ updatedAt: now
602
+ }));
603
+ trashMap.delete(id);
604
+ }
605
+ });
606
+ }
607
+ /** List trashed documents. */
608
+ listTrash() {
609
+ const trashMap = this.dm.getTrashMap();
610
+ if (!trashMap) return [];
611
+ const entries = [];
612
+ trashMap.forEach((raw, id) => {
613
+ const value = toPlain(raw);
614
+ if (typeof value !== "object" || value === null) return;
615
+ entries.push({
616
+ id,
617
+ label: value.label || "Untitled",
618
+ parentId: value.parentId ?? null,
619
+ order: value.order ?? 0,
620
+ type: value.type,
621
+ meta: value.meta
622
+ });
623
+ });
624
+ return entries;
625
+ }
626
+ /** Get enabled plugin names from space-plugins map. */
627
+ getEnabledPlugins() {
628
+ const pluginsMap = this.dm.getPluginsMap();
629
+ if (!pluginsMap) return [];
630
+ const plugins = [];
631
+ pluginsMap.forEach((raw, key) => {
632
+ const value = toPlain(raw);
633
+ if (value && value.enabled) plugins.push(key);
634
+ });
635
+ return plugins;
636
+ }
637
+ _descendantIds(entries, parentId) {
638
+ const result = [];
639
+ const visited = /* @__PURE__ */ new Set();
640
+ const collect = (pid) => {
641
+ if (visited.has(pid)) return;
642
+ visited.add(pid);
643
+ for (const child of entries.filter((e) => e.parentId === pid)) {
644
+ result.push(child.id);
645
+ collect(child.id);
646
+ }
647
+ };
648
+ collect(parentId);
649
+ return result;
650
+ }
651
+ };
652
+
653
+ //#endregion
654
+ export { TreeManager };
655
+ //# sourceMappingURL=TreeManager.js.map