@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
@@ -0,0 +1,841 @@
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 __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
15
+ };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+
25
+ // src/wasm-memory.ts
26
+ var RESERVE_MIB_TARGETS = [192, 128, 64, 32];
27
+ var WASM_PAGE_BYTES = 64 * 1024;
28
+ var reserved = /* @__PURE__ */ new WeakSet();
29
+ function reserveLinearMemory(memory) {
30
+ if (reserved.has(memory)) return;
31
+ reserved.add(memory);
32
+ for (const mib of RESERVE_MIB_TARGETS) {
33
+ try {
34
+ memory.grow(mib * 1024 * 1024 / WASM_PAGE_BYTES);
35
+ return;
36
+ } catch {
37
+ }
38
+ }
39
+ }
40
+
41
+ // src/worker.ts
42
+ var import_ping_wasm = __toESM(require("../wasm/ping_wasm"), 1);
43
+
44
+ // src/epoch-events.ts
45
+ function conversationKey(id) {
46
+ let out = "";
47
+ for (let i = 0; i < id.length; i += 1) out += (id[i] ?? 0).toString(16).padStart(2, "0");
48
+ return out;
49
+ }
50
+ function epochMap(metas) {
51
+ const out = /* @__PURE__ */ new Map();
52
+ for (const meta of metas) out.set(conversationKey(meta.id), meta.epoch);
53
+ return out;
54
+ }
55
+ function advancedEpochs(before, after) {
56
+ const out = [];
57
+ for (const meta of after) {
58
+ const previous = before.get(conversationKey(meta.id));
59
+ if (previous === void 0 || meta.epoch <= previous) continue;
60
+ out.push(meta);
61
+ }
62
+ return out;
63
+ }
64
+ function conversationIdOf(key) {
65
+ const out = new Uint8Array(key.length >> 1);
66
+ for (let i = 0; i < out.length; i += 1) out[i] = Number.parseInt(key.slice(i * 2, i * 2 + 2), 16);
67
+ return out;
68
+ }
69
+ function changedHoldings(before, after) {
70
+ const appeared = [];
71
+ const still = /* @__PURE__ */ new Set();
72
+ for (const meta of after) {
73
+ const key = conversationKey(meta.id);
74
+ still.add(key);
75
+ if (!before.has(key)) appeared.push(meta);
76
+ }
77
+ const disappeared = [];
78
+ for (const key of before.keys()) {
79
+ if (!still.has(key)) disappeared.push(conversationIdOf(key));
80
+ }
81
+ return { appeared, disappeared };
82
+ }
83
+
84
+ // src/catch-up-pass.ts
85
+ function catchUpPass(deps) {
86
+ const seen = /* @__PURE__ */ new Set();
87
+ const delivered = [];
88
+ let pending = null;
89
+ let relisted = false;
90
+ const sortedUnseen = (ids) => ids.filter((id) => !seen.has(conversationKey(id))).sort((a, b) => conversationKey(a) < conversationKey(b) ? -1 : 1);
91
+ const initial = async () => {
92
+ const heads = await deps.fetchHeads();
93
+ if (heads === null) return sortedUnseen(deps.listConversationIds());
94
+ for (const h of heads) seen.add(conversationKey(h.conversation_id));
95
+ const behind = deps.conversationsBehind(heads);
96
+ for (const id of behind) seen.delete(conversationKey(id));
97
+ return sortedUnseen(behind);
98
+ };
99
+ return async () => {
100
+ try {
101
+ if (pending === null) pending = await initial();
102
+ if (pending.length === 0 && !relisted) {
103
+ relisted = true;
104
+ pending = sortedUnseen(deps.listConversationIds());
105
+ }
106
+ } catch (e) {
107
+ deps.finish(false, e);
108
+ return false;
109
+ }
110
+ const id = pending[0];
111
+ if (id === void 0) {
112
+ deps.finish(true, delivered);
113
+ return false;
114
+ }
115
+ let more = false;
116
+ try {
117
+ const page = await deps.step(id);
118
+ for (const m of page.messages) delivered.push(m);
119
+ deps.onPage(page);
120
+ more = page.has_more;
121
+ } catch {
122
+ }
123
+ if (!more) {
124
+ seen.add(conversationKey(id));
125
+ pending.shift();
126
+ }
127
+ return true;
128
+ };
129
+ }
130
+
131
+ // src/request-lanes.ts
132
+ var RequestScheduler = class {
133
+ primary = [];
134
+ stepped = [];
135
+ pumping = false;
136
+ /** Queue an ordinary request behind the ordinary requests before it. */
137
+ enqueue(job) {
138
+ this.primary.push(job);
139
+ void this.pump();
140
+ }
141
+ /** Queue a stepped job; its steps run whenever the primary lane is empty. */
142
+ enqueueStepped(job) {
143
+ this.stepped.push(job);
144
+ void this.pump();
145
+ }
146
+ /** Requests waiting in the primary lane (diagnostics / tests). */
147
+ get pendingPrimary() {
148
+ return this.primary.length;
149
+ }
150
+ /** Stepped jobs not yet finished (diagnostics / tests). */
151
+ get pendingStepped() {
152
+ return this.stepped.length;
153
+ }
154
+ async pump() {
155
+ if (this.pumping) return;
156
+ this.pumping = true;
157
+ try {
158
+ for (; ; ) {
159
+ const job = this.primary.shift();
160
+ if (job !== void 0) {
161
+ await job().catch(() => void 0);
162
+ continue;
163
+ }
164
+ const step = this.stepped[0];
165
+ if (step === void 0) return;
166
+ let more = false;
167
+ try {
168
+ more = await step();
169
+ } catch {
170
+ more = false;
171
+ }
172
+ if (!more) this.stepped.shift();
173
+ }
174
+ } finally {
175
+ this.pumping = false;
176
+ }
177
+ }
178
+ };
179
+
180
+ // src/worker.ts
181
+ var client = null;
182
+ var wasmReady = null;
183
+ var pendingStorage = /* @__PURE__ */ new Map();
184
+ var pendingTransport = /* @__PURE__ */ new Map();
185
+ var nextStorageId = 1;
186
+ var nextTransportId = 1;
187
+ var transportCalls = 0;
188
+ var proxyStorage = {
189
+ get: (namespace, key) => callMain("storage", "get", [namespace, key]),
190
+ put: (namespace, key, value) => callMain("storage", "put", [namespace, key, value]),
191
+ del: (namespace, key) => callMain("storage", "del", [namespace, key]),
192
+ listKeys: (namespace, prefix) => callMain("storage", "listKeys", [namespace, prefix])
193
+ };
194
+ var applyBatchProxy = (namespace, puts, deletes) => callMain("storage", "applyBatch", [namespace, puts, deletes]);
195
+ var listEntriesProxy = (namespace, prefix) => callMain("storage", "listEntries", [namespace, prefix]);
196
+ function makeProxyStorage(features) {
197
+ return {
198
+ ...proxyStorage,
199
+ ...features?.applyBatch ? { applyBatch: applyBatchProxy } : {},
200
+ ...features?.listEntries ? { listEntries: listEntriesProxy } : {}
201
+ };
202
+ }
203
+ var proxyTransport = {
204
+ send: (envelope) => callMain("transport", "send", [envelope]),
205
+ // Always declared here: the main-thread dispatch emulates it with
206
+ // sequential sends when the host transport has no `sendBatch`, encoding a
207
+ // partial delivery with the `batch partial after <n>:` sentinel the wasm
208
+ // bridge understands (see index.ts `BATCH_PARTIAL_PREFIX`).
209
+ sendBatch: (envelopes) => callMain("transport", "sendBatch", [envelopes]),
210
+ fetchSince: (conv, cursor, limit) => callMain("transport", "fetchSince", [conv, cursor, limit]),
211
+ discoverDevices: (userId) => callMain("transport", "discoverDevices", [userId]),
212
+ // Optional on the host (see `Transport.setNextWelcomeRecipients` in types.ts).
213
+ // The main-thread dispatch (index.ts `handleWorker → case "transport.call"`)
214
+ // resolves `undefined` to a `transport.reply { ok: true, value: undefined }`
215
+ // when the host hasn't implemented the method, which we treat as a no-op.
216
+ setNextWelcomeRecipients: (conv, recipients) => callMain("transport", "setNextWelcomeRecipients", [conv, recipients])
217
+ };
218
+ var transportFeatures = { fetchLogSince: false, fetchLogHeads: false };
219
+ var fetchLogSinceProxy = (position, limit) => callMain("transport", "fetchLogSince", [position, limit]);
220
+ var fetchLogHeadsProxy = () => callMain("transport", "fetchLogHeads", []);
221
+ function makeProxyTransport(features) {
222
+ return {
223
+ ...proxyTransport,
224
+ ...features.fetchLogSince ? { fetchLogSince: fetchLogSinceProxy } : {},
225
+ ...features.fetchLogHeads ? { fetchLogHeads: fetchLogHeadsProxy } : {}
226
+ };
227
+ }
228
+ function callMain(kind, method, args) {
229
+ return new Promise((resolve, reject) => {
230
+ const id = kind === "storage" ? nextStorageId++ : nextTransportId++;
231
+ const map = kind === "storage" ? pendingStorage : pendingTransport;
232
+ if (kind === "transport") transportCalls += 1;
233
+ map.set(id, ({ ok, value }) => ok ? resolve(value) : reject(new Error(String(value))));
234
+ self.postMessage({ kind: `${kind}.call`, id, method, args });
235
+ });
236
+ }
237
+ async function ensureWasm() {
238
+ if (wasmReady) return wasmReady;
239
+ wasmReady = (0, import_ping_wasm.default)().then((out) => {
240
+ reserveLinearMemory(out.memory);
241
+ });
242
+ return wasmReady;
243
+ }
244
+ var scheduler = new RequestScheduler();
245
+ var EPOCH_ADVANCING_REQUESTS = /* @__PURE__ */ new Set([
246
+ "addMembers",
247
+ "addMembersWithVerdicts",
248
+ "reAdmitDevice",
249
+ "removeMembers",
250
+ "removeOwnOtherLeaves",
251
+ "removeMembersByIdentity",
252
+ "commitPendingProposals",
253
+ "setConversationName",
254
+ "setConversationRoles",
255
+ "admitDeviceToChats",
256
+ "admitDeviceToChatsConcurrent",
257
+ "revokeDevice",
258
+ "removeDeviceEverywhere",
259
+ "removeOwnDevicesExcept",
260
+ "syncConversations",
261
+ "syncConversation",
262
+ "consumeLinkingTicket",
263
+ "importStateSnapshot"
264
+ ]);
265
+ var EPOCH_UPKEEP_REQUESTS = /* @__PURE__ */ new Set([
266
+ "buildLinkingTicket"
267
+ ]);
268
+ function readMeta(id) {
269
+ if (!client) return null;
270
+ try {
271
+ return client.conversationMeta(id) ?? null;
272
+ } catch {
273
+ return null;
274
+ }
275
+ }
276
+ var SINGLE_READS_MAX = 8;
277
+ function readMetas(ids) {
278
+ const out = /* @__PURE__ */ new Map();
279
+ for (const id of ids) out.set(conversationKey(id), null);
280
+ if (out.size <= SINGLE_READS_MAX) {
281
+ for (const id of ids) out.set(conversationKey(id), readMeta(id));
282
+ return out;
283
+ }
284
+ if (!client) return out;
285
+ try {
286
+ for (const meta of client.listConversations()) {
287
+ const key = conversationKey(meta.id);
288
+ if (out.has(key)) out.set(key, meta);
289
+ }
290
+ } catch {
291
+ }
292
+ return out;
293
+ }
294
+ function postConversationEvent(id, epoch, sender, meta) {
295
+ self.postMessage({
296
+ kind: "event.conversation",
297
+ id,
298
+ epoch,
299
+ ...sender !== void 0 ? { sender } : {},
300
+ ...meta !== null ? { meta } : {}
301
+ });
302
+ }
303
+ function postCacheUpkeep(held, dropped) {
304
+ if (held.length === 0 && dropped.length === 0) return;
305
+ self.postMessage({ kind: "cache.conversations", held, dropped });
306
+ }
307
+ function refreshCached(ids) {
308
+ if (ids.length === 0) return;
309
+ const metas = readMetas(ids);
310
+ const held = [];
311
+ const dropped = [];
312
+ const done = /* @__PURE__ */ new Set();
313
+ for (const id of ids) {
314
+ const key = conversationKey(id);
315
+ if (done.has(key)) continue;
316
+ done.add(key);
317
+ const meta = metas.get(key) ?? null;
318
+ if (meta !== null) held.push(meta);
319
+ else dropped.push(id);
320
+ }
321
+ postCacheUpkeep(held, dropped);
322
+ }
323
+ function watchFor(msg) {
324
+ const held = client;
325
+ if (!held) return null;
326
+ const announce = EPOCH_ADVANCING_REQUESTS.has(msg.kind);
327
+ if (!announce && !EPOCH_UPKEEP_REQUESTS.has(msg.kind)) return null;
328
+ const list = () => held.listConversations();
329
+ try {
330
+ return { before: epochMap(list()), after: list, announce };
331
+ } catch {
332
+ return null;
333
+ }
334
+ }
335
+ function emitEpochAdvances(watch) {
336
+ const told = /* @__PURE__ */ new Set();
337
+ let metas;
338
+ try {
339
+ metas = watch.after();
340
+ } catch {
341
+ return told;
342
+ }
343
+ const advanced = advancedEpochs(watch.before, metas);
344
+ for (const meta of advanced) {
345
+ told.add(conversationKey(meta.id));
346
+ if (watch.announce) postConversationEvent(meta.id, meta.epoch, void 0, meta);
347
+ }
348
+ const { appeared, disappeared } = changedHoldings(watch.before, metas);
349
+ for (const meta of appeared) told.add(conversationKey(meta.id));
350
+ for (const id of disappeared) told.add(conversationKey(id));
351
+ postCacheUpkeep(watch.announce ? appeared : [...advanced, ...appeared], disappeared);
352
+ return told;
353
+ }
354
+ function sendLeftCopyBehind(msg, outcome, calls) {
355
+ if (!outcome.ok || calls !== 1) return true;
356
+ const sentAt = outcome.value?.epoch;
357
+ return typeof sentAt !== "number" || sentAt !== msg.heldEpoch;
358
+ }
359
+ function announceUpdated(updated, senders = /* @__PURE__ */ new Map(), removed = []) {
360
+ if (updated.length === 0 && removed.length === 0) return;
361
+ const metas = readMetas([
362
+ ...updated.map((u) => u.conversation_id),
363
+ ...removed.map((r) => r.conversation_id)
364
+ ]);
365
+ const told = /* @__PURE__ */ new Set();
366
+ for (const u of updated) {
367
+ const key = conversationKey(u.conversation_id);
368
+ told.add(key);
369
+ postConversationEvent(u.conversation_id, u.epoch, senders.get(key), metas.get(key) ?? null);
370
+ }
371
+ const held = [];
372
+ const dropped = [];
373
+ for (const r of removed) {
374
+ const key = conversationKey(r.conversation_id);
375
+ if (told.has(key)) continue;
376
+ told.add(key);
377
+ const meta = metas.get(key) ?? null;
378
+ if (meta !== null) held.push(meta);
379
+ else dropped.push(r.conversation_id);
380
+ }
381
+ postCacheUpkeep(held, dropped);
382
+ }
383
+ function welcomeSenders(items, joined) {
384
+ const out = /* @__PURE__ */ new Map();
385
+ if (joined.length === 0) return out;
386
+ const wanted = new Set(joined.map((id) => conversationKey(id)));
387
+ for (const item of items) {
388
+ if (item.envelope.kind !== "Welcome") continue;
389
+ const key = conversationKey(item.envelope.conversation_id);
390
+ if (wanted.has(key) && !out.has(key)) out.set(key, item.envelope.sender_device);
391
+ }
392
+ return out;
393
+ }
394
+ var CONVERSATION_REQUESTS = /* @__PURE__ */ new Set([
395
+ "addMembers",
396
+ "addMembersWithVerdicts",
397
+ "reAdmitDevice",
398
+ "removeMembers",
399
+ "removeOwnOtherLeaves",
400
+ "removeMembersByIdentity",
401
+ "commitPendingProposals",
402
+ "setConversationName",
403
+ "setConversationRoles",
404
+ "syncConversation",
405
+ "leaveConversation",
406
+ "dropConversationLocal"
407
+ ]);
408
+ var CONVERSATION_RESULT_REQUESTS = /* @__PURE__ */ new Set([
409
+ "createConversation",
410
+ "createCallConversation",
411
+ "importStateSnapshot"
412
+ ]);
413
+ function conversationTouched(msg, value) {
414
+ if (CONVERSATION_REQUESTS.has(msg.kind)) {
415
+ const conv = msg.conv;
416
+ return conv instanceof Uint8Array ? conv : null;
417
+ }
418
+ if (CONVERSATION_RESULT_REQUESTS.has(msg.kind)) {
419
+ return value instanceof Uint8Array ? value : null;
420
+ }
421
+ return null;
422
+ }
423
+ function conversationsOfFailedApply(msg) {
424
+ switch (msg.kind) {
425
+ case "processEnvelope":
426
+ return [msg.envelope.conversation_id];
427
+ case "joinConversation":
428
+ case "joinConversationAt":
429
+ case "processWelcomeAt":
430
+ return [msg.welcome.conversation_id];
431
+ case "syncConversationStep":
432
+ return [msg.conv];
433
+ case "processSequencedBatch":
434
+ return msg.items.map((item) => item.envelope.conversation_id);
435
+ default:
436
+ return [];
437
+ }
438
+ }
439
+ function reportConversations(msg, watch, outcome, calls) {
440
+ try {
441
+ const told = watch ? emitEpochAdvances(watch) : /* @__PURE__ */ new Set();
442
+ const touched = conversationTouched(msg, outcome.ok ? outcome.value : void 0);
443
+ const owed = outcome.ok ? [] : conversationsOfFailedApply(msg);
444
+ if (touched !== null) owed.push(touched);
445
+ if (msg.kind === "send" && sendLeftCopyBehind(msg, outcome, calls)) owed.push(msg.conv);
446
+ refreshCached(owed.filter((id) => id instanceof Uint8Array && !told.has(conversationKey(id))));
447
+ } catch {
448
+ }
449
+ }
450
+ async function runRequest(msg) {
451
+ const watch = watchFor(msg);
452
+ const callsBefore = transportCalls;
453
+ try {
454
+ const value = await dispatch(msg);
455
+ reportConversations(msg, watch, { ok: true, value }, transportCalls - callsBefore);
456
+ self.postMessage({ kind: "result", id: msg.id, ok: true, value });
457
+ } catch (e) {
458
+ reportConversations(msg, watch, { ok: false }, transportCalls - callsBefore);
459
+ self.postMessage({
460
+ kind: "result",
461
+ id: msg.id,
462
+ ok: false,
463
+ error: e instanceof Error ? e.message : String(e)
464
+ });
465
+ }
466
+ }
467
+ self.onmessage = (ev) => {
468
+ const msg = ev.data;
469
+ if (msg.kind === "storage.reply") {
470
+ const slot = pendingStorage.get(msg.id);
471
+ if (slot) {
472
+ pendingStorage.delete(msg.id);
473
+ msg.ok ? slot({ ok: true, value: msg.value }) : slot({ ok: false, value: msg.error });
474
+ }
475
+ return;
476
+ }
477
+ if (msg.kind === "transport.reply") {
478
+ const slot = pendingTransport.get(msg.id);
479
+ if (slot) {
480
+ pendingTransport.delete(msg.id);
481
+ msg.ok ? slot({ ok: true, value: msg.value }) : slot({ ok: false, value: msg.error });
482
+ }
483
+ return;
484
+ }
485
+ if (msg.kind === "syncConversations") {
486
+ scheduler.enqueueStepped(catchUpPassStepper(msg));
487
+ return;
488
+ }
489
+ if (msg.kind === "syncConversationStep" && msg.stepped === true) {
490
+ scheduler.enqueueStepped(async () => {
491
+ await runRequest(msg);
492
+ return false;
493
+ });
494
+ return;
495
+ }
496
+ scheduler.enqueue(() => runRequest(msg));
497
+ };
498
+ function catchUpPassStepper(msg) {
499
+ const post = (m) => self.postMessage(m);
500
+ let pass = null;
501
+ return async () => {
502
+ if (pass === null) {
503
+ try {
504
+ await ensureWasm();
505
+ ensureClient();
506
+ } catch (e) {
507
+ post({
508
+ kind: "result",
509
+ id: msg.id,
510
+ ok: false,
511
+ error: e instanceof Error ? e.message : String(e)
512
+ });
513
+ return false;
514
+ }
515
+ pass = catchUpPass({
516
+ listConversationIds: () => ensureClient().listConversations().map((meta) => meta.id),
517
+ fetchHeads: async () => transportFeatures.fetchLogHeads ? await fetchLogHeadsProxy() ?? null : null,
518
+ conversationsBehind: (heads) => ensureClient().conversationsBehind(heads),
519
+ step: async (id) => {
520
+ try {
521
+ return await ensureClient().syncConversationStep(id, msg.nowMs);
522
+ } catch (e) {
523
+ refreshCached([id]);
524
+ throw e;
525
+ }
526
+ },
527
+ onPage: (page) => {
528
+ announceUpdated(page.updated, void 0, page.removed);
529
+ if (page.messages.length > 0) {
530
+ post({ kind: "event.batch", messages: page.messages, source: "page" });
531
+ }
532
+ },
533
+ finish: (ok, value) => {
534
+ if (ok) {
535
+ post({ kind: "result", id: msg.id, ok: true, value });
536
+ } else {
537
+ post({
538
+ kind: "result",
539
+ id: msg.id,
540
+ ok: false,
541
+ error: value instanceof Error ? value.message : String(value)
542
+ });
543
+ }
544
+ }
545
+ });
546
+ }
547
+ return pass();
548
+ };
549
+ }
550
+ async function dispatch(msg) {
551
+ await ensureWasm();
552
+ switch (msg.kind) {
553
+ case "init": {
554
+ transportFeatures = msg.transportFeatures ?? { fetchLogSince: false, fetchLogHeads: false };
555
+ client = await import_ping_wasm.PingClient.init(
556
+ msg.identityExport,
557
+ msg.deviceLabel,
558
+ makeProxyStorage(msg.storageFeatures),
559
+ makeProxyTransport(transportFeatures),
560
+ msg.nowMs,
561
+ // Optional Ed25519 device signing secret — see protocol.ts
562
+ // and ClientConfig.deviceSigningSecretKey. Forwarding `null`
563
+ // explicitly when absent so the wasm-bindgen `Option<Vec<u8>>`
564
+ // shape is matched correctly.
565
+ msg.deviceSigningSecretKey ?? null,
566
+ // The owner each conversation's FIRST roles write must name
567
+ // (2026-11-04, round 2); `null` for none.
568
+ msg.expectedOwners ?? null
569
+ );
570
+ client.onMessage((m) => {
571
+ self.postMessage({ kind: "event.message", msg: m });
572
+ });
573
+ return null;
574
+ }
575
+ case "openReadOnly": {
576
+ client = await import_ping_wasm.PingClient.openReadOnly(
577
+ msg.identityExport,
578
+ msg.deviceLabel,
579
+ makeProxyStorage(msg.storageFeatures),
580
+ proxyTransport,
581
+ msg.nowMs
582
+ );
583
+ return null;
584
+ }
585
+ case "previewEnvelope":
586
+ return ensureClient().previewEnvelope(msg.envelope, msg.nowMs);
587
+ case "generateIdentity":
588
+ return import_ping_wasm.PingClient.generateIdentity();
589
+ case "userId":
590
+ return ensureClient().userId();
591
+ case "exportIdentity":
592
+ return ensureClient().exportIdentity();
593
+ case "rotateIdentity":
594
+ return await ensureClient().rotateIdentity(msg.newIdentityExport, msg.nowMs);
595
+ case "rotateIdentityRetry":
596
+ return await ensureClient().rotateIdentityRetry(msg.conv, msg.nowMs);
597
+ case "deviceId":
598
+ return ensureClient().deviceId();
599
+ case "suspendStorage":
600
+ return ensureClient().suspendStorage();
601
+ case "resumeStorage":
602
+ return ensureClient().resumeStorage();
603
+ case "freshKeyPackage":
604
+ return ensureClient().freshKeyPackage();
605
+ case "freshLastResortKeyPackage":
606
+ return ensureClient().freshLastResortKeyPackage();
607
+ case "createConversation":
608
+ return await ensureClient().createConversation(msg.name ?? void 0, msg.nowMs);
609
+ case "createCallConversation":
610
+ return await ensureClient().createCallConversation(msg.name ?? void 0, msg.nowMs);
611
+ case "joinConversation": {
612
+ const id = await ensureClient().joinConversation(msg.welcome, msg.nowMs);
613
+ postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));
614
+ return id;
615
+ }
616
+ case "listConversations":
617
+ return ensureClient().listConversations();
618
+ case "conversationMeta":
619
+ return ensureClient().conversationMeta(msg.conv) ?? null;
620
+ case "strandedConversations":
621
+ return ensureClient().strandedConversations();
622
+ case "conversationsLeaving":
623
+ return ensureClient().conversationsLeaving();
624
+ case "conversationsLeaveStalled":
625
+ return ensureClient().conversationsLeaveStalled();
626
+ case "readmitPendingConversations":
627
+ return ensureClient().readmitPendingConversations(msg.nowMs);
628
+ case "undeliverableCount":
629
+ return ensureClient().undeliverableCount();
630
+ case "members":
631
+ return ensureClient().members(msg.conv);
632
+ case "conversationPolicy":
633
+ return ensureClient().conversationPolicy(msg.conv);
634
+ case "setExpectedOwners":
635
+ return ensureClient().setExpectedOwners(msg.entries);
636
+ case "setConversationRoles":
637
+ return await ensureClient().setConversationRoles(msg.conv, msg.owner, msg.admins, msg.nowMs);
638
+ case "send":
639
+ return await ensureClient().send(msg.conv, msg.plaintext, msg.nowMs);
640
+ case "addMembers":
641
+ return await ensureClient().addMembers(msg.conv, msg.entries, msg.nowMs);
642
+ case "addMembersWithVerdicts":
643
+ return await ensureClient().addMembersWithVerdicts(msg.conv, msg.entries, msg.nowMs);
644
+ case "reAdmitDevice":
645
+ return await ensureClient().reAdmitDevice(msg.conv, msg.entry, msg.nowMs);
646
+ case "mayReadmit":
647
+ return ensureClient().mayReadmit(msg.conv, msg.identity, msg.deviceId);
648
+ case "keyPackageIdentity":
649
+ return ensureClient().keyPackageIdentity(msg.keyPackage);
650
+ case "setConversationName":
651
+ return await ensureClient().setConversationName(msg.conv, msg.name ?? void 0, msg.nowMs);
652
+ case "admitDeviceToChats":
653
+ return await ensureClient().admitDeviceToChats(msg.deviceId, msg.entries, msg.nowMs);
654
+ case "admitDeviceToChatsConcurrent":
655
+ return await ensureClient().admitDeviceToChatsConcurrent(
656
+ msg.deviceId,
657
+ msg.entries,
658
+ msg.nowMs,
659
+ msg.concurrency
660
+ );
661
+ case "removeMembers":
662
+ return await ensureClient().removeMembers(msg.conv, new Uint32Array(msg.leaves), msg.nowMs);
663
+ case "removeOwnOtherLeaves":
664
+ return await ensureClient().removeOwnOtherLeaves(msg.conv, msg.nowMs);
665
+ case "removeMembersByIdentity":
666
+ return await ensureClient().removeMembersByIdentity(msg.conv, msg.identities, msg.nowMs);
667
+ case "leaveConversation":
668
+ return await ensureClient().leaveConversation(msg.conv, msg.nowMs);
669
+ case "dropConversationLocal":
670
+ return await ensureClient().dropConversationLocal(msg.conv);
671
+ case "conversationsWithPendingProposals":
672
+ return ensureClient().conversationsWithPendingProposals();
673
+ case "commitPendingProposals":
674
+ return await ensureClient().commitPendingProposals(msg.conv, msg.nowMs);
675
+ case "pendingProposalsCommitRank":
676
+ return ensureClient().pendingProposalsCommitRank(msg.conv) ?? null;
677
+ case "commitsInDoubt":
678
+ return ensureClient().commitsInDoubt();
679
+ case "revokeDevice":
680
+ return await ensureClient().revokeDevice(msg.deviceId, msg.nowMs);
681
+ case "removeDeviceEverywhere":
682
+ return await ensureClient().removeDeviceEverywhere(msg.deviceId, msg.nowMs);
683
+ case "removeOwnDevicesExcept":
684
+ return await ensureClient().removeOwnDevicesExcept(msg.keep, msg.listed, msg.nowMs);
685
+ case "processEnvelope": {
686
+ const result = await ensureClient().processEnvelope(msg.envelope, msg.nowMs);
687
+ postConversationEvent(
688
+ msg.envelope.conversation_id,
689
+ msg.envelope.epoch,
690
+ void 0,
691
+ readMeta(msg.envelope.conversation_id)
692
+ );
693
+ return result;
694
+ }
695
+ case "pendingApplies":
696
+ return ensureClient().pendingApplies();
697
+ case "confirmApplied":
698
+ return await ensureClient().confirmApplied(msg.journalIds);
699
+ case "syncConversations":
700
+ return await ensureClient().syncConversations(msg.nowMs);
701
+ case "syncConversation":
702
+ return await ensureClient().syncConversation(msg.conv, msg.nowMs);
703
+ // Sequenced log sync. The batch and page results carry their messages
704
+ // (the wasm does not fan them out through `onMessage`); the main thread
705
+ // delivers them from the result. Conversation updates are announced from
706
+ // the core's exact `updated` list, before the result resolves.
707
+ case "processSequencedBatch": {
708
+ const raw = await ensureClient().processSequencedBatch(msg.items, msg.nowMs);
709
+ announceUpdated(raw.updated, welcomeSenders(msg.items, raw.joined), raw.removed);
710
+ return raw;
711
+ }
712
+ case "syncConversationStep": {
713
+ const raw = await ensureClient().syncConversationStep(msg.conv, msg.nowMs);
714
+ announceUpdated(raw.updated, void 0, raw.removed);
715
+ return raw;
716
+ }
717
+ case "logPositions":
718
+ return ensureClient().logPositions();
719
+ case "logPosition":
720
+ return ensureClient().logPosition(msg.conv);
721
+ case "adoptLogPosition":
722
+ return await ensureClient().adoptLogPosition(msg.conv, msg.epoch, msg.serverSeq);
723
+ case "conversationsBehind":
724
+ return ensureClient().conversationsBehind(msg.heads);
725
+ case "heldFrameCount":
726
+ return ensureClient().heldFrameCount();
727
+ case "joinConversationAt": {
728
+ const id = await ensureClient().joinConversationAt(msg.welcome, msg.position, msg.nowMs);
729
+ postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));
730
+ return id;
731
+ }
732
+ case "processWelcomeAt": {
733
+ const id = await ensureClient().processWelcomeAt(msg.welcome, msg.position, msg.nowMs);
734
+ if (id !== null && id !== void 0) {
735
+ postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));
736
+ return id;
737
+ }
738
+ return null;
739
+ }
740
+ case "buildLinkingTicket":
741
+ return await ensureClient().buildLinkingTicket(
742
+ msg.newDeviceId,
743
+ msg.newDeviceKp,
744
+ msg.lastAppEvents,
745
+ msg.nowMs
746
+ );
747
+ case "consumeLinkingTicket":
748
+ await ensureClient().consumeLinkingTicket(msg.ticket, msg.nowMs);
749
+ return null;
750
+ case "decodeCatchupSnapshot":
751
+ return (0, import_ping_wasm.decodeCatchupSnapshot)(msg.snapshotBytes);
752
+ case "exportConversationSecret":
753
+ return ensureClient().exportConversationSecret(
754
+ msg.conv,
755
+ msg.label,
756
+ msg.context,
757
+ msg.length
758
+ );
759
+ case "sealLinkingTicket":
760
+ return (0, import_ping_wasm.sealLinkingTicket)(msg.ticket, msg.newDevicePub);
761
+ case "openLinkingTicket":
762
+ return (0, import_ping_wasm.openLinkingTicket)(msg.sealed, msg.newDevicePriv);
763
+ case "hpkeSeal":
764
+ return (0, import_ping_wasm.hpkeSeal)(msg.plaintext, msg.recipientPub, msg.info);
765
+ case "hpkeOpen":
766
+ return (0, import_ping_wasm.hpkeOpen)(msg.sealed, msg.recipientPriv, msg.info);
767
+ case "hpkeSealRaw":
768
+ return (0, import_ping_wasm.hpkeSealRaw)(msg.plaintext, msg.recipientPub, msg.info);
769
+ case "hpkeOpenRaw":
770
+ return (0, import_ping_wasm.hpkeOpenRaw)(msg.sealed, msg.recipientPriv, msg.info);
771
+ case "hpkeGenerateKeypair":
772
+ return (0, import_ping_wasm.hpkeGenerateKeypair)();
773
+ // Post-quantum (X-Wing) twins: all pure WASM, no client state required.
774
+ case "sealLinkingTicketPq":
775
+ return (0, import_ping_wasm.sealLinkingTicketPq)(msg.ticket, msg.newDevicePub);
776
+ case "openLinkingTicketPq":
777
+ return (0, import_ping_wasm.openLinkingTicketPq)(msg.sealed, msg.newDevicePriv);
778
+ case "hpkeSealPq":
779
+ return (0, import_ping_wasm.hpkeSealPq)(msg.plaintext, msg.recipientPub, msg.info);
780
+ case "hpkeOpenPq":
781
+ return (0, import_ping_wasm.hpkeOpenPq)(msg.sealed, msg.recipientPriv, msg.info);
782
+ case "hpkeSealRawPq":
783
+ return (0, import_ping_wasm.hpkeSealRawPq)(msg.plaintext, msg.recipientPub, msg.info);
784
+ case "hpkeOpenRawPq":
785
+ return (0, import_ping_wasm.hpkeOpenRawPq)(msg.sealed, msg.recipientPriv, msg.info);
786
+ case "hpkeGenerateKeypairPq":
787
+ return (0, import_ping_wasm.hpkeGenerateKeypairPq)();
788
+ case "hpkePublicKeyFromSeed":
789
+ return (0, import_ping_wasm.hpkePublicKeyFromSeed)(msg.seed);
790
+ case "deviceGroupIdFor":
791
+ return (0, import_ping_wasm.deviceGroupIdFor)(msg.userId);
792
+ case "hpkePublicKeyFromPrivate":
793
+ return (0, import_ping_wasm.hpkePublicKeyFromPrivate)(msg.privateKey);
794
+ case "signDeviceReauth":
795
+ return (0, import_ping_wasm.signDeviceReauth)(msg.deviceSigningSecretKey, msg.challengeId, msg.nonce, msg.accountId, msg.audience);
796
+ case "signDeviceLinkApproval":
797
+ return (0, import_ping_wasm.signDeviceLinkApproval)(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.newDevicePubkey, msg.audience);
798
+ case "signDeviceLinkPossession":
799
+ return (0, import_ping_wasm.signDeviceLinkPossession)(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.audience);
800
+ case "exportConversationStateSnapshot":
801
+ return ensureClient().exportConversationStateSnapshot(msg.conv, msg.nowMs);
802
+ case "importStateSnapshot":
803
+ return await ensureClient().importStateSnapshot(msg.snapshotBytes, msg.nowMs);
804
+ // Recovery — all pure WASM; no client state required.
805
+ case "generateMnemonicPhrase":
806
+ return (0, import_ping_wasm.generateMnemonicPhrase)();
807
+ case "normalizeMnemonicPhrase":
808
+ return (0, import_ping_wasm.normalizeMnemonicPhrase)(msg.phrase);
809
+ case "encryptBackup":
810
+ return (0, import_ping_wasm.encryptBackup)(
811
+ msg.mnemonicPhrase,
812
+ msg.accountId,
813
+ msg.identityExport,
814
+ msg.deviceGroupSnapshot,
815
+ // Map idiomatic camelCase → the snake_case keys serde expects on the
816
+ // WASM boundary (matches the decrypt view's account_id / group_state_bytes).
817
+ msg.conversationSnapshots.map((c) => ({
818
+ conversation_id: c.conversationId,
819
+ group_state_bytes: c.groupStateBytes
820
+ })),
821
+ msg.createdAtMs
822
+ );
823
+ case "decryptBackup":
824
+ return (0, import_ping_wasm.decryptBackup)(msg.blob, msg.mnemonicPhrase);
825
+ case "sealHistoryBundle":
826
+ return (0, import_ping_wasm.sealHistoryBundle)(msg.bundle, msg.recipientPub, msg.senderIdentitySecret);
827
+ case "openHistoryBundle":
828
+ return (0, import_ping_wasm.openHistoryBundle)(msg.sealed, msg.recipientPriv, msg.senderIdentityPub);
829
+ case "sealHistoryBundlePq":
830
+ return (0, import_ping_wasm.sealHistoryBundlePq)(msg.bundle, msg.recipientPub, msg.senderIdentitySecret);
831
+ case "openHistoryBundlePq":
832
+ return (0, import_ping_wasm.openHistoryBundlePq)(msg.sealed, msg.recipientPriv, msg.senderIdentityPub);
833
+ default:
834
+ throw new Error(`unknown request kind: ${msg.kind}`);
835
+ }
836
+ }
837
+ function ensureClient() {
838
+ if (!client) throw new Error("client not initialised");
839
+ return client;
840
+ }
841
+ //# sourceMappingURL=worker.cjs.map