@ping-app/ping-openmls-sdk 0.10.2 → 0.10.3
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.
- package/dist/index.cjs +50 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +35 -3
- package/dist/index.d.ts +35 -3
- package/dist/index.js +49 -0
- package/dist/index.js.map +1 -1
- package/dist/notification-preview.d.cts +1 -1
- package/dist/notification-preview.d.ts +1 -1
- package/dist/storage/indexeddb.d.cts +1 -1
- package/dist/storage/indexeddb.d.ts +1 -1
- package/dist/transport/websocket.d.cts +1 -1
- package/dist/transport/websocket.d.ts +1 -1
- package/dist/{types-gAmJFSC-.d.cts → types-BOXvsHgp.d.cts} +30 -1
- package/dist/{types-gAmJFSC-.d.ts → types-BOXvsHgp.d.ts} +30 -1
- package/dist/worker.cjs +2 -0
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.js +3 -0
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/wasm/package.json +1 -1
- package/wasm/ping_wasm.d.ts +20 -2
- package/wasm/ping_wasm.js +60 -22
- package/wasm/ping_wasm_bg.wasm +0 -0
- package/wasm/ping_wasm_bg.wasm.d.ts +3 -2
package/dist/worker.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/wasm-memory.ts","../src/worker.ts","../src/epoch-events.ts","../src/catch-up-pass.ts","../src/request-lanes.ts"],"sourcesContent":["// Linear-memory reservation shared by every realm that instantiates the wasm.\n\n/**\n * Linear-memory headroom the worker reserves from JavaScript right after\n * instantiation, largest first; a target the engine refuses (`RangeError`)\n * falls through to the next. Sized so the Argon2id recovery backup\n * (64 MiB of blocks in ONE allocation) and a large history bundle fit\n * inside memory the module already owns.\n *\n * Why from JS and not inside the module: Safari/JSC (macOS 26 / iOS 26,\n * IPInt) crashes the WebContent process when the wasm `memory.grow`\n * INSTRUCTION runs in a Worker while the Web Inspector is attached — the GC\n * it triggers walks the stack and dies on the wasm frame. The same grow\n * requested through `WebAssembly.Memory.prototype.grow` has only JS frames\n * on the stack and is fine. The module's allocator (`ping-wasm/src/alloc.rs`)\n * claims these pages before it would ever execute the instruction itself.\n * The pages are virtual until touched, so an idle worker costs nothing extra.\n */\nexport const RESERVE_MIB_TARGETS = [192, 128, 64, 32] as const;\nconst WASM_PAGE_BYTES = 64 * 1024;\n\n/** Memories already reserved: `init` is idempotent per realm and returns the\n * same instance, so a second open must not grow it again. */\nconst reserved = new WeakSet<WebAssembly.Memory>();\n\nexport function reserveLinearMemory(memory: WebAssembly.Memory): void {\n if (reserved.has(memory)) return;\n reserved.add(memory);\n for (const mib of RESERVE_MIB_TARGETS) {\n try {\n memory.grow((mib * 1024 * 1024) / WASM_PAGE_BYTES);\n return;\n } catch {\n // Over the engine's limit for this memory; try a smaller reservation.\n }\n }\n}\n\n","// Web Worker entry. Owns the WASM `PingClient` instance. Receives Requests from the main thread\n// and posts Responses back. Storage / Transport calls back to the main thread are tracked by id.\n//\n// The WASM module is loaded lazily on the first `init` so that ephemeral identity-only spawns\n// (used by `MessagingClient.generateIdentity()`) don't pay the cost.\n\n/// <reference lib=\"webworker\" />\n\nimport { reserveLinearMemory } from \"./wasm-memory\";\nimport init, {\n PingClient,\n sealLinkingTicket as wasmSealLinkingTicket,\n openLinkingTicket as wasmOpenLinkingTicket,\n hpkeSeal as wasmHpkeSeal,\n hpkeOpen as wasmHpkeOpen,\n hpkeSealRaw as wasmHpkeSealRaw,\n hpkeOpenRaw as wasmHpkeOpenRaw,\n hpkeGenerateKeypair as wasmHpkeGenerateKeypair,\n sealLinkingTicketPq as wasmSealLinkingTicketPq,\n openLinkingTicketPq as wasmOpenLinkingTicketPq,\n hpkeSealPq as wasmHpkeSealPq,\n hpkeOpenPq as wasmHpkeOpenPq,\n hpkeSealRawPq as wasmHpkeSealRawPq,\n hpkeOpenRawPq as wasmHpkeOpenRawPq,\n hpkeGenerateKeypairPq as wasmHpkeGenerateKeypairPq,\n deviceGroupIdFor as wasmDeviceGroupIdFor,\n hpkePublicKeyFromSeed as wasmHpkePublicKeyFromSeed,\n hpkePublicKeyFromPrivate as wasmHpkePublicKeyFromPrivate,\n signDeviceReauth as wasmSignDeviceReauth,\n signDeviceLinkApproval as wasmSignDeviceLinkApproval,\n signDeviceLinkPossession as wasmSignDeviceLinkPossession,\n decodeCatchupSnapshot as wasmDecodeCatchupSnapshot,\n generateMnemonicPhrase as wasmGenerateMnemonicPhrase,\n normalizeMnemonicPhrase as wasmNormalizeMnemonicPhrase,\n encryptBackup as wasmEncryptBackup,\n decryptBackup as wasmDecryptBackup,\n sealHistoryBundle as wasmSealHistoryBundle,\n openHistoryBundle as wasmOpenHistoryBundle,\n sealHistoryBundlePq as wasmSealHistoryBundlePq,\n openHistoryBundlePq as wasmOpenHistoryBundlePq,\n} from \"../wasm/ping_wasm\";\nimport { catchUpPass } from \"./catch-up-pass\";\nimport {\n advancedEpochs, changedHoldings, type ConversationEpoch, conversationKey, epochMap,\n} from \"./epoch-events\";\nimport type { Request, Response, StorageFeatures, TransportFeatures } from \"./protocol\";\nimport { RequestScheduler } from \"./request-lanes\";\nimport type {\n ApplyBatchResultWire,\n ConversationRemovalWire,\n ConversationUpdateWire,\n LogHeadWire,\n SequencedEnvelopeWire,\n SyncStepResultWire,\n} from \"./sequenced\";\nimport type { ConversationMeta, DeviceId, IncomingMessage, MessageEnvelope } from \"./types\";\n\ndeclare const self: DedicatedWorkerGlobalScope;\n\nlet client: PingClient | null = null;\nlet wasmReady: Promise<void> | null = null;\n\nconst pendingStorage = new Map<number, (r: { ok: boolean; value: unknown }) => void>();\nconst pendingTransport = new Map<number, (r: { ok: boolean; value: unknown }) => void>();\nlet nextStorageId = 1;\nlet nextTransportId = 1;\n/** Calls made to the host transport so far. The worker runs one request at a\n * time, so the difference around a request is what that request sent and\n * fetched (see `sendLeftCopyBehind`). */\nlet transportCalls = 0;\n\nconst proxyStorage = {\n get: (namespace: string, key: string) => callMain<Uint8Array | null>(\"storage\", \"get\", [namespace, key]),\n put: (namespace: string, key: string, value: Uint8Array) =>\n callMain<void>(\"storage\", \"put\", [namespace, key, value]),\n del: (namespace: string, key: string) => callMain<void>(\"storage\", \"del\", [namespace, key]),\n listKeys: (namespace: string, prefix: string) =>\n callMain<string[]>(\"storage\", \"listKeys\", [namespace, prefix]),\n};\n// The two optional methods are declared on the proxy ONLY when the host\n// storage has them: the wasm bridge decides by their presence whether to hand\n// the per-row MLS store's delta to the host as one atomic batch (and read the\n// rows in one call) or to take its own journalled row-by-row fallback.\nconst applyBatchProxy = (namespace: string, puts: Array<[string, Uint8Array]>, deletes: string[]) =>\n callMain<void>(\"storage\", \"applyBatch\", [namespace, puts, deletes]);\nconst listEntriesProxy = (namespace: string, prefix: string) =>\n callMain<Array<[string, Uint8Array]>>(\"storage\", \"listEntries\", [namespace, prefix]);\nfunction makeProxyStorage(features: StorageFeatures | undefined) {\n return {\n ...proxyStorage,\n ...(features?.applyBatch ? { applyBatch: applyBatchProxy } : {}),\n ...(features?.listEntries ? { listEntries: listEntriesProxy } : {}),\n };\n}\nconst proxyTransport = {\n send: (envelope: MessageEnvelope) => callMain<void>(\"transport\", \"send\", [envelope]),\n // Always declared here: the main-thread dispatch emulates it with\n // sequential sends when the host transport has no `sendBatch`, encoding a\n // partial delivery with the `batch partial after <n>:` sentinel the wasm\n // bridge understands (see index.ts `BATCH_PARTIAL_PREFIX`).\n sendBatch: (envelopes: MessageEnvelope[]) => callMain<void>(\"transport\", \"sendBatch\", [envelopes]),\n fetchSince: (conv: Uint8Array, cursor: Uint8Array, limit: number) =>\n callMain<MessageEnvelope[]>(\"transport\", \"fetchSince\", [conv, cursor, limit]),\n discoverDevices: (userId: Uint8Array) => callMain<unknown[]>(\"transport\", \"discoverDevices\", [userId]),\n // Optional on the host (see `Transport.setNextWelcomeRecipients` in types.ts).\n // The main-thread dispatch (index.ts `handleWorker → case \"transport.call\"`)\n // resolves `undefined` to a `transport.reply { ok: true, value: undefined }`\n // when the host hasn't implemented the method, which we treat as a no-op.\n setNextWelcomeRecipients: (conv: Uint8Array, recipients: Uint8Array[]) =>\n callMain<void>(\"transport\", \"setNextWelcomeRecipients\", [conv, recipients]),\n};\n\n/** What the host transport declared at `init`; read by the catch-up pass. */\nlet transportFeatures: TransportFeatures = { fetchLogSince: false, fetchLogHeads: false };\n\nconst fetchLogSinceProxy = (position: unknown, limit: number) =>\n callMain<SequencedEnvelopeWire[] | null>(\"transport\", \"fetchLogSince\", [position, limit]);\nconst fetchLogHeadsProxy = () =>\n callMain<LogHeadWire[] | null | undefined>(\"transport\", \"fetchLogHeads\", []);\n\n/**\n * The transport proxy the wasm sees. Unlike `setNextWelcomeRecipients`, the\n * two sequenced-log methods are NOT always declared: the wasm bridge decides\n * by their presence whether to call them or fall back to the core default\n * (`fetchSince` at position 0; no heads), and `fetchLogSince` has no\n * main-thread emulation because only the core can encode the legacy cursor.\n */\nfunction makeProxyTransport(features: TransportFeatures) {\n return {\n ...proxyTransport,\n ...(features.fetchLogSince ? { fetchLogSince: fetchLogSinceProxy } : {}),\n ...(features.fetchLogHeads ? { fetchLogHeads: fetchLogHeadsProxy } : {}),\n };\n}\n\nfunction callMain<T>(kind: \"storage\" | \"transport\", method: string, args: unknown[]): Promise<T> {\n return new Promise((resolve, reject) => {\n const id = kind === \"storage\" ? nextStorageId++ : nextTransportId++;\n const map = kind === \"storage\" ? pendingStorage : pendingTransport;\n if (kind === \"transport\") transportCalls += 1;\n map.set(id, ({ ok, value }) => ok ? resolve(value as T) : reject(new Error(String(value))));\n self.postMessage({ kind: `${kind}.call`, id, method, args } as Response);\n });\n}\n\nasync function ensureWasm() {\n if (wasmReady) return wasmReady;\n // The bundled wasm path is rewritten by the build script to be relative to `dist/`.\n wasmReady = init().then((out) => {\n reserveLinearMemory(out.memory);\n });\n return wasmReady;\n}\n\n// The WASM `PingClient` is SINGLE-THREADED (this one worker). Its async\n// methods hold internal locks across `.await` (e.g. a `conversations`\n// RwLock guard kept while `snapshot_to_storage` awaits IndexedDB). If we\n// let `onmessage` dispatch a SECOND top-level request while the first is\n// suspended at an await, the two WASM calls interleave on the single\n// thread, the second re-acquires a held lock, and `parking_lot`'s wasm\n// stub `panic!`s with \"Parking not supported on this platform\" — which\n// poisons the module (`RuntimeError: unreachable`) and breaks every\n// subsequent call. We therefore SERIALIZE top-level request dispatch:\n// one WASM call runs to completion before the next begins.\n//\n// ONE CALL AT A TIME IS NOT THE SAME AS FIRST COME, FIRST SERVED. A\n// whole-account `syncConversations` used to be one request: every\n// conversation paged inside a single turn, one network round trip each,\n// and a `send` posted while it ran started only after the last of them.\n// On a tab returning from an idle hour that was the whole visible cost of\n// the first message: the composer cleared, the bubble sat on a clock for\n// the length of the pass, and the second message went out at once. The\n// scheduler below keeps the one-call invariant but runs a whole-account\n// pass as a sequence of per-conversation steps (`syncConversation`) and\n// lets everything else queued run between steps. Ordinary requests stay\n// FIFO among themselves, so the inbound ordering that per-conversation\n// chaining on the main thread relies on is untouched; a host's own\n// `syncConversation` for the chat the user is looking at is an ordinary\n// request too, so it runs ahead of the background pass.\n//\n// CRUCIAL: `storage.reply` / `transport.reply` are NOT serialized — an\n// in-flight request awaits those replies (via `callMain`), so queuing\n// them behind the request would deadlock. They resolve pending callbacks\n// immediately, exactly as before.\nconst scheduler = new RequestScheduler();\n\n// Requests that can advance a conversation's MLS epoch WITHOUT an inbound\n// envelope to announce it.\n//\n// `event.conversation` was only ever emitted from `processEnvelope` and\n// `joinConversation`, so it announced exactly one of the three ways an epoch\n// moves: a Commit received from someone else. The other two were invisible to\n// every consumer:\n//\n// 1. A commit THIS device authored. `MessagingClient.dispatchIncoming` drops\n// envelopes whose `sender_device` is ours (the relay echoes our own\n// sends), so the author's own commit never reaches `processEnvelope`.\n// A host that re-derives exported secrets on epoch change — call media\n// keys are the load-bearing case — therefore kept using the PREVIOUS\n// epoch's secret after adding a member, and went silent against everyone\n// who had rotated. It is specifically the device that INVITES that breaks.\n// 2. A commit applied during catch-up. `syncConversations` fetches and\n// applies envelopes but posted nothing, so a client that reconnected after\n// missing a commit resumed on a stale secret.\n//\n// Rather than enumerate emissions per operation (and miss the next one added),\n// the epoch map is snapshotted around these requests and any conversation whose\n// epoch actually MOVED is announced. Conversations are only compared, never\n// created, so this can never invent an event: a freshly joined conversation is\n// already announced by `joinConversation`, and one that disappears (leave/drop)\n// is not an epoch change.\n//\n// `send` is deliberately absent from this set: it is the hot path. It must not\n// pay for two `listConversations` calls, and it reports no conversation event\n// of its own. A send is not only an application message, though: before it\n// encrypts, the core settles a Commit this device left in doubt there and\n// commits pending proposals, and after it the core refreshes this device's\n// leaf when that is due. Each of those moves the epoch, and the first can land\n// a rename. The core reports such a move with the next batch or page, and\n// that is where the host hears it, once. Here the main thread's copy of the\n// conversation is only kept level with the group, and a send that moved\n// nothing reads nothing (see `sendLeftCopyBehind`).\nconst EPOCH_ADVANCING_REQUESTS: ReadonlySet<string> = new Set([\n \"addMembers\",\n \"addMembersWithVerdicts\",\n \"reAdmitDevice\",\n \"removeMembers\",\n \"removeOwnOtherLeaves\",\n \"removeMembersByIdentity\",\n \"commitPendingProposals\",\n \"setConversationName\",\n \"setConversationRoles\",\n \"admitDeviceToChats\",\n \"admitDeviceToChatsConcurrent\",\n \"revokeDevice\",\n \"removeDeviceEverywhere\",\n \"removeOwnDevicesExcept\",\n \"syncConversations\",\n \"syncConversation\",\n \"consumeLinkingTicket\",\n \"importStateSnapshot\",\n]);\n\n// Requests that commit and whose epoch move is NOT announced to the host: it\n// never was, and a new host event is not what keeps a handle fresh. The\n// conversations are compared around them all the same, and the main thread's\n// copy of each one that moved is brought level with `cache.conversations`,\n// which calls no listener. `buildLinkingTicket` commits to the DeviceGroup.\nconst EPOCH_UPKEEP_REQUESTS: ReadonlySet<string> = new Set([\n \"buildLinkingTicket\",\n]);\n\n// THE MAIN THREAD'S COPY OF A CONVERSATION'S METADATA\n//\n// The main thread keeps one `ConversationMeta` per conversation so that a\n// conversation handle can answer `name`, `epoch` and `meta()` without a round\n// trip. That copy used to be refilled by `listConversations()` only, so after\n// any change of a group it kept answering the metadata from before the change:\n// a host that carries a group's title and picture id in the name rebuilt the\n// name from the stale read and lost the picture on a rename.\n//\n// The rule now: every message that tells the main thread a conversation\n// changed CARRIES the conversation's metadata as the group holds it at that\n// moment, and the main thread stores it before it calls any host listener. A\n// request that changes a conversation without reporting an event (a creation,\n// a leave, a call whose Commit did not move the epoch, a `send` or a\n// `buildLinkingTicket` that moved one) says so with a\n// `cache.conversations` message before its `result`. Nothing here lists every\n// conversation to do it: the one conversation is read (`conversationMeta`), or\n// the record comes from a listing the request already paid for.\n\n/** One conversation's metadata as the group holds it now. `null`: the client\n * does not hold it (unknown, dropped, removed, or left) or it could not be\n * read; either way the main thread must not keep answering for it. */\nfunction readMeta(id: Uint8Array): ConversationMeta | null {\n if (!client) return null;\n try {\n return (client.conversationMeta(id) as ConversationMeta | null | undefined) ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Past this many conversations, one listing is cheaper than reading them one\n * at a time. The single read walks the client's conversations inside the\n * wasm and hands over one record; a listing hands over all of them and costs\n * about twelve single reads at any account size (measured at 100, 500 and\n * 2000 conversations). So the cost of bringing any number of conversations\n * up to date is bounded by one listing.\n */\nconst SINGLE_READS_MAX = 8;\n\n/** The metadata of each of `ids` as the groups hold it now, by\n * `conversationKey`; `null` for one the client does not hold. */\nfunction readMetas(ids: readonly Uint8Array[]): Map<string, ConversationMeta | null> {\n const out = new Map<string, ConversationMeta | null>();\n for (const id of ids) out.set(conversationKey(id), null);\n if (out.size <= SINGLE_READS_MAX) {\n for (const id of ids) out.set(conversationKey(id), readMeta(id));\n return out;\n }\n if (!client) return out;\n try {\n for (const meta of client.listConversations() as unknown as ConversationMeta[]) {\n const key = conversationKey(meta.id);\n if (out.has(key)) out.set(key, meta);\n }\n } catch {\n // Unreadable: every one of them stays `null`, and the main thread drops\n // its copies instead of keeping the old ones.\n }\n return out;\n}\n\n/** Tell the main thread a conversation changed, with its metadata as the\n * group holds it now (`null`: it is not held any more). */\nfunction postConversationEvent(\n id: Uint8Array,\n epoch: number,\n sender: DeviceId | undefined,\n meta: ConversationMeta | null,\n): void {\n (self.postMessage as (m: Response) => void)({\n kind: \"event.conversation\",\n id,\n epoch,\n ...(sender !== undefined ? { sender } : {}),\n ...(meta !== null ? { meta } : {}),\n });\n}\n\n/** Cache upkeep with no host event: what the main thread must hold now and\n * what it must forget. Posts nothing when there is nothing to say. */\nfunction postCacheUpkeep(held: ConversationMeta[], dropped: Uint8Array[]): void {\n if (held.length === 0 && dropped.length === 0) return;\n (self.postMessage as (m: Response) => void)({ kind: \"cache.conversations\", held, dropped });\n}\n\n/** Read each of `ids` and post the upkeep for them as one message. */\nfunction refreshCached(ids: readonly Uint8Array[]): void {\n if (ids.length === 0) return;\n const metas = readMetas(ids);\n const held: ConversationMeta[] = [];\n const dropped: Uint8Array[] = [];\n const done = new Set<string>();\n for (const id of ids) {\n const key = conversationKey(id);\n if (done.has(key)) continue;\n done.add(key);\n const meta = metas.get(key) ?? null;\n if (meta !== null) held.push(meta);\n else dropped.push(id);\n }\n postCacheUpkeep(held, dropped);\n}\n\n/**\n * What a request is watched over: the epoch of every conversation the client\n * held before it ran (one listing), and how to list them again after it.\n * `announce` says what a moved epoch becomes: a host event (the requests in\n * `EPOCH_ADVANCING_REQUESTS`) or upkeep of the main thread's copy only (the\n * requests in `EPOCH_UPKEEP_REQUESTS`).\n */\ninterface EpochWatch {\n before: Map<string, number>;\n after(): ConversationMeta[];\n announce: boolean;\n}\n\n/** The watch for `msg`, or `null` when it needs none or the conversations\n * could not be read: no epoch change is reported for that request then, and\n * nothing is concluded from an absence. */\nfunction watchFor(msg: Request): EpochWatch | null {\n const held = client;\n if (!held) return null;\n const announce = EPOCH_ADVANCING_REQUESTS.has(msg.kind);\n if (!announce && !EPOCH_UPKEEP_REQUESTS.has(msg.kind)) return null;\n const list = (): ConversationMeta[] => held.listConversations() as unknown as ConversationMeta[];\n try {\n return { before: epochMap(list()), after: list, announce };\n } catch {\n // A client mid-teardown (or a storage read failure) is not a reason to\n // fail the request the caller actually made.\n return null;\n }\n}\n\n/**\n * Tell the main thread about every watched conversation whose epoch moved,\n * each with the metadata just read: as a host event when the watch announces,\n * as cache upkeep when it does not. The conversations the request brought in\n * or took away are cache upkeep either way. Returns the keys of every\n * conversation the main thread was told about, so the caller does not read\n * one of them a second time.\n */\nfunction emitEpochAdvances(watch: EpochWatch): Set<string> {\n const told = new Set<string>();\n let metas: ConversationMeta[];\n try {\n metas = watch.after();\n } catch {\n return told;\n }\n const advanced = advancedEpochs(watch.before, metas);\n for (const meta of advanced) {\n told.add(conversationKey(meta.id));\n if (watch.announce) postConversationEvent(meta.id, meta.epoch, undefined, meta);\n }\n const { appeared, disappeared } = changedHoldings(watch.before, metas);\n for (const meta of appeared) told.add(conversationKey(meta.id));\n for (const id of disappeared) told.add(conversationKey(id));\n postCacheUpkeep(watch.announce ? appeared : [...advanced, ...appeared], disappeared);\n return told;\n}\n\n/**\n * Whether the main thread's copy of the conversation a `send` named may be\n * behind the group now. Answered from what the worker already holds, so a\n * send that moved nothing reads nothing:\n *\n * - The envelope the send produced carries the epoch it was encrypted at,\n * and the main thread sent the epoch of its own copy with the request.\n * Everything the core does BEFORE it encrypts shows in that comparison:\n * settling a Commit this device left in doubt, committing pending\n * proposals, applying another member's Commits from the log.\n * - The one thing the core does AFTER it encrypts is the refresh of this\n * device's leaf: a Commit, merged only once the transport accepted it. A\n * send that moved nothing makes exactly one transport call, the message\n * itself, so any other count means something else was sent or fetched.\n *\n * A send that failed produced no envelope to compare, so the conversation is\n * read. In every case the cost is at most ONE read of the one conversation,\n * made after the send; never a listing, and never a host event.\n */\nfunction sendLeftCopyBehind(\n msg: Extract<Request, { kind: \"send\" }>,\n outcome: { ok: true; value: unknown } | { ok: false },\n calls: number,\n): boolean {\n if (!outcome.ok || calls !== 1) return true;\n const sentAt = (outcome.value as { epoch?: unknown } | null | undefined)?.epoch;\n return typeof sentAt !== \"number\" || sentAt !== msg.heldEpoch;\n}\n\n/**\n * Announce the conversations a batch or page moved. The sequenced paths\n * report `updated` exactly (the core lists every conversation whose epoch\n * moved or that was joined), so there is nothing to diff: one event per\n * entry, each with the conversation's metadata read at that moment.\n * `senders` labels a join with the inviter's device, as `joinConversation`\n * does. `removed` are the conversations the batch took this device out of:\n * no host event (the result reports them), but the main thread's copy of\n * each is brought to what the client holds now.\n */\nfunction announceUpdated(\n updated: ConversationUpdateWire[],\n senders: Map<string, DeviceId> = new Map(),\n removed: ConversationRemovalWire[] = [],\n): void {\n if (updated.length === 0 && removed.length === 0) return;\n const metas = readMetas([\n ...updated.map((u) => u.conversation_id),\n ...removed.map((r) => r.conversation_id),\n ]);\n const told = new Set<string>();\n for (const u of updated) {\n const key = conversationKey(u.conversation_id);\n told.add(key);\n postConversationEvent(u.conversation_id, u.epoch, senders.get(key), metas.get(key) ?? null);\n }\n const held: ConversationMeta[] = [];\n const dropped: Uint8Array[] = [];\n for (const r of removed) {\n const key = conversationKey(r.conversation_id);\n if (told.has(key)) continue;\n told.add(key);\n const meta = metas.get(key) ?? null;\n if (meta !== null) held.push(meta);\n else dropped.push(r.conversation_id);\n }\n postCacheUpkeep(held, dropped);\n}\n\n/** The inviter's device for every conversation a batch joined, from the\n * Welcome that joined it. */\nfunction welcomeSenders(items: SequencedEnvelopeWire[], joined: Uint8Array[]): Map<string, DeviceId> {\n const out = new Map<string, DeviceId>();\n if (joined.length === 0) return out;\n const wanted = new Set(joined.map((id) => conversationKey(id)));\n for (const item of items) {\n if (item.envelope.kind !== \"Welcome\") continue;\n const key = conversationKey(item.envelope.conversation_id);\n if (wanted.has(key) && !out.has(key)) out.set(key, item.envelope.sender_device);\n }\n return out;\n}\n\n// Requests after which ONE conversation's metadata on the main thread must be\n// what the group holds, whether or not an event said so: this device's own\n// calls on a conversation. When the call moved the epoch, the event above\n// already carried the metadata and nothing more is read. When it did not (the\n// call failed, its Commit is in doubt, the conversation is now left or\n// dropped), the one conversation is read once, here.\nconst CONVERSATION_REQUESTS: ReadonlySet<string> = new Set([\n \"addMembers\",\n \"addMembersWithVerdicts\",\n \"reAdmitDevice\",\n \"removeMembers\",\n \"removeOwnOtherLeaves\",\n \"removeMembersByIdentity\",\n \"commitPendingProposals\",\n \"setConversationName\",\n \"setConversationRoles\",\n \"syncConversation\",\n \"leaveConversation\",\n \"dropConversationLocal\",\n]);\n\n// Requests that resolve to the id of a conversation they brought in.\nconst CONVERSATION_RESULT_REQUESTS: ReadonlySet<string> = new Set([\n \"createConversation\",\n \"createCallConversation\",\n \"importStateSnapshot\",\n]);\n\n/** The conversation a finished request must leave fresh on the main thread. */\nfunction conversationTouched(msg: Request, value: unknown): Uint8Array | null {\n if (CONVERSATION_REQUESTS.has(msg.kind)) {\n const conv = (msg as { conv?: unknown }).conv;\n return conv instanceof Uint8Array ? conv : null;\n }\n if (CONVERSATION_RESULT_REQUESTS.has(msg.kind)) {\n return value instanceof Uint8Array ? value : null;\n }\n return null;\n}\n\n/**\n * The conversations a request that applies inbound frames named. When such a\n * request succeeds, the events it posted carried the metadata. When it\n * THROWS it posted nothing, yet the group may have moved before the throw (a\n * Commit merged, then the checkpoint failed), so each conversation it named\n * is read once and the main thread's copy follows. No host event: a failed\n * apply never announced one.\n */\nfunction conversationsOfFailedApply(msg: Request): Uint8Array[] {\n switch (msg.kind) {\n case \"processEnvelope\":\n return [msg.envelope.conversation_id];\n case \"joinConversation\":\n case \"joinConversationAt\":\n case \"processWelcomeAt\":\n return [msg.welcome.conversation_id];\n case \"syncConversationStep\":\n return [msg.conv];\n case \"processSequencedBatch\":\n return msg.items.map((item) => item.envelope.conversation_id);\n default:\n return [];\n }\n}\n\n/** Everything the main thread must know about conversations before it hears\n * the request's outcome. `calls` is how many transport calls the request\n * made. Never throws. */\nfunction reportConversations(\n msg: Request,\n watch: EpochWatch | null,\n outcome: { ok: true; value: unknown } | { ok: false },\n calls: number,\n): void {\n try {\n const told = watch ? emitEpochAdvances(watch) : new Set<string>();\n const touched = conversationTouched(msg, outcome.ok ? outcome.value : undefined);\n const owed = outcome.ok ? [] : conversationsOfFailedApply(msg);\n if (touched !== null) owed.push(touched);\n if (msg.kind === \"send\" && sendLeftCopyBehind(msg, outcome, calls)) owed.push(msg.conv);\n refreshCached(owed.filter((id) => id instanceof Uint8Array && !told.has(conversationKey(id))));\n } catch {\n // Reporting is never a reason to fail the request the caller made.\n }\n}\n\nasync function runRequest(msg: Request): Promise<void> {\n // Snapshot BEFORE the request and diff after, so a self-authored commit or a\n // catch-up-applied one is announced like any other epoch change.\n const watch = watchFor(msg);\n const callsBefore = transportCalls;\n try {\n const value = await dispatch(msg);\n // Announce the epoch change BEFORE resolving the caller, so a host that\n // awaits `addMembers` and then reads a derived secret cannot observe the\n // new epoch before being told about it. The same order is what makes the\n // conversation handle fresh when the call resolves.\n reportConversations(msg, watch, { ok: true, value }, transportCalls - callsBefore);\n (self.postMessage as (m: Response) => void)({ kind: \"result\", id: msg.id, ok: true, value });\n } catch (e) {\n // A failed request can still have advanced the epoch (a commit that merged\n // locally before a later step threw), so report the change either way.\n reportConversations(msg, watch, { ok: false }, transportCalls - callsBefore);\n (self.postMessage as (m: Response) => void)({\n kind: \"result\", id: msg.id, ok: false, error: e instanceof Error ? e.message : String(e),\n });\n }\n}\n\nself.onmessage = (ev: MessageEvent<Request>) => {\n const msg = ev.data;\n\n // Storage / transport responses from the main thread — handle\n // immediately (they unblock the in-flight request). Never queued.\n if (msg.kind === \"storage.reply\") {\n const slot = pendingStorage.get(msg.id);\n if (slot) {\n pendingStorage.delete(msg.id);\n msg.ok ? slot({ ok: true, value: msg.value })\n : slot({ ok: false, value: msg.error });\n }\n return;\n }\n if (msg.kind === \"transport.reply\") {\n const slot = pendingTransport.get(msg.id);\n if (slot) {\n pendingTransport.delete(msg.id);\n msg.ok ? slot({ ok: true, value: msg.value })\n : slot({ ok: false, value: msg.error });\n }\n return;\n }\n\n // Top-level client request. A whole-account catch-up becomes a stepped\n // pass the scheduler runs one conversation per turn, behind everything\n // else queued; every other request runs FIFO, one WASM call at a time.\n // `runRequest` and the pass stepper never reject (errors are posted as\n // results), so the scheduler can't wedge.\n if (msg.kind === \"syncConversations\") {\n scheduler.enqueueStepped(catchUpPassStepper(msg));\n return;\n }\n // The SDK's own gap fill: one page per turn on the stepped lane, so a\n // send posted while a long fill runs goes between pages.\n if (msg.kind === \"syncConversationStep\" && msg.stepped === true) {\n scheduler.enqueueStepped(async () => {\n await runRequest(msg);\n return false;\n });\n return;\n }\n scheduler.enqueue(() => runRequest(msg));\n};\n\n/**\n * One whole-account catch-up as a stepped job: ONE PAGE of one conversation\n * per scheduler turn (`catch-up-pass.ts` has the policy). The scheduler runs\n * queued ordinary requests between pages. When the host transport reports\n * the server's log heads, only the conversations that are behind are\n * stepped. Each page's messages are posted as an `event.batch` (source\n * `page`) and its conversation updates come from the core's exact `updated`\n * list, so nothing here diffs epochs. The result is posted once, when the\n * pass is complete, with every decrypted application message in apply\n * order, the same contract `syncConversations()` callers have always had.\n */\nfunction catchUpPassStepper(\n msg: Extract<Request, { kind: \"syncConversations\" }>,\n): () => Promise<boolean> {\n const post = (m: Response): void => (self.postMessage as (m: Response) => void)(m);\n let pass: (() => Promise<boolean>) | null = null;\n return async (): Promise<boolean> => {\n if (pass === null) {\n try {\n await ensureWasm();\n ensureClient();\n } catch (e) {\n post({\n kind: \"result\", id: msg.id, ok: false,\n error: e instanceof Error ? e.message : String(e),\n });\n return false;\n }\n pass = catchUpPass({\n listConversationIds: () =>\n (ensureClient().listConversations() as unknown as ConversationEpoch[]).map((meta) => meta.id),\n fetchHeads: async () =>\n transportFeatures.fetchLogHeads ? (await fetchLogHeadsProxy()) ?? null : null,\n conversationsBehind: (heads) =>\n ensureClient().conversationsBehind(heads) as unknown as Uint8Array[],\n step: async (id) => {\n try {\n return await (ensureClient().syncConversationStep(id, msg.nowMs) as unknown as Promise<SyncStepResultWire>);\n } catch (e) {\n // A page that threw announced nothing; the group may still have\n // moved before the throw (see `conversationsOfFailedApply`).\n refreshCached([id]);\n throw e;\n }\n },\n onPage: (page) => {\n announceUpdated(page.updated, undefined, page.removed);\n if (page.messages.length > 0) {\n post({ kind: \"event.batch\", messages: page.messages, source: \"page\" });\n }\n },\n finish: (ok, value) => {\n if (ok) {\n post({ kind: \"result\", id: msg.id, ok: true, value });\n } else {\n post({\n kind: \"result\", id: msg.id, ok: false,\n error: value instanceof Error ? value.message : String(value),\n });\n }\n },\n });\n }\n return pass();\n };\n}\n\nasync function dispatch(msg: Request): Promise<unknown> {\n await ensureWasm();\n switch (msg.kind) {\n case \"init\": {\n transportFeatures = msg.transportFeatures ?? { fetchLogSince: false, fetchLogHeads: false };\n client = await PingClient.init(\n msg.identityExport, msg.deviceLabel,\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n makeProxyTransport(transportFeatures) as unknown as never,\n msg.nowMs,\n // Optional Ed25519 device signing secret — see protocol.ts\n // and ClientConfig.deviceSigningSecretKey. Forwarding `null`\n // explicitly when absent so the wasm-bindgen `Option<Vec<u8>>`\n // shape is matched correctly.\n msg.deviceSigningSecretKey ?? null,\n // The owner each conversation's FIRST roles write must name\n // (2026-11-04, round 2); `null` for none.\n msg.expectedOwners ?? null,\n );\n // Wire decrypted application-message callback back to the main thread.\n client.onMessage((m: unknown) => {\n (self.postMessage as (m: Response) => void)({ kind: \"event.message\", msg: m as never });\n });\n return null;\n }\n case \"openReadOnly\": {\n // No `onMessage` wiring here: a read-only client exists to answer one\n // question about one envelope, not to stream. Registering the callback\n // would also fire the tab's handlers from the worker.\n client = await PingClient.openReadOnly(\n msg.identityExport, msg.deviceLabel,\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n proxyTransport as unknown as never,\n msg.nowMs,\n );\n return null;\n }\n\n case \"previewEnvelope\":\n return ensureClient().previewEnvelope(msg.envelope as unknown as never, msg.nowMs);\n case \"previewEnvelopeWithPrerequisites\":\n return ensureClient().previewEnvelopeWithPrerequisites(\n msg.prerequisites as unknown as never,\n msg.envelope as unknown as never,\n msg.nowMs,\n );\n\n case \"generateIdentity\":\n return PingClient.generateIdentity();\n case \"userId\": return ensureClient().userId();\n case \"exportIdentity\": return ensureClient().exportIdentity();\n case \"rotateIdentity\":\n // One self-update Commit per conversation moves the leaf credential to\n // the new user id; the device signing key and deviceId stay put. The\n // identity swaps even when some conversations end up in `failed`.\n return await ensureClient().rotateIdentity(msg.newIdentityExport, msg.nowMs);\n case \"rotateIdentityRetry\":\n return await ensureClient().rotateIdentityRetry(msg.conv, msg.nowMs);\n case \"deviceId\": return ensureClient().deviceId();\n case \"suspendStorage\": return ensureClient().suspendStorage();\n case \"resumeStorage\": return ensureClient().resumeStorage();\n case \"freshKeyPackage\": return ensureClient().freshKeyPackage();\n case \"freshLastResortKeyPackage\": return ensureClient().freshLastResortKeyPackage();\n case \"createConversation\":\n return await ensureClient().createConversation(msg.name ?? undefined, msg.nowMs);\n case \"createCallConversation\":\n return await ensureClient().createCallConversation(msg.name ?? undefined, msg.nowMs);\n case \"joinConversation\": {\n const id = await ensureClient().joinConversation(msg.welcome, msg.nowMs) as Uint8Array;\n // Notify the main thread that we just entered a new conversation. We forward the\n // Welcome's `sender_device` so the host can label \"joined chat with <inviter>\".\n postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));\n return id;\n }\n case \"listConversations\":\n return ensureClient().listConversations();\n case \"conversationMeta\":\n // ONE conversation, read where the group lives: no listing crosses to\n // the main thread. `null` when the client does not hold it.\n return ensureClient().conversationMeta(msg.conv) ?? null;\n case \"strandedConversations\":\n return ensureClient().strandedConversations();\n case \"conversationsLeaving\":\n return ensureClient().conversationsLeaving();\n case \"conversationsLeaveStalled\":\n return ensureClient().conversationsLeaveStalled();\n case \"readmitPendingConversations\":\n return ensureClient().readmitPendingConversations(msg.nowMs);\n case \"undeliverableCount\":\n return ensureClient().undeliverableCount();\n case \"members\":\n return ensureClient().members(msg.conv);\n case \"conversationPolicy\":\n return ensureClient().conversationPolicy(msg.conv);\n case \"setExpectedOwners\":\n return ensureClient().setExpectedOwners(msg.entries);\n case \"setConversationRoles\":\n return await ensureClient().setConversationRoles(msg.conv, msg.owner, msg.admins, msg.nowMs);\n case \"send\":\n return await ensureClient().send(msg.conv, msg.plaintext, msg.nowMs);\n case \"addMembers\":\n // wasm-bindgen takes the entries as a plain array of {deviceId, keyPackage};\n // serde-wasm-bindgen on the Rust side deserialises into Vec<JsAddMemberEntry>.\n return await ensureClient().addMembers(msg.conv, msg.entries, msg.nowMs);\n case \"addMembersWithVerdicts\":\n // Per-entry verdicts; resolves to the serialised AddMembersReport.\n return await ensureClient().addMembersWithVerdicts(msg.conv, msg.entries, msg.nowMs);\n case \"reAdmitDevice\":\n // Re-admit one device that kept its key: the leaf with the KeyPackage's\n // own signature key goes and the fresh KeyPackage is added. Never an add:\n // with no such leaf it rejects \"not permitted: ...\", and so does a\n // committer the roles do not permit. Resolves to the device id of the\n // replaced leaf.\n return await ensureClient().reAdmitDevice(msg.conv, msg.entry, msg.nowMs);\n case \"mayReadmit\":\n // A pure query: would this device's Commit re-admitting or adding that\n // device pass the membership rules now. Nothing is built or sent.\n return ensureClient().mayReadmit(msg.conv, msg.identity, msg.deviceId);\n case \"keyPackageIdentity\":\n // A pure read: the identity the KeyPackage's credential claims, after the\n // KeyPackage was validated (signatures, lifetime). `undefined` for a\n // credential that is not the project's; throws for anything else.\n return ensureClient().keyPackageIdentity(msg.keyPackage);\n case \"setConversationName\":\n // GroupContextExtensions commit carrying the new conversation name — the\n // rename / avatar-id change propagates to every member via group state.\n return await ensureClient().setConversationName(msg.conv, msg.name ?? undefined, msg.nowMs);\n case \"admitDeviceToChats\":\n // Per-chat add for a newly-linked device. Returns Vec<JsAdmitChatOutcome>\n // — the host inspects per-entry status to decide whether to retry.\n return await ensureClient().admitDeviceToChats(msg.deviceId, msg.entries, msg.nowMs);\n case \"admitDeviceToChatsConcurrent\":\n // Same per-chat add with up to `concurrency` admissions in flight inside\n // this ONE wasm call (the worker still runs one call at a time; the\n // overlap is the core's, across conversations). Outcomes in input order.\n return await ensureClient().admitDeviceToChatsConcurrent(\n msg.deviceId,\n msg.entries,\n msg.nowMs,\n msg.concurrency,\n );\n case \"removeMembers\":\n // wasm-bindgen exposes Vec<u32> as Uint32Array; convert from the protocol's number[].\n return await ensureClient().removeMembers(msg.conv, new Uint32Array(msg.leaves), msg.nowMs);\n case \"removeOwnOtherLeaves\":\n // Every OTHER leaf of this account in one conversation; resolves to the count.\n return await ensureClient().removeOwnOtherLeaves(msg.conv, msg.nowMs);\n case \"removeMembersByIdentity\":\n // Every leaf whose credential verifies for one of `identities`; resolves to the count.\n return await ensureClient().removeMembersByIdentity(msg.conv, msg.identities, msg.nowMs);\n case \"leaveConversation\":\n return await ensureClient().leaveConversation(msg.conv, msg.nowMs);\n case \"dropConversationLocal\":\n return await ensureClient().dropConversationLocal(msg.conv);\n case \"conversationsWithPendingProposals\":\n return ensureClient().conversationsWithPendingProposals();\n case \"commitPendingProposals\":\n return await ensureClient().commitPendingProposals(msg.conv, msg.nowMs);\n case \"pendingProposalsCommitRank\":\n return ensureClient().pendingProposalsCommitRank(msg.conv) ?? null;\n case \"commitsInDoubt\":\n return ensureClient().commitsInDoubt();\n case \"revokeDevice\":\n // [CR-2] returns the array of Commit envelopes the SDK has already broadcast.\n return await ensureClient().revokeDevice(msg.deviceId, msg.nowMs);\n case \"removeDeviceEverywhere\":\n // Every group, DeviceGroup first, never stopping at a failure; resolves\n // to the report the host persists and retries from.\n return await ensureClient().removeDeviceEverywhere(msg.deviceId, msg.nowMs);\n case \"removeOwnDevicesExcept\":\n // The \"secure my account\" sweep: every other leaf of this account\n // except `keep` (by credential, or listed by the server); same report.\n return await ensureClient().removeOwnDevicesExcept(msg.keep, msg.listed, msg.nowMs);\n case \"processEnvelope\": {\n const result = await ensureClient().processEnvelope(msg.envelope, msg.nowMs);\n postConversationEvent(\n msg.envelope.conversation_id, msg.envelope.epoch, undefined,\n readMeta(msg.envelope.conversation_id),\n );\n return result;\n }\n case \"pendingApplies\":\n // [D27] Journal listing — reading does not consume.\n return ensureClient().pendingApplies();\n case \"confirmApplied\":\n // [D27] Removes + checkpoints; unknown ids are ignored (idempotent).\n return await ensureClient().confirmApplied(msg.journalIds);\n case \"syncConversations\":\n // Reached only if a caller bypasses `onmessage`; the scheduler turns\n // this kind into a stepped pass before it can get here.\n return await ensureClient().syncConversations(msg.nowMs);\n case \"syncConversation\":\n return await ensureClient().syncConversation(msg.conv, msg.nowMs);\n // Sequenced log sync. The batch and page results carry their messages\n // (the wasm does not fan them out through `onMessage`); the main thread\n // delivers them from the result. Conversation updates are announced from\n // the core's exact `updated` list, before the result resolves.\n case \"processSequencedBatch\": {\n const raw = await ensureClient().processSequencedBatch(msg.items, msg.nowMs) as unknown as ApplyBatchResultWire;\n announceUpdated(raw.updated, welcomeSenders(msg.items, raw.joined), raw.removed);\n return raw;\n }\n case \"syncConversationStep\": {\n const raw = await ensureClient().syncConversationStep(msg.conv, msg.nowMs) as unknown as SyncStepResultWire;\n announceUpdated(raw.updated, undefined, raw.removed);\n return raw;\n }\n case \"logPositions\":\n return ensureClient().logPositions();\n case \"logPosition\":\n return ensureClient().logPosition(msg.conv);\n case \"adoptLogPosition\":\n return await ensureClient().adoptLogPosition(msg.conv, msg.epoch, msg.serverSeq);\n case \"conversationsBehind\":\n return ensureClient().conversationsBehind(msg.heads);\n case \"heldFrameCount\":\n return ensureClient().heldFrameCount();\n case \"joinConversationAt\": {\n const id = await ensureClient().joinConversationAt(msg.welcome, msg.position, msg.nowMs) as Uint8Array;\n postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));\n return id;\n }\n case \"processWelcomeAt\": {\n const id = await ensureClient().processWelcomeAt(msg.welcome, msg.position, msg.nowMs) as Uint8Array | null;\n if (id !== null && id !== undefined) {\n postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));\n return id;\n }\n return null;\n }\n case \"buildLinkingTicket\":\n return await ensureClient().buildLinkingTicket(\n msg.newDeviceId, msg.newDeviceKp, msg.lastAppEvents, msg.nowMs,\n );\n case \"consumeLinkingTicket\":\n await ensureClient().consumeLinkingTicket(msg.ticket, msg.nowMs);\n return null;\n case \"decodeCatchupSnapshot\":\n // Pure WASM — no client state required. The new device may call this in an\n // ephemeral worker before init() completes.\n return wasmDecodeCatchupSnapshot(msg.snapshotBytes);\n case \"exportConversationSecret\":\n // wasm-bindgen returns a Uint8Array sized to `length`. The bytes are a secret —\n // the main thread is responsible for clearing the typed array when done.\n return ensureClient().exportConversationSecret(\n msg.conv, msg.label, msg.context, msg.length,\n );\n case \"exportConversationSecretWithEpoch\":\n // `{ epoch, secret }` from ONE read inside the core: the epoch is the one\n // the secret was exported at. Passed through as it is, never rebuilt from\n // a second read. The secret is the main thread's to clear when done.\n return ensureClient().exportConversationSecretWithEpoch(\n msg.conv, msg.label, msg.context, msg.length,\n );\n case \"sealLinkingTicket\":\n // Pure WASM call — no client state required. Lets a sender seal a ticket from an\n // ephemeral worker without standing up the full PingClient.\n return wasmSealLinkingTicket(msg.ticket, msg.newDevicePub);\n case \"openLinkingTicket\":\n // Same — runs without an initialised client, which is the receiving device's\n // pre-bootstrap state (it has the X25519 ephemeral key but no identity yet).\n return wasmOpenLinkingTicket(msg.sealed, msg.newDevicePriv);\n case \"hpkeSeal\":\n // Generic HPKE seal for app-layer envelopes (e.g. linking auth envelope).\n return wasmHpkeSeal(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpen\":\n return wasmHpkeOpen(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeSealRaw\":\n // The RFC 9180 canonical layout (`enc || ct`), which the app layers use.\n return wasmHpkeSealRaw(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenRaw\":\n return wasmHpkeOpenRaw(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeGenerateKeypair\":\n return wasmHpkeGenerateKeypair();\n // Post-quantum (X-Wing) twins: all pure WASM, no client state required.\n case \"sealLinkingTicketPq\":\n return wasmSealLinkingTicketPq(msg.ticket, msg.newDevicePub);\n case \"openLinkingTicketPq\":\n return wasmOpenLinkingTicketPq(msg.sealed, msg.newDevicePriv);\n case \"hpkeSealPq\":\n return wasmHpkeSealPq(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenPq\":\n return wasmHpkeOpenPq(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeSealRawPq\":\n return wasmHpkeSealRawPq(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenRawPq\":\n return wasmHpkeOpenRawPq(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeGenerateKeypairPq\":\n return wasmHpkeGenerateKeypairPq();\n case \"hpkePublicKeyFromSeed\":\n return wasmHpkePublicKeyFromSeed(msg.seed);\n case \"deviceGroupIdFor\":\n // Pure: the core's DeviceGroup id derivation for an MLS user id.\n return wasmDeviceGroupIdFor(msg.userId);\n case \"hpkePublicKeyFromPrivate\":\n return wasmHpkePublicKeyFromPrivate(msg.privateKey);\n case \"signDeviceReauth\":\n // Pure WASM: the SDK builds the signed bytes, so this signs nothing else\n // with the device key. Returns `deviceId (32) || signature (64)`.\n return wasmSignDeviceReauth(msg.deviceSigningSecretKey, msg.challengeId, msg.nonce, msg.accountId, msg.audience);\n case \"signDeviceLinkApproval\":\n // Pure WASM, link verification v2: the SDK builds the signed bytes and\n // derives both ids. Returns `approverDeviceId (32) || newDeviceId (32) ||\n // signature (64)`.\n return wasmSignDeviceLinkApproval(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.newDevicePubkey, msg.audience);\n case \"signDeviceLinkPossession\":\n // Pure WASM. Returns `deviceId (32) || signature (64)`.\n return wasmSignDeviceLinkPossession(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.audience);\n case \"exportConversationStateSnapshot\":\n // [CR-7] state snapshot bytes are a secret (past epoch keys); the main thread\n // is responsible for clearing the typed array when done.\n return ensureClient().exportConversationStateSnapshot(msg.conv, msg.nowMs);\n case \"importStateSnapshot\":\n // [CR-7] returns the imported conversation id as a Uint8Array.\n return await ensureClient().importStateSnapshot(msg.snapshotBytes, msg.nowMs);\n // Recovery — all pure WASM; no client state required.\n case \"generateMnemonicPhrase\":\n return wasmGenerateMnemonicPhrase();\n case \"normalizeMnemonicPhrase\":\n return wasmNormalizeMnemonicPhrase(msg.phrase);\n case \"encryptBackup\":\n return wasmEncryptBackup(\n msg.mnemonicPhrase, msg.accountId, msg.identityExport,\n msg.deviceGroupSnapshot,\n // Map idiomatic camelCase → the snake_case keys serde expects on the\n // WASM boundary (matches the decrypt view's account_id / group_state_bytes).\n msg.conversationSnapshots.map((c) => ({\n conversation_id: c.conversationId,\n group_state_bytes: c.groupStateBytes,\n })),\n msg.createdAtMs,\n );\n case \"decryptBackup\":\n return wasmDecryptBackup(msg.blob, msg.mnemonicPhrase);\n case \"sealHistoryBundle\":\n return wasmSealHistoryBundle(msg.bundle, msg.recipientPub, msg.senderIdentitySecret);\n case \"openHistoryBundle\":\n return wasmOpenHistoryBundle(msg.sealed, msg.recipientPriv, msg.senderIdentityPub);\n case \"sealHistoryBundlePq\":\n return wasmSealHistoryBundlePq(msg.bundle, msg.recipientPub, msg.senderIdentitySecret);\n case \"openHistoryBundlePq\":\n return wasmOpenHistoryBundlePq(msg.sealed, msg.recipientPriv, msg.senderIdentityPub);\n default:\n throw new Error(`unknown request kind: ${(msg as { kind: string }).kind}`);\n }\n}\n\nfunction ensureClient(): PingClient {\n if (!client) throw new Error(\"client not initialised\");\n return client;\n}\n","// Which conversations' MLS epochs moved, and therefore which `event.conversation`\n// notifications the worker owes the main thread.\n//\n// This lives outside `worker.ts` purely so it is testable: importing the worker\n// module runs its top-level `self.onmessage` wiring, which needs a\n// `DedicatedWorkerGlobalScope`. The rule it encodes is small but load-bearing —\n// see `EPOCH_ADVANCING_REQUESTS` in the worker for why a self-authored or\n// catch-up-applied commit would otherwise be announced to nobody.\n\n/** The two fields of a `ConversationMeta` this comparison needs. */\nexport interface ConversationEpoch {\n id: Uint8Array;\n epoch: number;\n}\n\n/** Stable map key for a 16-byte conversation id. */\nexport function conversationKey(id: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < id.length; i += 1) out += (id[i] ?? 0).toString(16).padStart(2, \"0\");\n return out;\n}\n\n/** Epoch per conversation, keyed by `conversationKey`. */\nexport function epochMap(metas: readonly ConversationEpoch[]): Map<string, number> {\n const out = new Map<string, number>();\n for (const meta of metas) out.set(conversationKey(meta.id), meta.epoch);\n return out;\n}\n\n/**\n * Conversations whose epoch STRICTLY advanced between `before` and `after`.\n *\n * Only conversations present in both are considered:\n * - a conversation that is new since `before` was either just created by this\n * caller or just joined, and `joinConversation` already announces the\n * latter — announcing it here would double-fire;\n * - a conversation that has disappeared (left / dropped) has no epoch to\n * report;\n * - an epoch that did not move is not an event, however many times the\n * request that ran touched the group.\n *\n * The elements returned are the elements of `after` themselves, so a caller\n * that listed whole metadata records gets them back whole.\n */\nexport function advancedEpochs<T extends ConversationEpoch>(\n before: ReadonlyMap<string, number>,\n after: readonly T[],\n): T[] {\n const out: T[] = [];\n for (const meta of after) {\n const previous = before.get(conversationKey(meta.id));\n if (previous === undefined || meta.epoch <= previous) continue;\n out.push(meta);\n }\n return out;\n}\n\n/** The id a `conversationKey` was made from. */\nexport function conversationIdOf(key: string): Uint8Array {\n const out = new Uint8Array(key.length >> 1);\n for (let i = 0; i < out.length; i += 1) out[i] = Number.parseInt(key.slice(i * 2, i * 2 + 2), 16);\n return out;\n}\n\n/**\n * The conversations a request brought in or took away, which\n * {@link advancedEpochs} deliberately does not report.\n *\n * They are not host events (whoever joined or left already said so, or it is\n * not an epoch change at all), but the main thread's copy of a conversation's\n * metadata must still follow them: a conversation that `appeared` is held\n * now, one that `disappeared` is not, and a copy that kept answering for it\n * would be answering for a group this device no longer reads.\n */\nexport function changedHoldings<T extends ConversationEpoch>(\n before: ReadonlyMap<string, number>,\n after: readonly T[],\n): { appeared: T[]; disappeared: Uint8Array[] } {\n const appeared: T[] = [];\n const still = new Set<string>();\n for (const meta of after) {\n const key = conversationKey(meta.id);\n still.add(key);\n if (!before.has(key)) appeared.push(meta);\n }\n const disappeared: Uint8Array[] = [];\n for (const key of before.keys()) {\n if (!still.has(key)) disappeared.push(conversationIdOf(key));\n }\n return { appeared, disappeared };\n}\n","// The whole-account catch-up as a stepped job: one PAGE of one conversation\n// per scheduler turn.\n//\n// `syncConversations()` used to page each conversation to its end inside one\n// wasm call; a 2,000-message group backlog was eight pages behind which\n// every queued send waited. Each call of the returned step now applies ONE\n// page through `syncConversationStep` and yields, so the primary lane (a\n// send, a live batch, a host's own step) runs between pages as well as\n// between conversations. A conversation whose page was full stays at the\n// head of the queue and continues next turn.\n//\n// When the transport can report the server's log heads, only the\n// conversations `conversationsBehind` names are stepped: one request instead\n// of one page per conversation the account holds. A transport without\n// `fetchLogHeads` (or one that answers `null`: the relay has no heads route)\n// gets the whole-account walk, as before. A heads request that FAILS ends\n// the pass with that error instead: walking every conversation on a network\n// that just failed one request would fail N more times, and the host retries\n// the pass on its next trigger (reconnect, foreground, heartbeat), by which\n// time the socket's `resume_ack` has usually named what is behind anyway.\n//\n// The pass ends with one re-list so a conversation joined while it ran is\n// still covered, exactly as the core re-reads its map. Conversations already\n// evaluated (stepped, or present in the heads snapshot) are not re-stepped.\n//\n// Lives outside `worker.ts` so it is testable without a\n// `DedicatedWorkerGlobalScope`; the worker supplies the dependencies.\n\nimport { conversationKey } from \"./epoch-events\";\nimport type { LogHeadWire, SyncStepResultWire } from \"./sequenced\";\nimport type { IncomingMessage } from \"./types\";\n\nexport interface CatchUpPassDeps {\n /** Ids of every conversation the client holds right now. */\n listConversationIds(): Uint8Array[];\n /** The server's heads, or `null` when the transport cannot report them. */\n fetchHeads(): Promise<LogHeadWire[] | null>;\n /** The core's verdict on which of `heads` this device is behind on. */\n conversationsBehind(heads: LogHeadWire[]): Uint8Array[];\n /** Apply ONE page of one conversation. */\n step(id: Uint8Array): Promise<SyncStepResultWire>;\n /** Deliver a page: its conversation updates and its messages. */\n onPage(result: SyncStepResultWire): void;\n /** Post the pass result: every message in apply order, or the error. */\n finish(ok: boolean, value: IncomingMessage[] | unknown): void;\n}\n\n/**\n * Build the stepped job. Each call runs one step and resolves `true` while\n * the pass has more to do; it never rejects (errors are posted through\n * `finish`).\n */\nexport function catchUpPass(deps: CatchUpPassDeps): () => Promise<boolean> {\n const seen = new Set<string>();\n const delivered: IncomingMessage[] = [];\n let pending: Uint8Array[] | null = null;\n let relisted = false;\n\n const sortedUnseen = (ids: Uint8Array[]): Uint8Array[] =>\n ids\n .filter((id) => !seen.has(conversationKey(id)))\n .sort((a, b) => (conversationKey(a) < conversationKey(b) ? -1 : 1));\n\n const initial = async (): Promise<Uint8Array[]> => {\n // A rejection propagates to the caller, which posts it through `finish`.\n const heads = await deps.fetchHeads();\n if (heads === null) return sortedUnseen(deps.listConversationIds());\n // Every conversation the heads describe has been evaluated: the ones\n // that are current are not stepped now and not re-stepped by the re-list.\n for (const h of heads) seen.add(conversationKey(h.conversation_id));\n const behind = deps.conversationsBehind(heads);\n for (const id of behind) seen.delete(conversationKey(id));\n return sortedUnseen(behind);\n };\n\n return async (): Promise<boolean> => {\n try {\n if (pending === null) pending = await initial();\n if (pending.length === 0 && !relisted) {\n relisted = true;\n pending = sortedUnseen(deps.listConversationIds());\n }\n } catch (e) {\n deps.finish(false, e);\n return false;\n }\n const id = pending[0];\n if (id === undefined) {\n deps.finish(true, delivered);\n return false;\n }\n let more = false;\n try {\n const page = await deps.step(id);\n for (const m of page.messages) delivered.push(m);\n deps.onPage(page);\n more = page.has_more;\n } catch {\n // Dropped between the listing and this step (a wipe, a self-removal),\n // a transport failure, or a checkpoint failure: this conversation's\n // paging ends for this pass. The durable cursor is where the next\n // pass resumes, which is what the whole-account request did too.\n }\n if (!more) {\n seen.add(conversationKey(id));\n pending.shift();\n }\n return true;\n };\n}\n","// Request scheduling for the WASM worker: one call in flight at a time, in\n// two lanes.\n//\n// The worker may run only ONE WASM call at a time (see `worker.ts`), so every\n// request waits for the one before it. That is fine for the requests a user\n// is waiting on (a send, a live frame) — they are short. It was not fine for a\n// whole-account catch-up, which paged every conversation inside a single\n// request: a `send` posted while it ran started after all of them, and on a\n// tab returning from an idle hour that wait WAS the first message's latency.\n//\n// This scheduler keeps the one-call invariant and adds a second lane for\n// work that is allowed to be interrupted between its natural steps. An\n// ordinary request runs FIFO in the primary lane; a stepped job runs one\n// step per turn and only when the primary lane is empty, so anything queued\n// while a step ran goes next. Stepped jobs are FIFO among themselves and a\n// job's steps never interleave with another job's.\n//\n// Lives outside `worker.ts` so it is testable without a\n// `DedicatedWorkerGlobalScope` (the same reason `epoch-events.ts` exists).\n\n/** An ordinary request: runs to completion in one turn. Must not reject. */\nexport type LaneJob = () => Promise<void>;\n\n/**\n * A stepped job: each call runs ONE step and resolves `true` while more steps\n * remain. A rejected step ends the job (the scheduler treats it as `false`).\n */\nexport type SteppedJob = () => Promise<boolean>;\n\nexport class RequestScheduler {\n private readonly primary: LaneJob[] = [];\n private readonly stepped: SteppedJob[] = [];\n private pumping = false;\n\n /** Queue an ordinary request behind the ordinary requests before it. */\n enqueue(job: LaneJob): void {\n this.primary.push(job);\n void this.pump();\n }\n\n /** Queue a stepped job; its steps run whenever the primary lane is empty. */\n enqueueStepped(job: SteppedJob): void {\n this.stepped.push(job);\n void this.pump();\n }\n\n /** Requests waiting in the primary lane (diagnostics / tests). */\n get pendingPrimary(): number {\n return this.primary.length;\n }\n\n /** Stepped jobs not yet finished (diagnostics / tests). */\n get pendingStepped(): number {\n return this.stepped.length;\n }\n\n private async pump(): Promise<void> {\n if (this.pumping) return;\n this.pumping = true;\n try {\n for (;;) {\n const job = this.primary.shift();\n if (job !== undefined) {\n // A job posts its own error as a result; a rejection here would\n // only mean a bug in the job, and it must not stall the lane.\n await job().catch(() => undefined);\n continue;\n }\n const step = this.stepped[0];\n if (step === undefined) return;\n let more = false;\n try {\n more = await step();\n } catch {\n more = false;\n }\n if (!more) this.stepped.shift();\n }\n } finally {\n this.pumping = false;\n }\n }\n}\n"],"m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,mBAAmB,EAAE;AAAA,QACvB,EAAE;AAAA,QACF,IAAI;AAAA,MACN;AAAA,IACF,KAAK;AACH,aAAO,kBAAkB,IAAI,MAAM,IAAI,cAAc;AAAA,IACvD,KAAK;AACH,aAAO,sBAAsB,IAAI,QAAQ,IAAI,cAAc,IAAI,oBAAoB;AAAA,IACrF,KAAK;AACH,aAAO,sBAAsB,IAAI,QAAQ,IAAI,eAAe,IAAI,iBAAiB;AAAA,IACnF,KAAK;AACH,aAAO,wBAAwB,IAAI,QAAQ,IAAI,cAAc,IAAI,oBAAoB;AAAA,IACvF,KAAK;AACH,aAAO,wBAAwB,IAAI,QAAQ,IAAI,eAAe,IAAI,iBAAiB;AAAA,IACrF;AACE,YAAM,IAAI,MAAM,yBAA0B,IAAyB,IAAI,EAAE;AAAA,EAC7E;AACF;AAEA,SAAS,eAA2B;AAClC,MAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,wBAAwB;AACrD,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/wasm-memory.ts","../src/worker.ts","../src/epoch-events.ts","../src/catch-up-pass.ts","../src/request-lanes.ts"],"sourcesContent":["// Linear-memory reservation shared by every realm that instantiates the wasm.\n\n/**\n * Linear-memory headroom the worker reserves from JavaScript right after\n * instantiation, largest first; a target the engine refuses (`RangeError`)\n * falls through to the next. Sized so the Argon2id recovery backup\n * (64 MiB of blocks in ONE allocation) and a large history bundle fit\n * inside memory the module already owns.\n *\n * Why from JS and not inside the module: Safari/JSC (macOS 26 / iOS 26,\n * IPInt) crashes the WebContent process when the wasm `memory.grow`\n * INSTRUCTION runs in a Worker while the Web Inspector is attached — the GC\n * it triggers walks the stack and dies on the wasm frame. The same grow\n * requested through `WebAssembly.Memory.prototype.grow` has only JS frames\n * on the stack and is fine. The module's allocator (`ping-wasm/src/alloc.rs`)\n * claims these pages before it would ever execute the instruction itself.\n * The pages are virtual until touched, so an idle worker costs nothing extra.\n */\nexport const RESERVE_MIB_TARGETS = [192, 128, 64, 32] as const;\nconst WASM_PAGE_BYTES = 64 * 1024;\n\n/** Memories already reserved: `init` is idempotent per realm and returns the\n * same instance, so a second open must not grow it again. */\nconst reserved = new WeakSet<WebAssembly.Memory>();\n\nexport function reserveLinearMemory(memory: WebAssembly.Memory): void {\n if (reserved.has(memory)) return;\n reserved.add(memory);\n for (const mib of RESERVE_MIB_TARGETS) {\n try {\n memory.grow((mib * 1024 * 1024) / WASM_PAGE_BYTES);\n return;\n } catch {\n // Over the engine's limit for this memory; try a smaller reservation.\n }\n }\n}\n\n","// Web Worker entry. Owns the WASM `PingClient` instance. Receives Requests from the main thread\n// and posts Responses back. Storage / Transport calls back to the main thread are tracked by id.\n//\n// The WASM module is loaded lazily on the first `init` so that ephemeral identity-only spawns\n// (used by `MessagingClient.generateIdentity()`) don't pay the cost.\n\n/// <reference lib=\"webworker\" />\n\nimport { reserveLinearMemory } from \"./wasm-memory\";\nimport init, {\n PingClient,\n sealLinkingTicket as wasmSealLinkingTicket,\n openLinkingTicket as wasmOpenLinkingTicket,\n hpkeSeal as wasmHpkeSeal,\n hpkeOpen as wasmHpkeOpen,\n hpkeSealRaw as wasmHpkeSealRaw,\n hpkeOpenRaw as wasmHpkeOpenRaw,\n hpkeGenerateKeypair as wasmHpkeGenerateKeypair,\n sealLinkingTicketPq as wasmSealLinkingTicketPq,\n openLinkingTicketPq as wasmOpenLinkingTicketPq,\n hpkeSealPq as wasmHpkeSealPq,\n hpkeOpenPq as wasmHpkeOpenPq,\n hpkeSealRawPq as wasmHpkeSealRawPq,\n hpkeOpenRawPq as wasmHpkeOpenRawPq,\n hpkeGenerateKeypairPq as wasmHpkeGenerateKeypairPq,\n deviceGroupIdFor as wasmDeviceGroupIdFor,\n hpkePublicKeyFromSeed as wasmHpkePublicKeyFromSeed,\n hpkePublicKeyFromPrivate as wasmHpkePublicKeyFromPrivate,\n signDeviceReauth as wasmSignDeviceReauth,\n signDeviceLinkApproval as wasmSignDeviceLinkApproval,\n signDeviceLinkPossession as wasmSignDeviceLinkPossession,\n decodeCatchupSnapshot as wasmDecodeCatchupSnapshot,\n generateMnemonicPhrase as wasmGenerateMnemonicPhrase,\n normalizeMnemonicPhrase as wasmNormalizeMnemonicPhrase,\n encryptBackup as wasmEncryptBackup,\n decryptBackup as wasmDecryptBackup,\n checkBackupPhrase as wasmCheckBackupPhrase,\n sealHistoryBundle as wasmSealHistoryBundle,\n openHistoryBundle as wasmOpenHistoryBundle,\n sealHistoryBundlePq as wasmSealHistoryBundlePq,\n openHistoryBundlePq as wasmOpenHistoryBundlePq,\n} from \"../wasm/ping_wasm\";\nimport { catchUpPass } from \"./catch-up-pass\";\nimport {\n advancedEpochs, changedHoldings, type ConversationEpoch, conversationKey, epochMap,\n} from \"./epoch-events\";\nimport type { Request, Response, StorageFeatures, TransportFeatures } from \"./protocol\";\nimport { RequestScheduler } from \"./request-lanes\";\nimport type {\n ApplyBatchResultWire,\n ConversationRemovalWire,\n ConversationUpdateWire,\n LogHeadWire,\n SequencedEnvelopeWire,\n SyncStepResultWire,\n} from \"./sequenced\";\nimport type { ConversationMeta, DeviceId, IncomingMessage, MessageEnvelope } from \"./types\";\n\ndeclare const self: DedicatedWorkerGlobalScope;\n\nlet client: PingClient | null = null;\nlet wasmReady: Promise<void> | null = null;\n\nconst pendingStorage = new Map<number, (r: { ok: boolean; value: unknown }) => void>();\nconst pendingTransport = new Map<number, (r: { ok: boolean; value: unknown }) => void>();\nlet nextStorageId = 1;\nlet nextTransportId = 1;\n/** Calls made to the host transport so far. The worker runs one request at a\n * time, so the difference around a request is what that request sent and\n * fetched (see `sendLeftCopyBehind`). */\nlet transportCalls = 0;\n\nconst proxyStorage = {\n get: (namespace: string, key: string) => callMain<Uint8Array | null>(\"storage\", \"get\", [namespace, key]),\n put: (namespace: string, key: string, value: Uint8Array) =>\n callMain<void>(\"storage\", \"put\", [namespace, key, value]),\n del: (namespace: string, key: string) => callMain<void>(\"storage\", \"del\", [namespace, key]),\n listKeys: (namespace: string, prefix: string) =>\n callMain<string[]>(\"storage\", \"listKeys\", [namespace, prefix]),\n};\n// The two optional methods are declared on the proxy ONLY when the host\n// storage has them: the wasm bridge decides by their presence whether to hand\n// the per-row MLS store's delta to the host as one atomic batch (and read the\n// rows in one call) or to take its own journalled row-by-row fallback.\nconst applyBatchProxy = (namespace: string, puts: Array<[string, Uint8Array]>, deletes: string[]) =>\n callMain<void>(\"storage\", \"applyBatch\", [namespace, puts, deletes]);\nconst listEntriesProxy = (namespace: string, prefix: string) =>\n callMain<Array<[string, Uint8Array]>>(\"storage\", \"listEntries\", [namespace, prefix]);\nfunction makeProxyStorage(features: StorageFeatures | undefined) {\n return {\n ...proxyStorage,\n ...(features?.applyBatch ? { applyBatch: applyBatchProxy } : {}),\n ...(features?.listEntries ? { listEntries: listEntriesProxy } : {}),\n };\n}\nconst proxyTransport = {\n send: (envelope: MessageEnvelope) => callMain<void>(\"transport\", \"send\", [envelope]),\n // Always declared here: the main-thread dispatch emulates it with\n // sequential sends when the host transport has no `sendBatch`, encoding a\n // partial delivery with the `batch partial after <n>:` sentinel the wasm\n // bridge understands (see index.ts `BATCH_PARTIAL_PREFIX`).\n sendBatch: (envelopes: MessageEnvelope[]) => callMain<void>(\"transport\", \"sendBatch\", [envelopes]),\n fetchSince: (conv: Uint8Array, cursor: Uint8Array, limit: number) =>\n callMain<MessageEnvelope[]>(\"transport\", \"fetchSince\", [conv, cursor, limit]),\n discoverDevices: (userId: Uint8Array) => callMain<unknown[]>(\"transport\", \"discoverDevices\", [userId]),\n // Optional on the host (see `Transport.setNextWelcomeRecipients` in types.ts).\n // The main-thread dispatch (index.ts `handleWorker → case \"transport.call\"`)\n // resolves `undefined` to a `transport.reply { ok: true, value: undefined }`\n // when the host hasn't implemented the method, which we treat as a no-op.\n setNextWelcomeRecipients: (conv: Uint8Array, recipients: Uint8Array[]) =>\n callMain<void>(\"transport\", \"setNextWelcomeRecipients\", [conv, recipients]),\n};\n\n/** What the host transport declared at `init`; read by the catch-up pass. */\nlet transportFeatures: TransportFeatures = { fetchLogSince: false, fetchLogHeads: false };\n\nconst fetchLogSinceProxy = (position: unknown, limit: number) =>\n callMain<SequencedEnvelopeWire[] | null>(\"transport\", \"fetchLogSince\", [position, limit]);\nconst fetchLogHeadsProxy = () =>\n callMain<LogHeadWire[] | null | undefined>(\"transport\", \"fetchLogHeads\", []);\n\n/**\n * The transport proxy the wasm sees. Unlike `setNextWelcomeRecipients`, the\n * two sequenced-log methods are NOT always declared: the wasm bridge decides\n * by their presence whether to call them or fall back to the core default\n * (`fetchSince` at position 0; no heads), and `fetchLogSince` has no\n * main-thread emulation because only the core can encode the legacy cursor.\n */\nfunction makeProxyTransport(features: TransportFeatures) {\n return {\n ...proxyTransport,\n ...(features.fetchLogSince ? { fetchLogSince: fetchLogSinceProxy } : {}),\n ...(features.fetchLogHeads ? { fetchLogHeads: fetchLogHeadsProxy } : {}),\n };\n}\n\nfunction callMain<T>(kind: \"storage\" | \"transport\", method: string, args: unknown[]): Promise<T> {\n return new Promise((resolve, reject) => {\n const id = kind === \"storage\" ? nextStorageId++ : nextTransportId++;\n const map = kind === \"storage\" ? pendingStorage : pendingTransport;\n if (kind === \"transport\") transportCalls += 1;\n map.set(id, ({ ok, value }) => ok ? resolve(value as T) : reject(new Error(String(value))));\n self.postMessage({ kind: `${kind}.call`, id, method, args } as Response);\n });\n}\n\nasync function ensureWasm() {\n if (wasmReady) return wasmReady;\n // The bundled wasm path is rewritten by the build script to be relative to `dist/`.\n wasmReady = init().then((out) => {\n reserveLinearMemory(out.memory);\n });\n return wasmReady;\n}\n\n// The WASM `PingClient` is SINGLE-THREADED (this one worker). Its async\n// methods hold internal locks across `.await` (e.g. a `conversations`\n// RwLock guard kept while `snapshot_to_storage` awaits IndexedDB). If we\n// let `onmessage` dispatch a SECOND top-level request while the first is\n// suspended at an await, the two WASM calls interleave on the single\n// thread, the second re-acquires a held lock, and `parking_lot`'s wasm\n// stub `panic!`s with \"Parking not supported on this platform\" — which\n// poisons the module (`RuntimeError: unreachable`) and breaks every\n// subsequent call. We therefore SERIALIZE top-level request dispatch:\n// one WASM call runs to completion before the next begins.\n//\n// ONE CALL AT A TIME IS NOT THE SAME AS FIRST COME, FIRST SERVED. A\n// whole-account `syncConversations` used to be one request: every\n// conversation paged inside a single turn, one network round trip each,\n// and a `send` posted while it ran started only after the last of them.\n// On a tab returning from an idle hour that was the whole visible cost of\n// the first message: the composer cleared, the bubble sat on a clock for\n// the length of the pass, and the second message went out at once. The\n// scheduler below keeps the one-call invariant but runs a whole-account\n// pass as a sequence of per-conversation steps (`syncConversation`) and\n// lets everything else queued run between steps. Ordinary requests stay\n// FIFO among themselves, so the inbound ordering that per-conversation\n// chaining on the main thread relies on is untouched; a host's own\n// `syncConversation` for the chat the user is looking at is an ordinary\n// request too, so it runs ahead of the background pass.\n//\n// CRUCIAL: `storage.reply` / `transport.reply` are NOT serialized — an\n// in-flight request awaits those replies (via `callMain`), so queuing\n// them behind the request would deadlock. They resolve pending callbacks\n// immediately, exactly as before.\nconst scheduler = new RequestScheduler();\n\n// Requests that can advance a conversation's MLS epoch WITHOUT an inbound\n// envelope to announce it.\n//\n// `event.conversation` was only ever emitted from `processEnvelope` and\n// `joinConversation`, so it announced exactly one of the three ways an epoch\n// moves: a Commit received from someone else. The other two were invisible to\n// every consumer:\n//\n// 1. A commit THIS device authored. `MessagingClient.dispatchIncoming` drops\n// envelopes whose `sender_device` is ours (the relay echoes our own\n// sends), so the author's own commit never reaches `processEnvelope`.\n// A host that re-derives exported secrets on epoch change — call media\n// keys are the load-bearing case — therefore kept using the PREVIOUS\n// epoch's secret after adding a member, and went silent against everyone\n// who had rotated. It is specifically the device that INVITES that breaks.\n// 2. A commit applied during catch-up. `syncConversations` fetches and\n// applies envelopes but posted nothing, so a client that reconnected after\n// missing a commit resumed on a stale secret.\n//\n// Rather than enumerate emissions per operation (and miss the next one added),\n// the epoch map is snapshotted around these requests and any conversation whose\n// epoch actually MOVED is announced. Conversations are only compared, never\n// created, so this can never invent an event: a freshly joined conversation is\n// already announced by `joinConversation`, and one that disappears (leave/drop)\n// is not an epoch change.\n//\n// `send` is deliberately absent from this set: it is the hot path. It must not\n// pay for two `listConversations` calls, and it reports no conversation event\n// of its own. A send is not only an application message, though: before it\n// encrypts, the core settles a Commit this device left in doubt there and\n// commits pending proposals, and after it the core refreshes this device's\n// leaf when that is due. Each of those moves the epoch, and the first can land\n// a rename. The core reports such a move with the next batch or page, and\n// that is where the host hears it, once. Here the main thread's copy of the\n// conversation is only kept level with the group, and a send that moved\n// nothing reads nothing (see `sendLeftCopyBehind`).\nconst EPOCH_ADVANCING_REQUESTS: ReadonlySet<string> = new Set([\n \"addMembers\",\n \"addMembersWithVerdicts\",\n \"reAdmitDevice\",\n \"removeMembers\",\n \"removeOwnOtherLeaves\",\n \"removeMembersByIdentity\",\n \"commitPendingProposals\",\n \"setConversationName\",\n \"setConversationRoles\",\n \"admitDeviceToChats\",\n \"admitDeviceToChatsConcurrent\",\n \"revokeDevice\",\n \"removeDeviceEverywhere\",\n \"removeOwnDevicesExcept\",\n \"syncConversations\",\n \"syncConversation\",\n \"consumeLinkingTicket\",\n \"importStateSnapshot\",\n]);\n\n// Requests that commit and whose epoch move is NOT announced to the host: it\n// never was, and a new host event is not what keeps a handle fresh. The\n// conversations are compared around them all the same, and the main thread's\n// copy of each one that moved is brought level with `cache.conversations`,\n// which calls no listener. `buildLinkingTicket` commits to the DeviceGroup.\nconst EPOCH_UPKEEP_REQUESTS: ReadonlySet<string> = new Set([\n \"buildLinkingTicket\",\n]);\n\n// THE MAIN THREAD'S COPY OF A CONVERSATION'S METADATA\n//\n// The main thread keeps one `ConversationMeta` per conversation so that a\n// conversation handle can answer `name`, `epoch` and `meta()` without a round\n// trip. That copy used to be refilled by `listConversations()` only, so after\n// any change of a group it kept answering the metadata from before the change:\n// a host that carries a group's title and picture id in the name rebuilt the\n// name from the stale read and lost the picture on a rename.\n//\n// The rule now: every message that tells the main thread a conversation\n// changed CARRIES the conversation's metadata as the group holds it at that\n// moment, and the main thread stores it before it calls any host listener. A\n// request that changes a conversation without reporting an event (a creation,\n// a leave, a call whose Commit did not move the epoch, a `send` or a\n// `buildLinkingTicket` that moved one) says so with a\n// `cache.conversations` message before its `result`. Nothing here lists every\n// conversation to do it: the one conversation is read (`conversationMeta`), or\n// the record comes from a listing the request already paid for.\n\n/** One conversation's metadata as the group holds it now. `null`: the client\n * does not hold it (unknown, dropped, removed, or left) or it could not be\n * read; either way the main thread must not keep answering for it. */\nfunction readMeta(id: Uint8Array): ConversationMeta | null {\n if (!client) return null;\n try {\n return (client.conversationMeta(id) as ConversationMeta | null | undefined) ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Past this many conversations, one listing is cheaper than reading them one\n * at a time. The single read walks the client's conversations inside the\n * wasm and hands over one record; a listing hands over all of them and costs\n * about twelve single reads at any account size (measured at 100, 500 and\n * 2000 conversations). So the cost of bringing any number of conversations\n * up to date is bounded by one listing.\n */\nconst SINGLE_READS_MAX = 8;\n\n/** The metadata of each of `ids` as the groups hold it now, by\n * `conversationKey`; `null` for one the client does not hold. */\nfunction readMetas(ids: readonly Uint8Array[]): Map<string, ConversationMeta | null> {\n const out = new Map<string, ConversationMeta | null>();\n for (const id of ids) out.set(conversationKey(id), null);\n if (out.size <= SINGLE_READS_MAX) {\n for (const id of ids) out.set(conversationKey(id), readMeta(id));\n return out;\n }\n if (!client) return out;\n try {\n for (const meta of client.listConversations() as unknown as ConversationMeta[]) {\n const key = conversationKey(meta.id);\n if (out.has(key)) out.set(key, meta);\n }\n } catch {\n // Unreadable: every one of them stays `null`, and the main thread drops\n // its copies instead of keeping the old ones.\n }\n return out;\n}\n\n/** Tell the main thread a conversation changed, with its metadata as the\n * group holds it now (`null`: it is not held any more). */\nfunction postConversationEvent(\n id: Uint8Array,\n epoch: number,\n sender: DeviceId | undefined,\n meta: ConversationMeta | null,\n): void {\n (self.postMessage as (m: Response) => void)({\n kind: \"event.conversation\",\n id,\n epoch,\n ...(sender !== undefined ? { sender } : {}),\n ...(meta !== null ? { meta } : {}),\n });\n}\n\n/** Cache upkeep with no host event: what the main thread must hold now and\n * what it must forget. Posts nothing when there is nothing to say. */\nfunction postCacheUpkeep(held: ConversationMeta[], dropped: Uint8Array[]): void {\n if (held.length === 0 && dropped.length === 0) return;\n (self.postMessage as (m: Response) => void)({ kind: \"cache.conversations\", held, dropped });\n}\n\n/** Read each of `ids` and post the upkeep for them as one message. */\nfunction refreshCached(ids: readonly Uint8Array[]): void {\n if (ids.length === 0) return;\n const metas = readMetas(ids);\n const held: ConversationMeta[] = [];\n const dropped: Uint8Array[] = [];\n const done = new Set<string>();\n for (const id of ids) {\n const key = conversationKey(id);\n if (done.has(key)) continue;\n done.add(key);\n const meta = metas.get(key) ?? null;\n if (meta !== null) held.push(meta);\n else dropped.push(id);\n }\n postCacheUpkeep(held, dropped);\n}\n\n/**\n * What a request is watched over: the epoch of every conversation the client\n * held before it ran (one listing), and how to list them again after it.\n * `announce` says what a moved epoch becomes: a host event (the requests in\n * `EPOCH_ADVANCING_REQUESTS`) or upkeep of the main thread's copy only (the\n * requests in `EPOCH_UPKEEP_REQUESTS`).\n */\ninterface EpochWatch {\n before: Map<string, number>;\n after(): ConversationMeta[];\n announce: boolean;\n}\n\n/** The watch for `msg`, or `null` when it needs none or the conversations\n * could not be read: no epoch change is reported for that request then, and\n * nothing is concluded from an absence. */\nfunction watchFor(msg: Request): EpochWatch | null {\n const held = client;\n if (!held) return null;\n const announce = EPOCH_ADVANCING_REQUESTS.has(msg.kind);\n if (!announce && !EPOCH_UPKEEP_REQUESTS.has(msg.kind)) return null;\n const list = (): ConversationMeta[] => held.listConversations() as unknown as ConversationMeta[];\n try {\n return { before: epochMap(list()), after: list, announce };\n } catch {\n // A client mid-teardown (or a storage read failure) is not a reason to\n // fail the request the caller actually made.\n return null;\n }\n}\n\n/**\n * Tell the main thread about every watched conversation whose epoch moved,\n * each with the metadata just read: as a host event when the watch announces,\n * as cache upkeep when it does not. The conversations the request brought in\n * or took away are cache upkeep either way. Returns the keys of every\n * conversation the main thread was told about, so the caller does not read\n * one of them a second time.\n */\nfunction emitEpochAdvances(watch: EpochWatch): Set<string> {\n const told = new Set<string>();\n let metas: ConversationMeta[];\n try {\n metas = watch.after();\n } catch {\n return told;\n }\n const advanced = advancedEpochs(watch.before, metas);\n for (const meta of advanced) {\n told.add(conversationKey(meta.id));\n if (watch.announce) postConversationEvent(meta.id, meta.epoch, undefined, meta);\n }\n const { appeared, disappeared } = changedHoldings(watch.before, metas);\n for (const meta of appeared) told.add(conversationKey(meta.id));\n for (const id of disappeared) told.add(conversationKey(id));\n postCacheUpkeep(watch.announce ? appeared : [...advanced, ...appeared], disappeared);\n return told;\n}\n\n/**\n * Whether the main thread's copy of the conversation a `send` named may be\n * behind the group now. Answered from what the worker already holds, so a\n * send that moved nothing reads nothing:\n *\n * - The envelope the send produced carries the epoch it was encrypted at,\n * and the main thread sent the epoch of its own copy with the request.\n * Everything the core does BEFORE it encrypts shows in that comparison:\n * settling a Commit this device left in doubt, committing pending\n * proposals, applying another member's Commits from the log.\n * - The one thing the core does AFTER it encrypts is the refresh of this\n * device's leaf: a Commit, merged only once the transport accepted it. A\n * send that moved nothing makes exactly one transport call, the message\n * itself, so any other count means something else was sent or fetched.\n *\n * A send that failed produced no envelope to compare, so the conversation is\n * read. In every case the cost is at most ONE read of the one conversation,\n * made after the send; never a listing, and never a host event.\n */\nfunction sendLeftCopyBehind(\n msg: Extract<Request, { kind: \"send\" }>,\n outcome: { ok: true; value: unknown } | { ok: false },\n calls: number,\n): boolean {\n if (!outcome.ok || calls !== 1) return true;\n const sentAt = (outcome.value as { epoch?: unknown } | null | undefined)?.epoch;\n return typeof sentAt !== \"number\" || sentAt !== msg.heldEpoch;\n}\n\n/**\n * Announce the conversations a batch or page moved. The sequenced paths\n * report `updated` exactly (the core lists every conversation whose epoch\n * moved or that was joined), so there is nothing to diff: one event per\n * entry, each with the conversation's metadata read at that moment.\n * `senders` labels a join with the inviter's device, as `joinConversation`\n * does. `removed` are the conversations the batch took this device out of:\n * no host event (the result reports them), but the main thread's copy of\n * each is brought to what the client holds now.\n */\nfunction announceUpdated(\n updated: ConversationUpdateWire[],\n senders: Map<string, DeviceId> = new Map(),\n removed: ConversationRemovalWire[] = [],\n): void {\n if (updated.length === 0 && removed.length === 0) return;\n const metas = readMetas([\n ...updated.map((u) => u.conversation_id),\n ...removed.map((r) => r.conversation_id),\n ]);\n const told = new Set<string>();\n for (const u of updated) {\n const key = conversationKey(u.conversation_id);\n told.add(key);\n postConversationEvent(u.conversation_id, u.epoch, senders.get(key), metas.get(key) ?? null);\n }\n const held: ConversationMeta[] = [];\n const dropped: Uint8Array[] = [];\n for (const r of removed) {\n const key = conversationKey(r.conversation_id);\n if (told.has(key)) continue;\n told.add(key);\n const meta = metas.get(key) ?? null;\n if (meta !== null) held.push(meta);\n else dropped.push(r.conversation_id);\n }\n postCacheUpkeep(held, dropped);\n}\n\n/** The inviter's device for every conversation a batch joined, from the\n * Welcome that joined it. */\nfunction welcomeSenders(items: SequencedEnvelopeWire[], joined: Uint8Array[]): Map<string, DeviceId> {\n const out = new Map<string, DeviceId>();\n if (joined.length === 0) return out;\n const wanted = new Set(joined.map((id) => conversationKey(id)));\n for (const item of items) {\n if (item.envelope.kind !== \"Welcome\") continue;\n const key = conversationKey(item.envelope.conversation_id);\n if (wanted.has(key) && !out.has(key)) out.set(key, item.envelope.sender_device);\n }\n return out;\n}\n\n// Requests after which ONE conversation's metadata on the main thread must be\n// what the group holds, whether or not an event said so: this device's own\n// calls on a conversation. When the call moved the epoch, the event above\n// already carried the metadata and nothing more is read. When it did not (the\n// call failed, its Commit is in doubt, the conversation is now left or\n// dropped), the one conversation is read once, here.\nconst CONVERSATION_REQUESTS: ReadonlySet<string> = new Set([\n \"addMembers\",\n \"addMembersWithVerdicts\",\n \"reAdmitDevice\",\n \"removeMembers\",\n \"removeOwnOtherLeaves\",\n \"removeMembersByIdentity\",\n \"commitPendingProposals\",\n \"setConversationName\",\n \"setConversationRoles\",\n \"syncConversation\",\n \"leaveConversation\",\n \"dropConversationLocal\",\n]);\n\n// Requests that resolve to the id of a conversation they brought in.\nconst CONVERSATION_RESULT_REQUESTS: ReadonlySet<string> = new Set([\n \"createConversation\",\n \"createCallConversation\",\n \"importStateSnapshot\",\n]);\n\n/** The conversation a finished request must leave fresh on the main thread. */\nfunction conversationTouched(msg: Request, value: unknown): Uint8Array | null {\n if (CONVERSATION_REQUESTS.has(msg.kind)) {\n const conv = (msg as { conv?: unknown }).conv;\n return conv instanceof Uint8Array ? conv : null;\n }\n if (CONVERSATION_RESULT_REQUESTS.has(msg.kind)) {\n return value instanceof Uint8Array ? value : null;\n }\n return null;\n}\n\n/**\n * The conversations a request that applies inbound frames named. When such a\n * request succeeds, the events it posted carried the metadata. When it\n * THROWS it posted nothing, yet the group may have moved before the throw (a\n * Commit merged, then the checkpoint failed), so each conversation it named\n * is read once and the main thread's copy follows. No host event: a failed\n * apply never announced one.\n */\nfunction conversationsOfFailedApply(msg: Request): Uint8Array[] {\n switch (msg.kind) {\n case \"processEnvelope\":\n return [msg.envelope.conversation_id];\n case \"joinConversation\":\n case \"joinConversationAt\":\n case \"processWelcomeAt\":\n return [msg.welcome.conversation_id];\n case \"syncConversationStep\":\n return [msg.conv];\n case \"processSequencedBatch\":\n return msg.items.map((item) => item.envelope.conversation_id);\n default:\n return [];\n }\n}\n\n/** Everything the main thread must know about conversations before it hears\n * the request's outcome. `calls` is how many transport calls the request\n * made. Never throws. */\nfunction reportConversations(\n msg: Request,\n watch: EpochWatch | null,\n outcome: { ok: true; value: unknown } | { ok: false },\n calls: number,\n): void {\n try {\n const told = watch ? emitEpochAdvances(watch) : new Set<string>();\n const touched = conversationTouched(msg, outcome.ok ? outcome.value : undefined);\n const owed = outcome.ok ? [] : conversationsOfFailedApply(msg);\n if (touched !== null) owed.push(touched);\n if (msg.kind === \"send\" && sendLeftCopyBehind(msg, outcome, calls)) owed.push(msg.conv);\n refreshCached(owed.filter((id) => id instanceof Uint8Array && !told.has(conversationKey(id))));\n } catch {\n // Reporting is never a reason to fail the request the caller made.\n }\n}\n\nasync function runRequest(msg: Request): Promise<void> {\n // Snapshot BEFORE the request and diff after, so a self-authored commit or a\n // catch-up-applied one is announced like any other epoch change.\n const watch = watchFor(msg);\n const callsBefore = transportCalls;\n try {\n const value = await dispatch(msg);\n // Announce the epoch change BEFORE resolving the caller, so a host that\n // awaits `addMembers` and then reads a derived secret cannot observe the\n // new epoch before being told about it. The same order is what makes the\n // conversation handle fresh when the call resolves.\n reportConversations(msg, watch, { ok: true, value }, transportCalls - callsBefore);\n (self.postMessage as (m: Response) => void)({ kind: \"result\", id: msg.id, ok: true, value });\n } catch (e) {\n // A failed request can still have advanced the epoch (a commit that merged\n // locally before a later step threw), so report the change either way.\n reportConversations(msg, watch, { ok: false }, transportCalls - callsBefore);\n (self.postMessage as (m: Response) => void)({\n kind: \"result\", id: msg.id, ok: false, error: e instanceof Error ? e.message : String(e),\n });\n }\n}\n\nself.onmessage = (ev: MessageEvent<Request>) => {\n const msg = ev.data;\n\n // Storage / transport responses from the main thread — handle\n // immediately (they unblock the in-flight request). Never queued.\n if (msg.kind === \"storage.reply\") {\n const slot = pendingStorage.get(msg.id);\n if (slot) {\n pendingStorage.delete(msg.id);\n msg.ok ? slot({ ok: true, value: msg.value })\n : slot({ ok: false, value: msg.error });\n }\n return;\n }\n if (msg.kind === \"transport.reply\") {\n const slot = pendingTransport.get(msg.id);\n if (slot) {\n pendingTransport.delete(msg.id);\n msg.ok ? slot({ ok: true, value: msg.value })\n : slot({ ok: false, value: msg.error });\n }\n return;\n }\n\n // Top-level client request. A whole-account catch-up becomes a stepped\n // pass the scheduler runs one conversation per turn, behind everything\n // else queued; every other request runs FIFO, one WASM call at a time.\n // `runRequest` and the pass stepper never reject (errors are posted as\n // results), so the scheduler can't wedge.\n if (msg.kind === \"syncConversations\") {\n scheduler.enqueueStepped(catchUpPassStepper(msg));\n return;\n }\n // The SDK's own gap fill: one page per turn on the stepped lane, so a\n // send posted while a long fill runs goes between pages.\n if (msg.kind === \"syncConversationStep\" && msg.stepped === true) {\n scheduler.enqueueStepped(async () => {\n await runRequest(msg);\n return false;\n });\n return;\n }\n scheduler.enqueue(() => runRequest(msg));\n};\n\n/**\n * One whole-account catch-up as a stepped job: ONE PAGE of one conversation\n * per scheduler turn (`catch-up-pass.ts` has the policy). The scheduler runs\n * queued ordinary requests between pages. When the host transport reports\n * the server's log heads, only the conversations that are behind are\n * stepped. Each page's messages are posted as an `event.batch` (source\n * `page`) and its conversation updates come from the core's exact `updated`\n * list, so nothing here diffs epochs. The result is posted once, when the\n * pass is complete, with every decrypted application message in apply\n * order, the same contract `syncConversations()` callers have always had.\n */\nfunction catchUpPassStepper(\n msg: Extract<Request, { kind: \"syncConversations\" }>,\n): () => Promise<boolean> {\n const post = (m: Response): void => (self.postMessage as (m: Response) => void)(m);\n let pass: (() => Promise<boolean>) | null = null;\n return async (): Promise<boolean> => {\n if (pass === null) {\n try {\n await ensureWasm();\n ensureClient();\n } catch (e) {\n post({\n kind: \"result\", id: msg.id, ok: false,\n error: e instanceof Error ? e.message : String(e),\n });\n return false;\n }\n pass = catchUpPass({\n listConversationIds: () =>\n (ensureClient().listConversations() as unknown as ConversationEpoch[]).map((meta) => meta.id),\n fetchHeads: async () =>\n transportFeatures.fetchLogHeads ? (await fetchLogHeadsProxy()) ?? null : null,\n conversationsBehind: (heads) =>\n ensureClient().conversationsBehind(heads) as unknown as Uint8Array[],\n step: async (id) => {\n try {\n return await (ensureClient().syncConversationStep(id, msg.nowMs) as unknown as Promise<SyncStepResultWire>);\n } catch (e) {\n // A page that threw announced nothing; the group may still have\n // moved before the throw (see `conversationsOfFailedApply`).\n refreshCached([id]);\n throw e;\n }\n },\n onPage: (page) => {\n announceUpdated(page.updated, undefined, page.removed);\n if (page.messages.length > 0) {\n post({ kind: \"event.batch\", messages: page.messages, source: \"page\" });\n }\n },\n finish: (ok, value) => {\n if (ok) {\n post({ kind: \"result\", id: msg.id, ok: true, value });\n } else {\n post({\n kind: \"result\", id: msg.id, ok: false,\n error: value instanceof Error ? value.message : String(value),\n });\n }\n },\n });\n }\n return pass();\n };\n}\n\nasync function dispatch(msg: Request): Promise<unknown> {\n await ensureWasm();\n switch (msg.kind) {\n case \"init\": {\n transportFeatures = msg.transportFeatures ?? { fetchLogSince: false, fetchLogHeads: false };\n client = await PingClient.init(\n msg.identityExport, msg.deviceLabel,\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n makeProxyTransport(transportFeatures) as unknown as never,\n msg.nowMs,\n // Optional Ed25519 device signing secret — see protocol.ts\n // and ClientConfig.deviceSigningSecretKey. Forwarding `null`\n // explicitly when absent so the wasm-bindgen `Option<Vec<u8>>`\n // shape is matched correctly.\n msg.deviceSigningSecretKey ?? null,\n // The owner each conversation's FIRST roles write must name\n // (2026-11-04, round 2); `null` for none.\n msg.expectedOwners ?? null,\n );\n // Wire decrypted application-message callback back to the main thread.\n client.onMessage((m: unknown) => {\n (self.postMessage as (m: Response) => void)({ kind: \"event.message\", msg: m as never });\n });\n return null;\n }\n case \"openReadOnly\": {\n // No `onMessage` wiring here: a read-only client exists to answer one\n // question about one envelope, not to stream. Registering the callback\n // would also fire the tab's handlers from the worker.\n client = await PingClient.openReadOnly(\n msg.identityExport, msg.deviceLabel,\n makeProxyStorage(msg.storageFeatures) as unknown as never,\n proxyTransport as unknown as never,\n msg.nowMs,\n );\n return null;\n }\n\n case \"previewEnvelope\":\n return ensureClient().previewEnvelope(msg.envelope as unknown as never, msg.nowMs);\n case \"previewEnvelopeWithPrerequisites\":\n return ensureClient().previewEnvelopeWithPrerequisites(\n msg.prerequisites as unknown as never,\n msg.envelope as unknown as never,\n msg.nowMs,\n );\n\n case \"generateIdentity\":\n return PingClient.generateIdentity();\n case \"userId\": return ensureClient().userId();\n case \"exportIdentity\": return ensureClient().exportIdentity();\n case \"rotateIdentity\":\n // One self-update Commit per conversation moves the leaf credential to\n // the new user id; the device signing key and deviceId stay put. The\n // identity swaps even when some conversations end up in `failed`.\n return await ensureClient().rotateIdentity(msg.newIdentityExport, msg.nowMs);\n case \"rotateIdentityRetry\":\n return await ensureClient().rotateIdentityRetry(msg.conv, msg.nowMs);\n case \"deviceId\": return ensureClient().deviceId();\n case \"suspendStorage\": return ensureClient().suspendStorage();\n case \"resumeStorage\": return ensureClient().resumeStorage();\n case \"freshKeyPackage\": return ensureClient().freshKeyPackage();\n case \"freshLastResortKeyPackage\": return ensureClient().freshLastResortKeyPackage();\n case \"createConversation\":\n return await ensureClient().createConversation(msg.name ?? undefined, msg.nowMs);\n case \"createCallConversation\":\n return await ensureClient().createCallConversation(msg.name ?? undefined, msg.nowMs);\n case \"joinConversation\": {\n const id = await ensureClient().joinConversation(msg.welcome, msg.nowMs) as Uint8Array;\n // Notify the main thread that we just entered a new conversation. We forward the\n // Welcome's `sender_device` so the host can label \"joined chat with <inviter>\".\n postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));\n return id;\n }\n case \"listConversations\":\n return ensureClient().listConversations();\n case \"conversationMeta\":\n // ONE conversation, read where the group lives: no listing crosses to\n // the main thread. `null` when the client does not hold it.\n return ensureClient().conversationMeta(msg.conv) ?? null;\n case \"strandedConversations\":\n return ensureClient().strandedConversations();\n case \"conversationsLeaving\":\n return ensureClient().conversationsLeaving();\n case \"conversationsLeaveStalled\":\n return ensureClient().conversationsLeaveStalled();\n case \"readmitPendingConversations\":\n return ensureClient().readmitPendingConversations(msg.nowMs);\n case \"undeliverableCount\":\n return ensureClient().undeliverableCount();\n case \"members\":\n return ensureClient().members(msg.conv);\n case \"conversationPolicy\":\n return ensureClient().conversationPolicy(msg.conv);\n case \"setExpectedOwners\":\n return ensureClient().setExpectedOwners(msg.entries);\n case \"setConversationRoles\":\n return await ensureClient().setConversationRoles(msg.conv, msg.owner, msg.admins, msg.nowMs);\n case \"send\":\n return await ensureClient().send(msg.conv, msg.plaintext, msg.nowMs);\n case \"addMembers\":\n // wasm-bindgen takes the entries as a plain array of {deviceId, keyPackage};\n // serde-wasm-bindgen on the Rust side deserialises into Vec<JsAddMemberEntry>.\n return await ensureClient().addMembers(msg.conv, msg.entries, msg.nowMs);\n case \"addMembersWithVerdicts\":\n // Per-entry verdicts; resolves to the serialised AddMembersReport.\n return await ensureClient().addMembersWithVerdicts(msg.conv, msg.entries, msg.nowMs);\n case \"reAdmitDevice\":\n // Re-admit one device that kept its key: the leaf with the KeyPackage's\n // own signature key goes and the fresh KeyPackage is added. Never an add:\n // with no such leaf it rejects \"not permitted: ...\", and so does a\n // committer the roles do not permit. Resolves to the device id of the\n // replaced leaf.\n return await ensureClient().reAdmitDevice(msg.conv, msg.entry, msg.nowMs);\n case \"mayReadmit\":\n // A pure query: would this device's Commit re-admitting or adding that\n // device pass the membership rules now. Nothing is built or sent.\n return ensureClient().mayReadmit(msg.conv, msg.identity, msg.deviceId);\n case \"keyPackageIdentity\":\n // A pure read: the identity the KeyPackage's credential claims, after the\n // KeyPackage was validated (signatures, lifetime). `undefined` for a\n // credential that is not the project's; throws for anything else.\n return ensureClient().keyPackageIdentity(msg.keyPackage);\n case \"setConversationName\":\n // GroupContextExtensions commit carrying the new conversation name — the\n // rename / avatar-id change propagates to every member via group state.\n return await ensureClient().setConversationName(msg.conv, msg.name ?? undefined, msg.nowMs);\n case \"admitDeviceToChats\":\n // Per-chat add for a newly-linked device. Returns Vec<JsAdmitChatOutcome>\n // — the host inspects per-entry status to decide whether to retry.\n return await ensureClient().admitDeviceToChats(msg.deviceId, msg.entries, msg.nowMs);\n case \"admitDeviceToChatsConcurrent\":\n // Same per-chat add with up to `concurrency` admissions in flight inside\n // this ONE wasm call (the worker still runs one call at a time; the\n // overlap is the core's, across conversations). Outcomes in input order.\n return await ensureClient().admitDeviceToChatsConcurrent(\n msg.deviceId,\n msg.entries,\n msg.nowMs,\n msg.concurrency,\n );\n case \"removeMembers\":\n // wasm-bindgen exposes Vec<u32> as Uint32Array; convert from the protocol's number[].\n return await ensureClient().removeMembers(msg.conv, new Uint32Array(msg.leaves), msg.nowMs);\n case \"removeOwnOtherLeaves\":\n // Every OTHER leaf of this account in one conversation; resolves to the count.\n return await ensureClient().removeOwnOtherLeaves(msg.conv, msg.nowMs);\n case \"removeMembersByIdentity\":\n // Every leaf whose credential verifies for one of `identities`; resolves to the count.\n return await ensureClient().removeMembersByIdentity(msg.conv, msg.identities, msg.nowMs);\n case \"leaveConversation\":\n return await ensureClient().leaveConversation(msg.conv, msg.nowMs);\n case \"dropConversationLocal\":\n return await ensureClient().dropConversationLocal(msg.conv);\n case \"conversationsWithPendingProposals\":\n return ensureClient().conversationsWithPendingProposals();\n case \"commitPendingProposals\":\n return await ensureClient().commitPendingProposals(msg.conv, msg.nowMs);\n case \"pendingProposalsCommitRank\":\n return ensureClient().pendingProposalsCommitRank(msg.conv) ?? null;\n case \"commitsInDoubt\":\n return ensureClient().commitsInDoubt();\n case \"revokeDevice\":\n // [CR-2] returns the array of Commit envelopes the SDK has already broadcast.\n return await ensureClient().revokeDevice(msg.deviceId, msg.nowMs);\n case \"removeDeviceEverywhere\":\n // Every group, DeviceGroup first, never stopping at a failure; resolves\n // to the report the host persists and retries from.\n return await ensureClient().removeDeviceEverywhere(msg.deviceId, msg.nowMs);\n case \"removeOwnDevicesExcept\":\n // The \"secure my account\" sweep: every other leaf of this account\n // except `keep` (by credential, or listed by the server); same report.\n return await ensureClient().removeOwnDevicesExcept(msg.keep, msg.listed, msg.nowMs);\n case \"processEnvelope\": {\n const result = await ensureClient().processEnvelope(msg.envelope, msg.nowMs);\n postConversationEvent(\n msg.envelope.conversation_id, msg.envelope.epoch, undefined,\n readMeta(msg.envelope.conversation_id),\n );\n return result;\n }\n case \"pendingApplies\":\n // [D27] Journal listing — reading does not consume.\n return ensureClient().pendingApplies();\n case \"confirmApplied\":\n // [D27] Removes + checkpoints; unknown ids are ignored (idempotent).\n return await ensureClient().confirmApplied(msg.journalIds);\n case \"syncConversations\":\n // Reached only if a caller bypasses `onmessage`; the scheduler turns\n // this kind into a stepped pass before it can get here.\n return await ensureClient().syncConversations(msg.nowMs);\n case \"syncConversation\":\n return await ensureClient().syncConversation(msg.conv, msg.nowMs);\n // Sequenced log sync. The batch and page results carry their messages\n // (the wasm does not fan them out through `onMessage`); the main thread\n // delivers them from the result. Conversation updates are announced from\n // the core's exact `updated` list, before the result resolves.\n case \"processSequencedBatch\": {\n const raw = await ensureClient().processSequencedBatch(msg.items, msg.nowMs) as unknown as ApplyBatchResultWire;\n announceUpdated(raw.updated, welcomeSenders(msg.items, raw.joined), raw.removed);\n return raw;\n }\n case \"syncConversationStep\": {\n const raw = await ensureClient().syncConversationStep(msg.conv, msg.nowMs) as unknown as SyncStepResultWire;\n announceUpdated(raw.updated, undefined, raw.removed);\n return raw;\n }\n case \"logPositions\":\n return ensureClient().logPositions();\n case \"logPosition\":\n return ensureClient().logPosition(msg.conv);\n case \"adoptLogPosition\":\n return await ensureClient().adoptLogPosition(msg.conv, msg.epoch, msg.serverSeq);\n case \"conversationsBehind\":\n return ensureClient().conversationsBehind(msg.heads);\n case \"heldFrameCount\":\n return ensureClient().heldFrameCount();\n case \"joinConversationAt\": {\n const id = await ensureClient().joinConversationAt(msg.welcome, msg.position, msg.nowMs) as Uint8Array;\n postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));\n return id;\n }\n case \"processWelcomeAt\": {\n const id = await ensureClient().processWelcomeAt(msg.welcome, msg.position, msg.nowMs) as Uint8Array | null;\n if (id !== null && id !== undefined) {\n postConversationEvent(id, 0, msg.welcome.sender_device, readMeta(id));\n return id;\n }\n return null;\n }\n case \"buildLinkingTicket\":\n return await ensureClient().buildLinkingTicket(\n msg.newDeviceId, msg.newDeviceKp, msg.lastAppEvents, msg.nowMs,\n );\n case \"consumeLinkingTicket\":\n await ensureClient().consumeLinkingTicket(msg.ticket, msg.nowMs);\n return null;\n case \"decodeCatchupSnapshot\":\n // Pure WASM — no client state required. The new device may call this in an\n // ephemeral worker before init() completes.\n return wasmDecodeCatchupSnapshot(msg.snapshotBytes);\n case \"exportConversationSecret\":\n // wasm-bindgen returns a Uint8Array sized to `length`. The bytes are a secret —\n // the main thread is responsible for clearing the typed array when done.\n return ensureClient().exportConversationSecret(\n msg.conv, msg.label, msg.context, msg.length,\n );\n case \"exportConversationSecretWithEpoch\":\n // `{ epoch, secret }` from ONE read inside the core: the epoch is the one\n // the secret was exported at. Passed through as it is, never rebuilt from\n // a second read. The secret is the main thread's to clear when done.\n return ensureClient().exportConversationSecretWithEpoch(\n msg.conv, msg.label, msg.context, msg.length,\n );\n case \"sealLinkingTicket\":\n // Pure WASM call — no client state required. Lets a sender seal a ticket from an\n // ephemeral worker without standing up the full PingClient.\n return wasmSealLinkingTicket(msg.ticket, msg.newDevicePub);\n case \"openLinkingTicket\":\n // Same — runs without an initialised client, which is the receiving device's\n // pre-bootstrap state (it has the X25519 ephemeral key but no identity yet).\n return wasmOpenLinkingTicket(msg.sealed, msg.newDevicePriv);\n case \"hpkeSeal\":\n // Generic HPKE seal for app-layer envelopes (e.g. linking auth envelope).\n return wasmHpkeSeal(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpen\":\n return wasmHpkeOpen(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeSealRaw\":\n // The RFC 9180 canonical layout (`enc || ct`), which the app layers use.\n return wasmHpkeSealRaw(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenRaw\":\n return wasmHpkeOpenRaw(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeGenerateKeypair\":\n return wasmHpkeGenerateKeypair();\n // Post-quantum (X-Wing) twins: all pure WASM, no client state required.\n case \"sealLinkingTicketPq\":\n return wasmSealLinkingTicketPq(msg.ticket, msg.newDevicePub);\n case \"openLinkingTicketPq\":\n return wasmOpenLinkingTicketPq(msg.sealed, msg.newDevicePriv);\n case \"hpkeSealPq\":\n return wasmHpkeSealPq(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenPq\":\n return wasmHpkeOpenPq(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeSealRawPq\":\n return wasmHpkeSealRawPq(msg.plaintext, msg.recipientPub, msg.info);\n case \"hpkeOpenRawPq\":\n return wasmHpkeOpenRawPq(msg.sealed, msg.recipientPriv, msg.info);\n case \"hpkeGenerateKeypairPq\":\n return wasmHpkeGenerateKeypairPq();\n case \"hpkePublicKeyFromSeed\":\n return wasmHpkePublicKeyFromSeed(msg.seed);\n case \"deviceGroupIdFor\":\n // Pure: the core's DeviceGroup id derivation for an MLS user id.\n return wasmDeviceGroupIdFor(msg.userId);\n case \"hpkePublicKeyFromPrivate\":\n return wasmHpkePublicKeyFromPrivate(msg.privateKey);\n case \"signDeviceReauth\":\n // Pure WASM: the SDK builds the signed bytes, so this signs nothing else\n // with the device key. Returns `deviceId (32) || signature (64)`.\n return wasmSignDeviceReauth(msg.deviceSigningSecretKey, msg.challengeId, msg.nonce, msg.accountId, msg.audience);\n case \"signDeviceLinkApproval\":\n // Pure WASM, link verification v2: the SDK builds the signed bytes and\n // derives both ids. Returns `approverDeviceId (32) || newDeviceId (32) ||\n // signature (64)`.\n return wasmSignDeviceLinkApproval(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.newDevicePubkey, msg.audience);\n case \"signDeviceLinkPossession\":\n // Pure WASM. Returns `deviceId (32) || signature (64)`.\n return wasmSignDeviceLinkPossession(msg.deviceSigningSecretKey, msg.approvalSessionId, msg.accountId, msg.audience);\n case \"exportConversationStateSnapshot\":\n // [CR-7] state snapshot bytes are a secret (past epoch keys); the main thread\n // is responsible for clearing the typed array when done.\n return ensureClient().exportConversationStateSnapshot(msg.conv, msg.nowMs);\n case \"importStateSnapshot\":\n // [CR-7] returns the imported conversation id as a Uint8Array.\n return await ensureClient().importStateSnapshot(msg.snapshotBytes, msg.nowMs);\n // Recovery — all pure WASM; no client state required.\n case \"generateMnemonicPhrase\":\n return wasmGenerateMnemonicPhrase();\n case \"normalizeMnemonicPhrase\":\n return wasmNormalizeMnemonicPhrase(msg.phrase);\n case \"encryptBackup\":\n return wasmEncryptBackup(\n msg.mnemonicPhrase, msg.accountId, msg.identityExport,\n msg.deviceGroupSnapshot,\n // Map idiomatic camelCase → the snake_case keys serde expects on the\n // WASM boundary (matches the decrypt view's account_id / group_state_bytes).\n msg.conversationSnapshots.map((c) => ({\n conversation_id: c.conversationId,\n group_state_bytes: c.groupStateBytes,\n })),\n msg.createdAtMs,\n );\n case \"decryptBackup\":\n return wasmDecryptBackup(msg.blob, msg.mnemonicPhrase);\n case \"checkBackupPhrase\":\n // `{ outcome, reason? }`, the wasm's own codes, passed on untouched.\n return wasmCheckBackupPhrase(msg.blob, msg.mnemonicPhrase);\n case \"sealHistoryBundle\":\n return wasmSealHistoryBundle(msg.bundle, msg.recipientPub, msg.senderIdentitySecret);\n case \"openHistoryBundle\":\n return wasmOpenHistoryBundle(msg.sealed, msg.recipientPriv, msg.senderIdentityPub);\n case \"sealHistoryBundlePq\":\n return wasmSealHistoryBundlePq(msg.bundle, msg.recipientPub, msg.senderIdentitySecret);\n case \"openHistoryBundlePq\":\n return wasmOpenHistoryBundlePq(msg.sealed, msg.recipientPriv, msg.senderIdentityPub);\n default:\n throw new Error(`unknown request kind: ${(msg as { kind: string }).kind}`);\n }\n}\n\nfunction ensureClient(): PingClient {\n if (!client) throw new Error(\"client not initialised\");\n return client;\n}\n","// Which conversations' MLS epochs moved, and therefore which `event.conversation`\n// notifications the worker owes the main thread.\n//\n// This lives outside `worker.ts` purely so it is testable: importing the worker\n// module runs its top-level `self.onmessage` wiring, which needs a\n// `DedicatedWorkerGlobalScope`. The rule it encodes is small but load-bearing —\n// see `EPOCH_ADVANCING_REQUESTS` in the worker for why a self-authored or\n// catch-up-applied commit would otherwise be announced to nobody.\n\n/** The two fields of a `ConversationMeta` this comparison needs. */\nexport interface ConversationEpoch {\n id: Uint8Array;\n epoch: number;\n}\n\n/** Stable map key for a 16-byte conversation id. */\nexport function conversationKey(id: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < id.length; i += 1) out += (id[i] ?? 0).toString(16).padStart(2, \"0\");\n return out;\n}\n\n/** Epoch per conversation, keyed by `conversationKey`. */\nexport function epochMap(metas: readonly ConversationEpoch[]): Map<string, number> {\n const out = new Map<string, number>();\n for (const meta of metas) out.set(conversationKey(meta.id), meta.epoch);\n return out;\n}\n\n/**\n * Conversations whose epoch STRICTLY advanced between `before` and `after`.\n *\n * Only conversations present in both are considered:\n * - a conversation that is new since `before` was either just created by this\n * caller or just joined, and `joinConversation` already announces the\n * latter — announcing it here would double-fire;\n * - a conversation that has disappeared (left / dropped) has no epoch to\n * report;\n * - an epoch that did not move is not an event, however many times the\n * request that ran touched the group.\n *\n * The elements returned are the elements of `after` themselves, so a caller\n * that listed whole metadata records gets them back whole.\n */\nexport function advancedEpochs<T extends ConversationEpoch>(\n before: ReadonlyMap<string, number>,\n after: readonly T[],\n): T[] {\n const out: T[] = [];\n for (const meta of after) {\n const previous = before.get(conversationKey(meta.id));\n if (previous === undefined || meta.epoch <= previous) continue;\n out.push(meta);\n }\n return out;\n}\n\n/** The id a `conversationKey` was made from. */\nexport function conversationIdOf(key: string): Uint8Array {\n const out = new Uint8Array(key.length >> 1);\n for (let i = 0; i < out.length; i += 1) out[i] = Number.parseInt(key.slice(i * 2, i * 2 + 2), 16);\n return out;\n}\n\n/**\n * The conversations a request brought in or took away, which\n * {@link advancedEpochs} deliberately does not report.\n *\n * They are not host events (whoever joined or left already said so, or it is\n * not an epoch change at all), but the main thread's copy of a conversation's\n * metadata must still follow them: a conversation that `appeared` is held\n * now, one that `disappeared` is not, and a copy that kept answering for it\n * would be answering for a group this device no longer reads.\n */\nexport function changedHoldings<T extends ConversationEpoch>(\n before: ReadonlyMap<string, number>,\n after: readonly T[],\n): { appeared: T[]; disappeared: Uint8Array[] } {\n const appeared: T[] = [];\n const still = new Set<string>();\n for (const meta of after) {\n const key = conversationKey(meta.id);\n still.add(key);\n if (!before.has(key)) appeared.push(meta);\n }\n const disappeared: Uint8Array[] = [];\n for (const key of before.keys()) {\n if (!still.has(key)) disappeared.push(conversationIdOf(key));\n }\n return { appeared, disappeared };\n}\n","// The whole-account catch-up as a stepped job: one PAGE of one conversation\n// per scheduler turn.\n//\n// `syncConversations()` used to page each conversation to its end inside one\n// wasm call; a 2,000-message group backlog was eight pages behind which\n// every queued send waited. Each call of the returned step now applies ONE\n// page through `syncConversationStep` and yields, so the primary lane (a\n// send, a live batch, a host's own step) runs between pages as well as\n// between conversations. A conversation whose page was full stays at the\n// head of the queue and continues next turn.\n//\n// When the transport can report the server's log heads, only the\n// conversations `conversationsBehind` names are stepped: one request instead\n// of one page per conversation the account holds. A transport without\n// `fetchLogHeads` (or one that answers `null`: the relay has no heads route)\n// gets the whole-account walk, as before. A heads request that FAILS ends\n// the pass with that error instead: walking every conversation on a network\n// that just failed one request would fail N more times, and the host retries\n// the pass on its next trigger (reconnect, foreground, heartbeat), by which\n// time the socket's `resume_ack` has usually named what is behind anyway.\n//\n// The pass ends with one re-list so a conversation joined while it ran is\n// still covered, exactly as the core re-reads its map. Conversations already\n// evaluated (stepped, or present in the heads snapshot) are not re-stepped.\n//\n// Lives outside `worker.ts` so it is testable without a\n// `DedicatedWorkerGlobalScope`; the worker supplies the dependencies.\n\nimport { conversationKey } from \"./epoch-events\";\nimport type { LogHeadWire, SyncStepResultWire } from \"./sequenced\";\nimport type { IncomingMessage } from \"./types\";\n\nexport interface CatchUpPassDeps {\n /** Ids of every conversation the client holds right now. */\n listConversationIds(): Uint8Array[];\n /** The server's heads, or `null` when the transport cannot report them. */\n fetchHeads(): Promise<LogHeadWire[] | null>;\n /** The core's verdict on which of `heads` this device is behind on. */\n conversationsBehind(heads: LogHeadWire[]): Uint8Array[];\n /** Apply ONE page of one conversation. */\n step(id: Uint8Array): Promise<SyncStepResultWire>;\n /** Deliver a page: its conversation updates and its messages. */\n onPage(result: SyncStepResultWire): void;\n /** Post the pass result: every message in apply order, or the error. */\n finish(ok: boolean, value: IncomingMessage[] | unknown): void;\n}\n\n/**\n * Build the stepped job. Each call runs one step and resolves `true` while\n * the pass has more to do; it never rejects (errors are posted through\n * `finish`).\n */\nexport function catchUpPass(deps: CatchUpPassDeps): () => Promise<boolean> {\n const seen = new Set<string>();\n const delivered: IncomingMessage[] = [];\n let pending: Uint8Array[] | null = null;\n let relisted = false;\n\n const sortedUnseen = (ids: Uint8Array[]): Uint8Array[] =>\n ids\n .filter((id) => !seen.has(conversationKey(id)))\n .sort((a, b) => (conversationKey(a) < conversationKey(b) ? -1 : 1));\n\n const initial = async (): Promise<Uint8Array[]> => {\n // A rejection propagates to the caller, which posts it through `finish`.\n const heads = await deps.fetchHeads();\n if (heads === null) return sortedUnseen(deps.listConversationIds());\n // Every conversation the heads describe has been evaluated: the ones\n // that are current are not stepped now and not re-stepped by the re-list.\n for (const h of heads) seen.add(conversationKey(h.conversation_id));\n const behind = deps.conversationsBehind(heads);\n for (const id of behind) seen.delete(conversationKey(id));\n return sortedUnseen(behind);\n };\n\n return async (): Promise<boolean> => {\n try {\n if (pending === null) pending = await initial();\n if (pending.length === 0 && !relisted) {\n relisted = true;\n pending = sortedUnseen(deps.listConversationIds());\n }\n } catch (e) {\n deps.finish(false, e);\n return false;\n }\n const id = pending[0];\n if (id === undefined) {\n deps.finish(true, delivered);\n return false;\n }\n let more = false;\n try {\n const page = await deps.step(id);\n for (const m of page.messages) delivered.push(m);\n deps.onPage(page);\n more = page.has_more;\n } catch {\n // Dropped between the listing and this step (a wipe, a self-removal),\n // a transport failure, or a checkpoint failure: this conversation's\n // paging ends for this pass. The durable cursor is where the next\n // pass resumes, which is what the whole-account request did too.\n }\n if (!more) {\n seen.add(conversationKey(id));\n pending.shift();\n }\n return true;\n };\n}\n","// Request scheduling for the WASM worker: one call in flight at a time, in\n// two lanes.\n//\n// The worker may run only ONE WASM call at a time (see `worker.ts`), so every\n// request waits for the one before it. That is fine for the requests a user\n// is waiting on (a send, a live frame) — they are short. It was not fine for a\n// whole-account catch-up, which paged every conversation inside a single\n// request: a `send` posted while it ran started after all of them, and on a\n// tab returning from an idle hour that wait WAS the first message's latency.\n//\n// This scheduler keeps the one-call invariant and adds a second lane for\n// work that is allowed to be interrupted between its natural steps. An\n// ordinary request runs FIFO in the primary lane; a stepped job runs one\n// step per turn and only when the primary lane is empty, so anything queued\n// while a step ran goes next. Stepped jobs are FIFO among themselves and a\n// job's steps never interleave with another job's.\n//\n// Lives outside `worker.ts` so it is testable without a\n// `DedicatedWorkerGlobalScope` (the same reason `epoch-events.ts` exists).\n\n/** An ordinary request: runs to completion in one turn. Must not reject. */\nexport type LaneJob = () => Promise<void>;\n\n/**\n * A stepped job: each call runs ONE step and resolves `true` while more steps\n * remain. A rejected step ends the job (the scheduler treats it as `false`).\n */\nexport type SteppedJob = () => Promise<boolean>;\n\nexport class RequestScheduler {\n private readonly primary: LaneJob[] = [];\n private readonly stepped: SteppedJob[] = [];\n private pumping = false;\n\n /** Queue an ordinary request behind the ordinary requests before it. */\n enqueue(job: LaneJob): void {\n this.primary.push(job);\n void this.pump();\n }\n\n /** Queue a stepped job; its steps run whenever the primary lane is empty. */\n enqueueStepped(job: SteppedJob): void {\n this.stepped.push(job);\n void this.pump();\n }\n\n /** Requests waiting in the primary lane (diagnostics / tests). */\n get pendingPrimary(): number {\n return this.primary.length;\n }\n\n /** Stepped jobs not yet finished (diagnostics / tests). */\n get pendingStepped(): number {\n return this.stepped.length;\n }\n\n private async pump(): Promise<void> {\n if (this.pumping) return;\n this.pumping = true;\n try {\n for (;;) {\n const job = this.primary.shift();\n if (job !== undefined) {\n // A job posts its own error as a result; a rejection here would\n // only mean a bug in the job, and it must not stall the lane.\n await job().catch(() => undefined);\n continue;\n }\n const step = this.stepped[0];\n if (step === undefined) return;\n let more = false;\n try {\n more = await step();\n } catch {\n more = false;\n }\n if (!more) this.stepped.shift();\n }\n } finally {\n this.pumping = false;\n }\n }\n}\n"],"mappings":";AAkBO,IAAM,sBAAsB,CAAC,KAAK,KAAK,IAAI,EAAE;AACpD,IAAM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AI;AAAA,MACN;AAAA,IACF,KAAK;AACH,aAAO,kBAAkB,IAAI,MAAM,IAAI,cAAc;AAAA,IACvD,KAAK;AAEH,aAAO,sBAAsB,IAAI,MAAM,IAAI,cAAc;AAAA,IAC3D,KAAK;AACH,aAAO,sBAAsB,IAAI,QAAQ,IAAI,cAAc,IAAI,oBAAoB;AAAA,IACrF,KAAK;AACH,aAAO,sBAAsB,IAAI,QAAQ,IAAI,eAAe,IAAI,iBAAiB;AAAA,IACnF,KAAK;AACH,aAAO,wBAAwB,IAAI,QAAQ,IAAI,cAAc,IAAI,oBAAoB;AAAA,IACvF,KAAK;AACH,aAAO,wBAAwB,IAAI,QAAQ,IAAI,eAAe,IAAI,iBAAiB;AAAA,IACrF;AACE,YAAM,IAAI,MAAM,yBAA0B,IAAyB,IAAI,EAAE;AAAA,EAC7E;AACF;AAEA,SAAS,eAA2B;AAClC,MAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,wBAAwB;AACrD,SAAO;AACT;","names":[]}
|
package/package.json
CHANGED
package/wasm/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "ping-openmls-sdk-wasm",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"description": "wasm-bindgen surface for the Ping OpenMLS SDK — drives the ping-openmls-sdk npm package",
|
|
5
|
-
"version": "0.10.
|
|
5
|
+
"version": "0.10.3",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
7
|
"files": [
|
|
8
8
|
"ping_wasm_bg.wasm",
|
package/wasm/ping_wasm.d.ts
CHANGED
|
@@ -601,6 +601,23 @@ export class PingClient {
|
|
|
601
601
|
|
|
602
602
|
export function _start(): void;
|
|
603
603
|
|
|
604
|
+
/**
|
|
605
|
+
* Whether `mnemonicPhrase` opens `blob`, with THREE answers
|
|
606
|
+
* (`ping_recovery::check_backup_phrase`). Resolves
|
|
607
|
+
* `{ outcome: "opens" | "authenticationFailed" | "couldNotCheck", reason? }`,
|
|
608
|
+
* where `reason` is set exactly for `couldNotCheck`: `"invalidPhrase"`,
|
|
609
|
+
* `"unsupportedVersion"`, `"malformed"`, `"undecodable"` or `"internal"`. The
|
|
610
|
+
* codes are the core's (`outcome_code`, `BackupCheckFailure::code`), pinned
|
|
611
|
+
* there and replayed from one table by `sdk/js`
|
|
612
|
+
* (`backup-phrase-check.test.ts`).
|
|
613
|
+
*
|
|
614
|
+
* `authenticationFailed` is the only proof that the phrase does not open
|
|
615
|
+
* these bytes; every `couldNotCheck` is a doubt. Never throws for an answer
|
|
616
|
+
* of the check, returns nothing of the backup, logs nothing. `decryptBackup`
|
|
617
|
+
* is unchanged and still rejects with its one message.
|
|
618
|
+
*/
|
|
619
|
+
export function checkBackupPhrase(blob: Uint8Array, mnemonic_phrase: string): any;
|
|
620
|
+
|
|
604
621
|
/**
|
|
605
622
|
* HPKE-open a sealed `LinkingTicket` ([CR-3]). Pure function — usable without an
|
|
606
623
|
* initialized `PingClient`, which is exactly the situation the receiving device is in
|
|
@@ -816,6 +833,7 @@ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembl
|
|
|
816
833
|
export interface InitOutput {
|
|
817
834
|
readonly memory: WebAssembly.Memory;
|
|
818
835
|
readonly __wbg_pingclient_free: (a: number, b: number) => void;
|
|
836
|
+
readonly checkBackupPhrase: (a: number, b: number, c: number, d: number, e: number) => void;
|
|
819
837
|
readonly decodeCatchupSnapshot: (a: number, b: number, c: number) => void;
|
|
820
838
|
readonly decryptBackup: (a: number, b: number, c: number, d: number, e: number) => void;
|
|
821
839
|
readonly deviceGroupIdFor: (a: number, b: number) => number;
|
|
@@ -917,8 +935,8 @@ export interface InitOutput {
|
|
|
917
935
|
readonly signDeviceLinkPossession: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number) => void;
|
|
918
936
|
readonly signDeviceReauth: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number) => void;
|
|
919
937
|
readonly _start: () => void;
|
|
920
|
-
readonly
|
|
921
|
-
readonly
|
|
938
|
+
readonly __wasm_bindgen_func_elem_4223: (a: number, b: number, c: number, d: number) => void;
|
|
939
|
+
readonly __wasm_bindgen_func_elem_4238: (a: number, b: number, c: number, d: number) => void;
|
|
922
940
|
readonly __wbindgen_export: (a: number, b: number) => number;
|
|
923
941
|
readonly __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
|
|
924
942
|
readonly __wbindgen_export3: (a: number) => void;
|