@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.
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 @@
1
+ {"version":3,"file":"AbracadabraClient.js","names":[],"sources":["../../src/AbracadabraClient.ts"],"sourcesContent":["import type {\n\tUserProfile,\n\tDocumentMeta,\n\tUploadMeta,\n\tUploadInfo,\n\tThumbnailOptions,\n\tStreamTokenInfo,\n\tPublicKeyInfo,\n\tPermissionEntry,\n\tEffectivePermissionsResponse,\n\tHealthStatus,\n\tReadyzStatus,\n\tServerInfo,\n\tInviteRow,\n\tSnapshotMeta,\n\tSnapshotData,\n\tSnapshotCreateResult,\n\tSnapshotRestoreResult,\n\tSnapshotForkResult,\n\tDocBacklink,\n\tDocSearchHit,\n\tAuditLogEntry,\n\tAuditQueryOpts,\n\tAuditVerifyResult,\n\tAdminConfigField,\n\tEnvSnapshotResponse,\n} from \"./types.ts\";\nimport { Kind, SERVER_ROOT_ID } from \"./types.ts\";\nimport type { DocEncryptionInfo } from \"./types.ts\";\nimport type { DocumentCache } from \"./DocumentCache.ts\";\nimport type { ServerResetOutcome } from \"./ServerReset.ts\";\nimport { dropCachesIfServerReplaced } from \"./ServerReset.ts\";\nimport { deriveDmDocId } from \"./docIds.ts\";\n\nfunction fromBase64(b64: string): Uint8Array {\n\treturn Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\n/**\n * Decode a base64url-encoded string (e.g. a JWT header/payload segment) to\n * UTF-8 text. `atob` only accepts standard base64, so we translate the\n * url-safe alphabet (`-`/`_`) and re-pad before decoding — otherwise a\n * perfectly valid token whose payload happens to contain `-` or `_` throws\n * and gets misclassified as invalid/expired.\n */\nfunction decodeBase64UrlToString(b64url: string): string {\n\tlet b64 = b64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst pad = b64.length % 4;\n\tif (pad) b64 += \"=\".repeat(4 - pad);\n\tconst bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n\treturn new TextDecoder().decode(bytes);\n}\n\n/**\n * Reason classifications surfaced to `onAuthFailed`. Consumers can decide\n * whether to silently re-register the keypair (`user_not_found`) or\n * surface a hard block (`account_revoked`, `forbidden`).\n */\nexport type AuthFailureReason =\n\t| \"user_not_found\"\n\t| \"account_revoked\"\n\t| \"forbidden\"\n\t| \"unauthorized\";\n\nexport interface AuthFailureContext {\n\t/** HTTP status code from the failed request. */\n\tstatus: number;\n\t/** Server-provided error message verbatim. */\n\tmessage: string;\n\t/** Best-guess classification from the message text. */\n\treason: AuthFailureReason;\n\t/** Method + path of the failed request, useful for debugging. */\n\tmethod: string;\n\tpath: string;\n}\n\nexport interface AbracadabraClientConfig {\n\t/** Server base URL (http or https). WebSocket URL is derived automatically. */\n\turl: string;\n\t/** Initial JWT token. If omitted and persistAuth is true, loads from storage. */\n\ttoken?: string;\n\t/** Persist JWT to localStorage for stay-logged-in. Default: true in browser. */\n\tpersistAuth?: boolean;\n\t/** localStorage key for token persistence. Default: \"abracadabra:auth\". */\n\tstorageKey?: string;\n\t/** Custom fetch implementation (useful for Node.js or testing). */\n\tfetch?: typeof globalThis.fetch;\n\t/**\n\t * Optional metadata cache. When provided, read methods (getDoc, listChildren,\n\t * getMe, listPermissions, listUploads) check the cache before hitting the\n\t * network. Write methods (deleteDoc, upload, deleteUpload) invalidate affected\n\t * cache entries automatically.\n\t */\n\tcache?: DocumentCache;\n\t/**\n\t * Called whenever a REST call returns 401/403 with a recoverable reason\n\t * (typically \"user not found\" — server's DB was wiped or repointed).\n\t * Consumers wire this to their reauth path (in cou-sh: `_reauthFn`)\n\t * so silently-failing background fetches still trigger key re-registration\n\t * without waiting for the next WS action to surface the problem.\n\t *\n\t * The callback runs OUT-OF-BAND of the failing request — the original\n\t * Promise still rejects so callers handle their own error path.\n\t * Long-running auth handlers should debounce or short-circuit duplicate\n\t * concurrent invocations.\n\t */\n\tonAuthFailed?: (ctx: AuthFailureContext) => void;\n\t/**\n\t * How long before a token's `exp` the session is re-minted, in ms.\n\t *\n\t * Only meaningful once a session renewer is installed — which\n\t * {@link AbracadabraClient.loginWithKey} does for you. Capped at a third of\n\t * the token's own lifetime, so a server issuing short-lived tokens is not\n\t * re-authenticated on every check.\n\t *\n\t * Default 20 minutes: comfortably inside the server's 4-hour crypto-auth\n\t * TTL and wider than any polling interval a consumer is likely to run.\n\t */\n\ttokenRenewMarginMs?: number;\n\t/**\n\t * Fallback interval, in ms, for a token whose `exp` cannot be read.\n\t * Default 60s.\n\t *\n\t * Renewal is normally scheduled from the token's own expiry, so this is not\n\t * a poll. `0` disables the timer entirely — the session is then renewed\n\t * only on demand (before a socket handshake, or an explicit\n\t * {@link AbracadabraClient.ensureFreshToken}).\n\t */\n\ttokenRenewCheckMs?: number;\n}\n\n/**\n * Read a JWT's `exp` / `iat` claims, in ms. `0` for anything unreadable.\n *\n * Deliberately tolerant: a token this cannot parse is treated as expiring now,\n * which costs one extra handshake and never costs a dead session.\n */\nfunction readJwtTimes(token: string | null): { exp: number; iat: number } {\n\tif (!token) return { exp: 0, iat: 0 };\n\tconst payload = token.split(\".\")[1];\n\tif (!payload) return { exp: 0, iat: 0 };\n\ttry {\n\t\tconst claims = JSON.parse(decodeBase64UrlToString(payload)) as {\n\t\t\texp?: unknown;\n\t\t\tiat?: unknown;\n\t\t};\n\t\treturn {\n\t\t\texp: typeof claims.exp === \"number\" ? claims.exp * 1000 : 0,\n\t\t\tiat: typeof claims.iat === \"number\" ? claims.iat * 1000 : 0,\n\t\t};\n\t} catch {\n\t\treturn { exp: 0, iat: 0 };\n\t}\n}\n\nexport class AbracadabraClient {\n\tprivate _token: string | null;\n\tprivate readonly baseUrl: string;\n\tprivate readonly persistAuth: boolean;\n\tprivate readonly storageKey: string;\n\tprivate readonly _fetch: typeof globalThis.fetch;\n\treadonly cache: DocumentCache | null;\n\tprivate readonly _onAuthFailed: ((ctx: AuthFailureContext) => void) | null;\n\t/** Single-flight for root listings (`/docs?root=true`) — the per-row\n\t * permission cascade makes this a multi-second / hundreds-of-KB call on\n\t * a busy server, and a connect burst fires several identical ones.\n\t * Keyed by the kind filter; cleared when the request settles. */\n\tprivate readonly rootListInflight = new Map<\n\t\tstring,\n\t\tPromise<DocumentMeta[]>\n\t>();\n\t/** Cached media-stream grants (`getStreamUrl`), keyed `docId/uploadId`.\n\t * Re-minted just before expiry and dropped whenever the session token\n\t * changes — a stream token inherits the identity that minted it. */\n\tprivate readonly streamTokens = new Map<\n\t\tstring,\n\t\t{ url: string; expiresAt: number }\n\t>();\n\t/** In-flight mints, keyed like `streamTokens` — collapses the burst a page\n\t * of media blocks produces into one request per upload. */\n\tprivate readonly streamTokenInflight = new Map<string, Promise<string>>();\n\n\t// ── Session renewal ──────────────────────────────────────────────────────\n\t//\n\t// A crypto-auth JWT is SHORT-LIVED — the server mints it with\n\t// `auth.jwt_token_ttl_crypto_secs`, four hours by default, on the stated\n\t// reasoning that \"devices can silently re-authenticate\". Until this existed\n\t// nothing did: a client logged in once and held that token for as long as\n\t// the process (or the tab) lived.\n\t//\n\t// What that costs is worth stating, because the failure is split and neither\n\t// half looks like an auth problem:\n\t//\n\t// - An ALREADY-OPEN socket keeps working for an elevated (service/admin)\n\t// session, because `SyncSession::is_jwt_expired` waves those through, and\n\t// `MSG_STATELESS` is exempt for every session. So chat and presence carry\n\t// on and the client looks completely alive. For an ordinary session the\n\t// first sync or awareness frame past `exp` drops the socket, and it then\n\t// reconnect-storms with the same dead token.\n\t// - Every NEW socket is refused at the handshake — the server logs\n\t// `auth rejected: JWT error: ExpiredSignature` — and the provider simply\n\t// never syncs. Anything that opens a provider per document (an SSR doc\n\t// cache, a background indexer, a Node runner visiting a page) stops\n\t// working entirely, four hours in, with `Sync timed out` as its only\n\t// symptom.\n\t//\n\t// Two mechanisms, and both are needed. `ensureFreshToken()` re-mints before\n\t// `exp` and is awaited by the provider's own token closure, so no handshake\n\t// ever carries a stale token. And every token change is broadcast, so an\n\t// open socket can be re-armed in place with the server's `auth:refresh`\n\t// frame rather than being dropped and rebuilt.\n\tprivate _renew: (() => Promise<string>) | null = null;\n\tprivate _renewing: Promise<boolean> | null = null;\n\tprivate _renewTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate readonly _tokenListeners = new Set<(token: string) => void>();\n\tprivate readonly renewMarginMs: number;\n\tprivate readonly renewCheckMs: number;\n\n\tconstructor(config: AbracadabraClientConfig) {\n\t\tthis.baseUrl = config.url.replace(/\\/+$/, \"\");\n\t\tthis.persistAuth = config.persistAuth ?? typeof localStorage !== \"undefined\";\n\t\tthis.storageKey = config.storageKey ?? \"abracadabra:auth\";\n\t\tthis._fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n\t\tthis.cache = config.cache ?? null;\n\t\tthis._onAuthFailed = config.onAuthFailed ?? null;\n\t\tthis.renewMarginMs = config.tokenRenewMarginMs ?? 20 * 60_000;\n\t\tthis.renewCheckMs = config.tokenRenewCheckMs ?? 60_000;\n\n\t\t// Load token: explicit > persisted > null\n\t\tthis._token = config.token ?? this.loadPersistedToken() ?? null;\n\t}\n\n\t// ── Token management ─────────────────────────────────────────────────────\n\n\tget token(): string | null {\n\t\treturn this._token;\n\t}\n\n\tset token(value: string | null) {\n\t\tconst changed = value !== this._token;\n\t\tthis._token = value;\n\t\t// Stream grants carry the old identity (and die with it on\n\t\t// logout-all) — never serve one across a session change.\n\t\tthis.streamTokens.clear();\n\t\tthis.streamTokenInflight.clear();\n\t\tif (this.persistAuth) {\n\t\t\tif (value) {\n\t\t\t\tthis.persistToken(value);\n\t\t\t} else {\n\t\t\t\tthis.clearPersistedToken();\n\t\t\t}\n\t\t}\n\t\t// Every auth path in this class assigns through here — login, verify,\n\t\t// a device refresh, a key revocation, a renewal — so this is the one\n\t\t// place a provider needs to watch to keep an OPEN socket armed. A\n\t\t// listener that throws is its own problem and must not break the login\n\t\t// that produced the token.\n\t\tif (changed && value) {\n\t\t\t// A new token has a new deadline. Re-arming here rather than only\n\t\t\t// inside the renewal covers every other path that adopts one — a\n\t\t\t// password login, a device refresh, a key revocation.\n\t\t\tthis.scheduleSessionRenewal();\n\t\t\tfor (const listener of this._tokenListeners) {\n\t\t\t\ttry {\n\t\t\t\t\tlistener(value);\n\t\t\t\t} catch {\n\t\t\t\t\t/* a consumer's listener must not break authentication */\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tget isAuthenticated(): boolean {\n\t\treturn this._token !== null;\n\t}\n\n\t/** Check if the current JWT token is present and not expired. */\n\tisTokenValid(): boolean {\n\t\tif (!this._token) return false;\n\t\ttry {\n\t\t\tconst [, payload] = this._token.split(\".\");\n\t\t\t// JWT payloads are base64url — `atob` only handles standard base64,\n\t\t\t// so a payload containing `-` or `_` would throw and a valid token\n\t\t\t// would be misread as expired, forcing a spurious re-auth.\n\t\t\tconst { exp } = JSON.parse(decodeBase64UrlToString(payload));\n\t\t\treturn typeof exp === \"number\" && exp * 1000 > Date.now();\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** When the current token stops validating, in ms. `0` when unknown. */\n\tget tokenExpiresAt(): number {\n\t\treturn readJwtTimes(this._token).exp;\n\t}\n\n\t/**\n\t * Install the way this client re-authenticates itself, or `null` to stop.\n\t *\n\t * {@link loginWithKey} installs one for you, so a key-authenticated client\n\t * — every Node runner, and every browser session on a crypto identity —\n\t * renews without its consumer doing anything. Install one by hand for a\n\t * password session or any other flow that can mint a fresh token.\n\t *\n\t * The function must return the new JWT; adopting it (and notifying open\n\t * sockets) is this client's job.\n\t */\n\tsetSessionRenewer(renew: (() => Promise<string>) | null): void {\n\t\tthis._renew = renew;\n\t\tif (renew) this.scheduleSessionRenewal();\n\t\telse this.stopSessionRenewal();\n\t}\n\n\t/** Whether this client knows how to re-authenticate itself. */\n\tget canRenewSession(): boolean {\n\t\treturn this._renew !== null;\n\t}\n\n\t/**\n\t * Called whenever the session token changes — a login, a renewal, a device\n\t * refresh, a key revocation. Providers use this to re-arm sockets that are\n\t * already open. Returns an unsubscribe function.\n\t */\n\tonTokenChanged(listener: (token: string) => void): () => void {\n\t\tthis._tokenListeners.add(listener);\n\t\treturn () => this._tokenListeners.delete(listener);\n\t}\n\n\t/**\n\t * Make sure the token has life left in it, re-minting if it does not.\n\t *\n\t * Cheap when the token is fresh — one subtraction — so callers need not\n\t * reason about when the last renewal was, and concurrent callers share one\n\t * handshake. Returns whether the session is believed good; `false` is not\n\t * fatal, and the caller's own failure is still the authority.\n\t */\n\tasync ensureFreshToken(marginMs?: number): Promise<boolean> {\n\t\tif (!this._renew) return this.isTokenValid();\n\t\tif (this._renewing) return this._renewing;\n\n\t\tconst { exp } = readJwtTimes(this._token);\n\t\tif (exp > 0 && exp - Date.now() > this.renewMargin(marginMs)) return true;\n\n\t\t// Captured before the closure: `setSessionRenewer(null)` may land while\n\t\t// this is in flight, and a renewal that read `this._renew` at await time\n\t\t// would then throw instead of finishing the handshake it started.\n\t\tconst mint = this._renew;\n\t\tconst renew = (async (): Promise<boolean> => {\n\t\t\ttry {\n\t\t\t\tconst token = await mint();\n\t\t\t\t// `verify()` (and therefore `loginWithKey`) already adopts the\n\t\t\t\t// token through the setter, which is what notifies listeners.\n\t\t\t\t// Assigning again would be a second, identical notification.\n\t\t\t\tif (token && token !== this._token) this.token = token;\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\t// Do NOT push the expiry out on failure: the next caller must\n\t\t\t\t// try again rather than believe a renewal that did not happen.\n\t\t\t\treturn false;\n\t\t\t} finally {\n\t\t\t\tthis._renewing = null;\n\t\t\t}\n\t\t})();\n\t\tthis._renewing = renew;\n\t\treturn renew;\n\t}\n\n\t/**\n\t * How long before `exp` this session is re-minted.\n\t *\n\t * Capped at a third of the token's own lifetime, so a server configured\n\t * with short-lived tokens is not re-authenticated on every check — without\n\t * the cap a 45-second token against a 20-minute margin would mint a new\n\t * session every time anything asked.\n\t */\n\tprivate renewMargin(marginMs?: number): number {\n\t\tconst { exp, iat } = readJwtTimes(this._token);\n\t\tconst lifetime = exp > iat && iat > 0 ? exp - iat : Number.POSITIVE_INFINITY;\n\t\treturn Math.min(marginMs ?? this.renewMarginMs, lifetime / 3);\n\t}\n\n\t/**\n\t * Arm a single timer for the moment this token needs replacing.\n\t *\n\t * Scheduled from the token's OWN expiry rather than on a fixed interval,\n\t * and that is not tidiness. A poll can outrun the margin: measured against\n\t * a server issuing 45-second tokens, a 60-second poll first fired fifteen\n\t * seconds AFTER the token had already lapsed — long enough for the\n\t * awareness heartbeat to hit an expired session and have the socket dropped\n\t * under it. A deadline cannot be outrun by the thing it is a deadline for.\n\t *\n\t * Re-armed on every token change, so a renewal schedules the next one.\n\t */\n\tprivate scheduleSessionRenewal(): void {\n\t\tthis.stopSessionRenewal();\n\t\tif (!this._renew || this.renewCheckMs <= 0) return;\n\t\tconst { exp } = readJwtTimes(this._token);\n\t\t// A token whose expiry cannot be read falls back to the poll interval —\n\t\t// unreadable means \"assume the worst\", not \"stop renewing\".\n\t\tconst delay =\n\t\t\texp > 0\n\t\t\t\t? Math.max(1_000, exp - Date.now() - this.renewMargin())\n\t\t\t\t: this.renewCheckMs;\n\t\t// `setTimeout` treats anything past 2^31-1 ms as zero and fires at once,\n\t\t// which would busy-loop on a long-lived token. Re-arm instead.\n\t\tthis._renewTimer = setTimeout(\n\t\t\t() => {\n\t\t\t\tvoid this.ensureFreshToken()\n\t\t\t\t\t.catch(() => false)\n\t\t\t\t\t// A FAILED renewal must still re-arm, or one flaky moment\n\t\t\t\t\t// costs the session for the life of the process — the exact\n\t\t\t\t\t// shape of failure this mechanism exists to end.\n\t\t\t\t\t.finally(() => this.scheduleSessionRenewal());\n\t\t\t},\n\t\t\tMath.min(delay, 12 * 60 * 60_000),\n\t\t);\n\t\t// Never hold a Node process open for a session nothing is using.\n\t\t(this._renewTimer as { unref?: () => void }).unref?.();\n\t}\n\n\tprivate stopSessionRenewal(): void {\n\t\tif (!this._renewTimer) return;\n\t\tclearTimeout(this._renewTimer);\n\t\tthis._renewTimer = null;\n\t}\n\n\t/**\n\t * Stop renewing and drop every listener. Call when a client is discarded —\n\t * a long-lived consumer that builds one client per connection would\n\t * otherwise leave a timer per discarded client.\n\t */\n\tdestroy(): void {\n\t\tthis.stopSessionRenewal();\n\t\tthis._renew = null;\n\t\tthis._tokenListeners.clear();\n\t}\n\n\t/** Derives ws:// or wss:// URL from the http(s) base URL. */\n\tget wsUrl(): string {\n\t\treturn this.baseUrl\n\t\t\t.replace(/^https:\\/\\//, \"wss://\")\n\t\t\t.replace(/^http:\\/\\//, \"ws://\") + \"/ws\";\n\t}\n\n\t// ── Auth ─────────────────────────────────────────────────────────────────\n\n\t/** Register a new user with password. */\n\tasync register(opts: {\n\t\tusername: string;\n\t\tpassword: string;\n\t\temail?: string;\n\t\tdisplayName?: string;\n\t\tinviteCode?: string;\n\t}): Promise<UserProfile> {\n\t\treturn this.request<UserProfile>(\"POST\", \"/auth/register\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/**\n\t * Register a new user with an Ed25519 public key (crypto auth).\n\t * Username is optional — if omitted, a short identifier is derived from the key.\n\t */\n\tasync registerWithKey(opts: {\n\t\tpublicKey: string;\n\t\tusername?: string;\n\t\tdeviceName?: string;\n\t\tdisplayName?: string;\n\t\temail?: string;\n\t\tinviteCode?: string;\n\t\t/** X25519 encryption public key paired with the Ed25519 identity key. Required for E2E channels. */\n\t\tx25519Key?: string;\n\t}): Promise<UserProfile> {\n\t\tconst username = opts.username ?? `user-${opts.publicKey.slice(0, 8)}`;\n\t\treturn this.request<UserProfile>(\"POST\", \"/auth/register\", {\n\t\t\tbody: {\n\t\t\t\tusername,\n\t\t\t\tidentityPublicKey: opts.publicKey,\n\t\t\t\tdeviceName: opts.deviceName,\n\t\t\t\tdisplayName: opts.displayName,\n\t\t\t\temail: opts.email,\n\t\t\t\tinviteCode: opts.inviteCode,\n\t\t\t\tx25519Key: opts.x25519Key,\n\t\t\t},\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/** Login with username + password. Auto-persists returned token. */\n\tasync login(opts: { username: string; password: string }): Promise<string> {\n\t\tconst res = await this.request<{ token: string }>(\"POST\", \"/auth/login\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t\tthis.token = res.token;\n\t\treturn res.token;\n\t}\n\n\t/** Request an Ed25519 crypto auth challenge for the given public key. */\n\tasync challenge(publicKey: string): Promise<{ challenge: string; expiresAt: number }> {\n\t\treturn this.request(\"POST\", \"/auth/challenge\", {\n\t\t\tbody: { publicKey },\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/** Verify an Ed25519 signature to complete crypto auth. Auto-persists token. */\n\tasync verify(opts: {\n\t\tpublicKey: string;\n\t\tsignature: string;\n\t\tchallenge: string;\n\t}): Promise<string> {\n\t\tconst res = await this.request<{ token: string }>(\"POST\", \"/auth/verify\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t\tthis.token = res.token;\n\t\treturn res.token;\n\t}\n\n\t/**\n\t * Full crypto auth flow: challenge → sign → verify.\n\t * Convenience method combining challenge() + external signing + verify().\n\t */\n\tasync loginWithKey(\n\t\tpublicKey: string,\n\t\tsignChallenge: (challenge: string) => Promise<string>,\n\t): Promise<string> {\n\t\tconst { challenge } = await this.challenge(publicKey);\n\t\tconst signature = await signChallenge(challenge);\n\t\tconst token = await this.verify({ publicKey, signature, challenge });\n\t\t// A key-authenticated session can always mint itself another one — the\n\t\t// signer is right here — so this client becomes self-renewing the\n\t\t// moment it logs in, and no consumer has to remember that the server's\n\t\t// crypto-auth tokens expire in four hours. Installed AFTER `verify`, so\n\t\t// a failed login leaves no renewer behind.\n\t\tthis.setSessionRenewer(() => this.loginWithKey(publicKey, signChallenge));\n\t\treturn token;\n\t}\n\n\t/** Add a new Ed25519 public key to the current user (multi-device). */\n\tasync addKey(opts: { publicKey: string; deviceName?: string; x25519Key?: string }): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/keys\", { body: { publicKey: opts.publicKey, deviceName: opts.deviceName, x25519Key: opts.x25519Key } });\n\t}\n\n\t/** List all registered public keys for the current user. */\n\tasync listKeys(): Promise<PublicKeyInfo[]> {\n\t\tconst res = await this.request<{ keys: PublicKeyInfo[] }>(\"GET\", \"/auth/keys\");\n\t\treturn res.keys;\n\t}\n\n\t/** Rename a registered device key. */\n\tasync renameKey(keyId: string, deviceName: string): Promise<void> {\n\t\tawait this.request(\"PATCH\", `/auth/keys/${encodeURIComponent(keyId)}`, { body: { deviceName } });\n\t}\n\n\t/**\n\t * Revoke a public key by its ID. The server treats this as a panic\n\t * action: every outstanding JWT for the account is invalidated (a stolen\n\t * device's token must die immediately, and tokens carry no per-key\n\t * claim), and a fresh token for THIS session is returned and adopted\n\t * automatically — so the device performing the revocation stays\n\t * authenticated while every other device silently re-auths.\n\t */\n\tasync revokeKey(keyId: string): Promise<void> {\n\t\tconst res = await this.request<{ token?: string } | null>(\n\t\t\t\"DELETE\",\n\t\t\t`/auth/keys/${encodeURIComponent(keyId)}`,\n\t\t);\n\t\t// Older servers respond 204 with no body — keep working against them.\n\t\tif (res && typeof res === \"object\" && typeof res.token === \"string\") {\n\t\t\tthis.token = res.token;\n\t\t}\n\t}\n\n\t// ── Device Invites ───────────────────────────────────────────────────────\n\n\t/** Create a single-use device invite code for pairing a new device to this account. */\n\tasync createDeviceInvite(opts?: { expiresIn?: number }): Promise<{ code: string; expiresAt: number }> {\n\t\treturn this.request<{ code: string; expiresAt: number }>(\"POST\", \"/auth/device-invite\", {\n\t\t\tbody: opts?.expiresIn != null ? { expiresIn: opts.expiresIn } : {},\n\t\t});\n\t}\n\n\t/** Redeem a device invite code to register a new device key. Returns a JWT token. */\n\tasync redeemDeviceInvite(opts: {\n\t\tcode: string;\n\t\tpublicKey: string;\n\t\tx25519Key?: string;\n\t\tdeviceName?: string;\n\t}): Promise<{ token: string; user: { id: string; username: string; publicKey: string } }> {\n\t\treturn this.request(\"POST\", \"/auth/device-redeem\", {\n\t\t\tbody: { code: opts.code, publicKey: opts.publicKey, x25519Key: opts.x25519Key, deviceName: opts.deviceName },\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t// ── Device Sessions ────────────────────────────────────────────────────\n\n\t/** Request a device session token after successful crypto auth. Requires valid JWT. */\n\tasync requestDeviceSession(opts: {\n\t\tpublicKey: string;\n\t\tdeviceName?: string;\n\t}): Promise<{ sessionId: string; sessionToken: string; expiresAt: number }> {\n\t\treturn this.request(\"POST\", \"/auth/device-session\", {\n\t\t\tbody: { publicKey: opts.publicKey, deviceName: opts.deviceName },\n\t\t});\n\t}\n\n\t/** Exchange a device session token for a fresh JWT. No biometric/passkey needed. */\n\tasync refreshWithDeviceSession(sessionToken: string): Promise<string> {\n\t\tconst res = await this.request<{ token: string }>(\"POST\", \"/auth/refresh\", {\n\t\t\tbody: { sessionToken },\n\t\t\tauth: false,\n\t\t});\n\t\tthis.token = res.token;\n\t\treturn res.token;\n\t}\n\n\t/** List active device sessions for the authenticated user. */\n\tasync listDeviceSessions(): Promise<\n\t\tArray<{ id: string; keyId: string; deviceName?: string; issuedAt: number; expiresAt: number; lastUsedAt?: number }>\n\t> {\n\t\tconst res = await this.request<{\n\t\t\tsessions: Array<{ id: string; keyId: string; deviceName?: string; issuedAt: number; expiresAt: number; lastUsedAt?: number }>;\n\t\t}>(\"GET\", \"/auth/device-session\");\n\t\treturn res.sessions;\n\t}\n\n\t/** Revoke a device session by ID. */\n\tasync revokeDeviceSession(sessionId: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/auth/device-session/${encodeURIComponent(sessionId)}`);\n\t}\n\n\t// ── Pairing ─────────────────────────────────────────────────────────────\n\n\t/**\n\t * Fetch a short-lived anonymous pairing token for WebRTC signaling.\n\t * No authentication required. The token only grants access to `__pairing_*` rooms.\n\t */\n\tstatic async getPairingToken(serverUrl: string): Promise<string> {\n\t\tlet base = serverUrl;\n\t\twhile (base.endsWith(\"/\")) base = base.slice(0, -1);\n\t\tconst resp = await fetch(`${base}/auth/pairing-token`, { method: \"POST\" });\n\t\tif (!resp.ok) {\n\t\t\tthrow new Error(`Failed to fetch pairing token: ${resp.status}`);\n\t\t}\n\t\tconst { token } = (await resp.json()) as { token: string };\n\t\treturn token;\n\t}\n\n\t// ── Encryption ───────────────────────────────────────────────────────────\n\n\t/** Get encryption info for a document. */\n\tasync getDocEncryption(docId: string): Promise<DocEncryptionInfo> {\n\t\treturn this.request<DocEncryptionInfo>(\"GET\", `/docs/${encodeURIComponent(docId)}/encryption`);\n\t}\n\n\t/** Set the encryption mode for a document (no downgrade). */\n\tasync setDocEncryption(docId: string, mode: \"none\" | \"cse\" | \"e2e\"): Promise<void> {\n\t\tawait this.request(\"PATCH\", `/docs/${encodeURIComponent(docId)}/encryption`, { body: { mode } });\n\t}\n\n\t/** Get the caller's key envelope for a document (for decrypting the DocKey). */\n\tasync getMyKeyEnvelope(docId: string): Promise<{ encrypted_key: string; key_epoch: number } | null> {\n\t\treturn this.requestOrNull<{ encrypted_key: string; key_epoch: number }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/key-envelope`,\n\t\t);\n\t}\n\n\t/** Upload key envelopes for a document (Owner only). */\n\tasync uploadKeyEnvelopes(\n\t\tdocId: string,\n\t\topts: { key_epoch: number; envelopes: { recipient_key_id: string; encrypted_key: string }[] },\n\t): Promise<void> {\n\t\tawait this.request(\"POST\", `/docs/${encodeURIComponent(docId)}/key-envelopes`, { body: opts });\n\t}\n\n\t/** Get the X25519 public key for a user. */\n\tasync getUserX25519Key(userId: string): Promise<string | null> {\n\t\tconst res = await this.requestOrNull<{ x25519_key: string }>(\n\t\t\t\"GET\",\n\t\t\t`/users/${encodeURIComponent(userId)}/x25519-key`,\n\t\t);\n\t\treturn res?.x25519_key ?? null;\n\t}\n\n\t/** List all non-revoked keys for a user (Owner/Admin or self). */\n\tasync listUserKeys(userId: string): Promise<{ id: string; publicKey: string; x25519Key: string | null }[]> {\n\t\tconst res = await this.request<{ keys: { id: string; publicKey: string; x25519Key: string | null }[] }>(\n\t\t\t\"GET\",\n\t\t\t`/users/${encodeURIComponent(userId)}/keys`,\n\t\t);\n\t\treturn res.keys;\n\t}\n\n\t/** Fetch encrypted E2E update blobs since a given sequence number. */\n\tasync getE2EUpdatesSince(docId: string, sinceSeq: number): Promise<{ seq: number; data: Uint8Array }[]> {\n\t\tconst res = await this.request<{ updates: { seq: number; data: string }[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/e2e-updates?since_seq=${sinceSeq}`,\n\t\t);\n\t\treturn res.updates.map((u) => ({\n\t\t\tseq: u.seq,\n\t\t\tdata: fromBase64(u.data),\n\t\t}));\n\t}\n\n\t/**\n\t * Clear token from memory and storage. Local-only; does NOT notify the\n\t * server. Use {@link logoutServer} or {@link logoutAll} when you also\n\t * want the JWT to land in the server's revocation cache.\n\t */\n\tlogout(): void {\n\t\tthis.token = null;\n\t}\n\n\t/**\n\t * Revoke the current JWT server-side and clear local state. Adds the\n\t * token's `jti` to the server's revocation cache so subsequent requests\n\t * with this token return 401, even if the JWT signature still verifies\n\t * and `exp` hasn't passed. Safe to call when no token is set — degrades\n\t * to a local clear.\n\t *\n\t * Network errors are swallowed (the local state is always cleared) so\n\t * a sign-out flow can't get stuck on a flaky connection. The endpoint\n\t * itself is idempotent.\n\t */\n\tasync logoutServer(): Promise<void> {\n\t\tif (this._token) {\n\t\t\ttry {\n\t\t\t\tawait this.request(\"POST\", \"/auth/logout\");\n\t\t\t} catch {\n\t\t\t\t// best-effort — local clear must always happen\n\t\t\t}\n\t\t}\n\t\tthis.token = null;\n\t}\n\n\t/**\n\t * Bump the user's `tokens_invalid_before` watermark, revoking every\n\t * outstanding JWT for this user — every device, every browser, every\n\t * pending background tab. The current token is required (this is the\n\t * user's \"I am who I say I am\" assertion). After the call returns,\n\t * future authenticated requests with any pre-existing token return 401.\n\t */\n\tasync logoutAll(): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/logout-all\");\n\t\tthis.token = null;\n\t}\n\n\t// ── Email verification ──────────────────────────────────────────────────\n\n\t/**\n\t * Request an email verification message be sent to the current user's\n\t * registered email address. Requires authentication. Server enforces a\n\t * per-user rate limit (1/min, 10/day). Returns 404 if email\n\t * verification is disabled in `[auth.email_verification]`.\n\t */\n\tasync requestEmailVerification(): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/verify-email/request\", { body: {} });\n\t}\n\n\t/**\n\t * Confirm an email verification token (typically opened from a link in\n\t * the verification email). On success the server sets\n\t * `users.email_verified_at`. No auth required — the token itself is\n\t * the proof.\n\t */\n\tasync confirmEmailVerification(token: string): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/verify-email/confirm\", {\n\t\t\tbody: { token },\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t// ── Password lifecycle ──────────────────────────────────────────────────\n\n\t/**\n\t * Initiate a password reset for a user identified by username or\n\t * email. The server always returns 202 to avoid leaking whether the\n\t * identifier exists; a real reset email is only sent if the lookup\n\t * matched. Heavily rate-limited per-identifier and per-IP.\n\t */\n\tasync requestPasswordReset(opts: { identifier: string }): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/password-reset/request\", {\n\t\t\tbody: opts,\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/**\n\t * Complete a password reset using the token from the reset email.\n\t * On success the user's password is updated and every existing JWT for\n\t * the account is invalidated (the `tokens_invalid_before` watermark\n\t * bumps). The caller is NOT auto-logged-in — call {@link login} after.\n\t */\n\tasync confirmPasswordReset(opts: { token: string; newPassword: string }): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/password-reset/confirm\", {\n\t\t\tbody: { token: opts.token, newPassword: opts.newPassword },\n\t\t\tauth: false,\n\t\t});\n\t}\n\n\t/**\n\t * Change the current user's password. Requires the current password —\n\t * a stolen JWT alone can't pivot to \"I now own this account forever\"\n\t * because the lockout counter (shared with `/auth/login`) trips after\n\t * a few wrong tries. The endpoint also bumps `tokens_invalid_before`,\n\t * so other sessions are forced to re-auth.\n\t */\n\tasync changePassword(opts: { currentPassword: string; newPassword: string }): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/password-change\", {\n\t\t\tbody: { currentPassword: opts.currentPassword, newPassword: opts.newPassword },\n\t\t});\n\t}\n\n\t/**\n\t * Add a password to an account that doesn't have one yet — for example,\n\t * a key-based soft identity opting into a recovery credential. Requires\n\t * the caller to be authenticated. The server checks\n\t * `users.password_hash IS NULL` and returns 409 if a password is already\n\t * set — use {@link changePassword} in that case.\n\t *\n\t * Setting a password does not bump `tokens_invalid_before`: it adds an\n\t * orthogonal credential rather than rotating an existing one. Other\n\t * devices keep their sessions; this just unlocks the password-login\n\t * code path for future logins on new devices.\n\t */\n\tasync setPassword(newPassword: string): Promise<void> {\n\t\tawait this.request(\"POST\", \"/auth/set-password\", {\n\t\t\tbody: { newPassword },\n\t\t});\n\t}\n\n\t// ── User ─────────────────────────────────────────────────────────────────\n\n\t/** Get the current user's profile. */\n\tasync getMe(): Promise<UserProfile> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getCurrentProfile();\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst profile = await this.request<UserProfile>(\"GET\", \"/users/me\");\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setCurrentProfile(profile).catch(() => null);\n\t\t}\n\t\treturn profile;\n\t}\n\n\t/** Update the current user's display name. */\n\tasync updateMe(opts: { displayName?: string }): Promise<void> {\n\t\tawait this.request(\"PATCH\", \"/users/me\", { body: opts });\n\t}\n\n\t// ── Documents ────────────────────────────────────────────────────────────\n\n\t/**\n\t * Create a new root (top-level) document. Returns its metadata.\n\t *\n\t * Requires Admin-or-above unless the server sets\n\t * `[access].allow_user_top_level = true` — subtree docs go through\n\t * {@link createChild} instead and inherit creation rights from the parent.\n\t *\n\t * The options mirror the server's `CreateDocRequest`. They used to be typed\n\t * as just `{ id?: string }`, which is why `findOrCreateDmDoc` below reaches\n\t * past this method with a raw `request()` to set `kind` / `public_access`.\n\t */\n\tasync createDoc(opts?: {\n\t\tid?: string;\n\t\tlabel?: string;\n\t\tdescription?: string;\n\t\tkind?: string;\n\t\t/** See {@link AbracadabraClient.setDocumentAccess} for what each value means. */\n\t\tpublic_access?: \"none\" | \"private\" | \"observer\" | \"viewer\" | \"editor\";\n\t}): Promise<DocumentMeta> {\n\t\treturn this.request<DocumentMeta>(\"POST\", \"/docs\", { body: opts ?? {} });\n\t}\n\n\t/** Get document metadata. */\n\tasync getDoc(docId: string): Promise<DocumentMeta> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getDoc(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst meta = await this.request<DocumentMeta>(\"GET\", `/docs/${encodeURIComponent(docId)}`);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setDoc(meta).catch(() => null);\n\t\t}\n\t\treturn meta;\n\t}\n\n\t/** Delete a document (requires Owner role). Cascades to children and uploads. */\n\tasync deleteDoc(docId: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/docs/${encodeURIComponent(docId)}`);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateDoc(docId).catch(() => null);\n\t\t}\n\t}\n\n\t/**\n\t * Restore a soft-deleted document (and its descendants). Requires the\n\t * same `manage` permission as {@link deleteDoc}, and works even when\n\t * the doc currently has `deleted_at` set — the cascade resolver walks\n\t * the ancestor chain regardless of soft-delete state. Returns the\n\t * number of restored rows in the audit log; the SDK call returns\n\t * `void` because the wire response is 204.\n\t */\n\tasync restoreDoc(docId: string): Promise<void> {\n\t\tawait this.request(\"POST\", `/docs/${encodeURIComponent(docId)}/restore`);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateDoc(docId).catch(() => null);\n\t\t}\n\t}\n\n\t/**\n\t * Full-text search over document labels via `GET /docs/search`. The\n\t * server filters each candidate hit through the cascade resolver, so\n\t * results only include docs the caller can read at viewer or above.\n\t * Anonymous callers are permitted but only see public docs.\n\t *\n\t * `limit` is clamped to `[1, 50]` server-side; the default is 20.\n\t * Hits arrive in best-first order. `snippet` is HTML with `<mark>`\n\t * markers around matched tokens — sanitize before injecting.\n\t */\n\tasync searchDocs(query: string, opts?: { limit?: number }): Promise<DocSearchHit[]> {\n\t\tconst params = new URLSearchParams({ q: query });\n\t\tif (opts?.limit != null) params.set(\"limit\", String(opts.limit));\n\t\tconst res = await this.request<{ results: DocSearchHit[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/search?${params.toString()}`,\n\t\t);\n\t\treturn res.results;\n\t}\n\n\t/**\n\t * Documents that link TO `docId`, via `GET /docs/:id/backlinks`.\n\t *\n\t * Served from the server's `doc_links` index, which is rebuilt from each\n\t * document's CRDT state whenever a snapshot is written. Prefer this over\n\t * inverting links from a local cache: a client can only invert what it has\n\t * downloaded, so on a large space a purely local backlink list is silently\n\t * incomplete rather than empty-and-obviously-wrong.\n\t *\n\t * The caller must be able to read the target document, and each hit is\n\t * cascade-filtered, so this never reveals a document the caller couldn't\n\t * otherwise see. `limit` is clamped to `[1, 200]` server-side (default 50).\n\t *\n\t * Throws on servers that predate the endpoint — callers that need to work\n\t * against older deployments should catch and fall back to a local index.\n\t */\n\tasync getBacklinks(\n\t\tdocId: string,\n\t\topts?: { limit?: number },\n\t): Promise<DocBacklink[]> {\n\t\tconst params = new URLSearchParams();\n\t\tif (opts?.limit != null) params.set(\"limit\", String(opts.limit));\n\t\tconst qs = params.toString();\n\t\tconst res = await this.request<{ results: DocBacklink[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/backlinks${qs ? `?${qs}` : \"\"}`,\n\t\t);\n\t\treturn res.results;\n\t}\n\n\t/**\n\t * Query for documents matching a structural predicate. v1 of the\n\t * indexed-query layer described in\n\t * `ARCHITECTURE/20-kickoff-phase3-queries.md`.\n\t *\n\t * The wire shape accepts a `where` field so v2 (meta-predicate\n\t * filtering on top of the `doc_meta_index` projection) can light up\n\t * without a compatibility break. Sending a non-empty `where` today\n\t * returns a 400 — callers should leave it absent.\n\t *\n\t * Returns docs the requester can read at viewer-or-above, filtered\n\t * through the cascading permission resolver server-side.\n\t */\n\tasync queryDocs(opts: {\n\t\ttype?: string;\n\t\tparentId?: string;\n\t\tlabelContains?: string;\n\t\tlimit?: number;\n\t}): Promise<DocumentMeta[]> {\n\t\tconst body: Record<string, unknown> = {};\n\t\tif (opts.type != null) body.type = opts.type;\n\t\tif (opts.parentId != null) body.parent_id = opts.parentId;\n\t\tif (opts.labelContains != null) body.label_contains = opts.labelContains;\n\t\tif (opts.limit != null) body.limit = opts.limit;\n\t\tconst res = await this.request<{ documents: DocumentMeta[]; v: number }>(\n\t\t\t\"POST\",\n\t\t\t\"/docs/query\",\n\t\t\t{ body },\n\t\t);\n\t\treturn res.documents;\n\t}\n\n\t/**\n\t * List the direct children of a document, returning full metadata. Pass\n\t * no argument to list the children of the server root — what the\n\t * dashboard renders as the Spaces sidebar.\n\t *\n\t * The cache (when configured) stores the bare `id[]` topology used by\n\t * recursive tree walks; callers that need it can read `meta.id` from\n\t * the returned metas.\n\t */\n\tasync listChildren(\n\t\tparentId?: string,\n\t\topts?: { kind?: string },\n\t): Promise<DocumentMeta[]> {\n\t\tconst kind = opts?.kind;\n\t\tif (parentId) {\n\t\t\tconst res = await this.request<{\n\t\t\t\tdocuments: DocumentMeta[];\n\t\t\t\tchildren?: string[];\n\t\t\t}>(\"GET\", `/docs/${encodeURIComponent(parentId)}/children`);\n\t\t\tif (this.cache && res.children) {\n\t\t\t\tawait this.cache.setChildren(parentId, res.children).catch(() => null);\n\t\t\t}\n\t\t\treturn kind\n\t\t\t\t? res.documents.filter((d) => d.kind === kind)\n\t\t\t\t: res.documents;\n\t\t}\n\t\t// Root listing. The server runs the per-row permission cascade for\n\t\t// every top-level doc, so this is the expensive call. Send the\n\t\t// optional server-side `kind` filter — a fixed server skips the\n\t\t// cascade for non-matching docs; an old server ignores the unknown\n\t\t// param and we still filter client-side below, so the result is\n\t\t// identical either way. Concurrent identical root listings (a\n\t\t// connect fans out several) share one in-flight request.\n\t\tconst key = kind ?? \"\";\n\t\tconst existing = this.rootListInflight.get(key);\n\t\tconst docs = existing\n\t\t\t? await existing\n\t\t\t: await (() => {\n\t\t\t\t\tconst p = this.request<{\n\t\t\t\t\t\tdocuments: DocumentMeta[];\n\t\t\t\t\t\tchildren?: string[];\n\t\t\t\t\t}>(\n\t\t\t\t\t\t\"GET\",\n\t\t\t\t\t\tkind\n\t\t\t\t\t\t\t? `/docs?root=true&kind=${encodeURIComponent(kind)}`\n\t\t\t\t\t\t\t: \"/docs?root=true\",\n\t\t\t\t\t)\n\t\t\t\t\t\t.then((res) => res.documents)\n\t\t\t\t\t\t.finally(() => this.rootListInflight.delete(key));\n\t\t\t\t\tthis.rootListInflight.set(key, p);\n\t\t\t\t\treturn p;\n\t\t\t\t})();\n\t\treturn kind ? docs.filter((d) => d.kind === kind) : docs;\n\t}\n\n\t/**\n\t * Create a child document under a parent (requires write permission).\n\t *\n\t * `kind` is the well-known tag (`Kind.Channel`, `Kind.Page`, etc.); the\n\t * server stores it in `documents.kind` but does not enforce semantics.\n\t * `description` is freeform metadata.\n\t */\n\tasync createChild(\n\t\tdocId: string,\n\t\topts?: {\n\t\t\tchild_id?: string;\n\t\t\tdoc_type?: string;\n\t\t\tlabel?: string;\n\t\t\tkind?: string;\n\t\t\tdescription?: string;\n\t\t},\n\t): Promise<DocumentMeta> {\n\t\treturn this.request<DocumentMeta>(\n\t\t\t\"POST\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/children`,\n\t\t\t{ body: opts ?? {} },\n\t\t);\n\t}\n\n\t/** Broadcast a stateless message to all connected clients on a document (requires manage permission). */\n\tasync broadcast(docId: string, payload: string): Promise<void> {\n\t\tawait this.request(\"POST\", `/docs/${encodeURIComponent(docId)}/broadcast`, { body: { payload } });\n\t}\n\n\t// ── Permissions ──────────────────────────────────────────────────────────\n\n\t/** List all permissions for a document (requires read access). */\n\tasync listPermissions(docId: string): Promise<PermissionEntry[]> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getPermissions(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst res = await this.request<{ permissions: PermissionEntry[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/permissions`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setPermissions(docId, res.permissions).catch(() => null);\n\t\t}\n\t\treturn res.permissions;\n\t}\n\n\t/** List effective permissions including inherited ones from ancestor documents. */\n\tasync listEffectivePermissions(\n\t\tdocId: string,\n\t): Promise<EffectivePermissionsResponse> {\n\t\ttry {\n\t\t\treturn await this.request<EffectivePermissionsResponse>(\n\t\t\t\t\"GET\",\n\t\t\t\t`/docs/${encodeURIComponent(docId)}/effective-permissions`,\n\t\t\t);\n\t\t} catch (e: unknown) {\n\t\t\t// Fallback for older servers that don't support this endpoint (404 only)\n\t\t\tif (typeof e === \"object\" && e !== null && \"status\" in e && (e as { status: number }).status === 404) {\n\t\t\t\tconst perms = await this.listPermissions(docId);\n\t\t\t\treturn {\n\t\t\t\t\tpermissions: perms.map((p) => ({ ...p, source: \"direct\" as const })),\n\t\t\t\t\tdefault_role: \"viewer\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t/** Grant or change a user's role on a document (requires Owner). */\n\tasync setPermission(\n\t\tdocId: string,\n\t\topts: { user_id: string; role: \"owner\" | \"editor\" | \"viewer\" | \"observer\" },\n\t): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"POST\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/permissions`,\n\t\t\t{ body: opts },\n\t\t);\n\t}\n\n\t/** Revoke a user's permission on a document (requires Owner). */\n\tasync removePermission(docId: string, opts: { user_id: string }): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"DELETE\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/permissions`,\n\t\t\t{ body: opts },\n\t\t);\n\t}\n\n\t// ── Uploads ──────────────────────────────────────────────────────────────\n\n\t/** Upload a file to a document (requires write permission). */\n\tasync upload(\n\t\tdocId: string,\n\t\tfile: File | Blob,\n\t\tfilename?: string,\n\t): Promise<UploadMeta> {\n\t\tconst formData = new FormData();\n\t\tformData.append(\"file\", file, filename);\n\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}/docs/${encodeURIComponent(docId)}/uploads`,\n\t\t\t{ method: \"POST\", headers, body: formData },\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res);\n\t\t}\n\t\tconst meta = await res.json() as UploadMeta;\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateUploads(docId).catch(() => null);\n\t\t}\n\t\treturn meta;\n\t}\n\n\t/** List all uploads for a document. */\n\tasync listUploads(docId: string): Promise<UploadInfo[]> {\n\t\tif (this.cache) {\n\t\t\tconst cached = await this.cache.getUploads(docId);\n\t\t\tif (cached) return cached;\n\t\t}\n\t\tconst res = await this.request<{ uploads: UploadInfo[] }>(\n\t\t\t\"GET\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/uploads`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.setUploads(docId, res.uploads).catch(() => null);\n\t\t}\n\t\treturn res.uploads;\n\t}\n\n\t/** Download an upload as a Blob. */\n\tasync getUpload(docId: string, uploadId: string): Promise<Blob> {\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}`,\n\t\t\t{ method: \"GET\", headers },\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res);\n\t\t}\n\t\treturn res.blob();\n\t}\n\n\t/**\n\t * Mint a short-lived, read-only token bound to this one upload.\n\t * Prefer `getStreamUrl`, which caches and reuses the grant.\n\t */\n\tasync createStreamToken(\n\t\tdocId: string,\n\t\tuploadId: string,\n\t): Promise<StreamTokenInfo> {\n\t\treturn this.request<StreamTokenInfo>(\n\t\t\t\"POST\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}/stream-token`,\n\t\t);\n\t}\n\n\t/**\n\t * Absolute URL that streams an upload straight from the server, safe to\n\t * hand to `<video src>` / `<audio src>`.\n\t *\n\t * Unlike `FileBlobStore.getBlobUrl` (which downloads the whole blob into\n\t * IndexedDB and hands back an object URL), this keeps the bytes on the\n\t * server so the browser can seek natively over HTTP Range — the difference\n\t * between \"wait for 400 MB\" and \"scrub instantly\". It needs the network,\n\t * so callers should fall back to `getBlobUrl` when offline.\n\t *\n\t * Grants are cached per upload and re-minted shortly before they expire.\n\t * Throws on servers older than the `stream-token` endpoint (404).\n\t */\n\tasync getStreamUrl(docId: string, uploadId: string): Promise<string> {\n\t\tconst key = `${docId}/${uploadId}`;\n\t\tconst cached = this.streamTokens.get(key);\n\t\t// Re-mint a minute early so a URL handed to a media element doesn't\n\t\t// expire mid-request.\n\t\tif (cached && cached.expiresAt - 60_000 > Date.now()) return cached.url;\n\n\t\t// Single-flight: a page full of media blocks resolves the same upload\n\t\t// from several components at once, and each mint is a round trip.\n\t\tconst inflight = this.streamTokenInflight.get(key);\n\t\tif (inflight) return inflight;\n\n\t\tconst pending = this.createStreamToken(docId, uploadId)\n\t\t\t.then((info) => {\n\t\t\t\tconst url = `${this.baseUrl}${info.url}`;\n\t\t\t\tthis.streamTokens.set(key, {\n\t\t\t\t\turl,\n\t\t\t\t\texpiresAt: Date.now() + info.expires_in * 1000,\n\t\t\t\t});\n\t\t\t\treturn url;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tthis.streamTokenInflight.delete(key);\n\t\t\t});\n\t\tthis.streamTokenInflight.set(key, pending);\n\t\treturn pending;\n\t}\n\n\t/** Drop any cached stream grant for an upload (or all of them). */\n\tclearStreamUrl(docId?: string, uploadId?: string): void {\n\t\tif (docId && uploadId) {\n\t\t\tthis.streamTokens.delete(`${docId}/${uploadId}`);\n\t\t\tthis.streamTokenInflight.delete(`${docId}/${uploadId}`);\n\t\t\treturn;\n\t\t}\n\t\tthis.streamTokens.clear();\n\t\tthis.streamTokenInflight.clear();\n\t}\n\n\t/**\n\t * Build the request path (with query string) for an upload's thumbnail.\n\t * Also the canonical cache key suffix — the query string is deterministic\n\t * in insertion order, so identical options map to the same URL and the\n\t * same `FileBlobStore` cache entry.\n\t */\n\tthumbnailPath(docId: string, uploadId: string, opts: ThumbnailOptions = {}): string {\n\t\tconst p = new URLSearchParams();\n\t\tif (opts.w != null) p.set(\"w\", String(opts.w));\n\t\tif (opts.h != null) p.set(\"h\", String(opts.h));\n\t\tif (opts.fit) p.set(\"fit\", opts.fit);\n\t\tif (opts.format) p.set(\"format\", opts.format);\n\t\tif (opts.q != null) p.set(\"q\", String(opts.q));\n\t\tconst qs = p.toString();\n\t\treturn `/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}/thumbnail${qs ? `?${qs}` : \"\"}`;\n\t}\n\n\t/**\n\t * Download a generated thumbnail of an image upload as a Blob. The server\n\t * renders + caches it on first request. Because a browser `<img>` can't\n\t * send `Authorization`, callers render the returned Blob via an object URL\n\t * (see `FileBlobStore.getThumbUrl`, which also caches it locally).\n\t * Throws (with `.status = 415`) when the source isn't a thumbnailable\n\t * raster image, or `422` for an out-of-allowlist size/format.\n\t */\n\tasync getThumbnail(\n\t\tdocId: string,\n\t\tuploadId: string,\n\t\topts: ThumbnailOptions = {},\n\t): Promise<Blob> {\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}${this.thumbnailPath(docId, uploadId, opts)}`,\n\t\t\t{ method: \"GET\", headers },\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res);\n\t\t}\n\t\treturn res.blob();\n\t}\n\n\t/** Delete an upload (requires uploader or document Owner). */\n\tasync deleteUpload(docId: string, uploadId: string): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"DELETE\",\n\t\t\t`/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}`,\n\t\t);\n\t\tif (this.cache) {\n\t\t\tawait this.cache.invalidateUploads(docId).catch(() => null);\n\t\t}\n\t}\n\n\t// ── Invites ──────────────────────────────────────────────────────────────\n\n\t/** Create an invite code (requires permission per server config). */\n\tasync createInvite(opts?: { role?: string; maxUses?: number; expiresIn?: number }): Promise<InviteRow> {\n\t\treturn this.request<InviteRow>(\"POST\", \"/invites\", { body: opts ?? {} });\n\t}\n\n\t/** List invite codes visible to the current user. */\n\tasync listInvites(): Promise<InviteRow[]> {\n\t\tconst res = await this.request<{ invites: InviteRow[] }>(\"GET\", \"/invites\");\n\t\treturn res.invites;\n\t}\n\n\t/** Revoke an invite by its code. */\n\tasync revokeInvite(code: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/invites/${encodeURIComponent(code)}`);\n\t}\n\n\t/** Redeem an invite code for the currently authenticated user. */\n\tasync redeemInvite(code: string): Promise<void> {\n\t\tawait this.request(\"POST\", \"/invites/redeem\", { body: { code } });\n\t}\n\n\t// ── Document Access & Discovery ──────────────────────────────────────────\n\n\t/**\n\t * Set the public_access level for a document. Pass null to inherit from parent.\n\t *\n\t * The values, and the two that are easy to confuse:\n\t *\n\t * - `\"observer\"` / `\"viewer\"` / `\"editor\"` — a FLOOR. Raises whoever reaches\n\t * this document to at least that role, cascading to descendants.\n\t * - `\"none\"` — no floor from here. Blocks anonymous, but an authenticated\n\t * principal still falls through to the server's `[access].authenticated`\n\t * default, so on a server with a floor this does NOT make a document private.\n\t * - `\"private\"` — no floor AND no ambient default. Only explicit grants,\n\t * ownership, Admin and Service reach a sealed document. This is what makes\n\t * a document private without reconfiguring the whole server.\n\t *\n\t * The cascade takes the NEAREST ancestor that sets a value, not the strongest,\n\t * so a descendant can re-publish itself out of a private parent.\n\t *\n\t * `\"private\"` requires server ≥ the release that introduced it. An older\n\t * server rejects it with 400 rather than silently storing it.\n\t */\n\tasync setDocumentAccess(\n\t\tdocId: string,\n\t\tpublicAccess: \"none\" | \"private\" | \"observer\" | \"viewer\" | \"editor\" | null,\n\t): Promise<void> {\n\t\tawait this.request(\"PATCH\", `/docs/${encodeURIComponent(docId)}/access`, {\n\t\t\tbody: { public_access: publicAccess },\n\t\t});\n\t}\n\n\t/** Get the public_access info for a document. */\n\tasync getDocumentAccess(docId: string): Promise<{ public_access: string | null; effective_public_access: string | null }> {\n\t\treturn this.request(\"GET\", `/docs/${encodeURIComponent(docId)}/access`);\n\t}\n\n\t/**\n\t * Update document metadata (label, description, kind, doc_type, parent_id).\n\t * Requires manage permission on the doc; reparenting additionally requires\n\t * manage on the new parent (or admin if moving under the server root).\n\t *\n\t * `doc_type` is the renderer hint (`\"kanban\"`, `\"graph\"`, …) — orthogonal\n\t * to `kind` (the structural role). Use it for post-create type changes;\n\t * never write renderer strings into `kind`. Servers older than migration\n\t * 0014 ignore the field (unknown JSON fields are dropped server-side).\n\t */\n\tasync updateDocumentMeta(\n\t\tdocId: string,\n\t\topts: {\n\t\t\tlabel?: string | null;\n\t\t\tdescription?: string | null;\n\t\t\tkind?: string | null;\n\t\t\tdoc_type?: string | null;\n\t\t\tparent_id?: string | null;\n\t\t},\n\t): Promise<void> {\n\t\tawait this.request(\"PATCH\", `/docs/${encodeURIComponent(docId)}`, { body: opts });\n\t}\n\n\t// ── Spaces ───────────────────────────────────────────────────────────────\n\t//\n\t// \"Spaces\" are direct children of the server root with `kind: \"space\"`.\n\t// They live in the regular `documents` table — there's no dedicated\n\t// spaces resource on the server anymore. These helpers keep the familiar\n\t// names so callers don't have to think about the underlying tree.\n\n\t/**\n\t * List Spaces visible to the caller — top-level docs (children of the\n\t * server root) tagged with `kind: \"space\"`. Authenticated users see\n\t * spaces resolving to any role; anonymous users see public ones.\n\t */\n\tasync listSpaces(): Promise<DocumentMeta[]> {\n\t\treturn this.listChildren(undefined, { kind: Kind.Space });\n\t}\n\n\t/**\n\t * Create a new top-level Space. Equivalent to a `POST /docs` with\n\t * `kind: \"space\"` plus the supplied metadata in one round trip.\n\t *\n\t * `visibility: \"public\"` sets `public_access = \"observer\"` (anonymous\n\t * read, no awareness or writes). `\"private\"` (the default) leaves\n\t * `public_access` unset so only explicit grants apply.\n\t */\n\tasync createSpace(opts: {\n\t\tname: string;\n\t\tdescription?: string;\n\t\tvisibility?: \"public\" | \"private\";\n\t\tid?: string;\n\t}): Promise<DocumentMeta> {\n\t\tconst public_access = opts.visibility === \"public\" ? \"observer\" : \"none\";\n\t\treturn this.request<DocumentMeta>(\"POST\", \"/docs\", {\n\t\t\tbody: {\n\t\t\t\tid: opts.id,\n\t\t\t\tlabel: opts.name,\n\t\t\t\tdescription: opts.description,\n\t\t\t\tkind: Kind.Space,\n\t\t\t\tpublic_access,\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Update a Space's metadata. `visibility` flips `public_access` between\n\t * `\"observer\"` (public) and `\"none\"` (private). To leave visibility\n\t * untouched, omit it. Pass any property as `null` to clear it.\n\t */\n\tasync updateSpace(\n\t\tdocId: string,\n\t\topts: { name?: string | null; description?: string | null; visibility?: \"public\" | \"private\" },\n\t): Promise<void> {\n\t\tconst meta: { label?: string | null; description?: string | null } = {};\n\t\tif (opts.name !== undefined) meta.label = opts.name;\n\t\tif (opts.description !== undefined) meta.description = opts.description;\n\t\tif (Object.keys(meta).length > 0) {\n\t\t\tawait this.updateDocumentMeta(docId, meta);\n\t\t}\n\t\tif (opts.visibility !== undefined) {\n\t\t\tawait this.setDocumentAccess(docId, opts.visibility === \"public\" ? \"observer\" : \"none\");\n\t\t}\n\t}\n\n\t/** Delete a Space (and every doc nested under it). Requires manage permission. */\n\tasync deleteSpace(docId: string): Promise<void> {\n\t\tawait this.deleteDoc(docId);\n\t}\n\n\t/**\n\t * Look up the DM doc between the calling user and `otherUserPk`, or\n\t * create it if none exists. The doc id is deterministically derived from\n\t * the sorted pubkey pair (see {@link deriveDmDocId}) so both sides\n\t * compute the same target — race-tolerant by construction. The created\n\t * doc has `kind = \"dm\"`, `public_access = \"none\"`, and explicit Editor\n\t * permissions for both participants.\n\t *\n\t * The cascade resolver enforces that no other user can read the DM,\n\t * because:\n\t * - `public_access = \"none\"` blocks anonymous + falls through to the\n\t * server-wide `[access].authenticated` floor for everyone else;\n\t * - the explicit Editor rows only exist for the two participants, so\n\t * non-participants get only the (capped) authenticated floor;\n\t * - the doc lives at server root, so there's no ancestor that could\n\t * leak via a higher cascade grant.\n\t *\n\t * Note: when `[access].authenticated >= \"viewer\"` is set server-wide,\n\t * non-participants can still *read* the DM via the authenticated floor —\n\t * `public_access = \"none\"` removes the floor but not the ambient default.\n\t *\n\t * Servers that support `public_access = \"private\"` can seal it properly:\n\t * call `setDocumentAccess(dmId, \"private\")` after creating one. That is NOT\n\t * done here, deliberately — this SDK talks to older servers too, and they\n\t * reject the value with a 400. Callers that know their server version can\n\t * opt in; a future major may make it the default.\n\t *\n\t * @param otherUserPk Base64url-encoded Ed25519 public key of the other party.\n\t * @returns The DM doc's id (existing or newly created).\n\t */\n\tasync findOrCreateDmDoc(otherUserPk: string): Promise<string> {\n\t\tconst me = await this.getMe();\n\t\tif (!me.publicKey) {\n\t\t\tthrow new Error(\"findOrCreateDmDoc: caller has no public key\");\n\t\t}\n\t\tconst dmId = deriveDmDocId(me.publicKey, otherUserPk);\n\t\t// Try to fetch the doc first — if it exists, we're done.\n\t\ttry {\n\t\t\tconst existing = await this.getDoc(dmId);\n\t\t\tif (existing && existing.kind === Kind.Dm) {\n\t\t\t\treturn dmId;\n\t\t\t}\n\t\t} catch {\n\t\t\t// 404 is the expected miss; any other error we let bubble up\n\t\t\t// from createDoc below.\n\t\t}\n\t\t// Race-tolerant create: both clients hashing the same pubkey pair\n\t\t// generate the same id, so whoever loses the create gets Conflict\n\t\t// and the catch reuses the id.\n\t\ttry {\n\t\t\tawait this.request<DocumentMeta>(\"POST\", \"/docs\", {\n\t\t\t\tbody: {\n\t\t\t\t\tid: dmId,\n\t\t\t\t\tkind: Kind.Dm,\n\t\t\t\t\tpublic_access: \"none\",\n\t\t\t\t},\n\t\t\t});\n\t\t} catch (err: any) {\n\t\t\t// Conflict means the other side already created it; reuse.\n\t\t\tconst status = err?.status ?? err?.response?.status;\n\t\t\tif (status !== 409) throw err;\n\t\t}\n\t\t// Idempotent permission grants (server upserts on (doc_id, user_id)).\n\t\tawait this.setPermission(dmId, { user_id: me.publicKey, role: \"editor\" });\n\t\tawait this.setPermission(dmId, { user_id: otherUserPk, role: \"editor\" });\n\t\treturn dmId;\n\t}\n\n\t/**\n\t * The reserved server root document id. Convenience accessor for the\n\t * client; identical to {@link SERVER_ROOT_ID}. Use this as the parent for\n\t * top-level docs / Spaces.\n\t */\n\tget rootDocId(): string {\n\t\treturn SERVER_ROOT_ID;\n\t}\n\n\t// ── Admin ───────────────────────────────────────────────────────────────\n\n\t/** List all users (requires elevated role: admin or service). */\n\tasync adminListUsers(): Promise<{ users: (UserProfile & { revoked: boolean; deviceKeys: string[] })[] }> {\n\t\treturn this.request(\"GET\", \"/admin/users\");\n\t}\n\n\t/** Promote a user to admin (requires service role). */\n\tasync adminPromote(userId: string): Promise<void> {\n\t\tawait this.request(\"POST\", `/admin/users/${encodeURIComponent(userId)}/admin`);\n\t}\n\n\t/** Demote an admin user back to regular (requires service role). */\n\tasync adminDemote(userId: string): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/admin/users/${encodeURIComponent(userId)}/admin`);\n\t}\n\n\t/** Sweep orphaned file blobs from storage (requires elevated role). */\n\tasync adminStorageSweep(): Promise<{ blobsDeleted: number }> {\n\t\treturn this.request(\"POST\", \"/admin/storage/sweep\");\n\t}\n\n\t/** Repair blob ref-counts and sweep orphans (requires elevated role). */\n\tasync adminStorageRepair(): Promise<{ refCountsRepaired: number; blobsSwept: number }> {\n\t\treturn this.request(\"POST\", \"/admin/storage/repair\");\n\t}\n\n\t/**\n\t * Admin one-shot: populate the `snapshot_files` table for snapshots\n\t * created before that migration ran, so `SnapshotMeta.file_count` and\n\t * upload-ref tracking become accurate. Idempotent (insert-or-ignore).\n\t * Requires elevated role.\n\t */\n\tasync adminSnapshotsBackfillRefs(): Promise<{\n\t\tsnapshotsScanned: number;\n\t\trefsWritten: number;\n\t}> {\n\t\treturn this.request(\"POST\", \"/admin/snapshots/backfill-refs\");\n\t}\n\n\t/**\n\t * Admin one-shot: migrate pre-dedup inline snapshot data into the\n\t * content-addressed `snapshot_blobs` store. Idempotent (only migrates\n\t * rows with `data_hash IS NULL`). Requires elevated role.\n\t */\n\tasync adminSnapshotsBackfillBlobs(): Promise<{\n\t\tsnapshotsMigrated: number;\n\t\tblobsAfter: number;\n\t\ttotalBytesAfter: number;\n\t}> {\n\t\treturn this.request(\"POST\", \"/admin/snapshots/backfill-blobs\");\n\t}\n\n\t/**\n\t * Admin: server-wide upload listing, joined with the owning document\n\t * (label is best-effort — labels live in the CRDT, not the SQL row)\n\t * and the content-addressed blob (`ref_count` exposes dedup).\n\t * Server-side paginated + filtered. Requires elevated role.\n\t */\n\tasync adminListUploads(\n\t\topts: { q?: string; docId?: string; limit?: number; offset?: number } = {},\n\t): Promise<{\n\t\tuploads: Array<{\n\t\t\tid: string;\n\t\t\tdoc_id: string;\n\t\t\tdoc_label: string | null;\n\t\t\tfilename: string;\n\t\t\tmime_type: string | null;\n\t\t\tsize: number | null;\n\t\t\tcontent_hash: string | null;\n\t\t\tref_count: number | null;\n\t\t\towner_id: string;\n\t\t\tcreated_at: number;\n\t\t}>;\n\t\ttotal: number;\n\t}> {\n\t\tconst p = new URLSearchParams();\n\t\tif (opts.q) p.set(\"q\", opts.q);\n\t\tif (opts.docId) p.set(\"doc_id\", opts.docId);\n\t\tif (opts.limit != null) p.set(\"limit\", String(opts.limit));\n\t\tif (opts.offset != null) p.set(\"offset\", String(opts.offset));\n\t\tconst qs = p.toString();\n\t\treturn this.request(\"GET\", `/admin/uploads${qs ? `?${qs}` : \"\"}`);\n\t}\n\n\t/**\n\t * Admin: aggregate storage figures. `logicalBytes` is what users\n\t * uploaded; `physicalBytes` is on-disk after content-addressed dedup;\n\t * `dedupSaved` is the difference. Requires elevated role.\n\t */\n\tasync adminStorageStats(): Promise<{\n\t\tuploadCount: number;\n\t\tblobCount: number;\n\t\tlogicalBytes: number;\n\t\tphysicalBytes: number;\n\t\tdedupSaved: number;\n\t}> {\n\t\treturn this.request(\"GET\", \"/admin/storage/stats\");\n\t}\n\n\t/**\n\t * Clear the lockout state on a user account: zeroes the failed-login\n\t * counter and `locked_until`. Requires elevated role (Admin or\n\t * Service). The action is recorded in the audit log under\n\t * `admin.user_unlock`.\n\t */\n\tasync adminUnlockUser(userId: string): Promise<void> {\n\t\tawait this.request(\"POST\", `/admin/users/${encodeURIComponent(userId)}/unlock`);\n\t}\n\n\t/**\n\t * Admin: every non-deleted document the user owns (`source: \"owner\"`)\n\t * or has an explicit permission grant on (`source: \"grant\"`, with\n\t * `role`). Answers \"what does this identity touch\" without an N+1\n\t * client tree walk. Labels are best-effort (they live in the CRDT).\n\t * Requires elevated role.\n\t */\n\tasync adminUserDocs(\n\t\tuserId: string,\n\t\topts: { limit?: number } = {},\n\t): Promise<{\n\t\tdocs: Array<{\n\t\t\tid: string;\n\t\t\tlabel: string | null;\n\t\t\tkind: string | null;\n\t\t\tdoc_type: string | null;\n\t\t\tparent_id: string | null;\n\t\t\tsource: \"owner\" | \"grant\";\n\t\t\trole: string | null;\n\t\t}>;\n\t}> {\n\t\tconst qs = opts.limit != null ? `?limit=${opts.limit}` : \"\";\n\t\treturn this.request(\n\t\t\t\"GET\",\n\t\t\t`/admin/users/${encodeURIComponent(userId)}/docs${qs}`,\n\t\t);\n\t}\n\n\t/**\n\t * List `service`-role users (runners, demo seeders, automation\n\t * identities). Requires Service role. Admins can see service users via\n\t * `/admin/users` too but cannot mint or rotate them.\n\t */\n\tasync adminListServiceAccounts(): Promise<{\n\t\titems: Array<{\n\t\t\tid: string;\n\t\t\tusername: string;\n\t\t\tpublic_key: string | null;\n\t\t\trevoked: boolean;\n\t\t\tdisplay_name: string | null;\n\t\t}>;\n\t}> {\n\t\treturn this.request(\"GET\", \"/admin/service-accounts\");\n\t}\n\n\t/**\n\t * Create a new `service`-role user. When `public_key` is omitted the\n\t * server generates a keypair and returns the private half in the\n\t * response — show it to the operator **once** and discard; the server\n\t * never persists it. Requires Service role.\n\t */\n\tasync adminCreateServiceAccount(body: {\n\t\tusername: string;\n\t\tpublic_key?: string;\n\t}): Promise<{\n\t\tid: string;\n\t\tusername: string;\n\t\tpublic_key: string;\n\t\trole: string;\n\t\tprivate_key?: string;\n\t}> {\n\t\treturn this.request(\"POST\", \"/admin/service-accounts\", { body });\n\t}\n\n\t/**\n\t * Rotate the active keypair on a service account. Old JWTs are\n\t * invalidated; old device keys are marked revoked; the canonical\n\t * `users.public_key` swaps to the new value. `users.id` stays put so\n\t * existing permission rows keep matching. Returns the new pubkey (and\n\t * private half when the server generated it). Requires Service role.\n\t */\n\tasync adminRotateServiceAccountKey(\n\t\tuserId: string,\n\t\tbody: { public_key?: string } = {},\n\t): Promise<{ id: string; public_key: string; private_key?: string }> {\n\t\treturn this.request(\n\t\t\t\"POST\",\n\t\t\t`/admin/service-accounts/${encodeURIComponent(userId)}/rotate-key`,\n\t\t\t{ body },\n\t\t);\n\t}\n\n\t/**\n\t * Lock a service account and revoke all of its device keys. Idempotent.\n\t * Refuses targets whose `users.role` isn't `\"service\"`. Requires\n\t * Service role.\n\t */\n\tasync adminRevokeServiceAccount(userId: string): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"DELETE\",\n\t\t\t`/admin/service-accounts/${encodeURIComponent(userId)}`,\n\t\t);\n\t}\n\n\t/**\n\t * Revoke a single device key on a user (any role). Bumps\n\t * `tokens_invalid_before` so open WS sessions tied to the key must\n\t * re-auth. Requires elevated role (Service or Admin@root).\n\t */\n\tasync adminRevokeDeviceKey(userId: string, keyId: string): Promise<void> {\n\t\tawait this.request(\n\t\t\t\"POST\",\n\t\t\t`/admin/users/${encodeURIComponent(userId)}/device-keys/${encodeURIComponent(keyId)}/revoke`,\n\t\t);\n\t}\n\n\t/**\n\t * Page through the audit log. Filters AND-combine; `limit` defaults to\n\t * 100 server-side. Requires elevated role.\n\t */\n\tasync adminAuditList(opts?: AuditQueryOpts): Promise<AuditLogEntry[]> {\n\t\tconst params = new URLSearchParams();\n\t\tif (opts?.event_type) params.set(\"event_type\", opts.event_type);\n\t\tif (opts?.actor_user_id) params.set(\"actor_user_id\", opts.actor_user_id);\n\t\tif (opts?.target_type) params.set(\"target_type\", opts.target_type);\n\t\tif (opts?.target_id) params.set(\"target_id\", opts.target_id);\n\t\tif (opts?.since_ts != null) params.set(\"since_ts\", String(opts.since_ts));\n\t\tif (opts?.until_ts != null) params.set(\"until_ts\", String(opts.until_ts));\n\t\tif (opts?.limit != null) params.set(\"limit\", String(opts.limit));\n\t\tif (opts?.offset != null) params.set(\"offset\", String(opts.offset));\n\t\tconst qs = params.toString();\n\t\tconst res = await this.request<{ items: AuditLogEntry[] }>(\n\t\t\t\"GET\",\n\t\t\t`/admin/audit${qs ? `?${qs}` : \"\"}`,\n\t\t);\n\t\treturn res.items;\n\t}\n\n\t/**\n\t * Stream the audit log as NDJSON (one JSON object per line) for SIEM\n\t * ingestion. Filters mirror {@link adminAuditList} minus `limit`/`offset`.\n\t * The server pages internally so memory usage is bounded; this method\n\t * buffers the full response into a string and is therefore best for\n\t * moderate exports — large dumps should consume `/admin/audit/export`\n\t * directly with a streaming HTTP client.\n\t */\n\tasync adminAuditExport(opts?: Omit<AuditQueryOpts, \"limit\" | \"offset\">): Promise<string> {\n\t\tconst params = new URLSearchParams();\n\t\tif (opts?.event_type) params.set(\"event_type\", opts.event_type);\n\t\tif (opts?.actor_user_id) params.set(\"actor_user_id\", opts.actor_user_id);\n\t\tif (opts?.target_type) params.set(\"target_type\", opts.target_type);\n\t\tif (opts?.target_id) params.set(\"target_id\", opts.target_id);\n\t\tif (opts?.since_ts != null) params.set(\"since_ts\", String(opts.since_ts));\n\t\tif (opts?.until_ts != null) params.set(\"until_ts\", String(opts.until_ts));\n\t\tconst qs = params.toString();\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) headers[\"Authorization\"] = `Bearer ${this._token}`;\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}/admin/audit/export${qs ? `?${qs}` : \"\"}`,\n\t\t\t{ method: \"GET\", headers },\n\t\t);\n\t\tif (!res.ok) throw await this.toError(res, \"GET\", \"/admin/audit/export\");\n\t\treturn res.text();\n\t}\n\n\t/**\n\t * Verify the integrity of the audit-log hash chain. Returns the result\n\t * unchanged: `status: \"ok\"` when the chain is intact, `status: \"broken\"`\n\t * with a `break` payload identifying the first divergent row when\n\t * tampering is detected. Wraps `GET /admin/audit/verify`. Requires\n\t * elevated role.\n\t *\n\t * Note: the server returns HTTP 409 on a broken chain — this method\n\t * special-cases the 409 status and returns the body as a successful\n\t * result rather than throwing, because \"broken\" is a valid answer\n\t * from the verifier, not an error.\n\t */\n\tasync adminAuditVerify(): Promise<AuditVerifyResult> {\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) headers[\"Authorization\"] = `Bearer ${this._token}`;\n\t\tconst res = await this._fetch(`${this.baseUrl}/admin/audit/verify`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders,\n\t\t});\n\t\tif (res.status === 200 || res.status === 409) {\n\t\t\treturn res.json() as Promise<AuditVerifyResult>;\n\t\t}\n\t\tthrow await this.toError(res, \"GET\", \"/admin/audit/verify\");\n\t}\n\n\t/**\n\t * Download a tar archive of the schema-meaningful tables (users,\n\t * documents, permissions, invites, optionally audit log). Requires\n\t * elevated role. The server gzips the response when the client sends\n\t * `Accept-Encoding: gzip` — `fetch` handles that transparently, so\n\t * the returned Blob is the raw tar bytes.\n\t */\n\tasync adminBackupDump(opts?: { includeAudit?: boolean }): Promise<Blob> {\n\t\tconst params = new URLSearchParams();\n\t\tif (opts?.includeAudit) params.set(\"include_audit\", \"true\");\n\t\tconst qs = params.toString();\n\t\tconst headers: Record<string, string> = {};\n\t\tif (this._token) headers[\"Authorization\"] = `Bearer ${this._token}`;\n\t\tconst res = await this._fetch(\n\t\t\t`${this.baseUrl}/admin/backup/dump${qs ? `?${qs}` : \"\"}`,\n\t\t\t{ method: \"GET\", headers },\n\t\t);\n\t\tif (!res.ok) throw await this.toError(res, \"GET\", \"/admin/backup/dump\");\n\t\treturn res.blob();\n\t}\n\n\t// ── Admin: runtime config store ──────────────────────────────────────────\n\n\t/**\n\t * List every registered config field with current value + origin\n\t * (`default` / `env` / `global_override` / `route_override`). Requires\n\t * elevated role.\n\t */\n\tasync adminConfigList(): Promise<AdminConfigField[]> {\n\t\tconst res = await this.request<{ items: AdminConfigField[] }>(\n\t\t\t\"GET\", \"/admin/config\",\n\t\t);\n\t\treturn res.items;\n\t}\n\n\t/** Read a single config field by dotted path (e.g. `\"access.authenticated\"`). */\n\tasync adminConfigGet(path: string): Promise<AdminConfigField> {\n\t\treturn this.request<AdminConfigField>(\n\t\t\t\"GET\", `/admin/config/fields/${encodeURIComponent(path)}`,\n\t\t);\n\t}\n\n\t/**\n\t * Set a runtime override on a config field. The field must be marked\n\t * `runtime_mutable = true` in the registry; immutable fields return a\n\t * schema error. Persists to the `settings_overrides` table.\n\t */\n\tasync adminConfigSet(path: string, value: unknown): Promise<AdminConfigField> {\n\t\treturn this.request<AdminConfigField>(\n\t\t\t\"PUT\", `/admin/config/fields/${encodeURIComponent(path)}`,\n\t\t\t{ body: { value } },\n\t\t);\n\t}\n\n\t/**\n\t * Clear a runtime override and revert the field to its env/TOML/default\n\t * base value. Returns `true` when an override was actually removed.\n\t */\n\tasync adminConfigUnset(path: string): Promise<boolean> {\n\t\tconst res = await this.request<{ existed: boolean }>(\n\t\t\t\"DELETE\", `/admin/config/fields/${encodeURIComponent(path)}`,\n\t\t);\n\t\treturn res.existed;\n\t}\n\n\t/**\n\t * Diagnostic dump of every `ABRA_*` env var the running process saw at\n\t * boot, mapped to its config path. Use this to debug\n\t * \"I set this in `.env` but the server reports a different value\".\n\t * Secrets are redacted (`value: null`, `redacted: true`).\n\t */\n\tasync adminConfigEnvSnapshot(): Promise<EnvSnapshotResponse> {\n\t\treturn this.request<EnvSnapshotResponse>(\"GET\", \"/admin/config/env-snapshot\");\n\t}\n\n\t/**\n\t * List every route pattern that currently has at least one per-route\n\t * config override. Use {@link adminConfigGetRoute} to read individual\n\t * fields. Requires elevated role.\n\t */\n\tasync adminConfigListRoutes(): Promise<string[]> {\n\t\tconst res = await this.request<{ routes: string[] }>(\n\t\t\t\"GET\", \"/admin/config/routes\",\n\t\t);\n\t\treturn res.routes;\n\t}\n\n\t/**\n\t * Read a field's effective value scoped to `route`, falling back to\n\t * the global value when no per-route override exists. `origin_kind`\n\t * is `\"route_override\"` only when an override is actually set.\n\t */\n\tasync adminConfigGetRoute(route: string, path: string): Promise<AdminConfigField> {\n\t\treturn this.request<AdminConfigField>(\n\t\t\t\"GET\",\n\t\t\t`/admin/config/routes/${encodeURIComponent(route)}/fields/${encodeURIComponent(path)}`,\n\t\t);\n\t}\n\n\t/** Set or replace a per-route override. Mirrors {@link adminConfigSet}. */\n\tasync adminConfigSetRoute(route: string, path: string, value: unknown): Promise<AdminConfigField> {\n\t\treturn this.request<AdminConfigField>(\n\t\t\t\"PUT\",\n\t\t\t`/admin/config/routes/${encodeURIComponent(route)}/fields/${encodeURIComponent(path)}`,\n\t\t\t{ body: { value } },\n\t\t);\n\t}\n\n\t/** Clear a per-route override (falls back to global). True if one existed. */\n\tasync adminConfigUnsetRoute(route: string, path: string): Promise<boolean> {\n\t\tconst res = await this.request<{ existed: boolean }>(\n\t\t\t\"DELETE\",\n\t\t\t`/admin/config/routes/${encodeURIComponent(route)}/fields/${encodeURIComponent(path)}`,\n\t\t);\n\t\treturn res.existed;\n\t}\n\n\t// ── Snapshots ────────────────────────────────────────────────────────────\n\n\t/** List snapshot metadata for a document. */\n\tasync listSnapshots(docId: string, opts?: { limit?: number; offset?: number }): Promise<SnapshotMeta[]> {\n\t\tconst params = new URLSearchParams();\n\t\tif (opts?.limit != null) params.set(\"limit\", String(opts.limit));\n\t\tif (opts?.offset != null) params.set(\"offset\", String(opts.offset));\n\t\tconst qs = params.toString();\n\t\tconst res = await this.request<{ snapshots: SnapshotMeta[] }>(\n\t\t\t\"GET\", `/docs/${encodeURIComponent(docId)}/snapshots${qs ? `?${qs}` : \"\"}`,\n\t\t);\n\t\treturn res.snapshots;\n\t}\n\n\t/** Fetch a single snapshot including its base64-encoded data blob.\n\t * Pass `{ include: \"files\" }` to also receive the joined upload list\n\t * (each `fileBlock` / `coverUploadId` resolved against `uploads`). */\n\tasync getSnapshot(\n\t\tdocId: string,\n\t\tversion: number,\n\t\topts?: { include?: \"files\" | string },\n\t): Promise<SnapshotData> {\n\t\tconst qs = opts?.include ? `?include=${encodeURIComponent(opts.include)}` : \"\";\n\t\treturn this.request<SnapshotData>(\n\t\t\t\"GET\", `/docs/${encodeURIComponent(docId)}/snapshots/${version}${qs}`,\n\t\t);\n\t}\n\n\t/** Create a manual snapshot of the current document state. */\n\tasync createSnapshot(docId: string, opts?: { label?: string }): Promise<SnapshotCreateResult> {\n\t\treturn this.request<SnapshotCreateResult>(\n\t\t\t\"POST\", `/docs/${encodeURIComponent(docId)}/snapshots`,\n\t\t\t{ body: opts ?? {} },\n\t\t);\n\t}\n\n\t/** Delete a specific snapshot version. Requires manage permission. */\n\tasync deleteSnapshot(docId: string, version: number): Promise<void> {\n\t\tawait this.request(\"DELETE\", `/docs/${encodeURIComponent(docId)}/snapshots/${version}`);\n\t}\n\n\t/** Restore a snapshot by merging it forward into the current document state. */\n\tasync restoreSnapshot(docId: string, version: number): Promise<SnapshotRestoreResult> {\n\t\treturn this.request<SnapshotRestoreResult>(\n\t\t\t\"POST\", `/docs/${encodeURIComponent(docId)}/snapshots/${version}/restore`,\n\t\t\t{ body: {} },\n\t\t);\n\t}\n\n\t/** Fork a snapshot into a new document. */\n\tasync forkSnapshot(docId: string, version: number): Promise<SnapshotForkResult> {\n\t\treturn this.request<SnapshotForkResult>(\n\t\t\t\"POST\", `/docs/${encodeURIComponent(docId)}/snapshots/${version}/fork`,\n\t\t\t{ body: {} },\n\t\t);\n\t}\n\n\t// ── System ───────────────────────────────────────────────────────────────\n\n\t/** Health check — no auth required. */\n\tasync health(): Promise<HealthStatus> {\n\t\treturn this.request<HealthStatus>(\"GET\", \"/health\", { auth: false });\n\t}\n\n\t/**\n\t * Readiness probe — pings the database. Returns 200 with\n\t * `status: \"ready\"` only when the server can serve traffic, 503 with\n\t * `status: \"unready\"` otherwise (load balancers / Kubernetes probes\n\t * use the status code; the body is informational).\n\t *\n\t * The 503 case is special-cased here: instead of throwing, the method\n\t * returns the unready body so callers can react to the state without\n\t * try/catch boilerplate.\n\t */\n\tasync readyz(): Promise<ReadyzStatus> {\n\t\tconst res = await this._fetch(`${this.baseUrl}/readyz`, { method: \"GET\" });\n\t\tif (res.status === 200 || res.status === 503) {\n\t\t\treturn res.json() as Promise<ReadyzStatus>;\n\t\t}\n\t\tthrow await this.toError(res, \"GET\", \"/readyz\");\n\t}\n\n\t/**\n\t * Fetch server metadata including `root_doc_id` and the `[access]` policy.\n\t * No auth required.\n\t */\n\tasync serverInfo(): Promise<ServerInfo> {\n\t\treturn this.request<ServerInfo>(\"GET\", \"/info\", { auth: false });\n\t}\n\n\t/**\n\t * Drop this browser's caches for this server if its database has been\n\t * REPLACED since the last visit, and report what happened.\n\t *\n\t * **Call it before opening any provider**, and await it. A deleted database\n\t * is not a tombstone — it is a peer that lost its memory — so a tab that\n\t * reconnects with stale IndexedDB re-pushes the old tree into the fresh one\n\t * and a seeder adds its own on top: every page twice, then three times. Once\n\t * a provider holds a store open, `deleteDatabase` blocks instead of deleting\n\t * and the damage is already queued; those stores come back in `blocked`,\n\t * which is a signal that this ran too late rather than something to ignore.\n\t *\n\t * Returns `null` when there is nothing to do — no `server_id`, no browser\n\t * storage, a first visit, or the same database as last time. It never\n\t * throws: an app must not fail to start because a cache could not be tidied.\n\t *\n\t * @see dropCachesIfServerReplaced for what is dropped and what is kept.\n\t */\n\tasync ensureFreshServer(): Promise<ServerResetOutcome | null> {\n\t\ttry {\n\t\t\tconst info = await this.serverInfo();\n\t\t\tif (!info?.server_id) return null;\n\t\t\t// `host`, matching how providers scope their stores — the port is part\n\t\t\t// of a server's identity, so two servers on one machine do not share a\n\t\t\t// cache namespace.\n\t\t\tconst host = new URL(this.wsUrl).host;\n\t\t\treturn await dropCachesIfServerReplaced(host, info.server_id);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Fetch ICE server configuration for WebRTC peer connections.\n\t * Falls back to default Google STUN server if the endpoint is unavailable.\n\t * No auth required.\n\t */\n\tasync getIceServers(): Promise<RTCIceServer[]> {\n\t\ttry {\n\t\t\tconst res = await this.request<{ iceServers: RTCIceServer[] }>(\n\t\t\t\t\"GET\",\n\t\t\t\t\"/ice-servers\",\n\t\t\t\t{ auth: false },\n\t\t\t);\n\t\t\treturn res.iceServers;\n\t\t} catch {\n\t\t\treturn [{ urls: \"stun:stun.l.google.com:19302\" }];\n\t\t}\n\t}\n\n\t// ── Internals ────────────────────────────────────────────────────────────\n\n\tprivate async request<T = void>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\topts?: { body?: unknown; auth?: boolean },\n\t): Promise<T> {\n\t\tconst auth = opts?.auth ?? true;\n\t\tconst headers: Record<string, string> = {};\n\n\t\tif (auth && this._token) {\n\t\t\theaders[\"Authorization\"] = `Bearer ${this._token}`;\n\t\t}\n\n\t\tconst init: RequestInit = { method, headers, signal: AbortSignal.timeout(30_000) };\n\n\t\tif (opts?.body !== undefined) {\n\t\t\theaders[\"Content-Type\"] = \"application/json\";\n\t\t\tinit.body = JSON.stringify(opts.body);\n\t\t}\n\n\t\tconst res = await this._fetch(`${this.baseUrl}${path}`, init);\n\n\t\tif (!res.ok) {\n\t\t\tthrow await this.toError(res, method, path);\n\t\t}\n\n\t\t// 204 No Content\n\t\tif (res.status === 204) {\n\t\t\treturn undefined as T;\n\t\t}\n\n\t\treturn res.json() as Promise<T>;\n\t}\n\n\tprivate async requestOrNull<T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\topts?: { body?: unknown; auth?: boolean },\n\t): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await this.request<T>(method, path, opts);\n\t\t} catch (e: unknown) {\n\t\t\tif (typeof e === \"object\" && e !== null && \"status\" in e && (e as { status: number }).status === 404) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tprivate async toError(res: Response, method?: string, path?: string): Promise<Error> {\n\t\tlet message: string;\n\t\ttry {\n\t\t\tconst body = await res.json() as { error?: string };\n\t\t\tmessage = body.error ?? res.statusText;\n\t\t} catch {\n\t\t\tmessage = res.statusText;\n\t\t}\n\t\tconst prefix = method && path ? `${method} ${path}: ` : \"\";\n\t\tconst err = new Error(`${prefix}${message} (${res.status})`);\n\t\t(err as any).status = res.status;\n\t\t// Surface 401/403 to the auth-failed handler so consumers can trigger\n\t\t// reauth without waiting for the next WS action. Fire-and-forget —\n\t\t// the original Promise still rejects so callers handle their own\n\t\t// error path. Wrap in setTimeout(0) so the callback runs out-of-band\n\t\t// of the current request's microtask queue.\n\t\tif ((res.status === 401 || res.status === 403) && this._onAuthFailed) {\n\t\t\tconst lower = message.toLowerCase();\n\t\t\tlet reason: AuthFailureReason = res.status === 401 ? \"unauthorized\" : \"forbidden\";\n\t\t\tif (/user not found|user_not_found|public key not registered|no such user/.test(lower)) {\n\t\t\t\treason = \"user_not_found\";\n\t\t\t} else if (/account revoked|user account revoked/.test(lower)) {\n\t\t\t\treason = \"account_revoked\";\n\t\t\t} else if (/forbidden|insufficient permissions/.test(lower)) {\n\t\t\t\treason = \"forbidden\";\n\t\t\t}\n\t\t\tconst ctx: AuthFailureContext = {\n\t\t\t\tstatus: res.status,\n\t\t\t\tmessage,\n\t\t\t\treason,\n\t\t\t\tmethod: method ?? \"\",\n\t\t\t\tpath: path ?? \"\",\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tsetTimeout(() => { try { this._onAuthFailed!(ctx); } catch { /* swallow */ } }, 0);\n\t\t\t} catch { /* setTimeout unavailable in some sandboxes — drop the signal */ }\n\t\t}\n\t\treturn err;\n\t}\n\n\tprivate loadPersistedToken(): string | null {\n\t\ttry {\n\t\t\treturn localStorage.getItem(this.storageKey);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate persistToken(token: string): void {\n\t\ttry {\n\t\t\tlocalStorage.setItem(this.storageKey, token);\n\t\t} catch {\n\t\t\t// localStorage unavailable (SSR / Node.js)\n\t\t}\n\t}\n\n\tprivate clearPersistedToken(): void {\n\t\ttry {\n\t\t\tlocalStorage.removeItem(this.storageKey);\n\t\t} catch {\n\t\t\t// localStorage unavailable\n\t\t}\n\t}\n}\n"],"mappings":";;;;;AAkCA,SAAS,WAAW,KAAyB;AAC5C,QAAO,WAAW,KAAK,KAAK,IAAI,GAAG,MAAM,EAAE,WAAW,EAAE,CAAC;;;;;;;;;AAU1D,SAAS,wBAAwB,QAAwB;CACxD,IAAI,MAAM,OAAO,QAAQ,MAAM,IAAI,CAAC,QAAQ,MAAM,IAAI;CACtD,MAAM,MAAM,IAAI,SAAS;AACzB,KAAI,IAAK,QAA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