@ping-app/ping-openmls-sdk 0.0.0-stage → 0.10.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 (39) hide show
  1. package/README.md +94 -2
  2. package/dist/index.cjs +2782 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +1229 -0
  5. package/dist/index.d.ts +1229 -0
  6. package/dist/index.js +2715 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/notification-preview.cjs +137 -0
  9. package/dist/notification-preview.cjs.map +1 -0
  10. package/dist/notification-preview.d.cts +85 -0
  11. package/dist/notification-preview.d.ts +85 -0
  12. package/dist/notification-preview.js +98 -0
  13. package/dist/notification-preview.js.map +1 -0
  14. package/dist/storage/indexeddb.cjs +153 -0
  15. package/dist/storage/indexeddb.cjs.map +1 -0
  16. package/dist/storage/indexeddb.d.cts +21 -0
  17. package/dist/storage/indexeddb.d.ts +21 -0
  18. package/dist/storage/indexeddb.js +128 -0
  19. package/dist/storage/indexeddb.js.map +1 -0
  20. package/dist/transport/websocket.cjs +121 -0
  21. package/dist/transport/websocket.cjs.map +1 -0
  22. package/dist/transport/websocket.d.cts +23 -0
  23. package/dist/transport/websocket.d.ts +23 -0
  24. package/dist/transport/websocket.js +94 -0
  25. package/dist/transport/websocket.js.map +1 -0
  26. package/dist/types-B1GFwNXa.d.cts +535 -0
  27. package/dist/types-B1GFwNXa.d.ts +535 -0
  28. package/dist/worker.cjs +841 -0
  29. package/dist/worker.cjs.map +1 -0
  30. package/dist/worker.d.cts +2 -0
  31. package/dist/worker.d.ts +2 -0
  32. package/dist/worker.js +848 -0
  33. package/dist/worker.js.map +1 -0
  34. package/package.json +61 -4
  35. package/wasm/package.json +17 -0
  36. package/wasm/ping_wasm.d.ts +909 -0
  37. package/wasm/ping_wasm.js +3028 -0
  38. package/wasm/ping_wasm_bg.wasm +0 -0
  39. package/wasm/ping_wasm_bg.wasm.d.ts +112 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,2782 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ BATCH_PARTIAL_PREFIX: () => BATCH_PARTIAL_PREFIX,
