@abraca/dabra 2.90.0 → 2.91.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 (71) hide show
  1. package/package.json +5 -11
  2. package/src/AbracadabraBaseProvider.ts +0 -963
  3. package/src/AbracadabraClient.ts +0 -1960
  4. package/src/AbracadabraProvider.ts +0 -915
  5. package/src/AbracadabraWS.ts +0 -695
  6. package/src/BackgroundSyncManager.ts +0 -856
  7. package/src/BackgroundSyncPersistence.ts +0 -140
  8. package/src/ChatClient.ts +0 -314
  9. package/src/CloseEvents.ts +0 -49
  10. package/src/ContentManager.ts +0 -246
  11. package/src/CoverReconcile.ts +0 -168
  12. package/src/CryptoIdentityKeystore.ts +0 -754
  13. package/src/DeviceRegistrationService.ts +0 -257
  14. package/src/DocConverters.ts +0 -1859
  15. package/src/DocKeyManager.ts +0 -163
  16. package/src/DocTypes.ts +0 -628
  17. package/src/DocUtils.ts +0 -251
  18. package/src/DocumentCache.ts +0 -210
  19. package/src/DocumentManager.ts +0 -410
  20. package/src/E2EAbracadabraProvider.ts +0 -426
  21. package/src/E2EOfflineStore.ts +0 -55
  22. package/src/EncryptedChatClient.ts +0 -173
  23. package/src/EncryptedY.ts +0 -145
  24. package/src/EventEmitter.ts +0 -59
  25. package/src/FileBlobStore.ts +0 -569
  26. package/src/IdentityDoc.ts +0 -711
  27. package/src/IncomingMessage.ts +0 -63
  28. package/src/MessageReceiver.ts +0 -151
  29. package/src/MessageSender.ts +0 -22
  30. package/src/MetaManager.ts +0 -194
  31. package/src/MnemonicKeyDerivation.ts +0 -171
  32. package/src/NodeConnect.ts +0 -63
  33. package/src/NodeIdentity.ts +0 -378
  34. package/src/NotificationsClient.ts +0 -207
  35. package/src/OfflineStore.ts +0 -294
  36. package/src/OutgoingMessage.ts +0 -25
  37. package/src/OutgoingMessages/AuthenticationMessage.ts +0 -23
  38. package/src/OutgoingMessages/AwarenessMessage.ts +0 -41
  39. package/src/OutgoingMessages/CloseMessage.ts +0 -17
  40. package/src/OutgoingMessages/QueryAwarenessMessage.ts +0 -17
  41. package/src/OutgoingMessages/StatelessMessage.ts +0 -18
  42. package/src/OutgoingMessages/SubdocMessage.ts +0 -35
  43. package/src/OutgoingMessages/SyncStepOneMessage.ts +0 -25
  44. package/src/OutgoingMessages/SyncStepTwoMessage.ts +0 -25
  45. package/src/OutgoingMessages/UpdateMessage.ts +0 -20
  46. package/src/QueryClient.ts +0 -209
  47. package/src/RpcClient.ts +0 -659
  48. package/src/SchemaTypes.ts +0 -179
  49. package/src/SearchIndex.ts +0 -250
  50. package/src/ServerRegistry.ts +0 -220
  51. package/src/ServerReset.ts +0 -222
  52. package/src/TokenManager.ts +0 -337
  53. package/src/TreeManager.ts +0 -894
  54. package/src/TreeTimestamps.ts +0 -101
  55. package/src/auth.ts +0 -62
  56. package/src/awarenessStatesToArray.ts +0 -10
  57. package/src/index.ts +0 -219
  58. package/src/messageRecord.ts +0 -121
  59. package/src/sync/BroadcastChannelSync.ts +0 -235
  60. package/src/types.ts +0 -790
  61. package/src/webrtc/AbracadabraWebRTC.ts +0 -683
  62. package/src/webrtc/DataChannelRouter.ts +0 -179
  63. package/src/webrtc/DevicePairingChannel.ts +0 -496
  64. package/src/webrtc/E2EEChannel.ts +0 -195
  65. package/src/webrtc/FileTransferChannel.ts +0 -367
  66. package/src/webrtc/ManualSignaling.ts +0 -204
  67. package/src/webrtc/PeerConnection.ts +0 -133
  68. package/src/webrtc/SignalingSocket.ts +0 -378
  69. package/src/webrtc/YjsDataChannel.ts +0 -203
  70. package/src/webrtc/index.ts +0 -26
  71. package/src/webrtc/types.ts +0 -177
