@abraca/dabra 2.102.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.
- package/dist/abracadabra-provider.cjs +6673 -6543
- package/dist/abracadabra-provider.cjs.map +1 -1
- package/dist/esm/AbracadabraBaseProvider.js +558 -0
- package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
- package/dist/esm/AbracadabraClient.js +1424 -0
- package/dist/esm/AbracadabraClient.js.map +1 -0
- package/dist/esm/AbracadabraProvider.js +547 -0
- package/dist/esm/AbracadabraProvider.js.map +1 -0
- package/dist/esm/AbracadabraWS.js +398 -0
- package/dist/esm/AbracadabraWS.js.map +1 -0
- package/dist/esm/BackgroundSyncManager.js +571 -0
- package/dist/esm/BackgroundSyncManager.js.map +1 -0
- package/dist/esm/BackgroundSyncPersistence.js +62 -0
- package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
- package/dist/esm/ChatClient.js +176 -0
- package/dist/esm/ChatClient.js.map +1 -0
- package/dist/esm/CloseEvents.js +45 -0
- package/dist/esm/CloseEvents.js.map +1 -0
- package/dist/esm/ContentManager.js +153 -0
- package/dist/esm/ContentManager.js.map +1 -0
- package/dist/esm/CoverReconcile.js +124 -0
- package/dist/esm/CoverReconcile.js.map +1 -0
- package/dist/esm/CryptoIdentityKeystore.js +580 -0
- package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
- package/dist/esm/DeviceRegistrationService.js +158 -0
- package/dist/esm/DeviceRegistrationService.js.map +1 -0
- package/dist/esm/DocConverters.js +1300 -0
- package/dist/esm/DocConverters.js.map +1 -0
- package/dist/esm/DocKeyManager.js +145 -0
- package/dist/esm/DocKeyManager.js.map +1 -0
- package/dist/esm/DocTypes.js +792 -0
- package/dist/esm/DocTypes.js.map +1 -0
- package/dist/esm/DocUtils.js +180 -0
- package/dist/esm/DocUtils.js.map +1 -0
- package/dist/esm/DocumentCache.js +131 -0
- package/dist/esm/DocumentCache.js.map +1 -0
- package/dist/esm/DocumentManager.js +240 -0
- package/dist/esm/DocumentManager.js.map +1 -0
- package/dist/esm/E2EAbracadabraProvider.js +273 -0
- package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
- package/dist/esm/E2EOfflineStore.js +53 -0
- package/dist/esm/E2EOfflineStore.js.map +1 -0
- package/dist/esm/EncryptedChatClient.js +156 -0
- package/dist/esm/EncryptedChatClient.js.map +1 -0
- package/dist/esm/EncryptedY.js +115 -0
- package/dist/esm/EncryptedY.js.map +1 -0
- package/dist/esm/EventEmitter.js +40 -0
- package/dist/esm/EventEmitter.js.map +1 -0
- package/dist/esm/FileBlobStore.js +410 -0
- package/dist/esm/FileBlobStore.js.map +1 -0
- package/dist/esm/IdentityDoc.js +413 -0
- package/dist/esm/IdentityDoc.js.map +1 -0
- package/dist/esm/IncomingMessage.js +39 -0
- package/dist/esm/IncomingMessage.js.map +1 -0
- package/dist/esm/LifecycleGate.js +124 -0
- package/dist/esm/LifecycleGate.js.map +1 -0
- package/dist/esm/MessageReceiver.js +86 -0
- package/dist/esm/MessageReceiver.js.map +1 -0
- package/dist/esm/MessageSender.js +19 -0
- package/dist/esm/MessageSender.js.map +1 -0
- package/dist/esm/MetaManager.js +112 -0
- package/dist/esm/MetaManager.js.map +1 -0
- package/dist/esm/MnemonicKeyDerivation.js +137 -0
- package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
- package/dist/esm/NodeConnect.js +63 -0
- package/dist/esm/NodeConnect.js.map +1 -0
- package/dist/esm/NodeIdentity.js +212 -0
- package/dist/esm/NodeIdentity.js.map +1 -0
- package/dist/esm/NotificationsClient.js +136 -0
- package/dist/esm/NotificationsClient.js.map +1 -0
- package/dist/esm/OfflineStore.js +291 -0
- package/dist/esm/OfflineStore.js.map +1 -0
- package/dist/esm/OutgoingMessage.js +18 -0
- package/dist/esm/OutgoingMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
- package/dist/esm/PerfCounters.js +336 -0
- package/dist/esm/PerfCounters.js.map +1 -0
- package/dist/esm/QueryClient.js +117 -0
- package/dist/esm/QueryClient.js.map +1 -0
- package/dist/esm/RpcClient.js +456 -0
- package/dist/esm/RpcClient.js.map +1 -0
- package/dist/esm/SchemaTypes.js +38 -0
- package/dist/esm/SchemaTypes.js.map +1 -0
- package/dist/esm/SearchIndex.js +167 -0
- package/dist/esm/SearchIndex.js.map +1 -0
- package/dist/esm/ServerRegistry.js +139 -0
- package/dist/esm/ServerRegistry.js.map +1 -0
- package/dist/esm/ServerReset.js +170 -0
- package/dist/esm/ServerReset.js.map +1 -0
- package/dist/esm/TokenManager.js +236 -0
- package/dist/esm/TokenManager.js.map +1 -0
- package/dist/esm/TreeManager.js +655 -0
- package/dist/esm/TreeManager.js.map +1 -0
- package/dist/esm/TreeTimestamps.js +61 -0
- package/dist/esm/TreeTimestamps.js.map +1 -0
- package/dist/esm/auth.js +43 -0
- package/dist/esm/auth.js.map +1 -0
- package/dist/esm/awarenessStatesToArray.js +13 -0
- package/dist/esm/awarenessStatesToArray.js.map +1 -0
- package/dist/esm/docIds.js +53 -0
- package/dist/esm/docIds.js.map +1 -0
- package/dist/esm/encryptedContent.js +21 -0
- package/dist/esm/encryptedContent.js.map +1 -0
- package/dist/esm/index.js +61 -0
- package/dist/esm/messageRecord.js +64 -0
- package/dist/esm/messageRecord.js.map +1 -0
- package/dist/esm/sync/BroadcastChannelSync.js +160 -0
- package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
- package/dist/esm/types.js +54 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
- package/dist/esm/webrtc/DataChannelRouter.js +124 -0
- package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
- package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
- package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
- package/dist/esm/webrtc/E2EEChannel.js +137 -0
- package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
- package/dist/esm/webrtc/FileTransferChannel.js +250 -0
- package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
- package/dist/esm/webrtc/ManualSignaling.js +161 -0
- package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
- package/dist/esm/webrtc/PeerConnection.js +96 -0
- package/dist/esm/webrtc/PeerConnection.js.map +1 -0
- package/dist/esm/webrtc/SignalingSocket.js +274 -0
- package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
- package/dist/esm/webrtc/YjsDataChannel.js +135 -0
- package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
- package/dist/esm/webrtc/types.js +29 -0
- package/dist/esm/webrtc/types.js.map +1 -0
- package/dist/esm/x25519Convert.js +69 -0
- package/dist/esm/x25519Convert.js.map +1 -0
- package/dist/index.d.ts +26 -11
- package/package.json +6 -4
- package/dist/abracadabra-provider.esm.js +0 -14860
- package/dist/abracadabra-provider.esm.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TreeManager.js","names":[],"sources":["../../src/TreeManager.ts"],"sourcesContent":["/**\n * TreeManager — typed ORM layer over the root Y.Doc's \"doc-tree\" / \"doc-trash\"\n * Y.Maps.\n *\n * Extracted from `mcp/tools/tree.ts` and `cli/commands/documents.ts` logic.\n * All tree CRUD operations go through this class.\n */\nimport type * as Y from \"yjs\";\nimport type {\n\tPageMeta,\n\tTreeEntry,\n\tTreeNode,\n\tTreeSearchResult,\n} from \"./DocTypes.ts\";\nimport { resolvePageType } from \"./DocTypes.ts\";\nimport {\n\tmakeEntryMap,\n\tnormalizeRootId,\n\tpatchEntry,\n\ttoPlain,\n} from \"./DocUtils.ts\";\nimport type { DocumentManager } from \"./DocumentManager.ts\";\nimport {\n\tprojectTreeEntry,\n\ttype SchemaRegistryLike,\n\ttype TypedTreeEntry,\n} from \"./SchemaTypes.ts\";\n\n/**\n * Stable total order over tree siblings: `order` ascending, then `id`\n * ascending as a deterministic tiebreak. The legacy scan sorted by\n * `order` alone and left ties to insertion/iteration order — a superset\n * change that makes cursor pagination well-defined.\n */\nfunction cmpKey(oa: number, ia: string, ob: number, ib: string): number {\n\tif (oa !== ob) return oa < ob ? -1 : 1;\n\treturn ia < ib ? -1 : ia > ib ? 1 : 0;\n}\nfunction cmpEntry(a: TreeEntry, b: TreeEntry): number {\n\treturn cmpKey(a.order ?? 0, a.id, b.order ?? 0, b.id);\n}\n\n/**\n * Deterministic, convergent cycle break for the parent-pointer forest.\n *\n * Concurrent offline reparents converge (Yjs LWW on each entry's *own*\n * `parentId` key) to a state that can contain a directed cycle — e.g. peer A\n * moves X under Y while peer B moves Y under X yields `X.parent=Y` AND\n * `Y.parent=X`. Both writes touch different keys so both survive, and the\n * whole subtree then floats unreachable from root (the \"orphaned subtree\"\n * corruption — §3b of OFFLINE-FIRST-TREE-AUDIT). Yjs guarantees every replica\n * converges to the SAME cyclic map, so any repair that is a pure function of\n * that map is itself convergent: every replica picks the identical break and\n * agrees on the result with no coordinator (a lightweight stand-in for the\n * full Kleppmann fold — it loses one move's intent, but never corrupts).\n *\n * Rule: in each cycle, the node with the lexicographically-greatest id is\n * logically reparented to root. Returns the set of such break-node ids — empty\n * when the forest is already acyclic (the overwhelmingly common case, so the\n * hot path adds one O(n) walk and changes no behavior).\n *\n * `parentOf` returns the effective *normalized* parent (null = root); a parent\n * id absent from `ids` is a strand, not a cycle (Tier-0 does not auto-rescue\n * strands). Self-loops (`parentId === id`) are a degenerate one-node cycle and\n * are handled. The Rust provider mirrors this exactly (`cycle_break_ids`).\n */\nfunction cycleBreakIds(\n\tids: Iterable<string>,\n\tparentOf: (id: string) => string | null,\n): Set<string> {\n\tconst idSet = new Set(ids);\n\tconst done = new Set<string>();\n\tconst breaks = new Set<string>();\n\tfor (const start of idSet) {\n\t\tif (done.has(start)) continue;\n\t\tconst path: string[] = [];\n\t\tconst onPath = new Map<string, number>();\n\t\tlet cur: string | null = start;\n\t\twhile (cur !== null && idSet.has(cur) && !done.has(cur)) {\n\t\t\tconst seenAt = onPath.get(cur);\n\t\t\tif (seenAt !== undefined) {\n\t\t\t\t// path[seenAt..] is the cycle; break its greatest id.\n\t\t\t\tlet maxId = path[seenAt];\n\t\t\t\tfor (let i = seenAt + 1; i < path.length; i++) {\n\t\t\t\t\tif (path[i] > maxId) maxId = path[i];\n\t\t\t\t}\n\t\t\t\tbreaks.add(maxId);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tonPath.set(cur, path.length);\n\t\t\tpath.push(cur);\n\t\t\tcur = parentOf(cur);\n\t\t}\n\t\tfor (const id of path) done.add(id);\n\t}\n\treturn breaks;\n}\n\n/** Opaque, dependency-free cursor over the (order,id) sibling order. */\nfunction encodeCursor(order: number, id: string): string {\n\treturn encodeURIComponent(JSON.stringify([order ?? 0, id]));\n}\nfunction decodeCursor(c: string): { order: number; id: string } | null {\n\ttry {\n\t\tconst v = JSON.parse(decodeURIComponent(c)) as unknown;\n\t\tif (\n\t\t\tArray.isArray(v) &&\n\t\t\ttypeof v[0] === \"number\" &&\n\t\t\ttypeof v[1] === \"string\"\n\t\t) {\n\t\t\treturn { order: v[0], id: v[1] };\n\t\t}\n\t} catch {\n\t\t// Garbage / tampered cursor → treat as \"from the beginning\".\n\t}\n\treturn null;\n}\n\nexport interface ChildrenPage {\n\tentries: TreeEntry[];\n\t/** Pass back as `cursor` for the next page; `null` when exhausted. */\n\tnextCursor: string | null;\n}\n\nexport class TreeManager {\n\tconstructor(private dm: DocumentManager) {}\n\n\t// ── Path-1 prototype: lazy parent→children index ──────────────────────────\n\t//\n\t// Gated by `dm.treeIndexEnabled`. When off, every method below falls\n\t// through to the original whole-map scan (unchanged). When on, tree\n\t// WALKS resolve against a normalized adjacency index that is rebuilt\n\t// lazily: an `observeDeep` on the bound `doc-tree` Y.Map only flips a\n\t// dirty bit, so the O(n) rebuild happens at most once per mutation\n\t// batch instead of once per read, and reads between writes are\n\t// O(k)/O(result) instead of O(n)/O(n²). `readEntries`/`get` keep RAW\n\t// parentId for round-trip consumers and are intentionally NOT indexed.\n\tprivate _idxMap: Y.Map<unknown> | null = null;\n\tprivate _idxObserver: (() => void) | null = null;\n\tprivate _idxDirty = true;\n\tprivate _byId = new Map<string, TreeEntry>();\n\tprivate _childrenByParent = new Map<string | null, TreeEntry[]>();\n\n\t/**\n\t * Ensure the index is enabled, bound to the current root doc's tree\n\t * map, and fresh. Returns `false` when the index is disabled or there\n\t * is no tree map yet — callers then use the legacy scan path.\n\t */\n\tprivate ensureIndex(): boolean {\n\t\tif (!this.dm.treeIndexEnabled) return false;\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tif (!treeMap) {\n\t\t\tthis.unbindIndex();\n\t\t\treturn false;\n\t\t}\n\t\tif (treeMap !== this._idxMap) {\n\t\t\t// Root doc (space) swapped, or first use — rebind the observer.\n\t\t\tthis.unbindIndex();\n\t\t\tconst obs = () => {\n\t\t\t\tthis._idxDirty = true;\n\t\t\t};\n\t\t\ttreeMap.observeDeep(obs);\n\t\t\tthis._idxMap = treeMap;\n\t\t\tthis._idxObserver = obs;\n\t\t\tthis._idxDirty = true;\n\t\t}\n\t\tif (this._idxDirty) this.rebuildIndex(treeMap);\n\t\treturn true;\n\t}\n\n\tprivate unbindIndex(): void {\n\t\tif (this._idxMap && this._idxObserver) {\n\t\t\tthis._idxMap.unobserveDeep(this._idxObserver);\n\t\t}\n\t\tthis._idxMap = null;\n\t\tthis._idxObserver = null;\n\t\tthis._byId = new Map();\n\t\tthis._childrenByParent = new Map();\n\t\tthis._idxDirty = true;\n\t}\n\n\tprivate rebuildIndex(treeMap: Y.Map<unknown>): void {\n\t\tconst root = this.dm.rootDocId;\n\t\tconst byId = new Map<string, TreeEntry>();\n\t\ttreeMap.forEach((raw: unknown, id: string) => {\n\t\t\tconst value = toPlain(raw) as Record<string, unknown>;\n\t\t\tif (typeof value !== \"object\" || value === null) return;\n\t\t\tbyId.set(id, {\n\t\t\t\tid,\n\t\t\t\tlabel: (value.label as string) || \"Untitled\",\n\t\t\t\tparentId: normalizeRootId(\n\t\t\t\t\t(value.parentId as string | null) ?? null,\n\t\t\t\t\troot,\n\t\t\t\t),\n\t\t\t\torder: (value.order as number) ?? 0,\n\t\t\t\ttype: value.type as string | undefined,\n\t\t\t\tmeta: value.meta as PageMeta | undefined,\n\t\t\t\tcreatedAt: value.createdAt as number | undefined,\n\t\t\t\tupdatedAt: value.updatedAt as number | undefined,\n\t\t\t});\n\t\t});\n\t\t// Converge concurrent-move cycles: logically reparent each cycle's\n\t\t// break node to root so the materialized adjacency is acyclic and\n\t\t// fully reachable. Non-mutating — the CRDT is untouched; only this\n\t\t// read-side cache is corrected (`repairTree()` persists the fix when\n\t\t// a writer wants it). No-op for the common acyclic tree. See\n\t\t// {@link cycleBreakIds}.\n\t\tconst breaks = cycleBreakIds(\n\t\t\tbyId.keys(),\n\t\t\t(id) => byId.get(id)?.parentId ?? null,\n\t\t);\n\t\tfor (const id of breaks) {\n\t\t\tconst e = byId.get(id);\n\t\t\tif (e) e.parentId = null;\n\t\t}\n\t\tconst childrenByParent = new Map<string | null, TreeEntry[]>();\n\t\tfor (const entry of byId.values()) {\n\t\t\tlet bucket = childrenByParent.get(entry.parentId);\n\t\t\tif (!bucket) {\n\t\t\t\tbucket = [];\n\t\t\t\tchildrenByParent.set(entry.parentId, bucket);\n\t\t\t}\n\t\t\tbucket.push(entry);\n\t\t}\n\t\tfor (const bucket of childrenByParent.values()) bucket.sort(cmpEntry);\n\t\tthis._byId = byId;\n\t\tthis._childrenByParent = childrenByParent;\n\t\tthis._idxDirty = false;\n\t}\n\n\t/**\n\t * Release the deep observer. Optional — the observer is auto-rebound\n\t * on space switch and becomes moot when the root Y.Doc is GC'd — but\n\t * available for consumers that want deterministic teardown.\n\t */\n\tdispose(): void {\n\t\tthis.unbindIndex();\n\t}\n\n\t// ── Reading ───────────────────────────────────────────────────────────────\n\n\t/** Read all tree entries as plain objects. */\n\treadEntries(): TreeEntry[] {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tif (!treeMap) return [];\n\n\t\tconst entries: TreeEntry[] = [];\n\t\ttreeMap.forEach((raw: unknown, id: string) => {\n\t\t\tconst value = toPlain(raw) as Record<string, unknown>;\n\t\t\tif (typeof value !== \"object\" || value === null) return;\n\t\t\tentries.push({\n\t\t\t\tid,\n\t\t\t\tlabel: (value.label as string) || \"Untitled\",\n\t\t\t\tparentId: (value.parentId as string | null) ?? null,\n\t\t\t\torder: (value.order as number) ?? 0,\n\t\t\t\ttype: value.type as string | undefined,\n\t\t\t\tmeta: value.meta as PageMeta | undefined,\n\t\t\t\tcreatedAt: value.createdAt as number | undefined,\n\t\t\t\tupdatedAt: value.updatedAt as number | undefined,\n\t\t\t});\n\t\t});\n\t\treturn entries;\n\t}\n\n\t/**\n\t * Like {@link readEntries} but with every entry's *stored* parentId\n\t * run through {@link normalizeRootId} (parentId === rootDocId → null),\n\t * so a cou-sh / orphan-rescue top-level doc (parentId === spaceRoot)\n\t * resolves to top-level identically to a provider-created one\n\t * (parentId: null). Without this, the raw `parentId === spaceRoot`\n\t * form never matches the normalized `null` query and such docs are\n\t * silently invisible cross-client. Mirrors the Rust provider's\n\t * `normalized_entries`. readEntries/get keep raw values for\n\t * round-trip consumers; only tree-walk reads use this.\n\t */\n\tprivate normalizedEntries(): TreeEntry[] {\n\t\tif (this.ensureIndex()) return Array.from(this._byId.values());\n\t\tconst root = this.dm.rootDocId;\n\t\tconst entries = this.readEntries().map((e) => ({\n\t\t\t...e,\n\t\t\tparentId: normalizeRootId(e.parentId, root),\n\t\t}));\n\t\t// Same read-side cycle break as the indexed path (see\n\t\t// {@link rebuildIndex} / {@link cycleBreakIds}) so the legacy scan\n\t\t// walks an acyclic, fully-reachable tree too. No-op when acyclic.\n\t\tconst byId = new Map(entries.map((e) => [e.id, e]));\n\t\tconst breaks = cycleBreakIds(\n\t\t\tbyId.keys(),\n\t\t\t(id) => byId.get(id)?.parentId ?? null,\n\t\t);\n\t\tfor (const id of breaks) {\n\t\t\tconst e = byId.get(id);\n\t\t\tif (e) e.parentId = null;\n\t\t}\n\t\treturn entries;\n\t}\n\n\t/** Get immediate children of a parent (sorted by order). */\n\tchildrenOf(parentId: string | null): TreeEntry[] {\n\t\tconst normalized = normalizeRootId(parentId, this.dm.rootDocId);\n\t\tif (this.ensureIndex()) {\n\t\t\t// Copy: callers (descendantsOf, find, consumers) must not\n\t\t\t// mutate the cached bucket.\n\t\t\tconst bucket = this._childrenByParent.get(normalized);\n\t\t\treturn bucket ? bucket.slice() : [];\n\t\t}\n\t\treturn this.normalizedEntries()\n\t\t\t.filter((e) => e.parentId === normalized)\n\t\t\t.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n\t}\n\n\t/**\n\t * Paginated immediate children — the Path-1 surface for large fan-out\n\t * parents. Walks the same stable (order,id) sibling order as\n\t * {@link childrenOf}; `cursor` is opaque (round-trip `nextCursor`).\n\t * `limit` defaults to 100. A stale/garbage cursor restarts from the\n\t * head rather than throwing. Cursor stability is exact when the index\n\t * is enabled; on the legacy scan path siblings with equal `order`\n\t * may shift between calls.\n\t */\n\tchildrenOfPage(\n\t\tparentId: string | null,\n\t\topts: { limit?: number; cursor?: string | null } = {},\n\t): ChildrenPage {\n\t\tconst all = this.childrenOf(parentId);\n\t\tconst limit =\n\t\t\topts.limit != null && opts.limit > 0 ? Math.floor(opts.limit) : 100;\n\t\tlet start = 0;\n\t\tif (opts.cursor) {\n\t\t\tconst dec = decodeCursor(opts.cursor);\n\t\t\tif (dec) {\n\t\t\t\tconst at = all.findIndex(\n\t\t\t\t\t(e) => cmpKey(e.order ?? 0, e.id, dec.order, dec.id) > 0,\n\t\t\t\t);\n\t\t\t\tstart = at < 0 ? all.length : at;\n\t\t\t}\n\t\t}\n\t\tconst entries = all.slice(start, start + limit);\n\t\tconst last = entries[entries.length - 1];\n\t\tconst nextCursor =\n\t\t\tlast && start + limit < all.length\n\t\t\t\t? encodeCursor(last.order ?? 0, last.id)\n\t\t\t\t: null;\n\t\treturn { entries, nextCursor };\n\t}\n\n\t/** Get all descendants recursively. */\n\tdescendantsOf(parentId: string | null): TreeEntry[] {\n\t\tconst normalized = normalizeRootId(parentId, this.dm.rootDocId);\n\t\tif (this.ensureIndex()) {\n\t\t\tconst result: TreeEntry[] = [];\n\t\t\tconst visited = new Set<string>();\n\t\t\tconst walk = (pid: string | null) => {\n\t\t\t\tif (pid !== null) {\n\t\t\t\t\tif (visited.has(pid)) return;\n\t\t\t\t\tvisited.add(pid);\n\t\t\t\t}\n\t\t\t\tconst bucket = this._childrenByParent.get(pid);\n\t\t\t\tif (!bucket) return;\n\t\t\t\tfor (const child of bucket) {\n\t\t\t\t\tresult.push(child);\n\t\t\t\t\twalk(child.id);\n\t\t\t\t}\n\t\t\t};\n\t\t\twalk(normalized);\n\t\t\treturn result;\n\t\t}\n\t\tconst entries = this.normalizedEntries();\n\t\tconst result: TreeEntry[] = [];\n\t\tconst visited = new Set<string>();\n\n\t\tconst collect = (pid: string | null) => {\n\t\t\tif (pid !== null && visited.has(pid)) return;\n\t\t\tif (pid !== null) visited.add(pid);\n\t\t\tfor (const child of entries\n\t\t\t\t.filter((e) => e.parentId === pid)\n\t\t\t\t.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))) {\n\t\t\t\tresult.push(child);\n\t\t\t\tcollect(child.id);\n\t\t\t}\n\t\t};\n\t\tcollect(normalized);\n\t\treturn result;\n\t}\n\n\t/** Build nested tree JSON. */\n\tbuildTree(rootId?: string | null, maxDepth = 3): TreeNode[] {\n\t\tconst normalized = normalizeRootId(rootId ?? null, this.dm.rootDocId);\n\t\tif (this.ensureIndex()) {\n\t\t\treturn this._buildTreeIndexed(normalized, maxDepth, 0, new Set());\n\t\t}\n\t\tconst entries = this.normalizedEntries();\n\t\treturn this._buildTree(entries, normalized, maxDepth, 0, new Set());\n\t}\n\n\tprivate _buildTreeIndexed(\n\t\trootId: string | null,\n\t\tmaxDepth: number,\n\t\tcurrentDepth: number,\n\t\tvisited: Set<string>,\n\t): TreeNode[] {\n\t\tif (maxDepth >= 0 && currentDepth >= maxDepth) return [];\n\t\tconst children = this._childrenByParent.get(rootId) ?? [];\n\t\treturn children\n\t\t\t.filter((e) => !visited.has(e.id))\n\t\t\t.map((entry) => {\n\t\t\t\tconst next = new Set(visited);\n\t\t\t\tnext.add(entry.id);\n\t\t\t\treturn {\n\t\t\t\t\tid: entry.id,\n\t\t\t\t\tlabel: entry.label,\n\t\t\t\t\ttype: entry.type,\n\t\t\t\t\tmeta: entry.meta,\n\t\t\t\t\torder: entry.order,\n\t\t\t\t\tchildren: this._buildTreeIndexed(\n\t\t\t\t\t\tentry.id,\n\t\t\t\t\t\tmaxDepth,\n\t\t\t\t\t\tcurrentDepth + 1,\n\t\t\t\t\t\tnext,\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t});\n\t}\n\n\tprivate _buildTree(\n\t\tentries: TreeEntry[],\n\t\trootId: string | null,\n\t\tmaxDepth: number,\n\t\tcurrentDepth: number,\n\t\tvisited: Set<string>,\n\t): TreeNode[] {\n\t\tif (maxDepth >= 0 && currentDepth >= maxDepth) return [];\n\t\tconst children = entries\n\t\t\t.filter((e) => e.parentId === rootId)\n\t\t\t.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n\n\t\treturn children\n\t\t\t.filter((e) => !visited.has(e.id))\n\t\t\t.map((entry) => {\n\t\t\t\tconst next = new Set(visited);\n\t\t\t\tnext.add(entry.id);\n\t\t\t\treturn {\n\t\t\t\t\tid: entry.id,\n\t\t\t\t\tlabel: entry.label,\n\t\t\t\t\ttype: entry.type,\n\t\t\t\t\tmeta: entry.meta,\n\t\t\t\t\torder: entry.order,\n\t\t\t\t\tchildren: this._buildTree(\n\t\t\t\t\t\tentries,\n\t\t\t\t\t\tentry.id,\n\t\t\t\t\t\tmaxDepth,\n\t\t\t\t\t\tcurrentDepth + 1,\n\t\t\t\t\t\tnext,\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t});\n\t}\n\n\t/**\n\t * Schema-typed lookup. Returns a `TypedTreeEntry<TMap, N>` when the\n\t * entry's `type` matches `expectedType`, else `null`. Pure projection\n\t * over the existing untyped tree — no schema validation is performed\n\t * here (the entry's data is whatever was last synced; meta correctness\n\t * is the writer's responsibility, optionally enforced via\n\t * `MetaManager.setSchema`).\n\t *\n\t * Rule 4 alignment: when the entry's type doesn't match, returns null\n\t * rather than throwing — callers branch on the result.\n\t */\n\tgetTyped<TMap extends Record<string, unknown>, N extends keyof TMap & string>(\n\t\t_schema: SchemaRegistryLike<TMap>,\n\t\texpectedType: N,\n\t\tdocId: string,\n\t): TypedTreeEntry<TMap, N> | null {\n\t\treturn projectTreeEntry<TMap, N>(this.get(docId), expectedType);\n\t}\n\n\t/** Find a single entry by ID. */\n\tget(docId: string): TreeEntry | null {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tif (!treeMap) return null;\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) return null;\n\t\tconst value = toPlain(raw) as Record<string, unknown>;\n\t\tif (typeof value !== \"object\" || value === null) return null;\n\t\treturn {\n\t\t\tid: docId,\n\t\t\tlabel: (value.label as string) || \"Untitled\",\n\t\t\tparentId: (value.parentId as string | null) ?? null,\n\t\t\torder: (value.order as number) ?? 0,\n\t\t\ttype: value.type as string | undefined,\n\t\t\tmeta: value.meta as PageMeta | undefined,\n\t\t\tcreatedAt: value.createdAt as number | undefined,\n\t\t\tupdatedAt: value.updatedAt as number | undefined,\n\t\t};\n\t}\n\n\t/** Search by label (case-insensitive substring match). */\n\tfind(query: string, rootId?: string | null): TreeSearchResult[] {\n\t\tconst entries = this.normalizedEntries();\n\t\tconst lowerQuery = query.toLowerCase();\n\n\t\tconst normalized = normalizeRootId(rootId ?? null, this.dm.rootDocId);\n\t\tconst searchSet = normalized ? this.descendantsOf(normalized) : entries;\n\n\t\tconst matches = searchSet.filter((e) =>\n\t\t\te.label.toLowerCase().includes(lowerQuery),\n\t\t);\n\n\t\tconst byId = new Map(entries.map((e) => [e.id, e]));\n\t\treturn matches.map((entry) => {\n\t\t\tconst path: string[] = [];\n\t\t\tlet current = entry.parentId;\n\t\t\tconst visited = new Set<string>();\n\t\t\twhile (current && !visited.has(current)) {\n\t\t\t\tvisited.add(current);\n\t\t\t\tconst parent = byId.get(current);\n\t\t\t\tif (!parent) break;\n\t\t\t\tpath.unshift(parent.label);\n\t\t\t\tcurrent = parent.parentId;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tid: entry.id,\n\t\t\t\tlabel: entry.label,\n\t\t\t\ttype: entry.type,\n\t\t\t\tmeta: entry.meta,\n\t\t\t\tpath,\n\t\t\t};\n\t\t});\n\t}\n\n\t// ── Writing ──────────────────────────────────────────────────────────────\n\n\t/** Create a new document in the tree. Returns the new entry. */\n\tcreate(opts: {\n\t\tparentId?: string | null;\n\t\tlabel: string;\n\t\ttype?: string;\n\t\tmeta?: Partial<PageMeta>;\n\t}): TreeEntry {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !rootDoc) {\n\t\t\tthrow new Error(\"Not connected\");\n\t\t}\n\n\t\tconst id = crypto.randomUUID();\n\t\tconst normalizedParent = normalizeRootId(\n\t\t\topts.parentId ?? null,\n\t\t\tthis.dm.rootDocId,\n\t\t);\n\t\tconst now = Date.now();\n\n\t\trootDoc.transact(() => {\n\t\t\ttreeMap.set(\n\t\t\t\tid,\n\t\t\t\tmakeEntryMap({\n\t\t\t\t\tlabel: opts.label,\n\t\t\t\t\tparentId: normalizedParent,\n\t\t\t\t\torder: now,\n\t\t\t\t\ttype: opts.type,\n\t\t\t\t\tmeta: opts.meta as PageMeta,\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t}),\n\t\t\t);\n\t\t});\n\n\t\treturn {\n\t\t\tid,\n\t\t\tlabel: opts.label,\n\t\t\tparentId: normalizedParent,\n\t\t\torder: now,\n\t\t\ttype: opts.type,\n\t\t\tmeta: opts.meta as PageMeta | undefined,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\t}\n\n\t/**\n\t * Create a document and auto-apply renderer defaults from the page type's\n\t * `defaultMetaFields` (toggle fields with `default` values).\n\t */\n\tcreateWithTypeDefaults(opts: {\n\t\tparentId?: string | null;\n\t\tlabel: string;\n\t\ttype: string;\n\t\textraMeta?: Partial<PageMeta>;\n\t}): TreeEntry {\n\t\tconst typeInfo = resolvePageType(opts.type);\n\t\tconst autoMeta: Record<string, unknown> = {};\n\t\tif (typeInfo?.defaultMetaFields) {\n\t\t\tfor (const field of typeInfo.defaultMetaFields) {\n\t\t\t\tif (\n\t\t\t\t\tfield.type === \"toggle\" &&\n\t\t\t\t\tfield.key &&\n\t\t\t\t\tfield.default !== undefined\n\t\t\t\t) {\n\t\t\t\t\tautoMeta[field.key] = field.default;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst mergedMeta =\n\t\t\tObject.keys(autoMeta).length > 0 || opts.extraMeta\n\t\t\t\t? { ...autoMeta, ...(opts.extraMeta ?? {}) }\n\t\t\t\t: undefined;\n\t\treturn this.create({\n\t\t\tparentId: opts.parentId,\n\t\t\tlabel: opts.label,\n\t\t\ttype: opts.type,\n\t\t\tmeta: mergedMeta,\n\t\t});\n\t}\n\n\t/** Rename a document. */\n\trename(docId: string, label: string): void {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !rootDoc) throw new Error(\"Not connected\");\n\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) throw new Error(`Document ${docId} not found`);\n\n\t\trootDoc.transact(() => {\n\t\t\tpatchEntry(treeMap, docId, { label, updatedAt: Date.now() });\n\t\t});\n\t}\n\n\t/** Move a document to a new parent. */\n\tmove(docId: string, newParentId?: string | null, order?: number): void {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !rootDoc) throw new Error(\"Not connected\");\n\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) throw new Error(`Document ${docId} not found`);\n\n\t\trootDoc.transact(() => {\n\t\t\tpatchEntry(treeMap, docId, {\n\t\t\t\tparentId: normalizeRootId(newParentId ?? null, this.dm.rootDocId),\n\t\t\t\torder: order ?? Date.now(),\n\t\t\t\tupdatedAt: Date.now(),\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Heal converged move-cycles in the stored tree itself.\n\t *\n\t * The read paths already present a cycle-free, fully-reachable tree\n\t * without writing (see {@link cycleBreakIds}); this *persists* that repair\n\t * into the CRDT so the stored structure is acyclic too — useful as a\n\t * one-shot on load, or behind a \"repair tree\" action. Deterministic and\n\t * convergent: every replica computes the identical break set, so even\n\t * concurrent calls from multiple peers write the same `parentId: null` and\n\t * converge. Returns the number of nodes reparented to root (0 when already\n\t * acyclic — the common case, where no transaction is opened). Optional —\n\t * the always-on read guard already makes the corruption invisible.\n\t */\n\trepairTree(): number {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !rootDoc) throw new Error(\"Not connected\");\n\t\tconst root = this.dm.rootDocId;\n\t\tconst parentById = new Map<string, string | null>();\n\t\ttreeMap.forEach((raw: unknown, id: string) => {\n\t\t\tconst value = toPlain(raw) as Record<string, unknown>;\n\t\t\tif (typeof value !== \"object\" || value === null) return;\n\t\t\tparentById.set(\n\t\t\t\tid,\n\t\t\t\tnormalizeRootId((value.parentId as string | null) ?? null, root),\n\t\t\t);\n\t\t});\n\t\tconst breaks = cycleBreakIds(\n\t\t\tparentById.keys(),\n\t\t\t(id) => parentById.get(id) ?? null,\n\t\t);\n\t\tif (!breaks.size) return 0;\n\t\trootDoc.transact(() => {\n\t\t\tfor (const id of breaks) {\n\t\t\t\tif (treeMap.get(id)) {\n\t\t\t\t\tpatchEntry(treeMap, id, {\n\t\t\t\t\t\tparentId: null,\n\t\t\t\t\t\tupdatedAt: Date.now(),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn breaks.size;\n\t}\n\n\t/** Change the page type of a document. */\n\tchangeType(docId: string, type: string): void {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !rootDoc) throw new Error(\"Not connected\");\n\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) throw new Error(`Document ${docId} not found`);\n\n\t\trootDoc.transact(() => {\n\t\t\tpatchEntry(treeMap, docId, { type, updatedAt: Date.now() });\n\t\t});\n\t}\n\n\t/**\n\t * Soft-delete a document and descendants (move to trash).\n\t * @returns count of deleted documents\n\t */\n\tdelete(docId: string): number {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst trashMap = this.dm.getTrashMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !trashMap || !rootDoc) {\n\t\t\tthrow new Error(\"Not connected\");\n\t\t}\n\n\t\tconst now = Date.now();\n\t\tlet deletedCount = 0;\n\t\t// Compute the descendant set and trash it inside ONE synchronous\n\t\t// Yjs transaction. transact() callbacks are atomic — no local or\n\t\t// remote update interleaves — so a child concurrently added under\n\t\t// this subtree cannot be stranded with a trashed parent the way a\n\t\t// read-then-separate-write delete allowed.\n\t\trootDoc.transact(() => {\n\t\t\tconst entries = this.readEntries();\n\t\t\tconst toDelete = [docId, ...this._descendantIds(entries, docId)];\n\t\t\tdeletedCount = toDelete.length;\n\t\t\tfor (const nid of toDelete) {\n\t\t\t\tconst raw = treeMap.get(nid);\n\t\t\t\tif (!raw) continue;\n\t\t\t\tconst entry = toPlain(raw) as Record<string, unknown>;\n\t\t\t\ttrashMap.set(nid, {\n\t\t\t\t\tlabel: entry.label || \"Untitled\",\n\t\t\t\t\tparentId: entry.parentId ?? null,\n\t\t\t\t\torder: entry.order ?? 0,\n\t\t\t\t\ttype: entry.type,\n\t\t\t\t\tmeta: entry.meta,\n\t\t\t\t\tdeletedAt: now,\n\t\t\t\t});\n\t\t\t\ttreeMap.delete(nid);\n\t\t\t}\n\t\t});\n\n\t\treturn deletedCount;\n\t}\n\n\t/** Duplicate a document (shallow clone). Returns the new entry. */\n\tduplicate(docId: string): TreeEntry {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tif (!treeMap) throw new Error(\"Not connected\");\n\n\t\tconst raw = treeMap.get(docId);\n\t\tif (!raw) throw new Error(`Document ${docId} not found`);\n\n\t\tconst entry = toPlain(raw) as Record<string, unknown>;\n\t\tconst newId = crypto.randomUUID();\n\t\tconst now = Date.now();\n\t\tconst newLabel = ((entry.label as string) || \"Untitled\") + \" (copy)\";\n\t\ttreeMap.set(\n\t\t\tnewId,\n\t\t\tmakeEntryMap({\n\t\t\t\t...entry,\n\t\t\t\tlabel: newLabel,\n\t\t\t\torder: now,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tupdatedAt: now,\n\t\t\t}),\n\t\t);\n\n\t\treturn {\n\t\t\tid: newId,\n\t\t\tlabel: newLabel,\n\t\t\tparentId: (entry.parentId as string | null) ?? null,\n\t\t\torder: now,\n\t\t\ttype: entry.type as string | undefined,\n\t\t\tmeta: entry.meta as PageMeta | undefined,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\t}\n\n\t/** Restore a document from trash back into the tree. */\n\trestore(docId: string): void {\n\t\tconst treeMap = this.dm.getTreeMap();\n\t\tconst trashMap = this.dm.getTrashMap();\n\t\tconst rootDoc = this.dm.rootDocument;\n\t\tif (!treeMap || !trashMap || !rootDoc) {\n\t\t\tthrow new Error(\"Not connected\");\n\t\t}\n\n\t\tif (!trashMap.get(docId)) {\n\t\t\tthrow new Error(`Document ${docId} not found in trash`);\n\t\t}\n\n\t\tconst now = Date.now();\n\t\t// Restore docId AND its whole trashed subtree. delete() trashes\n\t\t// the subtree as independent entries; restoring only the named id\n\t\t// stranded every descendant in trash forever (audit RISK 4). The\n\t\t// trash snapshot + descendant walk happen INSIDE the transaction,\n\t\t// the same atomicity discipline delete() uses.\n\t\trootDoc.transact(() => {\n\t\t\tconst trashed = new Map<string, Record<string, unknown>>();\n\t\t\ttrashMap.forEach((raw: unknown, id: string) => {\n\t\t\t\tconst v = toPlain(raw) as Record<string, unknown>;\n\t\t\t\tif (typeof v === \"object\" && v !== null) trashed.set(id, v);\n\t\t\t});\n\n\t\t\tconst toRestore: string[] = [];\n\t\t\tconst visited = new Set<string>();\n\t\t\tconst collect = (id: string) => {\n\t\t\t\tif (visited.has(id)) return;\n\t\t\t\tvisited.add(id);\n\t\t\t\tif (!trashed.has(id)) return;\n\t\t\t\ttoRestore.push(id);\n\t\t\t\tfor (const [cid, v] of trashed) {\n\t\t\t\t\tif ((v.parentId ?? null) === id) collect(cid);\n\t\t\t\t}\n\t\t\t};\n\t\t\tcollect(docId);\n\n\t\t\tfor (const id of toRestore) {\n\t\t\t\tconst entry = trashed.get(id) as Record<string, unknown>;\n\t\t\t\ttreeMap.set(\n\t\t\t\t\tid,\n\t\t\t\t\tmakeEntryMap({\n\t\t\t\t\t\tlabel: entry.label || \"Untitled\",\n\t\t\t\t\t\tparentId: entry.parentId ?? null,\n\t\t\t\t\t\torder: entry.order ?? now,\n\t\t\t\t\t\ttype: entry.type,\n\t\t\t\t\t\tmeta: entry.meta,\n\t\t\t\t\t\tcreatedAt: entry.createdAt ?? now,\n\t\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\ttrashMap.delete(id);\n\t\t\t}\n\t\t});\n\t}\n\n\t/** List trashed documents. */\n\tlistTrash(): TreeEntry[] {\n\t\tconst trashMap = this.dm.getTrashMap();\n\t\tif (!trashMap) return [];\n\n\t\tconst entries: TreeEntry[] = [];\n\t\ttrashMap.forEach((raw: unknown, id: string) => {\n\t\t\tconst value = toPlain(raw) as Record<string, unknown>;\n\t\t\tif (typeof value !== \"object\" || value === null) return;\n\t\t\tentries.push({\n\t\t\t\tid,\n\t\t\t\tlabel: (value.label as string) || \"Untitled\",\n\t\t\t\tparentId: (value.parentId as string | null) ?? null,\n\t\t\t\torder: (value.order as number) ?? 0,\n\t\t\t\ttype: value.type as string | undefined,\n\t\t\t\tmeta: value.meta as PageMeta | undefined,\n\t\t\t});\n\t\t});\n\t\treturn entries;\n\t}\n\n\t/** Get enabled plugin names from space-plugins map. */\n\tgetEnabledPlugins(): string[] {\n\t\tconst pluginsMap = this.dm.getPluginsMap();\n\t\tif (!pluginsMap) return [];\n\n\t\tconst plugins: string[] = [];\n\t\tpluginsMap.forEach((raw: unknown, key: string) => {\n\t\t\tconst value = toPlain(raw) as Record<string, unknown>;\n\t\t\tif (value && value.enabled) {\n\t\t\t\tplugins.push(key);\n\t\t\t}\n\t\t});\n\t\treturn plugins;\n\t}\n\n\t// ── Internal helpers ──────────────────────────────────────────────────────\n\n\tprivate _descendantIds(entries: TreeEntry[], parentId: string): string[] {\n\t\tconst result: string[] = [];\n\t\tconst visited = new Set<string>();\n\t\tconst collect = (pid: string) => {\n\t\t\tif (visited.has(pid)) return;\n\t\t\tvisited.add(pid);\n\t\t\tfor (const child of entries.filter((e) => e.parentId === pid)) {\n\t\t\t\tresult.push(child.id);\n\t\t\t\tcollect(child.id);\n\t\t\t}\n\t\t};\n\t\tcollect(parentId);\n\t\treturn result;\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAkCA,SAAS,OAAO,IAAY,IAAY,IAAY,IAAoB;AACvE,KAAI,OAAO,GAAI,QAAO,KAAK,KAAK,KAAK;AACrC,QAAO,KAAK,KAAK,KAAK,KAAK,KAAK,IAAI;;AAErC,SAAS,SAAS,GAAc,GAAsB;AACrD,QAAO,OAAO,EAAE,SAAS,GAAG,EAAE,IAAI,EAAE,SAAS,GAAG,EAAE,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BtD,SAAS,cACR,KACA,UACc;CACd,MAAM,QAAQ,IAAI,IAAI,IAAI;CAC1B,MAAM,uBAAO,IAAI,KAAa;CAC9B,MAAM,yBAAS,IAAI,KAAa;AAChC,MAAK,MAAM,SAAS,OAAO;AAC1B,MAAI,KAAK,IAAI,MAAM,CAAE;EACrB,MAAM,OAAiB,EAAE;EACzB,MAAM,yBAAS,IAAI,KAAqB;EACxC,IAAI,MAAqB;AACzB,SAAO,QAAQ,QAAQ,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,EAAE;GACxD,MAAM,SAAS,OAAO,IAAI,IAAI;AAC9B,OAAI,WAAW,QAAW;IAEzB,IAAI,QAAQ,KAAK;AACjB,SAAK,IAAI,IAAI,SAAS,GAAG,IAAI,KAAK,QAAQ,IACzC,KAAI,KAAK,KAAK,MAAO,SAAQ,KAAK;AAEnC,WAAO,IAAI,MAAM;AACjB;;AAED,UAAO,IAAI,KAAK,KAAK,OAAO;AAC5B,QAAK,KAAK,IAAI;AACd,SAAM,SAAS,IAAI;;AAEpB,OAAK,MAAM,MAAM,KAAM,MAAK,IAAI,GAAG;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|
+
import "yjs";
|
|
3
|
+
|
|
4
|
+
//#region packages/provider/src/TreeTimestamps.ts
|
|
5
|
+
/**
|
|
6
|
+
* Attach an observer that writes `updatedAt` to the root doc-tree entry for
|
|
7
|
+
* `childDocId` whenever the child doc receives a local edit.
|
|
8
|
+
*
|
|
9
|
+
* @param treeMap The root doc's "doc-tree" Y.Map.
|
|
10
|
+
* @param childDocId The child document's UUID (key in treeMap).
|
|
11
|
+
* @param childDoc The child Y.Doc to observe.
|
|
12
|
+
* @param offlineStore The child provider's OfflineStore (used to detect
|
|
13
|
+
* offline-replay origins and skip them). Pass null when
|
|
14
|
+
* the offline store is disabled.
|
|
15
|
+
* @param options Optional config. `throttleMs` controls the throttle
|
|
16
|
+
* window (default 5000).
|
|
17
|
+
* @returns Cleanup function — call on provider destroy. Flushes
|
|
18
|
+
* any pending write before detaching.
|
|
19
|
+
*/
|
|
20
|
+
function attachUpdatedAtObserver(treeMap, childDocId, childDoc, offlineStore, options) {
|
|
21
|
+
const throttleMs = options?.throttleMs ?? 5e3;
|
|
22
|
+
let lastFlushedAt = 0;
|
|
23
|
+
let pendingTs = 0;
|
|
24
|
+
let timer = null;
|
|
25
|
+
function writeTs(ts) {
|
|
26
|
+
if (!treeMap.get(childDocId)) return;
|
|
27
|
+
patchEntry(treeMap, childDocId, { updatedAt: ts });
|
|
28
|
+
lastFlushedAt = ts;
|
|
29
|
+
}
|
|
30
|
+
function flushPending() {
|
|
31
|
+
timer = null;
|
|
32
|
+
if (pendingTs === 0) return;
|
|
33
|
+
const ts = pendingTs;
|
|
34
|
+
pendingTs = 0;
|
|
35
|
+
writeTs(ts);
|
|
36
|
+
}
|
|
37
|
+
function handler(tr) {
|
|
38
|
+
if (!tr.local) return;
|
|
39
|
+
if (offlineStore !== null && tr.origin === offlineStore) return;
|
|
40
|
+
if (tr.changed.size === 0) return;
|
|
41
|
+
const now = Date.now();
|
|
42
|
+
if (now - lastFlushedAt >= throttleMs) {
|
|
43
|
+
writeTs(now);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
pendingTs = now;
|
|
47
|
+
if (timer === null) timer = setTimeout(flushPending, throttleMs - (now - lastFlushedAt));
|
|
48
|
+
}
|
|
49
|
+
childDoc.on("afterTransaction", handler);
|
|
50
|
+
return () => {
|
|
51
|
+
childDoc.off("afterTransaction", handler);
|
|
52
|
+
if (timer !== null) {
|
|
53
|
+
clearTimeout(timer);
|
|
54
|
+
flushPending();
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
//#endregion
|
|
60
|
+
export { attachUpdatedAtObserver };
|
|
61
|
+
//# sourceMappingURL=TreeTimestamps.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TreeTimestamps.js","names":[],"sources":["../../src/TreeTimestamps.ts"],"sourcesContent":["/**\n * TreeTimestamps\n *\n * Attaches an afterTransaction observer on a child Y.Doc so that whenever a\n * LOCAL edit is made, the `updatedAt` timestamp on the corresponding entry\n * in the root doc's `doc-tree` map is written.\n *\n * This propagates \"last edited\" timestamps to all peers via the root CRDT,\n * without requiring any server-side changes.\n *\n * Leading-edge + trailing-edge throttle (default 5 s window): the first\n * update flushes immediately so the \"last edited\" badge updates instantly;\n * follow-up updates within the window are coalesced into one trailing flush.\n */\n\nimport * as Y from \"yjs\";\n\nimport { patchEntry } from \"./DocUtils.ts\";\nimport type { OfflineStore } from \"./OfflineStore.ts\";\n\n/**\n * Attach an observer that writes `updatedAt` to the root doc-tree entry for\n * `childDocId` whenever the child doc receives a local edit.\n *\n * @param treeMap The root doc's \"doc-tree\" Y.Map.\n * @param childDocId The child document's UUID (key in treeMap).\n * @param childDoc The child Y.Doc to observe.\n * @param offlineStore The child provider's OfflineStore (used to detect\n * offline-replay origins and skip them). Pass null when\n * the offline store is disabled.\n * @param options Optional config. `throttleMs` controls the throttle\n * window (default 5000).\n * @returns Cleanup function — call on provider destroy. Flushes\n * any pending write before detaching.\n */\nexport function attachUpdatedAtObserver(\n\ttreeMap: Y.Map<any>,\n\tchildDocId: string,\n\tchildDoc: Y.Doc,\n\tofflineStore: OfflineStore | null,\n\toptions?: { throttleMs?: number },\n): () => void {\n\tconst throttleMs = options?.throttleMs ?? 5000;\n\n\tlet lastFlushedAt = 0;\n\tlet pendingTs = 0;\n\tlet timer: ReturnType<typeof setTimeout> | null = null;\n\n\tfunction writeTs(ts: number): void {\n\t\tconst raw = treeMap.get(childDocId);\n\t\tif (!raw) return;\n\t\t// Per-key set on the entry's nested Y.Map: the 5 s `updatedAt`\n\t\t// write no longer clobbers a concurrent parentId/label edit\n\t\t// (whole-entry-LWW fix, audit ⑦).\n\t\tpatchEntry(treeMap, childDocId, { updatedAt: ts });\n\t\tlastFlushedAt = ts;\n\t}\n\n\tfunction flushPending(): void {\n\t\ttimer = null;\n\t\tif (pendingTs === 0) return;\n\t\tconst ts = pendingTs;\n\t\tpendingTs = 0;\n\t\twriteTs(ts);\n\t}\n\n\tfunction handler(tr: Y.Transaction): void {\n\t\t// Only LOCAL edits stamp updatedAt. Remote updates (tr.local === false:\n\t\t// initial sync replay, other peers' edits, offline-store replay,\n\t\t// cross-tab broadcast) are stamped by the client that made them and the\n\t\t// timestamp propagates through the root CRDT — counting them here\n\t\t// turned \"last edited\" into \"last synced on this client\": merely\n\t\t// opening a doc bumped its updatedAt to now.\n\t\tif (!tr.local) return;\n\t\tif (offlineStore !== null && tr.origin === offlineStore) return;\n\t\t// No-op transactions (nothing actually changed) don't count as edits.\n\t\tif (tr.changed.size === 0) return;\n\n\t\tconst now = Date.now();\n\t\tif (now - lastFlushedAt >= throttleMs) {\n\t\t\t// Leading edge — flush immediately.\n\t\t\twriteTs(now);\n\t\t\treturn;\n\t\t}\n\t\t// Inside the throttle window — coalesce into a trailing flush.\n\t\tpendingTs = now;\n\t\tif (timer === null) {\n\t\t\ttimer = setTimeout(flushPending, throttleMs - (now - lastFlushedAt));\n\t\t}\n\t}\n\n\tchildDoc.on(\"afterTransaction\", handler);\n\n\treturn () => {\n\t\tchildDoc.off(\"afterTransaction\", handler);\n\t\tif (timer !== null) {\n\t\t\tclearTimeout(timer);\n\t\t\tflushPending();\n\t\t}\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,wBACf,SACA,YACA,UACA,cACA,SACa;CACb,MAAM,aAAa,SAAS,cAAc;CAE1C,IAAI,gBAAgB;CACpB,IAAI,YAAY;CAChB,IAAI,QAA8C;CAElD,SAAS,QAAQ,IAAkB;AAElC,MAAI,CADQ,QAAQ,IAAI,WAAW,CACzB;AAIV,aAAW,SAAS,YAAY,EAAE,WAAW,IAAI,CAAC;AAClD,kBAAgB;;CAGjB,SAAS,eAAqB;AAC7B,UAAQ;AACR,MAAI,cAAc,EAAG;EACrB,MAAM,KAAK;AACX,cAAY;AACZ,UAAQ,GAAG;;CAGZ,SAAS,QAAQ,IAAyB;AAOzC,MAAI,CAAC,GAAG,MAAO;AACf,MAAI,iBAAiB,QAAQ,GAAG,WAAW,aAAc;AAEzD,MAAI,GAAG,QAAQ,SAAS,EAAG;EAE3B,MAAM,MAAM,KAAK,KAAK;AACtB,MAAI,MAAM,iBAAiB,YAAY;AAEtC,WAAQ,IAAI;AACZ;;AAGD,cAAY;AACZ,MAAI,UAAU,KACb,SAAQ,WAAW,cAAc,cAAc,MAAM,eAAe;;AAItE,UAAS,GAAG,oBAAoB,QAAQ;AAExC,cAAa;AACZ,WAAS,IAAI,oBAAoB,QAAQ;AACzC,MAAI,UAAU,MAAM;AACnB,gBAAa,MAAM;AACnB,iBAAc"}
|
package/dist/esm/auth.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import * as decoding from "lib0/decoding";
|
|
2
|
+
import * as encoding from "lib0/encoding";
|
|
3
|
+
|
|
4
|
+
//#region packages/provider/src/auth.ts
|
|
5
|
+
let AuthMessageType = /* @__PURE__ */ function(AuthMessageType) {
|
|
6
|
+
AuthMessageType[AuthMessageType["Token"] = 0] = "Token";
|
|
7
|
+
AuthMessageType[AuthMessageType["PermissionDenied"] = 1] = "PermissionDenied";
|
|
8
|
+
AuthMessageType[AuthMessageType["Authenticated"] = 2] = "Authenticated";
|
|
9
|
+
return AuthMessageType;
|
|
10
|
+
}({});
|
|
11
|
+
const writeAuthentication = (encoder, auth) => {
|
|
12
|
+
encoding.writeVarUint(encoder, AuthMessageType.Token);
|
|
13
|
+
encoding.writeVarString(encoder, auth);
|
|
14
|
+
};
|
|
15
|
+
const writePermissionDenied = (encoder, reason) => {
|
|
16
|
+
encoding.writeVarUint(encoder, AuthMessageType.PermissionDenied);
|
|
17
|
+
encoding.writeVarString(encoder, reason);
|
|
18
|
+
};
|
|
19
|
+
const writeAuthenticated = (encoder, scope) => {
|
|
20
|
+
encoding.writeVarUint(encoder, AuthMessageType.Authenticated);
|
|
21
|
+
encoding.writeVarString(encoder, scope);
|
|
22
|
+
};
|
|
23
|
+
const writeTokenSyncRequest = (encoder) => {
|
|
24
|
+
encoding.writeVarUint(encoder, AuthMessageType.Token);
|
|
25
|
+
};
|
|
26
|
+
const readAuthMessage = (decoder, sendToken, permissionDeniedHandler, authenticatedHandler) => {
|
|
27
|
+
switch (decoding.readVarUint(decoder)) {
|
|
28
|
+
case AuthMessageType.Token:
|
|
29
|
+
sendToken();
|
|
30
|
+
break;
|
|
31
|
+
case AuthMessageType.PermissionDenied:
|
|
32
|
+
permissionDeniedHandler(decoding.readVarString(decoder));
|
|
33
|
+
break;
|
|
34
|
+
case AuthMessageType.Authenticated:
|
|
35
|
+
authenticatedHandler(decoding.readVarString(decoder));
|
|
36
|
+
break;
|
|
37
|
+
default:
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
//#endregion
|
|
42
|
+
export { AuthMessageType, readAuthMessage, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest };
|
|
43
|
+
//# sourceMappingURL=auth.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.js","names":[],"sources":["../../src/auth.ts"],"sourcesContent":["import * as encoding from \"lib0/encoding\";\nimport * as decoding from \"lib0/decoding\";\nimport type { AuthorizedScope } from \"./types.ts\";\n\nexport enum AuthMessageType {\n\tToken = 0,\n\tPermissionDenied = 1,\n\tAuthenticated = 2,\n}\n\nexport const writeAuthentication = (\n\tencoder: encoding.Encoder,\n\tauth: string,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.Token);\n\tencoding.writeVarString(encoder, auth);\n};\n\nexport const writePermissionDenied = (\n\tencoder: encoding.Encoder,\n\treason: string,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.PermissionDenied);\n\tencoding.writeVarString(encoder, reason);\n};\n\nexport const writeAuthenticated = (\n\tencoder: encoding.Encoder,\n\tscope: AuthorizedScope,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.Authenticated);\n\tencoding.writeVarString(encoder, scope);\n};\n\nexport const writeTokenSyncRequest = (\n\tencoder: encoding.Encoder,\n) => {\n\tencoding.writeVarUint(encoder, AuthMessageType.Token);\n};\n\nexport const readAuthMessage = (\n\tdecoder: decoding.Decoder,\n\tsendToken: () => void,\n\tpermissionDeniedHandler: (reason: string) => void,\n\tauthenticatedHandler: (scope: string) => void,\n) => {\n\tswitch (decoding.readVarUint(decoder)) {\n\t\tcase AuthMessageType.Token: {\n\t\t\tsendToken();\n\t\t\tbreak;\n\t\t}\n\t\tcase AuthMessageType.PermissionDenied: {\n\t\t\tpermissionDeniedHandler(decoding.readVarString(decoder));\n\t\t\tbreak;\n\t\t}\n\t\tcase AuthMessageType.Authenticated: {\n\t\t\tauthenticatedHandler(decoding.readVarString(decoder));\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t}\n};\n"],"mappings":";;;;AAIA,IAAY,kBAAL;AACN;AACA;AACA;;KACA;AAED,MAAa,uBACZ,SACA,SACI;AACJ,UAAS,aAAa,SAAS,gBAAgB,MAAM;AACrD,UAAS,eAAe,SAAS,KAAK;;AAGvC,MAAa,yBACZ,SACA,WACI;AACJ,UAAS,aAAa,SAAS,gBAAgB,iBAAiB;AAChE,UAAS,eAAe,SAAS,OAAO;;AAGzC,MAAa,sBACZ,SACA,UACI;AACJ,UAAS,aAAa,SAAS,gBAAgB,cAAc;AAC7D,UAAS,eAAe,SAAS,MAAM;;AAGxC,MAAa,yBACZ,YACI;AACJ,UAAS,aAAa,SAAS,gBAAgB,MAAM;;AAGtD,MAAa,mBACZ,SACA,WACA,yBACA,yBACI;AACJ,SAAQ,SAAS,YAAY,QAAQ,EAArC;EACC,KAAK,gBAAgB;AACpB,cAAW;AACX;EAED,KAAK,gBAAgB;AACpB,2BAAwB,SAAS,cAAc,QAAQ,CAAC;AACxD;EAED,KAAK,gBAAgB;AACpB,wBAAqB,SAAS,cAAc,QAAQ,CAAC;AACrD;EAED"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
//#region packages/provider/src/awarenessStatesToArray.ts
|
|
2
|
+
const awarenessStatesToArray = (states) => {
|
|
3
|
+
return Array.from(states.entries()).map(([key, value]) => {
|
|
4
|
+
return {
|
|
5
|
+
clientId: key,
|
|
6
|
+
...value
|
|
7
|
+
};
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
//#endregion
|
|
12
|
+
export { awarenessStatesToArray };
|
|
13
|
+
//# sourceMappingURL=awarenessStatesToArray.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"awarenessStatesToArray.js","names":[],"sources":["../../src/awarenessStatesToArray.ts"],"sourcesContent":["export const awarenessStatesToArray = (\n\tstates: Map<number, Record<string, any>>,\n) => {\n\treturn Array.from(states.entries()).map(([key, value]) => {\n\t\treturn {\n\t\t\tclientId: key,\n\t\t\t...value,\n\t\t};\n\t});\n};\n"],"mappings":";AAAA,MAAa,0BACZ,WACI;AACJ,QAAO,MAAM,KAAK,OAAO,SAAS,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW;AACzD,SAAO;GACN,UAAU;GACV,GAAG;GACH;GACA"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
2
|
+
|
|
3
|
+
//#region packages/provider/src/docIds.ts
|
|
4
|
+
/**
|
|
5
|
+
* Deterministic document ids derived from public keys — a LEAF module.
|
|
6
|
+
*
|
|
7
|
+
* These lived in `IdentityDoc.ts`, which imports the identity provider and
|
|
8
|
+
* `webrtc/AbracadabraWebRTC` (and through it the E2EE channel and
|
|
9
|
+
* `@noble/curves`). `AbracadabraClient` and every chat surface need only the
|
|
10
|
+
* two hashes, so importing them from there put the whole WebRTC stack in the
|
|
11
|
+
* entry chunk of every app. `IdentityDoc.ts` re-exports both unchanged.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Derives a deterministic UUID from an Ed25519 account-level public key.
|
|
15
|
+
*
|
|
16
|
+
* The result is a valid UUID v5-style string that any device sharing the
|
|
17
|
+
* same identity can independently compute. The `abracadabra:identity:`
|
|
18
|
+
* prefix prevents collisions with randomly generated doc UUIDs.
|
|
19
|
+
*
|
|
20
|
+
* @param publicKeyB64 Base64url-encoded Ed25519 public key (32 bytes).
|
|
21
|
+
*/
|
|
22
|
+
function deriveIdentityDocId(publicKeyB64) {
|
|
23
|
+
const hash = sha256(new TextEncoder().encode(`abracadabra:identity:${publicKeyB64}`));
|
|
24
|
+
const bytes = new Uint8Array(hash.buffer, hash.byteOffset, 16);
|
|
25
|
+
bytes[6] = bytes[6] & 15 | 80;
|
|
26
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
27
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
28
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Derives a deterministic UUID for the DM doc between two participants
|
|
32
|
+
* (independent of which side computes it). The two pubkeys are sorted
|
|
33
|
+
* lexicographically before hashing so both clients produce the same id —
|
|
34
|
+
* this lets `findOrCreateDmDoc` race-tolerantly create-or-claim the doc
|
|
35
|
+
* without coordinating; whichever client wins the create-with-id call
|
|
36
|
+
* is fine, the other gets a Conflict and reuses the existing id.
|
|
37
|
+
*
|
|
38
|
+
* @param pubkeyA Base64url-encoded Ed25519 public key (32 bytes).
|
|
39
|
+
* @param pubkeyB Base64url-encoded Ed25519 public key (32 bytes).
|
|
40
|
+
*/
|
|
41
|
+
function deriveDmDocId(pubkeyA, pubkeyB) {
|
|
42
|
+
const [first, second] = [pubkeyA, pubkeyB].sort();
|
|
43
|
+
const hash = sha256(new TextEncoder().encode(`abracadabra:dm:${first}:${second}`));
|
|
44
|
+
const bytes = new Uint8Array(hash.buffer, hash.byteOffset, 16);
|
|
45
|
+
bytes[6] = bytes[6] & 15 | 80;
|
|
46
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
47
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
48
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
//#endregion
|
|
52
|
+
export { deriveDmDocId, deriveIdentityDocId };
|
|
53
|
+
//# sourceMappingURL=docIds.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"docIds.js","names":[],"sources":["../../src/docIds.ts"],"sourcesContent":["/**\n * Deterministic document ids derived from public keys — a LEAF module.\n *\n * These lived in `IdentityDoc.ts`, which imports the identity provider and\n * `webrtc/AbracadabraWebRTC` (and through it the E2EE channel and\n * `@noble/curves`). `AbracadabraClient` and every chat surface need only the\n * two hashes, so importing them from there put the whole WebRTC stack in the\n * entry chunk of every app. `IdentityDoc.ts` re-exports both unchanged.\n */\nimport { sha256 } from \"@noble/hashes/sha2.js\";\n\n// ── Identity Doc ID Derivation ─────────────────────────────────────────────\n\n/**\n * Derives a deterministic UUID from an Ed25519 account-level public key.\n *\n * The result is a valid UUID v5-style string that any device sharing the\n * same identity can independently compute. The `abracadabra:identity:`\n * prefix prevents collisions with randomly generated doc UUIDs.\n *\n * @param publicKeyB64 Base64url-encoded Ed25519 public key (32 bytes).\n */\nexport function deriveIdentityDocId(publicKeyB64: string): string {\n\tconst hash = sha256(\n\t\tnew TextEncoder().encode(`abracadabra:identity:${publicKeyB64}`),\n\t);\n\tconst bytes = new Uint8Array(hash.buffer, hash.byteOffset, 16);\n\t// Set UUID version 5 + variant 1 bits.\n\tbytes[6] = (bytes[6] & 0x0f) | 0x50;\n\tbytes[8] = (bytes[8] & 0x3f) | 0x80;\n\tconst hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\n\t\t\"\",\n\t);\n\treturn `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;\n}\n\n/**\n * Derives a deterministic UUID for the DM doc between two participants\n * (independent of which side computes it). The two pubkeys are sorted\n * lexicographically before hashing so both clients produce the same id —\n * this lets `findOrCreateDmDoc` race-tolerantly create-or-claim the doc\n * without coordinating; whichever client wins the create-with-id call\n * is fine, the other gets a Conflict and reuses the existing id.\n *\n * @param pubkeyA Base64url-encoded Ed25519 public key (32 bytes).\n * @param pubkeyB Base64url-encoded Ed25519 public key (32 bytes).\n */\nexport function deriveDmDocId(pubkeyA: string, pubkeyB: string): string {\n\tconst [first, second] = [pubkeyA, pubkeyB].sort();\n\tconst hash = sha256(\n\t\tnew TextEncoder().encode(`abracadabra:dm:${first}:${second}`),\n\t);\n\tconst bytes = new Uint8Array(hash.buffer, hash.byteOffset, 16);\n\tbytes[6] = (bytes[6] & 0x0f) | 0x50;\n\tbytes[8] = (bytes[8] & 0x3f) | 0x80;\n\tconst hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\n\t\t\"\",\n\t);\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AI,MAAM,IAAI,GAAG,CAAC,GAAG,IAAI,MAAM,IAAI,GAAG"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
//#region packages/provider/src/encryptedContent.ts
|
|
2
|
+
/**
|
|
3
|
+
* The `e2e:1:` chat envelope test — a LEAF module.
|
|
4
|
+
*
|
|
5
|
+
* Every chat surface calls this per message to decide whether it needs the
|
|
6
|
+
* crypto at all. It used to live in `EncryptedChatClient.ts`, which imports
|
|
7
|
+
* `DocKeyManager` and through it `@noble/curves`, so the question "is this
|
|
8
|
+
* encrypted?" cost the answer's whole dependency graph.
|
|
9
|
+
*/
|
|
10
|
+
const E2E_SENTINEL = "e2e:1:";
|
|
11
|
+
/**
|
|
12
|
+
* Returns true if `content` is an `e2e:1:` envelope. Cleartext content always
|
|
13
|
+
* returns false.
|
|
14
|
+
*/
|
|
15
|
+
function isEncryptedContent(content) {
|
|
16
|
+
return typeof content === "string" && content.startsWith(E2E_SENTINEL);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
//#endregion
|
|
20
|
+
export { E2E_SENTINEL, isEncryptedContent };
|
|
21
|
+
//# sourceMappingURL=encryptedContent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"encryptedContent.js","names":[],"sources":["../../src/encryptedContent.ts"],"sourcesContent":["/**\n * The `e2e:1:` chat envelope test — a LEAF module.\n *\n * Every chat surface calls this per message to decide whether it needs the\n * crypto at all. It used to live in `EncryptedChatClient.ts`, which imports\n * `DocKeyManager` and through it `@noble/curves`, so the question \"is this\n * encrypted?\" cost the answer's whole dependency graph.\n */\nexport const E2E_SENTINEL = \"e2e:1:\";\n\n/**\n * Returns true if `content` is an `e2e:1:` envelope. Cleartext content always\n * returns false.\n */\nexport function isEncryptedContent(content: string): boolean {\n\treturn typeof content === \"string\" && content.startsWith(E2E_SENTINEL);\n}\n"],"mappings":";;;;;;;;;AAQA,MAAa,eAAe;;;;;AAM5B,SAAgB,mBAAmB,SAA0B;AAC5D,QAAO,OAAO,YAAY,YAAY,QAAQ,WAAW,aAAa"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { awarenessStatesToArray } from "./awarenessStatesToArray.js";
|
|
2
|
+
import { Kind, MessageType, SERVER_ROOT_ID, WebSocketStatus, WsReadyStates } from "./types.js";
|
|
3
|
+
import { HIDE_GRACE_MS, LifecycleGate, ManualVisibilitySource, getLifecycleGate, setLifecycleGate } from "./LifecycleGate.js";
|
|
4
|
+
import { AbracadabraWS, HocuspocusProviderWebsocket } from "./AbracadabraWS.js";
|
|
5
|
+
import { AuthMessageType, readAuthMessage, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest } from "./auth.js";
|
|
6
|
+
import { RPC_PREFIX, RpcClient, RpcError } from "./RpcClient.js";
|
|
7
|
+
import { QUERY_PREFIX, QueryClient, QueryError } from "./QueryClient.js";
|
|
8
|
+
import { AbracadabraBaseProvider, AwarenessError, HocuspocusProvider } from "./AbracadabraBaseProvider.js";
|
|
9
|
+
import { OfflineStore } from "./OfflineStore.js";
|
|
10
|
+
import { SubdocMessage } from "./OutgoingMessages/SubdocMessage.js";
|
|
11
|
+
import { AbracadabraProvider } from "./AbracadabraProvider.js";
|
|
12
|
+
import { dropCachesIfServerReplaced, forgetServerIdentity, isServerScopedStore } from "./ServerReset.js";
|
|
13
|
+
import { deriveDmDocId, deriveIdentityDocId } from "./docIds.js";
|
|
14
|
+
import { AbracadabraClient } from "./AbracadabraClient.js";
|
|
15
|
+
import { LocalStorageDeviceSessionStorage, TokenManager } from "./TokenManager.js";
|
|
16
|
+
import { ConnectionTimeout, Forbidden, MessageTooBig, ResetConnection, Unauthorized } from "./CloseEvents.js";
|
|
17
|
+
import { deriveSeedWrappingKey, generateMnemonic, mnemonicToEd25519Seed, mnemonicToKeyPair, unwrapSeed, validateMnemonic, wordlist, wrapSeed } from "./MnemonicKeyDerivation.js";
|
|
18
|
+
import { CryptoIdentityKeystore } from "./CryptoIdentityKeystore.js";
|
|
19
|
+
import { deterministicKeypair, loadOrCreateKeyFile, loginOrRegisterWithKey, loginOrRegisterWithPolicy, makeChallengeSigner, signChallengeWithSeed } from "./NodeIdentity.js";
|
|
20
|
+
import { isPlaceholderLabel, makeEntryMap, normalizeRootId, patchEntry, readEntries, toPlain, waitForSync, withTimeout } from "./DocUtils.js";
|
|
21
|
+
import { openSyncedProvider, pickEntrySpace } from "./NodeConnect.js";
|
|
22
|
+
import { addServer, defaultKeyFileFor, loadServerRegistry, migrateLegacyDefault, removeServer, resolveServer, saveServerRegistry, serverRegistryPath, setDefault } from "./ServerRegistry.js";
|
|
23
|
+
import { DocumentCache } from "./DocumentCache.js";
|
|
24
|
+
import { SearchIndex } from "./SearchIndex.js";
|
|
25
|
+
import { FileBlobStore } from "./FileBlobStore.js";
|
|
26
|
+
import { DocKeyManager } from "./DocKeyManager.js";
|
|
27
|
+
import { EncryptedYMap, EncryptedYText, decryptField, encryptField, makeEncryptedYMap, makeEncryptedYText } from "./EncryptedY.js";
|
|
28
|
+
import { E2EOfflineStore } from "./E2EOfflineStore.js";
|
|
29
|
+
import { E2EAbracadabraProvider } from "./E2EAbracadabraProvider.js";
|
|
30
|
+
import { attachUpdatedAtObserver } from "./TreeTimestamps.js";
|
|
31
|
+
import { BackgroundSyncPersistence } from "./BackgroundSyncPersistence.js";
|
|
32
|
+
import { BackgroundSyncManager } from "./BackgroundSyncManager.js";
|
|
33
|
+
import { SignalingSocket } from "./webrtc/SignalingSocket.js";
|
|
34
|
+
import { CHANNEL_NAMES, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS } from "./webrtc/types.js";
|
|
35
|
+
import { DataChannelRouter, KEY_EXCHANGE_CHANNEL } from "./webrtc/DataChannelRouter.js";
|
|
36
|
+
import { PeerConnection } from "./webrtc/PeerConnection.js";
|
|
37
|
+
import { YjsDataChannel } from "./webrtc/YjsDataChannel.js";
|
|
38
|
+
import { FileTransferChannel, FileTransferHandle } from "./webrtc/FileTransferChannel.js";
|
|
39
|
+
import { E2EEChannel } from "./webrtc/E2EEChannel.js";
|
|
40
|
+
import { AbracadabraWebRTC } from "./webrtc/AbracadabraWebRTC.js";
|
|
41
|
+
import { ManualSignaling } from "./webrtc/ManualSignaling.js";
|
|
42
|
+
import { DevicePairingChannel } from "./webrtc/DevicePairingChannel.js";
|
|
43
|
+
import { BroadcastChannelSync } from "./sync/BroadcastChannelSync.js";
|
|
44
|
+
import { IdentityDocProvider } from "./IdentityDoc.js";
|
|
45
|
+
import { DeviceRegistrationService } from "./DeviceRegistrationService.js";
|
|
46
|
+
import { ChatClient } from "./ChatClient.js";
|
|
47
|
+
import { isEncryptedContent } from "./encryptedContent.js";
|
|
48
|
+
import { ChannelKeyResolver, EncryptedChatClient, decryptChatContent, encryptChatContent } from "./EncryptedChatClient.js";
|
|
49
|
+
import { foldRecords, recordFromYAny } from "./messageRecord.js";
|
|
50
|
+
import { NotificationsClient } from "./NotificationsClient.js";
|
|
51
|
+
import { GEO_TYPE_META_SCHEMAS, PAGE_TYPES, TYPE_ALIASES, resolvePageType } from "./DocTypes.js";
|
|
52
|
+
import { TypedDocTypeMismatchError } from "./SchemaTypes.js";
|
|
53
|
+
import { TreeManager } from "./TreeManager.js";
|
|
54
|
+
import { collectMediaFileBlocks, reconcileDocCover } from "./CoverReconcile.js";
|
|
55
|
+
import { buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, filenameToLabel, parseFrontmatter, populateYDocFromMarkdown, readBlocksFromFragment, yjsToMarkdown } from "./DocConverters.js";
|
|
56
|
+
import { ContentManager } from "./ContentManager.js";
|
|
57
|
+
import { MetaManager, MetaValidationError } from "./MetaManager.js";
|
|
58
|
+
import { DocumentManager } from "./DocumentManager.js";
|
|
59
|
+
import { diff, installPerfCounters, instrumentSocket, isInstalled, reset, snapshot, uninstall } from "./PerfCounters.js";
|
|
60
|
+
|
|
61
|
+
export { AbracadabraBaseProvider, AbracadabraClient, AbracadabraProvider, AbracadabraWS, AbracadabraWebRTC, AuthMessageType, AwarenessError, BackgroundSyncManager, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, ChatClient, ConnectionTimeout, ContentManager, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, DevicePairingChannel, DeviceRegistrationService, DocKeyManager, DocumentCache, DocumentManager, E2EAbracadabraProvider, E2EEChannel, E2EOfflineStore, EncryptedChatClient, EncryptedYMap, EncryptedYText, FileBlobStore, FileTransferChannel, FileTransferHandle, Forbidden, GEO_TYPE_META_SCHEMAS, HIDE_GRACE_MS, HocuspocusProvider, HocuspocusProviderWebsocket, IdentityDocProvider, KEY_EXCHANGE_CHANNEL, Kind, LifecycleGate, LocalStorageDeviceSessionStorage, ManualSignaling, ManualVisibilitySource, MessageTooBig, MessageType, MetaManager, MetaValidationError, NotificationsClient, OfflineStore, PAGE_TYPES, PeerConnection, QUERY_PREFIX, QueryClient, QueryError, RPC_PREFIX, ResetConnection, RpcClient, RpcError, SERVER_ROOT_ID, SearchIndex, SignalingSocket, SubdocMessage, TYPE_ALIASES, TokenManager, TreeManager, TypedDocTypeMismatchError, Unauthorized, WebSocketStatus, WsReadyStates, YjsDataChannel, addServer, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, defaultKeyFileFor, deriveDmDocId, deriveIdentityDocId, deriveSeedWrappingKey, deterministicKeypair, dropCachesIfServerReplaced, encryptChatContent, encryptField, filenameToLabel, foldRecords, forgetServerIdentity, generateMnemonic, getLifecycleGate, installPerfCounters, isEncryptedContent, isPlaceholderLabel, isServerScopedStore, loadOrCreateKeyFile, loadServerRegistry, loginOrRegisterWithKey, loginOrRegisterWithPolicy, makeChallengeSigner, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, migrateLegacyDefault, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, openSyncedProvider, parseFrontmatter, patchEntry, isInstalled as perfCountersInstalled, diff as perfDiff, instrumentSocket as perfInstrumentSocket, snapshot as perfSnapshot, pickEntrySpace, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, readEntries, reconcileDocCover, recordFromYAny, removeServer, reset as resetPerfCounters, resolvePageType, resolveServer, saveServerRegistry, serverRegistryPath, setDefault, setLifecycleGate, signChallengeWithSeed, toPlain, uninstall as uninstallPerfCounters, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
//#region packages/provider/src/messageRecord.ts
|
|
2
|
+
/**
|
|
3
|
+
* Fold an ordered list of records (oldest-first) into the visible
|
|
4
|
+
* messages a UI should render. Records may come from one period or
|
|
5
|
+
* across multiple periods concatenated in time order.
|
|
6
|
+
*/
|
|
7
|
+
function foldRecords(records) {
|
|
8
|
+
const tombstoned = /* @__PURE__ */ new Set();
|
|
9
|
+
for (const r of records) if (r.record_kind === "tombstone" && r.target_id) tombstoned.add(r.target_id);
|
|
10
|
+
const base = /* @__PURE__ */ new Map();
|
|
11
|
+
for (const r of records) {
|
|
12
|
+
if ((r.record_kind ?? "message") !== "message") continue;
|
|
13
|
+
if (tombstoned.has(r.id)) continue;
|
|
14
|
+
base.set(r.id, {
|
|
15
|
+
id: r.id,
|
|
16
|
+
channel: r.channel_doc_id,
|
|
17
|
+
senderId: r.sender_id,
|
|
18
|
+
content: r.content,
|
|
19
|
+
createdAt: r.ts,
|
|
20
|
+
...r.reply_to ? { replyTo: r.reply_to } : {}
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
for (const r of records) {
|
|
24
|
+
if (r.record_kind !== "edit" || !r.target_id) continue;
|
|
25
|
+
if (tombstoned.has(r.target_id)) continue;
|
|
26
|
+
const original = base.get(r.target_id);
|
|
27
|
+
if (!original) continue;
|
|
28
|
+
original.content = r.content;
|
|
29
|
+
original.editedAt = r.ts;
|
|
30
|
+
}
|
|
31
|
+
return [...base.values()].sort((a, b) => a.createdAt - b.createdAt);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Decode whatever the Y.Array stored for an entry into a MessageRecord.
|
|
35
|
+
* Note: the server stamps `ts` server-side via `Any::BigInt(now_ts_ms())`,
|
|
36
|
+
* so on the wire it round-trips as a JS BigInt — `typeof` is `'bigint'`,
|
|
37
|
+
* not `'number'`. Accept both and coerce.
|
|
38
|
+
*/
|
|
39
|
+
function recordFromYAny(any) {
|
|
40
|
+
if (!any || typeof any !== "object") return null;
|
|
41
|
+
const o = any;
|
|
42
|
+
const tsRaw = o.ts;
|
|
43
|
+
const tsIsValid = typeof tsRaw === "number" || typeof tsRaw === "bigint";
|
|
44
|
+
if (typeof o.id !== "string" || typeof o.sender_id !== "string" || typeof o.channel_doc_id !== "string" || !tsIsValid) return null;
|
|
45
|
+
const ts = typeof tsRaw === "bigint" ? Number(tsRaw) : tsRaw;
|
|
46
|
+
return {
|
|
47
|
+
record_kind: typeof o.record_kind === "string" ? o.record_kind : "message",
|
|
48
|
+
id: o.id,
|
|
49
|
+
target_id: typeof o.target_id === "string" ? o.target_id : void 0,
|
|
50
|
+
sender_id: o.sender_id,
|
|
51
|
+
channel_doc_id: o.channel_doc_id,
|
|
52
|
+
period_id: typeof o.period_id === "string" ? o.period_id : "",
|
|
53
|
+
ts,
|
|
54
|
+
content: typeof o.content === "string" ? o.content : "",
|
|
55
|
+
mentions: Array.isArray(o.mentions) ? o.mentions : [],
|
|
56
|
+
reply_to: typeof o.reply_to === "string" ? o.reply_to : null,
|
|
57
|
+
sig: typeof o.sig === "string" ? o.sig : void 0,
|
|
58
|
+
server_sig: typeof o.server_sig === "string" ? o.server_sig : void 0
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
//#endregion
|
|
63
|
+
export { foldRecords, recordFromYAny };
|
|
64
|
+
//# sourceMappingURL=messageRecord.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"messageRecord.js","names":[],"sources":["../../src/messageRecord.ts"],"sourcesContent":["/**\n * Decode + fold message records from a period doc's `messages` Y.Array\n * into the flat `ChatMessage[]` shape the dashboard renders.\n *\n * The server appends three kinds of records to the array (see\n * `abracadabra-rs/crates/abracadabra/src/messages.rs`):\n *\n * - `record_kind: \"message\"` — a real message (default kind).\n * - `record_kind: \"edit\"` — an updated version of `target_id`.\n * - `record_kind: \"tombstone\"` — `target_id` is deleted.\n *\n * Folding rules:\n * - For each `target_id`, apply edits in `ts` order; the *last* edit's\n * content wins. The original message's id, sender_id, and ts stay.\n * `editedAt` is the latest edit's ts.\n * - Any target_id with a tombstone is dropped from the output entirely.\n * - Records without record_kind default to \"message\" (back-compat).\n *\n * Cross-period folding: edits and tombstones can in principle target a\n * message in a *prior* period (e.g. user edits a message that lived on\n * the previous period after rollover). Callers that paginate across\n * periods should fold the joined list, not each period independently.\n */\n\nexport interface MessageRecord {\n record_kind?: 'message' | 'edit' | 'tombstone'\n id: string\n target_id?: string\n sender_id: string\n channel_doc_id: string\n period_id: string\n ts: number\n content: string\n mentions?: string[]\n reply_to?: string | null\n sig?: string\n server_sig?: string\n}\n\nexport interface FoldedMessage {\n id: string\n channel: string\n senderId: string\n senderName?: string\n content: string\n createdAt: number\n /** Set if the message has been edited at least once. */\n editedAt?: number\n /** Reply target message id, if any. */\n replyTo?: string\n}\n\n/**\n * Fold an ordered list of records (oldest-first) into the visible\n * messages a UI should render. Records may come from one period or\n * across multiple periods concatenated in time order.\n */\nexport function foldRecords(records: MessageRecord[]): FoldedMessage[] {\n const tombstoned = new Set<string>()\n for (const r of records) {\n if (r.record_kind === 'tombstone' && r.target_id) tombstoned.add(r.target_id)\n }\n\n const base = new Map<string, FoldedMessage>()\n for (const r of records) {\n const kind = r.record_kind ?? 'message'\n if (kind !== 'message') continue\n if (tombstoned.has(r.id)) continue\n base.set(r.id, {\n id: r.id,\n channel: r.channel_doc_id,\n senderId: r.sender_id,\n content: r.content,\n createdAt: r.ts,\n ...(r.reply_to ? { replyTo: r.reply_to } : {}),\n })\n }\n\n for (const r of records) {\n if (r.record_kind !== 'edit' || !r.target_id) continue\n if (tombstoned.has(r.target_id)) continue\n const original = base.get(r.target_id)\n if (!original) continue\n original.content = r.content\n original.editedAt = r.ts\n }\n\n return [...base.values()].sort((a, b) => a.createdAt - b.createdAt)\n}\n\n/**\n * Decode whatever the Y.Array stored for an entry into a MessageRecord.\n * Note: the server stamps `ts` server-side via `Any::BigInt(now_ts_ms())`,\n * so on the wire it round-trips as a JS BigInt — `typeof` is `'bigint'`,\n * not `'number'`. Accept both and coerce.\n */\nexport function recordFromYAny(any: unknown): MessageRecord | null {\n if (!any || typeof any !== 'object') return null\n const o = any as Record<string, unknown>\n const tsRaw = o.ts\n const tsIsValid = typeof tsRaw === 'number' || typeof tsRaw === 'bigint'\n if (typeof o.id !== 'string' || typeof o.sender_id !== 'string'\n || typeof o.channel_doc_id !== 'string' || !tsIsValid) {\n return null\n }\n const ts = typeof tsRaw === 'bigint' ? Number(tsRaw) : (tsRaw as number)\n return {\n record_kind: typeof o.record_kind === 'string' ? o.record_kind as MessageRecord['record_kind'] : 'message',\n id: o.id,\n target_id: typeof o.target_id === 'string' ? o.target_id : undefined,\n sender_id: o.sender_id,\n channel_doc_id: o.channel_doc_id,\n period_id: typeof o.period_id === 'string' ? o.period_id : '',\n ts,\n content: typeof o.content === 'string' ? o.content : '',\n mentions: Array.isArray(o.mentions) ? o.mentions as string[] : [],\n reply_to: typeof o.reply_to === 'string' ? o.reply_to : null,\n sig: typeof o.sig === 'string' ? o.sig : undefined,\n server_sig: typeof o.server_sig ===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