34
+ CONTENT_TYPE_CBOR: () => CONTENT_TYPE_CBOR,
35
+ CONTENT_TYPE_CBOR_LEGACY_V1: () => CONTENT_TYPE_CBOR_LEGACY_V1,
36
+ CONTENT_TYPE_JSON: () => CONTENT_TYPE_JSON,
37
+ CONTENT_TYPE_JSON_LEGACY_V1: () => CONTENT_TYPE_JSON_LEGACY_V1,
38
+ EphemeralWorkerError: () => EphemeralWorkerError,
39
+ HPKE_PQ_ENC_BYTES: () => HPKE_PQ_ENC_BYTES,
40
+ HPKE_PQ_PUBLIC_KEY_BYTES: () => HPKE_PQ_PUBLIC_KEY_BYTES,
41
+ IndexedDbStorage: () => IndexedDbStorage,
42
+ MessagingClient: () => MessagingClient,
43
+ MessagingClientClosedError: () => MessagingClientClosedError,
44
+ NOT_PERMITTED_PREFIX: () => NOT_PERMITTED_PREFIX,
45
+ NotPermittedError: () => NotPermittedError,
46
+ PING_WIRE_CONTRACT_HEADER: () => PING_WIRE_CONTRACT_HEADER,
47
+ PING_WIRE_CONTRACT_HEADER_VALUE: () => PING_WIRE_CONTRACT_HEADER_VALUE,
48
+ PING_WIRE_CONTRACT_VERSION: () => PING_WIRE_CONTRACT_VERSION,
49
+ SENDER_MISMATCH_PREFIX: () => SENDER_MISMATCH_PREFIX,
50
+ SenderMismatchError: () => SenderMismatchError,
51
+ ValidationError: () => ValidationError,
52
+ WIRE_VERSION_MIN_ACCEPTED: () => WIRE_VERSION_MIN_ACCEPTED,
53
+ WebSocketTransport: () => WebSocketTransport,
54
+ describeTransportError: () => describeTransportError,
55
+ emulateSendBatch: () => emulateSendBatch,
56
+ isNotPermittedError: () => isNotPermittedError,
57
+ isSenderMismatchError: () => isSenderMismatchError,
58
+ negotiates: () => negotiates,
59
+ notPermittedRule: () => notPermittedRule,
60
+ openNotificationPreview: () => openNotificationPreview,
61
+ validate: () => validate,
62
+ verifyApplicationContentHash: () => verifyApplicationContentHash
63
+ });
64
+ module.exports = __toCommonJS(src_exports);
65
+
66
+ // src/fanout.ts
67
+ function errorKind(e) {
68
+ if (e instanceof Error) return e.name;
69
+ return typeof e;
70
+ }
71
+ var MessageFanout = class {
72
+ messageHandlers = /* @__PURE__ */ new Set();
73
+ batchHandlers = /* @__PURE__ */ new Set();
74
+ onMessage(handler) {
75
+ this.messageHandlers.add(handler);
76
+ return () => this.messageHandlers.delete(handler);
77
+ }
78
+ onMessageBatch(handler) {
79
+ this.batchHandlers.add(handler);
80
+ return () => this.batchHandlers.delete(handler);
81
+ }
82
+ get hasBatchHandlers() {
83
+ return this.batchHandlers.size > 0;
84
+ }
85
+ /** One message from the legacy per-envelope path. */
86
+ deliverOne(m) {
87
+ for (const h of this.messageHandlers) {
88
+ try {
89
+ h(m);
90
+ } catch (e) {
91
+ if (typeof console !== "undefined") {
92
+ console.debug("[ping-sdk] onMessage handler threw:", errorKind(e));
93
+ }
94
+ }
95
+ }
96
+ }
97
+ /**
98
+ * One batch or page result. An empty result is not delivered: there is
99
+ * nothing to persist, and the caller already has the result value.
100
+ */
101
+ deliverBatch(messages, meta) {
102
+ if (messages.length === 0) return;
103
+ if (this.batchHandlers.size === 0) {
104
+ for (const m of messages) this.deliverOne(m);
105
+ return;
106
+ }
107
+ for (const h of this.batchHandlers) {
108
+ try {
109
+ h(messages, meta);
110
+ } catch (e) {
111
+ if (typeof console !== "undefined") {
112
+ console.debug("[ping-sdk] onMessageBatch handler threw:", errorKind(e));
113
+ }
114
+ }
115
+ }
116
+ }
117
+ };
118
+
119
+ // src/gap-fill.ts
120
+ var GapFiller = class {
121
+ lanes = /* @__PURE__ */ new Map();
122
+ /**
123
+ * Fill the gap for `key`. `stepOnce` applies ONE page and resolves `true`
124
+ * while the server may hold more. Resolves when the loop (and any rerun a
125
+ * concurrent request asked for) has finished; rejects with the first step
126
+ * error, which ends that loop.
127
+ */
128
+ fill(key, stepOnce) {
129
+ const running = this.lanes.get(key);
130
+ if (running !== void 0) {
131
+ running.again = true;
132
+ return running.run;
133
+ }
134
+ const lane = { run: Promise.resolve(), again: false };
135
+ lane.run = (async () => {
136
+ try {
137
+ do {
138
+ lane.again = false;
139
+ let more = true;
140
+ while (more) more = await stepOnce();
141
+ } while (lane.again);
142
+ } finally {
143
+ if (this.lanes.get(key) === lane) this.lanes.delete(key);
144
+ }
145
+ })();
146
+ this.lanes.set(key, lane);
147
+ return lane.run;
148
+ }
149
+ /** Conversations with a fill loop running (diagnostics / tests). */
150
+ get inFlight() {
151
+ return this.lanes.size;
152
+ }
153
+ };
154
+
155
+ // src/inbound-coalescer.ts
156
+ var InboundCoalescer = class {
157
+ /**
158
+ * @param apply Applies one batch. A rejection settles the promises of the
159
+ * frames in that batch with the error and the lane moves on to whatever
160
+ * queued meanwhile, so one bad batch cannot wedge a conversation.
161
+ * @param maxBatch Upper bound on frames per batch. A burst larger than
162
+ * this goes out as consecutive batches of at most `maxBatch`, so a
163
+ * flood cannot turn into one unbounded wasm call.
164
+ */
165
+ constructor(apply, maxBatch = 256) {
166
+ this.apply = apply;
167
+ this.maxBatch = maxBatch;
168
+ }
169
+ apply;
170
+ maxBatch;
171
+ lanes = /* @__PURE__ */ new Map();
172
+ /**
173
+ * Queue a frame. Resolves when the batch that carried it has been applied
174
+ * (rejects if that batch failed), so a transport that awaits the dispatch
175
+ * to ack a watermark still sees the truth.
176
+ */
177
+ push(key, item) {
178
+ const lane = this.lanes.get(key);
179
+ if (lane !== void 0) {
180
+ return new Promise((resolve, reject) => {
181
+ lane.queued.push(item);
182
+ lane.waiters.push({ resolve, reject });
183
+ });
184
+ }
185
+ const fresh = { queued: [], waiters: [] };
186
+ this.lanes.set(key, fresh);
187
+ return this.run(key, fresh, [item], []);
188
+ }
189
+ /** Conversations with a batch in flight (diagnostics / tests). */
190
+ get inFlight() {
191
+ return this.lanes.size;
192
+ }
193
+ run(key, lane, items, waiters) {
194
+ let attempt;
195
+ try {
196
+ attempt = this.apply(key, items);
197
+ } catch (e) {
198
+ attempt = Promise.reject(e);
199
+ }
200
+ attempt.then(
201
+ () => {
202
+ for (const w of waiters) w.resolve();
203
+ },
204
+ (e) => {
205
+ for (const w of waiters) w.reject(e);
206
+ }
207
+ );
208
+ void attempt.then(
209
+ () => this.drain(key, lane),
210
+ () => this.drain(key, lane)
211
+ );
212
+ return attempt;
213
+ }
214
+ drain(key, lane) {
215
+ if (lane.queued.length === 0) {
216
+ if (this.lanes.get(key) === lane) this.lanes.delete(key);
217
+ return;
218
+ }
219
+ const items = lane.queued.splice(0, this.maxBatch);
220
+ const waiters = lane.waiters.splice(0, items.length);
221
+ void this.run(key, lane, items, waiters).catch(() => void 0);
222
+ }
223
+ };
224
+
225
+ // src/storage/scope.ts
226
+ function scopeStorage(storage, accountNamespace) {
227
+ const scope = (ns) => `${accountNamespace} ${ns}`;
228
+ const scoped = {
229
+ get: (ns, key) => storage.get(scope(ns), key),
230
+ put: (ns, key, value) => storage.put(scope(ns), key, value),
231
+ del: (ns, key) => storage.del(scope(ns), key),
232
+ listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix)
233
+ };
234
+ const hostApplyBatch = storage.applyBatch;
235
+ if (typeof hostApplyBatch === "function") {
236
+ scoped.applyBatch = (ns, puts, deletes) => hostApplyBatch.call(storage, scope(ns), puts, deletes);
237
+ }
238
+ const hostListEntries = storage.listEntries;
239
+ if (typeof hostListEntries === "function") {
240
+ scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);
241
+ }
242
+ return scoped;
243
+ }
244
+ function storageFeaturesOf(storage) {
245
+ return {
246
+ applyBatch: typeof storage.applyBatch === "function",
247
+ listEntries: typeof storage.listEntries === "function"
248
+ };
249
+ }
250
+
251
+ // src/sequenced.ts
252
+ function isSequencedFrame(frame) {
253
+ return typeof frame === "object" && frame !== null && "envelope" in frame && typeof frame.envelope === "object" && frame.envelope !== null;
254
+ }
255
+ function sequencedToWire(item) {
256
+ return { envelope: item.envelope, server_seq: item.serverSeq };
257
+ }
258
+ function logPositionFromWire(p) {
259
+ return {
260
+ conversationId: p.conversation_id,
261
+ epoch: p.epoch,
262
+ serverSeq: p.server_seq,
263
+ anchored: p.anchored
264
+ };
265
+ }
266
+ function logHeadToWire(h) {
267
+ return {
268
+ conversation_id: h.conversationId,
269
+ head_server_seq: h.headServerSeq,
270
+ head_epoch: h.headEpoch
271
+ };
272
+ }
273
+ function logGapFromWire(g) {
274
+ return {
275
+ conversationId: g.conversation_id,
276
+ appliedServerSeq: g.applied_server_seq,
277
+ firstBufferedServerSeq: g.first_buffered_server_seq
278
+ };
279
+ }
280
+ function conversationUpdateFromWire(u) {
281
+ return { conversationId: u.conversation_id, epoch: u.epoch };
282
+ }
283
+ function variant(name) {
284
+ return name.charAt(0).toLowerCase() + name.slice(1);
285
+ }
286
+ function conversationRemovalFromWire(r) {
287
+ return {
288
+ conversationId: r.conversation_id,
289
+ serverSeq: r.server_seq,
290
+ epoch: r.epoch,
291
+ readmitted: r.readmitted
292
+ };
293
+ }
294
+ function welcomeFailureFromWire(w) {
295
+ return {
296
+ conversationId: w.conversation_id,
297
+ serverSeq: w.server_seq,
298
+ reason: variant(w.reason)
299
+ };
300
+ }
301
+ function strandedConversationFromWire(s) {
302
+ return {
303
+ conversationId: s.conversation_id,
304
+ serverSeq: s.server_seq,
305
+ epoch: s.epoch,
306
+ reason: variant(s.reason)
307
+ };
308
+ }
309
+ function bufferOverflowFromWire(o) {
310
+ return {
311
+ conversationId: o.conversation_id,
312
+ reason: variant(o.reason),
313
+ dropped: o.dropped
314
+ };
315
+ }
316
+ function outcomesFromWire(r) {
317
+ return {
318
+ removed: (r.removed ?? []).map(conversationRemovalFromWire),
319
+ welcomeFailures: (r.welcome_failures ?? []).map(welcomeFailureFromWire),
320
+ stranded: (r.stranded ?? []).map(strandedConversationFromWire),
321
+ proposalsPending: r.proposals_pending ?? [],
322
+ overflow: (r.overflow ?? []).map(bufferOverflowFromWire)
323
+ };
324
+ }
325
+ function applyBatchResultFromWire(r) {
326
+ return {
327
+ messages: r.messages,
328
+ applied: r.applied,
329
+ duplicates: r.duplicates,
330
+ buffered: r.buffered,
331
+ failed: r.failed,
332
+ gaps: r.gaps.map(logGapFromWire),
333
+ joined: r.joined,
334
+ updated: r.updated.map(conversationUpdateFromWire),
335
+ ...outcomesFromWire(r)
336
+ };
337
+ }
338
+ function syncStepResultFromWire(r) {
339
+ return {
340
+ messages: r.messages,
341
+ hasMore: r.has_more,
342
+ fetched: r.fetched,
343
+ position: logPositionFromWire(r.position),
344
+ updated: r.updated.map(conversationUpdateFromWire),
345
+ joined: r.joined ?? [],
346
+ ...outcomesFromWire(r)
347
+ };
348
+ }
349
+ function addMembersReportFromWire(r) {
350
+ return {
351
+ verdicts: r.verdicts.map((v) => ({
352
+ deviceId: v.device_id,
353
+ status: variant(v.status),
354
+ leafIndex: v.leaf_index ?? null
355
+ })),
356
+ epoch: r.epoch ?? null
357
+ };
358
+ }
359
+ function commitInDoubtFromWire(c) {
360
+ return {
361
+ conversationId: c.conversation_id,
362
+ attempts: c.attempts,
363
+ nextAttemptAtMs: c.next_attempt_at_ms
364
+ };
365
+ }
366
+
367
+ // src/storage/indexeddb.ts
368
+ var DB_NAME = "ping-sdk";
369
+ var DB_VERSION = 1;
370
+ var STORE = "kv";
371
+ function open() {
372
+ return new Promise((resolve, reject) => {
373
+ const req = indexedDB.open(DB_NAME, DB_VERSION);
374
+ req.onupgradeneeded = () => {
375
+ const db = req.result;
376
+ if (!db.objectStoreNames.contains(STORE)) {
377
+ const os = db.createObjectStore(STORE, { keyPath: ["ns", "key"] });
378
+ os.createIndex("ns", "ns", { unique: false });
379
+ }
380
+ };
381
+ req.onsuccess = () => resolve(req.result);
382
+ req.onerror = () => reject(req.error);
383
+ });
384
+ }
385
+ var IndexedDbStorage = class {
386
+ dbPromise;
387
+ constructor() {
388
+ this.dbPromise = open();
389
+ }
390
+ async get(namespace, key) {
391
+ const db = await this.dbPromise;
392
+ return new Promise((resolve, reject) => {
393
+ const tx = db.transaction(STORE, "readonly");
394
+ const r = tx.objectStore(STORE).get([namespace, key]);
395
+ r.onsuccess = () => resolve(r.result?.value ?? null);
396
+ r.onerror = () => reject(r.error);
397
+ });
398
+ }
399
+ async put(namespace, key, value) {
400
+ const db = await this.dbPromise;
401
+ return new Promise((resolve, reject) => {
402
+ const tx = db.transaction(STORE, "readwrite");
403
+ tx.objectStore(STORE).put({ ns: namespace, key, value });
404
+ tx.oncomplete = () => resolve();
405
+ tx.onerror = () => reject(tx.error);
406
+ });
407
+ }
408
+ async del(namespace, key) {
409
+ const db = await this.dbPromise;
410
+ return new Promise((resolve, reject) => {
411
+ const tx = db.transaction(STORE, "readwrite");
412
+ tx.objectStore(STORE).delete([namespace, key]);
413
+ tx.oncomplete = () => resolve();
414
+ tx.onerror = () => reject(tx.error);
415
+ });
416
+ }
417
+ /**
418
+ * One `readwrite` transaction for the whole batch. Every request is issued
419
+ * synchronously inside it (an await on anything else would let the
420
+ * transaction auto-commit), so a failure or a crash mid-way aborts all of
421
+ * it: the per-row MLS store relies on that to keep a checkpoint atomic.
422
+ */
423
+ async applyBatch(namespace, puts, deletes) {
424
+ if (puts.length === 0 && deletes.length === 0) return;
425
+ const db = await this.dbPromise;
426
+ return new Promise((resolve, reject) => {
427
+ const tx = db.transaction(STORE, "readwrite");
428
+ let settled = false;
429
+ const fail = (e) => {
430
+ if (settled) return;
431
+ settled = true;
432
+ reject(e instanceof Error ? e : new Error(String(e)));
433
+ };
434
+ tx.oncomplete = () => {
435
+ if (!settled) {
436
+ settled = true;
437
+ resolve();
438
+ }
439
+ };
440
+ tx.onerror = () => fail(tx.error);
441
+ tx.onabort = () => fail(tx.error ?? new Error("applyBatch aborted"));
442
+ try {
443
+ const os = tx.objectStore(STORE);
444
+ for (const [key, value] of puts) os.put({ ns: namespace, key, value });
445
+ for (const key of deletes) os.delete([namespace, key]);
446
+ } catch (e) {
447
+ try {
448
+ tx.abort();
449
+ } catch {
450
+ }
451
+ fail(e);
452
+ }
453
+ });
454
+ }
455
+ /** Every `[key, value]` under `namespace` with the prefix, in one read. */
456
+ async listEntries(namespace, prefix) {
457
+ const db = await this.dbPromise;
458
+ return new Promise((resolve, reject) => {
459
+ const tx = db.transaction(STORE, "readonly");
460
+ const idx = tx.objectStore(STORE).index("ns");
461
+ const req = idx.openCursor(IDBKeyRange.only(namespace));
462
+ const out = [];
463
+ req.onsuccess = () => {
464
+ const cur = req.result;
465
+ if (!cur) return resolve(out);
466
+ const row = cur.value;
467
+ if (!prefix || row.key.startsWith(prefix)) out.push([row.key, row.value]);
468
+ cur.continue();
469
+ };
470
+ req.onerror = () => reject(req.error);
471
+ });
472
+ }
473
+ async listKeys(namespace, prefix) {
474
+ const db = await this.dbPromise;
475
+ return new Promise((resolve, reject) => {
476
+ const tx = db.transaction(STORE, "readonly");
477
+ const idx = tx.objectStore(STORE).index("ns");
478
+ const req = idx.openCursor(IDBKeyRange.only(namespace));
479
+ const out = [];
480
+ req.onsuccess = () => {
481
+ const cur = req.result;
482
+ if (!cur) return resolve(out);
483
+ const row = cur.value;
484
+ if (!prefix || row.key.startsWith(prefix)) out.push(row.key);
485
+ cur.continue();
486
+ };
487
+ req.onerror = () => reject(req.error);
488
+ });
489
+ }
490
+ };
491
+
492
+ // src/wire-contract.ts
493
+ var PING_WIRE_CONTRACT_VERSION = 2;
494
+ var WIRE_VERSION_MIN_ACCEPTED = 1;
495
+ var CONTENT_TYPE_CBOR = "application/vnd.ping.wire.v2+cbor";
496
+ var CONTENT_TYPE_JSON = "application/vnd.ping.wire.v2+json";
497
+ var CONTENT_TYPE_CBOR_LEGACY_V1 = "application/vnd.ping.wire.v1+cbor";
498
+ var CONTENT_TYPE_JSON_LEGACY_V1 = "application/vnd.ping.wire.v1+json";
499
+ var PING_WIRE_CONTRACT_HEADER = "X-Ping-Wire-Contract";
500
+ var PING_WIRE_CONTRACT_HEADER_VALUE = `ping/${PING_WIRE_CONTRACT_VERSION}`;
501
+ var ValidationError = class extends Error {
502
+ constructor(kind, message) {
503
+ super(message);
504
+ this.kind = kind;
505
+ this.name = "PingWireContractValidationError";
506
+ }
507
+ kind;
508
+ };
509
+ var KIND_DISCRIMINANT = {
510
+ Application: 1,
511
+ Commit: 2,
512
+ Welcome: 3,
513
+ Proposal: 4,
514
+ KeyPackage: 5
515
+ };
516
+ async function sha256(bytes) {
517
+ const ab = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
518
+ const hash = await crypto.subtle.digest("SHA-256", ab);
519
+ return new Uint8Array(hash);
520
+ }
521
+ function bytesEqual(a, b) {
522
+ if (a.length !== b.length) return false;
523
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
524
+ return true;
525
+ }
526
+ async function validate(env) {
527
+ if (env.v < WIRE_VERSION_MIN_ACCEPTED || env.v > PING_WIRE_CONTRACT_VERSION) {
528
+ throw new ValidationError(
529
+ "UnsupportedVersion",
530
+ `unsupported wire-contract version: envelope says v=${env.v}, expected v\u2208[${WIRE_VERSION_MIN_ACCEPTED}, ${PING_WIRE_CONTRACT_VERSION}]`
531
+ );
532
+ }
533
+ if (env.conversation_id.length !== 16) {
534
+ throw new ValidationError(
535
+ "BadConversationIdLen",
536
+ `conversation_id must be 16 bytes (ULID), got ${env.conversation_id.length}`
537
+ );
538
+ }
539
+ if (env.sender_device.length !== 32) {
540
+ throw new ValidationError(
541
+ "BadSenderDeviceLen",
542
+ `sender_device must be 32 bytes, got ${env.sender_device.length}`
543
+ );
544
+ }
545
+ if (env.v >= 2 && env.kind === "Application") {
546
+ return;
547
+ }
548
+ const buf = new Uint8Array(1 + env.payload.length);
549
+ buf[0] = KIND_DISCRIMINANT[env.kind];
550
+ buf.set(env.payload, 1);
551
+ const computed = await sha256(buf);
552
+ if (!bytesEqual(computed, env.content_hash)) {
553
+ throw new ValidationError(
554
+ "ContentHashMismatch",
555
+ "content_hash mismatch: envelope is forged, corrupted, or built by a non-conformant sender"
556
+ );
557
+ }
558
+ }
559
+ async function verifyApplicationContentHash(env, plaintext) {
560
+ if (env.v < 2 || env.kind !== "Application") return;
561
+ const computed = await sha256(plaintext);
562
+ if (!bytesEqual(computed, env.content_hash)) {
563
+ throw new ValidationError(
564
+ "ContentHashMismatch",
565
+ "v=2 application content_hash mismatch against decrypted plaintext"
566
+ );
567
+ }
568
+ }
569
+ function negotiates(contentType) {
570
+ if (!contentType) return false;
571
+ const primary = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
572
+ return primary === CONTENT_TYPE_CBOR || primary === CONTENT_TYPE_JSON || primary === CONTENT_TYPE_CBOR_LEGACY_V1 || primary === CONTENT_TYPE_JSON_LEGACY_V1;
573
+ }
574
+
575
+ // src/transport/websocket.ts
576
+ var WebSocketTransport = class {
577
+ constructor(cfg) {
578
+ this.cfg = cfg;
579
+ this.fetchImpl = cfg.fetchImpl ?? globalThis.fetch.bind(globalThis);
580
+ this.openSocket();
581
+ }
582
+ cfg;
583
+ ws = null;
584
+ liveHandlers = /* @__PURE__ */ new Set();
585
+ fetchImpl;
586
+ openSocket() {
587
+ if (typeof WebSocket === "undefined") return;
588
+ const url = `${this.cfg.baseUrl.replace(/^http/, "ws")}/stream`;
589
+ this.ws = new WebSocket(url);
590
+ this.ws.onmessage = (ev) => {
591
+ const text = typeof ev.data === "string" ? ev.data : new TextDecoder().decode(ev.data);
592
+ try {
593
+ const env = JSON.parse(text, reviver);
594
+ for (const h of this.liveHandlers) h(env);
595
+ } catch (e) {
596
+ if (typeof console !== "undefined") console.debug("[ping-sdk] WS frame parse error:", e);
597
+ }
598
+ };
599
+ this.ws.onclose = () => setTimeout(() => this.openSocket(), 1e3);
600
+ }
601
+ async send(envelope) {
602
+ const res = await this.fetchImpl(`${this.cfg.baseUrl}/send`, {
603
+ method: "POST",
604
+ headers: {
605
+ "content-type": CONTENT_TYPE_JSON,
606
+ [PING_WIRE_CONTRACT_HEADER]: PING_WIRE_CONTRACT_HEADER_VALUE,
607
+ ...this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {}
608
+ },
609
+ body: JSON.stringify(envelope, replacer)
610
+ });
611
+ if (res.status === 409) throw new Error("EpochOccupied");
612
+ if (!res.ok) throw new Error(`transport send failed: ${res.status}`);
613
+ }
614
+ async fetchSince(conversationId, cursor, limit) {
615
+ const url = new URL(`${this.cfg.baseUrl}/sync`);
616
+ url.searchParams.set("conv", toHex(conversationId));
617
+ url.searchParams.set("cursor", btoaUrl(cursor));
618
+ url.searchParams.set("limit", String(limit));
619
+ const res = await this.fetchImpl(url.toString(), {
620
+ headers: { ...this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {} }
621
+ });
622
+ if (!res.ok) throw new Error(`transport fetch failed: ${res.status}`);
623
+ const text = await res.text();
624
+ return JSON.parse(text, reviver);
625
+ }
626
+ subscribe(onEvent) {
627
+ this.liveHandlers.add(onEvent);
628
+ return { unsubscribe: () => this.liveHandlers.delete(onEvent) };
629
+ }
630
+ async discoverDevices(userId) {
631
+ const res = await this.fetchImpl(`${this.cfg.baseUrl}/devices/${toHex(userId)}`, {
632
+ headers: { ...this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {} }
633
+ });
634
+ if (!res.ok) throw new Error(`device discovery failed: ${res.status}`);
635
+ const text = await res.text();
636
+ return JSON.parse(text, reviver);
637
+ }
638
+ };
639
+ function replacer(_k, v) {
640
+ if (v instanceof Uint8Array) return { _bytes: Array.from(v) };
641
+ return v;
642
+ }
643
+ function reviver(_k, v) {
644
+ if (v && typeof v === "object" && Array.isArray(v._bytes)) {
645
+ return new Uint8Array(v._bytes);
646
+ }
647
+ return v;
648
+ }
649
+ function toHex(b) {
650
+ let s = "";
651
+ for (const v of b) s += v.toString(16).padStart(2, "0");
652
+ return s;
653
+ }
654
+ function btoaUrl(b) {
655
+ let s = "";
656
+ for (const v of b) s += String.fromCharCode(v);
657
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
658
+ }
659
+
660
+ // src/wasm-memory.ts
661
+ var RESERVE_MIB_TARGETS = [192, 128, 64, 32];
662
+ var WASM_PAGE_BYTES = 64 * 1024;
663
+ var reserved = /* @__PURE__ */ new WeakSet();
664
+ function reserveLinearMemory(memory) {
665
+ if (reserved.has(memory)) return;
666
+ reserved.add(memory);
667
+ for (const mib of RESERVE_MIB_TARGETS) {
668
+ try {
669
+ memory.grow(mib * 1024 * 1024 / WASM_PAGE_BYTES);
670
+ return;
671
+ } catch {
672
+ }
673
+ }
674
+ }
675
+
676
+ // src/notification-preview.ts
677
+ async function openNotificationPreview(opts) {
678
+ const now = opts.now ?? (() => Date.now());
679
+ const scoped = opts.accountNamespace !== void 0 && opts.accountNamespace.length > 0 ? scopeStorage(opts.storage, opts.accountNamespace) : opts.storage;
680
+ const storage = readOnlyStorage(scoped);
681
+ const wasm = await import("../wasm/ping_wasm");
682
+ const out = await wasm.default(
683
+ opts.wasmModuleOrPath === void 0 ? void 0 : { module_or_path: opts.wasmModuleOrPath }
684
+ );
685
+ reserveLinearMemory(out.memory);
686
+ const client = await wasm.PingClient.openReadOnly(
687
+ opts.identityExport,
688
+ // Label is unused on the read-only path (no LocalDevice is ever minted).
689
+ "notification-preview",
690
+ storage,
691
+ silentTransport(),
692
+ now()
693
+ );
694
+ let closed = false;
695
+ return {
696
+ async previewEnvelope(envelope) {
697
+ if (closed) throw new Error("notification-preview session is closed");
698
+ const result = client.previewEnvelope(envelope, now());
699
+ return result ?? null;
700
+ },
701
+ close() {
702
+ if (closed) return;
703
+ closed = true;
704
+ client.free();
705
+ }
706
+ };
707
+ }
708
+ function readOnlyStorage(storage) {
709
+ const refuse = (op) => Promise.reject(
710
+ new Error(`notification-preview storage is read-only (attempted ${op})`)
711
+ );
712
+ const readOnly = {
713
+ get: (ns, key) => storage.get(ns, key),
714
+ put: (_ns, _key, _value) => refuse("put"),
715
+ del: (_ns, _key) => refuse("del"),
716
+ listKeys: (ns, prefix) => storage.listKeys(ns, prefix)
717
+ };
718
+ const hostListEntries = storage.listEntries;
719
+ if (typeof hostListEntries === "function") {
720
+ readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);
721
+ }
722
+ return readOnly;
723
+ }
724
+ function silentTransport() {
725
+ return {
726
+ send: () => Promise.reject(new Error("notification-preview cannot send")),
727
+ fetchSince: () => Promise.resolve([]),
728
+ discoverDevices: () => Promise.resolve([]),
729
+ setNextWelcomeRecipients: () => Promise.resolve()
730
+ };
731
+ }
732
+
733
+ // src/index.ts
734
+ var import_meta = {};
735
+ var MessagingClient = class _MessagingClient {
736
+ worker;
737
+ nextId = 1;
738
+ pending = /* @__PURE__ */ new Map();
739
+ storage;
740
+ transport;
741
+ now;
742
+ /** `onMessage` / `onMessageBatch` handlers and the guarded delivery to them. */
743
+ fanout = new MessageFanout();
744
+ conversationHandlers = /* @__PURE__ */ new Set();
745
+ subscription = null;
746
+ /**
747
+ * This client's copy of each conversation's metadata, keyed by lowercase-hex
748
+ * conversation id: what a conversation handle's `name`, `epoch` and `meta()`
749
+ * answer from.
750
+ *
751
+ * It is never older than what the host has been told. The worker attaches a
752
+ * conversation's metadata to every change it reports, and {@link handleWorker}
753
+ * stores it before it calls a listener or settles a call; an entry whose
754
+ * conversation changed with no metadata attached is dropped, never kept.
755
+ * Bounded by the conversations the client holds: an entry goes when its
756
+ * conversation is left, dropped or removed, and `listConversations()`
757
+ * replaces the whole map.
758
+ */
759
+ metaCache = /* @__PURE__ */ new Map();
760
+ /**
761
+ * Per-conversation batching of sequenced live frames: the first frame goes
762
+ * to the worker at once, frames that arrive while that batch is in flight
763
+ * go out as ONE `processSequencedBatch` when it returns. See
764
+ * {@link dispatchIncoming}.
765
+ */
766
+ coalescer = new InboundCoalescer(
767
+ (_key, items) => this.applyLiveBatch(items)
768
+ );
769
+ /** Single-flight gap fills, one `syncConversationStep` loop per conversation. */
770
+ gapFiller = new GapFiller();
771
+ /** Set by {@link close}: every later call rejects instead of hanging. */
772
+ closed = false;
773
+ // Cached at init() so dispatchIncoming can skip envelopes we sent ourselves — the relay
774
+ // broadcasts to all WS subscribers including the sender, and re-applying our own already-
775
+ // merged commits would error with "epoch differs".
776
+ ownDeviceId = null;
777
+ /**
778
+ * Per-conversation dispatch chains. See {@link dispatchIncoming}.
779
+ *
780
+ * Keyed by lowercase-hex conversation id. Bounded: a chain is deleted the
781
+ * moment it settles and is still the tail, so an account with thousands of
782
+ * conversations holds at most one entry per conversation with work IN FLIGHT,
783
+ * not one per conversation it has ever seen.
784
+ */
785
+ dispatchChains = /* @__PURE__ */ new Map();
786
+ constructor(cfg, worker) {
787
+ this.worker = worker;
788
+ this.storage = cfg.accountNamespace !== void 0 && cfg.accountNamespace.length > 0 ? scopeStorage(cfg.storage, cfg.accountNamespace) : cfg.storage;
789
+ this.transport = cfg.transport;
790
+ this.now = cfg.now ?? (() => Date.now());
791
+ this.worker.onmessage = (ev) => this.handleWorker(ev.data);
792
+ this.worker.onerror = () => this.failPending(new MessagingClientClosedError("worker-error"));
793
+ }
794
+ /** Generate a fresh identity. The returned bytes are a secret — store them encrypted. */
795
+ static async generateIdentity() {
796
+ return _MessagingClient.ephemeralWorkerCall({
797
+ kind: "generateIdentity",
798
+ id: 1
799
+ });
800
+ }
801
+ /**
802
+ * HPKE-seal a `LinkingTicket` for delivery to a new device ([CR-3]).
803
+ *
804
+ * Returns CBOR-encoded bytes safe to relay through an untrusted inbox. The new device's
805
+ * X25519 public key (`newDevicePub`) is exchanged out-of-band — typically as part of a
806
+ * QR-encoded handshake on the linking screen. Pure function; runs in an ephemeral
807
+ * worker so no live `MessagingClient` is required on the sender side.
808
+ *
809
+ * Suite: `DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-128-GCM` (matches MLS).
810
+ */
811
+ static async sealLinkingTicket(ticket, newDevicePub) {
812
+ if (newDevicePub.length !== 32) {
813
+ throw new Error("sealLinkingTicket: newDevicePub must be 32 bytes");
814
+ }
815
+ return _MessagingClient.ephemeralWorkerCall({
816
+ kind: "sealLinkingTicket",
817
+ id: 1,
818
+ ticket,
819
+ newDevicePub
820
+ });
821
+ }
822
+ /**
823
+ * HPKE-open a sealed `LinkingTicket` on the new device ([CR-3]).
824
+ *
825
+ * The receiving device hasn't booted a `MessagingClient` yet — it only has its X25519
826
+ * ephemeral keypair. This static method runs the open in an ephemeral worker, returning
827
+ * the cleartext ticket which the host then feeds to `init()` + `consumeLinkingTicket()`.
828
+ *
829
+ * On failure the error message is deliberately generic (no discriminator between "wrong
830
+ * key" vs "tampered ciphertext") so a probing attacker can't tell the new device's key
831
+ * was the issue.
832
+ */
833
+ static async openLinkingTicket(sealed, newDevicePriv) {
834
+ if (newDevicePriv.length !== 32) {
835
+ throw new Error("openLinkingTicket: newDevicePriv must be 32 bytes");
836
+ }
837
+ return _MessagingClient.ephemeralWorkerCall({
838
+ kind: "openLinkingTicket",
839
+ id: 1,
840
+ sealed,
841
+ newDevicePriv
842
+ });
843
+ }
844
+ /**
845
+ * Generic HPKE-Base seal of arbitrary bytes to `recipientPub` (32-byte X25519)
846
+ * under a caller-supplied `info`. One shared HPKE implementation so app layers
847
+ * (e.g. the device-linking auth envelope) stop hand-rolling per-platform HPKE
848
+ * that drifts and breaks cross-platform. Runs in an ephemeral worker.
849
+ */
850
+ static async hpkeSeal(plaintext, recipientPub, info) {
851
+ if (recipientPub.length !== 32) {
852
+ throw new Error("hpkeSeal: recipientPub must be 32 bytes");
853
+ }
854
+ return _MessagingClient.ephemeralWorkerCall({
855
+ kind: "hpkeSeal",
856
+ id: 1,
857
+ plaintext,
858
+ recipientPub,
859
+ info
860
+ });
861
+ }
862
+ /** Generic HPKE-Base open — inverse of {@link hpkeSeal}. `info` must match the sender. */
863
+ static async hpkeOpen(sealed, recipientPriv, info) {
864
+ if (recipientPriv.length !== 32) {
865
+ throw new Error("hpkeOpen: recipientPriv must be 32 bytes");
866
+ }
867
+ return _MessagingClient.ephemeralWorkerCall({
868
+ kind: "hpkeOpen",
869
+ id: 1,
870
+ sealed,
871
+ recipientPriv,
872
+ info
873
+ });
874
+ }
875
+ /**
876
+ * HPKE-Base seal in the RFC 9180 CANONICAL layout, `enc || ct||tag`, with no
877
+ * CBOR wrapper.
878
+ *
879
+ * Use this, not {@link hpkeSeal}, for anything the app layers already speak.
880
+ * `hpkeSeal` wraps its output in CBOR `{v, enc, ct}` for the linking ticket,
881
+ * and because that could not read the RFC layout, iOS, Android, web and the
882
+ * third-party `ping-notify` sender each ended up hand-composing their own
883
+ * HPKE for the same suite. This is the one they agree on.
884
+ */
885
+ static async hpkeSealRaw(plaintext, recipientPub, info) {
886
+ if (recipientPub.length !== 32) {
887
+ throw new Error("hpkeSealRaw: recipientPub must be 32 bytes");
888
+ }
889
+ return _MessagingClient.ephemeralWorkerCall({
890
+ kind: "hpkeSealRaw",
891
+ id: 1,
892
+ plaintext,
893
+ recipientPub,
894
+ info
895
+ });
896
+ }
897
+ /**
898
+ * Inverse of {@link hpkeSealRaw}. `info` must match the sender's.
899
+ *
900
+ * Rejects with one uniform error whatever went wrong. This opens bytes from
901
+ * an unauthenticated inbox, so a caller that could tell "wrong key" from
902
+ * "tampered" from "truncated" would be an oracle for whoever wrote them.
903
+ */
904
+ static async hpkeOpenRaw(sealed, recipientPriv, info) {
905
+ if (recipientPriv.length !== 32) {
906
+ throw new Error("hpkeOpenRaw: recipientPriv must be 32 bytes");
907
+ }
908
+ return _MessagingClient.ephemeralWorkerCall({
909
+ kind: "hpkeOpenRaw",
910
+ id: 1,
911
+ sealed,
912
+ recipientPriv,
913
+ info
914
+ });
915
+ }
916
+ /**
917
+ * A fresh X25519 keypair for the suite.
918
+ *
919
+ * Exposed so a caller minting a recipient key (a Ping Notify inbox, a linking
920
+ * handshake) does not reach for WebCrypto to do it, which is the same problem
921
+ * one layer down.
922
+ */
923
+ static async hpkeGenerateKeypair() {
924
+ const both = await _MessagingClient.ephemeralWorkerCall({
925
+ kind: "hpkeGenerateKeypair",
926
+ id: 1
927
+ });
928
+ if (both.length !== 64) {
929
+ throw new Error("hpkeGenerateKeypair: expected 64 bytes");
930
+ }
931
+ return { publicKey: both.slice(0, 32), privateKey: both.slice(32) };
932
+ }
933
+ // ---- Post-quantum HPKE (X-Wing), docs/POST_QUANTUM.md phase 2 ----
934
+ //
935
+ // The `Pq` twins of the functions above: HPKE with KEM X-Wing draft-06
936
+ // (ML-KEM-768 + X25519), HKDF-SHA256, AES-128-GCM. A public key is
937
+ // {@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes, `enc` {@link HPKE_PQ_ENC_BYTES}, the
938
+ // private key a 32-byte seed. These are what the pairing, link-auth,
939
+ // history-transfer and app-inbox flows use from phase 2 on; the classical
940
+ // forms stay for app inboxes created with a 32-byte key before the roll. A
941
+ // classical private key and an X-Wing seed are both 32 bytes but are NOT
942
+ // interchangeable: the host knows which family a stored key belongs to.
943
+ /**
944
+ * HPKE-seal a `LinkingTicket` under the new device's X-Wing public key
945
+ * ([CR-3], post-quantum). CBOR `{v: 2, enc, ct}` under `ping/link/v2`; the
946
+ * classical {@link openLinkingTicket} refuses it and {@link openLinkingTicketPq}
947
+ * refuses a `v: 1` blob, so there is no downgrade in either direction.
948
+ */
949
+ static async sealLinkingTicketPq(ticket, newDevicePub) {
950
+ if (newDevicePub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
951
+ throw new Error(`sealLinkingTicketPq: newDevicePub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
952
+ }
953
+ return _MessagingClient.ephemeralWorkerCall({
954
+ kind: "sealLinkingTicketPq",
955
+ id: 1,
956
+ ticket,
957
+ newDevicePub
958
+ });
959
+ }
960
+ /**
961
+ * HPKE-open a sealed `v: 2` ticket with the new device's 32-byte X-Wing seed
962
+ * ([CR-3], post-quantum). The error is deliberately generic, like
963
+ * {@link openLinkingTicket}.
964
+ */
965
+ static async openLinkingTicketPq(sealed, newDevicePriv) {
966
+ if (newDevicePriv.length !== 32) {
967
+ throw new Error("openLinkingTicketPq: newDevicePriv must be 32 bytes");
968
+ }
969
+ return _MessagingClient.ephemeralWorkerCall({
970
+ kind: "openLinkingTicketPq",
971
+ id: 1,
972
+ sealed,
973
+ newDevicePriv
974
+ });
975
+ }
976
+ /** Post-quantum {@link hpkeSeal}: CBOR-wrapped (`v: 2`), `recipientPub` is 1216 bytes. */
977
+ static async hpkeSealPq(plaintext, recipientPub, info) {
978
+ if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
979
+ throw new Error(`hpkeSealPq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
980
+ }
981
+ return _MessagingClient.ephemeralWorkerCall({
982
+ kind: "hpkeSealPq",
983
+ id: 1,
984
+ plaintext,
985
+ recipientPub,
986
+ info
987
+ });
988
+ }
989
+ /** Inverse of {@link hpkeSealPq}. `recipientPriv` is the 32-byte seed; `info` must match. */
990
+ static async hpkeOpenPq(sealed, recipientPriv, info) {
991
+ if (recipientPriv.length !== 32) {
992
+ throw new Error("hpkeOpenPq: recipientPriv must be 32 bytes");
993
+ }
994
+ return _MessagingClient.ephemeralWorkerCall({
995
+ kind: "hpkeOpenPq",
996
+ id: 1,
997
+ sealed,
998
+ recipientPriv,
999
+ info
1000
+ });
1001
+ }
1002
+ /**
1003
+ * Post-quantum {@link hpkeSealRaw}: RFC 9180 canonical `enc(1120) || ct || tag`.
1004
+ * The `v2` form of every app-layer envelope (`ping/link-auth/v2`,
1005
+ * `ping/app-inbox/v2`).
1006
+ */
1007
+ static async hpkeSealRawPq(plaintext, recipientPub, info) {
1008
+ if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
1009
+ throw new Error(`hpkeSealRawPq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
1010
+ }
1011
+ return _MessagingClient.ephemeralWorkerCall({
1012
+ kind: "hpkeSealRawPq",
1013
+ id: 1,
1014
+ plaintext,
1015
+ recipientPub,
1016
+ info
1017
+ });
1018
+ }
1019
+ /** Inverse of {@link hpkeSealRawPq}. One uniform error, as for {@link hpkeOpenRaw}. */
1020
+ static async hpkeOpenRawPq(sealed, recipientPriv, info) {
1021
+ if (recipientPriv.length !== 32) {
1022
+ throw new Error("hpkeOpenRawPq: recipientPriv must be 32 bytes");
1023
+ }
1024
+ return _MessagingClient.ephemeralWorkerCall({
1025
+ kind: "hpkeOpenRawPq",
1026
+ id: 1,
1027
+ sealed,
1028
+ recipientPriv,
1029
+ info
1030
+ });
1031
+ }
1032
+ /**
1033
+ * A fresh X-Wing keypair: `publicKey` is {@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes,
1034
+ * `privateKey` the 32-byte seed. Persist only the seed and recompute the public
1035
+ * half with {@link hpkePublicKeyFromSeed}; wipe both buffers when done.
1036
+ */
1037
+ static async hpkeGenerateKeypairPq() {
1038
+ const both = await _MessagingClient.ephemeralWorkerCall({
1039
+ kind: "hpkeGenerateKeypairPq",
1040
+ id: 1
1041
+ });
1042
+ if (both.length !== HPKE_PQ_PUBLIC_KEY_BYTES + 32) {
1043
+ throw new Error(`hpkeGenerateKeypairPq: expected ${HPKE_PQ_PUBLIC_KEY_BYTES + 32} bytes`);
1044
+ }
1045
+ return {
1046
+ publicKey: both.slice(0, HPKE_PQ_PUBLIC_KEY_BYTES),
1047
+ privateKey: both.slice(HPKE_PQ_PUBLIC_KEY_BYTES)
1048
+ };
1049
+ }
1050
+ /**
1051
+ * The X-Wing public key for a stored 32-byte seed. Deterministic: the pairing
1052
+ * code carries SHA-256 of exactly these bytes, so what a device advertises
1053
+ * always matches what it will open with.
1054
+ */
1055
+ static async hpkePublicKeyFromSeed(seed) {
1056
+ if (seed.length !== 32) {
1057
+ throw new Error("hpkePublicKeyFromSeed: seed must be 32 bytes");
1058
+ }
1059
+ return _MessagingClient.ephemeralWorkerCall({
1060
+ kind: "hpkePublicKeyFromSeed",
1061
+ id: 1,
1062
+ seed
1063
+ });
1064
+ }
1065
+ /**
1066
+ * The id of an account's DeviceGroup (the private sync group of the
1067
+ * account's own devices), derived by the SDK core from the account's MLS
1068
+ * user id: `userId` is `client.userId()` (32 bytes), NOT the server's
1069
+ * account id. Deterministic: every device of the account derives the same
1070
+ * id, so a host recognises the DeviceGroup without copying the derivation.
1071
+ * Stateless (no client needed); bytes that are not an MLS user id derive an
1072
+ * id no device uses.
1073
+ */
1074
+ static async deviceGroupIdFor(userId) {
1075
+ return _MessagingClient.ephemeralWorkerCall({
1076
+ kind: "deviceGroupIdFor",
1077
+ id: 1,
1078
+ userId
1079
+ });
1080
+ }
1081
+ /** The 32-byte X25519 public key for a stored classical private key. */
1082
+ static async hpkePublicKeyFromPrivate(privateKey) {
1083
+ if (privateKey.length !== 32) {
1084
+ throw new Error("hpkePublicKeyFromPrivate: privateKey must be 32 bytes");
1085
+ }
1086
+ return _MessagingClient.ephemeralWorkerCall({
1087
+ kind: "hpkePublicKeyFromPrivate",
1088
+ id: 1,
1089
+ privateKey
1090
+ });
1091
+ }
1092
+ /**
1093
+ * Answer a device re-authentication challenge (`POST /v1/auth/device/challenge`) with
1094
+ * the device signing key, so a device whose session tokens are gone or dead gets fresh
1095
+ * ones for the SAME device without a code (`POST /v1/auth/device/verify`).
1096
+ *
1097
+ * The SDK builds the signed bytes itself (`"ping/device-reauth/v1" || challengeId ||
1098
+ * nonce || deviceId || accountId || audience`), so this cannot sign anything else with
1099
+ * the device key. `deviceSigningSecretKey` is the 32-byte secret the host passes as
1100
+ * `deviceSigningSecretKey` to {@link init}; `challengeId` (16 bytes) and `nonce`
1101
+ * (32 bytes) come from the challenge response. `accountId` (16 bytes) is the account
1102
+ * the host stored with its session; the server refuses a proof for any other account,
1103
+ * so send the same id with the proof. `audience` is the canonical origin of the API
1104
+ * THIS host is configured to reach (`new URL(apiBase).origin`, for example
1105
+ * `https://api-prod.ping.live`), never the value the server returned: that is what
1106
+ * makes a challenge relayed from another deployment useless there. The returned
1107
+ * `deviceId` is SHA-256 of the key's public half; send it with the signature.
1108
+ *
1109
+ * Rejects wrong widths and a non-canonical audience. Runs in an ephemeral worker.
1110
+ */
1111
+ static async signDeviceReauth(params) {
1112
+ const { deviceSigningSecretKey, challengeId, nonce, accountId, audience } = params;
1113
+ if (deviceSigningSecretKey.length !== 32) {
1114
+ throw new Error("signDeviceReauth: deviceSigningSecretKey must be 32 bytes");
1115
+ }
1116
+ if (challengeId.length !== 16) {
1117
+ throw new Error("signDeviceReauth: challengeId must be 16 bytes");
1118
+ }
1119
+ if (nonce.length !== 32) {
1120
+ throw new Error("signDeviceReauth: nonce must be 32 bytes");
1121
+ }
1122
+ if (accountId.length !== 16) {
1123
+ throw new Error("signDeviceReauth: accountId must be 16 bytes");
1124
+ }
1125
+ const both = await _MessagingClient.ephemeralWorkerCall({
1126
+ kind: "signDeviceReauth",
1127
+ id: 1,
1128
+ deviceSigningSecretKey,
1129
+ challengeId,
1130
+ nonce,
1131
+ accountId,
1132
+ audience
1133
+ });
1134
+ if (both.length !== 96) {
1135
+ throw new Error("signDeviceReauth: expected 96 bytes");
1136
+ }
1137
+ return { deviceId: both.slice(0, 32), signature: both.slice(32) };
1138
+ }
1139
+ /**
1140
+ * Link verification v2, on the APPROVING device: approve ONE new device on ONE
1141
+ * server link session (`POST /v1/auth/link/sessions` returned `approvalSessionId`)
1142
+ * with this device's signing key. The new device sends the result with its own
1143
+ * {@link signDeviceLinkPossession} proof to `POST /v1/auth/link/verify`.
1144
+ *
1145
+ * The SDK builds the signed bytes itself (`"ping/device-link-approve/v1" ||
1146
+ * approvalSessionId || accountId || approverDeviceId || newDeviceId ||
1147
+ * newDevicePubkey || audience`, see docs/DEVICE_LINK_V2_VECTORS.md) and derives
1148
+ * both device ids from the keys, so this cannot sign anything else with the device
1149
+ * key. `deviceSigningSecretKey` is the 32-byte seed the host holds for THIS device
1150
+ * (the one registered as its device signing key); `accountId` (16 bytes) is the
1151
+ * account stored with this device's session; `newDevicePubkey` (32 bytes) is the
1152
+ * new device's key from its handshake; `audience` is the canonical origin of the API
1153
+ * THIS host is configured to reach (`new URL(apiBase).origin`), as for
1154
+ * {@link signDeviceReauth}.
1155
+ *
1156
+ * Rejects wrong widths, a non-canonical audience, a new key that is not a canonical
1157
+ * Ed25519 point outside the small-order subgroup, and this device's own key. Runs in
1158
+ * an ephemeral worker.
1159
+ */
1160
+ static async signDeviceLinkApproval(params) {
1161
+ const { deviceSigningSecretKey, approvalSessionId, accountId, newDevicePubkey, audience } = params;
1162
+ if (deviceSigningSecretKey.length !== 32) {
1163
+ throw new Error("signDeviceLinkApproval: deviceSigningSecretKey must be 32 bytes");
1164
+ }
1165
+ if (approvalSessionId.length !== 16) {
1166
+ throw new Error("signDeviceLinkApproval: approvalSessionId must be 16 bytes");
1167
+ }
1168
+ if (accountId.length !== 16) {
1169
+ throw new Error("signDeviceLinkApproval: accountId must be 16 bytes");
1170
+ }
1171
+ if (newDevicePubkey.length !== 32) {
1172
+ throw new Error("signDeviceLinkApproval: newDevicePubkey must be 32 bytes");
1173
+ }
1174
+ const all = await _MessagingClient.ephemeralWorkerCall({
1175
+ kind: "signDeviceLinkApproval",
1176
+ id: 1,
1177
+ deviceSigningSecretKey,
1178
+ approvalSessionId,
1179
+ accountId,
1180
+ newDevicePubkey,
1181
+ audience
1182
+ });
1183
+ if (all.length !== 128) {
1184
+ throw new Error("signDeviceLinkApproval: expected 128 bytes");
1185
+ }
1186
+ return {
1187
+ approverDeviceId: all.slice(0, 32),
1188
+ newDeviceId: all.slice(32, 64),
1189
+ signature: all.slice(64)
1190
+ };
1191
+ }
1192
+ /**
1193
+ * Link verification v2, on the NEW device: prove that this device holds the key the
1194
+ * link session names (`"ping/device-link-possess/v1" || approvalSessionId ||
1195
+ * accountId || deviceId || audience`). `deviceSigningSecretKey` is this device's own
1196
+ * 32-byte seed (the key its handshake advertised); `approvalSessionId` and
1197
+ * `accountId` come from the approving device's sealed envelope; `audience` as for
1198
+ * {@link signDeviceReauth}. Check `approval.newDeviceId` equals the returned
1199
+ * `deviceId` before verifying: a substituted handshake is refused locally.
1200
+ *
1201
+ * Rejects wrong widths and a non-canonical audience. Runs in an ephemeral worker.
1202
+ */
1203
+ static async signDeviceLinkPossession(params) {
1204
+ const { deviceSigningSecretKey, approvalSessionId, accountId, audience } = params;
1205
+ if (deviceSigningSecretKey.length !== 32) {
1206
+ throw new Error("signDeviceLinkPossession: deviceSigningSecretKey must be 32 bytes");
1207
+ }
1208
+ if (approvalSessionId.length !== 16) {
1209
+ throw new Error("signDeviceLinkPossession: approvalSessionId must be 16 bytes");
1210
+ }
1211
+ if (accountId.length !== 16) {
1212
+ throw new Error("signDeviceLinkPossession: accountId must be 16 bytes");
1213
+ }
1214
+ const both = await _MessagingClient.ephemeralWorkerCall({
1215
+ kind: "signDeviceLinkPossession",
1216
+ id: 1,
1217
+ deviceSigningSecretKey,
1218
+ approvalSessionId,
1219
+ accountId,
1220
+ audience
1221
+ });
1222
+ if (both.length !== 96) {
1223
+ throw new Error("signDeviceLinkPossession: expected 96 bytes");
1224
+ }
1225
+ return { deviceId: both.slice(0, 32), signature: both.slice(32) };
1226
+ }
1227
+ // Spawn-call-terminate helper for stateless WASM functions exposed at module scope (no
1228
+ // PingClient required). Each call gets a fresh worker; the cost is acceptable because
1229
+ // these are one-shot, off-the-hot-path operations (identity gen, linking ticket seal/open).
1230
+ //
1231
+ // The returned promise ALWAYS settles and the worker is ALWAYS terminated: on its
1232
+ // result, on a worker `error` (the script failed to load or import, or threw at top
1233
+ // level), on a `messageerror` (a reply that could not be deserialised), and when the
1234
+ // worker cannot be created or the request cannot be posted. Only `onmessage` used to be
1235
+ // wired, so a worker that failed to load left `generateIdentity()` pending forever and
1236
+ // the worker alive.
1237
+ static ephemeralWorkerCall(req) {
1238
+ let w;
1239
+ try {
1240
+ w = new Worker(new URL("./worker.js", import_meta.url), { type: "module" });
1241
+ } catch {
1242
+ return Promise.reject(new EphemeralWorkerError("spawn"));
1243
+ }
1244
+ return new Promise((resolve, reject) => {
1245
+ let settled = false;
1246
+ const settle = (finish) => {
1247
+ if (settled) return;
1248
+ settled = true;
1249
+ w.onmessage = null;
1250
+ w.onerror = null;
1251
+ w.onmessageerror = null;
1252
+ w.terminate();
1253
+ finish();
1254
+ };
1255
+ w.onmessage = (ev) => {
1256
+ const msg = ev.data;
1257
+ if (msg.kind === "result" && msg.id === req.id) {
1258
+ settle(() => msg.ok ? resolve(msg.value) : reject(new Error(msg.error)));
1259
+ }
1260
+ };
1261
+ w.onerror = () => settle(() => reject(new EphemeralWorkerError("error")));
1262
+ w.onmessageerror = () => settle(() => reject(new EphemeralWorkerError("messageerror")));
1263
+ try {
1264
+ w.postMessage(req);
1265
+ } catch {
1266
+ settle(() => reject(new EphemeralWorkerError("post")));
1267
+ }
1268
+ });
1269
+ }
1270
+ static async init(cfg) {
1271
+ const worker = new Worker(new URL("./worker.js", import_meta.url), { type: "module" });
1272
+ const client = new _MessagingClient(cfg, worker);
1273
+ const transportFeatures = {
1274
+ fetchLogSince: typeof cfg.transport.fetchLogSince === "function",
1275
+ fetchLogHeads: typeof cfg.transport.fetchLogHeads === "function"
1276
+ };
1277
+ const storageFeatures = storageFeaturesOf(client.storage);
1278
+ await client.call({
1279
+ kind: "init",
1280
+ id: client.nextId++,
1281
+ identityExport: cfg.identityExport,
1282
+ deviceLabel: cfg.deviceLabel,
1283
+ nowMs: client.now(),
1284
+ ...cfg.deviceSigningSecretKey ? { deviceSigningSecretKey: cfg.deviceSigningSecretKey } : {},
1285
+ ...cfg.expectedOwners ? { expectedOwners: cfg.expectedOwners } : {},
1286
+ transportFeatures,
1287
+ storageFeatures
1288
+ });
1289
+ client.ownDeviceId = await client.deviceId();
1290
+ client.subscription = cfg.transport.subscribe(
1291
+ (frame) => client.dispatchIncoming(frame)
1292
+ );
1293
+ return client;
1294
+ }
1295
+ /**
1296
+ * Internal: route an inbound envelope to the right handler, IN ARRIVAL ORDER
1297
+ * PER CONVERSATION.
1298
+ *
1299
+ * ## Why the ordering is load-bearing
1300
+ *
1301
+ * A group invitation arrives as a Welcome immediately followed by the
1302
+ * inviter's hydration Application messages (group title, roster, avatar id).
1303
+ * `joinConversation` is asynchronous — it is several round trips to the WASM
1304
+ * worker — so a naive `void dispatchIncoming(...)` per frame let the
1305
+ * Applications reach `processEnvelope` while the join was still in flight.
1306
+ * The conversation did not exist yet, so every one of them was dropped with
1307
+ * "envelope drop: unknown conversation".
1308
+ *
1309
+ * That loss is PERMANENT and silent: MLS ratchets forward, the transport has
1310
+ * already marked the frames seen and advanced its cursor, and the server will
1311
+ * not resend them. The visible symptom was an invitation landing as an
1312
+ * unnamed "New chat" with no avatar and no roster, and — for the same reason —
1313
+ * a rename, avatar change, member add/remove or role change being lost
1314
+ * whenever it happened to land while a join or another commit for that group
1315
+ * was still being applied.
1316
+ *
1317
+ * Chaining PER CONVERSATION (not globally) is deliberate: MLS state is
1318
+ * per-group, so that is the granularity correctness actually requires, and a
1319
+ * busy conversation must not be able to head-of-line block every other one.
1320
+ * The chain is built synchronously on entry, so chain order is exactly frame
1321
+ * arrival order.
1322
+ *
1323
+ * ## Sequenced frames
1324
+ *
1325
+ * A frame that carries its server position (`{ envelope, serverSeq }`,
1326
+ * `serverSeq > 0`) does not need the chain: the core applies it at its
1327
+ * position, holds it ahead of a hole and drops it at or below what was
1328
+ * applied, whatever order it arrived in. What it needs is BATCHING: one
1329
+ * MLS checkpoint and one host transaction per burst instead of one per
1330
+ * frame. So the first frame for a conversation goes to the worker at once
1331
+ * as a batch of one, and frames that arrive while that batch is in flight
1332
+ * accumulate and go out as ONE `processSequencedBatch` when it returns; no
1333
+ * timer ever delays a frame. Own-device echoes are NOT dropped on this
1334
+ * path: the core advances the position past them without touching MLS,
1335
+ * and dropping one would leave a hole the next frame reports as a gap. A
1336
+ * sequenced frame at `serverSeq` 0 is a legacy frame in a wrapper and
1337
+ * takes the legacy path unchanged.
1338
+ */
1339
+ dispatchIncoming(frame) {
1340
+ if (isSequencedFrame(frame)) {
1341
+ if (frame.serverSeq > 0) {
1342
+ return this.coalescer.push(hexOf(frame.envelope.conversation_id), frame);
1343
+ }
1344
+ return this.dispatchLegacy(frame.envelope);
1345
+ }
1346
+ return this.dispatchLegacy(frame);
1347
+ }
1348
+ /** The legacy per-envelope path: own-device drop, then the per-conversation chain. */
1349
+ dispatchLegacy(envelope) {
1350
+ if (this.ownDeviceId && sameBytesU8(envelope.sender_device, this.ownDeviceId)) {
1351
+ return Promise.resolve();
1352
+ }
1353
+ const key = hexOf(envelope.conversation_id);
1354
+ const prior = this.dispatchChains.get(key) ?? Promise.resolve();
1355
+ const next = prior.catch(() => void 0).then(() => this.dispatchIncomingOrdered(envelope));
1356
+ const tail = next.catch(() => void 0).finally(() => {
1357
+ if (this.dispatchChains.get(key) === tail) this.dispatchChains.delete(key);
1358
+ });
1359
+ this.dispatchChains.set(key, tail);
1360
+ return next;
1361
+ }
1362
+ /** The actual routing, run inside the per-conversation chain. */
1363
+ async dispatchIncomingOrdered(envelope) {
1364
+ if (envelope.kind === "Welcome") {
1365
+ try {
1366
+ const known = await this.listConversations();
1367
+ const already = known.some((m) => sameBytesU8(m.id, envelope.conversation_id));
1368
+ if (already) {
1369
+ const stranded = await this.strandedConversations();
1370
+ const isStranded = stranded.some((id) => sameBytesU8(id, envelope.conversation_id));
1371
+ if (!isStranded) return;
1372
+ }
1373
+ await this.joinConversation(envelope);
1374
+ } catch (e) {
1375
+ if (typeof console !== "undefined") console.debug("[ping-sdk] welcome ignored:", e);
1376
+ }
1377
+ return;
1378
+ }
1379
+ try {
1380
+ await this.processEnvelope(envelope);
1381
+ } catch (e) {
1382
+ if (typeof console !== "undefined") console.debug("[ping-sdk] envelope deferred:", e);
1383
+ }
1384
+ }
1385
+ /**
1386
+ * One coalesced batch of live frames. Errors are logged at debug and
1387
+ * swallowed, exactly as the legacy path treats a failed envelope: the
1388
+ * dispatch promise a transport may await resolves either way, and the
1389
+ * core retains anything it could not apply yet.
1390
+ */
1391
+ async applyLiveBatch(items) {
1392
+ try {
1393
+ await this.processSequencedBatch(items);
1394
+ } catch (e) {
1395
+ if (typeof console !== "undefined") console.debug("[ping-sdk] sequenced batch failed:", errorKind(e));
1396
+ }
1397
+ }
1398
+ /** Start a fill for every gap a batch reported; each is single-flight. */
1399
+ scheduleGapFills(result) {
1400
+ for (const gap of result.gaps) {
1401
+ void this.fillGap(gap.conversationId).catch((e) => {
1402
+ if (typeof console !== "undefined") console.debug("[ping-sdk] gap fill failed:", errorKind(e));
1403
+ });
1404
+ }
1405
+ }
1406
+ /** One page, delivered as a page, on the requested lane. */
1407
+ async stepConversation(id, stepped) {
1408
+ const raw = await this.call({
1409
+ kind: "syncConversationStep",
1410
+ id: this.nextId++,
1411
+ conv: id,
1412
+ nowMs: this.now(),
1413
+ ...stepped ? { stepped: true } : {}
1414
+ });
1415
+ const result = syncStepResultFromWire(raw);
1416
+ this.fanout.deliverBatch(result.messages, { source: "page" });
1417
+ return result;
1418
+ }
1419
+ // ------------------------ Public API ------------------------
1420
+ async userId() {
1421
+ return await this.call({ kind: "userId", id: this.nextId++ });
1422
+ }
1423
+ /**
1424
+ * Export the account identity seed (CBOR-wrapped Ed25519, **SECRET**).
1425
+ * Transfer to a newly-linked device over the sealed linking channel so all of
1426
+ * an account's devices share one `userId` — the basis for cross-device
1427
+ * self-attribution (`IncomingMessage.sender_user_id === userId()`). Never log
1428
+ * or persist in cleartext.
1429
+ */
1430
+ async exportIdentity() {
1431
+ return await this.call({ kind: "exportIdentity", id: this.nextId++ });
1432
+ }
1433
+ /**
1434
+ * RETIRED (2026-11-03): always rejects (`Invalid`) and changes nothing.
1435
+ *
1436
+ * It moved every conversation's own leaf to a new account identity with a
1437
+ * credential-changing Commit, the way out of `409 mls_identity_conflict`.
1438
+ * Every Ping client now refuses a Commit that changes a member's leaf
1439
+ * credential (a hostile linked device could otherwise move its leaf to a
1440
+ * peer's identity and escape the account's removal), so a rotation would
1441
+ * strand every conversation it touched. The way out of an identity conflict
1442
+ * is to link this device again, or sign out and in. Kept so no caller
1443
+ * breaks. See `docs/MULTIDEVICE.md` "Identity rotation".
1444
+ *
1445
+ * @deprecated Retired: always rejects. Link this device again instead.
1446
+ */
1447
+ async rotateIdentity(newIdentityExport, nowMs = this.now()) {
1448
+ return await this.call({
1449
+ kind: "rotateIdentity",
1450
+ id: this.nextId++,
1451
+ newIdentityExport,
1452
+ nowMs
1453
+ });
1454
+ }
1455
+ /**
1456
+ * RETIRED with [[rotateIdentity]]: always rejects (`Invalid`).
1457
+ *
1458
+ * @deprecated Retired: always rejects.
1459
+ */
1460
+ async rotateIdentityRetry(conv, nowMs = this.now()) {
1461
+ await this.call({ kind: "rotateIdentityRetry", id: this.nextId++, conv, nowMs });
1462
+ }
1463
+ async deviceId() {
1464
+ return await this.call({ kind: "deviceId", id: this.nextId++ });
1465
+ }
1466
+ /**
1467
+ * Release every file lock the MLS store holds so the host process can be
1468
+ * suspended. Resolves `true` when the locks are genuinely gone.
1469
+ *
1470
+ * Present on web for API parity, and a no-op returning `true` here: this build
1471
+ * persists through the host's `Storage` (IndexedDB by default), which holds no
1472
+ * file locks and has nothing to release. It is load-bearing on the native
1473
+ * bindings, where iOS kills a backgrounded process that still holds a lock on
1474
+ * a file in an App Group container. Exposed on every platform so a host
1475
+ * sharing code across web and native does not have to branch on it.
1476
+ *
1477
+ * Pair with `resumeStorage()`.
1478
+ */
1479
+ async suspendStorage() {
1480
+ return await this.call({ kind: "suspendStorage", id: this.nextId++ });
1481
+ }
1482
+ /** Undo `suspendStorage()`. Idempotent. */
1483
+ async resumeStorage() {
1484
+ await this.call({ kind: "resumeStorage", id: this.nextId++ });
1485
+ }
1486
+ async freshKeyPackage() {
1487
+ return await this.call({ kind: "freshKeyPackage", id: this.nextId++ });
1488
+ }
1489
+ /**
1490
+ * Generate a fresh LAST-RESORT KeyPackage (RFC 9420 §10). Publish exactly one
1491
+ * per device so the server can serve it repeatedly as a fallback when the
1492
+ * single-use pool empties — invites then never hard-fail purely because the
1493
+ * peer ran out of KeyPackages.
1494
+ */
1495
+ async freshLastResortKeyPackage() {
1496
+ return await this.call({ kind: "freshLastResortKeyPackage", id: this.nextId++ });
1497
+ }
1498
+ async createConversation(opts = {}) {
1499
+ const idBytes = await this.call({
1500
+ kind: "createConversation",
1501
+ id: this.nextId++,
1502
+ name: opts.name ?? null,
1503
+ nowMs: this.now()
1504
+ });
1505
+ return this.conversationProxy(idBytes);
1506
+ }
1507
+ /**
1508
+ * Create an ephemeral per-call MLS group. Identical to {@link createConversation}
1509
+ * except the id carries the `0xFF 0xCC` call-group sentinel, so every device
1510
+ * recognises it structurally (by id alone — no name, no registry) and keeps it
1511
+ * out of the chat list. Hosts MUST use this for call groups.
1512
+ */
1513
+ async createCallConversation(opts = {}) {
1514
+ const idBytes = await this.call({
1515
+ kind: "createCallConversation",
1516
+ id: this.nextId++,
1517
+ name: opts.name ?? null,
1518
+ nowMs: this.now()
1519
+ });
1520
+ return this.conversationProxy(idBytes);
1521
+ }
1522
+ async joinConversation(welcome) {
1523
+ const idBytes = await this.call({
1524
+ kind: "joinConversation",
1525
+ id: this.nextId++,
1526
+ welcome,
1527
+ nowMs: this.now()
1528
+ });
1529
+ return this.conversationProxy(idBytes);
1530
+ }
1531
+ /**
1532
+ * Get a `Conversation` proxy for an already-known conversation. Use this when you have a
1533
+ * conversation id (e.g., from `listConversations()`) and want to send/addMembers without
1534
+ * re-creating it. Throws if the id isn't known to the worker — call `listConversations()`
1535
+ * first to verify membership.
1536
+ */
1537
+ getConversation(id) {
1538
+ return this.conversationProxy(id);
1539
+ }
1540
+ async listConversations() {
1541
+ const metas = await this.call({ kind: "listConversations", id: this.nextId++ });
1542
+ this.metaCache.clear();
1543
+ for (const m of metas) this.metaCache.set(hex(m.id), m);
1544
+ return metas;
1545
+ }
1546
+ /**
1547
+ * ONE conversation's metadata as the group holds it now: the same record as
1548
+ * its element of {@link listConversations}, without listing the others.
1549
+ * Resolves `null` when this client does not hold the conversation (unknown,
1550
+ * dropped, removed, or left). A pure read of local state: nothing is
1551
+ * fetched. Rejects for an id that is not 16 bytes.
1552
+ *
1553
+ * It also brings the conversation handle's `name`, `epoch` and `meta()` to
1554
+ * the answer, though they do not need it to be fresh: the client replaces
1555
+ * its copy of a conversation's metadata
1556
+ * - before any {@link onConversationUpdated} listener is told the
1557
+ * conversation changed (a Commit from another member, a join, a page of
1558
+ * a catch-up), and
1559
+ * - before this device's own call that changed it resolves (a rename, a
1560
+ * roles or membership change, a creation, a leave).
1561
+ * Use this read for a conversation nothing has reported yet in this
1562
+ * session, or to learn that a conversation is no longer held.
1563
+ */
1564
+ async readConversationMeta(id) {
1565
+ const meta = await this.call({
1566
+ kind: "conversationMeta",
1567
+ id: this.nextId++,
1568
+ conv: id
1569
+ });
1570
+ this.storeMeta(id, meta);
1571
+ return meta ?? null;
1572
+ }
1573
+ /**
1574
+ * Conversations detected as STRANDED during catch-up — a Commit was missed
1575
+ * and the group can no longer advance from local state, so new messages stop
1576
+ * arriving. Poll after a sync and recover each (re-Welcome / state-snapshot
1577
+ * import). Returns 16-byte conversation ids; the set self-clears as a
1578
+ * conversation makes progress or is re-joined.
1579
+ */
1580
+ async strandedConversations() {
1581
+ return await this.call({ kind: "strandedConversations", id: this.nextId++ });
1582
+ }
1583
+ /**
1584
+ * Conversations this device asked to leave and is still a member of:
1585
+ * the leave is OWED. The SDK holds their state and proposes the leave
1586
+ * again by itself; the host only keeps delivering their rows (live
1587
+ * frames and catch-up pages). An id leaves the list when the leave has
1588
+ * completed: this device processed its own removal and the state is
1589
+ * deleted. Sorted 16-byte conversation ids.
1590
+ */
1591
+ async conversationsLeaving() {
1592
+ return await this.call({ kind: "conversationsLeaving", id: this.nextId++ });
1593
+ }
1594
+ /**
1595
+ * The leaving conversations whose leave has STALLED: 8 sends of it
1596
+ * FAILED and this device is still a member, or this device can no longer
1597
+ * follow the group. Nothing more is proposed for them. The host may call
1598
+ * {@link leaveConversation} again (the count starts over) or give up with
1599
+ * {@link dropConversationLocal}, which leaves this device's leaf in the group
1600
+ * until somebody removes it. Sorted 16-byte conversation ids.
1601
+ */
1602
+ async conversationsLeaveStalled() {
1603
+ return await this.call({ kind: "conversationsLeaveStalled", id: this.nextId++ });
1604
+ }
1605
+ /**
1606
+ * Conversations this device was just torn down from by a SELF-RE-ADD Commit
1607
+ * — a peer's `reAdmitDevice` of this device — whose Welcome for the new
1608
+ * leaf is expected within seconds. Treat these as "re-admission in flight",
1609
+ * not stranded or evicted: no repair advertise, no delivery-key rotation,
1610
+ * no KeyPackage-pool replace, until the join lands or the entry ages out
1611
+ * (ten minutes). Returns 16-byte conversation ids.
1612
+ */
1613
+ async readmitPendingConversations(nowMs = Date.now()) {
1614
+ return await this.call({
1615
+ kind: "readmitPendingConversations",
1616
+ id: this.nextId++,
1617
+ nowMs
1618
+ });
1619
+ }
1620
+ /**
1621
+ * How many inbound envelopes are currently RETAINED awaiting replay, across
1622
+ * all conversations.
1623
+ *
1624
+ * An envelope that cannot be applied yet — its Welcome has not been processed,
1625
+ * or a Commit that advances the epoch is missing — is buffered and replayed on
1626
+ * join / epoch advance / catch-up sync rather than dropped (see
1627
+ * docs/INVITE_HARDENING.md §S6).
1628
+ *
1629
+ * A non-zero count means "delivered but not yet applicable", which is
1630
+ * materially different from "not delivered" and is the distinction a host
1631
+ * needs to explain a chat that looks incomplete. Expected to be 0 at rest; a
1632
+ * value that stays high points at a conversation whose handshake never
1633
+ * arrived.
1634
+ */
1635
+ async undeliverableCount() {
1636
+ return await this.call({ kind: "undeliverableCount", id: this.nextId++ });
1637
+ }
1638
+ /**
1639
+ * Leave a conversation: broadcasts a self-Remove PROPOSAL (MLS forbids
1640
+ * committing your own removal: a remaining member commits it via
1641
+ * `commitPendingProposals`) and answers at once. From then on the conversation is
1642
+ * LEFT for the host: it is no longer listed, every call that names it
1643
+ * answers `UnknownConversation`, and nothing of it is surfaced again.
1644
+ *
1645
+ * Do NOT delete it locally afterwards ({@link dropConversationLocal}). The SDK keeps the
1646
+ * group's state, follows its Commits, and proposes the leave again after
1647
+ * each Commit that did not carry it (a Commit built before the proposal
1648
+ * arrived voids it), until this device is removed; then it deletes the
1649
+ * state itself. Keep delivering the conversation's rows to the client
1650
+ * while {@link conversationsLeaving} lists it. The bound is 8 FAILED sends;
1651
+ * after that {@link conversationsLeaveStalled} lists the conversation and calling
1652
+ * this again starts over.
1653
+ *
1654
+ * The group's OWNER hands over first: this call commits the successor (the
1655
+ * one every device computes when the owner's last leaf goes) and only then
1656
+ * proposes the leave. If that Commit cannot be made the call fails with the
1657
+ * Commit's error and nothing is marked: call it again. Nothing is handed
1658
+ * over when the owner's account keeps another device in the group or when
1659
+ * no other member could take over.
1660
+ */
1661
+ async leaveConversation(id, nowMs = this.now()) {
1662
+ await this.call({ kind: "leaveConversation", id: this.nextId++, conv: id, nowMs });
1663
+ }
1664
+ /**
1665
+ * Drop a conversation's local state with NO network side effect. Unlike
1666
+ * {@link leaveConversation} (which broadcasts a self-Remove proposal), this
1667
+ * sends nothing — use it for a group the SERVER does not back: an invite that
1668
+ * minted the MLS group locally but never completed server-side, so the backend
1669
+ * 404s `fetchSince` / 403s the member roster for it. Deletes the OpenMLS group
1670
+ * state + the on-disk snapshot rows so the dead group stops rehydrating on the
1671
+ * next restart (and re-materialising as a ghost "New chat"). Idempotent — safe
1672
+ * on an unknown/already-dropped id.
1673
+ */
1674
+ async dropConversationLocal(id) {
1675
+ await this.call({ kind: "dropConversationLocal", id: this.nextId++, conv: id });
1676
+ }
1677
+ /**
1678
+ * Conversations with buffered pending proposals (e.g. a peer's leave). Poll
1679
+ * after a sync; if you're the designated committer, call
1680
+ * `commitPendingProposals` to evict the leaver.
1681
+ */
1682
+ async conversationsWithPendingProposals() {
1683
+ return await this.call({
1684
+ kind: "conversationsWithPendingProposals",
1685
+ id: this.nextId++
1686
+ });
1687
+ }
1688
+ /**
1689
+ * Commit buffered pending proposals for a conversation (evicts a peer who
1690
+ * left). No-op if nothing is pending; on an epoch-advanced rejection re-sync
1691
+ * (another member already committed). Call it on receipt (a batch or page
1692
+ * result's `proposalsPending`), elected with
1693
+ * {@link pendingProposalsCommitRank}. A `send` commits pending proposals
1694
+ * itself first, so a proposal never blocks a message.
1695
+ */
1696
+ async commitPendingProposals(id, nowMs = this.now()) {
1697
+ await this.call({ kind: "commitPendingProposals", id: this.nextId++, conv: id, nowMs });
1698
+ }
1699
+ /**
1700
+ * This device's rank in the deterministic election of who commits a
1701
+ * conversation's pending proposals: members by leaf index, excluding any
1702
+ * leaf a pending proposal removes; identical on every member. `0` means
1703
+ * commit now; rank `n` means wait `n` intervals (a few seconds each), then
1704
+ * commit if the proposals are still pending. `null` when nothing is pending
1705
+ * or this device is not eligible.
1706
+ */
1707
+ async pendingProposalsCommitRank(id) {
1708
+ const rank = await this.call({
1709
+ kind: "pendingProposalsCommitRank",
1710
+ id: this.nextId++,
1711
+ conv: id
1712
+ });
1713
+ return rank ?? null;
1714
+ }
1715
+ /**
1716
+ * The Commits this device holds in doubt: a Commit whose send got no
1717
+ * definite answer (no response, a 5xx) is neither merged nor discarded; the
1718
+ * SDK settles it on a capped exponential backoff, and every operation in
1719
+ * that conversation fails with `commit in doubt` until it settles. Retry
1720
+ * such an operation at `nextAttemptAtMs`.
1721
+ */
1722
+ async commitsInDoubt() {
1723
+ const raw = await this.call({ kind: "commitsInDoubt", id: this.nextId++ });
1724
+ return raw.map(commitInDoubtFromWire);
1725
+ }
1726
+ /**
1727
+ * Member roster for a conversation, recovered locally from the MLS
1728
+ * group's leaf credentials (no network, no out-of-band message). Returns
1729
+ * one entry per device leaf — a multi-device user appears multiple times,
1730
+ * so dedup by `user_id` for a per-user roster. Empty for an unknown id.
1731
+ */
1732
+ async members(conv) {
1733
+ return await this.call({ kind: "members", id: this.nextId++, conv });
1734
+ }
1735
+ /**
1736
+ * A conversation's credential policy (account-signed device credentials,
1737
+ * 2026-11-04): whether every leaf must carry a credential the account key signed
1738
+ * (`credentialsRequired`; a KeyPackage without one gets the add verdict
1739
+ * `credentialMissing`), the roles once the policy records them (round 2), and
1740
+ * `incapableMembers`, the accounts with a member on an app too old for this
1741
+ * group, which is what blocks the upgrade. Rejects for a conversation this client
1742
+ * does not hold. No host action is needed for the credentials themselves: the SDK
1743
+ * signs and verifies them internally.
1744
+ */
1745
+ async conversationPolicy(conv) {
1746
+ return await this.call({ kind: "conversationPolicy", id: this.nextId++, conv });
1747
+ }
1748
+ /**
1749
+ * Whether a Commit of THIS device that re-admits or adds the device `deviceId` of
1750
+ * the account `identity` would pass the membership rules of the conversation in
1751
+ * its state now, without building or sending anything (2026-11-18). True when
1752
+ * this device may add a leaf of that account (the owner, an admin, or a device of
1753
+ * that same account; a device of the OWNER only when this device is the owner's)
1754
+ * and, if `deviceId` holds a leaf there, may also remove that leaf. Always true in
1755
+ * a conversation without roles. Ask it BEFORE leasing a re-admission request or
1756
+ * claiming a KeyPackage: a device that is not privileged never claims another
1757
+ * account's KeyPackage. Advisory: the Commit is judged again when it is built and
1758
+ * by every receiver. Rejects for a conversation this client does not hold.
1759
+ */
1760
+ async mayReadmit(conv, identity, deviceId) {
1761
+ return await this.call({ kind: "mayReadmit", id: this.nextId++, conv, identity, deviceId });
1762
+ }
1763
+ /**
1764
+ * The identity (the account's user id) a KeyPackage's credential CLAIMS, read
1765
+ * without changing anything (2026-11-18, rule R13). `null` for a credential that
1766
+ * is not the project's. Rejects for bytes that are not a valid KeyPackage: the
1767
+ * checks OpenMLS runs on a KeyPackage an add carries run first (both signatures
1768
+ * under the leaf's own key, the version, the init key, the extensions against the
1769
+ * capabilities, the lifetime: an expired KeyPackage rejects).
1770
+ *
1771
+ * Before adding ANOTHER account's device, read it and compare it with the account
1772
+ * you meant to add, byte for byte; a different answer, or `null`, is enough to
1773
+ * refuse the KeyPackage the server handed out, before any Commit.
1774
+ *
1775
+ * The read runs the SAME credential verdict the add runs (the device
1776
+ * credential, then the leaf-ready check) and rejects for a claim the add
1777
+ * would refuse, so an identity answered is one the account's key vouched
1778
+ * for (rulings part 13, ruling 1; until then the answer was a bare claim).
1779
+ */
1780
+ async keyPackageIdentity(keyPackage) {
1781
+ const identity = await this.call({
1782
+ kind: "keyPackageIdentity",
1783
+ id: this.nextId++,
1784
+ keyPackage
1785
+ });
1786
+ return identity ?? null;
1787
+ }
1788
+ /**
1789
+ * Replace the owners this client expects first roles writes to name
1790
+ * (2026-11-04, round 2; see `ClientConfig.expectedOwners`).
1791
+ */
1792
+ async setExpectedOwners(entries) {
1793
+ await this.call({ kind: "setExpectedOwners", id: this.nextId++, entries });
1794
+ }
1795
+ /**
1796
+ * Record a group's roles in its policy (2026-11-04, round 2): `owner` and
1797
+ * `admins` as MLS user ids (map account ids through the roster). One
1798
+ * GroupContextExtensions Commit, no Welcome, send-then-merge. Rejects with
1799
+ * "not permitted ..." before anything is sent when this device's role does not
1800
+ * allow the change, when a member's app is too old for roles
1801
+ * (`conversationPolicy().incapableMembers` names it), or in the DeviceGroup.
1802
+ * The same call as `getConversation(id).setConversationRoles`.
1803
+ */
1804
+ async setConversationRoles(conv, owner, admins) {
1805
+ await this.call({
1806
+ kind: "setConversationRoles",
1807
+ id: this.nextId++,
1808
+ conv,
1809
+ owner,
1810
+ admins,
1811
+ nowMs: this.now()
1812
+ });
1813
+ }
1814
+ /**
1815
+ * Whole-account catch-up. The worker runs it one conversation at a time and
1816
+ * lets every other request (a `send` the user is waiting on, a live frame)
1817
+ * run between conversations, so a pass over many conversations never parks
1818
+ * an interactive call behind all of them. Resolves when every conversation
1819
+ * held at the start of the pass (plus any joined while it ran) has been
1820
+ * paged, with the decrypted application messages in apply order.
1821
+ */
1822
+ async syncConversations() {
1823
+ return await this.call({
1824
+ kind: "syncConversations",
1825
+ id: this.nextId++,
1826
+ nowMs: this.now()
1827
+ });
1828
+ }
1829
+ /**
1830
+ * Catch-up for ONE conversation: the unit `syncConversations` is built from.
1831
+ * Use it to bring the conversation the user is looking at up to date ahead
1832
+ * of the rest (a message must be encrypted at the epoch the group is really
1833
+ * at, so a host calls this before the first send after a reconnect), or to
1834
+ * step a pass in an order of its own. Rejects with the SDK's
1835
+ * `unknown conversation` error for an id this client does not hold.
1836
+ */
1837
+ async syncConversation(id) {
1838
+ return await this.call({
1839
+ kind: "syncConversation",
1840
+ id: this.nextId++,
1841
+ conv: id,
1842
+ nowMs: this.now()
1843
+ });
1844
+ }
1845
+ async processEnvelope(envelope) {
1846
+ return await this.call({
1847
+ kind: "processEnvelope",
1848
+ id: this.nextId++,
1849
+ envelope,
1850
+ nowMs: this.now()
1851
+ });
1852
+ }
1853
+ // ------------------------ Sequenced log sync ------------------------
1854
+ // See docs/SYNC_PROTOCOL.md "Sequenced log sync". The subscribe path feeds
1855
+ // these itself for a transport that hands over sequenced frames; they are
1856
+ // public for hosts that drive their own socket.
1857
+ /**
1858
+ * Apply a batch of live frames, each with its server log position, and
1859
+ * checkpoint once per touched conversation. Per conversation: the next
1860
+ * position applies, one ahead of a hole is held and reported in `gaps`,
1861
+ * one at or below the applied position is a duplicate. Welcomes are routed
1862
+ * to a join inside the SDK (a join anchors the new conversation at the
1863
+ * Welcome's position); own-device echoes advance the position without
1864
+ * touching MLS, so pass them through. Frames at `serverSeq` 0 take the
1865
+ * legacy per-sender path.
1866
+ *
1867
+ * The decrypted messages are returned AND delivered: to `onMessageBatch`
1868
+ * handlers as one call (source `live`) when any is registered, else per
1869
+ * message to `onMessage` handlers. `onConversationUpdated` fires once per
1870
+ * entry of `updated`. A reported gap starts {@link fillGap} for that
1871
+ * conversation.
1872
+ */
1873
+ async processSequencedBatch(items) {
1874
+ const raw = await this.call({
1875
+ kind: "processSequencedBatch",
1876
+ id: this.nextId++,
1877
+ items: items.map(sequencedToWire),
1878
+ nowMs: this.now()
1879
+ });
1880
+ const result = applyBatchResultFromWire(raw);
1881
+ this.fanout.deliverBatch(result.messages, { source: "live" });
1882
+ this.scheduleGapFills(result);
1883
+ return result;
1884
+ }
1885
+ /**
1886
+ * ONE page of a conversation's server log through `Transport.fetchLogSince`,
1887
+ * applied in order and checkpointed once, then whatever held frames the
1888
+ * page made contiguous. `hasMore` means step again. Same delivery as
1889
+ * {@link processSequencedBatch}, with source `page`. An ordinary request:
1890
+ * it runs ahead of any background pass, so a host can bring the open chat
1891
+ * current first. Rejects with the SDK's `unknown conversation` error for an
1892
+ * id this client does not hold; the durable cursor is unchanged on a
1893
+ * transport failure.
1894
+ */
1895
+ async syncConversationStep(id) {
1896
+ return this.stepConversation(id, false);
1897
+ }
1898
+ /**
1899
+ * Fill a conversation's gap: run {@link syncConversationStep} until
1900
+ * `hasMore` is false, single-flight per conversation, on the worker's
1901
+ * stepped lane so a send posted meanwhile goes between pages. The SDK
1902
+ * starts this itself for every gap a batch reports; hosts call it for the
1903
+ * heads a socket `resume_ack` shows above the local position. A call
1904
+ * while a fill is running rides on it (and the loop runs once more after,
1905
+ * in case the running one ended before the new gap's rows were appended).
1906
+ */
1907
+ fillGap(conversationId) {
1908
+ return this.gapFiller.fill(hexOf(conversationId), async () => {
1909
+ const page = await this.stepConversation(conversationId, true);
1910
+ return page.hasMore;
1911
+ });
1912
+ }
1913
+ /**
1914
+ * This device's applied position in every conversation it holds, sorted by
1915
+ * conversation id: what a host puts in its socket resume frame and
1916
+ * compares against the server's heads.
1917
+ */
1918
+ async logPositions() {
1919
+ const raw = await this.call({ kind: "logPositions", id: this.nextId++ });
1920
+ return raw.map(logPositionFromWire);
1921
+ }
1922
+ /** This device's applied position in one conversation; `null` when not held. */
1923
+ async logPosition(id) {
1924
+ const raw = await this.call({ kind: "logPosition", id: this.nextId++, conv: id });
1925
+ return raw === null || raw === void 0 ? null : logPositionFromWire(raw);
1926
+ }
1927
+ /**
1928
+ * Anchor a conversation whose cursor predates positions at the
1929
+ * `(epoch, serverSeq)` the host had recorded for it, so an existing install
1930
+ * does not page its whole current epoch again. Resolves `false` (a no-op)
1931
+ * when the conversation is already anchored; the MLS epoch is never
1932
+ * touched. Call it once at start-up for every conversation the host's own
1933
+ * cursor store holds a position for.
1934
+ */
1935
+ async adoptLogPosition(id, epoch, serverSeq) {
1936
+ return await this.call({
1937
+ kind: "adoptLogPosition",
1938
+ id: this.nextId++,
1939
+ conv: id,
1940
+ epoch,
1941
+ serverSeq
1942
+ });
1943
+ }
1944
+ /**
1945
+ * Conversations the server's heads show this device is behind on: not
1946
+ * anchored yet, a head above the applied position, or frames held in the
1947
+ * reorder buffer. Sorted by id. A held conversation absent from `heads` is
1948
+ * not listed.
1949
+ */
1950
+ async conversationsBehind(heads) {
1951
+ return await this.call({
1952
+ kind: "conversationsBehind",
1953
+ id: this.nextId++,
1954
+ heads: heads.map(logHeadToWire)
1955
+ });
1956
+ }
1957
+ /** Frames held in reorder buffers right now (diagnostics). */
1958
+ async heldFrameCount() {
1959
+ return await this.call({ kind: "heldFrameCount", id: this.nextId++ });
1960
+ }
1961
+ /**
1962
+ * {@link joinConversation} at the Welcome's log position, so the new
1963
+ * conversation is anchored there and its first live frame applies without
1964
+ * a page. Pass `null` (or omit) when the position is unknown.
1965
+ */
1966
+ async joinConversationAt(welcome, position = null) {
1967
+ const idBytes = await this.call({
1968
+ kind: "joinConversationAt",
1969
+ id: this.nextId++,
1970
+ welcome,
1971
+ position,
1972
+ nowMs: this.now()
1973
+ });
1974
+ return this.conversationProxy(idBytes);
1975
+ }
1976
+ /**
1977
+ * The Welcome routing rule at a known position: joins when the conversation
1978
+ * is unknown or held stranded and resolves to it, resolves `null` when it
1979
+ * is held healthy (a relay duplicate), rejects when the Welcome is not
1980
+ * addressed to this device.
1981
+ */
1982
+ async processWelcomeAt(welcome, position = null) {
1983
+ const idBytes = await this.call({
1984
+ kind: "processWelcomeAt",
1985
+ id: this.nextId++,
1986
+ welcome,
1987
+ position,
1988
+ nowMs: this.now()
1989
+ });
1990
+ return idBytes === null || idBytes === void 0 ? null : this.conversationProxy(idBytes);
1991
+ }
1992
+ /**
1993
+ * [D27] Decrypted-but-unconfirmed messages surviving in the pending-apply
1994
+ * journal, oldest first.
1995
+ *
1996
+ * The MLS ratchet advances at decrypt, BEFORE the host persists its own row
1997
+ * for the message; a crash inside that gap used to lose the message for good
1998
+ * (the server re-delivers, but MLS cannot re-decrypt a consumed generation).
1999
+ * The SDK now journals every decrypt in the same checkpoint that persists
2000
+ * the ratchet advance.
2001
+ *
2002
+ * CRASH-RECOVERY CONTRACT: on boot, BEFORE advancing any sync cursor or
2003
+ * sending any delivery ack, drain this list through the normal ingest —
2004
+ * dedup by `content_hash` / envelope identity exactly as for a redelivered
2005
+ * envelope — persist each message, then {@link confirmApplied} the drained
2006
+ * ids. Reading does not consume; unconfirmed entries survive further
2007
+ * restarts (bounded: 512 entries / 4 MiB, oldest evicted). See
2008
+ * docs/PENDING_APPLIES.md.
2009
+ */
2010
+ async pendingApplies() {
2011
+ return await this.call({ kind: "pendingApplies", id: this.nextId++ });
2012
+ }
2013
+ /**
2014
+ * [D27] Delete journal entries whose messages the host has durably
2015
+ * persisted (`IncomingMessage.journal_id` from live processing, or
2016
+ * `PendingApply.journal_id` from a boot drain), and checkpoint so the
2017
+ * deletion survives a reload. Unknown ids are ignored (idempotent).
2018
+ */
2019
+ async confirmApplied(journalIds) {
2020
+ if (journalIds.length === 0) return;
2021
+ await this.call({ kind: "confirmApplied", id: this.nextId++, journalIds });
2022
+ }
2023
+ /**
2024
+ * Build a `LinkingTicket` for a new device.
2025
+ *
2026
+ * [CR-13] `lastAppEvents` is host-supplied per-conversation "what you missed" data
2027
+ * (decrypted AppEvent bytes the new device will render before sync catches up).
2028
+ * Pass `[]` to suppress catchup data — the new device will see an empty conversation
2029
+ * list until normal sync runs.
2030
+ *
2031
+ * Caller is responsible for HPKE-sealing the returned ticket via
2032
+ * `MessagingClient.sealLinkingTicket` before transmitting (CR-3).
2033
+ *
2034
+ * Rejects (`Invalid`), before anything is sent, a KeyPackage that claims the
2035
+ * identity of another account this client knows: a new device links under an
2036
+ * identity of its own, or the account's.
2037
+ */
2038
+ async buildLinkingTicket(newDeviceId, newDeviceKp, lastAppEvents = []) {
2039
+ return await this.call({
2040
+ kind: "buildLinkingTicket",
2041
+ id: this.nextId++,
2042
+ newDeviceId,
2043
+ newDeviceKp,
2044
+ lastAppEvents,
2045
+ nowMs: this.now()
2046
+ });
2047
+ }
2048
+ /**
2049
+ * Decode a `LinkingTicket.catchup_snapshot` blob ([CR-13]).
2050
+ *
2051
+ * Pure WASM — runs in an ephemeral worker so the new device can call this before
2052
+ * `MessagingClient.init()` completes (just like `openLinkingTicket`). Returns the
2053
+ * structured view: per-conversation metas + last-known AppEvent bytes.
2054
+ *
2055
+ * Throws on malformed or oversized inputs. Empty bytes return `null` — that's the
2056
+ * "no catchup data" case (sender passed `[]` to buildLinkingTicket).
2057
+ */
2058
+ static async decodeCatchupSnapshot(snapshotBytes) {
2059
+ if (snapshotBytes.length === 0) return null;
2060
+ return _MessagingClient.ephemeralWorkerCall({
2061
+ kind: "decodeCatchupSnapshot",
2062
+ id: 1,
2063
+ snapshotBytes
2064
+ });
2065
+ }
2066
+ async consumeLinkingTicket(ticket) {
2067
+ await this.call({
2068
+ kind: "consumeLinkingTicket",
2069
+ id: this.nextId++,
2070
+ ticket,
2071
+ nowMs: this.now()
2072
+ });
2073
+ }
2074
+ // ------------------------ Recovery (account backup) ------------------------
2075
+ // All static + stateless: they run on an ephemeral worker, so the recovery screen can
2076
+ // call them before any client is initialised. Same Argon2id/AES-256-GCM IdentityBackup
2077
+ // wire format as the iOS/Android FFI bindings — backups are portable across platforms.
2078
+ /** Generate a fresh 12-word BIP39 mnemonic, returned as its canonical phrase string. */
2079
+ static async generateMnemonicPhrase() {
2080
+ return _MessagingClient.ephemeralWorkerCall({
2081
+ kind: "generateMnemonicPhrase",
2082
+ id: 1
2083
+ });
2084
+ }
2085
+ /** Validate + canonicalise a user-entered phrase (BIP39 wordlist + checksum). Rejects
2086
+ * malformed input. Use on the recovery screen before calling `decryptBackup`. */
2087
+ static async normalizeMnemonicPhrase(phrase) {
2088
+ return _MessagingClient.ephemeralWorkerCall({
2089
+ kind: "normalizeMnemonicPhrase",
2090
+ id: 1,
2091
+ phrase
2092
+ });
2093
+ }
2094
+ /** Encrypt an IdentityBackup for `POST /v1/recovery/blobs`. `deviceGroupSnapshot` may be
2095
+ * empty (Conservative path) or the DeviceGroup's `exportConversationStateSnapshot`. */
2096
+ static async encryptBackup(args) {
2097
+ return _MessagingClient.ephemeralWorkerCall({
2098
+ kind: "encryptBackup",
2099
+ id: 1,
2100
+ mnemonicPhrase: args.mnemonicPhrase,
2101
+ accountId: args.accountId,
2102
+ identityExport: args.identityExport,
2103
+ deviceGroupSnapshot: args.deviceGroupSnapshot,
2104
+ conversationSnapshots: args.conversationSnapshots ?? [],
2105
+ createdAtMs: args.createdAtMs
2106
+ });
2107
+ }
2108
+ /** Decrypt a recovery blob from `GET /v1/recovery/blobs`. Throws on wrong mnemonic or a
2109
+ * tampered blob. The returned `identity_export` is the secret seed for `init`. */
2110
+ static async decryptBackup(blob, mnemonicPhrase) {
2111
+ return _MessagingClient.ephemeralWorkerCall({
2112
+ kind: "decryptBackup",
2113
+ id: 1,
2114
+ blob,
2115
+ mnemonicPhrase
2116
+ });
2117
+ }
2118
+ // ------------------------ Peer-assisted history transfer ------------------------
2119
+ // Authenticated (sign-then-encrypt) device-to-device history used by linking and
2120
+ // post-recovery peer re-add. Confidential to the recipient's ephemeral X25519 key AND
2121
+ // signed by the account identity key, so the receiver proves the sender. Plaintext-only
2122
+ // share — preserves forward secrecy (no MLS keys leave the device).
2123
+ /** Seal+sign a `HistoryBundle` for a recipient device. `recipientPub` (X25519, 32B) is the
2124
+ * recipient's ephemeral pubkey from the linking QR; `senderIdentitySecret` (Ed25519 seed,
2125
+ * 32B) is this account's identity key. Returns the blob to POST to /v1/history-transfers. */
2126
+ static async sealHistoryBundle(bundle, recipientPub, senderIdentitySecret) {
2127
+ return _MessagingClient.ephemeralWorkerCall({
2128
+ kind: "sealHistoryBundle",
2129
+ id: 1,
2130
+ bundle,
2131
+ recipientPub,
2132
+ senderIdentitySecret
2133
+ });
2134
+ }
2135
+ /** Open+verify a sealed history bundle. `recipientPriv` (X25519, 32B) is this device's
2136
+ * ephemeral private key; `senderIdentityPub` (Ed25519, 32B) is the account identity pubkey
2137
+ * from the linking handshake. Throws if the signature doesn't verify. */
2138
+ static async openHistoryBundle(sealed, recipientPriv, senderIdentityPub) {
2139
+ return _MessagingClient.ephemeralWorkerCall({
2140
+ kind: "openHistoryBundle",
2141
+ id: 1,
2142
+ sealed,
2143
+ recipientPriv,
2144
+ senderIdentityPub
2145
+ });
2146
+ }
2147
+ /**
2148
+ * Post-quantum {@link sealHistoryBundle}: `recipientPub` is the recipient's
2149
+ * X-Wing public key ({@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes). Wrapper `v: 2`;
2150
+ * the classical open refuses it and vice versa.
2151
+ */
2152
+ static async sealHistoryBundlePq(bundle, recipientPub, senderIdentitySecret) {
2153
+ if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {
2154
+ throw new Error(`sealHistoryBundlePq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);
2155
+ }
2156
+ return _MessagingClient.ephemeralWorkerCall({
2157
+ kind: "sealHistoryBundlePq",
2158
+ id: 1,
2159
+ bundle,
2160
+ recipientPub,
2161
+ senderIdentitySecret
2162
+ });
2163
+ }
2164
+ /** Post-quantum {@link openHistoryBundle}: `recipientPriv` is the 32-byte X-Wing seed. */
2165
+ static async openHistoryBundlePq(sealed, recipientPriv, senderIdentityPub) {
2166
+ if (recipientPriv.length !== 32) {
2167
+ throw new Error("openHistoryBundlePq: recipientPriv must be 32 bytes");
2168
+ }
2169
+ return _MessagingClient.ephemeralWorkerCall({
2170
+ kind: "openHistoryBundlePq",
2171
+ id: 1,
2172
+ sealed,
2173
+ recipientPriv,
2174
+ senderIdentityPub
2175
+ });
2176
+ }
2177
+ /**
2178
+ * Admit a freshly-linked device to every chat in `entries` — one MLS
2179
+ * Commit + Welcome per chat, with the Welcome's `?recipient=` priming
2180
+ * handled inside the SDK. This is the post-link reconciliation step
2181
+ * that follows `consumeLinkingTicket`: the new device has the
2182
+ * DeviceGroup (from the ticket) and metadata for external chats (from
2183
+ * the catchup snapshot), but its leaf is not yet in any external
2184
+ * MLS group. The host on the EXISTING device calls this once the
2185
+ * new device shows up in `/v1/auth/sessions` and has uploaded its
2186
+ * KeyPackage batch, passing one freshly-claimed KP per chat.
2187
+ *
2188
+ * Per-chat failures (stale KP, transport error, unknown chat) are
2189
+ * captured in the returned outcomes rather than aborting — one bad
2190
+ * chat shouldn't lose the user access to all the others.
2191
+ *
2192
+ * Each KeyPackage must carry this account's identity (a linked device
2193
+ * adopts it with the link): one that claims any other identity fails its
2194
+ * chat and nothing is sent there.
2195
+ */
2196
+ async admitDeviceToChats(deviceId, entries) {
2197
+ return await this.call({
2198
+ kind: "admitDeviceToChats",
2199
+ id: this.nextId++,
2200
+ deviceId,
2201
+ entries,
2202
+ nowMs: this.now()
2203
+ });
2204
+ }
2205
+ /**
2206
+ * `admitDeviceToChats` with up to `concurrency` admissions in flight at
2207
+ * once. Same input, same per-chat outcomes in INPUT order whatever order
2208
+ * the sends finish in; `concurrency` 1 is exactly `admitDeviceToChats`,
2209
+ * 0 is treated as 1. Safe because every admission is its own conversation
2210
+ * (one Commit + Welcome per chat, the conversation lock is never held
2211
+ * across the send), so two admissions never touch the same epoch.
2212
+ *
2213
+ * This is the ONLY way to overlap admissions on web: the worker runs one
2214
+ * call at a time, so several `admitDeviceToChats` calls issued together
2215
+ * still run one after another. The overlap happens inside this one call.
2216
+ */
2217
+ async admitDeviceToChatsConcurrent(deviceId, entries, concurrency) {
2218
+ const lanes = Number.isFinite(concurrency) ? Math.min(4294967295, Math.max(1, Math.floor(concurrency))) : 1;
2219
+ return await this.call({
2220
+ kind: "admitDeviceToChatsConcurrent",
2221
+ id: this.nextId++,
2222
+ deviceId,
2223
+ entries,
2224
+ nowMs: this.now(),
2225
+ concurrency: lanes
2226
+ });
2227
+ }
2228
+ /**
2229
+ * Revoke a device ([CR-2]).
2230
+ *
2231
+ * Removes `deviceId`'s leaf from every conversation where this client locally
2232
+ * tracked the device→leaf mapping (i.e. conversations where this client itself
2233
+ * admitted the device via `addMembers`, or where this client is the device being
2234
+ * revoked). The SDK has already broadcast each Commit envelope via
2235
+ * `transport.send`; the returned array is for any additional host-side handling
2236
+ * (audit logs, UI). An empty array is a valid outcome — the device wasn't locally
2237
+ * known anywhere.
2238
+ *
2239
+ * **Scope note.** Conversations where a peer admitted the device on this client's
2240
+ * behalf are silently skipped — the leaf index isn't locally known. Host can fall
2241
+ * back to `transport.discoverDevices` + a manual `remove_members(leafIndex)` for
2242
+ * those, or wait for the affected user to revoke from a device that did the admit.
2243
+ * See `docs/architecture/multi-device.md §Device removal`.
2244
+ */
2245
+ async revokeDevice(deviceId) {
2246
+ return await this.call({
2247
+ kind: "revokeDevice",
2248
+ id: this.nextId++,
2249
+ deviceId,
2250
+ nowMs: this.now()
2251
+ });
2252
+ }
2253
+ /**
2254
+ * Remove one of THIS account's devices from every group this client is in, the
2255
+ * DeviceGroup included, without stopping at a failure, and report where it stands.
2256
+ *
2257
+ * Unlike {@link revokeDevice}, the device's leaf is read from each ratchet tree (the
2258
+ * leaf whose key hashes to the id), so this reaches leaves a sibling or a peer
2259
+ * admitted. The id is the server's word that the device is this account's; outside
2260
+ * the DeviceGroup a leaf is removed only when its credential names this account, or
2261
+ * when the device was seen in the account's DeviceGroup and its credential names no
2262
+ * other account this client knows (docs/MULTIDEVICE.md, "Which leaf"). An id that
2263
+ * names no leaf of this account is rejected before anything is sent. Every held
2264
+ * conversation is checked: a Commit of this device in doubt is settled first, and
2265
+ * the log is read to its end before the device is reported absent (what that read
2266
+ * applies comes with the next batch or page); a conversation that failed to load
2267
+ * is a failure with reason `Unloadable`. The DeviceGroup goes first, then the
2268
+ * conversations, a few at a time, each a send-then-merge Commit. Persist the report
2269
+ * and call again until `failed` is empty and `deviceGroup !== "failed"`. A
2270
+ * `CommitInDoubt` reason settles on its own backoff ({@link commitsInDoubt});
2271
+ * `NotOwnAccount` and `RefusedCommit` never resolve by retrying (for
2272
+ * `RefusedCommit`, offer to recreate the conversation). Groups this device joins
2273
+ * later are checked for the device too.
2274
+ *
2275
+ * MLS only: revoke the device on the server yourself. Rejects for this device's own
2276
+ * id (leave a conversation with `leaveConversation` instead) and for a device that
2277
+ * is not this account's.
2278
+ */
2279
+ async removeDeviceEverywhere(deviceId, nowMs = this.now()) {
2280
+ return await this.call({
2281
+ kind: "removeDeviceEverywhere",
2282
+ id: this.nextId++,
2283
+ deviceId,
2284
+ nowMs
2285
+ });
2286
+ }
2287
+ /**
2288
+ * Remove every other device of THIS account from every group this client is in,
2289
+ * except the devices in `keep` and this device: the "secure my account" sweep.
2290
+ *
2291
+ * `listed` is the server's list of this account's devices to remove (a reset's
2292
+ * `revoked_device_ids`). In the DeviceGroup every leaf but this device's and the
2293
+ * kept ones goes. Elsewhere a leaf goes when its credential names this client's
2294
+ * account (no device id has to match, so a device that moved its leaf to another
2295
+ * signature key is still reached), or when its device is in `listed` and was seen in
2296
+ * the account's DeviceGroup, whatever identity its leaf claims. A leaf the sweep
2297
+ * leaves although one of those two says it may be the account's (seen but not
2298
+ * listed, or listed but not seen) is reported: its conversation fails with
2299
+ * `NotOwnAccount`, so the report is never complete over it. Same pass and report as
2300
+ * {@link removeDeviceEverywhere}; call again until it is complete. MLS only.
2301
+ */
2302
+ async removeOwnDevicesExcept(keep, listed, nowMs = this.now()) {
2303
+ return await this.call({
2304
+ kind: "removeOwnDevicesExcept",
2305
+ id: this.nextId++,
2306
+ keep,
2307
+ listed,
2308
+ nowMs
2309
+ });
2310
+ }
2311
+ /**
2312
+ * Export a portable MLS state snapshot for one conversation ([CR-7]).
2313
+ *
2314
+ * Returned bytes can be embedded in a recovery blob or shipped through a
2315
+ * linking ticket so another device of the same user identity can re-attach to
2316
+ * the group via [[importStateSnapshot]]. The bytes contain past epoch secrets;
2317
+ * never log, never persist unencrypted, wipe (`.fill(0)`) after use.
2318
+ */
2319
+ async exportConversationStateSnapshot(conv) {
2320
+ return await this.call({
2321
+ kind: "exportConversationStateSnapshot",
2322
+ id: this.nextId++,
2323
+ conv,
2324
+ nowMs: this.now()
2325
+ });
2326
+ }
2327
+ /**
2328
+ * Import a `GroupStateSnapshot` from another device of the same user identity
2329
+ * ([CR-7]).
2330
+ *
2331
+ * On success, the conversation appears in [[listConversations]] and decryption
2332
+ * of subsequent peer-originated traffic works against the imported state. For
2333
+ * full multi-device participation, the recovered device SHOULD then issue an
2334
+ * MLS Update Proposal to rotate onto a fresh leaf (post-v1 follow-up — see
2335
+ * `docs/design/CR4_CR7_PERSISTENCE.md` open question #3).
2336
+ */
2337
+ async importStateSnapshot(snapshotBytes) {
2338
+ return await this.call({
2339
+ kind: "importStateSnapshot",
2340
+ id: this.nextId++,
2341
+ snapshotBytes,
2342
+ nowMs: this.now()
2343
+ });
2344
+ }
2345
+ /**
2346
+ * Export a derived secret from a conversation's MLS exporter ([CR-8]).
2347
+ *
2348
+ * Used to seed the ephemeral channel (`ping/ephemeral`), call-media keys
2349
+ * (`ping/calls/media/<call_id>`), and call-ephemeral framer keys
2350
+ * (`ping/calls/ephemeral/<call_id>`). The returned bytes are a secret — never log,
2351
+ * persist only encrypted, and call `bytes.fill(0)` after use to wipe the typed array.
2352
+ *
2353
+ * Same `(conversationId, current_epoch, label, context, length)` produces the same
2354
+ * bytes across every binding (Rust core, native UniFFI, WASM/JS). Cross-platform
2355
+ * byte-equality is enforced by `protocol/conformance/export_secret/`.
2356
+ */
2357
+ async exportConversationSecret(conv, label, context, length) {
2358
+ if (length <= 0 || length > 1024) {
2359
+ throw new Error("exportConversationSecret: length must be 1..=1024");
2360
+ }
2361
+ return await this.call({
2362
+ kind: "exportConversationSecret",
2363
+ id: this.nextId++,
2364
+ conv,
2365
+ label,
2366
+ context,
2367
+ length
2368
+ });
2369
+ }
2370
+ /**
2371
+ * Subscribe to decrypted application messages, one call per message. A
2372
+ * batch or page result (the sequenced paths) is fanned out here per
2373
+ * message only while no {@link onMessageBatch} handler is registered.
2374
+ */
2375
+ onMessage(handler) {
2376
+ return this.fanout.onMessage(handler);
2377
+ }
2378
+ /**
2379
+ * Subscribe to decrypted messages one BATCH at a time: one call per
2380
+ * `processSequencedBatch` result (source `live`) or per page of the server
2381
+ * log (source `page`: a gap fill, or the whole-account catch-up), so the
2382
+ * host persists the batch in one store transaction. While at least one
2383
+ * batch handler is registered, batch and page results go ONLY here, never
2384
+ * per message to `onMessage`; the legacy per-envelope path still delivers
2385
+ * per message. An empty result is not delivered.
2386
+ */
2387
+ onMessageBatch(handler) {
2388
+ return this.fanout.onMessageBatch(handler);
2389
+ }
2390
+ /** Fired after every state-changing event for a conversation (Commit, member changes). */
2391
+ /**
2392
+ * Fires after every conversation state change — joining via Welcome, processing a Commit,
2393
+ * etc. `sender` carries the device id of whoever triggered the event when known (e.g. the
2394
+ * inviter's device on auto-join), so the host can label peers in its UI.
2395
+ */
2396
+ onConversationUpdated(handler) {
2397
+ this.conversationHandlers.add(handler);
2398
+ return () => this.conversationHandlers.delete(handler);
2399
+ }
2400
+ /**
2401
+ * Stop the live subscription and terminate the worker. Every call still in
2402
+ * flight rejects with a {@link MessagingClientClosedError} (reason
2403
+ * `closed`), and every later call rejects the same way instead of waiting
2404
+ * on a worker that no longer exists. Idempotent.
2405
+ */
2406
+ async close() {
2407
+ if (this.closed) return;
2408
+ this.closed = true;
2409
+ this.subscription?.unsubscribe();
2410
+ this.worker.terminate();
2411
+ this.failPending(new MessagingClientClosedError("closed"));
2412
+ }
2413
+ /** Reject every pending call with `error` and forget them. */
2414
+ failPending(error) {
2415
+ const slots = [...this.pending.values()];
2416
+ this.pending.clear();
2417
+ for (const slot of slots) slot.reject(error);
2418
+ }
2419
+ // ------------------------ Internals ------------------------
2420
+ conversationProxy(id) {
2421
+ const self = this;
2422
+ return {
2423
+ id,
2424
+ async send(plaintext) {
2425
+ const heldEpoch = self.metaCache.get(hex(id))?.epoch;
2426
+ return await self.call({
2427
+ kind: "send",
2428
+ id: self.nextId++,
2429
+ conv: id,
2430
+ plaintext,
2431
+ nowMs: self.now(),
2432
+ ...heldEpoch !== void 0 ? { heldEpoch } : {}
2433
+ });
2434
+ },
2435
+ async addMembers(entries) {
2436
+ await self.call({
2437
+ kind: "addMembers",
2438
+ id: self.nextId++,
2439
+ conv: id,
2440
+ entries,
2441
+ nowMs: self.now()
2442
+ });
2443
+ },
2444
+ async addMembersWithVerdicts(entries) {
2445
+ const raw = await self.call({
2446
+ kind: "addMembersWithVerdicts",
2447
+ id: self.nextId++,
2448
+ conv: id,
2449
+ entries,
2450
+ nowMs: self.now()
2451
+ });
2452
+ return addMembersReportFromWire(raw);
2453
+ },
2454
+ async reAdmitDevice(entry) {
2455
+ const replaced = await self.call({
2456
+ kind: "reAdmitDevice",
2457
+ id: self.nextId++,
2458
+ conv: id,
2459
+ entry,
2460
+ nowMs: self.now()
2461
+ });
2462
+ return replaced ?? null;
2463
+ },
2464
+ async removeOwnOtherLeaves() {
2465
+ return await self.call({
2466
+ kind: "removeOwnOtherLeaves",
2467
+ id: self.nextId++,
2468
+ conv: id,
2469
+ nowMs: self.now()
2470
+ });
2471
+ },
2472
+ async removeMembersByIdentity(identities) {
2473
+ return await self.call({
2474
+ kind: "removeMembersByIdentity",
2475
+ id: self.nextId++,
2476
+ conv: id,
2477
+ identities,
2478
+ nowMs: self.now()
2479
+ });
2480
+ },
2481
+ async removeMembers(leaves) {
2482
+ await self.call({
2483
+ kind: "removeMembers",
2484
+ id: self.nextId++,
2485
+ conv: id,
2486
+ leaves,
2487
+ nowMs: self.now()
2488
+ });
2489
+ },
2490
+ async setConversationName(name) {
2491
+ await self.call({
2492
+ kind: "setConversationName",
2493
+ id: self.nextId++,
2494
+ conv: id,
2495
+ name,
2496
+ nowMs: self.now()
2497
+ });
2498
+ },
2499
+ async setConversationRoles(owner, admins) {
2500
+ await self.call({
2501
+ kind: "setConversationRoles",
2502
+ id: self.nextId++,
2503
+ conv: id,
2504
+ owner,
2505
+ admins,
2506
+ nowMs: self.now()
2507
+ });
2508
+ },
2509
+ /**
2510
+ * The conversation's MLS GroupContext name as the group holds it now, or
2511
+ * `undefined` when it has none or the client holds no metadata for it.
2512
+ *
2513
+ * This accessor did not exist, and hosts reasonably assumed it did:
2514
+ * `getConversation(id).name` read `undefined` on every call, which
2515
+ * silently disabled any host logic driven by group state — group titles,
2516
+ * rosters, avatars and roles carried in the GroupContext all appeared
2517
+ * absent, so a group would materialise unnamed until a best-effort
2518
+ * broadcast happened to arrive.
2519
+ *
2520
+ * A getter rather than a snapshot, so it reflects the client's copy at
2521
+ * read time. That copy used to be refilled by `listConversations()`
2522
+ * only, and this answered the name from BEFORE a rename until the host
2523
+ * listed again; it is now replaced with every change the worker reports
2524
+ * (see `metaCache`).
2525
+ */
2526
+ get name() {
2527
+ return self.metaCache.get(hex(id))?.name ?? void 0;
2528
+ },
2529
+ /** The conversation's current MLS epoch, or `undefined` when the client
2530
+ * holds no metadata for it. */
2531
+ get epoch() {
2532
+ return self.metaCache.get(hex(id))?.epoch;
2533
+ },
2534
+ meta() {
2535
+ const cached = self.metaCache.get(hex(id));
2536
+ if (!cached) {
2537
+ throw new Error("conversation meta not loaded; call readConversationMeta(id) or listConversations() first");
2538
+ }
2539
+ return cached;
2540
+ }
2541
+ };
2542
+ }
2543
+ /** Replace this client's copy of one conversation's metadata with what the
2544
+ * worker read; no metadata means the copy is dropped, so the handle answers
2545
+ * "not held" instead of what the group held before. */
2546
+ storeMeta(id, meta) {
2547
+ if (meta === null || meta === void 0) this.metaCache.delete(hex(id));
2548
+ else this.metaCache.set(hex(id), meta);
2549
+ }
2550
+ call(req) {
2551
+ if (this.closed) return Promise.reject(new MessagingClientClosedError("closed"));
2552
+ return new Promise((resolve, reject) => {
2553
+ this.pending.set(req.id, { resolve, reject });
2554
+ this.worker.postMessage(req);
2555
+ });
2556
+ }
2557
+ /** Dispatch a worker-side transport proxy call onto the host transport.
2558
+ * `sendBatch` is the one method the worker proxy always declares but a
2559
+ * host may not implement: emulate it with sequential sends and report a
2560
+ * partial delivery with the sentinel the wasm bridge maps to
2561
+ * `TransportPartial`, so the SDK still learns the Commit landed while the
2562
+ * Welcome did not (and surfaces `WelcomeUndelivered`). The two
2563
+ * sequenced-log methods cross in the wasm's wire shape and are converted
2564
+ * to the public shape here, both ways; the worker only asks for them when
2565
+ * the host declared them at `init`. */
2566
+ async callTransportMethod(method, args) {
2567
+ const t = this.transport;
2568
+ if (method === "sendBatch" && typeof t.sendBatch !== "function") {
2569
+ await emulateSendBatch(this.transport, args[0] ?? []);
2570
+ return void 0;
2571
+ }
2572
+ if (method === "fetchLogSince") {
2573
+ if (typeof this.transport.fetchLogSince !== "function") return null;
2574
+ const [position, limit] = args;
2575
+ const rows = await this.transport.fetchLogSince(logPositionFromWire(position), limit);
2576
+ return rows === null || rows === void 0 ? null : rows.map(sequencedToWire);
2577
+ }
2578
+ if (method === "fetchLogHeads") {
2579
+ if (typeof this.transport.fetchLogHeads !== "function") return null;
2580
+ const heads = await this.transport.fetchLogHeads();
2581
+ return heads === null || heads === void 0 ? null : heads.map(logHeadToWire);
2582
+ }
2583
+ return await t[method]?.(...args);
2584
+ }
2585
+ async handleWorker(msg) {
2586
+ switch (msg.kind) {
2587
+ case "result": {
2588
+ const slot = this.pending.get(msg.id);
2589
+ if (!slot) return;
2590
+ this.pending.delete(msg.id);
2591
+ msg.ok ? slot.resolve(msg.value) : slot.reject(errorFromWorker(msg.error));
2592
+ return;
2593
+ }
2594
+ case "event.message": {
2595
+ this.fanout.deliverOne(msg.msg);
2596
+ return;
2597
+ }
2598
+ case "event.batch": {
2599
+ this.fanout.deliverBatch(msg.messages, { source: msg.source });
2600
+ return;
2601
+ }
2602
+ case "event.conversation": {
2603
+ this.storeMeta(msg.id, msg.meta);
2604
+ for (const h of this.conversationHandlers) {
2605
+ try {
2606
+ h(msg.id, msg.epoch, msg.sender);
2607
+ } catch (e) {
2608
+ if (typeof console !== "undefined") {
2609
+ console.debug("[ping-sdk] onConversationUpdated handler threw:", errorKind(e));
2610
+ }
2611
+ }
2612
+ }
2613
+ return;
2614
+ }
2615
+ case "cache.conversations": {
2616
+ for (const meta of msg.held) this.storeMeta(meta.id, meta);
2617
+ for (const id of msg.dropped) this.storeMeta(id, null);
2618
+ return;
2619
+ }
2620
+ case "storage.call": {
2621
+ try {
2622
+ const method = this.storage[msg.method];
2623
+ if (typeof method !== "function") {
2624
+ throw new Error(`storage.${String(msg.method)} is not implemented by the host storage`);
2625
+ }
2626
+ const v = await method.apply(this.storage, msg.args);
2627
+ this.worker.postMessage({ kind: "storage.reply", id: msg.id, ok: true, value: v });
2628
+ } catch (e) {
2629
+ this.worker.postMessage({
2630
+ kind: "storage.reply",
2631
+ id: msg.id,
2632
+ ok: false,
2633
+ error: String(e)
2634
+ });
2635
+ }
2636
+ return;
2637
+ }
2638
+ case "transport.call": {
2639
+ try {
2640
+ const v = await this.callTransportMethod(msg.method, msg.args);
2641
+ this.worker.postMessage({ kind: "transport.reply", id: msg.id, ok: true, value: v });
2642
+ } catch (e) {
2643
+ this.worker.postMessage({
2644
+ kind: "transport.reply",
2645
+ id: msg.id,
2646
+ ok: false,
2647
+ error: describeTransportError(e)
2648
+ });
2649
+ }
2650
+ return;
2651
+ }
2652
+ }
2653
+ }
2654
+ };
2655
+ var EphemeralWorkerError = class extends Error {
2656
+ reason;
2657
+ constructor(reason) {
2658
+ super(`ping-openmls-sdk: one-shot worker failed (${reason})`);
2659
+ this.name = "EphemeralWorkerError";
2660
+ this.reason = reason;
2661
+ }
2662
+ };
2663
+ var MessagingClientClosedError = class extends Error {
2664
+ reason;
2665
+ constructor(reason) {
2666
+ super(reason === "closed" ? "MessagingClient is closed" : "MessagingClient worker error");
2667
+ this.name = "MessagingClientClosedError";
2668
+ this.reason = reason;
2669
+ }
2670
+ };
2671
+ var HPKE_PQ_PUBLIC_KEY_BYTES = 1216;
2672
+ var HPKE_PQ_ENC_BYTES = 1120;
2673
+ var BATCH_PARTIAL_PREFIX = "batch partial after ";
2674
+ var NOT_PERMITTED_PREFIX = "not permitted: ";
2675
+ var NotPermittedError = class extends Error {
2676
+ /** The rule that was broken: fixed text, no id, safe to log. */
2677
+ rule;
2678
+ constructor(message) {
2679
+ super(message);
2680
+ this.name = "NotPermittedError";
2681
+ this.rule = message.startsWith(NOT_PERMITTED_PREFIX) ? message.slice(NOT_PERMITTED_PREFIX.length) : message;
2682
+ }
2683
+ };
2684
+ function notPermittedRule(e) {
2685
+ const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
2686
+ return text !== null && text.startsWith(NOT_PERMITTED_PREFIX) ? text.slice(NOT_PERMITTED_PREFIX.length) : null;
2687
+ }
2688
+ function isNotPermittedError(e) {
2689
+ return notPermittedRule(e) !== null;
2690
+ }
2691
+ var SENDER_MISMATCH_PREFIX = "sender mismatch: ";
2692
+ var SenderMismatchError = class extends Error {
2693
+ constructor(message) {
2694
+ super(message);
2695
+ this.name = "SenderMismatchError";
2696
+ }
2697
+ };
2698
+ function isSenderMismatchError(e) {
2699
+ const text = typeof e === "string" ? e : e !== null && typeof e === "object" && typeof e.message === "string" ? e.message : null;
2700
+ return text !== null && text.startsWith(SENDER_MISMATCH_PREFIX);
2701
+ }
2702
+ function errorFromWorker(text) {
2703
+ if (text.startsWith(NOT_PERMITTED_PREFIX)) return new NotPermittedError(text);
2704
+ if (text.startsWith(SENDER_MISMATCH_PREFIX)) return new SenderMismatchError(text);
2705
+ return new Error(text);
2706
+ }
2707
+ async function emulateSendBatch(transport, envelopes) {
2708
+ let delivered = 0;
2709
+ for (const envelope of envelopes) {
2710
+ try {
2711
+ await transport.send(envelope);
2712
+ } catch (e) {
2713
+ if (delivered === 0) throw e;
2714
+ throw new Error(`${BATCH_PARTIAL_PREFIX}${delivered}: ${describeTransportError(e)}`);
2715
+ }
2716
+ delivered += 1;
2717
+ }
2718
+ }
2719
+ function describeTransportError(e) {
2720
+ if (e && typeof e === "object") {
2721
+ const rec = e;
2722
+ const status = typeof rec.status === "number" ? rec.status : void 0;
2723
+ const message = typeof rec.message === "string" ? rec.message : String(e);
2724
+ if (message.startsWith(BATCH_PARTIAL_PREFIX)) return message;
2725
+ const parts = [];
2726
+ if (typeof rec.name === "string" && rec.name) parts.push(`${rec.name}:`);
2727
+ parts.push(message);
2728
+ if (status !== void 0 && !message.includes(`http ${status}`)) parts.push(`(http ${status})`);
2729
+ if (typeof rec.serverError === "string" && rec.serverError) parts.push(`[${rec.serverError}]`);
2730
+ return parts.join(" ");
2731
+ }
2732
+ return String(e);
2733
+ }
2734
+ function hex(b) {
2735
+ let s = "";
2736
+ for (const v of b) s += v.toString(16).padStart(2, "0");
2737
+ return s;
2738
+ }
2739
+ function hexOf(bytes) {
2740
+ let out = "";
2741
+ for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
2742
+ return out;
2743
+ }
2744
+ function sameBytesU8(a, b) {
2745
+ if (a.length !== b.length) return false;
2746
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
2747
+ return true;
2748
+ }
2749
+ // Annotate the CommonJS export names for ESM import in node:
2750
+ 0 && (module.exports = {
2751
+ BATCH_PARTIAL_PREFIX,
2752
+ CONTENT_TYPE_CBOR,
2753
+ CONTENT_TYPE_CBOR_LEGACY_V1,
2754
+ CONTENT_TYPE_JSON,
2755
+ CONTENT_TYPE_JSON_LEGACY_V1,
2756
+ EphemeralWorkerError,
2757
+ HPKE_PQ_ENC_BYTES,
2758
+ HPKE_PQ_PUBLIC_KEY_BYTES,
2759
+ IndexedDbStorage,
2760
+ MessagingClient,
2761
+ MessagingClientClosedError,
2762
+ NOT_PERMITTED_PREFIX,
2763
+ NotPermittedError,
2764
+ PING_WIRE_CONTRACT_HEADER,
2765
+ PING_WIRE_CONTRACT_HEADER_VALUE,
2766
+ PING_WIRE_CONTRACT_VERSION,
2767
+ SENDER_MISMATCH_PREFIX,
2768
+ SenderMismatchError,
2769
+ ValidationError,
2770
+ WIRE_VERSION_MIN_ACCEPTED,
2771
+ WebSocketTransport,
2772
+ describeTransportError,
2773
+ emulateSendBatch,
2774
+ isNotPermittedError,
2775
+ isSenderMismatchError,
2776
+ negotiates,
2777
+ notPermittedRule,
2778
+ openNotificationPreview,
2779
+ validate,
2780
+ verifyApplicationContentHash
2781
+ });
2782
+ //# sourceMappingURL=index.cjs.map