@@ -1,378 +0,0 @@
1
- /**
2
- * NodeIdentity — Ed25519 identity helpers for Node-side consumers.
3
- *
4
- * The browser identity story lives in {@link CryptoIdentityKeystore} (WebAuthn
5
- * PRF + IndexedDB). Node CLIs and daemons (`@abraca/mcp`, `@abraca/cli`,
6
- * `@abraca/orchestrator`, `@abraca/resend`, `@abraca/wiki`) instead use a raw
7
- * 32-byte Ed25519 seed kept in a key file, and authenticate to the server with
8
- * the same challenge → sign → verify flow exposed by
9
- * {@link AbracadabraClient.loginWithKey}.
10
- *
11
- * Every one of those packages previously vendored a near-identical `crypto.ts`
12
- * (key-file load/create + `signChallenge`) plus a copy-pasted
13
- * "login → register-on-404 → re-login" block. These helpers are the single
14
- * shared home for both.
15
- *
16
- * The signing helpers are environment-agnostic. Only {@link loadOrCreateKeyFile}
17
- * touches the filesystem, and it does so via dynamic `import("node:…")` so this
18
- * module stays importable from browser bundles (the fs path simply isn't
19
- * reachable there).
20
- */
21
-
22
- import * as ed from "@noble/ed25519";
23
- import { sha512 } from "@noble/hashes/sha2.js";
24
-
25
- // @noble/ed25519 v3: wire sha512 for the sync sign/getPublicKey paths and an
26
- // async hook for *Async variants. Idempotent with the same assignment in
27
- // CryptoIdentityKeystore / MnemonicKeyDerivation — whichever module loads first
28
- // wins, and the value is identical.
29
- ed.hashes.sha512 = sha512;
30
- ed.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));
31
-
32
- // ── base64url (browser-safe; mirrors CryptoIdentityKeystore) ─────────────────
33
-
34
- function toBase64url(bytes: Uint8Array): string {
35
- return btoa(String.fromCharCode(...bytes))
36
- .replace(/\+/g, "-")
37
- .replace(/\//g, "_")
38
- .replace(/=/g, "");
39
- }
40
-
41
- function fromBase64url(b64: string): Uint8Array {
42
- const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
43
- const padLen = (4 - (padded.length % 4)) % 4;
44
- return Uint8Array.from(atob(padded + "=".repeat(padLen)), (c) =>
45
- c.charCodeAt(0),
46
- );
47
- }
48
-
49
- // ── Types ────────────────────────────────────────────────────────────────────
50
-
51
- /** A raw Node Ed25519 identity: 32-byte seed + base64url public key. */
52
- export interface NodeKeypair {
53
- /** 32-byte Ed25519 private-key seed. */
54
- privateKey: Uint8Array;
55
- /** base64url-encoded 32-byte Ed25519 public key. */
56
- publicKeyB64: string;
57
- }
58
-
59
- /** Options for {@link loadOrCreateKeyFile}. */
60
- export interface LoadKeyFileOptions {
61
- /**
62
- * File name under `~/.abracadabra/` used when `keyPath` is not given.
63
- * Lets each consumer keep its own identity slot (e.g. `"cli.key"`,
64
- * `"agent.key"`). Defaults to `"identity.key"`.
65
- */
66
- defaultFileName?: string;
67
- /** Invoked once when a brand-new key is generated (for logging). */
68
- onCreate?: (info: { path: string; publicKeyB64: string }) => void;
69
- }
70
-
71
- /** Minimal client surface needed by {@link loginOrRegisterWithKey}. */
72
- export interface KeyAuthClient {
73
- loginWithKey(
74
- publicKey: string,
75
- signChallenge: (challenge: string) => Promise<string>,
76
- ): Promise<string>;
77
- registerWithKey(opts: {
78
- publicKey: string;
79
- username?: string;
80
- displayName?: string;
81
- deviceName?: string;
82
- inviteCode?: string;
83
- }): Promise<unknown>;
84
- }
85
-
86
- /**
87
- * Wider client surface needed by {@link loginOrRegisterWithPolicy}: it probes
88
- * `serverInfo()` (unauthenticated) to decide the access policy and reads
89
- * `getMe()` after connecting to detect a read-only (un-promoted) role.
90
- */
91
- export interface PolicyAuthClient extends KeyAuthClient {
92
- serverInfo(): Promise<{
93
- name?: string;
94
- registration_allowed?: boolean;
95
- invite_only?: boolean;
96
- access?: { authenticated?: string };
97
- }>;
98
- getMe(): Promise<{ role?: string }>;
99
- }
100
-
101
- /**
102
- * Outcome of {@link loginOrRegisterWithPolicy}. A discriminated union so callers
103
- * (MCP `connect_server`, CLI `server login`) can render an actionable message.
104
- *
105
- * - `connected` — logged in (existing account) or registered (open server / valid
106
- * invite). `needsPromotion` is set when the account is read-only (`observer`),
107
- * so the caller can suggest an admin grant a write role to `publicKey`.
108
- * - `needs_invite` — server is invite-only, the key isn't registered, and no
109
- * invite code was supplied. Surface `publicKey` so an admin can authorize it by
110
- * hand if no token is available.
111
- * - `registration_closed` — open registration is disabled; only an admin can
112
- * provision the account. Surface `publicKey`.
113
- */
114
- export type ConnectPolicyResult =
115
- | {
116
- status: "connected";
117
- token: string;
118
- publicKey: string;
119
- serverName?: string;
120
- role?: string;
121
- needsPromotion: boolean;
122
- }
123
- | { status: "needs_invite"; publicKey: string; serverName?: string }
124
- | { status: "registration_closed"; publicKey: string; serverName?: string };
125
-
126
- /** Options for {@link loginOrRegisterWithKey}. */
127
- export interface LoginOrRegisterOptions {
128
- /**
129
- * Account username. Defaults to a slug of `displayName`
130
- * (`/\s+/g → "-"`, lowercased) when omitted.
131
- */
132
- username?: string;
133
- displayName?: string;
134
- deviceName?: string;
135
- inviteCode?: string;
136
- /** Invoked right before auto-registering on first run (for logging). */
137
- onRegister?: () => void;
138
- }
139
-
140
- // ── Signing ──────────────────────────────────────────────────────────────────
141
-
142
- /**
143
- * Sign a base64url server challenge with a 32-byte Ed25519 seed.
144
- * Returns a base64url signature suitable for
145
- * {@link AbracadabraClient.verify}. Synchronous (the sha512 hook is set above).
146
- */
147
- export function signChallengeWithSeed(
148
- challengeB64: string,
149
- seed: Uint8Array,
150
- ): string {
151
- return toBase64url(ed.sign(fromBase64url(challengeB64), seed));
152
- }
153
-
154
- /**
155
- * Build the async `signChallenge` callback that
156
- * {@link AbracadabraClient.loginWithKey} expects, bound to a keypair. Keep the
157
- * returned function around to re-authenticate after a JWT expires.
158
- */
159
- export function makeChallengeSigner(
160
- keypair: NodeKeypair,
161
- ): (challenge: string) => Promise<string> {
162
- return (challenge: string) =>
163
- Promise.resolve(signChallengeWithSeed(challenge, keypair.privateKey));
164
- }
165
-
166
- /**
167
- * Derive a deterministic keypair from a seed string: the same input always
168
- * yields the same on-server identity. Used by `@abraca/orchestrator` so a named
169
- * actor maps to one reproducible account across runs.
170
- *
171
- * @param salt domain-separation suffix (default `"orchestrator-salt"`, the
172
- * historical value — change only if you intend a different identity space).
173
- */
174
- export function deterministicKeypair(
175
- seed: string,
176
- salt = "orchestrator-salt",
177
- ): NodeKeypair {
178
- const privateKey = sha512(
179
- new TextEncoder().encode(`${seed}:${salt}`),
180
- ).slice(0, 32);
181
- return { privateKey, publicKeyB64: toBase64url(ed.getPublicKey(privateKey)) };
182
- }
183
-
184
- // ── Key file (Node only) ─────────────────────────────────────────────────────
185
-
186
- /**
187
- * Load an existing 32-byte Ed25519 seed from `keyPath`, or generate one and
188
- * persist it with `0o600` (dir `0o700`). When `keyPath` is omitted the file is
189
- * `~/.abracadabra/<defaultFileName>`.
190
- *
191
- * Node-only: filesystem modules are loaded via dynamic import, so importing
192
- * this symbol in a browser bundle is safe — only *calling* it requires Node.
193
- */
194
- export async function loadOrCreateKeyFile(
195
- keyPath?: string,
196
- opts: LoadKeyFileOptions = {},
197
- ): Promise<NodeKeypair> {
198
- const { existsSync } = await import("node:fs");
199
- const { readFile, writeFile, mkdir } = await import("node:fs/promises");
200
- const { homedir } = await import("node:os");
201
- const { join, dirname } = await import("node:path");
202
-
203
- const path =
204
- keyPath ??
205
- join(homedir(), ".abracadabra", opts.defaultFileName ?? "identity.key");
206
-
207
- if (existsSync(path)) {
208
- const seed = await readFile(path);
209
- if (seed.length !== 32) {
210
- throw new Error(
211
- `Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`,
212
- );
213
- }
214
- const privateKey = new Uint8Array(seed);
215
- return {
216
- privateKey,
217
- publicKeyB64: toBase64url(ed.getPublicKey(privateKey)),
218
- };
219
- }
220
-
221
- const privateKey = ed.utils.randomSecretKey();
222
- const publicKeyB64 = toBase64url(ed.getPublicKey(privateKey));
223
-
224
- const dir = dirname(path);
225
- if (!existsSync(dir)) await mkdir(dir, { recursive: true, mode: 0o700 });
226
- await writeFile(path, privateKey, { mode: 0o600 });
227
-
228
- opts.onCreate?.({ path, publicKeyB64 });
229
- return { privateKey, publicKeyB64 };
230
- }
231
-
232
- // ── Login / register ─────────────────────────────────────────────────────────
233
-
234
- /**
235
- * Authenticate `keypair` against the server, auto-registering on first run.
236
- *
237
- * Tries {@link AbracadabraClient.loginWithKey}; if the key isn't registered yet
238
- * — signalled by HTTP 404/422, or 401 with a "not registered / user not found"
239
- * message — it calls {@link AbracadabraClient.registerWithKey} and re-logs in.
240
- * Any other error propagates. Returns the JWT.
241
- *
242
- * This is the one shared implementation of the "login → register-on-404 →
243
- * re-login" dance previously copy-pasted into every Node consumer's connect().
244
- */
245
- export async function loginOrRegisterWithKey(
246
- client: KeyAuthClient,
247
- keypair: NodeKeypair,
248
- opts: LoginOrRegisterOptions = {},
249
- ): Promise<string> {
250
- const sign = makeChallengeSigner(keypair);
251
- try {
252
- return await client.loginWithKey(keypair.publicKeyB64, sign);
253
- } catch (err: unknown) {
254
- const e = err as { status?: number; response?: { status?: number }; message?: string };
255
- const status = e?.status ?? e?.response?.status;
256
- const msg = String(e?.message ?? "").toLowerCase();
257
- const notRegistered =
258
- status === 404 ||
259
- status === 422 ||
260
- (status === 401 && /not registered|user not found|no such user/.test(msg));
261
- if (!notRegistered) throw err;
262
-
263
- opts.onRegister?.();
264
- const username =
265
- opts.username ??
266
- (opts.displayName
267
- ? opts.displayName.replace(/\s+/g, "-").toLowerCase()
268
- : undefined);
269
- await client.registerWithKey({
270
- publicKey: keypair.publicKeyB64,
271
- username,
272
- displayName: opts.displayName,
273
- deviceName: opts.deviceName,
274
- inviteCode: opts.inviteCode,
275
- });
276
- return await client.loginWithKey(keypair.publicKeyB64, sign);
277
- }
278
- }
279
-
280
- /**
281
- * Like {@link loginOrRegisterWithKey}, but probes the server's access policy
282
- * first so an un-registered key produces an *actionable* result instead of a raw
283
- * register error. This is what lets a running agent say "this server is
284
- * invite-only — give me a token, or have an admin authorize my public key"
285
- * rather than failing opaquely.
286
- *
287
- * Flow:
288
- * 1. `serverInfo()` (unauthenticated) for the access policy + server name.
289
- * 2. Try `loginWithKey`. Success → fetch `getMe()` for the role → `connected`.
290
- * 3. On a "not registered" error, branch on the policy:
291
- * - an `inviteCode` was supplied → register with it (works for invite-only
292
- * and open servers) → re-login → `connected`.
293
- * - no code + `invite_only` → `needs_invite`.
294
- * - no code + `registration_allowed === false` → `registration_closed`.
295
- * - otherwise (open registration) → register without a code → `connected`.
296
- * 4. Any other login error propagates.
297
- */
298
- export async function loginOrRegisterWithPolicy(
299
- client: PolicyAuthClient,
300
- keypair: NodeKeypair,
301
- opts: LoginOrRegisterOptions = {},
302
- ): Promise<ConnectPolicyResult> {
303
- const sign = makeChallengeSigner(keypair);
304
- const publicKey = keypair.publicKeyB64;
305
-
306
- // Best-effort policy probe — never fatal (older servers may omit fields).
307
- let info: Awaited<ReturnType<PolicyAuthClient["serverInfo"]>> = {};
308
- try {
309
- info = await client.serverInfo();
310
- } catch {
311
- /* fall through with empty policy → behave like open/unknown */
312
- }
313
- const serverName = info.name;
314
-
315
- const connected = async (token: string): Promise<ConnectPolicyResult> => {
316
- let role: string | undefined;
317
- try {
318
- role = (await client.getMe()).role;
319
- } catch {
320
- /* role unknown — don't block the connection on it */
321
- }
322
- // A bare `observer` is the read-only floor: connected, but can't write
323
- // until an admin promotes the key. `service`/`admin`/`owner`/`editor` are
324
- // write-capable; `viewer` is intentionally read-only by grant, not a
325
- // missing-promotion signal, so only flag `observer`.
326
- const needsPromotion = role === "observer";
327
- return {
328
- status: "connected",
329
- token,
330
- publicKey,
331
- serverName,
332
- role,
333
- needsPromotion,
334
- };
335
- };
336
-
337
- try {
338
- return await connected(await client.loginWithKey(publicKey, sign));
339
- } catch (err: unknown) {
340
- const e = err as {
341
- status?: number;
342
- response?: { status?: number };
343
- message?: string;
344
- };
345
- const status = e?.status ?? e?.response?.status;
346
- const msg = String(e?.message ?? "").toLowerCase();
347
- const notRegistered =
348
- status === 404 ||
349
- status === 422 ||
350
- (status === 401 && /not registered|user not found|no such user/.test(msg));
351
- if (!notRegistered) throw err;
352
-
353
- // Not registered — decide based on policy + whether we have a code.
354
- if (!opts.inviteCode) {
355
- if (info.invite_only === true) {
356
- return { status: "needs_invite", publicKey, serverName };
357
- }
358
- if (info.registration_allowed === false) {
359
- return { status: "registration_closed", publicKey, serverName };
360
- }
361
- }
362
-
363
- opts.onRegister?.();
364
- const username =
365
- opts.username ??
366
- (opts.displayName
367
- ? opts.displayName.replace(/\s+/g, "-").toLowerCase()
368
- : undefined);
369
- await client.registerWithKey({
370
- publicKey,
371
- username,
372
- displayName: opts.displayName,
373
- deviceName: opts.deviceName,
374
- inviteCode: opts.inviteCode,
375
- });
376
- return await connected(await client.loginWithKey(publicKey, sign));
377
- }
378
- }
@@ -1,207 +0,0 @@
1
- import EventEmitter from "./EventEmitter.ts";
2
- import type { ChatClientTransport } from "./ChatClient.ts";
3
-
4
- type PendingResolver<T> = {
5
- resolve: (value: T) => void;
6
- reject: (err: Error) => void;
7
- timer: ReturnType<typeof setTimeout>;
8
- };
9
-
10
- const DEFAULT_TIMEOUT_MS = 10_000;
11
-
12
- /** Per-user inbox doc entry. Mirrors `InboxEntry` on the server. */
13
- export interface InboxEntry {
14
- id: string;
15
- /** "mention" | "reply" | "dm" | "system". */
16
- kind: string;
17
- channel_doc_id: string;
18
- message_id?: string | null;
19
- sender_id?: string | null;
20
- sender_name?: string | null;
21
- /** Empty for E2E channels (server can't read body). Filled otherwise. */
22
- preview?: string | null;
23
- ts: number;
24
- /** Synthesized client-side from the inbox doc's `read` Y.Map. */
25
- read: boolean;
26
- }
27
-
28
- export interface FetchInboxInput {
29
- before?: number;
30
- limit?: number;
31
- unread_only?: boolean;
32
- }
33
-
34
- export interface MarkReadInput {
35
- id?: string;
36
- ids?: string[];
37
- source_id?: string;
38
- all?: boolean;
39
- }
40
-
41
- /**
42
- * Thin façade over the `messages:inbox_*` stateless protocol.
43
- *
44
- * Per-user notifications live as Y.Array entries on the user's inbox doc
45
- * (`kind = "inbox"`, owned by the user, child of the server root, server-only
46
- * writer). Real-time observation of new entries is a Y.Array observer the
47
- * consumer attaches via `AbracadabraProvider` on the inbox doc.
48
- *
49
- * This client handles only the request/response layer:
50
- * - `fetch()` issues `messages:inbox_fetch`, returns the entry list.
51
- * - `markRead()` issues `messages:inbox_mark_read` (id / ids / source_id /
52
- * all variants).
53
- *
54
- * For incoming notification observation, open an AbracadabraProvider on the
55
- * inbox doc and observe its `entries` Y.Array directly. The dashboard's
56
- * `useNotifications` composable does this.
57
- */
58
- export class NotificationsClient extends EventEmitter {
59
- private readonly provider: ChatClientTransport;
60
- private readonly responseTimeoutMs: number;
61
- private readonly pending: Map<string, PendingResolver<any>[]> = new Map();
62
- private readonly boundOnStateless: (data: { payload: string }) => void;
63
- private readonly boundOnServerError: (data: {
64
- source: string;
65
- code: string;
66
- message: string;
67
- meta?: unknown;
68
- }) => void;
69
-
70
- constructor(provider: ChatClientTransport, options?: { responseTimeoutMs?: number }) {
71
- super();
72
- this.provider = provider;
73
- this.responseTimeoutMs = options?.responseTimeoutMs ?? DEFAULT_TIMEOUT_MS;
74
- this.boundOnStateless = (data) => this.handleStateless(data.payload);
75
- this.boundOnServerError = (data) => this.handleServerError(data);
76
- this.provider.on("stateless", this.boundOnStateless);
77
- // BaseProvider emits `serverError` for `{type:"error",source,code}` frames
78
- // instead of `stateless`. Subscribe so inbox request rejections surface.
79
- this.provider.on("serverError", this.boundOnServerError);
80
- }
81
-
82
- destroy(): void {
83
- this.provider.off("stateless", this.boundOnStateless);
84
- this.provider.off("serverError", this.boundOnServerError);
85
- for (const queue of this.pending.values()) {
86
- for (const p of queue) {
87
- clearTimeout(p.timer);
88
- p.reject(new Error("NotificationsClient destroyed"));
89
- }
90
- }
91
- this.pending.clear();
92
- this.removeAllListeners();
93
- }
94
-
95
- /** Fetch a slice of the calling user's inbox. Resolves with the entries. */
96
- fetch(input: FetchInboxInput = {}): Promise<{ entries: InboxEntry[] }> {
97
- const promise = this.enqueue<{ entries: InboxEntry[] }>("messages:inbox_history");
98
- this.provider.sendStateless(
99
- JSON.stringify({
100
- type: "messages:inbox_fetch",
101
- ...(input.before !== undefined ? { before: input.before } : {}),
102
- ...(input.limit !== undefined ? { limit: input.limit } : {}),
103
- ...(input.unread_only !== undefined ? { unread_only: input.unread_only } : {}),
104
- }),
105
- );
106
- return promise;
107
- }
108
-
109
- /**
110
- * Mark inbox entries read. One of `id`, `ids`, `source_id`, or `all`.
111
- * Returns when the server has acked.
112
- */
113
- markRead(input: MarkReadInput): Promise<void> {
114
- const body: Record<string, unknown> = { type: "messages:inbox_mark_read" };
115
- if (input.all === true) body.all = true;
116
- else if (input.source_id !== undefined) body.source_id = input.source_id;
117
- else if (input.ids !== undefined) body.ids = input.ids;
118
- else if (input.id !== undefined) body.id = input.id;
119
- else return Promise.reject(new Error("markRead: one of id/ids/source_id/all required"));
120
-
121
- const promise = this.enqueue<void>("messages:inbox_mark_read");
122
- this.provider.sendStateless(JSON.stringify(body));
123
- return promise;
124
- }
125
-
126
- // ── Internals ─────────────────────────────────────────────────────────────
127
-
128
- private enqueue<T>(source: string): Promise<T> {
129
- return new Promise<T>((resolve, reject) => {
130
- const timer = setTimeout(() => {
131
- this.removePending(source, entry);
132
- reject(new Error(`NotificationsClient: timeout waiting for ${source}`));
133
- }, this.responseTimeoutMs);
134
- const entry: PendingResolver<T> = { resolve, reject, timer };
135
- const queue = this.pending.get(source) ?? [];
136
- queue.push(entry);
137
- this.pending.set(source, queue);
138
- });
139
- }
140
-
141
- private removePending(source: string, entry: PendingResolver<any>): void {
142
- const queue = this.pending.get(source);
143
- if (!queue) return;
144
- const idx = queue.indexOf(entry);
145
- if (idx >= 0) queue.splice(idx, 1);
146
- if (queue.length === 0) this.pending.delete(source);
147
- }
148
-
149
- private resolveNext<T>(source: string, value: T): boolean {
150
- const queue = this.pending.get(source);
151
- if (!queue || queue.length === 0) return false;
152
- const next = queue.shift()!;
153
- if (queue.length === 0) this.pending.delete(source);
154
- clearTimeout(next.timer);
155
- next.resolve(value);
156
- return true;
157
- }
158
-
159
- private rejectNext(source: string, err: Error): boolean {
160
- const queue = this.pending.get(source);
161
- if (!queue || queue.length === 0) return false;
162
- const next = queue.shift()!;
163
- if (queue.length === 0) this.pending.delete(source);
164
- clearTimeout(next.timer);
165
- next.reject(err);
166
- return true;
167
- }
168
-
169
- private handleStateless(payload: string): void {
170
- let parsed: any;
171
- try {
172
- parsed = JSON.parse(payload);
173
- } catch {
174
- return;
175
- }
176
- const type: unknown = parsed?.type;
177
- if (typeof type !== "string") return;
178
-
179
- if (type === "messages:inbox_history") {
180
- this.resolveNext("messages:inbox_history", {
181
- entries: parsed.entries ?? [],
182
- });
183
- return;
184
- }
185
- if (type === "messages:ok" && parsed.source === "messages:inbox_mark_read") {
186
- this.resolveNext("messages:inbox_mark_read", undefined);
187
- return;
188
- }
189
- }
190
-
191
- private handleServerError(data: {
192
- source: string;
193
- code: string;
194
- message: string;
195
- meta?: unknown;
196
- }): void {
197
- if (data.source !== "messages:inbox_fetch" && data.source !== "messages:inbox_mark_read") {
198
- return;
199
- }
200
- const key =
201
- data.source === "messages:inbox_fetch" ? "messages:inbox_history" : data.source;
202
- this.rejectNext(
203
- key,
204
- new Error(`${data.code ?? "error"}: ${data.message ?? "inbox request failed"}`),
205
- );
206
- }
207
- }