@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,1424 @@
1
+ import { Kind, SERVER_ROOT_ID } from "./types.js";
2
+ import { dropCachesIfServerReplaced } from "./ServerReset.js";
3
+ import { deriveDmDocId } from "./docIds.js";
4
+
5
+ //#region packages/provider/src/AbracadabraClient.ts
6
+ function fromBase64(b64) {
7
+ return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
8
+ }
9
+ /**
10
+ * Decode a base64url-encoded string (e.g. a JWT header/payload segment) to
11
+ * UTF-8 text. `atob` only accepts standard base64, so we translate the
12
+ * url-safe alphabet (`-`/`_`) and re-pad before decoding — otherwise a
13
+ * perfectly valid token whose payload happens to contain `-` or `_` throws
14
+ * and gets misclassified as invalid/expired.
15
+ */
16
+ function decodeBase64UrlToString(b64url) {
17
+ let b64 = b64url.replace(/-/g, "+").replace(/_/g, "/");
18
+ const pad = b64.length % 4;
19
+ if (pad) b64 += "=".repeat(4 - pad);
20
+ const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
21
+ return new TextDecoder().decode(bytes);
22
+ }
23
+ /**
24
+ * Read a JWT's `exp` / `iat` claims, in ms. `0` for anything unreadable.
25
+ *
26
+ * Deliberately tolerant: a token this cannot parse is treated as expiring now,
27
+ * which costs one extra handshake and never costs a dead session.
28
+ */
29
+ function readJwtTimes(token) {
30
+ if (!token) return {
31
+ exp: 0,
32
+ iat: 0
33
+ };
34
+ const payload = token.split(".")[1];
35
+ if (!payload) return {
36
+ exp: 0,
37
+ iat: 0
38
+ };
39
+ try {
40
+ const claims = JSON.parse(decodeBase64UrlToString(payload));
41
+ return {
42
+ exp: typeof claims.exp === "number" ? claims.exp * 1e3 : 0,
43
+ iat: typeof claims.iat === "number" ? claims.iat * 1e3 : 0
44
+ };
45
+ } catch {
46
+ return {
47
+ exp: 0,
48
+ iat: 0
49
+ };
50
+ }
51
+ }
52
+ var AbracadabraClient = class {
53
+ constructor(config) {
54
+ this.rootListInflight = /* @__PURE__ */ new Map();
55
+ this.streamTokens = /* @__PURE__ */ new Map();
56
+ this.streamTokenInflight = /* @__PURE__ */ new Map();
57
+ this._renew = null;
58
+ this._renewing = null;
59
+ this._renewTimer = null;
60
+ this._tokenListeners = /* @__PURE__ */ new Set();
61
+ this.baseUrl = config.url.replace(/\/+$/, "");
62
+ this.persistAuth = config.persistAuth ?? typeof localStorage !== "undefined";
63
+ this.storageKey = config.storageKey ?? "abracadabra:auth";
64
+ this._fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
65
+ this.cache = config.cache ?? null;
66
+ this._onAuthFailed = config.onAuthFailed ?? null;
67
+ this.renewMarginMs = config.tokenRenewMarginMs ?? 20 * 6e4;
68
+ this.renewCheckMs = config.tokenRenewCheckMs ?? 6e4;
69
+ this._token = config.token ?? this.loadPersistedToken() ?? null;
70
+ }
71
+ get token() {
72
+ return this._token;
73
+ }
74
+ set token(value) {
75
+ const changed = value !== this._token;
76
+ this._token = value;
77
+ this.streamTokens.clear();
78
+ this.streamTokenInflight.clear();
79
+ if (this.persistAuth) if (value) this.persistToken(value);
80
+ else this.clearPersistedToken();
81
+ if (changed && value) {
82
+ this.scheduleSessionRenewal();
83
+ for (const listener of this._tokenListeners) try {
84
+ listener(value);
85
+ } catch {}
86
+ }
87
+ }
88
+ get isAuthenticated() {
89
+ return this._token !== null;
90
+ }
91
+ /** Check if the current JWT token is present and not expired. */
92
+ isTokenValid() {
93
+ if (!this._token) return false;
94
+ try {
95
+ const [, payload] = this._token.split(".");
96
+ const { exp } = JSON.parse(decodeBase64UrlToString(payload));
97
+ return typeof exp === "number" && exp * 1e3 > Date.now();
98
+ } catch {
99
+ return false;
100
+ }
101
+ }
102
+ /** When the current token stops validating, in ms. `0` when unknown. */
103
+ get tokenExpiresAt() {
104
+ return readJwtTimes(this._token).exp;
105
+ }
106
+ /**
107
+ * Install the way this client re-authenticates itself, or `null` to stop.
108
+ *
109
+ * {@link loginWithKey} installs one for you, so a key-authenticated client
110
+ * — every Node runner, and every browser session on a crypto identity —
111
+ * renews without its consumer doing anything. Install one by hand for a
112
+ * password session or any other flow that can mint a fresh token.
113
+ *
114
+ * The function must return the new JWT; adopting it (and notifying open
115
+ * sockets) is this client's job.
116
+ */
117
+ setSessionRenewer(renew) {
118
+ this._renew = renew;
119
+ if (renew) this.scheduleSessionRenewal();
120
+ else this.stopSessionRenewal();
121
+ }
122
+ /** Whether this client knows how to re-authenticate itself. */
123
+ get canRenewSession() {
124
+ return this._renew !== null;
125
+ }
126
+ /**
127
+ * Called whenever the session token changes — a login, a renewal, a device
128
+ * refresh, a key revocation. Providers use this to re-arm sockets that are
129
+ * already open. Returns an unsubscribe function.
130
+ */
131
+ onTokenChanged(listener) {
132
+ this._tokenListeners.add(listener);
133
+ return () => this._tokenListeners.delete(listener);
134
+ }
135
+ /**
136
+ * Make sure the token has life left in it, re-minting if it does not.
137
+ *
138
+ * Cheap when the token is fresh — one subtraction — so callers need not
139
+ * reason about when the last renewal was, and concurrent callers share one
140
+ * handshake. Returns whether the session is believed good; `false` is not
141
+ * fatal, and the caller's own failure is still the authority.
142
+ */
143
+ async ensureFreshToken(marginMs) {
144
+ if (!this._renew) return this.isTokenValid();
145
+ if (this._renewing) return this._renewing;
146
+ const { exp } = readJwtTimes(this._token);
147
+ if (exp > 0 && exp - Date.now() > this.renewMargin(marginMs)) return true;
148
+ const mint = this._renew;
149
+ const renew = (async () => {
150
+ try {
151
+ const token = await mint();
152
+ if (token && token !== this._token) this.token = token;
153
+ return true;
154
+ } catch {
155
+ return false;
156
+ } finally {
157
+ this._renewing = null;
158
+ }
159
+ })();
160
+ this._renewing = renew;
161
+ return renew;
162
+ }
163
+ /**
164
+ * How long before `exp` this session is re-minted.
165
+ *
166
+ * Capped at a third of the token's own lifetime, so a server configured
167
+ * with short-lived tokens is not re-authenticated on every check — without
168
+ * the cap a 45-second token against a 20-minute margin would mint a new
169
+ * session every time anything asked.
170
+ */
171
+ renewMargin(marginMs) {
172
+ const { exp, iat } = readJwtTimes(this._token);
173
+ const lifetime = exp > iat && iat > 0 ? exp - iat : Number.POSITIVE_INFINITY;
174
+ return Math.min(marginMs ?? this.renewMarginMs, lifetime / 3);
175
+ }
176
+ /**
177
+ * Arm a single timer for the moment this token needs replacing.
178
+ *
179
+ * Scheduled from the token's OWN expiry rather than on a fixed interval,
180
+ * and that is not tidiness. A poll can outrun the margin: measured against
181
+ * a server issuing 45-second tokens, a 60-second poll first fired fifteen
182
+ * seconds AFTER the token had already lapsed — long enough for the
183
+ * awareness heartbeat to hit an expired session and have the socket dropped
184
+ * under it. A deadline cannot be outrun by the thing it is a deadline for.
185
+ *
186
+ * Re-armed on every token change, so a renewal schedules the next one.
187
+ */
188
+ scheduleSessionRenewal() {
189
+ this.stopSessionRenewal();
190
+ if (!this._renew || this.renewCheckMs <= 0) return;
191
+ const { exp } = readJwtTimes(this._token);
192
+ const delay = exp > 0 ? Math.max(1e3, exp - Date.now() - this.renewMargin()) : this.renewCheckMs;
193
+ this._renewTimer = setTimeout(() => {
194
+ this.ensureFreshToken().catch(() => false).finally(() => this.scheduleSessionRenewal());
195
+ }, Math.min(delay, 720 * 6e4));
196
+ this._renewTimer.unref?.();
197
+ }
198
+ stopSessionRenewal() {
199
+ if (!this._renewTimer) return;
200
+ clearTimeout(this._renewTimer);
201
+ this._renewTimer = null;
202
+ }
203
+ /**
204
+ * Stop renewing and drop every listener. Call when a client is discarded —
205
+ * a long-lived consumer that builds one client per connection would
206
+ * otherwise leave a timer per discarded client.
207
+ */
208
+ destroy() {
209
+ this.stopSessionRenewal();
210
+ this._renew = null;
211
+ this._tokenListeners.clear();
212
+ }
213
+ /** Derives ws:// or wss:// URL from the http(s) base URL. */
214
+ get wsUrl() {
215
+ return this.baseUrl.replace(/^https:\/\//, "wss://").replace(/^http:\/\//, "ws://") + "/ws";
216
+ }
217
+ /** Register a new user with password. */
218
+ async register(opts) {
219
+ return this.request("POST", "/auth/register", {
220
+ body: opts,
221
+ auth: false
222
+ });
223
+ }
224
+ /**
225
+ * Register a new user with an Ed25519 public key (crypto auth).
226
+ * Username is optional — if omitted, a short identifier is derived from the key.
227
+ */
228
+ async registerWithKey(opts) {
229
+ const username = opts.username ?? `user-${opts.publicKey.slice(0, 8)}`;
230
+ return this.request("POST", "/auth/register", {
231
+ body: {
232
+ username,
233
+ identityPublicKey: opts.publicKey,
234
+ deviceName: opts.deviceName,
235
+ displayName: opts.displayName,
236
+ email: opts.email,
237
+ inviteCode: opts.inviteCode,
238
+ x25519Key: opts.x25519Key
239
+ },
240
+ auth: false
241
+ });
242
+ }
243
+ /** Login with username + password. Auto-persists returned token. */
244
+ async login(opts) {
245
+ const res = await this.request("POST", "/auth/login", {
246
+ body: opts,
247
+ auth: false
248
+ });
249
+ this.token = res.token;
250
+ return res.token;
251
+ }
252
+ /** Request an Ed25519 crypto auth challenge for the given public key. */
253
+ async challenge(publicKey) {
254
+ return this.request("POST", "/auth/challenge", {
255
+ body: { publicKey },
256
+ auth: false
257
+ });
258
+ }
259
+ /** Verify an Ed25519 signature to complete crypto auth. Auto-persists token. */
260
+ async verify(opts) {
261
+ const res = await this.request("POST", "/auth/verify", {
262
+ body: opts,
263
+ auth: false
264
+ });
265
+ this.token = res.token;
266
+ return res.token;
267
+ }
268
+ /**
269
+ * Full crypto auth flow: challenge → sign → verify.
270
+ * Convenience method combining challenge() + external signing + verify().
271
+ */
272
+ async loginWithKey(publicKey, signChallenge) {
273
+ const { challenge } = await this.challenge(publicKey);
274
+ const signature = await signChallenge(challenge);
275
+ const token = await this.verify({
276
+ publicKey,
277
+ signature,
278
+ challenge
279
+ });
280
+ this.setSessionRenewer(() => this.loginWithKey(publicKey, signChallenge));
281
+ return token;
282
+ }
283
+ /** Add a new Ed25519 public key to the current user (multi-device). */
284
+ async addKey(opts) {
285
+ await this.request("POST", "/auth/keys", { body: {
286
+ publicKey: opts.publicKey,
287
+ deviceName: opts.deviceName,
288
+ x25519Key: opts.x25519Key
289
+ } });
290
+ }
291
+ /** List all registered public keys for the current user. */
292
+ async listKeys() {
293
+ return (await this.request("GET", "/auth/keys")).keys;
294
+ }
295
+ /** Rename a registered device key. */
296
+ async renameKey(keyId, deviceName) {
297
+ await this.request("PATCH", `/auth/keys/${encodeURIComponent(keyId)}`, { body: { deviceName } });
298
+ }
299
+ /**
300
+ * Revoke a public key by its ID. The server treats this as a panic
301
+ * action: every outstanding JWT for the account is invalidated (a stolen
302
+ * device's token must die immediately, and tokens carry no per-key
303
+ * claim), and a fresh token for THIS session is returned and adopted
304
+ * automatically — so the device performing the revocation stays
305
+ * authenticated while every other device silently re-auths.
306
+ */
307
+ async revokeKey(keyId) {
308
+ const res = await this.request("DELETE", `/auth/keys/${encodeURIComponent(keyId)}`);
309
+ if (res && typeof res === "object" && typeof res.token === "string") this.token = res.token;
310
+ }
311
+ /** Create a single-use device invite code for pairing a new device to this account. */
312
+ async createDeviceInvite(opts) {
313
+ return this.request("POST", "/auth/device-invite", { body: opts?.expiresIn != null ? { expiresIn: opts.expiresIn } : {} });
314
+ }
315
+ /** Redeem a device invite code to register a new device key. Returns a JWT token. */
316
+ async redeemDeviceInvite(opts) {
317
+ return this.request("POST", "/auth/device-redeem", {
318
+ body: {
319
+ code: opts.code,
320
+ publicKey: opts.publicKey,
321
+ x25519Key: opts.x25519Key,
322
+ deviceName: opts.deviceName
323
+ },
324
+ auth: false
325
+ });
326
+ }
327
+ /** Request a device session token after successful crypto auth. Requires valid JWT. */
328
+ async requestDeviceSession(opts) {
329
+ return this.request("POST", "/auth/device-session", { body: {
330
+ publicKey: opts.publicKey,
331
+ deviceName: opts.deviceName
332
+ } });
333
+ }
334
+ /** Exchange a device session token for a fresh JWT. No biometric/passkey needed. */
335
+ async refreshWithDeviceSession(sessionToken) {
336
+ const res = await this.request("POST", "/auth/refresh", {
337
+ body: { sessionToken },
338
+ auth: false
339
+ });
340
+ this.token = res.token;
341
+ return res.token;
342
+ }
343
+ /** List active device sessions for the authenticated user. */
344
+ async listDeviceSessions() {
345
+ return (await this.request("GET", "/auth/device-session")).sessions;
346
+ }
347
+ /** Revoke a device session by ID. */
348
+ async revokeDeviceSession(sessionId) {
349
+ await this.request("DELETE", `/auth/device-session/${encodeURIComponent(sessionId)}`);
350
+ }
351
+ /**
352
+ * Fetch a short-lived anonymous pairing token for WebRTC signaling.
353
+ * No authentication required. The token only grants access to `__pairing_*` rooms.
354
+ */
355
+ static async getPairingToken(serverUrl) {
356
+ let base = serverUrl;
357
+ while (base.endsWith("/")) base = base.slice(0, -1);
358
+ const resp = await fetch(`${base}/auth/pairing-token`, { method: "POST" });
359
+ if (!resp.ok) throw new Error(`Failed to fetch pairing token: ${resp.status}`);
360
+ const { token } = await resp.json();
361
+ return token;
362
+ }
363
+ /** Get encryption info for a document. */
364
+ async getDocEncryption(docId) {
365
+ return this.request("GET", `/docs/${encodeURIComponent(docId)}/encryption`);
366
+ }
367
+ /** Set the encryption mode for a document (no downgrade). */
368
+ async setDocEncryption(docId, mode) {
369
+ await this.request("PATCH", `/docs/${encodeURIComponent(docId)}/encryption`, { body: { mode } });
370
+ }
371
+ /** Get the caller's key envelope for a document (for decrypting the DocKey). */
372
+ async getMyKeyEnvelope(docId) {
373
+ return this.requestOrNull("GET", `/docs/${encodeURIComponent(docId)}/key-envelope`);
374
+ }
375
+ /** Upload key envelopes for a document (Owner only). */
376
+ async uploadKeyEnvelopes(docId, opts) {
377
+ await this.request("POST", `/docs/${encodeURIComponent(docId)}/key-envelopes`, { body: opts });
378
+ }
379
+ /** Get the X25519 public key for a user. */
380
+ async getUserX25519Key(userId) {
381
+ return (await this.requestOrNull("GET", `/users/${encodeURIComponent(userId)}/x25519-key`))?.x25519_key ?? null;
382
+ }
383
+ /** List all non-revoked keys for a user (Owner/Admin or self). */
384
+ async listUserKeys(userId) {
385
+ return (await this.request("GET", `/users/${encodeURIComponent(userId)}/keys`)).keys;
386
+ }
387
+ /** Fetch encrypted E2E update blobs since a given sequence number. */
388
+ async getE2EUpdatesSince(docId, sinceSeq) {
389
+ return (await this.request("GET", `/docs/${encodeURIComponent(docId)}/e2e-updates?since_seq=${sinceSeq}`)).updates.map((u) => ({
390
+ seq: u.seq,
391
+ data: fromBase64(u.data)
392
+ }));
393
+ }
394
+ /**
395
+ * Clear token from memory and storage. Local-only; does NOT notify the
396
+ * server. Use {@link logoutServer} or {@link logoutAll} when you also
397
+ * want the JWT to land in the server's revocation cache.
398
+ */
399
+ logout() {
400
+ this.token = null;
401
+ }
402
+ /**
403
+ * Revoke the current JWT server-side and clear local state. Adds the
404
+ * token's `jti` to the server's revocation cache so subsequent requests
405
+ * with this token return 401, even if the JWT signature still verifies
406
+ * and `exp` hasn't passed. Safe to call when no token is set — degrades
407
+ * to a local clear.
408
+ *
409
+ * Network errors are swallowed (the local state is always cleared) so
410
+ * a sign-out flow can't get stuck on a flaky connection. The endpoint
411
+ * itself is idempotent.
412
+ */
413
+ async logoutServer() {
414
+ if (this._token) try {
415
+ await this.request("POST", "/auth/logout");
416
+ } catch {}
417
+ this.token = null;
418
+ }
419
+ /**
420
+ * Bump the user's `tokens_invalid_before` watermark, revoking every
421
+ * outstanding JWT for this user — every device, every browser, every
422
+ * pending background tab. The current token is required (this is the
423
+ * user's "I am who I say I am" assertion). After the call returns,
424
+ * future authenticated requests with any pre-existing token return 401.
425
+ */
426
+ async logoutAll() {
427
+ await this.request("POST", "/auth/logout-all");
428
+ this.token = null;
429
+ }
430
+ /**
431
+ * Request an email verification message be sent to the current user's
432
+ * registered email address. Requires authentication. Server enforces a
433
+ * per-user rate limit (1/min, 10/day). Returns 404 if email
434
+ * verification is disabled in `[auth.email_verification]`.
435
+ */
436
+ async requestEmailVerification() {
437
+ await this.request("POST", "/auth/verify-email/request", { body: {} });
438
+ }
439
+ /**
440
+ * Confirm an email verification token (typically opened from a link in
441
+ * the verification email). On success the server sets
442
+ * `users.email_verified_at`. No auth required — the token itself is
443
+ * the proof.
444
+ */
445
+ async confirmEmailVerification(token) {
446
+ await this.request("POST", "/auth/verify-email/confirm", {
447
+ body: { token },
448
+ auth: false
449
+ });
450
+ }
451
+ /**
452
+ * Initiate a password reset for a user identified by username or
453
+ * email. The server always returns 202 to avoid leaking whether the
454
+ * identifier exists; a real reset email is only sent if the lookup
455
+ * matched. Heavily rate-limited per-identifier and per-IP.
456
+ */
457
+ async requestPasswordReset(opts) {
458
+ await this.request("POST", "/auth/password-reset/request", {
459
+ body: opts,
460
+ auth: false
461
+ });
462
+ }
463
+ /**
464
+ * Complete a password reset using the token from the reset email.
465
+ * On success the user's password is updated and every existing JWT for
466
+ * the account is invalidated (the `tokens_invalid_before` watermark
467
+ * bumps). The caller is NOT auto-logged-in — call {@link login} after.
468
+ */
469
+ async confirmPasswordReset(opts) {
470
+ await this.request("POST", "/auth/password-reset/confirm", {
471
+ body: {
472
+ token: opts.token,
473
+ newPassword: opts.newPassword
474
+ },
475
+ auth: false
476
+ });
477
+ }
478
+ /**
479
+ * Change the current user's password. Requires the current password —
480
+ * a stolen JWT alone can't pivot to "I now own this account forever"
481
+ * because the lockout counter (shared with `/auth/login`) trips after
482
+ * a few wrong tries. The endpoint also bumps `tokens_invalid_before`,
483
+ * so other sessions are forced to re-auth.
484
+ */
485
+ async changePassword(opts) {
486
+ await this.request("POST", "/auth/password-change", { body: {
487
+ currentPassword: opts.currentPassword,
488
+ newPassword: opts.newPassword
489
+ } });
490
+ }
491
+ /**
492
+ * Add a password to an account that doesn't have one yet — for example,
493
+ * a key-based soft identity opting into a recovery credential. Requires
494
+ * the caller to be authenticated. The server checks
495
+ * `users.password_hash IS NULL` and returns 409 if a password is already
496
+ * set — use {@link changePassword} in that case.
497
+ *
498
+ * Setting a password does not bump `tokens_invalid_before`: it adds an
499
+ * orthogonal credential rather than rotating an existing one. Other
500
+ * devices keep their sessions; this just unlocks the password-login
501
+ * code path for future logins on new devices.
502
+ */
503
+ async setPassword(newPassword) {
504
+ await this.request("POST", "/auth/set-password", { body: { newPassword } });
505
+ }
506
+ /** Get the current user's profile. */
507
+ async getMe() {
508
+ if (this.cache) {
509
+ const cached = await this.cache.getCurrentProfile();
510
+ if (cached) return cached;
511
+ }
512
+ const profile = await this.request("GET", "/users/me");
513
+ if (this.cache) await this.cache.setCurrentProfile(profile).catch(() => null);
514
+ return profile;
515
+ }
516
+ /** Update the current user's display name. */
517
+ async updateMe(opts) {
518
+ await this.request("PATCH", "/users/me", { body: opts });
519
+ }
520
+ /**
521
+ * Create a new root (top-level) document. Returns its metadata.
522
+ *
523
+ * Requires Admin-or-above unless the server sets
524
+ * `[access].allow_user_top_level = true` — subtree docs go through
525
+ * {@link createChild} instead and inherit creation rights from the parent.
526
+ *
527
+ * The options mirror the server's `CreateDocRequest`. They used to be typed
528
+ * as just `{ id?: string }`, which is why `findOrCreateDmDoc` below reaches
529
+ * past this method with a raw `request()` to set `kind` / `public_access`.
530
+ */
531
+ async createDoc(opts) {
532
+ return this.request("POST", "/docs", { body: opts ?? {} });
533
+ }
534
+ /** Get document metadata. */
535
+ async getDoc(docId) {
536
+ if (this.cache) {
537
+ const cached = await this.cache.getDoc(docId);
538
+ if (cached) return cached;
539
+ }
540
+ const meta = await this.request("GET", `/docs/${encodeURIComponent(docId)}`);
541
+ if (this.cache) await this.cache.setDoc(meta).catch(() => null);
542
+ return meta;
543
+ }
544
+ /** Delete a document (requires Owner role). Cascades to children and uploads. */
545
+ async deleteDoc(docId) {
546
+ await this.request("DELETE", `/docs/${encodeURIComponent(docId)}`);
547
+ if (this.cache) await this.cache.invalidateDoc(docId).catch(() => null);
548
+ }
549
+ /**
550
+ * Restore a soft-deleted document (and its descendants). Requires the
551
+ * same `manage` permission as {@link deleteDoc}, and works even when
552
+ * the doc currently has `deleted_at` set — the cascade resolver walks
553
+ * the ancestor chain regardless of soft-delete state. Returns the
554
+ * number of restored rows in the audit log; the SDK call returns
555
+ * `void` because the wire response is 204.
556
+ */
557
+ async restoreDoc(docId) {
558
+ await this.request("POST", `/docs/${encodeURIComponent(docId)}/restore`);
559
+ if (this.cache) await this.cache.invalidateDoc(docId).catch(() => null);
560
+ }
561
+ /**
562
+ * Full-text search over document labels via `GET /docs/search`. The
563
+ * server filters each candidate hit through the cascade resolver, so
564
+ * results only include docs the caller can read at viewer or above.
565
+ * Anonymous callers are permitted but only see public docs.
566
+ *
567
+ * `limit` is clamped to `[1, 50]` server-side; the default is 20.
568
+ * Hits arrive in best-first order. `snippet` is HTML with `<mark>`
569
+ * markers around matched tokens — sanitize before injecting.
570
+ */
571
+ async searchDocs(query, opts) {
572
+ const params = new URLSearchParams({ q: query });
573
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
574
+ return (await this.request("GET", `/docs/search?${params.toString()}`)).results;
575
+ }
576
+ /**
577
+ * Documents that link TO `docId`, via `GET /docs/:id/backlinks`.
578
+ *
579
+ * Served from the server's `doc_links` index, which is rebuilt from each
580
+ * document's CRDT state whenever a snapshot is written. Prefer this over
581
+ * inverting links from a local cache: a client can only invert what it has
582
+ * downloaded, so on a large space a purely local backlink list is silently
583
+ * incomplete rather than empty-and-obviously-wrong.
584
+ *
585
+ * The caller must be able to read the target document, and each hit is
586
+ * cascade-filtered, so this never reveals a document the caller couldn't
587
+ * otherwise see. `limit` is clamped to `[1, 200]` server-side (default 50).
588
+ *
589
+ * Throws on servers that predate the endpoint — callers that need to work
590
+ * against older deployments should catch and fall back to a local index.
591
+ */
592
+ async getBacklinks(docId, opts) {
593
+ const params = new URLSearchParams();
594
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
595
+ const qs = params.toString();
596
+ return (await this.request("GET", `/docs/${encodeURIComponent(docId)}/backlinks${qs ? `?${qs}` : ""}`)).results;
597
+ }
598
+ /**
599
+ * Query for documents matching a structural predicate. v1 of the
600
+ * indexed-query layer described in
601
+ * `ARCHITECTURE/20-kickoff-phase3-queries.md`.
602
+ *
603
+ * The wire shape accepts a `where` field so v2 (meta-predicate
604
+ * filtering on top of the `doc_meta_index` projection) can light up
605
+ * without a compatibility break. Sending a non-empty `where` today
606
+ * returns a 400 — callers should leave it absent.
607
+ *
608
+ * Returns docs the requester can read at viewer-or-above, filtered
609
+ * through the cascading permission resolver server-side.
610
+ */
611
+ async queryDocs(opts) {
612
+ const body = {};
613
+ if (opts.type != null) body.type = opts.type;
614
+ if (opts.parentId != null) body.parent_id = opts.parentId;
615
+ if (opts.labelContains != null) body.label_contains = opts.labelContains;
616
+ if (opts.limit != null) body.limit = opts.limit;
617
+ return (await this.request("POST", "/docs/query", { body })).documents;
618
+ }
619
+ /**
620
+ * List the direct children of a document, returning full metadata. Pass
621
+ * no argument to list the children of the server root — what the
622
+ * dashboard renders as the Spaces sidebar.
623
+ *
624
+ * The cache (when configured) stores the bare `id[]` topology used by
625
+ * recursive tree walks; callers that need it can read `meta.id` from
626
+ * the returned metas.
627
+ */
628
+ async listChildren(parentId, opts) {
629
+ const kind = opts?.kind;
630
+ if (parentId) {
631
+ const res = await this.request("GET", `/docs/${encodeURIComponent(parentId)}/children`);
632
+ if (this.cache && res.children) await this.cache.setChildren(parentId, res.children).catch(() => null);
633
+ return kind ? res.documents.filter((d) => d.kind === kind) : res.documents;
634
+ }
635
+ const key = kind ?? "";
636
+ const existing = this.rootListInflight.get(key);
637
+ const docs = existing ? await existing : await (() => {
638
+ const p = this.request("GET", kind ? `/docs?root=true&kind=${encodeURIComponent(kind)}` : "/docs?root=true").then((res) => res.documents).finally(() => this.rootListInflight.delete(key));
639
+ this.rootListInflight.set(key, p);
640
+ return p;
641
+ })();
642
+ return kind ? docs.filter((d) => d.kind === kind) : docs;
643
+ }
644
+ /**
645
+ * Create a child document under a parent (requires write permission).
646
+ *
647
+ * `kind` is the well-known tag (`Kind.Channel`, `Kind.Page`, etc.); the
648
+ * server stores it in `documents.kind` but does not enforce semantics.
649
+ * `description` is freeform metadata.
650
+ */
651
+ async createChild(docId, opts) {
652
+ return this.request("POST", `/docs/${encodeURIComponent(docId)}/children`, { body: opts ?? {} });
653
+ }
654
+ /** Broadcast a stateless message to all connected clients on a document (requires manage permission). */
655
+ async broadcast(docId, payload) {
656
+ await this.request("POST", `/docs/${encodeURIComponent(docId)}/broadcast`, { body: { payload } });
657
+ }
658
+ /** List all permissions for a document (requires read access). */
659
+ async listPermissions(docId) {
660
+ if (this.cache) {
661
+ const cached = await this.cache.getPermissions(docId);
662
+ if (cached) return cached;
663
+ }
664
+ const res = await this.request("GET", `/docs/${encodeURIComponent(docId)}/permissions`);
665
+ if (this.cache) await this.cache.setPermissions(docId, res.permissions).catch(() => null);
666
+ return res.permissions;
667
+ }
668
+ /** List effective permissions including inherited ones from ancestor documents. */
669
+ async listEffectivePermissions(docId) {
670
+ try {
671
+ return await this.request("GET", `/docs/${encodeURIComponent(docId)}/effective-permissions`);
672
+ } catch (e) {
673
+ if (typeof e === "object" && e !== null && "status" in e && e.status === 404) return {
674
+ permissions: (await this.listPermissions(docId)).map((p) => ({
675
+ ...p,
676
+ source: "direct"
677
+ })),
678
+ default_role: "viewer"
679
+ };
680
+ throw e;
681
+ }
682
+ }
683
+ /** Grant or change a user's role on a document (requires Owner). */
684
+ async setPermission(docId, opts) {
685
+ await this.request("POST", `/docs/${encodeURIComponent(docId)}/permissions`, { body: opts });
686
+ }
687
+ /** Revoke a user's permission on a document (requires Owner). */
688
+ async removePermission(docId, opts) {
689
+ await this.request("DELETE", `/docs/${encodeURIComponent(docId)}/permissions`, { body: opts });
690
+ }
691
+ /** Upload a file to a document (requires write permission). */
692
+ async upload(docId, file, filename) {
693
+ const formData = new FormData();
694
+ formData.append("file", file, filename);
695
+ const headers = {};
696
+ if (this._token) headers["Authorization"] = `Bearer ${this._token}`;
697
+ const res = await this._fetch(`${this.baseUrl}/docs/${encodeURIComponent(docId)}/uploads`, {
698
+ method: "POST",
699
+ headers,
700
+ body: formData
701
+ });
702
+ if (!res.ok) throw await this.toError(res);
703
+ const meta = await res.json();
704
+ if (this.cache) await this.cache.invalidateUploads(docId).catch(() => null);
705
+ return meta;
706
+ }
707
+ /** List all uploads for a document. */
708
+ async listUploads(docId) {
709
+ if (this.cache) {
710
+ const cached = await this.cache.getUploads(docId);
711
+ if (cached) return cached;
712
+ }
713
+ const res = await this.request("GET", `/docs/${encodeURIComponent(docId)}/uploads`);
714
+ if (this.cache) await this.cache.setUploads(docId, res.uploads).catch(() => null);
715
+ return res.uploads;
716
+ }
717
+ /** Download an upload as a Blob. */
718
+ async getUpload(docId, uploadId) {
719
+ const headers = {};
720
+ if (this._token) headers["Authorization"] = `Bearer ${this._token}`;
721
+ const res = await this._fetch(`${this.baseUrl}/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}`, {
722
+ method: "GET",
723
+ headers
724
+ });
725
+ if (!res.ok) throw await this.toError(res);
726
+ return res.blob();
727
+ }
728
+ /**
729
+ * Mint a short-lived, read-only token bound to this one upload.
730
+ * Prefer `getStreamUrl`, which caches and reuses the grant.
731
+ */
732
+ async createStreamToken(docId, uploadId) {
733
+ return this.request("POST", `/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}/stream-token`);
734
+ }
735
+ /**
736
+ * Absolute URL that streams an upload straight from the server, safe to
737
+ * hand to `<video src>` / `<audio src>`.
738
+ *
739
+ * Unlike `FileBlobStore.getBlobUrl` (which downloads the whole blob into
740
+ * IndexedDB and hands back an object URL), this keeps the bytes on the
741
+ * server so the browser can seek natively over HTTP Range — the difference
742
+ * between "wait for 400 MB" and "scrub instantly". It needs the network,
743
+ * so callers should fall back to `getBlobUrl` when offline.
744
+ *
745
+ * Grants are cached per upload and re-minted shortly before they expire.
746
+ * Throws on servers older than the `stream-token` endpoint (404).
747
+ */
748
+ async getStreamUrl(docId, uploadId) {
749
+ const key = `${docId}/${uploadId}`;
750
+ const cached = this.streamTokens.get(key);
751
+ if (cached && cached.expiresAt - 6e4 > Date.now()) return cached.url;
752
+ const inflight = this.streamTokenInflight.get(key);
753
+ if (inflight) return inflight;
754
+ const pending = this.createStreamToken(docId, uploadId).then((info) => {
755
+ const url = `${this.baseUrl}${info.url}`;
756
+ this.streamTokens.set(key, {
757
+ url,
758
+ expiresAt: Date.now() + info.expires_in * 1e3
759
+ });
760
+ return url;
761
+ }).finally(() => {
762
+ this.streamTokenInflight.delete(key);
763
+ });
764
+ this.streamTokenInflight.set(key, pending);
765
+ return pending;
766
+ }
767
+ /** Drop any cached stream grant for an upload (or all of them). */
768
+ clearStreamUrl(docId, uploadId) {
769
+ if (docId && uploadId) {
770
+ this.streamTokens.delete(`${docId}/${uploadId}`);
771
+ this.streamTokenInflight.delete(`${docId}/${uploadId}`);
772
+ return;
773
+ }
774
+ this.streamTokens.clear();
775
+ this.streamTokenInflight.clear();
776
+ }
777
+ /**
778
+ * Build the request path (with query string) for an upload's thumbnail.
779
+ * Also the canonical cache key suffix — the query string is deterministic
780
+ * in insertion order, so identical options map to the same URL and the
781
+ * same `FileBlobStore` cache entry.
782
+ */
783
+ thumbnailPath(docId, uploadId, opts = {}) {
784
+ const p = new URLSearchParams();
785
+ if (opts.w != null) p.set("w", String(opts.w));
786
+ if (opts.h != null) p.set("h", String(opts.h));
787
+ if (opts.fit) p.set("fit", opts.fit);
788
+ if (opts.format) p.set("format", opts.format);
789
+ if (opts.q != null) p.set("q", String(opts.q));
790
+ const qs = p.toString();
791
+ return `/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}/thumbnail${qs ? `?${qs}` : ""}`;
792
+ }
793
+ /**
794
+ * Download a generated thumbnail of an image upload as a Blob. The server
795
+ * renders + caches it on first request. Because a browser `<img>` can't
796
+ * send `Authorization`, callers render the returned Blob via an object URL
797
+ * (see `FileBlobStore.getThumbUrl`, which also caches it locally).
798
+ * Throws (with `.status = 415`) when the source isn't a thumbnailable
799
+ * raster image, or `422` for an out-of-allowlist size/format.
800
+ */
801
+ async getThumbnail(docId, uploadId, opts = {}) {
802
+ const headers = {};
803
+ if (this._token) headers["Authorization"] = `Bearer ${this._token}`;
804
+ const res = await this._fetch(`${this.baseUrl}${this.thumbnailPath(docId, uploadId, opts)}`, {
805
+ method: "GET",
806
+ headers
807
+ });
808
+ if (!res.ok) throw await this.toError(res);
809
+ return res.blob();
810
+ }
811
+ /** Delete an upload (requires uploader or document Owner). */
812
+ async deleteUpload(docId, uploadId) {
813
+ await this.request("DELETE", `/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}`);
814
+ if (this.cache) await this.cache.invalidateUploads(docId).catch(() => null);
815
+ }
816
+ /** Create an invite code (requires permission per server config). */
817
+ async createInvite(opts) {
818
+ return this.request("POST", "/invites", { body: opts ?? {} });
819
+ }
820
+ /** List invite codes visible to the current user. */
821
+ async listInvites() {
822
+ return (await this.request("GET", "/invites")).invites;
823
+ }
824
+ /** Revoke an invite by its code. */
825
+ async revokeInvite(code) {
826
+ await this.request("DELETE", `/invites/${encodeURIComponent(code)}`);
827
+ }
828
+ /** Redeem an invite code for the currently authenticated user. */
829
+ async redeemInvite(code) {
830
+ await this.request("POST", "/invites/redeem", { body: { code } });
831
+ }
832
+ /**
833
+ * Set the public_access level for a document. Pass null to inherit from parent.
834
+ *
835
+ * The values, and the two that are easy to confuse:
836
+ *
837
+ * - `"observer"` / `"viewer"` / `"editor"` — a FLOOR. Raises whoever reaches
838
+ * this document to at least that role, cascading to descendants.
839
+ * - `"none"` — no floor from here. Blocks anonymous, but an authenticated
840
+ * principal still falls through to the server's `[access].authenticated`
841
+ * default, so on a server with a floor this does NOT make a document private.
842
+ * - `"private"` — no floor AND no ambient default. Only explicit grants,
843
+ * ownership, Admin and Service reach a sealed document. This is what makes
844
+ * a document private without reconfiguring the whole server.
845
+ *
846
+ * The cascade takes the NEAREST ancestor that sets a value, not the strongest,
847
+ * so a descendant can re-publish itself out of a private parent.
848
+ *
849
+ * `"private"` requires server ≥ the release that introduced it. An older
850
+ * server rejects it with 400 rather than silently storing it.
851
+ */
852
+ async setDocumentAccess(docId, publicAccess) {
853
+ await this.request("PATCH", `/docs/${encodeURIComponent(docId)}/access`, { body: { public_access: publicAccess } });
854
+ }
855
+ /** Get the public_access info for a document. */
856
+ async getDocumentAccess(docId) {
857
+ return this.request("GET", `/docs/${encodeURIComponent(docId)}/access`);
858
+ }
859
+ /**
860
+ * Update document metadata (label, description, kind, doc_type, parent_id).
861
+ * Requires manage permission on the doc; reparenting additionally requires
862
+ * manage on the new parent (or admin if moving under the server root).
863
+ *
864
+ * `doc_type` is the renderer hint (`"kanban"`, `"graph"`, …) — orthogonal
865
+ * to `kind` (the structural role). Use it for post-create type changes;
866
+ * never write renderer strings into `kind`. Servers older than migration
867
+ * 0014 ignore the field (unknown JSON fields are dropped server-side).
868
+ */
869
+ async updateDocumentMeta(docId, opts) {
870
+ await this.request("PATCH", `/docs/${encodeURIComponent(docId)}`, { body: opts });
871
+ }
872
+ /**
873
+ * List Spaces visible to the caller — top-level docs (children of the
874
+ * server root) tagged with `kind: "space"`. Authenticated users see
875
+ * spaces resolving to any role; anonymous users see public ones.
876
+ */
877
+ async listSpaces() {
878
+ return this.listChildren(void 0, { kind: Kind.Space });
879
+ }
880
+ /**
881
+ * Create a new top-level Space. Equivalent to a `POST /docs` with
882
+ * `kind: "space"` plus the supplied metadata in one round trip.
883
+ *
884
+ * `visibility: "public"` sets `public_access = "observer"` (anonymous
885
+ * read, no awareness or writes). `"private"` (the default) leaves
886
+ * `public_access` unset so only explicit grants apply.
887
+ */
888
+ async createSpace(opts) {
889
+ const public_access = opts.visibility === "public" ? "observer" : "none";
890
+ return this.request("POST", "/docs", { body: {
891
+ id: opts.id,
892
+ label: opts.name,
893
+ description: opts.description,
894
+ kind: Kind.Space,
895
+ public_access
896
+ } });
897
+ }
898
+ /**
899
+ * Update a Space's metadata. `visibility` flips `public_access` between
900
+ * `"observer"` (public) and `"none"` (private). To leave visibility
901
+ * untouched, omit it. Pass any property as `null` to clear it.
902
+ */
903
+ async updateSpace(docId, opts) {
904
+ const meta = {};
905
+ if (opts.name !== void 0) meta.label = opts.name;
906
+ if (opts.description !== void 0) meta.description = opts.description;
907
+ if (Object.keys(meta).length > 0) await this.updateDocumentMeta(docId, meta);
908
+ if (opts.visibility !== void 0) await this.setDocumentAccess(docId, opts.visibility === "public" ? "observer" : "none");
909
+ }
910
+ /** Delete a Space (and every doc nested under it). Requires manage permission. */
911
+ async deleteSpace(docId) {
912
+ await this.deleteDoc(docId);
913
+ }
914
+ /**
915
+ * Look up the DM doc between the calling user and `otherUserPk`, or
916
+ * create it if none exists. The doc id is deterministically derived from
917
+ * the sorted pubkey pair (see {@link deriveDmDocId}) so both sides
918
+ * compute the same target — race-tolerant by construction. The created
919
+ * doc has `kind = "dm"`, `public_access = "none"`, and explicit Editor
920
+ * permissions for both participants.
921
+ *
922
+ * The cascade resolver enforces that no other user can read the DM,
923
+ * because:
924
+ * - `public_access = "none"` blocks anonymous + falls through to the
925
+ * server-wide `[access].authenticated` floor for everyone else;
926
+ * - the explicit Editor rows only exist for the two participants, so
927
+ * non-participants get only the (capped) authenticated floor;
928
+ * - the doc lives at server root, so there's no ancestor that could
929
+ * leak via a higher cascade grant.
930
+ *
931
+ * Note: when `[access].authenticated >= "viewer"` is set server-wide,
932
+ * non-participants can still *read* the DM via the authenticated floor —
933
+ * `public_access = "none"` removes the floor but not the ambient default.
934
+ *
935
+ * Servers that support `public_access = "private"` can seal it properly:
936
+ * call `setDocumentAccess(dmId, "private")` after creating one. That is NOT
937
+ * done here, deliberately — this SDK talks to older servers too, and they
938
+ * reject the value with a 400. Callers that know their server version can
939
+ * opt in; a future major may make it the default.
940
+ *
941
+ * @param otherUserPk Base64url-encoded Ed25519 public key of the other party.
942
+ * @returns The DM doc's id (existing or newly created).
943
+ */
944
+ async findOrCreateDmDoc(otherUserPk) {
945
+ const me = await this.getMe();
946
+ if (!me.publicKey) throw new Error("findOrCreateDmDoc: caller has no public key");
947
+ const dmId = deriveDmDocId(me.publicKey, otherUserPk);
948
+ try {
949
+ const existing = await this.getDoc(dmId);
950
+ if (existing && existing.kind === Kind.Dm) return dmId;
951
+ } catch {}
952
+ try {
953
+ await this.request("POST", "/docs", { body: {
954
+ id: dmId,
955
+ kind: Kind.Dm,
956
+ public_access: "none"
957
+ } });
958
+ } catch (err) {
959
+ if ((err?.status ?? err?.response?.status) !== 409) throw err;
960
+ }
961
+ await this.setPermission(dmId, {
962
+ user_id: me.publicKey,
963
+ role: "editor"
964
+ });
965
+ await this.setPermission(dmId, {
966
+ user_id: otherUserPk,
967
+ role: "editor"
968
+ });
969
+ return dmId;
970
+ }
971
+ /**
972
+ * The reserved server root document id. Convenience accessor for the
973
+ * client; identical to {@link SERVER_ROOT_ID}. Use this as the parent for
974
+ * top-level docs / Spaces.
975
+ */
976
+ get rootDocId() {
977
+ return SERVER_ROOT_ID;
978
+ }
979
+ /** List all users (requires elevated role: admin or service). */
980
+ async adminListUsers() {
981
+ return this.request("GET", "/admin/users");
982
+ }
983
+ /** Promote a user to admin (requires service role). */
984
+ async adminPromote(userId) {
985
+ await this.request("POST", `/admin/users/${encodeURIComponent(userId)}/admin`);
986
+ }
987
+ /** Demote an admin user back to regular (requires service role). */
988
+ async adminDemote(userId) {
989
+ await this.request("DELETE", `/admin/users/${encodeURIComponent(userId)}/admin`);
990
+ }
991
+ /** Sweep orphaned file blobs from storage (requires elevated role). */
992
+ async adminStorageSweep() {
993
+ return this.request("POST", "/admin/storage/sweep");
994
+ }
995
+ /** Repair blob ref-counts and sweep orphans (requires elevated role). */
996
+ async adminStorageRepair() {
997
+ return this.request("POST", "/admin/storage/repair");
998
+ }
999
+ /**
1000
+ * Admin one-shot: populate the `snapshot_files` table for snapshots
1001
+ * created before that migration ran, so `SnapshotMeta.file_count` and
1002
+ * upload-ref tracking become accurate. Idempotent (insert-or-ignore).
1003
+ * Requires elevated role.
1004
+ */
1005
+ async adminSnapshotsBackfillRefs() {
1006
+ return this.request("POST", "/admin/snapshots/backfill-refs");
1007
+ }
1008
+ /**
1009
+ * Admin one-shot: migrate pre-dedup inline snapshot data into the
1010
+ * content-addressed `snapshot_blobs` store. Idempotent (only migrates
1011
+ * rows with `data_hash IS NULL`). Requires elevated role.
1012
+ */
1013
+ async adminSnapshotsBackfillBlobs() {
1014
+ return this.request("POST", "/admin/snapshots/backfill-blobs");
1015
+ }
1016
+ /**
1017
+ * Admin: server-wide upload listing, joined with the owning document
1018
+ * (label is best-effort — labels live in the CRDT, not the SQL row)
1019
+ * and the content-addressed blob (`ref_count` exposes dedup).
1020
+ * Server-side paginated + filtered. Requires elevated role.
1021
+ */
1022
+ async adminListUploads(opts = {}) {
1023
+ const p = new URLSearchParams();
1024
+ if (opts.q) p.set("q", opts.q);
1025
+ if (opts.docId) p.set("doc_id", opts.docId);
1026
+ if (opts.limit != null) p.set("limit", String(opts.limit));
1027
+ if (opts.offset != null) p.set("offset", String(opts.offset));
1028
+ const qs = p.toString();
1029
+ return this.request("GET", `/admin/uploads${qs ? `?${qs}` : ""}`);
1030
+ }
1031
+ /**
1032
+ * Admin: aggregate storage figures. `logicalBytes` is what users
1033
+ * uploaded; `physicalBytes` is on-disk after content-addressed dedup;
1034
+ * `dedupSaved` is the difference. Requires elevated role.
1035
+ */
1036
+ async adminStorageStats() {
1037
+ return this.request("GET", "/admin/storage/stats");
1038
+ }
1039
+ /**
1040
+ * Clear the lockout state on a user account: zeroes the failed-login
1041
+ * counter and `locked_until`. Requires elevated role (Admin or
1042
+ * Service). The action is recorded in the audit log under
1043
+ * `admin.user_unlock`.
1044
+ */
1045
+ async adminUnlockUser(userId) {
1046
+ await this.request("POST", `/admin/users/${encodeURIComponent(userId)}/unlock`);
1047
+ }
1048
+ /**
1049
+ * Admin: every non-deleted document the user owns (`source: "owner"`)
1050
+ * or has an explicit permission grant on (`source: "grant"`, with
1051
+ * `role`). Answers "what does this identity touch" without an N+1
1052
+ * client tree walk. Labels are best-effort (they live in the CRDT).
1053
+ * Requires elevated role.
1054
+ */
1055
+ async adminUserDocs(userId, opts = {}) {
1056
+ const qs = opts.limit != null ? `?limit=${opts.limit}` : "";
1057
+ return this.request("GET", `/admin/users/${encodeURIComponent(userId)}/docs${qs}`);
1058
+ }
1059
+ /**
1060
+ * List `service`-role users (runners, demo seeders, automation
1061
+ * identities). Requires Service role. Admins can see service users via
1062
+ * `/admin/users` too but cannot mint or rotate them.
1063
+ */
1064
+ async adminListServiceAccounts() {
1065
+ return this.request("GET", "/admin/service-accounts");
1066
+ }
1067
+ /**
1068
+ * Create a new `service`-role user. When `public_key` is omitted the
1069
+ * server generates a keypair and returns the private half in the
1070
+ * response — show it to the operator **once** and discard; the server
1071
+ * never persists it. Requires Service role.
1072
+ */
1073
+ async adminCreateServiceAccount(body) {
1074
+ return this.request("POST", "/admin/service-accounts", { body });
1075
+ }
1076
+ /**
1077
+ * Rotate the active keypair on a service account. Old JWTs are
1078
+ * invalidated; old device keys are marked revoked; the canonical
1079
+ * `users.public_key` swaps to the new value. `users.id` stays put so
1080
+ * existing permission rows keep matching. Returns the new pubkey (and
1081
+ * private half when the server generated it). Requires Service role.
1082
+ */
1083
+ async adminRotateServiceAccountKey(userId, body = {}) {
1084
+ return this.request("POST", `/admin/service-accounts/${encodeURIComponent(userId)}/rotate-key`, { body });
1085
+ }
1086
+ /**
1087
+ * Lock a service account and revoke all of its device keys. Idempotent.
1088
+ * Refuses targets whose `users.role` isn't `"service"`. Requires
1089
+ * Service role.
1090
+ */
1091
+ async adminRevokeServiceAccount(userId) {
1092
+ await this.request("DELETE", `/admin/service-accounts/${encodeURIComponent(userId)}`);
1093
+ }
1094
+ /**
1095
+ * Revoke a single device key on a user (any role). Bumps
1096
+ * `tokens_invalid_before` so open WS sessions tied to the key must
1097
+ * re-auth. Requires elevated role (Service or Admin@root).
1098
+ */
1099
+ async adminRevokeDeviceKey(userId, keyId) {
1100
+ await this.request("POST", `/admin/users/${encodeURIComponent(userId)}/device-keys/${encodeURIComponent(keyId)}/revoke`);
1101
+ }
1102
+ /**
1103
+ * Page through the audit log. Filters AND-combine; `limit` defaults to
1104
+ * 100 server-side. Requires elevated role.
1105
+ */
1106
+ async adminAuditList(opts) {
1107
+ const params = new URLSearchParams();
1108
+ if (opts?.event_type) params.set("event_type", opts.event_type);
1109
+ if (opts?.actor_user_id) params.set("actor_user_id", opts.actor_user_id);
1110
+ if (opts?.target_type) params.set("target_type", opts.target_type);
1111
+ if (opts?.target_id) params.set("target_id", opts.target_id);
1112
+ if (opts?.since_ts != null) params.set("since_ts", String(opts.since_ts));
1113
+ if (opts?.until_ts != null) params.set("until_ts", String(opts.until_ts));
1114
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
1115
+ if (opts?.offset != null) params.set("offset", String(opts.offset));
1116
+ const qs = params.toString();
1117
+ return (await this.request("GET", `/admin/audit${qs ? `?${qs}` : ""}`)).items;
1118
+ }
1119
+ /**
1120
+ * Stream the audit log as NDJSON (one JSON object per line) for SIEM
1121
+ * ingestion. Filters mirror {@link adminAuditList} minus `limit`/`offset`.
1122
+ * The server pages internally so memory usage is bounded; this method
1123
+ * buffers the full response into a string and is therefore best for
1124
+ * moderate exports — large dumps should consume `/admin/audit/export`
1125
+ * directly with a streaming HTTP client.
1126
+ */
1127
+ async adminAuditExport(opts) {
1128
+ const params = new URLSearchParams();
1129
+ if (opts?.event_type) params.set("event_type", opts.event_type);
1130
+ if (opts?.actor_user_id) params.set("actor_user_id", opts.actor_user_id);
1131
+ if (opts?.target_type) params.set("target_type", opts.target_type);
1132
+ if (opts?.target_id) params.set("target_id", opts.target_id);
1133
+ if (opts?.since_ts != null) params.set("since_ts", String(opts.since_ts));
1134
+ if (opts?.until_ts != null) params.set("until_ts", String(opts.until_ts));
1135
+ const qs = params.toString();
1136
+ const headers = {};
1137
+ if (this._token) headers["Authorization"] = `Bearer ${this._token}`;
1138
+ const res = await this._fetch(`${this.baseUrl}/admin/audit/export${qs ? `?${qs}` : ""}`, {
1139
+ method: "GET",
1140
+ headers
1141
+ });
1142
+ if (!res.ok) throw await this.toError(res, "GET", "/admin/audit/export");
1143
+ return res.text();
1144
+ }
1145
+ /**
1146
+ * Verify the integrity of the audit-log hash chain. Returns the result
1147
+ * unchanged: `status: "ok"` when the chain is intact, `status: "broken"`
1148
+ * with a `break` payload identifying the first divergent row when
1149
+ * tampering is detected. Wraps `GET /admin/audit/verify`. Requires
1150
+ * elevated role.
1151
+ *
1152
+ * Note: the server returns HTTP 409 on a broken chain — this method
1153
+ * special-cases the 409 status and returns the body as a successful
1154
+ * result rather than throwing, because "broken" is a valid answer
1155
+ * from the verifier, not an error.
1156
+ */
1157
+ async adminAuditVerify() {
1158
+ const headers = {};
1159
+ if (this._token) headers["Authorization"] = `Bearer ${this._token}`;
1160
+ const res = await this._fetch(`${this.baseUrl}/admin/audit/verify`, {
1161
+ method: "GET",
1162
+ headers
1163
+ });
1164
+ if (res.status === 200 || res.status === 409) return res.json();
1165
+ throw await this.toError(res, "GET", "/admin/audit/verify");
1166
+ }
1167
+ /**
1168
+ * Download a tar archive of the schema-meaningful tables (users,
1169
+ * documents, permissions, invites, optionally audit log). Requires
1170
+ * elevated role. The server gzips the response when the client sends
1171
+ * `Accept-Encoding: gzip` — `fetch` handles that transparently, so
1172
+ * the returned Blob is the raw tar bytes.
1173
+ */
1174
+ async adminBackupDump(opts) {
1175
+ const params = new URLSearchParams();
1176
+ if (opts?.includeAudit) params.set("include_audit", "true");
1177
+ const qs = params.toString();
1178
+ const headers = {};
1179
+ if (this._token) headers["Authorization"] = `Bearer ${this._token}`;
1180
+ const res = await this._fetch(`${this.baseUrl}/admin/backup/dump${qs ? `?${qs}` : ""}`, {
1181
+ method: "GET",
1182
+ headers
1183
+ });
1184
+ if (!res.ok) throw await this.toError(res, "GET", "/admin/backup/dump");
1185
+ return res.blob();
1186
+ }
1187
+ /**
1188
+ * List every registered config field with current value + origin
1189
+ * (`default` / `env` / `global_override` / `route_override`). Requires
1190
+ * elevated role.
1191
+ */
1192
+ async adminConfigList() {
1193
+ return (await this.request("GET", "/admin/config")).items;
1194
+ }
1195
+ /** Read a single config field by dotted path (e.g. `"access.authenticated"`). */
1196
+ async adminConfigGet(path) {
1197
+ return this.request("GET", `/admin/config/fields/${encodeURIComponent(path)}`);
1198
+ }
1199
+ /**
1200
+ * Set a runtime override on a config field. The field must be marked
1201
+ * `runtime_mutable = true` in the registry; immutable fields return a
1202
+ * schema error. Persists to the `settings_overrides` table.
1203
+ */
1204
+ async adminConfigSet(path, value) {
1205
+ return this.request("PUT", `/admin/config/fields/${encodeURIComponent(path)}`, { body: { value } });
1206
+ }
1207
+ /**
1208
+ * Clear a runtime override and revert the field to its env/TOML/default
1209
+ * base value. Returns `true` when an override was actually removed.
1210
+ */
1211
+ async adminConfigUnset(path) {
1212
+ return (await this.request("DELETE", `/admin/config/fields/${encodeURIComponent(path)}`)).existed;
1213
+ }
1214
+ /**
1215
+ * Diagnostic dump of every `ABRA_*` env var the running process saw at
1216
+ * boot, mapped to its config path. Use this to debug
1217
+ * "I set this in `.env` but the server reports a different value".
1218
+ * Secrets are redacted (`value: null`, `redacted: true`).
1219
+ */
1220
+ async adminConfigEnvSnapshot() {
1221
+ return this.request("GET", "/admin/config/env-snapshot");
1222
+ }
1223
+ /**
1224
+ * List every route pattern that currently has at least one per-route
1225
+ * config override. Use {@link adminConfigGetRoute} to read individual
1226
+ * fields. Requires elevated role.
1227
+ */
1228
+ async adminConfigListRoutes() {
1229
+ return (await this.request("GET", "/admin/config/routes")).routes;
1230
+ }
1231
+ /**
1232
+ * Read a field's effective value scoped to `route`, falling back to
1233
+ * the global value when no per-route override exists. `origin_kind`
1234
+ * is `"route_override"` only when an override is actually set.
1235
+ */
1236
+ async adminConfigGetRoute(route, path) {
1237
+ return this.request("GET", `/admin/config/routes/${encodeURIComponent(route)}/fields/${encodeURIComponent(path)}`);
1238
+ }
1239
+ /** Set or replace a per-route override. Mirrors {@link adminConfigSet}. */
1240
+ async adminConfigSetRoute(route, path, value) {
1241
+ return this.request("PUT", `/admin/config/routes/${encodeURIComponent(route)}/fields/${encodeURIComponent(path)}`, { body: { value } });
1242
+ }
1243
+ /** Clear a per-route override (falls back to global). True if one existed. */
1244
+ async adminConfigUnsetRoute(route, path) {
1245
+ return (await this.request("DELETE", `/admin/config/routes/${encodeURIComponent(route)}/fields/${encodeURIComponent(path)}`)).existed;
1246
+ }
1247
+ /** List snapshot metadata for a document. */
1248
+ async listSnapshots(docId, opts) {
1249
+ const params = new URLSearchParams();
1250
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
1251
+ if (opts?.offset != null) params.set("offset", String(opts.offset));
1252
+ const qs = params.toString();
1253
+ return (await this.request("GET", `/docs/${encodeURIComponent(docId)}/snapshots${qs ? `?${qs}` : ""}`)).snapshots;
1254
+ }
1255
+ /** Fetch a single snapshot including its base64-encoded data blob.
1256
+ * Pass `{ include: "files" }` to also receive the joined upload list
1257
+ * (each `fileBlock` / `coverUploadId` resolved against `uploads`). */
1258
+ async getSnapshot(docId, version, opts) {
1259
+ const qs = opts?.include ? `?include=${encodeURIComponent(opts.include)}` : "";
1260
+ return this.request("GET", `/docs/${encodeURIComponent(docId)}/snapshots/${version}${qs}`);
1261
+ }
1262
+ /** Create a manual snapshot of the current document state. */
1263
+ async createSnapshot(docId, opts) {
1264
+ return this.request("POST", `/docs/${encodeURIComponent(docId)}/snapshots`, { body: opts ?? {} });
1265
+ }
1266
+ /** Delete a specific snapshot version. Requires manage permission. */
1267
+ async deleteSnapshot(docId, version) {
1268
+ await this.request("DELETE", `/docs/${encodeURIComponent(docId)}/snapshots/${version}`);
1269
+ }
1270
+ /** Restore a snapshot by merging it forward into the current document state. */
1271
+ async restoreSnapshot(docId, version) {
1272
+ return this.request("POST", `/docs/${encodeURIComponent(docId)}/snapshots/${version}/restore`, { body: {} });
1273
+ }
1274
+ /** Fork a snapshot into a new document. */
1275
+ async forkSnapshot(docId, version) {
1276
+ return this.request("POST", `/docs/${encodeURIComponent(docId)}/snapshots/${version}/fork`, { body: {} });
1277
+ }
1278
+ /** Health check — no auth required. */
1279
+ async health() {
1280
+ return this.request("GET", "/health", { auth: false });
1281
+ }
1282
+ /**
1283
+ * Readiness probe — pings the database. Returns 200 with
1284
+ * `status: "ready"` only when the server can serve traffic, 503 with
1285
+ * `status: "unready"` otherwise (load balancers / Kubernetes probes
1286
+ * use the status code; the body is informational).
1287
+ *
1288
+ * The 503 case is special-cased here: instead of throwing, the method
1289
+ * returns the unready body so callers can react to the state without
1290
+ * try/catch boilerplate.
1291
+ */
1292
+ async readyz() {
1293
+ const res = await this._fetch(`${this.baseUrl}/readyz`, { method: "GET" });
1294
+ if (res.status === 200 || res.status === 503) return res.json();
1295
+ throw await this.toError(res, "GET", "/readyz");
1296
+ }
1297
+ /**
1298
+ * Fetch server metadata including `root_doc_id` and the `[access]` policy.
1299
+ * No auth required.
1300
+ */
1301
+ async serverInfo() {
1302
+ return this.request("GET", "/info", { auth: false });
1303
+ }
1304
+ /**
1305
+ * Drop this browser's caches for this server if its database has been
1306
+ * REPLACED since the last visit, and report what happened.
1307
+ *
1308
+ * **Call it before opening any provider**, and await it. A deleted database
1309
+ * is not a tombstone — it is a peer that lost its memory — so a tab that
1310
+ * reconnects with stale IndexedDB re-pushes the old tree into the fresh one
1311
+ * and a seeder adds its own on top: every page twice, then three times. Once
1312
+ * a provider holds a store open, `deleteDatabase` blocks instead of deleting
1313
+ * and the damage is already queued; those stores come back in `blocked`,
1314
+ * which is a signal that this ran too late rather than something to ignore.
1315
+ *
1316
+ * Returns `null` when there is nothing to do — no `server_id`, no browser
1317
+ * storage, a first visit, or the same database as last time. It never
1318
+ * throws: an app must not fail to start because a cache could not be tidied.
1319
+ *
1320
+ * @see dropCachesIfServerReplaced for what is dropped and what is kept.
1321
+ */
1322
+ async ensureFreshServer() {
1323
+ try {
1324
+ const info = await this.serverInfo();
1325
+ if (!info?.server_id) return null;
1326
+ const host = new URL(this.wsUrl).host;
1327
+ return await dropCachesIfServerReplaced(host, info.server_id);
1328
+ } catch {
1329
+ return null;
1330
+ }
1331
+ }
1332
+ /**
1333
+ * Fetch ICE server configuration for WebRTC peer connections.
1334
+ * Falls back to default Google STUN server if the endpoint is unavailable.
1335
+ * No auth required.
1336
+ */
1337
+ async getIceServers() {
1338
+ try {
1339
+ return (await this.request("GET", "/ice-servers", { auth: false })).iceServers;
1340
+ } catch {
1341
+ return [{ urls: "stun:stun.l.google.com:19302" }];
1342
+ }
1343
+ }
1344
+ async request(method, path, opts) {
1345
+ const auth = opts?.auth ?? true;
1346
+ const headers = {};
1347
+ if (auth && this._token) headers["Authorization"] = `Bearer ${this._token}`;
1348
+ const init = {
1349
+ method,
1350
+ headers,
1351
+ signal: AbortSignal.timeout(3e4)
1352
+ };
1353
+ if (opts?.body !== void 0) {
1354
+ headers["Content-Type"] = "application/json";
1355
+ init.body = JSON.stringify(opts.body);
1356
+ }
1357
+ const res = await this._fetch(`${this.baseUrl}${path}`, init);
1358
+ if (!res.ok) throw await this.toError(res, method, path);
1359
+ if (res.status === 204) return;
1360
+ return res.json();
1361
+ }
1362
+ async requestOrNull(method, path, opts) {
1363
+ try {
1364
+ return await this.request(method, path, opts);
1365
+ } catch (e) {
1366
+ if (typeof e === "object" && e !== null && "status" in e && e.status === 404) return null;
1367
+ throw e;
1368
+ }
1369
+ }
1370
+ async toError(res, method, path) {
1371
+ let message;
1372
+ try {
1373
+ message = (await res.json()).error ?? res.statusText;
1374
+ } catch {
1375
+ message = res.statusText;
1376
+ }
1377
+ const prefix = method && path ? `${method} ${path}: ` : "";
1378
+ const err = /* @__PURE__ */ new Error(`${prefix}${message} (${res.status})`);
1379
+ err.status = res.status;
1380
+ if ((res.status === 401 || res.status === 403) && this._onAuthFailed) {
1381
+ const lower = message.toLowerCase();
1382
+ let reason = res.status === 401 ? "unauthorized" : "forbidden";
1383
+ if (/user not found|user_not_found|public key not registered|no such user/.test(lower)) reason = "user_not_found";
1384
+ else if (/account revoked|user account revoked/.test(lower)) reason = "account_revoked";
1385
+ else if (/forbidden|insufficient permissions/.test(lower)) reason = "forbidden";
1386
+ const ctx = {
1387
+ status: res.status,
1388
+ message,
1389
+ reason,
1390
+ method: method ?? "",
1391
+ path: path ?? ""
1392
+ };
1393
+ try {
1394
+ setTimeout(() => {
1395
+ try {
1396
+ this._onAuthFailed(ctx);
1397
+ } catch {}
1398
+ }, 0);
1399
+ } catch {}
1400
+ }
1401
+ return err;
1402
+ }
1403
+ loadPersistedToken() {
1404
+ try {
1405
+ return localStorage.getItem(this.storageKey);
1406
+ } catch {
1407
+ return null;
1408
+ }
1409
+ }
1410
+ persistToken(token) {
1411
+ try {
1412
+ localStorage.setItem(this.storageKey, token);
1413
+ } catch {}
1414
+ }
1415
+ clearPersistedToken() {
1416
+ try {
1417
+ localStorage.removeItem(this.storageKey);
1418
+ } catch {}
1419
+ }
1420
+ };
1421
+
1422
+ //#endregion
1423
+ export { AbracadabraClient };
1424
+ //# sourceMappingURL=AbracadabraClient.js.map