@ping-app/ping-openmls-sdk 0.9.2 → 0.10.1
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 +91 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +52 -5
- package/dist/index.d.ts +52 -5
- package/dist/index.js +90 -8
- package/dist/index.js.map +1 -1
- package/dist/notification-preview.cjs +25 -0
- package/dist/notification-preview.cjs.map +1 -1
- package/dist/notification-preview.d.cts +40 -1
- package/dist/notification-preview.d.ts +40 -1
- package/dist/notification-preview.js +23 -0
- package/dist/notification-preview.js.map +1 -1
- package/dist/worker.cjs +214 -53
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.js +214 -53
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/wasm/package.json +1 -1
- package/wasm/ping_wasm.d.ts +47 -2
- package/wasm/ping_wasm.js +102 -23
- package/wasm/ping_wasm_bg.wasm +0 -0
- package/wasm/ping_wasm_bg.wasm.d.ts +4 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/fanout.ts","../src/gap-fill.ts","../src/inbound-coalescer.ts","../src/storage/scope.ts","../src/sequenced.ts","../src/storage/indexeddb.ts","../src/wire-contract.ts","../src/transport/websocket.ts","../src/wasm-memory.ts","../src/notification-preview.ts","../src/index.ts"],"sourcesContent":["// Delivery of decrypted messages to host handlers.\n//\n// Two subscriptions: `onMessage` (one call per message, the surface every\n// host has used so far) and `onMessageBatch` (one call per batch or page\n// result, so a host persists the whole batch in one store transaction). When\n// at least one batch handler is registered, batch and page results go ONLY\n// to the batch handlers; otherwise they are fanned out per message to the\n// `onMessage` handlers, so an existing host keeps working unchanged. The\n// legacy per-envelope path always delivers per message.\n//\n// Every handler call is guarded: a throwing handler used to abort the loop\n// and starve every handler registered after it. The log line carries the\n// error's kind only (never its message, which a handler could have built\n// from plaintext).\n//\n// Lives outside `index.ts` so it is testable without a Worker.\n\nimport type { IncomingMessage, MessageBatchMeta } from \"./types\";\n\nexport type MessageHandler = (m: IncomingMessage) => void;\nexport type BatchHandler = (messages: IncomingMessage[], meta: MessageBatchMeta) => void;\n\n/** The error's kind for a log line: its name, never its message. */\nexport function errorKind(e: unknown): string {\n if (e instanceof Error) return e.name;\n return typeof e;\n}\n\nexport class MessageFanout {\n private readonly messageHandlers = new Set<MessageHandler>();\n private readonly batchHandlers = new Set<BatchHandler>();\n\n onMessage(handler: MessageHandler): () => void {\n this.messageHandlers.add(handler);\n return () => this.messageHandlers.delete(handler);\n }\n\n onMessageBatch(handler: BatchHandler): () => void {\n this.batchHandlers.add(handler);\n return () => this.batchHandlers.delete(handler);\n }\n\n get hasBatchHandlers(): boolean {\n return this.batchHandlers.size > 0;\n }\n\n /** One message from the legacy per-envelope path. */\n deliverOne(m: IncomingMessage): void {\n for (const h of this.messageHandlers) {\n try {\n h(m);\n } catch (e) {\n if (typeof console !== \"undefined\") {\n console.debug(\"[ping-sdk] onMessage handler threw:\", errorKind(e));\n }\n }\n }\n }\n\n /**\n * One batch or page result. An empty result is not delivered: there is\n * nothing to persist, and the caller already has the result value.\n */\n deliverBatch(messages: IncomingMessage[], meta: MessageBatchMeta): void {\n if (messages.length === 0) return;\n if (this.batchHandlers.size === 0) {\n for (const m of messages) this.deliverOne(m);\n return;\n }\n for (const h of this.batchHandlers) {\n try {\n h(messages, meta);\n } catch (e) {\n if (typeof console !== \"undefined\") {\n console.debug(\"[ping-sdk] onMessageBatch handler threw:\", errorKind(e));\n }\n }\n }\n }\n}\n","// Single-flight gap filling: one loop of `syncConversationStep` per\n// conversation, run until the server reports no more rows.\n//\n// A gap is a hole between what this device has applied and a live frame the\n// SDK holds; it is resolved only against the server log, one page at a time.\n// Two callers asking for the same conversation share one loop. A request\n// that lands while a loop is already running is remembered (`again`), and\n// the loop runs once more after it finishes: the running loop may have\n// fetched its last page before the frame that reported the new gap was\n// appended, so ending on that page alone could leave the hole open until the\n// next batch happened to report it.\n//\n// Lives outside `index.ts` so it is testable without a Worker.\n\ninterface Lane {\n run: Promise<void>;\n again: boolean;\n}\n\nexport class GapFiller {\n private readonly lanes = new Map<string, Lane>();\n\n /**\n * Fill the gap for `key`. `stepOnce` applies ONE page and resolves `true`\n * while the server may hold more. Resolves when the loop (and any rerun a\n * concurrent request asked for) has finished; rejects with the first step\n * error, which ends that loop.\n */\n fill(key: string, stepOnce: () => Promise<boolean>): Promise<void> {\n const running = this.lanes.get(key);\n if (running !== undefined) {\n running.again = true;\n return running.run;\n }\n const lane: Lane = { run: Promise.resolve(), again: false };\n lane.run = (async () => {\n try {\n do {\n lane.again = false;\n let more = true;\n while (more) more = await stepOnce();\n } while (lane.again);\n } finally {\n if (this.lanes.get(key) === lane) this.lanes.delete(key);\n }\n })();\n this.lanes.set(key, lane);\n return lane.run;\n }\n\n /** Conversations with a fill loop running (diagnostics / tests). */\n get inFlight(): number {\n return this.lanes.size;\n }\n}\n","// Per-conversation batching of sequenced live frames.\n//\n// The first frame for a conversation is applied at once, as a batch of one.\n// Frames that arrive while that batch is in flight accumulate and go out as\n// ONE batch the moment it returns; no timer ever holds a frame back. The\n// core orders frames by their server position, so what this buys is not\n// ordering but cost: one MLS checkpoint and one host transaction per burst\n// instead of one per frame (see docs/SYNC_PROTOCOL.md \"Sequenced log sync\",\n// cost model).\n//\n// Lanes are keyed by conversation, so a busy group can never head-of-line\n// block another conversation, and an entry lives only while that\n// conversation has work in flight: it is removed the moment the last batch\n// settles with nothing queued, the same bound `dispatchIncoming` keeps for\n// its legacy chains.\n//\n// Lives outside `index.ts` so it is testable without a Worker.\n\nexport type BatchApplier<T> = (key: string, items: T[]) => Promise<void>;\n\ninterface Settler {\n resolve(): void;\n reject(error: unknown): void;\n}\n\ninterface Lane<T> {\n queued: T[];\n waiters: Settler[];\n}\n\nexport class InboundCoalescer<T> {\n private readonly lanes = new Map<string, Lane<T>>();\n\n /**\n * @param apply Applies one batch. A rejection settles the promises of the\n * frames in that batch with the error and the lane moves on to whatever\n * queued meanwhile, so one bad batch cannot wedge a conversation.\n * @param maxBatch Upper bound on frames per batch. A burst larger than\n * this goes out as consecutive batches of at most `maxBatch`, so a\n * flood cannot turn into one unbounded wasm call.\n */\n constructor(\n private readonly apply: BatchApplier<T>,\n private readonly maxBatch = 256,\n ) {}\n\n /**\n * Queue a frame. Resolves when the batch that carried it has been applied\n * (rejects if that batch failed), so a transport that awaits the dispatch\n * to ack a watermark still sees the truth.\n */\n push(key: string, item: T): Promise<void> {\n const lane = this.lanes.get(key);\n if (lane !== undefined) {\n return new Promise<void>((resolve, reject) => {\n lane.queued.push(item);\n lane.waiters.push({ resolve, reject });\n });\n }\n const fresh: Lane<T> = { queued: [], waiters: [] };\n this.lanes.set(key, fresh);\n return this.run(key, fresh, [item], []);\n }\n\n /** Conversations with a batch in flight (diagnostics / tests). */\n get inFlight(): number {\n return this.lanes.size;\n }\n\n private run(key: string, lane: Lane<T>, items: T[], waiters: Settler[]): Promise<void> {\n let attempt: Promise<void>;\n try {\n attempt = this.apply(key, items);\n } catch (e) {\n attempt = Promise.reject(e);\n }\n attempt.then(\n () => {\n for (const w of waiters) w.resolve();\n },\n (e: unknown) => {\n for (const w of waiters) w.reject(e);\n },\n );\n // The next batch, or the cleanup, follows however this one ended.\n void attempt.then(\n () => this.drain(key, lane),\n () => this.drain(key, lane),\n );\n return attempt;\n }\n\n private drain(key: string, lane: Lane<T>): void {\n if (lane.queued.length === 0) {\n // Only the lane that owns the entry clears it; a lane that replaced it\n // (which cannot happen while this one is registered, but the check is\n // what makes that invariant harmless to break) stays.\n if (this.lanes.get(key) === lane) this.lanes.delete(key);\n return;\n }\n const items = lane.queued.splice(0, this.maxBatch);\n const waiters = lane.waiters.splice(0, items.length);\n // Rejections reach the waiters above; nothing else awaits this chain.\n void this.run(key, lane, items, waiters).catch(() => undefined);\n }\n}\n","// Per-account storage scoping, and the optional-method probe that has to agree\n// with it.\n//\n// `MessagingClient` and `openNotificationPreview` both scope through\n// `scopeStorage`, so the tab's writer and the Service Worker's reader can never\n// disagree about which slot a namespace lives in.\n\nimport type { StorageFeatures } from \"../protocol\";\nimport type { Storage } from \"../types\";\n\n/**\n * Wrap a host `Storage` so every namespace carries the per-account scope\n * prefix: `\"${accountNamespace} ${ns}\"`, space separator. Keys and values pass\n * through untouched.\n *\n * The optional batch methods are forwarded exactly when the host has them.\n * That matters because the client tells the wasm which of them exist by\n * probing the storage it will actually call (`storageFeaturesOf`). This\n * wrapper once forwarded only the four basic methods, while the probe looked\n * at the unwrapped host: every scoped account was told `listEntries` existed,\n * the call reached the wrapper, resolved `undefined`, and the store open failed\n * with \"listEntries must resolve to an array\". A dropped `applyBatch` would\n * have been worse, acknowledging writes that never happened.\n */\nexport function scopeStorage(storage: Storage, accountNamespace: string): Storage {\n const scope = (ns: string): string => `${accountNamespace} ${ns}`;\n const scoped: Storage = {\n get: (ns, key) => storage.get(scope(ns), key),\n put: (ns, key, value) => storage.put(scope(ns), key, value),\n del: (ns, key) => storage.del(scope(ns), key),\n listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix),\n };\n const hostApplyBatch = storage.applyBatch;\n if (typeof hostApplyBatch === \"function\") {\n scoped.applyBatch = (ns, puts, deletes) =>\n hostApplyBatch.call(storage, scope(ns), puts, deletes);\n }\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);\n }\n return scoped;\n}\n\n/**\n * Which optional methods `storage` really has. Probe the storage the client\n * dispatches to (after any wrapping), never the one the host passed in: the\n * worker hands the wasm a proxy for exactly these, and a method the dispatch\n * target lacks must never be advertised.\n */\nexport function storageFeaturesOf(storage: Storage): StorageFeatures {\n return {\n applyBatch: typeof storage.applyBatch === \"function\",\n listEntries: typeof storage.listEntries === \"function\",\n };\n}\n","// Sequenced log sync: the shapes that cross the wasm boundary and their\n// conversion to the public surface.\n//\n// FIELD CONVENTIONS, DOCUMENTED ONCE. The wasm crate serialises the core's\n// `SequencedEnvelope` / `LogPosition` / `LogHead` / `LogGap` /\n// `ConversationUpdate` / `ApplyBatchResult` / `SyncStepResult` with serde's\n// default snake_case field names, exactly as it already does for\n// `MessageEnvelope` and `IncomingMessage`. Those two older types are exposed\n// on the JS surface UNCHANGED (snake_case), and every message inside a batch\n// or page result keeps that shape: an `IncomingMessage` from\n// `processSequencedBatch` is byte-for-byte the object `onMessage` has always\n// delivered. The NEW wrapper types are exposed in camelCase (`serverSeq`,\n// `hasMore`, `conversationId`), the convention the JS surface uses for the\n// shapes it added after the wire types (`IdentityRotation`,\n// `AdmitChatOutcome`, `KeyPackageEntry`). The converters below are the only\n// place that mapping lives; the worker speaks the wire shape, the main\n// thread speaks the public one.\n//\n// Kept free of worker globals so it is testable under vitest.\n\nimport type {\n AddMemberStatus,\n AddMembersReport,\n ApplyBatchResult,\n BufferOverflow,\n CommitInDoubt,\n ConversationId,\n ConversationRemoval,\n ConversationUpdate,\n IncomingMessage,\n LogGap,\n LogHead,\n LogPosition,\n MessageEnvelope,\n OverflowReason,\n SequencedEnvelope,\n StrandedConversation,\n StrandReason,\n SyncStepResult,\n WelcomeFailure,\n WelcomeFailureReason,\n} from \"./types\";\n\n// ---- Wire shapes (what the wasm emits and accepts) ----\n\nexport interface SequencedEnvelopeWire {\n envelope: MessageEnvelope;\n server_seq: number;\n}\n\nexport interface LogPositionWire {\n conversation_id: Uint8Array;\n epoch: number;\n server_seq: number;\n anchored: boolean;\n}\n\nexport interface LogHeadWire {\n conversation_id: Uint8Array;\n head_server_seq: number;\n head_epoch: number;\n}\n\nexport interface LogGapWire {\n conversation_id: Uint8Array;\n applied_server_seq: number;\n first_buffered_server_seq: number;\n}\n\nexport interface ConversationUpdateWire {\n conversation_id: Uint8Array;\n epoch: number;\n}\n\nexport interface ConversationRemovalWire {\n conversation_id: Uint8Array;\n server_seq: number;\n epoch: number;\n readmitted: boolean;\n}\n\nexport interface WelcomeFailureWire {\n conversation_id: Uint8Array;\n server_seq: number;\n /** serde's variant name: `\"Rejected\"` or `\"Storage\"`. */\n reason: string;\n}\n\nexport interface StrandedConversationWire {\n conversation_id: Uint8Array;\n server_seq: number;\n epoch: number;\n /** `\"NoProgress\"`, `\"AddedKeyPackageExpired\"`, `\"AddedKeyPackageNotYetValid\"`,\n * `\"CredentialInvalid\"`, `\"PolicyDowngrade\"`, `\"NotPermitted\"`. */\n reason: string;\n}\n\nexport interface BufferOverflowWire {\n conversation_id: Uint8Array;\n /** `\"HeldFrames\"` or `\"RetainedFrames\"`. */\n reason: string;\n dropped: number;\n}\n\n// The typed-outcome fields are optional on the wire so a result decoded from\n// an older wasm (or a hand-built test fixture) still converts.\nexport interface ApplyBatchResultWire {\n messages: IncomingMessage[];\n applied: number;\n duplicates: number;\n buffered: number;\n failed: number;\n gaps: LogGapWire[];\n joined: Uint8Array[];\n updated: ConversationUpdateWire[];\n removed?: ConversationRemovalWire[];\n welcome_failures?: WelcomeFailureWire[];\n stranded?: StrandedConversationWire[];\n proposals_pending?: Uint8Array[];\n overflow?: BufferOverflowWire[];\n}\n\nexport interface SyncStepResultWire {\n messages: IncomingMessage[];\n has_more: boolean;\n fetched: number;\n position: LogPositionWire;\n updated: ConversationUpdateWire[];\n joined?: Uint8Array[];\n removed?: ConversationRemovalWire[];\n welcome_failures?: WelcomeFailureWire[];\n stranded?: StrandedConversationWire[];\n proposals_pending?: Uint8Array[];\n overflow?: BufferOverflowWire[];\n}\n\nexport interface AddMemberVerdictWire {\n device_id: Uint8Array;\n /** serde's variant name, e.g. `\"AlreadyMember\"`. */\n status: string;\n leaf_index: number | null | undefined;\n}\n\nexport interface AddMembersReportWire {\n verdicts: AddMemberVerdictWire[];\n epoch: number | null | undefined;\n}\n\nexport interface CommitInDoubtWire {\n conversation_id: Uint8Array;\n attempts: number;\n next_attempt_at_ms: number;\n}\n\n// ---- Frame classification ----\n\n/**\n * Whether a frame the transport handed over carries its server position.\n * A bare `MessageEnvelope` has `conversation_id` at its top level; a\n * `SequencedEnvelope` wraps one under `envelope` next to `serverSeq`.\n */\nexport function isSequencedFrame(\n frame: MessageEnvelope | SequencedEnvelope,\n): frame is SequencedEnvelope {\n return (\n typeof frame === \"object\" &&\n frame !== null &&\n \"envelope\" in frame &&\n typeof (frame as SequencedEnvelope).envelope === \"object\" &&\n (frame as SequencedEnvelope).envelope !== null\n );\n}\n\n// ---- Converters ----\n\nexport function sequencedToWire(item: SequencedEnvelope): SequencedEnvelopeWire {\n return { envelope: item.envelope, server_seq: item.serverSeq };\n}\n\nexport function sequencedFromWire(item: SequencedEnvelopeWire): SequencedEnvelope {\n return { envelope: item.envelope, serverSeq: item.server_seq };\n}\n\nexport function logPositionFromWire(p: LogPositionWire): LogPosition {\n return {\n conversationId: p.conversation_id,\n epoch: p.epoch,\n serverSeq: p.server_seq,\n anchored: p.anchored,\n };\n}\n\nexport function logPositionToWire(p: LogPosition): LogPositionWire {\n return {\n conversation_id: p.conversationId,\n epoch: p.epoch,\n server_seq: p.serverSeq,\n anchored: p.anchored,\n };\n}\n\nexport function logHeadToWire(h: LogHead): LogHeadWire {\n return {\n conversation_id: h.conversationId,\n head_server_seq: h.headServerSeq,\n head_epoch: h.headEpoch,\n };\n}\n\nexport function logHeadFromWire(h: LogHeadWire): LogHead {\n return {\n conversationId: h.conversation_id,\n headServerSeq: h.head_server_seq,\n headEpoch: h.head_epoch,\n };\n}\n\nexport function logGapFromWire(g: LogGapWire): LogGap {\n return {\n conversationId: g.conversation_id,\n appliedServerSeq: g.applied_server_seq,\n firstBufferedServerSeq: g.first_buffered_server_seq,\n };\n}\n\nexport function conversationUpdateFromWire(u: ConversationUpdateWire): ConversationUpdate {\n return { conversationId: u.conversation_id, epoch: u.epoch };\n}\n\n/** serde's `PascalCase` variant name as the JS surface's `camelCase` string. */\nfunction variant<T extends string>(name: string): T {\n return (name.charAt(0).toLowerCase() + name.slice(1)) as T;\n}\n\nexport function conversationRemovalFromWire(r: ConversationRemovalWire): ConversationRemoval {\n return {\n conversationId: r.conversation_id,\n serverSeq: r.server_seq,\n epoch: r.epoch,\n readmitted: r.readmitted,\n };\n}\n\nexport function welcomeFailureFromWire(w: WelcomeFailureWire): WelcomeFailure {\n return {\n conversationId: w.conversation_id,\n serverSeq: w.server_seq,\n reason: variant<WelcomeFailureReason>(w.reason),\n };\n}\n\nexport function strandedConversationFromWire(s: StrandedConversationWire): StrandedConversation {\n return {\n conversationId: s.conversation_id,\n serverSeq: s.server_seq,\n epoch: s.epoch,\n reason: variant<StrandReason>(s.reason),\n };\n}\n\nexport function bufferOverflowFromWire(o: BufferOverflowWire): BufferOverflow {\n return {\n conversationId: o.conversation_id,\n reason: variant<OverflowReason>(o.reason),\n dropped: o.dropped,\n };\n}\n\n/** The typed outcomes a batch and a page share. */\nfunction outcomesFromWire(r: {\n removed?: ConversationRemovalWire[];\n welcome_failures?: WelcomeFailureWire[];\n stranded?: StrandedConversationWire[];\n proposals_pending?: ConversationId[];\n overflow?: BufferOverflowWire[];\n}): Pick<ApplyBatchResult, \"removed\" | \"welcomeFailures\" | \"stranded\" | \"proposalsPending\" | \"overflow\"> {\n return {\n removed: (r.removed ?? []).map(conversationRemovalFromWire),\n welcomeFailures: (r.welcome_failures ?? []).map(welcomeFailureFromWire),\n stranded: (r.stranded ?? []).map(strandedConversationFromWire),\n proposalsPending: r.proposals_pending ?? [],\n overflow: (r.overflow ?? []).map(bufferOverflowFromWire),\n };\n}\n\nexport function applyBatchResultFromWire(r: ApplyBatchResultWire): ApplyBatchResult {\n return {\n messages: r.messages,\n applied: r.applied,\n duplicates: r.duplicates,\n buffered: r.buffered,\n failed: r.failed,\n gaps: r.gaps.map(logGapFromWire),\n joined: r.joined,\n updated: r.updated.map(conversationUpdateFromWire),\n ...outcomesFromWire(r),\n };\n}\n\nexport function syncStepResultFromWire(r: SyncStepResultWire): SyncStepResult {\n return {\n messages: r.messages,\n hasMore: r.has_more,\n fetched: r.fetched,\n position: logPositionFromWire(r.position),\n updated: r.updated.map(conversationUpdateFromWire),\n joined: r.joined ?? [],\n ...outcomesFromWire(r),\n };\n}\n\nexport function addMembersReportFromWire(r: AddMembersReportWire): AddMembersReport {\n return {\n verdicts: r.verdicts.map((v) => ({\n deviceId: v.device_id,\n status: variant<AddMemberStatus>(v.status),\n leafIndex: v.leaf_index ?? null,\n })),\n epoch: r.epoch ?? null,\n };\n}\n\nexport function commitInDoubtFromWire(c: CommitInDoubtWire): CommitInDoubt {\n return {\n conversationId: c.conversation_id,\n attempts: c.attempts,\n nextAttemptAtMs: c.next_attempt_at_ms,\n };\n}\n","// Default IndexedDB-backed Storage implementation. Hosts can supply their own.\n\nimport type { Storage } from \"../types\";\n\nconst DB_NAME = \"ping-sdk\";\nconst DB_VERSION = 1;\nconst STORE = \"kv\";\n\ninterface Row { ns: string; key: string; value: Uint8Array }\n\nfunction open(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(DB_NAME, DB_VERSION);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(STORE)) {\n const os = db.createObjectStore(STORE, { keyPath: [\"ns\", \"key\"] });\n os.createIndex(\"ns\", \"ns\", { unique: false });\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n\nexport class IndexedDbStorage implements Storage {\n private dbPromise: Promise<IDBDatabase>;\n\n constructor() { this.dbPromise = open(); }\n\n async get(namespace: string, key: string): Promise<Uint8Array | null> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const r = tx.objectStore(STORE).get([namespace, key]);\n r.onsuccess = () => resolve(((r.result as Row | undefined)?.value) ?? null);\n r.onerror = () => reject(r.error);\n });\n }\n\n async put(namespace: string, key: string, value: Uint8Array): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).put({ ns: namespace, key, value } as Row);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n async del(namespace: string, key: string): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete([namespace, key]);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n /**\n * One `readwrite` transaction for the whole batch. Every request is issued\n * synchronously inside it (an await on anything else would let the\n * transaction auto-commit), so a failure or a crash mid-way aborts all of\n * it: the per-row MLS store relies on that to keep a checkpoint atomic.\n */\n async applyBatch(\n namespace: string,\n puts: Array<[key: string, value: Uint8Array]>,\n deletes: string[],\n ): Promise<void> {\n if (puts.length === 0 && deletes.length === 0) return;\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n let settled = false;\n const fail = (e: unknown) => {\n if (settled) return;\n settled = true;\n reject(e instanceof Error ? e : new Error(String(e)));\n };\n tx.oncomplete = () => {\n if (!settled) {\n settled = true;\n resolve();\n }\n };\n tx.onerror = () => fail(tx.error);\n tx.onabort = () => fail(tx.error ?? new Error(\"applyBatch aborted\"));\n try {\n const os = tx.objectStore(STORE);\n for (const [key, value] of puts) os.put({ ns: namespace, key, value } as Row);\n for (const key of deletes) os.delete([namespace, key]);\n } catch (e) {\n // A request that throws synchronously (an unserialisable key) does\n // not abort the transaction on its own; the requests already issued\n // would commit. Abort explicitly so the batch stays all-or-nothing.\n try {\n tx.abort();\n } catch {\n // Already aborted or finished.\n }\n fail(e);\n }\n });\n }\n\n /** Every `[key, value]` under `namespace` with the prefix, in one read. */\n async listEntries(\n namespace: string,\n prefix: string,\n ): Promise<Array<[key: string, value: Uint8Array]>> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: Array<[string, Uint8Array]> = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.startsWith(prefix)) out.push([row.key, row.value]);\n cur.continue();\n };\n req.onerror = () => reject(req.error);\n });\n }\n\n async listKeys(namespace: string, prefix: string): Promise<string[]> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: string[] = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.startsWith(prefix)) out.push(row.key);\n cur.continue();\n };\n req.onerror = () => reject(req.error);\n });\n }\n}\n","// Ping wire contract — TypeScript counterpart to the `ping-wire-contract` Rust crate.\n//\n// MUST stay in lockstep with `core/ping-wire-contract/src/lib.rs`. The full normative spec\n// lives in `docs/PING_WIRE_CONTRACT.md`.\n//\n// What this module is for: code paths that cross the network boundary (transports, relays,\n// service workers) that need to advertise or validate ping-wire-contract conformance from\n// JavaScript without round-tripping through WASM.\n\nimport type { MessageEnvelope } from \"./types\";\n\n/**\n * Ping wire contract version. Bumped on incompatible profile changes.\n *\n * Currently `2` — CR-6 changes the `content_hash` semantics for `Application` envelopes\n * (now hashed over plaintext, not the MLS ciphertext). Receivers run a 90-day dual-accept\n * window per Q-ARCH-02; see [[validate]] for the per-version routing.\n */\nexport const PING_WIRE_CONTRACT_VERSION = 2;\n\n/** Lowest envelope version accepted by [[validate]] during the dual-accept window. */\nexport const WIRE_VERSION_MIN_ACCEPTED = 1;\n\n/** Canonical CBOR content type. Production transports SHOULD use this. */\nexport const CONTENT_TYPE_CBOR = \"application/vnd.ping.wire.v2+cbor\";\n\n/** JSON projection — development and tooling only. Production MUST NOT use this. */\nexport const CONTENT_TYPE_JSON = \"application/vnd.ping.wire.v2+json\";\n\n/** Legacy v1 CBOR type, accepted during the CR-6 dual-accept window. */\nexport const CONTENT_TYPE_CBOR_LEGACY_V1 = \"application/vnd.ping.wire.v1+cbor\";\n\n/** Legacy v1 JSON type, accepted during the CR-6 dual-accept window. */\nexport const CONTENT_TYPE_JSON_LEGACY_V1 = \"application/vnd.ping.wire.v1+json\";\n\n/** Header used over transports that don't surface a content type (e.g. WebSocket). */\nexport const PING_WIRE_CONTRACT_HEADER = \"X-Ping-Wire-Contract\";\n\n/** Header value: `ping/<VERSION>`. */\nexport const PING_WIRE_CONTRACT_HEADER_VALUE = `ping/${PING_WIRE_CONTRACT_VERSION}`;\n\nexport type ValidationErrorKind =\n | \"UnsupportedVersion\"\n | \"BadConversationIdLen\"\n | \"BadSenderDeviceLen\"\n | \"ContentHashMismatch\";\n\nexport class ValidationError extends Error {\n constructor(public readonly kind: ValidationErrorKind, message: string) {\n super(message);\n this.name = \"PingWireContractValidationError\";\n }\n}\n\nconst KIND_DISCRIMINANT: Record<MessageEnvelope[\"kind\"], number> = {\n Application: 1,\n Commit: 2,\n Welcome: 3,\n Proposal: 4,\n KeyPackage: 5,\n};\n\nasync function sha256(bytes: Uint8Array): Promise<Uint8Array> {\n // `crypto.subtle` is available in browsers, Node 20+, and Workers. `bytes.buffer`\n // is typed as `ArrayBufferLike` which TS won't accept as `BufferSource` (the union\n // includes `SharedArrayBuffer`); pass an explicit ArrayBuffer slice instead.\n const ab = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;\n const hash = await crypto.subtle.digest(\"SHA-256\", ab);\n return new Uint8Array(hash);\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n}\n\n/**\n * Validate an envelope against the ping-wire-contract.\n *\n * Receivers claiming contract conformance MUST call this before applying any envelope.\n * External consumers using the raw envelope under their own profile are not bound by\n * these rules.\n *\n * CR-6 dual-accept window: `v ∈ [WIRE_VERSION_MIN_ACCEPTED, PING_WIRE_CONTRACT_VERSION]`\n * passes the version gate. For v=2 `Application` envelopes the content_hash is over\n * plaintext, so this function skips that check — callers MUST run\n * [[verifyApplicationContentHash]] after MLS decrypt to close the loop.\n */\nexport async function validate(env: MessageEnvelope): Promise<void> {\n if (env.v < WIRE_VERSION_MIN_ACCEPTED || env.v > PING_WIRE_CONTRACT_VERSION) {\n throw new ValidationError(\n \"UnsupportedVersion\",\n `unsupported wire-contract version: envelope says v=${env.v}, expected v∈[${WIRE_VERSION_MIN_ACCEPTED}, ${PING_WIRE_CONTRACT_VERSION}]`,\n );\n }\n if (env.conversation_id.length !== 16) {\n throw new ValidationError(\n \"BadConversationIdLen\",\n `conversation_id must be 16 bytes (ULID), got ${env.conversation_id.length}`,\n );\n }\n if (env.sender_device.length !== 32) {\n throw new ValidationError(\n \"BadSenderDeviceLen\",\n `sender_device must be 32 bytes, got ${env.sender_device.length}`,\n );\n }\n // CR-6 routing: skip the hash check for v=2 application envelopes.\n if (env.v >= 2 && env.kind === \"Application\") {\n return;\n }\n const buf = new Uint8Array(1 + env.payload.length);\n buf[0] = KIND_DISCRIMINANT[env.kind];\n buf.set(env.payload, 1);\n const computed = await sha256(buf);\n if (!bytesEqual(computed, env.content_hash)) {\n throw new ValidationError(\n \"ContentHashMismatch\",\n \"content_hash mismatch: envelope is forged, corrupted, or built by a non-conformant sender\",\n );\n }\n}\n\n/**\n * Verify a v=2 `Application` envelope's content_hash against the decrypted plaintext.\n *\n * Caller MUST run this after MLS decrypt for application envelopes whose `v >= 2`. For\n * v=1 envelopes or handshake kinds this is a no-op (those are covered by [[validate]]).\n */\nexport async function verifyApplicationContentHash(\n env: MessageEnvelope,\n plaintext: Uint8Array,\n): Promise<void> {\n if (env.v < 2 || env.kind !== \"Application\") return;\n const computed = await sha256(plaintext);\n if (!bytesEqual(computed, env.content_hash)) {\n throw new ValidationError(\n \"ContentHashMismatch\",\n \"v=2 application content_hash mismatch against decrypted plaintext\",\n );\n }\n}\n\n/**\n * True if the supplied content type negotiates the ping-wire-contract.\n *\n * Accepts the v2 canonical types AND the v1 legacy types during the CR-6 dual-accept\n * window. Tolerates whitespace and parameters (e.g. `; charset=utf-8`).\n */\nexport function negotiates(contentType: string | null | undefined): boolean {\n if (!contentType) return false;\n const primary = contentType.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n return (\n primary === CONTENT_TYPE_CBOR\n || primary === CONTENT_TYPE_JSON\n || primary === CONTENT_TYPE_CBOR_LEGACY_V1\n || primary === CONTENT_TYPE_JSON_LEGACY_V1\n );\n}\n","// Reference WebSocket transport. Treats the server as an opaque relay that:\n// - accepts a CBOR-encoded MessageEnvelope on `send`\n// - returns events newer than a cursor on `fetchSince`\n// - streams new events on the WS itself for `subscribe`\n// - exposes a directory endpoint for `discoverDevices`\n//\n// This is a sample. Real deployments will tune framing / auth.\n\nimport type { ConversationId, DiscoveredDevice, MessageEnvelope, Transport, UserId } from \"../types\";\nimport {\n CONTENT_TYPE_JSON,\n PING_WIRE_CONTRACT_HEADER,\n PING_WIRE_CONTRACT_HEADER_VALUE,\n} from \"../wire-contract\";\n\nexport interface WsTransportConfig {\n baseUrl: string; // ws[s]://...\n authHeader?: string; // optional bearer token\n fetchImpl?: typeof fetch; // override for SSR / tests\n}\n\nexport class WebSocketTransport implements Transport {\n private ws: WebSocket | null = null;\n private liveHandlers = new Set<(env: MessageEnvelope) => void>();\n private fetchImpl: typeof fetch;\n\n constructor(private cfg: WsTransportConfig) {\n this.fetchImpl = cfg.fetchImpl ?? globalThis.fetch.bind(globalThis);\n this.openSocket();\n }\n\n private openSocket() {\n if (typeof WebSocket === \"undefined\") return;\n const url = `${this.cfg.baseUrl.replace(/^http/, \"ws\")}/stream`;\n this.ws = new WebSocket(url);\n this.ws.onmessage = (ev) => {\n // Server sends one JSON envelope per text frame.\n const text = typeof ev.data === \"string\" ? ev.data : new TextDecoder().decode(ev.data as ArrayBuffer);\n try {\n const env = JSON.parse(text, reviver) as MessageEnvelope;\n for (const h of this.liveHandlers) h(env);\n } catch (e) {\n if (typeof console !== \"undefined\") console.debug(\"[ping-sdk] WS frame parse error:\", e);\n }\n };\n this.ws.onclose = () => setTimeout(() => this.openSocket(), 1000);\n }\n\n async send(envelope: MessageEnvelope): Promise<void> {\n // We're emitting the JSON projection of the ping-wire-contract. Production transports\n // would use CONTENT_TYPE_CBOR with a real CBOR codec; for the demo path the JSON shape\n // is the documented development projection.\n const res = await this.fetchImpl(`${this.cfg.baseUrl}/send`, {\n method: \"POST\",\n headers: {\n \"content-type\": CONTENT_TYPE_JSON,\n [PING_WIRE_CONTRACT_HEADER]: PING_WIRE_CONTRACT_HEADER_VALUE,\n ...(this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {}),\n },\n body: JSON.stringify(envelope, replacer),\n });\n if (res.status === 409) throw new Error(\"EpochOccupied\");\n if (!res.ok) throw new Error(`transport send failed: ${res.status}`);\n }\n\n async fetchSince(conversationId: ConversationId, cursor: Uint8Array, limit: number): Promise<MessageEnvelope[]> {\n const url = new URL(`${this.cfg.baseUrl}/sync`);\n url.searchParams.set(\"conv\", toHex(conversationId));\n url.searchParams.set(\"cursor\", btoaUrl(cursor));\n url.searchParams.set(\"limit\", String(limit));\n const res = await this.fetchImpl(url.toString(), {\n headers: { ...(this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {}) },\n });\n if (!res.ok) throw new Error(`transport fetch failed: ${res.status}`);\n const text = await res.text();\n return JSON.parse(text, reviver) as MessageEnvelope[];\n }\n\n subscribe(onEvent: (env: MessageEnvelope) => void): { unsubscribe(): void } {\n this.liveHandlers.add(onEvent);\n return { unsubscribe: () => this.liveHandlers.delete(onEvent) };\n }\n\n async discoverDevices(userId: UserId): Promise<DiscoveredDevice[]> {\n const res = await this.fetchImpl(`${this.cfg.baseUrl}/devices/${toHex(userId)}`, {\n headers: { ...(this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {}) },\n });\n if (!res.ok) throw new Error(`device discovery failed: ${res.status}`);\n const text = await res.text();\n return JSON.parse(text, reviver) as DiscoveredDevice[];\n }\n}\n\n// ---- Wire codec ----\n//\n// Demo wire format: JSON with byte fields wrapped as `{ _bytes: number[] }`. The relay's\n// `envFromJson`/`envToJson` use the same shape. The spec calls for CBOR; v0.2 swaps in a\n// real CBOR codec, but the JSON form is much friendlier to debug.\n//\n// (decodeEnvelope helpers used to live here; collapsed into inline JSON.parse calls above.)\n\nfunction replacer(_k: string, v: unknown): unknown {\n if (v instanceof Uint8Array) return { _bytes: Array.from(v) };\n return v;\n}\nfunction reviver(_k: string, v: unknown): unknown {\n if (v && typeof v === \"object\" && Array.isArray((v as { _bytes?: number[] })._bytes)) {\n return new Uint8Array((v as { _bytes: number[] })._bytes);\n }\n return v;\n}\n\nfunction toHex(b: Uint8Array): string {\n let s = \"\"; for (const v of b) s += v.toString(16).padStart(2, \"0\"); return s;\n}\nfunction btoaUrl(b: Uint8Array): string {\n let s = \"\"; for (const v of b) s += String.fromCharCode(v);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n","// 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","// [CR-5] Read-only notification preview for the web Service Worker.\n//\n// The web mirror of the iOS Notification Service Extension: a second JS realm\n// (the push-handling Service Worker, woken while the tab may be closed OR open\n// and writing) that must turn one push-delivered envelope into a sender and a\n// body preview, and change NOTHING.\n//\n// This module deliberately does NOT go through the SDK's usual Worker bridge:\n// a Service Worker cannot spawn a dedicated `Worker` on every browser, and a\n// preview needs one decrypt, not a message pipeline. The WASM module is loaded\n// INLINE in the calling realm (no DOM APIs are touched), wrapping the core's\n// `MessagingClient::open_read_only` + `preview_envelope` — the same read-only\n// seam the iOS NSE uses, with the same semantics:\n//\n// * the SDK storage is opened READ-ONLY: the MLS snapshot is copied into\n// memory at open and never written back, so the tab remains the single\n// writer and cannot be disturbed (two writers on the whole-state blob\n// REPLACE each other — see `StorageBackend::AsyncBlobReadOnly`);\n// * the ratchet advance from the preview decrypt is thrown away; the tab\n// decrypts the same message again later, independently. Nothing is\n// consumed that the tab needs, and nothing this session does is\n// observable by the tab;\n// * handshake traffic (Commit/Welcome/Proposal), unknown conversations, and\n// replays the hydrated cursor rejects all resolve to `null` — show the\n// generic banner, it is a normal answer;\n// * a message the tab ALREADY consumed and checkpointed cannot be decrypted\n// from the newer snapshot (its generation is burned): `previewEnvelope`\n// rejects. Treat ANY rejection as \"no preview\" (generic banner), never as\n// fatal.\n//\n// Concurrent-open safety: IndexedDB reads never block the tab's writes and the\n// session takes a point-in-time copy of the `__mls snapshot` blob at open, so\n// opening while a tab is live is safe by construction. The copy can be STALE\n// relative to the tab, which only widens the `null`/reject cases above. Open a\n// fresh session per push event (or per small batch) rather than caching one —\n// a fresh open sees the newest checkpoint.\n//\n// See docs/NOTIFICATION_PREVIEW_WEB.md for the full Service Worker guide\n// (wasm init in module vs classic workers, account-slot storage, ping-prime\n// wiring).\n\nimport { scopeStorage } from \"./storage/scope\";\nimport type { IncomingMessage, MessageEnvelope, Storage } from \"./types\";\nimport { reserveLinearMemory } from \"./wasm-memory\";\n\nexport interface NotificationPreviewOptions {\n /**\n * The account identity export (CBOR-wrapped Ed25519 seed, SECRET) — the\n * same bytes the tab passes to `MessagingClient.init`. The Service Worker\n * host must read it from wherever the tab keeps it (e.g. the encrypted IDB\n * slot); it never crosses the network.\n */\n identityExport: Uint8Array;\n /**\n * The SAME `Storage` implementation (and underlying IndexedDB database)\n * the tab's `MessagingClient` persists to. It is wrapped read-only here:\n * `put`/`del` reject, so a host bug cannot make the Service Worker a\n * second writer.\n */\n storage: Storage;\n /**\n * The tab's `ClientConfig.accountNamespace` for this account slot, when it\n * uses one. MUST match exactly — the preview scopes every namespace with\n * the same `\"${accountNamespace} \"` prefix rule as `MessagingClient`, and a\n * mismatch reads an empty store (open rejects with \"no checkpoint\").\n */\n accountNamespace?: string;\n /**\n * Where to load `ping_wasm_bg.wasm` from, passed through to the\n * wasm-bindgen `init`. Defaults to the URL baked next to the module —\n * correct when the bundler ships the `wasm/` directory alongside. Classic\n * (importScripts) Service Workers, or bundlers that relocate assets, pass\n * an explicit URL here.\n */\n wasmModuleOrPath?: string | URL | WebAssembly.Module;\n /** Override the wall clock (test/sim only). */\n now?: () => number;\n}\n\nexport interface NotificationPreviewSession {\n /**\n * Decrypt ONE push-delivered envelope for display. Resolves to the\n * decrypted message (sender ids, conversation id, plaintext — everything a\n * banner needs) or `null` when there is nothing to show. Rejects when the\n * snapshot cannot decrypt it (commonly: the tab consumed it first) — treat\n * a rejection exactly like `null` and fall back to the generic banner.\n *\n * The returned message never carries a `journal_id`: a preview decrypt is\n * not journaled (nothing durable happened) and needs no `confirmApplied`.\n */\n previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;\n /** Release the WASM instance. The session is unusable afterwards. */\n close(): void;\n}\n\n/**\n * Open the SDK read-only for notification previews, from a Service Worker (or\n * any realm without the SDK's Worker bridge). Rejects when the store holds no\n * checkpoint or no device identity — a Service Worker for an account that\n * never initialised locally has nothing to decrypt with, and \"successfully\n * decrypt nothing\" would be the worst possible answer.\n */\nexport async function openNotificationPreview(\n opts: NotificationPreviewOptions,\n): Promise<NotificationPreviewSession> {\n const now = opts.now ?? (() => Date.now());\n const scoped =\n opts.accountNamespace !== undefined && opts.accountNamespace.length > 0\n ? scopeStorage(opts.storage, opts.accountNamespace)\n : opts.storage;\n const storage = readOnlyStorage(scoped);\n\n // Inline WASM load — the module ships no DOM dependency, so this works in\n // window, worker, and service-worker realms alike. `init` is idempotent per\n // realm (subsequent opens reuse the instantiated module).\n const wasm = await import(\"../wasm/ping_wasm\");\n const out = await wasm.default(\n opts.wasmModuleOrPath === undefined\n ? undefined\n : ({ module_or_path: opts.wasmModuleOrPath } as never),\n );\n // Same Safari mitigation as the worker (`wasm-memory.ts`): grow from JS\n // once so the module never executes `memory.grow` itself. Idempotent.\n reserveLinearMemory(out.memory);\n\n const client = await wasm.PingClient.openReadOnly(\n opts.identityExport,\n // Label is unused on the read-only path (no LocalDevice is ever minted).\n \"notification-preview\",\n storage as never,\n silentTransport() as never,\n now(),\n );\n\n let closed = false;\n return {\n async previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n const result = client.previewEnvelope(envelope as never, now());\n return (result ?? null) as IncomingMessage | null;\n },\n close() {\n if (closed) return;\n closed = true;\n client.free();\n },\n };\n}\n\n/**\n * The per-account scope rule, shared with `MessagingClient` so the preview and\n * the tab's writer always read the same slot. Re-exported for tests.\n */\nexport { scopeStorage };\n\n/**\n * Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS\n * snapshot through a read-only backend; this guards the host-KV half\n * (`device`, `groups`, `cursors`, …), which the read-only MLS backend cannot\n * see. Defense in depth against a host bug making the Service Worker a second\n * writer. Exported for tests.\n */\nexport function readOnlyStorage(storage: Storage): Storage {\n const refuse = (op: string): Promise<never> =>\n Promise.reject(\n new Error(`notification-preview storage is read-only (attempted ${op})`),\n );\n const readOnly: Storage = {\n get: (ns, key) => storage.get(ns, key),\n put: (_ns, _key, _value) => refuse(\"put\"),\n del: (_ns, _key) => refuse(\"del\"),\n listKeys: (ns, prefix) => storage.listKeys(ns, prefix),\n };\n // `listEntries` is a read, so the read-only open keeps its one-call path.\n // `applyBatch` is a write and is deliberately absent: the wasm only uses\n // the methods it finds, and the read-only backend never batches.\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);\n }\n return readOnly;\n}\n\n/**\n * A transport that can never be used: the preview client never sends, never\n * fetches, never discovers. `send` rejects loudly so a wiring mistake is\n * caught instead of silently networking from a push handler.\n */\nfunction silentTransport(): {\n send(envelope: unknown): Promise<never>;\n fetchSince(conv: unknown, cursor: unknown, limit: number): Promise<unknown[]>;\n discoverDevices(userId: unknown): Promise<unknown[]>;\n setNextWelcomeRecipients(conv: unknown, recipients: unknown): Promise<void>;\n} {\n return {\n send: () => Promise.reject(new Error(\"notification-preview cannot send\")),\n fetchSince: () => Promise.resolve([]),\n discoverDevices: () => Promise.resolve([]),\n setNextWelcomeRecipients: () => Promise.resolve(),\n };\n}\n","// Public entry point. Spawns the dedicated Worker that hosts the WASM instance and exposes a\n// Promise-based, identical-to-native API. Crypto runs off the main thread.\n\nimport type {\n AddMembersReport, AdmitChatEntry, AdmitChatOutcome, ApplyBatchResult,\n CatchupAppEvent, CatchupSnapshotView, CommitInDoubt,\n ConversationId, ConversationMeta, ConversationPolicy, DeviceId, DeviceLinkApproval, DeviceLinkPossession,\n ExpectedOwner,\n DeviceReauthProof, DeviceRemovalReport, IncomingMessage,\n HistoryBundle, IdentityRotation, LogHead, LogPosition, MemberInfo, MessageBatchMeta, PendingApply,\n KeyPackageEntry, LinkingTicket, MessageEnvelope, RecoveryBackup, SequencedEnvelope, Storage,\n SyncStepResult, Transport, UserId,\n} from \"./types\";\nimport type { Request, Response, TransportFeatures } from \"./protocol\";\nimport { errorKind, MessageFanout } from \"./fanout\";\nimport { GapFiller } from \"./gap-fill\";\nimport { InboundCoalescer } from \"./inbound-coalescer\";\nimport { scopeStorage, storageFeaturesOf } from \"./storage/scope\";\nimport {\n type AddMembersReportWire,\n addMembersReportFromWire,\n type ApplyBatchResultWire,\n applyBatchResultFromWire,\n type CommitInDoubtWire,\n commitInDoubtFromWire,\n isSequencedFrame,\n type LogPositionWire,\n logHeadToWire,\n logPositionFromWire,\n sequencedToWire,\n type SyncStepResultWire,\n syncStepResultFromWire,\n} from \"./sequenced\";\n\nexport type * from \"./types\";\n\n// Re-export the default Storage and Transport implementations from the main entry so consumers\n// whose bundlers don't honor package.json#exports (Metro with strict resolution, some legacy\n// Webpack configs) can still get them with a plain `import { ... } from \"@ping-app/ping-openmls-sdk\"`. Power\n// users who care about tree-shaking can keep using the subpath imports.\nexport { IndexedDbStorage } from \"./storage/indexeddb\";\nexport { WebSocketTransport } from \"./transport/websocket\";\n// [CR-5] Service-worker notification preview. Prefer the subpath import\n// (`@ping-app/ping-openmls-sdk/notification-preview`) inside the Service Worker bundle; this\n// re-export exists for bundlers that don't honor package.json#exports. The\n// heavy work (WASM load) happens only when `openNotificationPreview` is called.\nexport {\n openNotificationPreview,\n type NotificationPreviewOptions,\n type NotificationPreviewSession,\n} from \"./notification-preview\";\n\n// Ping wire contract — version, content-type constants, and runtime validators. Internal\n// products MUST claim conformance; external consumers MAY adopt or run their own profile.\n// See docs/PING_WIRE_CONTRACT.md.\nexport {\n PING_WIRE_CONTRACT_VERSION,\n PING_WIRE_CONTRACT_HEADER,\n PING_WIRE_CONTRACT_HEADER_VALUE,\n WIRE_VERSION_MIN_ACCEPTED,\n CONTENT_TYPE_CBOR,\n CONTENT_TYPE_JSON,\n CONTENT_TYPE_CBOR_LEGACY_V1,\n CONTENT_TYPE_JSON_LEGACY_V1,\n ValidationError,\n validate,\n verifyApplicationContentHash,\n negotiates,\n} from \"./wire-contract\";\n\nexport interface ClientConfig {\n identityExport: Uint8Array;\n deviceLabel: string;\n storage: Storage;\n transport: Transport;\n /** Override the wall clock (test/sim only). */\n now?: () => number;\n /**\n * Optional 32-byte Ed25519 secret key. When supplied AND no\n * `LocalDevice` is yet persisted in `storage`, the SDK adopts this\n * as its device signing key — so `deviceId()` returns\n * `SHA-256(public_key_of(secret))`, deterministic from what the\n * caller passed.\n *\n * Use case: align the SDK's `device_id` (which the SDK stamps into\n * every envelope's `sender_device` field) with an externally-\n * computed device id — typically `SHA-256(device_signing_pubkey)`\n * in the host's auth layer, where the JWT carries that same value\n * as its `device_id` claim. Without this alignment, a server that\n * validates `envelope.sender_device == jwt.device_id` rejects every\n * upload with `sender_device_mismatch`.\n *\n * Ignored on subsequent inits (when `storage` already holds a\n * persisted `LocalDevice`) — the on-disk identity is authoritative\n * for stability across restarts.\n */\n deviceSigningSecretKey?: Uint8Array;\n /**\n * Optional per-account storage scope. When set, the SDK prefixes EVERY\n * storage namespace it reads/writes with `${accountNamespace}\\0`, so\n * multiple accounts that share one `Storage` backend can never read or\n * overwrite each other's MLS group state, device identity, or key\n * material. Hosts that already give each account its own physical store\n * (e.g. a per-account IndexedDB database) can still set this as\n * defense-in-depth — the prefix is stable across restarts and MUST be\n * the same value every init for a given account or its data becomes\n * unreachable. Use a stable, opaque per-account id (e.g. the account id\n * hex); never a display name.\n */\n accountNamespace?: string;\n /**\n * The owner each conversation's FIRST roles write must name (2026-11-04,\n * round 2): the server's recorded creator, as an MLS user id (map the\n * account id through the roster). Consulted only when a group without\n * roles gains them; a first roles write naming another owner strands as\n * `\"notPermitted\"`. A conversation with no entry accepts the first write\n * from any member. Refresh later with `setExpectedOwners`.\n */\n expectedOwners?: ExpectedOwner[];\n}\n\nexport interface Conversation {\n readonly id: ConversationId;\n send(plaintext: Uint8Array): Promise<MessageEnvelope>;\n /** [CR-2] Add members by (device_id, KeyPackage) pair. Hosts typically pull these\n * straight from `transport.discoverDevices(userId)`. All or nothing: one\n * unusable entry fails the whole add (see `addMembersWithVerdicts`). */\n addMembers(entries: KeyPackageEntry[]): Promise<void>;\n /** Add members with one verdict per entry: every entry is screened on its\n * own (KeyPackage verification, lifetime included; capabilities; an\n * existing leaf; a repeat), the usable ones go into ONE Commit sent with\n * its Welcome as one batch, and the rest are reported instead of failing\n * the Commit for every other invitee. A device that already has a leaf is\n * reported (`alreadyMember`, with its leaf), never evicted. */\n addMembersWithVerdicts(entries: KeyPackageEntry[]): Promise<AddMembersReport>;\n /** Re-admit a device that kept its signature key: ONE Commit that removes\n * the leaf holding the KeyPackage's own key (the device's stale leaf: a\n * stranded device, a restore over the same store) and adds its fresh\n * KeyPackage. A re-admission never brings in an account and never makes an\n * account's leaf count grow: with no leaf of that key it rejects\n * \"not permitted: ...\" (`isNotPermittedError`) in EVERY conversation,\n * before anything is sent. A device that came back with a NEW key is added\n * (`addMembers`) by a device of its own account, the owner or an admin.\n * In a conversation with roles the committer is a device of the same\n * account as the device it re-admits, the owner, or an admin (never an\n * admin for a device of the owner); anybody else is rejected the same way\n * (2026-11-18: the `replace` argument is gone, and a plain member no\n * longer re-admits another account's device). Ask the client's\n * `mayReadmit` BEFORE claiming the device's KeyPackage.\n * Resolves to the device id of the leaf the Commit replaced (the device\n * that kept its key). `null`: no leaf was replaced. */\n reAdmitDevice(entry: KeyPackageEntry): Promise<DeviceId | null>;\n removeMembers(leafIndexes: number[]): Promise<void>;\n /** Remove every OTHER leaf of this account from this conversation (step 2\n * of an account's leave, before leaving): one Commit removing every leaf\n * whose credential verifies for this client's own identity, except this\n * device's. Resolves to how many leaves it removed; 0 sends nothing. The\n * leaves are read from the tree on every call. Any role may call it. */\n removeOwnOtherLeaves(): Promise<number>;\n /** Remove an account from this conversation by identity: one Commit\n * removing every leaf whose credential verifies for one of `identities`\n * (MLS user ids, 32 bytes each: the account's current identity and any\n * older ones the host names). Resolves to how many leaves ITS OWN\n * Removes took (a leaf whose leave was already pending goes with the same\n * Commit and is not counted): read the roster for the outcome, never the\n * count. Read from the tree on every call, so a retry removes\n * what the tree holds then. In a group with roles it is the owner's or an\n * admin's call (rejects \"not permitted: ...\" otherwise) and it never\n * removes the owner's leaves. */\n removeMembersByIdentity(identities: UserId[]): Promise<number>;\n /** Record the group's roles in its policy (2026-11-04, round 2): `owner` and\n * `admins` as MLS user ids. One GroupContextExtensions Commit, no Welcome.\n * Rejects with \"not permitted ...\" before anything is sent when this\n * device's role does not allow the change (the first roles write is any\n * member's unless an expected owner says otherwise; then the owner hands\n * over, the owner or an admin changes the admins), when a member's app is\n * too old for roles (`conversationPolicy().incapableMembers`), or in the\n * DeviceGroup. Admins keep promotion order; the owner is never listed. */\n setConversationRoles(owner: UserId, admins: UserId[]): Promise<void>;\n /** Change the conversation `name` (carried in the GroupContext) via an MLS\n * GroupContextExtensions commit — the rename / embedded avatar-media-id change\n * propagates to every member and future joiner through group STATE, not a side\n * broadcast. Pass `null` to clear. All members must have re-linked since the\n * group-name capability shipped, else the SDK throws. */\n setConversationName(name: string | null): Promise<void>;\n /**\n * The conversation's MLS GroupContext name, or `undefined` when the meta cache\n * has not been primed (call `listConversations()` first).\n *\n * This accessor was MISSING, and hosts reasonably assumed it existed:\n * `getConversation(id).name` read `undefined` on every call, so any host logic\n * driven by group state — titles, rosters, avatars and roles carried in the\n * GroupContext — saw nothing. A group then materialised unnamed until a\n * best-effort broadcast happened to arrive, and never converged from group\n * state at all. Prefer `meta()` when you need the full record; this is the\n * one-field convenience that hosts were already reaching for.\n */\n readonly name?: string | undefined;\n /** The conversation's current MLS epoch, or `undefined` when the meta cache\n * has not been primed. */\n readonly epoch?: number | undefined;\n meta(): ConversationMeta;\n}\n\nexport class MessagingClient {\n private worker: Worker;\n private nextId = 1;\n private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();\n private storage: Storage;\n private transport: Transport;\n private now: () => number;\n /** `onMessage` / `onMessageBatch` handlers and the guarded delivery to them. */\n private readonly fanout = new MessageFanout();\n private conversationHandlers = new Set<(id: ConversationId, epoch: number, sender?: DeviceId) => void>();\n private subscription: { unsubscribe(): void } | null = null;\n private metaCache = new Map<string, ConversationMeta>();\n /**\n * Per-conversation batching of sequenced live frames: the first frame goes\n * to the worker at once, frames that arrive while that batch is in flight\n * go out as ONE `processSequencedBatch` when it returns. See\n * {@link dispatchIncoming}.\n */\n private readonly coalescer = new InboundCoalescer<SequencedEnvelope>(\n (_key, items) => this.applyLiveBatch(items),\n );\n /** Single-flight gap fills, one `syncConversationStep` loop per conversation. */\n private readonly gapFiller = new GapFiller();\n /** Set by {@link close}: every later call rejects instead of hanging. */\n private closed = false;\n // Cached at init() so dispatchIncoming can skip envelopes we sent ourselves — the relay\n // broadcasts to all WS subscribers including the sender, and re-applying our own already-\n // merged commits would error with \"epoch differs\".\n private ownDeviceId: Uint8Array | null = null;\n /**\n * Per-conversation dispatch chains. See {@link dispatchIncoming}.\n *\n * Keyed by lowercase-hex conversation id. Bounded: a chain is deleted the\n * moment it settles and is still the tail, so an account with thousands of\n * conversations holds at most one entry per conversation with work IN FLIGHT,\n * not one per conversation it has ever seen.\n */\n private dispatchChains = new Map<string, Promise<void>>();\n\n private constructor(cfg: ClientConfig, worker: Worker) {\n this.worker = worker;\n // Per-account storage scoping (defense-in-depth against cross-account\n // data mixing). When `accountNamespace` is set, every namespace the SDK\n // touches is prefixed so two accounts sharing a backend stay isolated.\n // Only the namespace is scoped: the SDK partitions all of its state\n // (device identity, MLS groups, key material) by namespace, and the\n // space separator never occurs in its own namespace strings, so scoped\n // and unscoped data coexist unambiguously.\n this.storage =\n cfg.accountNamespace !== undefined && cfg.accountNamespace.length > 0\n ? scopeStorage(cfg.storage, cfg.accountNamespace)\n : cfg.storage;\n this.transport = cfg.transport;\n this.now = cfg.now ?? (() => Date.now());\n this.worker.onmessage = (ev) => this.handleWorker(ev.data as Response);\n // An uncaught error inside the worker leaves every awaiting caller with\n // a promise nobody will ever settle; reject them with a typed error\n // instead. The client is not marked closed: the worker may still serve.\n this.worker.onerror = () => this.failPending(new MessagingClientClosedError(\"worker-error\"));\n }\n\n /** Generate a fresh identity. The returned bytes are a secret — store them encrypted. */\n static async generateIdentity(): Promise<Uint8Array> {\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"generateIdentity\", id: 1,\n });\n }\n\n /**\n * HPKE-seal a `LinkingTicket` for delivery to a new device ([CR-3]).\n *\n * Returns CBOR-encoded bytes safe to relay through an untrusted inbox. The new device's\n * X25519 public key (`newDevicePub`) is exchanged out-of-band — typically as part of a\n * QR-encoded handshake on the linking screen. Pure function; runs in an ephemeral\n * worker so no live `MessagingClient` is required on the sender side.\n *\n * Suite: `DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-128-GCM` (matches MLS).\n */\n static async sealLinkingTicket(\n ticket: LinkingTicket,\n newDevicePub: Uint8Array,\n ): Promise<Uint8Array> {\n if (newDevicePub.length !== 32) {\n throw new Error(\"sealLinkingTicket: newDevicePub must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"sealLinkingTicket\", id: 1, ticket, newDevicePub,\n });\n }\n\n /**\n * HPKE-open a sealed `LinkingTicket` on the new device ([CR-3]).\n *\n * The receiving device hasn't booted a `MessagingClient` yet — it only has its X25519\n * ephemeral keypair. This static method runs the open in an ephemeral worker, returning\n * the cleartext ticket which the host then feeds to `init()` + `consumeLinkingTicket()`.\n *\n * On failure the error message is deliberately generic (no discriminator between \"wrong\n * key\" vs \"tampered ciphertext\") so a probing attacker can't tell the new device's key\n * was the issue.\n */\n static async openLinkingTicket(\n sealed: Uint8Array,\n newDevicePriv: Uint8Array,\n ): Promise<LinkingTicket> {\n if (newDevicePriv.length !== 32) {\n throw new Error(\"openLinkingTicket: newDevicePriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<LinkingTicket>({\n kind: \"openLinkingTicket\", id: 1, sealed, newDevicePriv,\n });\n }\n\n /**\n * Generic HPKE-Base seal of arbitrary bytes to `recipientPub` (32-byte X25519)\n * under a caller-supplied `info`. One shared HPKE implementation so app layers\n * (e.g. the device-linking auth envelope) stop hand-rolling per-platform HPKE\n * that drifts and breaks cross-platform. Runs in an ephemeral worker.\n */\n static async hpkeSeal(\n plaintext: Uint8Array,\n recipientPub: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPub.length !== 32) {\n throw new Error(\"hpkeSeal: recipientPub must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeSeal\", id: 1, plaintext, recipientPub, info,\n });\n }\n\n /** Generic HPKE-Base open — inverse of {@link hpkeSeal}. `info` must match the sender. */\n static async hpkeOpen(\n sealed: Uint8Array,\n recipientPriv: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPriv.length !== 32) {\n throw new Error(\"hpkeOpen: recipientPriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeOpen\", id: 1, sealed, recipientPriv, info,\n });\n }\n\n /**\n * HPKE-Base seal in the RFC 9180 CANONICAL layout, `enc || ct||tag`, with no\n * CBOR wrapper.\n *\n * Use this, not {@link hpkeSeal}, for anything the app layers already speak.\n * `hpkeSeal` wraps its output in CBOR `{v, enc, ct}` for the linking ticket,\n * and because that could not read the RFC layout, iOS, Android, web and the\n * third-party `ping-notify` sender each ended up hand-composing their own\n * HPKE for the same suite. This is the one they agree on.\n */\n static async hpkeSealRaw(\n plaintext: Uint8Array,\n recipientPub: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPub.length !== 32) {\n throw new Error(\"hpkeSealRaw: recipientPub must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeSealRaw\", id: 1, plaintext, recipientPub, info,\n });\n }\n\n /**\n * Inverse of {@link hpkeSealRaw}. `info` must match the sender's.\n *\n * Rejects with one uniform error whatever went wrong. This opens bytes from\n * an unauthenticated inbox, so a caller that could tell \"wrong key\" from\n * \"tampered\" from \"truncated\" would be an oracle for whoever wrote them.\n */\n static async hpkeOpenRaw(\n sealed: Uint8Array,\n recipientPriv: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPriv.length !== 32) {\n throw new Error(\"hpkeOpenRaw: recipientPriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeOpenRaw\", id: 1, sealed, recipientPriv, info,\n });\n }\n\n /**\n * A fresh X25519 keypair for the suite.\n *\n * Exposed so a caller minting a recipient key (a Ping Notify inbox, a linking\n * handshake) does not reach for WebCrypto to do it, which is the same problem\n * one layer down.\n */\n static async hpkeGenerateKeypair(): Promise<{\n publicKey: Uint8Array;\n privateKey: Uint8Array;\n }> {\n const both = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeGenerateKeypair\", id: 1,\n });\n if (both.length !== 64) {\n throw new Error(\"hpkeGenerateKeypair: expected 64 bytes\");\n }\n return { publicKey: both.slice(0, 32), privateKey: both.slice(32) };\n }\n\n // ---- Post-quantum HPKE (X-Wing), docs/POST_QUANTUM.md phase 2 ----\n //\n // The `Pq` twins of the functions above: HPKE with KEM X-Wing draft-06\n // (ML-KEM-768 + X25519), HKDF-SHA256, AES-128-GCM. A public key is\n // {@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes, `enc` {@link HPKE_PQ_ENC_BYTES}, the\n // private key a 32-byte seed. These are what the pairing, link-auth,\n // history-transfer and app-inbox flows use from phase 2 on; the classical\n // forms stay for app inboxes created with a 32-byte key before the roll. A\n // classical private key and an X-Wing seed are both 32 bytes but are NOT\n // interchangeable: the host knows which family a stored key belongs to.\n\n /**\n * HPKE-seal a `LinkingTicket` under the new device's X-Wing public key\n * ([CR-3], post-quantum). CBOR `{v: 2, enc, ct}` under `ping/link/v2`; the\n * classical {@link openLinkingTicket} refuses it and {@link openLinkingTicketPq}\n * refuses a `v: 1` blob, so there is no downgrade in either direction.\n */\n static async sealLinkingTicketPq(\n ticket: LinkingTicket,\n newDevicePub: Uint8Array,\n ): Promise<Uint8Array> {\n if (newDevicePub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {\n throw new Error(`sealLinkingTicketPq: newDevicePub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"sealLinkingTicketPq\", id: 1, ticket, newDevicePub,\n });\n }\n\n /**\n * HPKE-open a sealed `v: 2` ticket with the new device's 32-byte X-Wing seed\n * ([CR-3], post-quantum). The error is deliberately generic, like\n * {@link openLinkingTicket}.\n */\n static async openLinkingTicketPq(\n sealed: Uint8Array,\n newDevicePriv: Uint8Array,\n ): Promise<LinkingTicket> {\n if (newDevicePriv.length !== 32) {\n throw new Error(\"openLinkingTicketPq: newDevicePriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<LinkingTicket>({\n kind: \"openLinkingTicketPq\", id: 1, sealed, newDevicePriv,\n });\n }\n\n /** Post-quantum {@link hpkeSeal}: CBOR-wrapped (`v: 2`), `recipientPub` is 1216 bytes. */\n static async hpkeSealPq(\n plaintext: Uint8Array,\n recipientPub: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {\n throw new Error(`hpkeSealPq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeSealPq\", id: 1, plaintext, recipientPub, info,\n });\n }\n\n /** Inverse of {@link hpkeSealPq}. `recipientPriv` is the 32-byte seed; `info` must match. */\n static async hpkeOpenPq(\n sealed: Uint8Array,\n recipientPriv: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPriv.length !== 32) {\n throw new Error(\"hpkeOpenPq: recipientPriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeOpenPq\", id: 1, sealed, recipientPriv, info,\n });\n }\n\n /**\n * Post-quantum {@link hpkeSealRaw}: RFC 9180 canonical `enc(1120) || ct || tag`.\n * The `v2` form of every app-layer envelope (`ping/link-auth/v2`,\n * `ping/app-inbox/v2`).\n */\n static async hpkeSealRawPq(\n plaintext: Uint8Array,\n recipientPub: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {\n throw new Error(`hpkeSealRawPq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeSealRawPq\", id: 1, plaintext, recipientPub, info,\n });\n }\n\n /** Inverse of {@link hpkeSealRawPq}. One uniform error, as for {@link hpkeOpenRaw}. */\n static async hpkeOpenRawPq(\n sealed: Uint8Array,\n recipientPriv: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPriv.length !== 32) {\n throw new Error(\"hpkeOpenRawPq: recipientPriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeOpenRawPq\", id: 1, sealed, recipientPriv, info,\n });\n }\n\n /**\n * A fresh X-Wing keypair: `publicKey` is {@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes,\n * `privateKey` the 32-byte seed. Persist only the seed and recompute the public\n * half with {@link hpkePublicKeyFromSeed}; wipe both buffers when done.\n */\n static async hpkeGenerateKeypairPq(): Promise<{\n publicKey: Uint8Array;\n privateKey: Uint8Array;\n }> {\n const both = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeGenerateKeypairPq\", id: 1,\n });\n if (both.length !== HPKE_PQ_PUBLIC_KEY_BYTES + 32) {\n throw new Error(`hpkeGenerateKeypairPq: expected ${HPKE_PQ_PUBLIC_KEY_BYTES + 32} bytes`);\n }\n return {\n publicKey: both.slice(0, HPKE_PQ_PUBLIC_KEY_BYTES),\n privateKey: both.slice(HPKE_PQ_PUBLIC_KEY_BYTES),\n };\n }\n\n /**\n * The X-Wing public key for a stored 32-byte seed. Deterministic: the pairing\n * code carries SHA-256 of exactly these bytes, so what a device advertises\n * always matches what it will open with.\n */\n static async hpkePublicKeyFromSeed(seed: Uint8Array): Promise<Uint8Array> {\n if (seed.length !== 32) {\n throw new Error(\"hpkePublicKeyFromSeed: seed must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkePublicKeyFromSeed\", id: 1, seed,\n });\n }\n\n /**\n * The id of an account's DeviceGroup (the private sync group of the\n * account's own devices), derived by the SDK core from the account's MLS\n * user id: `userId` is `client.userId()` (32 bytes), NOT the server's\n * account id. Deterministic: every device of the account derives the same\n * id, so a host recognises the DeviceGroup without copying the derivation.\n * Stateless (no client needed); bytes that are not an MLS user id derive an\n * id no device uses.\n */\n static async deviceGroupIdFor(userId: UserId): Promise<ConversationId> {\n return MessagingClient.ephemeralWorkerCall<ConversationId>({\n kind: \"deviceGroupIdFor\", id: 1, userId,\n });\n }\n\n /** The 32-byte X25519 public key for a stored classical private key. */\n static async hpkePublicKeyFromPrivate(privateKey: Uint8Array): Promise<Uint8Array> {\n if (privateKey.length !== 32) {\n throw new Error(\"hpkePublicKeyFromPrivate: privateKey must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkePublicKeyFromPrivate\", id: 1, privateKey,\n });\n }\n\n /**\n * Answer a device re-authentication challenge (`POST /v1/auth/device/challenge`) with\n * the device signing key, so a device whose session tokens are gone or dead gets fresh\n * ones for the SAME device without a code (`POST /v1/auth/device/verify`).\n *\n * The SDK builds the signed bytes itself (`\"ping/device-reauth/v1\" || challengeId ||\n * nonce || deviceId || accountId || audience`), so this cannot sign anything else with\n * the device key. `deviceSigningSecretKey` is the 32-byte secret the host passes as\n * `deviceSigningSecretKey` to {@link init}; `challengeId` (16 bytes) and `nonce`\n * (32 bytes) come from the challenge response. `accountId` (16 bytes) is the account\n * the host stored with its session; the server refuses a proof for any other account,\n * so send the same id with the proof. `audience` is the canonical origin of the API\n * THIS host is configured to reach (`new URL(apiBase).origin`, for example\n * `https://api-prod.ping.live`), never the value the server returned: that is what\n * makes a challenge relayed from another deployment useless there. The returned\n * `deviceId` is SHA-256 of the key's public half; send it with the signature.\n *\n * Rejects wrong widths and a non-canonical audience. Runs in an ephemeral worker.\n */\n static async signDeviceReauth(params: {\n deviceSigningSecretKey: Uint8Array;\n challengeId: Uint8Array;\n nonce: Uint8Array;\n accountId: Uint8Array;\n audience: string;\n }): Promise<DeviceReauthProof> {\n const { deviceSigningSecretKey, challengeId, nonce, accountId, audience } = params;\n if (deviceSigningSecretKey.length !== 32) {\n throw new Error(\"signDeviceReauth: deviceSigningSecretKey must be 32 bytes\");\n }\n if (challengeId.length !== 16) {\n throw new Error(\"signDeviceReauth: challengeId must be 16 bytes\");\n }\n if (nonce.length !== 32) {\n throw new Error(\"signDeviceReauth: nonce must be 32 bytes\");\n }\n if (accountId.length !== 16) {\n throw new Error(\"signDeviceReauth: accountId must be 16 bytes\");\n }\n const both = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"signDeviceReauth\", id: 1, deviceSigningSecretKey, challengeId, nonce, accountId, audience,\n });\n if (both.length !== 96) {\n throw new Error(\"signDeviceReauth: expected 96 bytes\");\n }\n return { deviceId: both.slice(0, 32), signature: both.slice(32) };\n }\n\n /**\n * Link verification v2, on the APPROVING device: approve ONE new device on ONE\n * server link session (`POST /v1/auth/link/sessions` returned `approvalSessionId`)\n * with this device's signing key. The new device sends the result with its own\n * {@link signDeviceLinkPossession} proof to `POST /v1/auth/link/verify`.\n *\n * The SDK builds the signed bytes itself (`\"ping/device-link-approve/v1\" ||\n * approvalSessionId || accountId || approverDeviceId || newDeviceId ||\n * newDevicePubkey || audience`, see docs/DEVICE_LINK_V2_VECTORS.md) and derives\n * both device ids from the keys, so this cannot sign anything else with the device\n * key. `deviceSigningSecretKey` is the 32-byte seed the host holds for THIS device\n * (the one registered as its device signing key); `accountId` (16 bytes) is the\n * account stored with this device's session; `newDevicePubkey` (32 bytes) is the\n * new device's key from its handshake; `audience` is the canonical origin of the API\n * THIS host is configured to reach (`new URL(apiBase).origin`), as for\n * {@link signDeviceReauth}.\n *\n * Rejects wrong widths, a non-canonical audience, a new key that is not a canonical\n * Ed25519 point outside the small-order subgroup, and this device's own key. Runs in\n * an ephemeral worker.\n */\n static async signDeviceLinkApproval(params: {\n deviceSigningSecretKey: Uint8Array;\n approvalSessionId: Uint8Array;\n accountId: Uint8Array;\n newDevicePubkey: Uint8Array;\n audience: string;\n }): Promise<DeviceLinkApproval> {\n const { deviceSigningSecretKey, approvalSessionId, accountId, newDevicePubkey, audience } =\n params;\n if (deviceSigningSecretKey.length !== 32) {\n throw new Error(\"signDeviceLinkApproval: deviceSigningSecretKey must be 32 bytes\");\n }\n if (approvalSessionId.length !== 16) {\n throw new Error(\"signDeviceLinkApproval: approvalSessionId must be 16 bytes\");\n }\n if (accountId.length !== 16) {\n throw new Error(\"signDeviceLinkApproval: accountId must be 16 bytes\");\n }\n if (newDevicePubkey.length !== 32) {\n throw new Error(\"signDeviceLinkApproval: newDevicePubkey must be 32 bytes\");\n }\n const all = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"signDeviceLinkApproval\", id: 1,\n deviceSigningSecretKey, approvalSessionId, accountId, newDevicePubkey, audience,\n });\n if (all.length !== 128) {\n throw new Error(\"signDeviceLinkApproval: expected 128 bytes\");\n }\n return {\n approverDeviceId: all.slice(0, 32),\n newDeviceId: all.slice(32, 64),\n signature: all.slice(64),\n };\n }\n\n /**\n * Link verification v2, on the NEW device: prove that this device holds the key the\n * link session names (`\"ping/device-link-possess/v1\" || approvalSessionId ||\n * accountId || deviceId || audience`). `deviceSigningSecretKey` is this device's own\n * 32-byte seed (the key its handshake advertised); `approvalSessionId` and\n * `accountId` come from the approving device's sealed envelope; `audience` as for\n * {@link signDeviceReauth}. Check `approval.newDeviceId` equals the returned\n * `deviceId` before verifying: a substituted handshake is refused locally.\n *\n * Rejects wrong widths and a non-canonical audience. Runs in an ephemeral worker.\n */\n static async signDeviceLinkPossession(params: {\n deviceSigningSecretKey: Uint8Array;\n approvalSessionId: Uint8Array;\n accountId: Uint8Array;\n audience: string;\n }): Promise<DeviceLinkPossession> {\n const { deviceSigningSecretKey, approvalSessionId, accountId, audience } = params;\n if (deviceSigningSecretKey.length !== 32) {\n throw new Error(\"signDeviceLinkPossession: deviceSigningSecretKey must be 32 bytes\");\n }\n if (approvalSessionId.length !== 16) {\n throw new Error(\"signDeviceLinkPossession: approvalSessionId must be 16 bytes\");\n }\n if (accountId.length !== 16) {\n throw new Error(\"signDeviceLinkPossession: accountId must be 16 bytes\");\n }\n const both = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"signDeviceLinkPossession\", id: 1,\n deviceSigningSecretKey, approvalSessionId, accountId, audience,\n });\n if (both.length !== 96) {\n throw new Error(\"signDeviceLinkPossession: expected 96 bytes\");\n }\n return { deviceId: both.slice(0, 32), signature: both.slice(32) };\n }\n\n // Spawn-call-terminate helper for stateless WASM functions exposed at module scope (no\n // PingClient required). Each call gets a fresh worker; the cost is acceptable because\n // these are one-shot, off-the-hot-path operations (identity gen, linking ticket seal/open).\n //\n // The returned promise ALWAYS settles and the worker is ALWAYS terminated: on its\n // result, on a worker `error` (the script failed to load or import, or threw at top\n // level), on a `messageerror` (a reply that could not be deserialised), and when the\n // worker cannot be created or the request cannot be posted. Only `onmessage` used to be\n // wired, so a worker that failed to load left `generateIdentity()` pending forever and\n // the worker alive.\n private static ephemeralWorkerCall<T>(req: Request): Promise<T> {\n let w: Worker;\n try {\n w = new Worker(new URL(\"./worker.js\", import.meta.url), { type: \"module\" });\n } catch {\n return Promise.reject(new EphemeralWorkerError(\"spawn\"));\n }\n return new Promise<T>((resolve, reject) => {\n let settled = false;\n const settle = (finish: () => void): void => {\n if (settled) return;\n settled = true;\n w.onmessage = null;\n w.onerror = null;\n w.onmessageerror = null;\n w.terminate();\n finish();\n };\n w.onmessage = (ev) => {\n const msg = ev.data as Response;\n if (msg.kind === \"result\" && msg.id === (req as { id: number }).id) {\n settle(() => (msg.ok ? resolve(msg.value as T) : reject(new Error(msg.error))));\n }\n };\n w.onerror = () => settle(() => reject(new EphemeralWorkerError(\"error\")));\n w.onmessageerror = () => settle(() => reject(new EphemeralWorkerError(\"messageerror\")));\n try {\n w.postMessage(req);\n } catch {\n settle(() => reject(new EphemeralWorkerError(\"post\")));\n }\n });\n }\n\n static async init(cfg: ClientConfig): Promise<MessagingClient> {\n const worker = new Worker(new URL(\"./worker.js\", import.meta.url), { type: \"module\" });\n const client = new MessagingClient(cfg, worker);\n\n // Which optional transport methods exist decides the proxy the worker\n // hands the wasm (see `TransportFeatures`).\n const transportFeatures: TransportFeatures = {\n fetchLogSince: typeof cfg.transport.fetchLogSince === \"function\",\n fetchLogHeads: typeof cfg.transport.fetchLogHeads === \"function\",\n };\n // Likewise for the optional storage methods: with `applyBatch` the\n // per-row MLS store hands the host each checkpoint delta as ONE atomic\n // write, with `listEntries` it opens in one read (see `Storage` in\n // types.ts). Probed on the storage the worker's calls are dispatched to\n // (`client.storage`, scoped when `accountNamespace` is set), never on\n // `cfg.storage`: advertising a method the dispatch target lacks is how\n // every scoped account once failed to open its store.\n const storageFeatures = storageFeaturesOf(client.storage);\n await client.call({\n kind: \"init\",\n id: client.nextId++,\n identityExport: cfg.identityExport,\n deviceLabel: cfg.deviceLabel,\n nowMs: client.now(),\n ...(cfg.deviceSigningSecretKey\n ? { deviceSigningSecretKey: cfg.deviceSigningSecretKey }\n : {}),\n ...(cfg.expectedOwners ? { expectedOwners: cfg.expectedOwners } : {}),\n transportFeatures,\n storageFeatures,\n });\n\n // Cache the device id once so we can drop envelopes we sent ourselves on the WS echo.\n client.ownDeviceId = await client.deviceId();\n\n // Start the live subscription. A sequenced frame (`{ envelope, serverSeq }`\n // with a known position) is coalesced per conversation into\n // `processSequencedBatch`; a bare envelope takes the legacy path, which\n // dispatches each envelope to the right handler:\n // - Welcome envelopes for unknown conversations → joinConversation\n // - Welcomes for already-joined conversations → drop (server may broadcast duplicates)\n // - Welcomes addressed to other devices → drop (we can't decrypt)\n // - Everything else → processEnvelope\n // The callback RETURNS the dispatch promise so a transport that wants to\n // await application (to ack a delivery watermark, or to avoid advancing a\n // cursor past an envelope that has not been applied) can. Transports that\n // ignore the return value are unaffected — ordering is guaranteed inside\n // `dispatchIncoming` regardless, because it enqueues synchronously.\n client.subscription = cfg.transport.subscribe(\n (frame) => client.dispatchIncoming(frame),\n );\n return client;\n }\n\n /**\n * Internal: route an inbound envelope to the right handler, IN ARRIVAL ORDER\n * PER CONVERSATION.\n *\n * ## Why the ordering is load-bearing\n *\n * A group invitation arrives as a Welcome immediately followed by the\n * inviter's hydration Application messages (group title, roster, avatar id).\n * `joinConversation` is asynchronous — it is several round trips to the WASM\n * worker — so a naive `void dispatchIncoming(...)` per frame let the\n * Applications reach `processEnvelope` while the join was still in flight.\n * The conversation did not exist yet, so every one of them was dropped with\n * \"envelope drop: unknown conversation\".\n *\n * That loss is PERMANENT and silent: MLS ratchets forward, the transport has\n * already marked the frames seen and advanced its cursor, and the server will\n * not resend them. The visible symptom was an invitation landing as an\n * unnamed \"New chat\" with no avatar and no roster, and — for the same reason —\n * a rename, avatar change, member add/remove or role change being lost\n * whenever it happened to land while a join or another commit for that group\n * was still being applied.\n *\n * Chaining PER CONVERSATION (not globally) is deliberate: MLS state is\n * per-group, so that is the granularity correctness actually requires, and a\n * busy conversation must not be able to head-of-line block every other one.\n * The chain is built synchronously on entry, so chain order is exactly frame\n * arrival order.\n *\n * ## Sequenced frames\n *\n * A frame that carries its server position (`{ envelope, serverSeq }`,\n * `serverSeq > 0`) does not need the chain: the core applies it at its\n * position, holds it ahead of a hole and drops it at or below what was\n * applied, whatever order it arrived in. What it needs is BATCHING: one\n * MLS checkpoint and one host transaction per burst instead of one per\n * frame. So the first frame for a conversation goes to the worker at once\n * as a batch of one, and frames that arrive while that batch is in flight\n * accumulate and go out as ONE `processSequencedBatch` when it returns; no\n * timer ever delays a frame. Own-device echoes are NOT dropped on this\n * path: the core advances the position past them without touching MLS,\n * and dropping one would leave a hole the next frame reports as a gap. A\n * sequenced frame at `serverSeq` 0 is a legacy frame in a wrapper and\n * takes the legacy path unchanged.\n */\n private dispatchIncoming(frame: MessageEnvelope | SequencedEnvelope): Promise<void> {\n if (isSequencedFrame(frame)) {\n if (frame.serverSeq > 0) {\n return this.coalescer.push(hexOf(frame.envelope.conversation_id), frame);\n }\n return this.dispatchLegacy(frame.envelope);\n }\n return this.dispatchLegacy(frame);\n }\n\n /** The legacy per-envelope path: own-device drop, then the per-conversation chain. */\n private dispatchLegacy(envelope: MessageEnvelope): Promise<void> {\n // The relay broadcasts every envelope to every WS subscriber, including the sender. For\n // our own sends, the local MLS state has already been advanced in-process — re-applying\n // would either fail with \"epoch differs\" (commits) or be a no-op dedupe (application\n // messages). Skip them here.\n //\n // Checked BEFORE enqueuing: our own echo needs no ordering guarantee and\n // must not occupy a slot in the conversation's chain.\n if (this.ownDeviceId && sameBytesU8(envelope.sender_device, this.ownDeviceId)) {\n return Promise.resolve();\n }\n\n const key = hexOf(envelope.conversation_id);\n const prior = this.dispatchChains.get(key) ?? Promise.resolve();\n // `.catch` before `.then` so one failed envelope cannot poison the chain and\n // silently swallow every later envelope for that conversation.\n const next = prior\n .catch(() => undefined)\n .then(() => this.dispatchIncomingOrdered(envelope));\n // The map holds — and the cleanup compares against — THE SAME promise.\n // Storing `next.finally(cb)` while `cb` compares against `next` can never\n // match, so the entry would never be deleted and the map would retain a live\n // chain per conversation for the whole session.\n // The STORED tail must never reject: nobody awaits it, so a rejection here\n // surfaces as an unhandled rejection in the host's console. The returned\n // `next` still rejects, so a transport that DOES await sees real failures.\n const tail: Promise<void> = next\n .catch(() => undefined)\n .finally(() => {\n // Only the tail clears the entry; a chain that grew while we ran stays.\n if (this.dispatchChains.get(key) === tail) this.dispatchChains.delete(key);\n });\n this.dispatchChains.set(key, tail);\n return next;\n }\n\n /** The actual routing, run inside the per-conversation chain. */\n private async dispatchIncomingOrdered(envelope: MessageEnvelope): Promise<void> {\n if (envelope.kind === \"Welcome\") {\n try {\n const known = await this.listConversations();\n const already = known.some((m) => sameBytesU8(m.id, envelope.conversation_id));\n if (already) {\n // Normally a duplicate broadcast for a group we're already in → skip.\n // BUT a re-invite AFTER removal reuses the same conversation_id, so we\n // must NOT blanket-skip: if this conversation is STRANDED (we missed a\n // Commit, or were removed and our local group can no longer advance),\n // the Welcome is our way back in. Attempt the join — `joinConversation`\n // REPLACES the stale group; a genuine duplicate (our KeyPackage already\n // consumed, or addressed to another device) fails harmlessly with\n // KeyPackageNotFound in the catch below and never disturbs a healthy\n // active group. (The core also tears a group down on self-removal, so\n // a cleanly-removed conversation is already UNKNOWN here; this covers\n // the case where the removing Commit was never processed.)\n const stranded = await this.strandedConversations();\n const isStranded = stranded.some((id) => sameBytesU8(id, envelope.conversation_id));\n if (!isStranded) return;\n }\n await this.joinConversation(envelope);\n } catch (e) {\n // Welcomes are broadcast to every connected client; only one device's KeyPackage can\n // decrypt each one, so most fail. Log at debug, drop silently.\n if (typeof console !== \"undefined\") console.debug(\"[ping-sdk] welcome ignored:\", e);\n }\n return;\n }\n try {\n await this.processEnvelope(envelope);\n } catch (e) {\n // NOT a silent drop any more. `core` RETAINS an envelope it cannot apply\n // yet (its Welcome has not been processed, or a Commit that advances the\n // epoch is missing) and replays it on join / epoch advance / catch-up\n // sync — see docs/INVITE_HARDENING.md §S6. The throw here is\n // informational: the frame is already buffered one layer down.\n if (typeof console !== \"undefined\") console.debug(\"[ping-sdk] envelope deferred:\", e);\n }\n }\n\n /**\n * One coalesced batch of live frames. Errors are logged at debug and\n * swallowed, exactly as the legacy path treats a failed envelope: the\n * dispatch promise a transport may await resolves either way, and the\n * core retains anything it could not apply yet.\n */\n private async applyLiveBatch(items: SequencedEnvelope[]): Promise<void> {\n try {\n await this.processSequencedBatch(items);\n } catch (e) {\n if (typeof console !== \"undefined\") console.debug(\"[ping-sdk] sequenced batch failed:\", errorKind(e));\n }\n }\n\n /** Start a fill for every gap a batch reported; each is single-flight. */\n private scheduleGapFills(result: ApplyBatchResult): void {\n for (const gap of result.gaps) {\n void this.fillGap(gap.conversationId).catch((e: unknown) => {\n if (typeof console !== \"undefined\") console.debug(\"[ping-sdk] gap fill failed:\", errorKind(e));\n });\n }\n }\n\n /** One page, delivered as a page, on the requested lane. */\n private async stepConversation(id: ConversationId, stepped: boolean): Promise<SyncStepResult> {\n const raw = await this.call({\n kind: \"syncConversationStep\", id: this.nextId++, conv: id, nowMs: this.now(),\n ...(stepped ? { stepped: true } : {}),\n }) as SyncStepResultWire;\n const result = syncStepResultFromWire(raw);\n this.fanout.deliverBatch(result.messages, { source: \"page\" });\n return result;\n }\n\n // ------------------------ Public API ------------------------\n\n async userId(): Promise<UserId> {\n return await this.call({ kind: \"userId\", id: this.nextId++ }) as UserId;\n }\n\n /**\n * Export the account identity seed (CBOR-wrapped Ed25519, **SECRET**).\n * Transfer to a newly-linked device over the sealed linking channel so all of\n * an account's devices share one `userId` — the basis for cross-device\n * self-attribution (`IncomingMessage.sender_user_id === userId()`). Never log\n * or persist in cleartext.\n */\n async exportIdentity(): Promise<Uint8Array> {\n return await this.call({ kind: \"exportIdentity\", id: this.nextId++ }) as Uint8Array;\n }\n\n /**\n * RETIRED (2026-11-03): always rejects (`Invalid`) and changes nothing.\n *\n * It moved every conversation's own leaf to a new account identity with a\n * credential-changing Commit, the way out of `409 mls_identity_conflict`.\n * Every Ping client now refuses a Commit that changes a member's leaf\n * credential (a hostile linked device could otherwise move its leaf to a\n * peer's identity and escape the account's removal), so a rotation would\n * strand every conversation it touched. The way out of an identity conflict\n * is to link this device again, or sign out and in. Kept so no caller\n * breaks. See `docs/MULTIDEVICE.md` \"Identity rotation\".\n *\n * @deprecated Retired: always rejects. Link this device again instead.\n */\n async rotateIdentity(\n newIdentityExport: Uint8Array,\n nowMs: number = this.now(),\n ): Promise<IdentityRotation> {\n return await this.call({\n kind: \"rotateIdentity\", id: this.nextId++, newIdentityExport, nowMs,\n }) as IdentityRotation;\n }\n\n /**\n * RETIRED with [[rotateIdentity]]: always rejects (`Invalid`).\n *\n * @deprecated Retired: always rejects.\n */\n async rotateIdentityRetry(\n conv: ConversationId,\n nowMs: number = this.now(),\n ): Promise<void> {\n await this.call({ kind: \"rotateIdentityRetry\", id: this.nextId++, conv, nowMs });\n }\n\n async deviceId(): Promise<DeviceId> {\n return await this.call({ kind: \"deviceId\", id: this.nextId++ }) as DeviceId;\n }\n\n /**\n * Release every file lock the MLS store holds so the host process can be\n * suspended. Resolves `true` when the locks are genuinely gone.\n *\n * Present on web for API parity, and a no-op returning `true` here: this build\n * persists through the host's `Storage` (IndexedDB by default), which holds no\n * file locks and has nothing to release. It is load-bearing on the native\n * bindings, where iOS kills a backgrounded process that still holds a lock on\n * a file in an App Group container. Exposed on every platform so a host\n * sharing code across web and native does not have to branch on it.\n *\n * Pair with `resumeStorage()`.\n */\n async suspendStorage(): Promise<boolean> {\n return await this.call({ kind: \"suspendStorage\", id: this.nextId++ }) as boolean;\n }\n\n /** Undo `suspendStorage()`. Idempotent. */\n async resumeStorage(): Promise<void> {\n await this.call({ kind: \"resumeStorage\", id: this.nextId++ });\n }\n\n async freshKeyPackage(): Promise<Uint8Array> {\n return await this.call({ kind: \"freshKeyPackage\", id: this.nextId++ }) as Uint8Array;\n }\n\n /**\n * Generate a fresh LAST-RESORT KeyPackage (RFC 9420 §10). Publish exactly one\n * per device so the server can serve it repeatedly as a fallback when the\n * single-use pool empties — invites then never hard-fail purely because the\n * peer ran out of KeyPackages.\n */\n async freshLastResortKeyPackage(): Promise<Uint8Array> {\n return await this.call({ kind: \"freshLastResortKeyPackage\", id: this.nextId++ }) as Uint8Array;\n }\n\n async createConversation(opts: { name?: string } = {}): Promise<Conversation> {\n const idBytes = await this.call({\n kind: \"createConversation\", id: this.nextId++, name: opts.name ?? null, nowMs: this.now(),\n }) as ConversationId;\n return this.conversationProxy(idBytes);\n }\n\n /**\n * Create an ephemeral per-call MLS group. Identical to {@link createConversation}\n * except the id carries the `0xFF 0xCC` call-group sentinel, so every device\n * recognises it structurally (by id alone — no name, no registry) and keeps it\n * out of the chat list. Hosts MUST use this for call groups.\n */\n async createCallConversation(opts: { name?: string } = {}): Promise<Conversation> {\n const idBytes = await this.call({\n kind: \"createCallConversation\", id: this.nextId++, name: opts.name ?? null, nowMs: this.now(),\n }) as ConversationId;\n return this.conversationProxy(idBytes);\n }\n\n async joinConversation(welcome: MessageEnvelope): Promise<Conversation> {\n const idBytes = await this.call({\n kind: \"joinConversation\", id: this.nextId++, welcome, nowMs: this.now(),\n }) as ConversationId;\n return this.conversationProxy(idBytes);\n }\n\n /**\n * Get a `Conversation` proxy for an already-known conversation. Use this when you have a\n * conversation id (e.g., from `listConversations()`) and want to send/addMembers without\n * re-creating it. Throws if the id isn't known to the worker — call `listConversations()`\n * first to verify membership.\n */\n getConversation(id: ConversationId): Conversation {\n return this.conversationProxy(id);\n }\n\n async listConversations(): Promise<ConversationMeta[]> {\n const metas = await this.call({ kind: \"listConversations\", id: this.nextId++ }) as ConversationMeta[];\n this.metaCache.clear();\n for (const m of metas) this.metaCache.set(hex(m.id), m);\n return metas;\n }\n\n /**\n * Conversations detected as STRANDED during catch-up — a Commit was missed\n * and the group can no longer advance from local state, so new messages stop\n * arriving. Poll after a sync and recover each (re-Welcome / state-snapshot\n * import). Returns 16-byte conversation ids; the set self-clears as a\n * conversation makes progress or is re-joined.\n */\n async strandedConversations(): Promise<ConversationId[]> {\n return await this.call({ kind: \"strandedConversations\", id: this.nextId++ }) as ConversationId[];\n }\n\n /**\n * Conversations this device asked to leave and is still a member of:\n * the leave is OWED. The SDK holds their state and proposes the leave\n * again by itself; the host only keeps delivering their rows (live\n * frames and catch-up pages). An id leaves the list when the leave has\n * completed: this device processed its own removal and the state is\n * deleted. Sorted 16-byte conversation ids.\n */\n async conversationsLeaving(): Promise<ConversationId[]> {\n return await this.call({ kind: \"conversationsLeaving\", id: this.nextId++ }) as ConversationId[];\n }\n\n /**\n * The leaving conversations whose leave has STALLED: 8 sends of it\n * FAILED and this device is still a member, or this device can no longer\n * follow the group. Nothing more is proposed for them. The host may call\n * {@link leaveConversation} again (the count starts over) or give up with\n * {@link dropConversationLocal}, which leaves this device's leaf in the group\n * until somebody removes it. Sorted 16-byte conversation ids.\n */\n async conversationsLeaveStalled(): Promise<ConversationId[]> {\n return await this.call({ kind: \"conversationsLeaveStalled\", id: this.nextId++ }) as ConversationId[];\n }\n\n /**\n * Conversations this device was just torn down from by a SELF-RE-ADD Commit\n * — a peer's `reAdmitDevice` of this device — whose Welcome for the new\n * leaf is expected within seconds. Treat these as \"re-admission in flight\",\n * not stranded or evicted: no repair advertise, no delivery-key rotation,\n * no KeyPackage-pool replace, until the join lands or the entry ages out\n * (ten minutes). Returns 16-byte conversation ids.\n */\n async readmitPendingConversations(nowMs: number = Date.now()): Promise<ConversationId[]> {\n return await this.call({\n kind: \"readmitPendingConversations\",\n id: this.nextId++,\n nowMs,\n }) as ConversationId[];\n }\n\n /**\n * How many inbound envelopes are currently RETAINED awaiting replay, across\n * all conversations.\n *\n * An envelope that cannot be applied yet — its Welcome has not been processed,\n * or a Commit that advances the epoch is missing — is buffered and replayed on\n * join / epoch advance / catch-up sync rather than dropped (see\n * docs/INVITE_HARDENING.md §S6).\n *\n * A non-zero count means \"delivered but not yet applicable\", which is\n * materially different from \"not delivered\" and is the distinction a host\n * needs to explain a chat that looks incomplete. Expected to be 0 at rest; a\n * value that stays high points at a conversation whose handshake never\n * arrived.\n */\n async undeliverableCount(): Promise<number> {\n return await this.call({ kind: \"undeliverableCount\", id: this.nextId++ }) as number;\n }\n\n /**\n * Leave a conversation: broadcasts a self-Remove PROPOSAL (MLS forbids\n * committing your own removal: a remaining member commits it via\n * `commitPendingProposals`) and answers at once. From then on the conversation is\n * LEFT for the host: it is no longer listed, every call that names it\n * answers `UnknownConversation`, and nothing of it is surfaced again.\n *\n * Do NOT delete it locally afterwards ({@link dropConversationLocal}). The SDK keeps the\n * group's state, follows its Commits, and proposes the leave again after\n * each Commit that did not carry it (a Commit built before the proposal\n * arrived voids it), until this device is removed; then it deletes the\n * state itself. Keep delivering the conversation's rows to the client\n * while {@link conversationsLeaving} lists it. The bound is 8 FAILED sends;\n * after that {@link conversationsLeaveStalled} lists the conversation and calling\n * this again starts over.\n *\n * The group's OWNER hands over first: this call commits the successor (the\n * one every device computes when the owner's last leaf goes) and only then\n * proposes the leave. If that Commit cannot be made the call fails with the\n * Commit's error and nothing is marked: call it again. Nothing is handed\n * over when the owner's account keeps another device in the group or when\n * no other member could take over.\n */\n async leaveConversation(id: ConversationId, nowMs: number = this.now()): Promise<void> {\n await this.call({ kind: \"leaveConversation\", id: this.nextId++, conv: id, nowMs });\n }\n\n /**\n * Drop a conversation's local state with NO network side effect. Unlike\n * {@link leaveConversation} (which broadcasts a self-Remove proposal), this\n * sends nothing — use it for a group the SERVER does not back: an invite that\n * minted the MLS group locally but never completed server-side, so the backend\n * 404s `fetchSince` / 403s the member roster for it. Deletes the OpenMLS group\n * state + the on-disk snapshot rows so the dead group stops rehydrating on the\n * next restart (and re-materialising as a ghost \"New chat\"). Idempotent — safe\n * on an unknown/already-dropped id.\n */\n async dropConversationLocal(id: ConversationId): Promise<void> {\n await this.call({ kind: \"dropConversationLocal\", id: this.nextId++, conv: id });\n }\n\n /**\n * Conversations with buffered pending proposals (e.g. a peer's leave). Poll\n * after a sync; if you're the designated committer, call\n * `commitPendingProposals` to evict the leaver.\n */\n async conversationsWithPendingProposals(): Promise<ConversationId[]> {\n return await this.call({\n kind: \"conversationsWithPendingProposals\",\n id: this.nextId++,\n }) as ConversationId[];\n }\n\n /**\n * Commit buffered pending proposals for a conversation (evicts a peer who\n * left). No-op if nothing is pending; on an epoch-advanced rejection re-sync\n * (another member already committed). Call it on receipt (a batch or page\n * result's `proposalsPending`), elected with\n * {@link pendingProposalsCommitRank}. A `send` commits pending proposals\n * itself first, so a proposal never blocks a message.\n */\n async commitPendingProposals(id: ConversationId, nowMs: number = this.now()): Promise<void> {\n await this.call({ kind: \"commitPendingProposals\", id: this.nextId++, conv: id, nowMs });\n }\n\n /**\n * This device's rank in the deterministic election of who commits a\n * conversation's pending proposals: members by leaf index, excluding any\n * leaf a pending proposal removes; identical on every member. `0` means\n * commit now; rank `n` means wait `n` intervals (a few seconds each), then\n * commit if the proposals are still pending. `null` when nothing is pending\n * or this device is not eligible.\n */\n async pendingProposalsCommitRank(id: ConversationId): Promise<number | null> {\n const rank = await this.call({\n kind: \"pendingProposalsCommitRank\", id: this.nextId++, conv: id,\n }) as number | null | undefined;\n return rank ?? null;\n }\n\n /**\n * The Commits this device holds in doubt: a Commit whose send got no\n * definite answer (no response, a 5xx) is neither merged nor discarded; the\n * SDK settles it on a capped exponential backoff, and every operation in\n * that conversation fails with `commit in doubt` until it settles. Retry\n * such an operation at `nextAttemptAtMs`.\n */\n async commitsInDoubt(): Promise<CommitInDoubt[]> {\n const raw = await this.call({ kind: \"commitsInDoubt\", id: this.nextId++ }) as CommitInDoubtWire[];\n return raw.map(commitInDoubtFromWire);\n }\n\n /**\n * Member roster for a conversation, recovered locally from the MLS\n * group's leaf credentials (no network, no out-of-band message). Returns\n * one entry per device leaf — a multi-device user appears multiple times,\n * so dedup by `user_id` for a per-user roster. Empty for an unknown id.\n */\n async members(conv: ConversationId): Promise<MemberInfo[]> {\n return await this.call({ kind: \"members\", id: this.nextId++, conv }) as MemberInfo[];\n }\n\n /**\n * A conversation's credential policy (account-signed device credentials,\n * 2026-11-04): whether every leaf must carry a credential the account key signed\n * (`credentialsRequired`; a KeyPackage without one gets the add verdict\n * `credentialMissing`), the roles once the policy records them (round 2), and\n * `incapableMembers`, the accounts with a member on an app too old for this\n * group, which is what blocks the upgrade. Rejects for a conversation this client\n * does not hold. No host action is needed for the credentials themselves: the SDK\n * signs and verifies them internally.\n */\n async conversationPolicy(conv: ConversationId): Promise<ConversationPolicy> {\n return await this.call({ kind: \"conversationPolicy\", id: this.nextId++, conv }) as ConversationPolicy;\n }\n\n /**\n * Whether a Commit of THIS device that re-admits or adds the device `deviceId` of\n * the account `identity` would pass the membership rules of the conversation in\n * its state now, without building or sending anything (2026-11-18). True when\n * this device may add a leaf of that account (the owner, an admin, or a device of\n * that same account; a device of the OWNER only when this device is the owner's)\n * and, if `deviceId` holds a leaf there, may also remove that leaf. Always true in\n * a conversation without roles. Ask it BEFORE leasing a re-admission request or\n * claiming a KeyPackage: a device that is not privileged never claims another\n * account's KeyPackage. Advisory: the Commit is judged again when it is built and\n * by every receiver. Rejects for a conversation this client does not hold.\n */\n async mayReadmit(conv: ConversationId, identity: UserId, deviceId: DeviceId): Promise<boolean> {\n return await this.call({ kind: \"mayReadmit\", id: this.nextId++, conv, identity, deviceId }) as boolean;\n }\n\n /**\n * The identity (the account's user id) a KeyPackage's credential CLAIMS, read\n * without changing anything (2026-11-18, rule R13). `null` for a credential that\n * is not the project's. Rejects for bytes that are not a valid KeyPackage: the\n * checks OpenMLS runs on a KeyPackage an add carries run first (both signatures\n * under the leaf's own key, the version, the init key, the extensions against the\n * capabilities, the lifetime: an expired KeyPackage rejects).\n *\n * Before adding ANOTHER account's device, read it and compare it with the account\n * you meant to add, byte for byte; a different answer, or `null`, is enough to\n * refuse the KeyPackage the server handed out, before any Commit.\n *\n * The read runs the SAME credential verdict the add runs (the device\n * credential, then the leaf-ready check) and rejects for a claim the add\n * would refuse, so an identity answered is one the account's key vouched\n * for (rulings part 13, ruling 1; until then the answer was a bare claim).\n */\n async keyPackageIdentity(keyPackage: Uint8Array): Promise<UserId | null> {\n const identity = await this.call({\n kind: \"keyPackageIdentity\", id: this.nextId++, keyPackage,\n }) as UserId | null | undefined;\n return identity ?? null;\n }\n\n /**\n * Replace the owners this client expects first roles writes to name\n * (2026-11-04, round 2; see `ClientConfig.expectedOwners`).\n */\n async setExpectedOwners(entries: ExpectedOwner[]): Promise<void> {\n await this.call({ kind: \"setExpectedOwners\", id: this.nextId++, entries });\n }\n\n /**\n * Record a group's roles in its policy (2026-11-04, round 2): `owner` and\n * `admins` as MLS user ids (map account ids through the roster). One\n * GroupContextExtensions Commit, no Welcome, send-then-merge. Rejects with\n * \"not permitted ...\" before anything is sent when this device's role does not\n * allow the change, when a member's app is too old for roles\n * (`conversationPolicy().incapableMembers` names it), or in the DeviceGroup.\n * The same call as `getConversation(id).setConversationRoles`.\n */\n async setConversationRoles(conv: ConversationId, owner: UserId, admins: UserId[]): Promise<void> {\n await this.call({\n kind: \"setConversationRoles\", id: this.nextId++, conv, owner, admins, nowMs: this.now(),\n });\n }\n\n /**\n * Whole-account catch-up. The worker runs it one conversation at a time and\n * lets every other request (a `send` the user is waiting on, a live frame)\n * run between conversations, so a pass over many conversations never parks\n * an interactive call behind all of them. Resolves when every conversation\n * held at the start of the pass (plus any joined while it ran) has been\n * paged, with the decrypted application messages in apply order.\n */\n async syncConversations(): Promise<IncomingMessage[]> {\n return await this.call({\n kind: \"syncConversations\", id: this.nextId++, nowMs: this.now(),\n }) as IncomingMessage[];\n }\n\n /**\n * Catch-up for ONE conversation: the unit `syncConversations` is built from.\n * Use it to bring the conversation the user is looking at up to date ahead\n * of the rest (a message must be encrypted at the epoch the group is really\n * at, so a host calls this before the first send after a reconnect), or to\n * step a pass in an order of its own. Rejects with the SDK's\n * `unknown conversation` error for an id this client does not hold.\n */\n async syncConversation(id: ConversationId): Promise<IncomingMessage[]> {\n return await this.call({\n kind: \"syncConversation\", id: this.nextId++, conv: id, nowMs: this.now(),\n }) as IncomingMessage[];\n }\n\n async processEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null> {\n return await this.call({\n kind: \"processEnvelope\", id: this.nextId++, envelope, nowMs: this.now(),\n }) as IncomingMessage | null;\n }\n\n // ------------------------ Sequenced log sync ------------------------\n // See docs/SYNC_PROTOCOL.md \"Sequenced log sync\". The subscribe path feeds\n // these itself for a transport that hands over sequenced frames; they are\n // public for hosts that drive their own socket.\n\n /**\n * Apply a batch of live frames, each with its server log position, and\n * checkpoint once per touched conversation. Per conversation: the next\n * position applies, one ahead of a hole is held and reported in `gaps`,\n * one at or below the applied position is a duplicate. Welcomes are routed\n * to a join inside the SDK (a join anchors the new conversation at the\n * Welcome's position); own-device echoes advance the position without\n * touching MLS, so pass them through. Frames at `serverSeq` 0 take the\n * legacy per-sender path.\n *\n * The decrypted messages are returned AND delivered: to `onMessageBatch`\n * handlers as one call (source `live`) when any is registered, else per\n * message to `onMessage` handlers. `onConversationUpdated` fires once per\n * entry of `updated`. A reported gap starts {@link fillGap} for that\n * conversation.\n */\n async processSequencedBatch(items: SequencedEnvelope[]): Promise<ApplyBatchResult> {\n const raw = await this.call({\n kind: \"processSequencedBatch\", id: this.nextId++,\n items: items.map(sequencedToWire), nowMs: this.now(),\n }) as ApplyBatchResultWire;\n const result = applyBatchResultFromWire(raw);\n this.fanout.deliverBatch(result.messages, { source: \"live\" });\n this.scheduleGapFills(result);\n return result;\n }\n\n /**\n * ONE page of a conversation's server log through `Transport.fetchLogSince`,\n * applied in order and checkpointed once, then whatever held frames the\n * page made contiguous. `hasMore` means step again. Same delivery as\n * {@link processSequencedBatch}, with source `page`. An ordinary request:\n * it runs ahead of any background pass, so a host can bring the open chat\n * current first. Rejects with the SDK's `unknown conversation` error for an\n * id this client does not hold; the durable cursor is unchanged on a\n * transport failure.\n */\n async syncConversationStep(id: ConversationId): Promise<SyncStepResult> {\n return this.stepConversation(id, false);\n }\n\n /**\n * Fill a conversation's gap: run {@link syncConversationStep} until\n * `hasMore` is false, single-flight per conversation, on the worker's\n * stepped lane so a send posted meanwhile goes between pages. The SDK\n * starts this itself for every gap a batch reports; hosts call it for the\n * heads a socket `resume_ack` shows above the local position. A call\n * while a fill is running rides on it (and the loop runs once more after,\n * in case the running one ended before the new gap's rows were appended).\n */\n fillGap(conversationId: ConversationId): Promise<void> {\n return this.gapFiller.fill(hexOf(conversationId), async () => {\n const page = await this.stepConversation(conversationId, true);\n return page.hasMore;\n });\n }\n\n /**\n * This device's applied position in every conversation it holds, sorted by\n * conversation id: what a host puts in its socket resume frame and\n * compares against the server's heads.\n */\n async logPositions(): Promise<LogPosition[]> {\n const raw = await this.call({ kind: \"logPositions\", id: this.nextId++ }) as LogPositionWire[];\n return raw.map(logPositionFromWire);\n }\n\n /** This device's applied position in one conversation; `null` when not held. */\n async logPosition(id: ConversationId): Promise<LogPosition | null> {\n const raw = await this.call({ kind: \"logPosition\", id: this.nextId++, conv: id }) as LogPositionWire | null;\n return raw === null || raw === undefined ? null : logPositionFromWire(raw);\n }\n\n /**\n * Anchor a conversation whose cursor predates positions at the\n * `(epoch, serverSeq)` the host had recorded for it, so an existing install\n * does not page its whole current epoch again. Resolves `false` (a no-op)\n * when the conversation is already anchored; the MLS epoch is never\n * touched. Call it once at start-up for every conversation the host's own\n * cursor store holds a position for.\n */\n async adoptLogPosition(id: ConversationId, epoch: number, serverSeq: number): Promise<boolean> {\n return await this.call({\n kind: \"adoptLogPosition\", id: this.nextId++, conv: id, epoch, serverSeq,\n }) as boolean;\n }\n\n /**\n * Conversations the server's heads show this device is behind on: not\n * anchored yet, a head above the applied position, or frames held in the\n * reorder buffer. Sorted by id. A held conversation absent from `heads` is\n * not listed.\n */\n async conversationsBehind(heads: LogHead[]): Promise<ConversationId[]> {\n return await this.call({\n kind: \"conversationsBehind\", id: this.nextId++, heads: heads.map(logHeadToWire),\n }) as ConversationId[];\n }\n\n /** Frames held in reorder buffers right now (diagnostics). */\n async heldFrameCount(): Promise<number> {\n return await this.call({ kind: \"heldFrameCount\", id: this.nextId++ }) as number;\n }\n\n /**\n * {@link joinConversation} at the Welcome's log position, so the new\n * conversation is anchored there and its first live frame applies without\n * a page. Pass `null` (or omit) when the position is unknown.\n */\n async joinConversationAt(welcome: MessageEnvelope, position: number | null = null): Promise<Conversation> {\n const idBytes = await this.call({\n kind: \"joinConversationAt\", id: this.nextId++, welcome, position, nowMs: this.now(),\n }) as ConversationId;\n return this.conversationProxy(idBytes);\n }\n\n /**\n * The Welcome routing rule at a known position: joins when the conversation\n * is unknown or held stranded and resolves to it, resolves `null` when it\n * is held healthy (a relay duplicate), rejects when the Welcome is not\n * addressed to this device.\n */\n async processWelcomeAt(welcome: MessageEnvelope, position: number | null = null): Promise<Conversation | null> {\n const idBytes = await this.call({\n kind: \"processWelcomeAt\", id: this.nextId++, welcome, position, nowMs: this.now(),\n }) as ConversationId | null;\n return idBytes === null || idBytes === undefined ? null : this.conversationProxy(idBytes);\n }\n\n /**\n * [D27] Decrypted-but-unconfirmed messages surviving in the pending-apply\n * journal, oldest first.\n *\n * The MLS ratchet advances at decrypt, BEFORE the host persists its own row\n * for the message; a crash inside that gap used to lose the message for good\n * (the server re-delivers, but MLS cannot re-decrypt a consumed generation).\n * The SDK now journals every decrypt in the same checkpoint that persists\n * the ratchet advance.\n *\n * CRASH-RECOVERY CONTRACT: on boot, BEFORE advancing any sync cursor or\n * sending any delivery ack, drain this list through the normal ingest —\n * dedup by `content_hash` / envelope identity exactly as for a redelivered\n * envelope — persist each message, then {@link confirmApplied} the drained\n * ids. Reading does not consume; unconfirmed entries survive further\n * restarts (bounded: 512 entries / 4 MiB, oldest evicted). See\n * docs/PENDING_APPLIES.md.\n */\n async pendingApplies(): Promise<PendingApply[]> {\n return await this.call({ kind: \"pendingApplies\", id: this.nextId++ }) as PendingApply[];\n }\n\n /**\n * [D27] Delete journal entries whose messages the host has durably\n * persisted (`IncomingMessage.journal_id` from live processing, or\n * `PendingApply.journal_id` from a boot drain), and checkpoint so the\n * deletion survives a reload. Unknown ids are ignored (idempotent).\n */\n async confirmApplied(journalIds: string[]): Promise<void> {\n if (journalIds.length === 0) return;\n await this.call({ kind: \"confirmApplied\", id: this.nextId++, journalIds });\n }\n\n /**\n * Build a `LinkingTicket` for a new device.\n *\n * [CR-13] `lastAppEvents` is host-supplied per-conversation \"what you missed\" data\n * (decrypted AppEvent bytes the new device will render before sync catches up).\n * Pass `[]` to suppress catchup data — the new device will see an empty conversation\n * list until normal sync runs.\n *\n * Caller is responsible for HPKE-sealing the returned ticket via\n * `MessagingClient.sealLinkingTicket` before transmitting (CR-3).\n *\n * Rejects (`Invalid`), before anything is sent, a KeyPackage that claims the\n * identity of another account this client knows: a new device links under an\n * identity of its own, or the account's.\n */\n async buildLinkingTicket(\n newDeviceId: DeviceId,\n newDeviceKp: Uint8Array,\n lastAppEvents: CatchupAppEvent[] = [],\n ): Promise<LinkingTicket> {\n return await this.call({\n kind: \"buildLinkingTicket\", id: this.nextId++,\n newDeviceId, newDeviceKp, lastAppEvents, nowMs: this.now(),\n }) as LinkingTicket;\n }\n\n /**\n * Decode a `LinkingTicket.catchup_snapshot` blob ([CR-13]).\n *\n * Pure WASM — runs in an ephemeral worker so the new device can call this before\n * `MessagingClient.init()` completes (just like `openLinkingTicket`). Returns the\n * structured view: per-conversation metas + last-known AppEvent bytes.\n *\n * Throws on malformed or oversized inputs. Empty bytes return `null` — that's the\n * \"no catchup data\" case (sender passed `[]` to buildLinkingTicket).\n */\n static async decodeCatchupSnapshot(\n snapshotBytes: Uint8Array,\n ): Promise<CatchupSnapshotView | null> {\n if (snapshotBytes.length === 0) return null;\n return MessagingClient.ephemeralWorkerCall<CatchupSnapshotView>({\n kind: \"decodeCatchupSnapshot\", id: 1, snapshotBytes,\n });\n }\n\n async consumeLinkingTicket(ticket: LinkingTicket): Promise<void> {\n await this.call({\n kind: \"consumeLinkingTicket\", id: this.nextId++, ticket, nowMs: this.now(),\n });\n }\n\n // ------------------------ Recovery (account backup) ------------------------\n // All static + stateless: they run on an ephemeral worker, so the recovery screen can\n // call them before any client is initialised. Same Argon2id/AES-256-GCM IdentityBackup\n // wire format as the iOS/Android FFI bindings — backups are portable across platforms.\n\n /** Generate a fresh 12-word BIP39 mnemonic, returned as its canonical phrase string. */\n static async generateMnemonicPhrase(): Promise<string> {\n return MessagingClient.ephemeralWorkerCall<string>({\n kind: \"generateMnemonicPhrase\", id: 1,\n });\n }\n\n /** Validate + canonicalise a user-entered phrase (BIP39 wordlist + checksum). Rejects\n * malformed input. Use on the recovery screen before calling `decryptBackup`. */\n static async normalizeMnemonicPhrase(phrase: string): Promise<string> {\n return MessagingClient.ephemeralWorkerCall<string>({\n kind: \"normalizeMnemonicPhrase\", id: 1, phrase,\n });\n }\n\n /** Encrypt an IdentityBackup for `POST /v1/recovery/blobs`. `deviceGroupSnapshot` may be\n * empty (Conservative path) or the DeviceGroup's `exportConversationStateSnapshot`. */\n static async encryptBackup(args: {\n mnemonicPhrase: string;\n accountId: Uint8Array;\n identityExport: Uint8Array;\n deviceGroupSnapshot: Uint8Array;\n /** External conversations to embed so recovery restores them offline. Pass\n * `[]` (the default) for identity + DeviceGroup only. Each `groupStateBytes`\n * is `Conversation.exportConversationStateSnapshot` output. Forward-secrecy\n * trade-off — see the SDK recovery docs. */\n conversationSnapshots?: { conversationId: Uint8Array; groupStateBytes: Uint8Array }[];\n createdAtMs: number;\n }): Promise<Uint8Array> {\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"encryptBackup\", id: 1,\n mnemonicPhrase: args.mnemonicPhrase,\n accountId: args.accountId,\n identityExport: args.identityExport,\n deviceGroupSnapshot: args.deviceGroupSnapshot,\n conversationSnapshots: args.conversationSnapshots ?? [],\n createdAtMs: args.createdAtMs,\n });\n }\n\n /** Decrypt a recovery blob from `GET /v1/recovery/blobs`. Throws on wrong mnemonic or a\n * tampered blob. The returned `identity_export` is the secret seed for `init`. */\n static async decryptBackup(\n blob: Uint8Array,\n mnemonicPhrase: string,\n ): Promise<RecoveryBackup> {\n return MessagingClient.ephemeralWorkerCall<RecoveryBackup>({\n kind: \"decryptBackup\", id: 1, blob, mnemonicPhrase,\n });\n }\n\n // ------------------------ Peer-assisted history transfer ------------------------\n // Authenticated (sign-then-encrypt) device-to-device history used by linking and\n // post-recovery peer re-add. Confidential to the recipient's ephemeral X25519 key AND\n // signed by the account identity key, so the receiver proves the sender. Plaintext-only\n // share — preserves forward secrecy (no MLS keys leave the device).\n\n /** Seal+sign a `HistoryBundle` for a recipient device. `recipientPub` (X25519, 32B) is the\n * recipient's ephemeral pubkey from the linking QR; `senderIdentitySecret` (Ed25519 seed,\n * 32B) is this account's identity key. Returns the blob to POST to /v1/history-transfers. */\n static async sealHistoryBundle(\n bundle: HistoryBundle,\n recipientPub: Uint8Array,\n senderIdentitySecret: Uint8Array,\n ): Promise<Uint8Array> {\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"sealHistoryBundle\", id: 1, bundle, recipientPub, senderIdentitySecret,\n });\n }\n\n /** Open+verify a sealed history bundle. `recipientPriv` (X25519, 32B) is this device's\n * ephemeral private key; `senderIdentityPub` (Ed25519, 32B) is the account identity pubkey\n * from the linking handshake. Throws if the signature doesn't verify. */\n static async openHistoryBundle(\n sealed: Uint8Array,\n recipientPriv: Uint8Array,\n senderIdentityPub: Uint8Array,\n ): Promise<HistoryBundle> {\n return MessagingClient.ephemeralWorkerCall<HistoryBundle>({\n kind: \"openHistoryBundle\", id: 1, sealed, recipientPriv, senderIdentityPub,\n });\n }\n\n /**\n * Post-quantum {@link sealHistoryBundle}: `recipientPub` is the recipient's\n * X-Wing public key ({@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes). Wrapper `v: 2`;\n * the classical open refuses it and vice versa.\n */\n static async sealHistoryBundlePq(\n bundle: HistoryBundle,\n recipientPub: Uint8Array,\n senderIdentitySecret: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {\n throw new Error(`sealHistoryBundlePq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"sealHistoryBundlePq\", id: 1, bundle, recipientPub, senderIdentitySecret,\n });\n }\n\n /** Post-quantum {@link openHistoryBundle}: `recipientPriv` is the 32-byte X-Wing seed. */\n static async openHistoryBundlePq(\n sealed: Uint8Array,\n recipientPriv: Uint8Array,\n senderIdentityPub: Uint8Array,\n ): Promise<HistoryBundle> {\n if (recipientPriv.length !== 32) {\n throw new Error(\"openHistoryBundlePq: recipientPriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<HistoryBundle>({\n kind: \"openHistoryBundlePq\", id: 1, sealed, recipientPriv, senderIdentityPub,\n });\n }\n\n /**\n * Admit a freshly-linked device to every chat in `entries` — one MLS\n * Commit + Welcome per chat, with the Welcome's `?recipient=` priming\n * handled inside the SDK. This is the post-link reconciliation step\n * that follows `consumeLinkingTicket`: the new device has the\n * DeviceGroup (from the ticket) and metadata for external chats (from\n * the catchup snapshot), but its leaf is not yet in any external\n * MLS group. The host on the EXISTING device calls this once the\n * new device shows up in `/v1/auth/sessions` and has uploaded its\n * KeyPackage batch, passing one freshly-claimed KP per chat.\n *\n * Per-chat failures (stale KP, transport error, unknown chat) are\n * captured in the returned outcomes rather than aborting — one bad\n * chat shouldn't lose the user access to all the others.\n *\n * Each KeyPackage must carry this account's identity (a linked device\n * adopts it with the link): one that claims any other identity fails its\n * chat and nothing is sent there.\n */\n async admitDeviceToChats(\n deviceId: DeviceId,\n entries: AdmitChatEntry[],\n ): Promise<AdmitChatOutcome[]> {\n return await this.call({\n kind: \"admitDeviceToChats\", id: this.nextId++,\n deviceId, entries, nowMs: this.now(),\n }) as AdmitChatOutcome[];\n }\n\n /**\n * `admitDeviceToChats` with up to `concurrency` admissions in flight at\n * once. Same input, same per-chat outcomes in INPUT order whatever order\n * the sends finish in; `concurrency` 1 is exactly `admitDeviceToChats`,\n * 0 is treated as 1. Safe because every admission is its own conversation\n * (one Commit + Welcome per chat, the conversation lock is never held\n * across the send), so two admissions never touch the same epoch.\n *\n * This is the ONLY way to overlap admissions on web: the worker runs one\n * call at a time, so several `admitDeviceToChats` calls issued together\n * still run one after another. The overlap happens inside this one call.\n */\n async admitDeviceToChatsConcurrent(\n deviceId: DeviceId,\n entries: AdmitChatEntry[],\n concurrency: number,\n ): Promise<AdmitChatOutcome[]> {\n const lanes = Number.isFinite(concurrency)\n ? Math.min(0xffff_ffff, Math.max(1, Math.floor(concurrency)))\n : 1;\n return await this.call({\n kind: \"admitDeviceToChatsConcurrent\", id: this.nextId++,\n deviceId, entries, nowMs: this.now(), concurrency: lanes,\n }) as AdmitChatOutcome[];\n }\n\n /**\n * Revoke a device ([CR-2]).\n *\n * Removes `deviceId`'s leaf from every conversation where this client locally\n * tracked the device→leaf mapping (i.e. conversations where this client itself\n * admitted the device via `addMembers`, or where this client is the device being\n * revoked). The SDK has already broadcast each Commit envelope via\n * `transport.send`; the returned array is for any additional host-side handling\n * (audit logs, UI). An empty array is a valid outcome — the device wasn't locally\n * known anywhere.\n *\n * **Scope note.** Conversations where a peer admitted the device on this client's\n * behalf are silently skipped — the leaf index isn't locally known. Host can fall\n * back to `transport.discoverDevices` + a manual `remove_members(leafIndex)` for\n * those, or wait for the affected user to revoke from a device that did the admit.\n * See `docs/architecture/multi-device.md §Device removal`.\n */\n async revokeDevice(deviceId: DeviceId): Promise<MessageEnvelope[]> {\n return await this.call({\n kind: \"revokeDevice\", id: this.nextId++, deviceId, nowMs: this.now(),\n }) as MessageEnvelope[];\n }\n\n /**\n * Remove one of THIS account's devices from every group this client is in, the\n * DeviceGroup included, without stopping at a failure, and report where it stands.\n *\n * Unlike {@link revokeDevice}, the device's leaf is read from each ratchet tree (the\n * leaf whose key hashes to the id), so this reaches leaves a sibling or a peer\n * admitted. The id is the server's word that the device is this account's; outside\n * the DeviceGroup a leaf is removed only when its credential names this account, or\n * when the device was seen in the account's DeviceGroup and its credential names no\n * other account this client knows (docs/MULTIDEVICE.md, \"Which leaf\"). An id that\n * names no leaf of this account is rejected before anything is sent. Every held\n * conversation is checked: a Commit of this device in doubt is settled first, and\n * the log is read to its end before the device is reported absent (what that read\n * applies comes with the next batch or page); a conversation that failed to load\n * is a failure with reason `Unloadable`. The DeviceGroup goes first, then the\n * conversations, a few at a time, each a send-then-merge Commit. Persist the report\n * and call again until `failed` is empty and `deviceGroup !== \"failed\"`. A\n * `CommitInDoubt` reason settles on its own backoff ({@link commitsInDoubt});\n * `NotOwnAccount` and `RefusedCommit` never resolve by retrying (for\n * `RefusedCommit`, offer to recreate the conversation). Groups this device joins\n * later are checked for the device too.\n *\n * MLS only: revoke the device on the server yourself. Rejects for this device's own\n * id (leave a conversation with `leaveConversation` instead) and for a device that\n * is not this account's.\n */\n async removeDeviceEverywhere(\n deviceId: DeviceId,\n nowMs: number = this.now(),\n ): Promise<DeviceRemovalReport> {\n return await this.call({\n kind: \"removeDeviceEverywhere\", id: this.nextId++, deviceId, nowMs,\n }) as DeviceRemovalReport;\n }\n\n /**\n * Remove every other device of THIS account from every group this client is in,\n * except the devices in `keep` and this device: the \"secure my account\" sweep.\n *\n * `listed` is the server's list of this account's devices to remove (a reset's\n * `revoked_device_ids`). In the DeviceGroup every leaf but this device's and the\n * kept ones goes. Elsewhere a leaf goes when its credential names this client's\n * account (no device id has to match, so a device that moved its leaf to another\n * signature key is still reached), or when its device is in `listed` and was seen in\n * the account's DeviceGroup, whatever identity its leaf claims. A leaf the sweep\n * leaves although one of those two says it may be the account's (seen but not\n * listed, or listed but not seen) is reported: its conversation fails with\n * `NotOwnAccount`, so the report is never complete over it. Same pass and report as\n * {@link removeDeviceEverywhere}; call again until it is complete. MLS only.\n */\n async removeOwnDevicesExcept(\n keep: DeviceId[],\n listed: DeviceId[],\n nowMs: number = this.now(),\n ): Promise<DeviceRemovalReport> {\n return await this.call({\n kind: \"removeOwnDevicesExcept\", id: this.nextId++, keep, listed, nowMs,\n }) as DeviceRemovalReport;\n }\n\n /**\n * Export a portable MLS state snapshot for one conversation ([CR-7]).\n *\n * Returned bytes can be embedded in a recovery blob or shipped through a\n * linking ticket so another device of the same user identity can re-attach to\n * the group via [[importStateSnapshot]]. The bytes contain past epoch secrets;\n * never log, never persist unencrypted, wipe (`.fill(0)`) after use.\n */\n async exportConversationStateSnapshot(conv: ConversationId): Promise<Uint8Array> {\n return await this.call({\n kind: \"exportConversationStateSnapshot\", id: this.nextId++,\n conv, nowMs: this.now(),\n }) as Uint8Array;\n }\n\n /**\n * Import a `GroupStateSnapshot` from another device of the same user identity\n * ([CR-7]).\n *\n * On success, the conversation appears in [[listConversations]] and decryption\n * of subsequent peer-originated traffic works against the imported state. For\n * full multi-device participation, the recovered device SHOULD then issue an\n * MLS Update Proposal to rotate onto a fresh leaf (post-v1 follow-up — see\n * `docs/design/CR4_CR7_PERSISTENCE.md` open question #3).\n */\n async importStateSnapshot(snapshotBytes: Uint8Array): Promise<ConversationId> {\n return await this.call({\n kind: \"importStateSnapshot\", id: this.nextId++,\n snapshotBytes, nowMs: this.now(),\n }) as ConversationId;\n }\n\n /**\n * Export a derived secret from a conversation's MLS exporter ([CR-8]).\n *\n * Used to seed the ephemeral channel (`ping/ephemeral`), call-media keys\n * (`ping/calls/media/<call_id>`), and call-ephemeral framer keys\n * (`ping/calls/ephemeral/<call_id>`). The returned bytes are a secret — never log,\n * persist only encrypted, and call `bytes.fill(0)` after use to wipe the typed array.\n *\n * Same `(conversationId, current_epoch, label, context, length)` produces the same\n * bytes across every binding (Rust core, native UniFFI, WASM/JS). Cross-platform\n * byte-equality is enforced by `protocol/conformance/export_secret/`.\n */\n async exportConversationSecret(\n conv: ConversationId,\n label: string,\n context: Uint8Array,\n length: number,\n ): Promise<Uint8Array> {\n if (length <= 0 || length > 1024) {\n throw new Error(\"exportConversationSecret: length must be 1..=1024\");\n }\n return await this.call({\n kind: \"exportConversationSecret\", id: this.nextId++,\n conv, label, context, length,\n }) as Uint8Array;\n }\n\n /**\n * Subscribe to decrypted application messages, one call per message. A\n * batch or page result (the sequenced paths) is fanned out here per\n * message only while no {@link onMessageBatch} handler is registered.\n */\n onMessage(handler: (m: IncomingMessage) => void): () => void {\n return this.fanout.onMessage(handler);\n }\n\n /**\n * Subscribe to decrypted messages one BATCH at a time: one call per\n * `processSequencedBatch` result (source `live`) or per page of the server\n * log (source `page`: a gap fill, or the whole-account catch-up), so the\n * host persists the batch in one store transaction. While at least one\n * batch handler is registered, batch and page results go ONLY here, never\n * per message to `onMessage`; the legacy per-envelope path still delivers\n * per message. An empty result is not delivered.\n */\n onMessageBatch(handler: (messages: IncomingMessage[], meta: MessageBatchMeta) => void): () => void {\n return this.fanout.onMessageBatch(handler);\n }\n\n /** Fired after every state-changing event for a conversation (Commit, member changes). */\n /**\n * Fires after every conversation state change — joining via Welcome, processing a Commit,\n * etc. `sender` carries the device id of whoever triggered the event when known (e.g. the\n * inviter's device on auto-join), so the host can label peers in its UI.\n */\n onConversationUpdated(handler: (id: ConversationId, epoch: number, sender?: DeviceId) => void): () => void {\n this.conversationHandlers.add(handler);\n return () => this.conversationHandlers.delete(handler);\n }\n\n /**\n * Stop the live subscription and terminate the worker. Every call still in\n * flight rejects with a {@link MessagingClientClosedError} (reason\n * `closed`), and every later call rejects the same way instead of waiting\n * on a worker that no longer exists. Idempotent.\n */\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n this.subscription?.unsubscribe();\n this.worker.terminate();\n this.failPending(new MessagingClientClosedError(\"closed\"));\n }\n\n /** Reject every pending call with `error` and forget them. */\n private failPending(error: MessagingClientClosedError): void {\n const slots = [...this.pending.values()];\n this.pending.clear();\n for (const slot of slots) slot.reject(error);\n }\n\n // ------------------------ Internals ------------------------\n\n private conversationProxy(id: ConversationId): Conversation {\n const self = this;\n return {\n id,\n async send(plaintext) {\n return await self.call({\n kind: \"send\", id: self.nextId++, conv: id, plaintext, nowMs: self.now(),\n }) as MessageEnvelope;\n },\n async addMembers(entries) {\n await self.call({\n kind: \"addMembers\", id: self.nextId++, conv: id, entries, nowMs: self.now(),\n });\n },\n async addMembersWithVerdicts(entries) {\n const raw = await self.call({\n kind: \"addMembersWithVerdicts\", id: self.nextId++, conv: id, entries, nowMs: self.now(),\n }) as AddMembersReportWire;\n return addMembersReportFromWire(raw);\n },\n async reAdmitDevice(entry) {\n const replaced = await self.call({\n kind: \"reAdmitDevice\", id: self.nextId++, conv: id, entry, nowMs: self.now(),\n }) as DeviceId | null | undefined;\n return replaced ?? null;\n },\n async removeOwnOtherLeaves() {\n return await self.call({\n kind: \"removeOwnOtherLeaves\", id: self.nextId++, conv: id, nowMs: self.now(),\n }) as number;\n },\n async removeMembersByIdentity(identities) {\n return await self.call({\n kind: \"removeMembersByIdentity\", id: self.nextId++, conv: id, identities, nowMs: self.now(),\n }) as number;\n },\n async removeMembers(leaves) {\n await self.call({\n kind: \"removeMembers\", id: self.nextId++, conv: id, leaves, nowMs: self.now(),\n });\n },\n async setConversationName(name) {\n await self.call({\n kind: \"setConversationName\", id: self.nextId++, conv: id, name, nowMs: self.now(),\n });\n },\n async setConversationRoles(owner, admins) {\n await self.call({\n kind: \"setConversationRoles\", id: self.nextId++, conv: id, owner, admins, nowMs: self.now(),\n });\n },\n /**\n * The conversation's MLS GroupContext name, or `undefined` when the meta\n * cache has not been primed (call `listConversations()`).\n *\n * This accessor did not exist, and hosts reasonably assumed it did:\n * `getConversation(id).name` read `undefined` on every call, which\n * silently disabled any host logic driven by group state — group titles,\n * rosters, avatars and roles carried in the GroupContext all appeared\n * absent, so a group would materialise unnamed until a best-effort\n * broadcast happened to arrive.\n *\n * A getter rather than a snapshot, so it reflects the cache at read time\n * and never goes stale against a later `listConversations()`.\n */\n get name(): string | undefined {\n return self.metaCache.get(hex(id))?.name ?? undefined;\n },\n /** The conversation's current MLS epoch, or `undefined` when the meta\n * cache has not been primed. */\n get epoch(): number | undefined {\n return self.metaCache.get(hex(id))?.epoch;\n },\n meta() {\n const cached = self.metaCache.get(hex(id));\n if (!cached) throw new Error(\"conversation meta not loaded; call listConversations() first\");\n return cached;\n },\n };\n }\n\n private call(req: Request): Promise<unknown> {\n if (this.closed) return Promise.reject(new MessagingClientClosedError(\"closed\"));\n return new Promise((resolve, reject) => {\n this.pending.set((req as { id: number }).id, { resolve, reject });\n this.worker.postMessage(req);\n });\n }\n\n /** Dispatch a worker-side transport proxy call onto the host transport.\n * `sendBatch` is the one method the worker proxy always declares but a\n * host may not implement: emulate it with sequential sends and report a\n * partial delivery with the sentinel the wasm bridge maps to\n * `TransportPartial`, so the SDK still learns the Commit landed while the\n * Welcome did not (and surfaces `WelcomeUndelivered`). The two\n * sequenced-log methods cross in the wasm's wire shape and are converted\n * to the public shape here, both ways; the worker only asks for them when\n * the host declared them at `init`. */\n private async callTransportMethod(method: string, args: unknown[]): Promise<unknown> {\n const t = this.transport as unknown as Record<string, ((...a: unknown[]) => unknown) | undefined>;\n if (method === \"sendBatch\" && typeof t.sendBatch !== \"function\") {\n await emulateSendBatch(this.transport, (args[0] ?? []) as MessageEnvelope[]);\n return undefined;\n }\n if (method === \"fetchLogSince\") {\n if (typeof this.transport.fetchLogSince !== \"function\") return null;\n const [position, limit] = args as [LogPositionWire, number];\n const rows = await this.transport.fetchLogSince(logPositionFromWire(position), limit);\n return rows === null || rows === undefined ? null : rows.map(sequencedToWire);\n }\n if (method === \"fetchLogHeads\") {\n if (typeof this.transport.fetchLogHeads !== \"function\") return null;\n const heads = await this.transport.fetchLogHeads();\n return heads === null || heads === undefined ? null : heads.map(logHeadToWire);\n }\n return await t[method]?.(...args);\n }\n\n private async handleWorker(msg: Response) {\n switch (msg.kind) {\n case \"result\": {\n const slot = this.pending.get(msg.id);\n if (!slot) return;\n this.pending.delete(msg.id);\n msg.ok ? slot.resolve(msg.value) : slot.reject(errorFromWorker(msg.error));\n return;\n }\n case \"event.message\": {\n this.fanout.deliverOne(msg.msg);\n return;\n }\n case \"event.batch\": {\n this.fanout.deliverBatch(msg.messages, { source: msg.source });\n return;\n }\n case \"event.conversation\": {\n // Guarded like the message handlers: one throwing handler must not\n // starve the handlers registered after it.\n for (const h of this.conversationHandlers) {\n try {\n h(msg.id, msg.epoch, msg.sender);\n } catch (e) {\n if (typeof console !== \"undefined\") {\n console.debug(\"[ping-sdk] onConversationUpdated handler threw:\", errorKind(e));\n }\n }\n }\n return;\n }\n case \"storage.call\": {\n try {\n // A method the host storage does not have is an ERROR, never an\n // `undefined` success: the worker only calls the optional methods\n // it was told exist, so a miss means the advertised features and\n // this storage disagree, and answering `undefined` would turn a\n // skipped `applyBatch` into an acknowledged write.\n const method = (this.storage as unknown as Record<string, unknown>)[msg.method];\n if (typeof method !== \"function\") {\n throw new Error(`storage.${String(msg.method)} is not implemented by the host storage`);\n }\n const v = await (method as (...a: unknown[]) => unknown).apply(this.storage, msg.args);\n this.worker.postMessage({ kind: \"storage.reply\", id: msg.id, ok: true, value: v } as Request);\n } catch (e) {\n this.worker.postMessage({\n kind: \"storage.reply\", id: msg.id, ok: false, error: String(e),\n } as Request);\n }\n return;\n }\n case \"transport.call\": {\n try {\n const v = await this.callTransportMethod(msg.method, msg.args);\n this.worker.postMessage({ kind: \"transport.reply\", id: msg.id, ok: true, value: v } as Request);\n } catch (e) {\n this.worker.postMessage({\n kind: \"transport.reply\", id: msg.id, ok: false, error: describeTransportError(e),\n } as Request);\n }\n return;\n }\n }\n }\n}\n\n/** A stateless SDK call ran on a one-shot worker that failed before it could answer:\n * the worker could not be created (`spawn`), the request could not be posted (`post`),\n * the worker script failed to load, import or run (`error`), or its reply could not be\n * deserialised (`messageerror`). The worker has already been terminated; the event's\n * details (which may name a script URL) are not carried. */\nexport class EphemeralWorkerError extends Error {\n readonly reason: \"spawn\" | \"post\" | \"error\" | \"messageerror\";\n constructor(reason: \"spawn\" | \"post\" | \"error\" | \"messageerror\") {\n super(`ping-openmls-sdk: one-shot worker failed (${reason})`);\n this.name = \"EphemeralWorkerError\";\n this.reason = reason;\n }\n}\n\n/**\n * The typed rejection every call still pending gets when the client is\n * closed (`reason: \"closed\"`) or the worker reported an uncaught error\n * (`reason: \"worker-error\"`), and what every call made after `close()`\n * rejects with. Before this, `close()` terminated the worker and left those\n * promises pending forever.\n */\nexport class MessagingClientClosedError extends Error {\n readonly reason: \"closed\" | \"worker-error\";\n constructor(reason: \"closed\" | \"worker-error\") {\n super(reason === \"closed\" ? \"MessagingClient is closed\" : \"MessagingClient worker error\");\n this.name = \"MessagingClientClosedError\";\n this.reason = reason;\n }\n}\n\n/** Sentinel prefix for an emulated batch that only partially landed. Kept in\n * lockstep with `core/ping-wasm/src/lib.rs` (`BATCH_PARTIAL_PREFIX`). */\n/** Width of an X-Wing (post-quantum HPKE) public key, `hpkeGenerateKeypairPq().publicKey`. */\nexport const HPKE_PQ_PUBLIC_KEY_BYTES = 1216;\n/** Width of the KEM encapsulation at the front of a post-quantum raw envelope. */\nexport const HPKE_PQ_ENC_BYTES = 1120;\n\nexport const BATCH_PARTIAL_PREFIX = \"batch partial after \";\n\n/** How the rejection of a call reads when the conversation's roles do not\n * permit it (the core's `Error::NotPermitted`): this prefix, then the rule\n * that was broken (fixed text, no id, safe to log). No other failure starts\n * this way (a malformed request reads `invalid input: ...`). Kept in\n * lockstep with the core's display (`stringify` in\n * `core/ping-wasm/src/lib.rs`, pinned by `ping-core/tests/typed_errors.rs`). */\nexport const NOT_PERMITTED_PREFIX = \"not permitted: \";\n\n/** The typed role refusal: what a `MessagingClient` call rejects with when\n * the encrypted group's roles do not permit it. Raised before anything was\n * built or sent, and final until the roles or the membership change: drop\n * the intent (never retry or queue it), read `conversationPolicy()` again.\n * A join from a Welcome and `importStateSnapshot` reject with it too, for a\n * state that names an owner or an admin without a verified leaf: drop that\n * invitation, or skip that conversation of the import. `message` stays the\n * core's text, so `isNotPermittedError` also reads a copy that lost its\n * class (a structured clone, another realm). */\nexport class NotPermittedError extends Error {\n /** The rule that was broken: fixed text, no id, safe to log. */\n readonly rule: string;\n constructor(message: string) {\n super(message);\n this.name = \"NotPermittedError\";\n this.rule = message.startsWith(NOT_PERMITTED_PREFIX)\n ? message.slice(NOT_PERMITTED_PREFIX.length)\n : message;\n }\n}\n\n/** The rule a role refusal names, or `null` when `e` is any other failure.\n * Accepts the rejection itself, any object with a `message`, or the text. */\nexport function notPermittedRule(e: unknown): string | null {\n const text = typeof e === \"string\"\n ? e\n : e !== null && typeof e === \"object\" && typeof (e as { message?: unknown }).message === \"string\"\n ? (e as { message: string }).message\n : null;\n return text !== null && text.startsWith(NOT_PERMITTED_PREFIX)\n ? text.slice(NOT_PERMITTED_PREFIX.length)\n : null;\n}\n\n/** True when `e` is the typed role refusal (\"the encrypted group's roles do\n * not permit this\") and no other failure. */\nexport function isNotPermittedError(e: unknown): boolean {\n return notPermittedRule(e) !== null;\n}\n\n/** How the rejection of a call reads when an envelope names a sender device\n * other than the one that sealed its MLS message (the core's\n * `Error::SenderMismatch`). No other failure starts this way. Kept in\n * lockstep with the core's display (`stringify` in\n * `core/ping-wasm/src/lib.rs`, pinned by `ping-core/tests/typed_errors.rs`). */\nexport const SENDER_MISMATCH_PREFIX = \"sender mismatch: \";\n\n/** The typed refusal of an envelope whose `senderDevice` is not the device\n * that sealed its message (checked after decryption against the sender\n * leaf's signature key). The message was not delivered, a Commit in it was\n * not applied, and no dedupe or ordering mark moved: the named device's own\n * messages are delivered as before. Drop the envelope, never retry it, show\n * nothing. `message` stays the core's text, so `isSenderMismatchError` also\n * reads a copy that lost its class. */\nexport class SenderMismatchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SenderMismatchError\";\n }\n}\n\n/** True when `e` is the typed sender refusal and no other failure. Accepts\n * the rejection itself, any object with a `message`, or the text. */\nexport function isSenderMismatchError(e: unknown): boolean {\n const text = typeof e === \"string\"\n ? e\n : e !== null && typeof e === \"object\" && typeof (e as { message?: unknown }).message === \"string\"\n ? (e as { message: string }).message\n : null;\n return text !== null && text.startsWith(SENDER_MISMATCH_PREFIX);\n}\n\n/** A worker's rejection text as the error a caller catches: the typed role\n * refusal or the typed sender refusal when it is one, a plain `Error`\n * otherwise. */\nfunction errorFromWorker(text: string): Error {\n if (text.startsWith(NOT_PERMITTED_PREFIX)) return new NotPermittedError(text);\n if (text.startsWith(SENDER_MISMATCH_PREFIX)) return new SenderMismatchError(text);\n return new Error(text);\n}\n\n/** Sequential stand-in for a host transport without `sendBatch`: sends in\n * order and reports a failure after at least one success with the partial\n * sentinel, so the SDK learns the Commit landed while the Welcome did not. */\nexport async function emulateSendBatch(\n transport: Pick<Transport, \"send\">,\n envelopes: MessageEnvelope[],\n): Promise<void> {\n let delivered = 0;\n for (const envelope of envelopes) {\n try {\n await transport.send(envelope);\n } catch (e) {\n if (delivered === 0) throw e;\n throw new Error(`${BATCH_PARTIAL_PREFIX}${delivered}: ${describeTransportError(e)}`);\n }\n delivered += 1;\n }\n}\n\n/** Serialise a transport rejection for the worker so the wasm bridge can\n * still classify it: the HTTP status survives as `http <status>` in the\n * text (a definite 4xx lets the SDK roll a staged Commit back), and any\n * server error code rides along for diagnostics. */\nexport function describeTransportError(e: unknown): string {\n if (e && typeof e === \"object\") {\n const rec = e as { status?: unknown; serverError?: unknown; message?: unknown; name?: unknown };\n const status = typeof rec.status === \"number\" ? rec.status : undefined;\n const message = typeof rec.message === \"string\" ? rec.message : String(e);\n if (message.startsWith(BATCH_PARTIAL_PREFIX)) return message;\n const parts: string[] = [];\n if (typeof rec.name === \"string\" && rec.name) parts.push(`${rec.name}:`);\n parts.push(message);\n if (status !== undefined && !message.includes(`http ${status}`)) parts.push(`(http ${status})`);\n if (typeof rec.serverError === \"string\" && rec.serverError) parts.push(`[${rec.serverError}]`);\n return parts.join(\" \");\n }\n return String(e);\n}\n\nfunction hex(b: Uint8Array): string {\n let s = \"\";\n for (const v of b) s += v.toString(16).padStart(2, \"0\");\n return s;\n}\n\n/**\n * Lowercase-hex of an id, used as a Map key. Conversation ids are 16 bytes, so\n * this is a fixed 32-char string — cheap enough to compute on every inbound\n * frame, and it gives the per-conversation dispatch chain a stable key that\n * `Uint8Array` identity cannot (two decodes of the same id are different\n * objects).\n */\nfunction hexOf(bytes: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < bytes.length; i++) out += bytes[i]!.toString(16).padStart(2, \"0\");\n return out;\n}\n\nfunction sameBytesU8(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n}\n"],"mappings":";AAuBO,SAAS,UAAU,GAAoB;AAC5C,MAAI,aAAa,MAAO,QAAO,EAAE;AACjC,SAAO,OAAO;AAChB;AAEO,IAAM,gBAAN,MAAoB;AAAA,EACR,kBAAkB,oBAAI,IAAoB;AAAA,EAC1C,gBAAgB,oBAAI,IAAkB;AAAA,EAEvD,UAAU,SAAqC;AAC7C,SAAK,gBAAgB,IAAI,OAAO;AAChC,WAAO,MAAM,KAAK,gBAAgB,OAAO,OAAO;AAAA,EAClD;AAAA,EAEA,eAAe,SAAmC;AAChD,SAAK,cAAc,IAAI,OAAO;AAC9B,WAAO,MAAM,KAAK,cAAc,OAAO,OAAO;AAAA,EAChD;AAAA,EAEA,IAAI,mBAA4B;AAC9B,WAAO,KAAK,cAAc,OAAO;AAAA,EACnC;AAAA;AAAA,EAGA,WAAW,GAA0B;AACnC,eAAW,KAAK,KAAK,iBAAiB;AACpC,UAAI;AACF,UAAE,CAAC;AAAA,MACL,SAAS,GAAG;AACV,YAAI,OAAO,YAAY,aAAa;AAClC,kBAAQ,MAAM,uCAAuC,UAAU,CAAC,CAAC;AAAA,QACnE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAa,UAA6B,MAA8B;AACtE,QAAI,SAAS,WAAW,EAAG;AAC3B,QAAI,KAAK,cAAc,SAAS,GAAG;AACjC,iBAAW,KAAK,SAAU,MAAK,WAAW,CAAC;AAC3C;AAAA,IACF;AACA,eAAW,KAAK,KAAK,eAAe;AAClC,UAAI;AACF,UAAE,UAAU,IAAI;AAAA,MAClB,SAAS,GAAG;AACV,YAAI,OAAO,YAAY,aAAa;AAClC,kBAAQ,MAAM,4C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IAAI,WAAW,GAAG;AAC7F,WAAO,MAAM,KAAK,GAAG;AAAA,EACvB;AACA,SAAO,OAAO,CAAC;AACjB;AAEA,SAAS,IAAI,GAAuB;AAClC,MAAI,IAAI;AACR,aAAW,KAAK,EAAG,MAAK,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AACtD,SAAO;AACT;AASA,SAAS,MAAM,OAA2B;AACxC,MAAI,MAAM;AACV,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,IAAK,QAAO,MAAM,CAAC,EAAG,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AACpF,SAAO;AACT;AAEA,SAAS,YAAY,GAAe,GAAwB;AAC1D,MAAI,EAAE,WAAW,EAAE,OAAQ,QAAO;AAClC,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,IAAK,KAAI,EAAE,CAAC,MAAM,EAAE,CAAC,EAAG,QAAO;AAC7D,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/fanout.ts","../src/gap-fill.ts","../src/inbound-coalescer.ts","../src/storage/scope.ts","../src/sequenced.ts","../src/storage/indexeddb.ts","../src/wire-contract.ts","../src/transport/websocket.ts","../src/wasm-memory.ts","../src/notification-preview.ts","../src/index.ts"],"sourcesContent":["// Delivery of decrypted messages to host handlers.\n//\n// Two subscriptions: `onMessage` (one call per message, the surface every\n// host has used so far) and `onMessageBatch` (one call per batch or page\n// result, so a host persists the whole batch in one store transaction). When\n// at least one batch handler is registered, batch and page results go ONLY\n// to the batch handlers; otherwise they are fanned out per message to the\n// `onMessage` handlers, so an existing host keeps working unchanged. The\n// legacy per-envelope path always delivers per message.\n//\n// Every handler call is guarded: a throwing handler used to abort the loop\n// and starve every handler registered after it. The log line carries the\n// error's kind only (never its message, which a handler could have built\n// from plaintext).\n//\n// Lives outside `index.ts` so it is testable without a Worker.\n\nimport type { IncomingMessage, MessageBatchMeta } from \"./types\";\n\nexport type MessageHandler = (m: IncomingMessage) => void;\nexport type BatchHandler = (messages: IncomingMessage[], meta: MessageBatchMeta) => void;\n\n/** The error's kind for a log line: its name, never its message. */\nexport function errorKind(e: unknown): string {\n if (e instanceof Error) return e.name;\n return typeof e;\n}\n\nexport class MessageFanout {\n private readonly messageHandlers = new Set<MessageHandler>();\n private readonly batchHandlers = new Set<BatchHandler>();\n\n onMessage(handler: MessageHandler): () => void {\n this.messageHandlers.add(handler);\n return () => this.messageHandlers.delete(handler);\n }\n\n onMessageBatch(handler: BatchHandler): () => void {\n this.batchHandlers.add(handler);\n return () => this.batchHandlers.delete(handler);\n }\n\n get hasBatchHandlers(): boolean {\n return this.batchHandlers.size > 0;\n }\n\n /** One message from the legacy per-envelope path. */\n deliverOne(m: IncomingMessage): void {\n for (const h of this.messageHandlers) {\n try {\n h(m);\n } catch (e) {\n if (typeof console !== \"undefined\") {\n console.debug(\"[ping-sdk] onMessage handler threw:\", errorKind(e));\n }\n }\n }\n }\n\n /**\n * One batch or page result. An empty result is not delivered: there is\n * nothing to persist, and the caller already has the result value.\n */\n deliverBatch(messages: IncomingMessage[], meta: MessageBatchMeta): void {\n if (messages.length === 0) return;\n if (this.batchHandlers.size === 0) {\n for (const m of messages) this.deliverOne(m);\n return;\n }\n for (const h of this.batchHandlers) {\n try {\n h(messages, meta);\n } catch (e) {\n if (typeof console !== \"undefined\") {\n console.debug(\"[ping-sdk] onMessageBatch handler threw:\", errorKind(e));\n }\n }\n }\n }\n}\n","// Single-flight gap filling: one loop of `syncConversationStep` per\n// conversation, run until the server reports no more rows.\n//\n// A gap is a hole between what this device has applied and a live frame the\n// SDK holds; it is resolved only against the server log, one page at a time.\n// Two callers asking for the same conversation share one loop. A request\n// that lands while a loop is already running is remembered (`again`), and\n// the loop runs once more after it finishes: the running loop may have\n// fetched its last page before the frame that reported the new gap was\n// appended, so ending on that page alone could leave the hole open until the\n// next batch happened to report it.\n//\n// Lives outside `index.ts` so it is testable without a Worker.\n\ninterface Lane {\n run: Promise<void>;\n again: boolean;\n}\n\nexport class GapFiller {\n private readonly lanes = new Map<string, Lane>();\n\n /**\n * Fill the gap for `key`. `stepOnce` applies ONE page and resolves `true`\n * while the server may hold more. Resolves when the loop (and any rerun a\n * concurrent request asked for) has finished; rejects with the first step\n * error, which ends that loop.\n */\n fill(key: string, stepOnce: () => Promise<boolean>): Promise<void> {\n const running = this.lanes.get(key);\n if (running !== undefined) {\n running.again = true;\n return running.run;\n }\n const lane: Lane = { run: Promise.resolve(), again: false };\n lane.run = (async () => {\n try {\n do {\n lane.again = false;\n let more = true;\n while (more) more = await stepOnce();\n } while (lane.again);\n } finally {\n if (this.lanes.get(key) === lane) this.lanes.delete(key);\n }\n })();\n this.lanes.set(key, lane);\n return lane.run;\n }\n\n /** Conversations with a fill loop running (diagnostics / tests). */\n get inFlight(): number {\n return this.lanes.size;\n }\n}\n","// Per-conversation batching of sequenced live frames.\n//\n// The first frame for a conversation is applied at once, as a batch of one.\n// Frames that arrive while that batch is in flight accumulate and go out as\n// ONE batch the moment it returns; no timer ever holds a frame back. The\n// core orders frames by their server position, so what this buys is not\n// ordering but cost: one MLS checkpoint and one host transaction per burst\n// instead of one per frame (see docs/SYNC_PROTOCOL.md \"Sequenced log sync\",\n// cost model).\n//\n// Lanes are keyed by conversation, so a busy group can never head-of-line\n// block another conversation, and an entry lives only while that\n// conversation has work in flight: it is removed the moment the last batch\n// settles with nothing queued, the same bound `dispatchIncoming` keeps for\n// its legacy chains.\n//\n// Lives outside `index.ts` so it is testable without a Worker.\n\nexport type BatchApplier<T> = (key: string, items: T[]) => Promise<void>;\n\ninterface Settler {\n resolve(): void;\n reject(error: unknown): void;\n}\n\ninterface Lane<T> {\n queued: T[];\n waiters: Settler[];\n}\n\nexport class InboundCoalescer<T> {\n private readonly lanes = new Map<string, Lane<T>>();\n\n /**\n * @param apply Applies one batch. A rejection settles the promises of the\n * frames in that batch with the error and the lane moves on to whatever\n * queued meanwhile, so one bad batch cannot wedge a conversation.\n * @param maxBatch Upper bound on frames per batch. A burst larger than\n * this goes out as consecutive batches of at most `maxBatch`, so a\n * flood cannot turn into one unbounded wasm call.\n */\n constructor(\n private readonly apply: BatchApplier<T>,\n private readonly maxBatch = 256,\n ) {}\n\n /**\n * Queue a frame. Resolves when the batch that carried it has been applied\n * (rejects if that batch failed), so a transport that awaits the dispatch\n * to ack a watermark still sees the truth.\n */\n push(key: string, item: T): Promise<void> {\n const lane = this.lanes.get(key);\n if (lane !== undefined) {\n return new Promise<void>((resolve, reject) => {\n lane.queued.push(item);\n lane.waiters.push({ resolve, reject });\n });\n }\n const fresh: Lane<T> = { queued: [], waiters: [] };\n this.lanes.set(key, fresh);\n return this.run(key, fresh, [item], []);\n }\n\n /** Conversations with a batch in flight (diagnostics / tests). */\n get inFlight(): number {\n return this.lanes.size;\n }\n\n private run(key: string, lane: Lane<T>, items: T[], waiters: Settler[]): Promise<void> {\n let attempt: Promise<void>;\n try {\n attempt = this.apply(key, items);\n } catch (e) {\n attempt = Promise.reject(e);\n }\n attempt.then(\n () => {\n for (const w of waiters) w.resolve();\n },\n (e: unknown) => {\n for (const w of waiters) w.reject(e);\n },\n );\n // The next batch, or the cleanup, follows however this one ended.\n void attempt.then(\n () => this.drain(key, lane),\n () => this.drain(key, lane),\n );\n return attempt;\n }\n\n private drain(key: string, lane: Lane<T>): void {\n if (lane.queued.length === 0) {\n // Only the lane that owns the entry clears it; a lane that replaced it\n // (which cannot happen while this one is registered, but the check is\n // what makes that invariant harmless to break) stays.\n if (this.lanes.get(key) === lane) this.lanes.delete(key);\n return;\n }\n const items = lane.queued.splice(0, this.maxBatch);\n const waiters = lane.waiters.splice(0, items.length);\n // Rejections reach the waiters above; nothing else awaits this chain.\n void this.run(key, lane, items, waiters).catch(() => undefined);\n }\n}\n","// Per-account storage scoping, and the optional-method probe that has to agree\n// with it.\n//\n// `MessagingClient` and `openNotificationPreview` both scope through\n// `scopeStorage`, so the tab's writer and the Service Worker's reader can never\n// disagree about which slot a namespace lives in.\n\nimport type { StorageFeatures } from \"../protocol\";\nimport type { Storage } from \"../types\";\n\n/**\n * Wrap a host `Storage` so every namespace carries the per-account scope\n * prefix: `\"${accountNamespace} ${ns}\"`, space separator. Keys and values pass\n * through untouched.\n *\n * The optional batch methods are forwarded exactly when the host has them.\n * That matters because the client tells the wasm which of them exist by\n * probing the storage it will actually call (`storageFeaturesOf`). This\n * wrapper once forwarded only the four basic methods, while the probe looked\n * at the unwrapped host: every scoped account was told `listEntries` existed,\n * the call reached the wrapper, resolved `undefined`, and the store open failed\n * with \"listEntries must resolve to an array\". A dropped `applyBatch` would\n * have been worse, acknowledging writes that never happened.\n */\nexport function scopeStorage(storage: Storage, accountNamespace: string): Storage {\n const scope = (ns: string): string => `${accountNamespace} ${ns}`;\n const scoped: Storage = {\n get: (ns, key) => storage.get(scope(ns), key),\n put: (ns, key, value) => storage.put(scope(ns), key, value),\n del: (ns, key) => storage.del(scope(ns), key),\n listKeys: (ns, prefix) => storage.listKeys(scope(ns), prefix),\n };\n const hostApplyBatch = storage.applyBatch;\n if (typeof hostApplyBatch === \"function\") {\n scoped.applyBatch = (ns, puts, deletes) =>\n hostApplyBatch.call(storage, scope(ns), puts, deletes);\n }\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n scoped.listEntries = (ns, prefix) => hostListEntries.call(storage, scope(ns), prefix);\n }\n return scoped;\n}\n\n/**\n * Which optional methods `storage` really has. Probe the storage the client\n * dispatches to (after any wrapping), never the one the host passed in: the\n * worker hands the wasm a proxy for exactly these, and a method the dispatch\n * target lacks must never be advertised.\n */\nexport function storageFeaturesOf(storage: Storage): StorageFeatures {\n return {\n applyBatch: typeof storage.applyBatch === \"function\",\n listEntries: typeof storage.listEntries === \"function\",\n };\n}\n","// Sequenced log sync: the shapes that cross the wasm boundary and their\n// conversion to the public surface.\n//\n// FIELD CONVENTIONS, DOCUMENTED ONCE. The wasm crate serialises the core's\n// `SequencedEnvelope` / `LogPosition` / `LogHead` / `LogGap` /\n// `ConversationUpdate` / `ApplyBatchResult` / `SyncStepResult` with serde's\n// default snake_case field names, exactly as it already does for\n// `MessageEnvelope` and `IncomingMessage`. Those two older types are exposed\n// on the JS surface UNCHANGED (snake_case), and every message inside a batch\n// or page result keeps that shape: an `IncomingMessage` from\n// `processSequencedBatch` is byte-for-byte the object `onMessage` has always\n// delivered. The NEW wrapper types are exposed in camelCase (`serverSeq`,\n// `hasMore`, `conversationId`), the convention the JS surface uses for the\n// shapes it added after the wire types (`IdentityRotation`,\n// `AdmitChatOutcome`, `KeyPackageEntry`). The converters below are the only\n// place that mapping lives; the worker speaks the wire shape, the main\n// thread speaks the public one.\n//\n// Kept free of worker globals so it is testable under vitest.\n\nimport type {\n AddMemberStatus,\n AddMembersReport,\n ApplyBatchResult,\n BufferOverflow,\n CommitInDoubt,\n ConversationId,\n ConversationRemoval,\n ConversationUpdate,\n IncomingMessage,\n LogGap,\n LogHead,\n LogPosition,\n MessageEnvelope,\n OverflowReason,\n SequencedEnvelope,\n StrandedConversation,\n StrandReason,\n SyncStepResult,\n WelcomeFailure,\n WelcomeFailureReason,\n} from \"./types\";\n\n// ---- Wire shapes (what the wasm emits and accepts) ----\n\nexport interface SequencedEnvelopeWire {\n envelope: MessageEnvelope;\n server_seq: number;\n}\n\nexport interface LogPositionWire {\n conversation_id: Uint8Array;\n epoch: number;\n server_seq: number;\n anchored: boolean;\n}\n\nexport interface LogHeadWire {\n conversation_id: Uint8Array;\n head_server_seq: number;\n head_epoch: number;\n}\n\nexport interface LogGapWire {\n conversation_id: Uint8Array;\n applied_server_seq: number;\n first_buffered_server_seq: number;\n}\n\nexport interface ConversationUpdateWire {\n conversation_id: Uint8Array;\n epoch: number;\n}\n\nexport interface ConversationRemovalWire {\n conversation_id: Uint8Array;\n server_seq: number;\n epoch: number;\n readmitted: boolean;\n}\n\nexport interface WelcomeFailureWire {\n conversation_id: Uint8Array;\n server_seq: number;\n /** serde's variant name: `\"Rejected\"` or `\"Storage\"`. */\n reason: string;\n}\n\nexport interface StrandedConversationWire {\n conversation_id: Uint8Array;\n server_seq: number;\n epoch: number;\n /** `\"NoProgress\"`, `\"AddedKeyPackageExpired\"`, `\"AddedKeyPackageNotYetValid\"`,\n * `\"CredentialInvalid\"`, `\"PolicyDowngrade\"`, `\"NotPermitted\"`. */\n reason: string;\n}\n\nexport interface BufferOverflowWire {\n conversation_id: Uint8Array;\n /** `\"HeldFrames\"` or `\"RetainedFrames\"`. */\n reason: string;\n dropped: number;\n}\n\n// The typed-outcome fields are optional on the wire so a result decoded from\n// an older wasm (or a hand-built test fixture) still converts.\nexport interface ApplyBatchResultWire {\n messages: IncomingMessage[];\n applied: number;\n duplicates: number;\n buffered: number;\n failed: number;\n gaps: LogGapWire[];\n joined: Uint8Array[];\n updated: ConversationUpdateWire[];\n removed?: ConversationRemovalWire[];\n welcome_failures?: WelcomeFailureWire[];\n stranded?: StrandedConversationWire[];\n proposals_pending?: Uint8Array[];\n overflow?: BufferOverflowWire[];\n}\n\nexport interface SyncStepResultWire {\n messages: IncomingMessage[];\n has_more: boolean;\n fetched: number;\n position: LogPositionWire;\n updated: ConversationUpdateWire[];\n joined?: Uint8Array[];\n removed?: ConversationRemovalWire[];\n welcome_failures?: WelcomeFailureWire[];\n stranded?: StrandedConversationWire[];\n proposals_pending?: Uint8Array[];\n overflow?: BufferOverflowWire[];\n}\n\nexport interface AddMemberVerdictWire {\n device_id: Uint8Array;\n /** serde's variant name, e.g. `\"AlreadyMember\"`. */\n status: string;\n leaf_index: number | null | undefined;\n}\n\nexport interface AddMembersReportWire {\n verdicts: AddMemberVerdictWire[];\n epoch: number | null | undefined;\n}\n\nexport interface CommitInDoubtWire {\n conversation_id: Uint8Array;\n attempts: number;\n next_attempt_at_ms: number;\n}\n\n// ---- Frame classification ----\n\n/**\n * Whether a frame the transport handed over carries its server position.\n * A bare `MessageEnvelope` has `conversation_id` at its top level; a\n * `SequencedEnvelope` wraps one under `envelope` next to `serverSeq`.\n */\nexport function isSequencedFrame(\n frame: MessageEnvelope | SequencedEnvelope,\n): frame is SequencedEnvelope {\n return (\n typeof frame === \"object\" &&\n frame !== null &&\n \"envelope\" in frame &&\n typeof (frame as SequencedEnvelope).envelope === \"object\" &&\n (frame as SequencedEnvelope).envelope !== null\n );\n}\n\n// ---- Converters ----\n\nexport function sequencedToWire(item: SequencedEnvelope): SequencedEnvelopeWire {\n return { envelope: item.envelope, server_seq: item.serverSeq };\n}\n\nexport function sequencedFromWire(item: SequencedEnvelopeWire): SequencedEnvelope {\n return { envelope: item.envelope, serverSeq: item.server_seq };\n}\n\nexport function logPositionFromWire(p: LogPositionWire): LogPosition {\n return {\n conversationId: p.conversation_id,\n epoch: p.epoch,\n serverSeq: p.server_seq,\n anchored: p.anchored,\n };\n}\n\nexport function logPositionToWire(p: LogPosition): LogPositionWire {\n return {\n conversation_id: p.conversationId,\n epoch: p.epoch,\n server_seq: p.serverSeq,\n anchored: p.anchored,\n };\n}\n\nexport function logHeadToWire(h: LogHead): LogHeadWire {\n return {\n conversation_id: h.conversationId,\n head_server_seq: h.headServerSeq,\n head_epoch: h.headEpoch,\n };\n}\n\nexport function logHeadFromWire(h: LogHeadWire): LogHead {\n return {\n conversationId: h.conversation_id,\n headServerSeq: h.head_server_seq,\n headEpoch: h.head_epoch,\n };\n}\n\nexport function logGapFromWire(g: LogGapWire): LogGap {\n return {\n conversationId: g.conversation_id,\n appliedServerSeq: g.applied_server_seq,\n firstBufferedServerSeq: g.first_buffered_server_seq,\n };\n}\n\nexport function conversationUpdateFromWire(u: ConversationUpdateWire): ConversationUpdate {\n return { conversationId: u.conversation_id, epoch: u.epoch };\n}\n\n/** serde's `PascalCase` variant name as the JS surface's `camelCase` string. */\nfunction variant<T extends string>(name: string): T {\n return (name.charAt(0).toLowerCase() + name.slice(1)) as T;\n}\n\nexport function conversationRemovalFromWire(r: ConversationRemovalWire): ConversationRemoval {\n return {\n conversationId: r.conversation_id,\n serverSeq: r.server_seq,\n epoch: r.epoch,\n readmitted: r.readmitted,\n };\n}\n\nexport function welcomeFailureFromWire(w: WelcomeFailureWire): WelcomeFailure {\n return {\n conversationId: w.conversation_id,\n serverSeq: w.server_seq,\n reason: variant<WelcomeFailureReason>(w.reason),\n };\n}\n\nexport function strandedConversationFromWire(s: StrandedConversationWire): StrandedConversation {\n return {\n conversationId: s.conversation_id,\n serverSeq: s.server_seq,\n epoch: s.epoch,\n reason: variant<StrandReason>(s.reason),\n };\n}\n\nexport function bufferOverflowFromWire(o: BufferOverflowWire): BufferOverflow {\n return {\n conversationId: o.conversation_id,\n reason: variant<OverflowReason>(o.reason),\n dropped: o.dropped,\n };\n}\n\n/** The typed outcomes a batch and a page share. */\nfunction outcomesFromWire(r: {\n removed?: ConversationRemovalWire[];\n welcome_failures?: WelcomeFailureWire[];\n stranded?: StrandedConversationWire[];\n proposals_pending?: ConversationId[];\n overflow?: BufferOverflowWire[];\n}): Pick<ApplyBatchResult, \"removed\" | \"welcomeFailures\" | \"stranded\" | \"proposalsPending\" | \"overflow\"> {\n return {\n removed: (r.removed ?? []).map(conversationRemovalFromWire),\n welcomeFailures: (r.welcome_failures ?? []).map(welcomeFailureFromWire),\n stranded: (r.stranded ?? []).map(strandedConversationFromWire),\n proposalsPending: r.proposals_pending ?? [],\n overflow: (r.overflow ?? []).map(bufferOverflowFromWire),\n };\n}\n\nexport function applyBatchResultFromWire(r: ApplyBatchResultWire): ApplyBatchResult {\n return {\n messages: r.messages,\n applied: r.applied,\n duplicates: r.duplicates,\n buffered: r.buffered,\n failed: r.failed,\n gaps: r.gaps.map(logGapFromWire),\n joined: r.joined,\n updated: r.updated.map(conversationUpdateFromWire),\n ...outcomesFromWire(r),\n };\n}\n\nexport function syncStepResultFromWire(r: SyncStepResultWire): SyncStepResult {\n return {\n messages: r.messages,\n hasMore: r.has_more,\n fetched: r.fetched,\n position: logPositionFromWire(r.position),\n updated: r.updated.map(conversationUpdateFromWire),\n joined: r.joined ?? [],\n ...outcomesFromWire(r),\n };\n}\n\nexport function addMembersReportFromWire(r: AddMembersReportWire): AddMembersReport {\n return {\n verdicts: r.verdicts.map((v) => ({\n deviceId: v.device_id,\n status: variant<AddMemberStatus>(v.status),\n leafIndex: v.leaf_index ?? null,\n })),\n epoch: r.epoch ?? null,\n };\n}\n\nexport function commitInDoubtFromWire(c: CommitInDoubtWire): CommitInDoubt {\n return {\n conversationId: c.conversation_id,\n attempts: c.attempts,\n nextAttemptAtMs: c.next_attempt_at_ms,\n };\n}\n","// Default IndexedDB-backed Storage implementation. Hosts can supply their own.\n\nimport type { Storage } from \"../types\";\n\nconst DB_NAME = \"ping-sdk\";\nconst DB_VERSION = 1;\nconst STORE = \"kv\";\n\ninterface Row { ns: string; key: string; value: Uint8Array }\n\nfunction open(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.open(DB_NAME, DB_VERSION);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(STORE)) {\n const os = db.createObjectStore(STORE, { keyPath: [\"ns\", \"key\"] });\n os.createIndex(\"ns\", \"ns\", { unique: false });\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n}\n\nexport class IndexedDbStorage implements Storage {\n private dbPromise: Promise<IDBDatabase>;\n\n constructor() { this.dbPromise = open(); }\n\n async get(namespace: string, key: string): Promise<Uint8Array | null> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const r = tx.objectStore(STORE).get([namespace, key]);\n r.onsuccess = () => resolve(((r.result as Row | undefined)?.value) ?? null);\n r.onerror = () => reject(r.error);\n });\n }\n\n async put(namespace: string, key: string, value: Uint8Array): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).put({ ns: namespace, key, value } as Row);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n async del(namespace: string, key: string): Promise<void> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete([namespace, key]);\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n }\n\n /**\n * One `readwrite` transaction for the whole batch. Every request is issued\n * synchronously inside it (an await on anything else would let the\n * transaction auto-commit), so a failure or a crash mid-way aborts all of\n * it: the per-row MLS store relies on that to keep a checkpoint atomic.\n */\n async applyBatch(\n namespace: string,\n puts: Array<[key: string, value: Uint8Array]>,\n deletes: string[],\n ): Promise<void> {\n if (puts.length === 0 && deletes.length === 0) return;\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readwrite\");\n let settled = false;\n const fail = (e: unknown) => {\n if (settled) return;\n settled = true;\n reject(e instanceof Error ? e : new Error(String(e)));\n };\n tx.oncomplete = () => {\n if (!settled) {\n settled = true;\n resolve();\n }\n };\n tx.onerror = () => fail(tx.error);\n tx.onabort = () => fail(tx.error ?? new Error(\"applyBatch aborted\"));\n try {\n const os = tx.objectStore(STORE);\n for (const [key, value] of puts) os.put({ ns: namespace, key, value } as Row);\n for (const key of deletes) os.delete([namespace, key]);\n } catch (e) {\n // A request that throws synchronously (an unserialisable key) does\n // not abort the transaction on its own; the requests already issued\n // would commit. Abort explicitly so the batch stays all-or-nothing.\n try {\n tx.abort();\n } catch {\n // Already aborted or finished.\n }\n fail(e);\n }\n });\n }\n\n /** Every `[key, value]` under `namespace` with the prefix, in one read. */\n async listEntries(\n namespace: string,\n prefix: string,\n ): Promise<Array<[key: string, value: Uint8Array]>> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: Array<[string, Uint8Array]> = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.startsWith(prefix)) out.push([row.key, row.value]);\n cur.continue();\n };\n req.onerror = () => reject(req.error);\n });\n }\n\n async listKeys(namespace: string, prefix: string): Promise<string[]> {\n const db = await this.dbPromise;\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE, \"readonly\");\n const idx = tx.objectStore(STORE).index(\"ns\");\n const req = idx.openCursor(IDBKeyRange.only(namespace));\n const out: string[] = [];\n req.onsuccess = () => {\n const cur = req.result;\n if (!cur) return resolve(out);\n const row = cur.value as Row;\n if (!prefix || row.key.startsWith(prefix)) out.push(row.key);\n cur.continue();\n };\n req.onerror = () => reject(req.error);\n });\n }\n}\n","// Ping wire contract — TypeScript counterpart to the `ping-wire-contract` Rust crate.\n//\n// MUST stay in lockstep with `core/ping-wire-contract/src/lib.rs`. The full normative spec\n// lives in `docs/PING_WIRE_CONTRACT.md`.\n//\n// What this module is for: code paths that cross the network boundary (transports, relays,\n// service workers) that need to advertise or validate ping-wire-contract conformance from\n// JavaScript without round-tripping through WASM.\n\nimport type { MessageEnvelope } from \"./types\";\n\n/**\n * Ping wire contract version. Bumped on incompatible profile changes.\n *\n * Currently `2` — CR-6 changes the `content_hash` semantics for `Application` envelopes\n * (now hashed over plaintext, not the MLS ciphertext). Receivers run a 90-day dual-accept\n * window per Q-ARCH-02; see [[validate]] for the per-version routing.\n */\nexport const PING_WIRE_CONTRACT_VERSION = 2;\n\n/** Lowest envelope version accepted by [[validate]] during the dual-accept window. */\nexport const WIRE_VERSION_MIN_ACCEPTED = 1;\n\n/** Canonical CBOR content type. Production transports SHOULD use this. */\nexport const CONTENT_TYPE_CBOR = \"application/vnd.ping.wire.v2+cbor\";\n\n/** JSON projection — development and tooling only. Production MUST NOT use this. */\nexport const CONTENT_TYPE_JSON = \"application/vnd.ping.wire.v2+json\";\n\n/** Legacy v1 CBOR type, accepted during the CR-6 dual-accept window. */\nexport const CONTENT_TYPE_CBOR_LEGACY_V1 = \"application/vnd.ping.wire.v1+cbor\";\n\n/** Legacy v1 JSON type, accepted during the CR-6 dual-accept window. */\nexport const CONTENT_TYPE_JSON_LEGACY_V1 = \"application/vnd.ping.wire.v1+json\";\n\n/** Header used over transports that don't surface a content type (e.g. WebSocket). */\nexport const PING_WIRE_CONTRACT_HEADER = \"X-Ping-Wire-Contract\";\n\n/** Header value: `ping/<VERSION>`. */\nexport const PING_WIRE_CONTRACT_HEADER_VALUE = `ping/${PING_WIRE_CONTRACT_VERSION}`;\n\nexport type ValidationErrorKind =\n | \"UnsupportedVersion\"\n | \"BadConversationIdLen\"\n | \"BadSenderDeviceLen\"\n | \"ContentHashMismatch\";\n\nexport class ValidationError extends Error {\n constructor(public readonly kind: ValidationErrorKind, message: string) {\n super(message);\n this.name = \"PingWireContractValidationError\";\n }\n}\n\nconst KIND_DISCRIMINANT: Record<MessageEnvelope[\"kind\"], number> = {\n Application: 1,\n Commit: 2,\n Welcome: 3,\n Proposal: 4,\n KeyPackage: 5,\n};\n\nasync function sha256(bytes: Uint8Array): Promise<Uint8Array> {\n // `crypto.subtle` is available in browsers, Node 20+, and Workers. `bytes.buffer`\n // is typed as `ArrayBufferLike` which TS won't accept as `BufferSource` (the union\n // includes `SharedArrayBuffer`); pass an explicit ArrayBuffer slice instead.\n const ab = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;\n const hash = await crypto.subtle.digest(\"SHA-256\", ab);\n return new Uint8Array(hash);\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n}\n\n/**\n * Validate an envelope against the ping-wire-contract.\n *\n * Receivers claiming contract conformance MUST call this before applying any envelope.\n * External consumers using the raw envelope under their own profile are not bound by\n * these rules.\n *\n * CR-6 dual-accept window: `v ∈ [WIRE_VERSION_MIN_ACCEPTED, PING_WIRE_CONTRACT_VERSION]`\n * passes the version gate. For v=2 `Application` envelopes the content_hash is over\n * plaintext, so this function skips that check — callers MUST run\n * [[verifyApplicationContentHash]] after MLS decrypt to close the loop.\n */\nexport async function validate(env: MessageEnvelope): Promise<void> {\n if (env.v < WIRE_VERSION_MIN_ACCEPTED || env.v > PING_WIRE_CONTRACT_VERSION) {\n throw new ValidationError(\n \"UnsupportedVersion\",\n `unsupported wire-contract version: envelope says v=${env.v}, expected v∈[${WIRE_VERSION_MIN_ACCEPTED}, ${PING_WIRE_CONTRACT_VERSION}]`,\n );\n }\n if (env.conversation_id.length !== 16) {\n throw new ValidationError(\n \"BadConversationIdLen\",\n `conversation_id must be 16 bytes (ULID), got ${env.conversation_id.length}`,\n );\n }\n if (env.sender_device.length !== 32) {\n throw new ValidationError(\n \"BadSenderDeviceLen\",\n `sender_device must be 32 bytes, got ${env.sender_device.length}`,\n );\n }\n // CR-6 routing: skip the hash check for v=2 application envelopes.\n if (env.v >= 2 && env.kind === \"Application\") {\n return;\n }\n const buf = new Uint8Array(1 + env.payload.length);\n buf[0] = KIND_DISCRIMINANT[env.kind];\n buf.set(env.payload, 1);\n const computed = await sha256(buf);\n if (!bytesEqual(computed, env.content_hash)) {\n throw new ValidationError(\n \"ContentHashMismatch\",\n \"content_hash mismatch: envelope is forged, corrupted, or built by a non-conformant sender\",\n );\n }\n}\n\n/**\n * Verify a v=2 `Application` envelope's content_hash against the decrypted plaintext.\n *\n * Caller MUST run this after MLS decrypt for application envelopes whose `v >= 2`. For\n * v=1 envelopes or handshake kinds this is a no-op (those are covered by [[validate]]).\n */\nexport async function verifyApplicationContentHash(\n env: MessageEnvelope,\n plaintext: Uint8Array,\n): Promise<void> {\n if (env.v < 2 || env.kind !== \"Application\") return;\n const computed = await sha256(plaintext);\n if (!bytesEqual(computed, env.content_hash)) {\n throw new ValidationError(\n \"ContentHashMismatch\",\n \"v=2 application content_hash mismatch against decrypted plaintext\",\n );\n }\n}\n\n/**\n * True if the supplied content type negotiates the ping-wire-contract.\n *\n * Accepts the v2 canonical types AND the v1 legacy types during the CR-6 dual-accept\n * window. Tolerates whitespace and parameters (e.g. `; charset=utf-8`).\n */\nexport function negotiates(contentType: string | null | undefined): boolean {\n if (!contentType) return false;\n const primary = contentType.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n return (\n primary === CONTENT_TYPE_CBOR\n || primary === CONTENT_TYPE_JSON\n || primary === CONTENT_TYPE_CBOR_LEGACY_V1\n || primary === CONTENT_TYPE_JSON_LEGACY_V1\n );\n}\n","// Reference WebSocket transport. Treats the server as an opaque relay that:\n// - accepts a CBOR-encoded MessageEnvelope on `send`\n// - returns events newer than a cursor on `fetchSince`\n// - streams new events on the WS itself for `subscribe`\n// - exposes a directory endpoint for `discoverDevices`\n//\n// This is a sample. Real deployments will tune framing / auth.\n\nimport type { ConversationId, DiscoveredDevice, MessageEnvelope, Transport, UserId } from \"../types\";\nimport {\n CONTENT_TYPE_JSON,\n PING_WIRE_CONTRACT_HEADER,\n PING_WIRE_CONTRACT_HEADER_VALUE,\n} from \"../wire-contract\";\n\nexport interface WsTransportConfig {\n baseUrl: string; // ws[s]://...\n authHeader?: string; // optional bearer token\n fetchImpl?: typeof fetch; // override for SSR / tests\n}\n\nexport class WebSocketTransport implements Transport {\n private ws: WebSocket | null = null;\n private liveHandlers = new Set<(env: MessageEnvelope) => void>();\n private fetchImpl: typeof fetch;\n\n constructor(private cfg: WsTransportConfig) {\n this.fetchImpl = cfg.fetchImpl ?? globalThis.fetch.bind(globalThis);\n this.openSocket();\n }\n\n private openSocket() {\n if (typeof WebSocket === \"undefined\") return;\n const url = `${this.cfg.baseUrl.replace(/^http/, \"ws\")}/stream`;\n this.ws = new WebSocket(url);\n this.ws.onmessage = (ev) => {\n // Server sends one JSON envelope per text frame.\n const text = typeof ev.data === \"string\" ? ev.data : new TextDecoder().decode(ev.data as ArrayBuffer);\n try {\n const env = JSON.parse(text, reviver) as MessageEnvelope;\n for (const h of this.liveHandlers) h(env);\n } catch (e) {\n if (typeof console !== \"undefined\") console.debug(\"[ping-sdk] WS frame parse error:\", e);\n }\n };\n this.ws.onclose = () => setTimeout(() => this.openSocket(), 1000);\n }\n\n async send(envelope: MessageEnvelope): Promise<void> {\n // We're emitting the JSON projection of the ping-wire-contract. Production transports\n // would use CONTENT_TYPE_CBOR with a real CBOR codec; for the demo path the JSON shape\n // is the documented development projection.\n const res = await this.fetchImpl(`${this.cfg.baseUrl}/send`, {\n method: \"POST\",\n headers: {\n \"content-type\": CONTENT_TYPE_JSON,\n [PING_WIRE_CONTRACT_HEADER]: PING_WIRE_CONTRACT_HEADER_VALUE,\n ...(this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {}),\n },\n body: JSON.stringify(envelope, replacer),\n });\n if (res.status === 409) throw new Error(\"EpochOccupied\");\n if (!res.ok) throw new Error(`transport send failed: ${res.status}`);\n }\n\n async fetchSince(conversationId: ConversationId, cursor: Uint8Array, limit: number): Promise<MessageEnvelope[]> {\n const url = new URL(`${this.cfg.baseUrl}/sync`);\n url.searchParams.set(\"conv\", toHex(conversationId));\n url.searchParams.set(\"cursor\", btoaUrl(cursor));\n url.searchParams.set(\"limit\", String(limit));\n const res = await this.fetchImpl(url.toString(), {\n headers: { ...(this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {}) },\n });\n if (!res.ok) throw new Error(`transport fetch failed: ${res.status}`);\n const text = await res.text();\n return JSON.parse(text, reviver) as MessageEnvelope[];\n }\n\n subscribe(onEvent: (env: MessageEnvelope) => void): { unsubscribe(): void } {\n this.liveHandlers.add(onEvent);\n return { unsubscribe: () => this.liveHandlers.delete(onEvent) };\n }\n\n async discoverDevices(userId: UserId): Promise<DiscoveredDevice[]> {\n const res = await this.fetchImpl(`${this.cfg.baseUrl}/devices/${toHex(userId)}`, {\n headers: { ...(this.cfg.authHeader ? { authorization: this.cfg.authHeader } : {}) },\n });\n if (!res.ok) throw new Error(`device discovery failed: ${res.status}`);\n const text = await res.text();\n return JSON.parse(text, reviver) as DiscoveredDevice[];\n }\n}\n\n// ---- Wire codec ----\n//\n// Demo wire format: JSON with byte fields wrapped as `{ _bytes: number[] }`. The relay's\n// `envFromJson`/`envToJson` use the same shape. The spec calls for CBOR; v0.2 swaps in a\n// real CBOR codec, but the JSON form is much friendlier to debug.\n//\n// (decodeEnvelope helpers used to live here; collapsed into inline JSON.parse calls above.)\n\nfunction replacer(_k: string, v: unknown): unknown {\n if (v instanceof Uint8Array) return { _bytes: Array.from(v) };\n return v;\n}\nfunction reviver(_k: string, v: unknown): unknown {\n if (v && typeof v === \"object\" && Array.isArray((v as { _bytes?: number[] })._bytes)) {\n return new Uint8Array((v as { _bytes: number[] })._bytes);\n }\n return v;\n}\n\nfunction toHex(b: Uint8Array): string {\n let s = \"\"; for (const v of b) s += v.toString(16).padStart(2, \"0\"); return s;\n}\nfunction btoaUrl(b: Uint8Array): string {\n let s = \"\"; for (const v of b) s += String.fromCharCode(v);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n","// 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","// [CR-5] Read-only notification preview for the web Service Worker.\n//\n// The web mirror of the iOS Notification Service Extension: a second JS realm\n// (the push-handling Service Worker, woken while the tab may be closed OR open\n// and writing) that must turn one push-delivered envelope into a sender and a\n// body preview, and change NOTHING.\n//\n// This module deliberately does NOT go through the SDK's usual Worker bridge:\n// a Service Worker cannot spawn a dedicated `Worker` on every browser, and a\n// preview needs one decrypt, not a message pipeline. The WASM module is loaded\n// INLINE in the calling realm (no DOM APIs are touched), wrapping the core's\n// `MessagingClient::open_read_only` + `preview_envelope` — the same read-only\n// seam the iOS NSE uses, with the same semantics:\n//\n// * the SDK storage is opened READ-ONLY: the MLS snapshot is copied into\n// memory at open and never written back, so the tab remains the single\n// writer and cannot be disturbed (two writers on the whole-state blob\n// REPLACE each other — see `StorageBackend::AsyncBlobReadOnly`);\n// * the ratchet advance from the preview decrypt is thrown away; the tab\n// decrypts the same message again later, independently. Nothing is\n// consumed that the tab needs, and nothing this session does is\n// observable by the tab;\n// * handshake traffic (Commit/Welcome/Proposal), unknown conversations, and\n// replays the hydrated cursor rejects all resolve to `null` — show the\n// generic banner, it is a normal answer;\n// * a message the tab ALREADY consumed and checkpointed cannot be decrypted\n// from the newer snapshot (its generation is burned): `previewEnvelope`\n// rejects. Treat ANY rejection as \"no preview\" (generic banner), never as\n// fatal.\n//\n// Concurrent-open safety: IndexedDB reads never block the tab's writes and the\n// session takes a point-in-time copy of the `__mls snapshot` blob at open, so\n// opening while a tab is live is safe by construction. The copy can be STALE\n// relative to the tab, which only widens the `null`/reject cases above. Open a\n// fresh session per push event (or per small batch) rather than caching one —\n// a fresh open sees the newest checkpoint.\n//\n// See docs/NOTIFICATION_PREVIEW_WEB.md for the full Service Worker guide\n// (wasm init in module vs classic workers, account-slot storage, ping-prime\n// wiring).\n\nimport { scopeStorage } from \"./storage/scope\";\nimport type { IncomingMessage, MessageEnvelope, Storage } from \"./types\";\nimport { reserveLinearMemory } from \"./wasm-memory\";\n\nexport interface NotificationPreviewOptions {\n /**\n * The account identity export (CBOR-wrapped Ed25519 seed, SECRET) — the\n * same bytes the tab passes to `MessagingClient.init`. The Service Worker\n * host must read it from wherever the tab keeps it (e.g. the encrypted IDB\n * slot); it never crosses the network.\n */\n identityExport: Uint8Array;\n /**\n * The SAME `Storage` implementation (and underlying IndexedDB database)\n * the tab's `MessagingClient` persists to. It is wrapped read-only here:\n * `put`/`del` reject, so a host bug cannot make the Service Worker a\n * second writer.\n */\n storage: Storage;\n /**\n * The tab's `ClientConfig.accountNamespace` for this account slot, when it\n * uses one. MUST match exactly — the preview scopes every namespace with\n * the same `\"${accountNamespace} \"` prefix rule as `MessagingClient`, and a\n * mismatch reads an empty store (open rejects with \"no checkpoint\").\n */\n accountNamespace?: string;\n /**\n * Where to load `ping_wasm_bg.wasm` from, passed through to the\n * wasm-bindgen `init`. Defaults to the URL baked next to the module —\n * correct when the bundler ships the `wasm/` directory alongside. Classic\n * (importScripts) Service Workers, or bundlers that relocate assets, pass\n * an explicit URL here.\n */\n wasmModuleOrPath?: string | URL | WebAssembly.Module;\n /** Override the wall clock (test/sim only). */\n now?: () => number;\n}\n\n/**\n * The most prerequisite envelopes `previewEnvelopeWithPrerequisites` accepts.\n * The envelopes come from the server before anything authenticates them, so\n * the work they can cause is bounded. Mirrors the core's\n * `PREVIEW_PREREQUISITES_MAX`.\n */\nexport const MAX_PREVIEW_PREREQUISITES = 64;\n\nexport interface NotificationPreviewSession {\n /**\n * Decrypt ONE push-delivered envelope for display. Resolves to the\n * decrypted message (sender ids, conversation id, plaintext — everything a\n * banner needs) or `null` when there is nothing to show. Rejects when the\n * snapshot cannot decrypt it (commonly: the tab consumed it first) — treat\n * a rejection exactly like `null` and fall back to the generic banner.\n *\n * The returned message never carries a `journal_id`: a preview decrypt is\n * not journaled (nothing durable happened) and needs no `confirmApplied`.\n */\n previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null>;\n /**\n * Decrypt ONE push-delivered envelope that this device cannot read yet,\n * because the handshake traffic in front of it has not been processed: the\n * first message of a conversation whose Welcome is still pending, or a\n * message sent after a Commit the tab has not applied.\n *\n * `prerequisites` are the envelopes that precede `envelope`, oldest first:\n * the pending Welcome (if any) and the Commits and Proposals after it.\n * They are applied to this session's private in-memory copy and then\n * `envelope` is decrypted. Nothing is persisted, the one-time KeyPackage\n * the Welcome was sealed to stays in the store, and the tab later joins and\n * decrypts for itself as if this call never happened.\n *\n * Envelopes for other conversations are ignored, a Welcome is not applied\n * to a conversation the snapshot already holds and can read, and a\n * prerequisite that does not apply is skipped. At most\n * {@link MAX_PREVIEW_PREREQUISITES} prerequisites; more rejects.\n *\n * Same result contract as `previewEnvelope`: `null` when there is nothing\n * to show, a rejection when the message cannot be decrypted. Treat both as\n * \"no preview\" and fall back to the generic banner.\n *\n * The applied prerequisites stay in the session's memory, so open a fresh\n * session per push event (the module comment already says to).\n */\n previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null>;\n /** Release the WASM instance. The session is unusable afterwards. */\n close(): void;\n}\n\n/**\n * Open the SDK read-only for notification previews, from a Service Worker (or\n * any realm without the SDK's Worker bridge). Rejects when the store holds no\n * checkpoint or no device identity — a Service Worker for an account that\n * never initialised locally has nothing to decrypt with, and \"successfully\n * decrypt nothing\" would be the worst possible answer.\n */\nexport async function openNotificationPreview(\n opts: NotificationPreviewOptions,\n): Promise<NotificationPreviewSession> {\n const now = opts.now ?? (() => Date.now());\n const scoped =\n opts.accountNamespace !== undefined && opts.accountNamespace.length > 0\n ? scopeStorage(opts.storage, opts.accountNamespace)\n : opts.storage;\n const storage = readOnlyStorage(scoped);\n\n // Inline WASM load — the module ships no DOM dependency, so this works in\n // window, worker, and service-worker realms alike. `init` is idempotent per\n // realm (subsequent opens reuse the instantiated module).\n const wasm = await import(\"../wasm/ping_wasm\");\n const out = await wasm.default(\n opts.wasmModuleOrPath === undefined\n ? undefined\n : ({ module_or_path: opts.wasmModuleOrPath } as never),\n );\n // Same Safari mitigation as the worker (`wasm-memory.ts`): grow from JS\n // once so the module never executes `memory.grow` itself. Idempotent.\n reserveLinearMemory(out.memory);\n\n const client = await wasm.PingClient.openReadOnly(\n opts.identityExport,\n // Label is unused on the read-only path (no LocalDevice is ever minted).\n \"notification-preview\",\n storage as never,\n silentTransport() as never,\n now(),\n );\n\n let closed = false;\n return {\n async previewEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n const result = client.previewEnvelope(envelope as never, now());\n return (result ?? null) as IncomingMessage | null;\n },\n async previewEnvelopeWithPrerequisites(\n prerequisites: MessageEnvelope[],\n envelope: MessageEnvelope,\n ): Promise<IncomingMessage | null> {\n if (closed) throw new Error(\"notification-preview session is closed\");\n assertPrerequisiteCount(prerequisites);\n const result = client.previewEnvelopeWithPrerequisites(\n prerequisites as never,\n envelope as never,\n now(),\n );\n return (result ?? null) as IncomingMessage | null;\n },\n close() {\n if (closed) return;\n closed = true;\n client.free();\n },\n };\n}\n\n/**\n * Refuse an oversized prerequisite list before it crosses into WASM. The core\n * enforces the same bound; checking here keeps the copy out of linear memory.\n * Exported for tests.\n */\nexport function assertPrerequisiteCount(prerequisites: readonly unknown[]): void {\n if (!Array.isArray(prerequisites)) {\n throw new Error(\"notification-preview prerequisites must be an array\");\n }\n if (prerequisites.length > MAX_PREVIEW_PREREQUISITES) {\n throw new Error(\n `notification-preview takes at most ${MAX_PREVIEW_PREREQUISITES} prerequisite envelopes`,\n );\n }\n}\n\n/**\n * The per-account scope rule, shared with `MessagingClient` so the preview and\n * the tab's writer always read the same slot. Re-exported for tests.\n */\nexport { scopeStorage };\n\n/**\n * Wrap a host `Storage` so writes REJECT. The Rust side already opens the MLS\n * snapshot through a read-only backend; this guards the host-KV half\n * (`device`, `groups`, `cursors`, …), which the read-only MLS backend cannot\n * see. Defense in depth against a host bug making the Service Worker a second\n * writer. Exported for tests.\n */\nexport function readOnlyStorage(storage: Storage): Storage {\n const refuse = (op: string): Promise<never> =>\n Promise.reject(\n new Error(`notification-preview storage is read-only (attempted ${op})`),\n );\n const readOnly: Storage = {\n get: (ns, key) => storage.get(ns, key),\n put: (_ns, _key, _value) => refuse(\"put\"),\n del: (_ns, _key) => refuse(\"del\"),\n listKeys: (ns, prefix) => storage.listKeys(ns, prefix),\n };\n // `listEntries` is a read, so the read-only open keeps its one-call path.\n // `applyBatch` is a write and is deliberately absent: the wasm only uses\n // the methods it finds, and the read-only backend never batches.\n const hostListEntries = storage.listEntries;\n if (typeof hostListEntries === \"function\") {\n readOnly.listEntries = (ns, prefix) => hostListEntries.call(storage, ns, prefix);\n }\n return readOnly;\n}\n\n/**\n * A transport that can never be used: the preview client never sends, never\n * fetches, never discovers. `send` rejects loudly so a wiring mistake is\n * caught instead of silently networking from a push handler.\n */\nfunction silentTransport(): {\n send(envelope: unknown): Promise<never>;\n fetchSince(conv: unknown, cursor: unknown, limit: number): Promise<unknown[]>;\n discoverDevices(userId: unknown): Promise<unknown[]>;\n setNextWelcomeRecipients(conv: unknown, recipients: unknown): Promise<void>;\n} {\n return {\n send: () => Promise.reject(new Error(\"notification-preview cannot send\")),\n fetchSince: () => Promise.resolve([]),\n discoverDevices: () => Promise.resolve([]),\n setNextWelcomeRecipients: () => Promise.resolve(),\n };\n}\n","// Public entry point. Spawns the dedicated Worker that hosts the WASM instance and exposes a\n// Promise-based, identical-to-native API. Crypto runs off the main thread.\n\nimport type {\n AddMembersReport, AdmitChatEntry, AdmitChatOutcome, ApplyBatchResult,\n CatchupAppEvent, CatchupSnapshotView, CommitInDoubt,\n ConversationId, ConversationMeta, ConversationPolicy, DeviceId, DeviceLinkApproval, DeviceLinkPossession,\n ExpectedOwner,\n DeviceReauthProof, DeviceRemovalReport, IncomingMessage,\n HistoryBundle, IdentityRotation, LogHead, LogPosition, MemberInfo, MessageBatchMeta, PendingApply,\n KeyPackageEntry, LinkingTicket, MessageEnvelope, RecoveryBackup, SequencedEnvelope, Storage,\n SyncStepResult, Transport, UserId,\n} from \"./types\";\nimport type { Request, Response, TransportFeatures } from \"./protocol\";\nimport { errorKind, MessageFanout } from \"./fanout\";\nimport { GapFiller } from \"./gap-fill\";\nimport { InboundCoalescer } from \"./inbound-coalescer\";\nimport { scopeStorage, storageFeaturesOf } from \"./storage/scope\";\nimport {\n type AddMembersReportWire,\n addMembersReportFromWire,\n type ApplyBatchResultWire,\n applyBatchResultFromWire,\n type CommitInDoubtWire,\n commitInDoubtFromWire,\n isSequencedFrame,\n type LogPositionWire,\n logHeadToWire,\n logPositionFromWire,\n sequencedToWire,\n type SyncStepResultWire,\n syncStepResultFromWire,\n} from \"./sequenced\";\n\nexport type * from \"./types\";\n\n// Re-export the default Storage and Transport implementations from the main entry so consumers\n// whose bundlers don't honor package.json#exports (Metro with strict resolution, some legacy\n// Webpack configs) can still get them with a plain `import { ... } from \"@ping-app/ping-openmls-sdk\"`. Power\n// users who care about tree-shaking can keep using the subpath imports.\nexport { IndexedDbStorage } from \"./storage/indexeddb\";\nexport { WebSocketTransport } from \"./transport/websocket\";\n// [CR-5] Service-worker notification preview. Prefer the subpath import\n// (`@ping-app/ping-openmls-sdk/notification-preview`) inside the Service Worker bundle; this\n// re-export exists for bundlers that don't honor package.json#exports. The\n// heavy work (WASM load) happens only when `openNotificationPreview` is called.\nexport {\n MAX_PREVIEW_PREREQUISITES,\n openNotificationPreview,\n type NotificationPreviewOptions,\n type NotificationPreviewSession,\n} from \"./notification-preview\";\n\n// Ping wire contract — version, content-type constants, and runtime validators. Internal\n// products MUST claim conformance; external consumers MAY adopt or run their own profile.\n// See docs/PING_WIRE_CONTRACT.md.\nexport {\n PING_WIRE_CONTRACT_VERSION,\n PING_WIRE_CONTRACT_HEADER,\n PING_WIRE_CONTRACT_HEADER_VALUE,\n WIRE_VERSION_MIN_ACCEPTED,\n CONTENT_TYPE_CBOR,\n CONTENT_TYPE_JSON,\n CONTENT_TYPE_CBOR_LEGACY_V1,\n CONTENT_TYPE_JSON_LEGACY_V1,\n ValidationError,\n validate,\n verifyApplicationContentHash,\n negotiates,\n} from \"./wire-contract\";\n\nexport interface ClientConfig {\n identityExport: Uint8Array;\n deviceLabel: string;\n storage: Storage;\n transport: Transport;\n /** Override the wall clock (test/sim only). */\n now?: () => number;\n /**\n * Optional 32-byte Ed25519 secret key. When supplied AND no\n * `LocalDevice` is yet persisted in `storage`, the SDK adopts this\n * as its device signing key — so `deviceId()` returns\n * `SHA-256(public_key_of(secret))`, deterministic from what the\n * caller passed.\n *\n * Use case: align the SDK's `device_id` (which the SDK stamps into\n * every envelope's `sender_device` field) with an externally-\n * computed device id — typically `SHA-256(device_signing_pubkey)`\n * in the host's auth layer, where the JWT carries that same value\n * as its `device_id` claim. Without this alignment, a server that\n * validates `envelope.sender_device == jwt.device_id` rejects every\n * upload with `sender_device_mismatch`.\n *\n * Ignored on subsequent inits (when `storage` already holds a\n * persisted `LocalDevice`) — the on-disk identity is authoritative\n * for stability across restarts.\n */\n deviceSigningSecretKey?: Uint8Array;\n /**\n * Optional per-account storage scope. When set, the SDK prefixes EVERY\n * storage namespace it reads/writes with `${accountNamespace}\\0`, so\n * multiple accounts that share one `Storage` backend can never read or\n * overwrite each other's MLS group state, device identity, or key\n * material. Hosts that already give each account its own physical store\n * (e.g. a per-account IndexedDB database) can still set this as\n * defense-in-depth — the prefix is stable across restarts and MUST be\n * the same value every init for a given account or its data becomes\n * unreachable. Use a stable, opaque per-account id (e.g. the account id\n * hex); never a display name.\n */\n accountNamespace?: string;\n /**\n * The owner each conversation's FIRST roles write must name (2026-11-04,\n * round 2): the server's recorded creator, as an MLS user id (map the\n * account id through the roster). Consulted only when a group without\n * roles gains them; a first roles write naming another owner strands as\n * `\"notPermitted\"`. A conversation with no entry accepts the first write\n * from any member. Refresh later with `setExpectedOwners`.\n */\n expectedOwners?: ExpectedOwner[];\n}\n\nexport interface Conversation {\n readonly id: ConversationId;\n send(plaintext: Uint8Array): Promise<MessageEnvelope>;\n /** [CR-2] Add members by (device_id, KeyPackage) pair. Hosts typically pull these\n * straight from `transport.discoverDevices(userId)`. All or nothing: one\n * unusable entry fails the whole add (see `addMembersWithVerdicts`). */\n addMembers(entries: KeyPackageEntry[]): Promise<void>;\n /** Add members with one verdict per entry: every entry is screened on its\n * own (KeyPackage verification, lifetime included; capabilities; an\n * existing leaf; a repeat), the usable ones go into ONE Commit sent with\n * its Welcome as one batch, and the rest are reported instead of failing\n * the Commit for every other invitee. A device that already has a leaf is\n * reported (`alreadyMember`, with its leaf), never evicted. */\n addMembersWithVerdicts(entries: KeyPackageEntry[]): Promise<AddMembersReport>;\n /** Re-admit a device that kept its signature key: ONE Commit that removes\n * the leaf holding the KeyPackage's own key (the device's stale leaf: a\n * stranded device, a restore over the same store) and adds its fresh\n * KeyPackage. A re-admission never brings in an account and never makes an\n * account's leaf count grow: with no leaf of that key it rejects\n * \"not permitted: ...\" (`isNotPermittedError`) in EVERY conversation,\n * before anything is sent. A device that came back with a NEW key is added\n * (`addMembers`) by a device of its own account, the owner or an admin.\n * In a conversation with roles the committer is a device of the same\n * account as the device it re-admits, the owner, or an admin (never an\n * admin for a device of the owner); anybody else is rejected the same way\n * (2026-11-18: the `replace` argument is gone, and a plain member no\n * longer re-admits another account's device). Ask the client's\n * `mayReadmit` BEFORE claiming the device's KeyPackage.\n * Resolves to the device id of the leaf the Commit replaced (the device\n * that kept its key). `null`: no leaf was replaced. */\n reAdmitDevice(entry: KeyPackageEntry): Promise<DeviceId | null>;\n removeMembers(leafIndexes: number[]): Promise<void>;\n /** Remove every OTHER leaf of this account from this conversation (step 2\n * of an account's leave, before leaving): one Commit removing every leaf\n * whose credential verifies for this client's own identity, except this\n * device's. Resolves to how many leaves it removed; 0 sends nothing. The\n * leaves are read from the tree on every call. Any role may call it. */\n removeOwnOtherLeaves(): Promise<number>;\n /** Remove an account from this conversation by identity: one Commit\n * removing every leaf whose credential verifies for one of `identities`\n * (MLS user ids, 32 bytes each: the account's current identity and any\n * older ones the host names). Resolves to how many leaves ITS OWN\n * Removes took (a leaf whose leave was already pending goes with the same\n * Commit and is not counted): read the roster for the outcome, never the\n * count. Read from the tree on every call, so a retry removes\n * what the tree holds then. In a group with roles it is the owner's or an\n * admin's call (rejects \"not permitted: ...\" otherwise) and it never\n * removes the owner's leaves. */\n removeMembersByIdentity(identities: UserId[]): Promise<number>;\n /** Record the group's roles in its policy (2026-11-04, round 2): `owner` and\n * `admins` as MLS user ids. One GroupContextExtensions Commit, no Welcome.\n * Rejects with \"not permitted ...\" before anything is sent when this\n * device's role does not allow the change (the first roles write is any\n * member's unless an expected owner says otherwise; then the owner hands\n * over, the owner or an admin changes the admins), when a member's app is\n * too old for roles (`conversationPolicy().incapableMembers`), or in the\n * DeviceGroup. Admins keep promotion order; the owner is never listed. */\n setConversationRoles(owner: UserId, admins: UserId[]): Promise<void>;\n /** Change the conversation `name` (carried in the GroupContext) via an MLS\n * GroupContextExtensions commit — the rename / embedded avatar-media-id change\n * propagates to every member and future joiner through group STATE, not a side\n * broadcast. Pass `null` to clear. All members must have re-linked since the\n * group-name capability shipped, else the SDK throws. */\n setConversationName(name: string | null): Promise<void>;\n /**\n * The conversation's MLS GroupContext name as the group holds it now, or\n * `undefined` when the group has none or the client holds no metadata for\n * the conversation (it is not held, or nothing has reported it yet: read it\n * with `readConversationMeta(id)`).\n *\n * Never the name from before a change. The client's copy of a conversation's\n * metadata is replaced before any `onConversationUpdated` listener is told\n * the conversation changed, and before this device's own call that changed\n * it resolves (see `MessagingClient.readConversationMeta`).\n *\n * This accessor was MISSING, and hosts reasonably assumed it existed:\n * `getConversation(id).name` read `undefined` on every call, so any host logic\n * driven by group state — titles, rosters, avatars and roles carried in the\n * GroupContext — saw nothing. A group then materialised unnamed until a\n * best-effort broadcast happened to arrive, and never converged from group\n * state at all. Prefer `meta()` when you need the full record; this is the\n * one-field convenience that hosts were already reaching for.\n */\n readonly name?: string | undefined;\n /** The conversation's current MLS epoch, or `undefined` when the client\n * holds no metadata for the conversation. Never an epoch from before a\n * change the host was already told about. */\n readonly epoch?: number | undefined;\n /** The whole record, as fresh as `name`. Throws when the client holds no\n * metadata for the conversation: `readConversationMeta(id)` answers `null`\n * instead, and tells \"not held\" from \"not read yet\". */\n meta(): ConversationMeta;\n}\n\nexport class MessagingClient {\n private worker: Worker;\n private nextId = 1;\n private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();\n private storage: Storage;\n private transport: Transport;\n private now: () => number;\n /** `onMessage` / `onMessageBatch` handlers and the guarded delivery to them. */\n private readonly fanout = new MessageFanout();\n private conversationHandlers = new Set<(id: ConversationId, epoch: number, sender?: DeviceId) => void>();\n private subscription: { unsubscribe(): void } | null = null;\n /**\n * This client's copy of each conversation's metadata, keyed by lowercase-hex\n * conversation id: what a conversation handle's `name`, `epoch` and `meta()`\n * answer from.\n *\n * It is never older than what the host has been told. The worker attaches a\n * conversation's metadata to every change it reports, and {@link handleWorker}\n * stores it before it calls a listener or settles a call; an entry whose\n * conversation changed with no metadata attached is dropped, never kept.\n * Bounded by the conversations the client holds: an entry goes when its\n * conversation is left, dropped or removed, and `listConversations()`\n * replaces the whole map.\n */\n private metaCache = new Map<string, ConversationMeta>();\n /**\n * Per-conversation batching of sequenced live frames: the first frame goes\n * to the worker at once, frames that arrive while that batch is in flight\n * go out as ONE `processSequencedBatch` when it returns. See\n * {@link dispatchIncoming}.\n */\n private readonly coalescer = new InboundCoalescer<SequencedEnvelope>(\n (_key, items) => this.applyLiveBatch(items),\n );\n /** Single-flight gap fills, one `syncConversationStep` loop per conversation. */\n private readonly gapFiller = new GapFiller();\n /** Set by {@link close}: every later call rejects instead of hanging. */\n private closed = false;\n // Cached at init() so dispatchIncoming can skip envelopes we sent ourselves — the relay\n // broadcasts to all WS subscribers including the sender, and re-applying our own already-\n // merged commits would error with \"epoch differs\".\n private ownDeviceId: Uint8Array | null = null;\n /**\n * Per-conversation dispatch chains. See {@link dispatchIncoming}.\n *\n * Keyed by lowercase-hex conversation id. Bounded: a chain is deleted the\n * moment it settles and is still the tail, so an account with thousands of\n * conversations holds at most one entry per conversation with work IN FLIGHT,\n * not one per conversation it has ever seen.\n */\n private dispatchChains = new Map<string, Promise<void>>();\n\n private constructor(cfg: ClientConfig, worker: Worker) {\n this.worker = worker;\n // Per-account storage scoping (defense-in-depth against cross-account\n // data mixing). When `accountNamespace` is set, every namespace the SDK\n // touches is prefixed so two accounts sharing a backend stay isolated.\n // Only the namespace is scoped: the SDK partitions all of its state\n // (device identity, MLS groups, key material) by namespace, and the\n // space separator never occurs in its own namespace strings, so scoped\n // and unscoped data coexist unambiguously.\n this.storage =\n cfg.accountNamespace !== undefined && cfg.accountNamespace.length > 0\n ? scopeStorage(cfg.storage, cfg.accountNamespace)\n : cfg.storage;\n this.transport = cfg.transport;\n this.now = cfg.now ?? (() => Date.now());\n this.worker.onmessage = (ev) => this.handleWorker(ev.data as Response);\n // An uncaught error inside the worker leaves every awaiting caller with\n // a promise nobody will ever settle; reject them with a typed error\n // instead. The client is not marked closed: the worker may still serve.\n this.worker.onerror = () => this.failPending(new MessagingClientClosedError(\"worker-error\"));\n }\n\n /** Generate a fresh identity. The returned bytes are a secret — store them encrypted. */\n static async generateIdentity(): Promise<Uint8Array> {\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"generateIdentity\", id: 1,\n });\n }\n\n /**\n * HPKE-seal a `LinkingTicket` for delivery to a new device ([CR-3]).\n *\n * Returns CBOR-encoded bytes safe to relay through an untrusted inbox. The new device's\n * X25519 public key (`newDevicePub`) is exchanged out-of-band — typically as part of a\n * QR-encoded handshake on the linking screen. Pure function; runs in an ephemeral\n * worker so no live `MessagingClient` is required on the sender side.\n *\n * Suite: `DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-128-GCM` (matches MLS).\n */\n static async sealLinkingTicket(\n ticket: LinkingTicket,\n newDevicePub: Uint8Array,\n ): Promise<Uint8Array> {\n if (newDevicePub.length !== 32) {\n throw new Error(\"sealLinkingTicket: newDevicePub must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"sealLinkingTicket\", id: 1, ticket, newDevicePub,\n });\n }\n\n /**\n * HPKE-open a sealed `LinkingTicket` on the new device ([CR-3]).\n *\n * The receiving device hasn't booted a `MessagingClient` yet — it only has its X25519\n * ephemeral keypair. This static method runs the open in an ephemeral worker, returning\n * the cleartext ticket which the host then feeds to `init()` + `consumeLinkingTicket()`.\n *\n * On failure the error message is deliberately generic (no discriminator between \"wrong\n * key\" vs \"tampered ciphertext\") so a probing attacker can't tell the new device's key\n * was the issue.\n */\n static async openLinkingTicket(\n sealed: Uint8Array,\n newDevicePriv: Uint8Array,\n ): Promise<LinkingTicket> {\n if (newDevicePriv.length !== 32) {\n throw new Error(\"openLinkingTicket: newDevicePriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<LinkingTicket>({\n kind: \"openLinkingTicket\", id: 1, sealed, newDevicePriv,\n });\n }\n\n /**\n * Generic HPKE-Base seal of arbitrary bytes to `recipientPub` (32-byte X25519)\n * under a caller-supplied `info`. One shared HPKE implementation so app layers\n * (e.g. the device-linking auth envelope) stop hand-rolling per-platform HPKE\n * that drifts and breaks cross-platform. Runs in an ephemeral worker.\n */\n static async hpkeSeal(\n plaintext: Uint8Array,\n recipientPub: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPub.length !== 32) {\n throw new Error(\"hpkeSeal: recipientPub must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeSeal\", id: 1, plaintext, recipientPub, info,\n });\n }\n\n /** Generic HPKE-Base open — inverse of {@link hpkeSeal}. `info` must match the sender. */\n static async hpkeOpen(\n sealed: Uint8Array,\n recipientPriv: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPriv.length !== 32) {\n throw new Error(\"hpkeOpen: recipientPriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeOpen\", id: 1, sealed, recipientPriv, info,\n });\n }\n\n /**\n * HPKE-Base seal in the RFC 9180 CANONICAL layout, `enc || ct||tag`, with no\n * CBOR wrapper.\n *\n * Use this, not {@link hpkeSeal}, for anything the app layers already speak.\n * `hpkeSeal` wraps its output in CBOR `{v, enc, ct}` for the linking ticket,\n * and because that could not read the RFC layout, iOS, Android, web and the\n * third-party `ping-notify` sender each ended up hand-composing their own\n * HPKE for the same suite. This is the one they agree on.\n */\n static async hpkeSealRaw(\n plaintext: Uint8Array,\n recipientPub: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPub.length !== 32) {\n throw new Error(\"hpkeSealRaw: recipientPub must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeSealRaw\", id: 1, plaintext, recipientPub, info,\n });\n }\n\n /**\n * Inverse of {@link hpkeSealRaw}. `info` must match the sender's.\n *\n * Rejects with one uniform error whatever went wrong. This opens bytes from\n * an unauthenticated inbox, so a caller that could tell \"wrong key\" from\n * \"tampered\" from \"truncated\" would be an oracle for whoever wrote them.\n */\n static async hpkeOpenRaw(\n sealed: Uint8Array,\n recipientPriv: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPriv.length !== 32) {\n throw new Error(\"hpkeOpenRaw: recipientPriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeOpenRaw\", id: 1, sealed, recipientPriv, info,\n });\n }\n\n /**\n * A fresh X25519 keypair for the suite.\n *\n * Exposed so a caller minting a recipient key (a Ping Notify inbox, a linking\n * handshake) does not reach for WebCrypto to do it, which is the same problem\n * one layer down.\n */\n static async hpkeGenerateKeypair(): Promise<{\n publicKey: Uint8Array;\n privateKey: Uint8Array;\n }> {\n const both = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeGenerateKeypair\", id: 1,\n });\n if (both.length !== 64) {\n throw new Error(\"hpkeGenerateKeypair: expected 64 bytes\");\n }\n return { publicKey: both.slice(0, 32), privateKey: both.slice(32) };\n }\n\n // ---- Post-quantum HPKE (X-Wing), docs/POST_QUANTUM.md phase 2 ----\n //\n // The `Pq` twins of the functions above: HPKE with KEM X-Wing draft-06\n // (ML-KEM-768 + X25519), HKDF-SHA256, AES-128-GCM. A public key is\n // {@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes, `enc` {@link HPKE_PQ_ENC_BYTES}, the\n // private key a 32-byte seed. These are what the pairing, link-auth,\n // history-transfer and app-inbox flows use from phase 2 on; the classical\n // forms stay for app inboxes created with a 32-byte key before the roll. A\n // classical private key and an X-Wing seed are both 32 bytes but are NOT\n // interchangeable: the host knows which family a stored key belongs to.\n\n /**\n * HPKE-seal a `LinkingTicket` under the new device's X-Wing public key\n * ([CR-3], post-quantum). CBOR `{v: 2, enc, ct}` under `ping/link/v2`; the\n * classical {@link openLinkingTicket} refuses it and {@link openLinkingTicketPq}\n * refuses a `v: 1` blob, so there is no downgrade in either direction.\n */\n static async sealLinkingTicketPq(\n ticket: LinkingTicket,\n newDevicePub: Uint8Array,\n ): Promise<Uint8Array> {\n if (newDevicePub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {\n throw new Error(`sealLinkingTicketPq: newDevicePub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"sealLinkingTicketPq\", id: 1, ticket, newDevicePub,\n });\n }\n\n /**\n * HPKE-open a sealed `v: 2` ticket with the new device's 32-byte X-Wing seed\n * ([CR-3], post-quantum). The error is deliberately generic, like\n * {@link openLinkingTicket}.\n */\n static async openLinkingTicketPq(\n sealed: Uint8Array,\n newDevicePriv: Uint8Array,\n ): Promise<LinkingTicket> {\n if (newDevicePriv.length !== 32) {\n throw new Error(\"openLinkingTicketPq: newDevicePriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<LinkingTicket>({\n kind: \"openLinkingTicketPq\", id: 1, sealed, newDevicePriv,\n });\n }\n\n /** Post-quantum {@link hpkeSeal}: CBOR-wrapped (`v: 2`), `recipientPub` is 1216 bytes. */\n static async hpkeSealPq(\n plaintext: Uint8Array,\n recipientPub: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {\n throw new Error(`hpkeSealPq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeSealPq\", id: 1, plaintext, recipientPub, info,\n });\n }\n\n /** Inverse of {@link hpkeSealPq}. `recipientPriv` is the 32-byte seed; `info` must match. */\n static async hpkeOpenPq(\n sealed: Uint8Array,\n recipientPriv: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPriv.length !== 32) {\n throw new Error(\"hpkeOpenPq: recipientPriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeOpenPq\", id: 1, sealed, recipientPriv, info,\n });\n }\n\n /**\n * Post-quantum {@link hpkeSealRaw}: RFC 9180 canonical `enc(1120) || ct || tag`.\n * The `v2` form of every app-layer envelope (`ping/link-auth/v2`,\n * `ping/app-inbox/v2`).\n */\n static async hpkeSealRawPq(\n plaintext: Uint8Array,\n recipientPub: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {\n throw new Error(`hpkeSealRawPq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeSealRawPq\", id: 1, plaintext, recipientPub, info,\n });\n }\n\n /** Inverse of {@link hpkeSealRawPq}. One uniform error, as for {@link hpkeOpenRaw}. */\n static async hpkeOpenRawPq(\n sealed: Uint8Array,\n recipientPriv: Uint8Array,\n info: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPriv.length !== 32) {\n throw new Error(\"hpkeOpenRawPq: recipientPriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeOpenRawPq\", id: 1, sealed, recipientPriv, info,\n });\n }\n\n /**\n * A fresh X-Wing keypair: `publicKey` is {@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes,\n * `privateKey` the 32-byte seed. Persist only the seed and recompute the public\n * half with {@link hpkePublicKeyFromSeed}; wipe both buffers when done.\n */\n static async hpkeGenerateKeypairPq(): Promise<{\n publicKey: Uint8Array;\n privateKey: Uint8Array;\n }> {\n const both = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkeGenerateKeypairPq\", id: 1,\n });\n if (both.length !== HPKE_PQ_PUBLIC_KEY_BYTES + 32) {\n throw new Error(`hpkeGenerateKeypairPq: expected ${HPKE_PQ_PUBLIC_KEY_BYTES + 32} bytes`);\n }\n return {\n publicKey: both.slice(0, HPKE_PQ_PUBLIC_KEY_BYTES),\n privateKey: both.slice(HPKE_PQ_PUBLIC_KEY_BYTES),\n };\n }\n\n /**\n * The X-Wing public key for a stored 32-byte seed. Deterministic: the pairing\n * code carries SHA-256 of exactly these bytes, so what a device advertises\n * always matches what it will open with.\n */\n static async hpkePublicKeyFromSeed(seed: Uint8Array): Promise<Uint8Array> {\n if (seed.length !== 32) {\n throw new Error(\"hpkePublicKeyFromSeed: seed must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkePublicKeyFromSeed\", id: 1, seed,\n });\n }\n\n /**\n * The id of an account's DeviceGroup (the private sync group of the\n * account's own devices), derived by the SDK core from the account's MLS\n * user id: `userId` is `client.userId()` (32 bytes), NOT the server's\n * account id. Deterministic: every device of the account derives the same\n * id, so a host recognises the DeviceGroup without copying the derivation.\n * Stateless (no client needed); bytes that are not an MLS user id derive an\n * id no device uses.\n */\n static async deviceGroupIdFor(userId: UserId): Promise<ConversationId> {\n return MessagingClient.ephemeralWorkerCall<ConversationId>({\n kind: \"deviceGroupIdFor\", id: 1, userId,\n });\n }\n\n /** The 32-byte X25519 public key for a stored classical private key. */\n static async hpkePublicKeyFromPrivate(privateKey: Uint8Array): Promise<Uint8Array> {\n if (privateKey.length !== 32) {\n throw new Error(\"hpkePublicKeyFromPrivate: privateKey must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"hpkePublicKeyFromPrivate\", id: 1, privateKey,\n });\n }\n\n /**\n * Answer a device re-authentication challenge (`POST /v1/auth/device/challenge`) with\n * the device signing key, so a device whose session tokens are gone or dead gets fresh\n * ones for the SAME device without a code (`POST /v1/auth/device/verify`).\n *\n * The SDK builds the signed bytes itself (`\"ping/device-reauth/v1\" || challengeId ||\n * nonce || deviceId || accountId || audience`), so this cannot sign anything else with\n * the device key. `deviceSigningSecretKey` is the 32-byte secret the host passes as\n * `deviceSigningSecretKey` to {@link init}; `challengeId` (16 bytes) and `nonce`\n * (32 bytes) come from the challenge response. `accountId` (16 bytes) is the account\n * the host stored with its session; the server refuses a proof for any other account,\n * so send the same id with the proof. `audience` is the canonical origin of the API\n * THIS host is configured to reach (`new URL(apiBase).origin`, for example\n * `https://api-prod.ping.live`), never the value the server returned: that is what\n * makes a challenge relayed from another deployment useless there. The returned\n * `deviceId` is SHA-256 of the key's public half; send it with the signature.\n *\n * Rejects wrong widths and a non-canonical audience. Runs in an ephemeral worker.\n */\n static async signDeviceReauth(params: {\n deviceSigningSecretKey: Uint8Array;\n challengeId: Uint8Array;\n nonce: Uint8Array;\n accountId: Uint8Array;\n audience: string;\n }): Promise<DeviceReauthProof> {\n const { deviceSigningSecretKey, challengeId, nonce, accountId, audience } = params;\n if (deviceSigningSecretKey.length !== 32) {\n throw new Error(\"signDeviceReauth: deviceSigningSecretKey must be 32 bytes\");\n }\n if (challengeId.length !== 16) {\n throw new Error(\"signDeviceReauth: challengeId must be 16 bytes\");\n }\n if (nonce.length !== 32) {\n throw new Error(\"signDeviceReauth: nonce must be 32 bytes\");\n }\n if (accountId.length !== 16) {\n throw new Error(\"signDeviceReauth: accountId must be 16 bytes\");\n }\n const both = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"signDeviceReauth\", id: 1, deviceSigningSecretKey, challengeId, nonce, accountId, audience,\n });\n if (both.length !== 96) {\n throw new Error(\"signDeviceReauth: expected 96 bytes\");\n }\n return { deviceId: both.slice(0, 32), signature: both.slice(32) };\n }\n\n /**\n * Link verification v2, on the APPROVING device: approve ONE new device on ONE\n * server link session (`POST /v1/auth/link/sessions` returned `approvalSessionId`)\n * with this device's signing key. The new device sends the result with its own\n * {@link signDeviceLinkPossession} proof to `POST /v1/auth/link/verify`.\n *\n * The SDK builds the signed bytes itself (`\"ping/device-link-approve/v1\" ||\n * approvalSessionId || accountId || approverDeviceId || newDeviceId ||\n * newDevicePubkey || audience`, see docs/DEVICE_LINK_V2_VECTORS.md) and derives\n * both device ids from the keys, so this cannot sign anything else with the device\n * key. `deviceSigningSecretKey` is the 32-byte seed the host holds for THIS device\n * (the one registered as its device signing key); `accountId` (16 bytes) is the\n * account stored with this device's session; `newDevicePubkey` (32 bytes) is the\n * new device's key from its handshake; `audience` is the canonical origin of the API\n * THIS host is configured to reach (`new URL(apiBase).origin`), as for\n * {@link signDeviceReauth}.\n *\n * Rejects wrong widths, a non-canonical audience, a new key that is not a canonical\n * Ed25519 point outside the small-order subgroup, and this device's own key. Runs in\n * an ephemeral worker.\n */\n static async signDeviceLinkApproval(params: {\n deviceSigningSecretKey: Uint8Array;\n approvalSessionId: Uint8Array;\n accountId: Uint8Array;\n newDevicePubkey: Uint8Array;\n audience: string;\n }): Promise<DeviceLinkApproval> {\n const { deviceSigningSecretKey, approvalSessionId, accountId, newDevicePubkey, audience } =\n params;\n if (deviceSigningSecretKey.length !== 32) {\n throw new Error(\"signDeviceLinkApproval: deviceSigningSecretKey must be 32 bytes\");\n }\n if (approvalSessionId.length !== 16) {\n throw new Error(\"signDeviceLinkApproval: approvalSessionId must be 16 bytes\");\n }\n if (accountId.length !== 16) {\n throw new Error(\"signDeviceLinkApproval: accountId must be 16 bytes\");\n }\n if (newDevicePubkey.length !== 32) {\n throw new Error(\"signDeviceLinkApproval: newDevicePubkey must be 32 bytes\");\n }\n const all = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"signDeviceLinkApproval\", id: 1,\n deviceSigningSecretKey, approvalSessionId, accountId, newDevicePubkey, audience,\n });\n if (all.length !== 128) {\n throw new Error(\"signDeviceLinkApproval: expected 128 bytes\");\n }\n return {\n approverDeviceId: all.slice(0, 32),\n newDeviceId: all.slice(32, 64),\n signature: all.slice(64),\n };\n }\n\n /**\n * Link verification v2, on the NEW device: prove that this device holds the key the\n * link session names (`\"ping/device-link-possess/v1\" || approvalSessionId ||\n * accountId || deviceId || audience`). `deviceSigningSecretKey` is this device's own\n * 32-byte seed (the key its handshake advertised); `approvalSessionId` and\n * `accountId` come from the approving device's sealed envelope; `audience` as for\n * {@link signDeviceReauth}. Check `approval.newDeviceId` equals the returned\n * `deviceId` before verifying: a substituted handshake is refused locally.\n *\n * Rejects wrong widths and a non-canonical audience. Runs in an ephemeral worker.\n */\n static async signDeviceLinkPossession(params: {\n deviceSigningSecretKey: Uint8Array;\n approvalSessionId: Uint8Array;\n accountId: Uint8Array;\n audience: string;\n }): Promise<DeviceLinkPossession> {\n const { deviceSigningSecretKey, approvalSessionId, accountId, audience } = params;\n if (deviceSigningSecretKey.length !== 32) {\n throw new Error(\"signDeviceLinkPossession: deviceSigningSecretKey must be 32 bytes\");\n }\n if (approvalSessionId.length !== 16) {\n throw new Error(\"signDeviceLinkPossession: approvalSessionId must be 16 bytes\");\n }\n if (accountId.length !== 16) {\n throw new Error(\"signDeviceLinkPossession: accountId must be 16 bytes\");\n }\n const both = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"signDeviceLinkPossession\", id: 1,\n deviceSigningSecretKey, approvalSessionId, accountId, audience,\n });\n if (both.length !== 96) {\n throw new Error(\"signDeviceLinkPossession: expected 96 bytes\");\n }\n return { deviceId: both.slice(0, 32), signature: both.slice(32) };\n }\n\n // Spawn-call-terminate helper for stateless WASM functions exposed at module scope (no\n // PingClient required). Each call gets a fresh worker; the cost is acceptable because\n // these are one-shot, off-the-hot-path operations (identity gen, linking ticket seal/open).\n //\n // The returned promise ALWAYS settles and the worker is ALWAYS terminated: on its\n // result, on a worker `error` (the script failed to load or import, or threw at top\n // level), on a `messageerror` (a reply that could not be deserialised), and when the\n // worker cannot be created or the request cannot be posted. Only `onmessage` used to be\n // wired, so a worker that failed to load left `generateIdentity()` pending forever and\n // the worker alive.\n private static ephemeralWorkerCall<T>(req: Request): Promise<T> {\n let w: Worker;\n try {\n w = new Worker(new URL(\"./worker.js\", import.meta.url), { type: \"module\" });\n } catch {\n return Promise.reject(new EphemeralWorkerError(\"spawn\"));\n }\n return new Promise<T>((resolve, reject) => {\n let settled = false;\n const settle = (finish: () => void): void => {\n if (settled) return;\n settled = true;\n w.onmessage = null;\n w.onerror = null;\n w.onmessageerror = null;\n w.terminate();\n finish();\n };\n w.onmessage = (ev) => {\n const msg = ev.data as Response;\n if (msg.kind === \"result\" && msg.id === (req as { id: number }).id) {\n settle(() => (msg.ok ? resolve(msg.value as T) : reject(new Error(msg.error))));\n }\n };\n w.onerror = () => settle(() => reject(new EphemeralWorkerError(\"error\")));\n w.onmessageerror = () => settle(() => reject(new EphemeralWorkerError(\"messageerror\")));\n try {\n w.postMessage(req);\n } catch {\n settle(() => reject(new EphemeralWorkerError(\"post\")));\n }\n });\n }\n\n static async init(cfg: ClientConfig): Promise<MessagingClient> {\n const worker = new Worker(new URL(\"./worker.js\", import.meta.url), { type: \"module\" });\n const client = new MessagingClient(cfg, worker);\n\n // Which optional transport methods exist decides the proxy the worker\n // hands the wasm (see `TransportFeatures`).\n const transportFeatures: TransportFeatures = {\n fetchLogSince: typeof cfg.transport.fetchLogSince === \"function\",\n fetchLogHeads: typeof cfg.transport.fetchLogHeads === \"function\",\n };\n // Likewise for the optional storage methods: with `applyBatch` the\n // per-row MLS store hands the host each checkpoint delta as ONE atomic\n // write, with `listEntries` it opens in one read (see `Storage` in\n // types.ts). Probed on the storage the worker's calls are dispatched to\n // (`client.storage`, scoped when `accountNamespace` is set), never on\n // `cfg.storage`: advertising a method the dispatch target lacks is how\n // every scoped account once failed to open its store.\n const storageFeatures = storageFeaturesOf(client.storage);\n await client.call({\n kind: \"init\",\n id: client.nextId++,\n identityExport: cfg.identityExport,\n deviceLabel: cfg.deviceLabel,\n nowMs: client.now(),\n ...(cfg.deviceSigningSecretKey\n ? { deviceSigningSecretKey: cfg.deviceSigningSecretKey }\n : {}),\n ...(cfg.expectedOwners ? { expectedOwners: cfg.expectedOwners } : {}),\n transportFeatures,\n storageFeatures,\n });\n\n // Cache the device id once so we can drop envelopes we sent ourselves on the WS echo.\n client.ownDeviceId = await client.deviceId();\n\n // Start the live subscription. A sequenced frame (`{ envelope, serverSeq }`\n // with a known position) is coalesced per conversation into\n // `processSequencedBatch`; a bare envelope takes the legacy path, which\n // dispatches each envelope to the right handler:\n // - Welcome envelopes for unknown conversations → joinConversation\n // - Welcomes for already-joined conversations → drop (server may broadcast duplicates)\n // - Welcomes addressed to other devices → drop (we can't decrypt)\n // - Everything else → processEnvelope\n // The callback RETURNS the dispatch promise so a transport that wants to\n // await application (to ack a delivery watermark, or to avoid advancing a\n // cursor past an envelope that has not been applied) can. Transports that\n // ignore the return value are unaffected — ordering is guaranteed inside\n // `dispatchIncoming` regardless, because it enqueues synchronously.\n client.subscription = cfg.transport.subscribe(\n (frame) => client.dispatchIncoming(frame),\n );\n return client;\n }\n\n /**\n * Internal: route an inbound envelope to the right handler, IN ARRIVAL ORDER\n * PER CONVERSATION.\n *\n * ## Why the ordering is load-bearing\n *\n * A group invitation arrives as a Welcome immediately followed by the\n * inviter's hydration Application messages (group title, roster, avatar id).\n * `joinConversation` is asynchronous — it is several round trips to the WASM\n * worker — so a naive `void dispatchIncoming(...)` per frame let the\n * Applications reach `processEnvelope` while the join was still in flight.\n * The conversation did not exist yet, so every one of them was dropped with\n * \"envelope drop: unknown conversation\".\n *\n * That loss is PERMANENT and silent: MLS ratchets forward, the transport has\n * already marked the frames seen and advanced its cursor, and the server will\n * not resend them. The visible symptom was an invitation landing as an\n * unnamed \"New chat\" with no avatar and no roster, and — for the same reason —\n * a rename, avatar change, member add/remove or role change being lost\n * whenever it happened to land while a join or another commit for that group\n * was still being applied.\n *\n * Chaining PER CONVERSATION (not globally) is deliberate: MLS state is\n * per-group, so that is the granularity correctness actually requires, and a\n * busy conversation must not be able to head-of-line block every other one.\n * The chain is built synchronously on entry, so chain order is exactly frame\n * arrival order.\n *\n * ## Sequenced frames\n *\n * A frame that carries its server position (`{ envelope, serverSeq }`,\n * `serverSeq > 0`) does not need the chain: the core applies it at its\n * position, holds it ahead of a hole and drops it at or below what was\n * applied, whatever order it arrived in. What it needs is BATCHING: one\n * MLS checkpoint and one host transaction per burst instead of one per\n * frame. So the first frame for a conversation goes to the worker at once\n * as a batch of one, and frames that arrive while that batch is in flight\n * accumulate and go out as ONE `processSequencedBatch` when it returns; no\n * timer ever delays a frame. Own-device echoes are NOT dropped on this\n * path: the core advances the position past them without touching MLS,\n * and dropping one would leave a hole the next frame reports as a gap. A\n * sequenced frame at `serverSeq` 0 is a legacy frame in a wrapper and\n * takes the legacy path unchanged.\n */\n private dispatchIncoming(frame: MessageEnvelope | SequencedEnvelope): Promise<void> {\n if (isSequencedFrame(frame)) {\n if (frame.serverSeq > 0) {\n return this.coalescer.push(hexOf(frame.envelope.conversation_id), frame);\n }\n return this.dispatchLegacy(frame.envelope);\n }\n return this.dispatchLegacy(frame);\n }\n\n /** The legacy per-envelope path: own-device drop, then the per-conversation chain. */\n private dispatchLegacy(envelope: MessageEnvelope): Promise<void> {\n // The relay broadcasts every envelope to every WS subscriber, including the sender. For\n // our own sends, the local MLS state has already been advanced in-process — re-applying\n // would either fail with \"epoch differs\" (commits) or be a no-op dedupe (application\n // messages). Skip them here.\n //\n // Checked BEFORE enqueuing: our own echo needs no ordering guarantee and\n // must not occupy a slot in the conversation's chain.\n if (this.ownDeviceId && sameBytesU8(envelope.sender_device, this.ownDeviceId)) {\n return Promise.resolve();\n }\n\n const key = hexOf(envelope.conversation_id);\n const prior = this.dispatchChains.get(key) ?? Promise.resolve();\n // `.catch` before `.then` so one failed envelope cannot poison the chain and\n // silently swallow every later envelope for that conversation.\n const next = prior\n .catch(() => undefined)\n .then(() => this.dispatchIncomingOrdered(envelope));\n // The map holds — and the cleanup compares against — THE SAME promise.\n // Storing `next.finally(cb)` while `cb` compares against `next` can never\n // match, so the entry would never be deleted and the map would retain a live\n // chain per conversation for the whole session.\n // The STORED tail must never reject: nobody awaits it, so a rejection here\n // surfaces as an unhandled rejection in the host's console. The returned\n // `next` still rejects, so a transport that DOES await sees real failures.\n const tail: Promise<void> = next\n .catch(() => undefined)\n .finally(() => {\n // Only the tail clears the entry; a chain that grew while we ran stays.\n if (this.dispatchChains.get(key) === tail) this.dispatchChains.delete(key);\n });\n this.dispatchChains.set(key, tail);\n return next;\n }\n\n /** The actual routing, run inside the per-conversation chain. */\n private async dispatchIncomingOrdered(envelope: MessageEnvelope): Promise<void> {\n if (envelope.kind === \"Welcome\") {\n try {\n const known = await this.listConversations();\n const already = known.some((m) => sameBytesU8(m.id, envelope.conversation_id));\n if (already) {\n // Normally a duplicate broadcast for a group we're already in → skip.\n // BUT a re-invite AFTER removal reuses the same conversation_id, so we\n // must NOT blanket-skip: if this conversation is STRANDED (we missed a\n // Commit, or were removed and our local group can no longer advance),\n // the Welcome is our way back in. Attempt the join — `joinConversation`\n // REPLACES the stale group; a genuine duplicate (our KeyPackage already\n // consumed, or addressed to another device) fails harmlessly with\n // KeyPackageNotFound in the catch below and never disturbs a healthy\n // active group. (The core also tears a group down on self-removal, so\n // a cleanly-removed conversation is already UNKNOWN here; this covers\n // the case where the removing Commit was never processed.)\n const stranded = await this.strandedConversations();\n const isStranded = stranded.some((id) => sameBytesU8(id, envelope.conversation_id));\n if (!isStranded) return;\n }\n await this.joinConversation(envelope);\n } catch (e) {\n // Welcomes are broadcast to every connected client; only one device's KeyPackage can\n // decrypt each one, so most fail. Log at debug, drop silently.\n if (typeof console !== \"undefined\") console.debug(\"[ping-sdk] welcome ignored:\", e);\n }\n return;\n }\n try {\n await this.processEnvelope(envelope);\n } catch (e) {\n // NOT a silent drop any more. `core` RETAINS an envelope it cannot apply\n // yet (its Welcome has not been processed, or a Commit that advances the\n // epoch is missing) and replays it on join / epoch advance / catch-up\n // sync — see docs/INVITE_HARDENING.md §S6. The throw here is\n // informational: the frame is already buffered one layer down.\n if (typeof console !== \"undefined\") console.debug(\"[ping-sdk] envelope deferred:\", e);\n }\n }\n\n /**\n * One coalesced batch of live frames. Errors are logged at debug and\n * swallowed, exactly as the legacy path treats a failed envelope: the\n * dispatch promise a transport may await resolves either way, and the\n * core retains anything it could not apply yet.\n */\n private async applyLiveBatch(items: SequencedEnvelope[]): Promise<void> {\n try {\n await this.processSequencedBatch(items);\n } catch (e) {\n if (typeof console !== \"undefined\") console.debug(\"[ping-sdk] sequenced batch failed:\", errorKind(e));\n }\n }\n\n /** Start a fill for every gap a batch reported; each is single-flight. */\n private scheduleGapFills(result: ApplyBatchResult): void {\n for (const gap of result.gaps) {\n void this.fillGap(gap.conversationId).catch((e: unknown) => {\n if (typeof console !== \"undefined\") console.debug(\"[ping-sdk] gap fill failed:\", errorKind(e));\n });\n }\n }\n\n /** One page, delivered as a page, on the requested lane. */\n private async stepConversation(id: ConversationId, stepped: boolean): Promise<SyncStepResult> {\n const raw = await this.call({\n kind: \"syncConversationStep\", id: this.nextId++, conv: id, nowMs: this.now(),\n ...(stepped ? { stepped: true } : {}),\n }) as SyncStepResultWire;\n const result = syncStepResultFromWire(raw);\n this.fanout.deliverBatch(result.messages, { source: \"page\" });\n return result;\n }\n\n // ------------------------ Public API ------------------------\n\n async userId(): Promise<UserId> {\n return await this.call({ kind: \"userId\", id: this.nextId++ }) as UserId;\n }\n\n /**\n * Export the account identity seed (CBOR-wrapped Ed25519, **SECRET**).\n * Transfer to a newly-linked device over the sealed linking channel so all of\n * an account's devices share one `userId` — the basis for cross-device\n * self-attribution (`IncomingMessage.sender_user_id === userId()`). Never log\n * or persist in cleartext.\n */\n async exportIdentity(): Promise<Uint8Array> {\n return await this.call({ kind: \"exportIdentity\", id: this.nextId++ }) as Uint8Array;\n }\n\n /**\n * RETIRED (2026-11-03): always rejects (`Invalid`) and changes nothing.\n *\n * It moved every conversation's own leaf to a new account identity with a\n * credential-changing Commit, the way out of `409 mls_identity_conflict`.\n * Every Ping client now refuses a Commit that changes a member's leaf\n * credential (a hostile linked device could otherwise move its leaf to a\n * peer's identity and escape the account's removal), so a rotation would\n * strand every conversation it touched. The way out of an identity conflict\n * is to link this device again, or sign out and in. Kept so no caller\n * breaks. See `docs/MULTIDEVICE.md` \"Identity rotation\".\n *\n * @deprecated Retired: always rejects. Link this device again instead.\n */\n async rotateIdentity(\n newIdentityExport: Uint8Array,\n nowMs: number = this.now(),\n ): Promise<IdentityRotation> {\n return await this.call({\n kind: \"rotateIdentity\", id: this.nextId++, newIdentityExport, nowMs,\n }) as IdentityRotation;\n }\n\n /**\n * RETIRED with [[rotateIdentity]]: always rejects (`Invalid`).\n *\n * @deprecated Retired: always rejects.\n */\n async rotateIdentityRetry(\n conv: ConversationId,\n nowMs: number = this.now(),\n ): Promise<void> {\n await this.call({ kind: \"rotateIdentityRetry\", id: this.nextId++, conv, nowMs });\n }\n\n async deviceId(): Promise<DeviceId> {\n return await this.call({ kind: \"deviceId\", id: this.nextId++ }) as DeviceId;\n }\n\n /**\n * Release every file lock the MLS store holds so the host process can be\n * suspended. Resolves `true` when the locks are genuinely gone.\n *\n * Present on web for API parity, and a no-op returning `true` here: this build\n * persists through the host's `Storage` (IndexedDB by default), which holds no\n * file locks and has nothing to release. It is load-bearing on the native\n * bindings, where iOS kills a backgrounded process that still holds a lock on\n * a file in an App Group container. Exposed on every platform so a host\n * sharing code across web and native does not have to branch on it.\n *\n * Pair with `resumeStorage()`.\n */\n async suspendStorage(): Promise<boolean> {\n return await this.call({ kind: \"suspendStorage\", id: this.nextId++ }) as boolean;\n }\n\n /** Undo `suspendStorage()`. Idempotent. */\n async resumeStorage(): Promise<void> {\n await this.call({ kind: \"resumeStorage\", id: this.nextId++ });\n }\n\n async freshKeyPackage(): Promise<Uint8Array> {\n return await this.call({ kind: \"freshKeyPackage\", id: this.nextId++ }) as Uint8Array;\n }\n\n /**\n * Generate a fresh LAST-RESORT KeyPackage (RFC 9420 §10). Publish exactly one\n * per device so the server can serve it repeatedly as a fallback when the\n * single-use pool empties — invites then never hard-fail purely because the\n * peer ran out of KeyPackages.\n */\n async freshLastResortKeyPackage(): Promise<Uint8Array> {\n return await this.call({ kind: \"freshLastResortKeyPackage\", id: this.nextId++ }) as Uint8Array;\n }\n\n async createConversation(opts: { name?: string } = {}): Promise<Conversation> {\n const idBytes = await this.call({\n kind: \"createConversation\", id: this.nextId++, name: opts.name ?? null, nowMs: this.now(),\n }) as ConversationId;\n return this.conversationProxy(idBytes);\n }\n\n /**\n * Create an ephemeral per-call MLS group. Identical to {@link createConversation}\n * except the id carries the `0xFF 0xCC` call-group sentinel, so every device\n * recognises it structurally (by id alone — no name, no registry) and keeps it\n * out of the chat list. Hosts MUST use this for call groups.\n */\n async createCallConversation(opts: { name?: string } = {}): Promise<Conversation> {\n const idBytes = await this.call({\n kind: \"createCallConversation\", id: this.nextId++, name: opts.name ?? null, nowMs: this.now(),\n }) as ConversationId;\n return this.conversationProxy(idBytes);\n }\n\n async joinConversation(welcome: MessageEnvelope): Promise<Conversation> {\n const idBytes = await this.call({\n kind: \"joinConversation\", id: this.nextId++, welcome, nowMs: this.now(),\n }) as ConversationId;\n return this.conversationProxy(idBytes);\n }\n\n /**\n * Get a `Conversation` proxy for an already-known conversation. Use this when you have a\n * conversation id (e.g., from `listConversations()`) and want to send/addMembers without\n * re-creating it. Throws if the id isn't known to the worker — call `listConversations()`\n * first to verify membership.\n */\n getConversation(id: ConversationId): Conversation {\n return this.conversationProxy(id);\n }\n\n async listConversations(): Promise<ConversationMeta[]> {\n const metas = await this.call({ kind: \"listConversations\", id: this.nextId++ }) as ConversationMeta[];\n this.metaCache.clear();\n for (const m of metas) this.metaCache.set(hex(m.id), m);\n return metas;\n }\n\n /**\n * ONE conversation's metadata as the group holds it now: the same record as\n * its element of {@link listConversations}, without listing the others.\n * Resolves `null` when this client does not hold the conversation (unknown,\n * dropped, removed, or left). A pure read of local state: nothing is\n * fetched. Rejects for an id that is not 16 bytes.\n *\n * It also brings the conversation handle's `name`, `epoch` and `meta()` to\n * the answer, though they do not need it to be fresh: the client replaces\n * its copy of a conversation's metadata\n * - before any {@link onConversationUpdated} listener is told the\n * conversation changed (a Commit from another member, a join, a page of\n * a catch-up), and\n * - before this device's own call that changed it resolves (a rename, a\n * roles or membership change, a creation, a leave).\n * Use this read for a conversation nothing has reported yet in this\n * session, or to learn that a conversation is no longer held.\n */\n async readConversationMeta(id: Uint8Array): Promise<ConversationMeta | null> {\n const meta = await this.call({\n kind: \"conversationMeta\", id: this.nextId++, conv: id,\n }) as ConversationMeta | null | undefined;\n this.storeMeta(id, meta);\n return meta ?? null;\n }\n\n /**\n * Conversations detected as STRANDED during catch-up — a Commit was missed\n * and the group can no longer advance from local state, so new messages stop\n * arriving. Poll after a sync and recover each (re-Welcome / state-snapshot\n * import). Returns 16-byte conversation ids; the set self-clears as a\n * conversation makes progress or is re-joined.\n */\n async strandedConversations(): Promise<ConversationId[]> {\n return await this.call({ kind: \"strandedConversations\", id: this.nextId++ }) as ConversationId[];\n }\n\n /**\n * Conversations this device asked to leave and is still a member of:\n * the leave is OWED. The SDK holds their state and proposes the leave\n * again by itself; the host only keeps delivering their rows (live\n * frames and catch-up pages). An id leaves the list when the leave has\n * completed: this device processed its own removal and the state is\n * deleted. Sorted 16-byte conversation ids.\n */\n async conversationsLeaving(): Promise<ConversationId[]> {\n return await this.call({ kind: \"conversationsLeaving\", id: this.nextId++ }) as ConversationId[];\n }\n\n /**\n * The leaving conversations whose leave has STALLED: 8 sends of it\n * FAILED and this device is still a member, or this device can no longer\n * follow the group. Nothing more is proposed for them. The host may call\n * {@link leaveConversation} again (the count starts over) or give up with\n * {@link dropConversationLocal}, which leaves this device's leaf in the group\n * until somebody removes it. Sorted 16-byte conversation ids.\n */\n async conversationsLeaveStalled(): Promise<ConversationId[]> {\n return await this.call({ kind: \"conversationsLeaveStalled\", id: this.nextId++ }) as ConversationId[];\n }\n\n /**\n * Conversations this device was just torn down from by a SELF-RE-ADD Commit\n * — a peer's `reAdmitDevice` of this device — whose Welcome for the new\n * leaf is expected within seconds. Treat these as \"re-admission in flight\",\n * not stranded or evicted: no repair advertise, no delivery-key rotation,\n * no KeyPackage-pool replace, until the join lands or the entry ages out\n * (ten minutes). Returns 16-byte conversation ids.\n */\n async readmitPendingConversations(nowMs: number = Date.now()): Promise<ConversationId[]> {\n return await this.call({\n kind: \"readmitPendingConversations\",\n id: this.nextId++,\n nowMs,\n }) as ConversationId[];\n }\n\n /**\n * How many inbound envelopes are currently RETAINED awaiting replay, across\n * all conversations.\n *\n * An envelope that cannot be applied yet — its Welcome has not been processed,\n * or a Commit that advances the epoch is missing — is buffered and replayed on\n * join / epoch advance / catch-up sync rather than dropped (see\n * docs/INVITE_HARDENING.md §S6).\n *\n * A non-zero count means \"delivered but not yet applicable\", which is\n * materially different from \"not delivered\" and is the distinction a host\n * needs to explain a chat that looks incomplete. Expected to be 0 at rest; a\n * value that stays high points at a conversation whose handshake never\n * arrived.\n */\n async undeliverableCount(): Promise<number> {\n return await this.call({ kind: \"undeliverableCount\", id: this.nextId++ }) as number;\n }\n\n /**\n * Leave a conversation: broadcasts a self-Remove PROPOSAL (MLS forbids\n * committing your own removal: a remaining member commits it via\n * `commitPendingProposals`) and answers at once. From then on the conversation is\n * LEFT for the host: it is no longer listed, every call that names it\n * answers `UnknownConversation`, and nothing of it is surfaced again.\n *\n * Do NOT delete it locally afterwards ({@link dropConversationLocal}). The SDK keeps the\n * group's state, follows its Commits, and proposes the leave again after\n * each Commit that did not carry it (a Commit built before the proposal\n * arrived voids it), until this device is removed; then it deletes the\n * state itself. Keep delivering the conversation's rows to the client\n * while {@link conversationsLeaving} lists it. The bound is 8 FAILED sends;\n * after that {@link conversationsLeaveStalled} lists the conversation and calling\n * this again starts over.\n *\n * The group's OWNER hands over first: this call commits the successor (the\n * one every device computes when the owner's last leaf goes) and only then\n * proposes the leave. If that Commit cannot be made the call fails with the\n * Commit's error and nothing is marked: call it again. Nothing is handed\n * over when the owner's account keeps another device in the group or when\n * no other member could take over.\n */\n async leaveConversation(id: ConversationId, nowMs: number = this.now()): Promise<void> {\n await this.call({ kind: \"leaveConversation\", id: this.nextId++, conv: id, nowMs });\n }\n\n /**\n * Drop a conversation's local state with NO network side effect. Unlike\n * {@link leaveConversation} (which broadcasts a self-Remove proposal), this\n * sends nothing — use it for a group the SERVER does not back: an invite that\n * minted the MLS group locally but never completed server-side, so the backend\n * 404s `fetchSince` / 403s the member roster for it. Deletes the OpenMLS group\n * state + the on-disk snapshot rows so the dead group stops rehydrating on the\n * next restart (and re-materialising as a ghost \"New chat\"). Idempotent — safe\n * on an unknown/already-dropped id.\n */\n async dropConversationLocal(id: ConversationId): Promise<void> {\n await this.call({ kind: \"dropConversationLocal\", id: this.nextId++, conv: id });\n }\n\n /**\n * Conversations with buffered pending proposals (e.g. a peer's leave). Poll\n * after a sync; if you're the designated committer, call\n * `commitPendingProposals` to evict the leaver.\n */\n async conversationsWithPendingProposals(): Promise<ConversationId[]> {\n return await this.call({\n kind: \"conversationsWithPendingProposals\",\n id: this.nextId++,\n }) as ConversationId[];\n }\n\n /**\n * Commit buffered pending proposals for a conversation (evicts a peer who\n * left). No-op if nothing is pending; on an epoch-advanced rejection re-sync\n * (another member already committed). Call it on receipt (a batch or page\n * result's `proposalsPending`), elected with\n * {@link pendingProposalsCommitRank}. A `send` commits pending proposals\n * itself first, so a proposal never blocks a message.\n */\n async commitPendingProposals(id: ConversationId, nowMs: number = this.now()): Promise<void> {\n await this.call({ kind: \"commitPendingProposals\", id: this.nextId++, conv: id, nowMs });\n }\n\n /**\n * This device's rank in the deterministic election of who commits a\n * conversation's pending proposals: members by leaf index, excluding any\n * leaf a pending proposal removes; identical on every member. `0` means\n * commit now; rank `n` means wait `n` intervals (a few seconds each), then\n * commit if the proposals are still pending. `null` when nothing is pending\n * or this device is not eligible.\n */\n async pendingProposalsCommitRank(id: ConversationId): Promise<number | null> {\n const rank = await this.call({\n kind: \"pendingProposalsCommitRank\", id: this.nextId++, conv: id,\n }) as number | null | undefined;\n return rank ?? null;\n }\n\n /**\n * The Commits this device holds in doubt: a Commit whose send got no\n * definite answer (no response, a 5xx) is neither merged nor discarded; the\n * SDK settles it on a capped exponential backoff, and every operation in\n * that conversation fails with `commit in doubt` until it settles. Retry\n * such an operation at `nextAttemptAtMs`.\n */\n async commitsInDoubt(): Promise<CommitInDoubt[]> {\n const raw = await this.call({ kind: \"commitsInDoubt\", id: this.nextId++ }) as CommitInDoubtWire[];\n return raw.map(commitInDoubtFromWire);\n }\n\n /**\n * Member roster for a conversation, recovered locally from the MLS\n * group's leaf credentials (no network, no out-of-band message). Returns\n * one entry per device leaf — a multi-device user appears multiple times,\n * so dedup by `user_id` for a per-user roster. Empty for an unknown id.\n */\n async members(conv: ConversationId): Promise<MemberInfo[]> {\n return await this.call({ kind: \"members\", id: this.nextId++, conv }) as MemberInfo[];\n }\n\n /**\n * A conversation's credential policy (account-signed device credentials,\n * 2026-11-04): whether every leaf must carry a credential the account key signed\n * (`credentialsRequired`; a KeyPackage without one gets the add verdict\n * `credentialMissing`), the roles once the policy records them (round 2), and\n * `incapableMembers`, the accounts with a member on an app too old for this\n * group, which is what blocks the upgrade. Rejects for a conversation this client\n * does not hold. No host action is needed for the credentials themselves: the SDK\n * signs and verifies them internally.\n */\n async conversationPolicy(conv: ConversationId): Promise<ConversationPolicy> {\n return await this.call({ kind: \"conversationPolicy\", id: this.nextId++, conv }) as ConversationPolicy;\n }\n\n /**\n * Whether a Commit of THIS device that re-admits or adds the device `deviceId` of\n * the account `identity` would pass the membership rules of the conversation in\n * its state now, without building or sending anything (2026-11-18). True when\n * this device may add a leaf of that account (the owner, an admin, or a device of\n * that same account; a device of the OWNER only when this device is the owner's)\n * and, if `deviceId` holds a leaf there, may also remove that leaf. Always true in\n * a conversation without roles. Ask it BEFORE leasing a re-admission request or\n * claiming a KeyPackage: a device that is not privileged never claims another\n * account's KeyPackage. Advisory: the Commit is judged again when it is built and\n * by every receiver. Rejects for a conversation this client does not hold.\n */\n async mayReadmit(conv: ConversationId, identity: UserId, deviceId: DeviceId): Promise<boolean> {\n return await this.call({ kind: \"mayReadmit\", id: this.nextId++, conv, identity, deviceId }) as boolean;\n }\n\n /**\n * The identity (the account's user id) a KeyPackage's credential CLAIMS, read\n * without changing anything (2026-11-18, rule R13). `null` for a credential that\n * is not the project's. Rejects for bytes that are not a valid KeyPackage: the\n * checks OpenMLS runs on a KeyPackage an add carries run first (both signatures\n * under the leaf's own key, the version, the init key, the extensions against the\n * capabilities, the lifetime: an expired KeyPackage rejects).\n *\n * Before adding ANOTHER account's device, read it and compare it with the account\n * you meant to add, byte for byte; a different answer, or `null`, is enough to\n * refuse the KeyPackage the server handed out, before any Commit.\n *\n * The read runs the SAME credential verdict the add runs (the device\n * credential, then the leaf-ready check) and rejects for a claim the add\n * would refuse, so an identity answered is one the account's key vouched\n * for (rulings part 13, ruling 1; until then the answer was a bare claim).\n */\n async keyPackageIdentity(keyPackage: Uint8Array): Promise<UserId | null> {\n const identity = await this.call({\n kind: \"keyPackageIdentity\", id: this.nextId++, keyPackage,\n }) as UserId | null | undefined;\n return identity ?? null;\n }\n\n /**\n * Replace the owners this client expects first roles writes to name\n * (2026-11-04, round 2; see `ClientConfig.expectedOwners`).\n */\n async setExpectedOwners(entries: ExpectedOwner[]): Promise<void> {\n await this.call({ kind: \"setExpectedOwners\", id: this.nextId++, entries });\n }\n\n /**\n * Record a group's roles in its policy (2026-11-04, round 2): `owner` and\n * `admins` as MLS user ids (map account ids through the roster). One\n * GroupContextExtensions Commit, no Welcome, send-then-merge. Rejects with\n * \"not permitted ...\" before anything is sent when this device's role does not\n * allow the change, when a member's app is too old for roles\n * (`conversationPolicy().incapableMembers` names it), or in the DeviceGroup.\n * The same call as `getConversation(id).setConversationRoles`.\n */\n async setConversationRoles(conv: ConversationId, owner: UserId, admins: UserId[]): Promise<void> {\n await this.call({\n kind: \"setConversationRoles\", id: this.nextId++, conv, owner, admins, nowMs: this.now(),\n });\n }\n\n /**\n * Whole-account catch-up. The worker runs it one conversation at a time and\n * lets every other request (a `send` the user is waiting on, a live frame)\n * run between conversations, so a pass over many conversations never parks\n * an interactive call behind all of them. Resolves when every conversation\n * held at the start of the pass (plus any joined while it ran) has been\n * paged, with the decrypted application messages in apply order.\n */\n async syncConversations(): Promise<IncomingMessage[]> {\n return await this.call({\n kind: \"syncConversations\", id: this.nextId++, nowMs: this.now(),\n }) as IncomingMessage[];\n }\n\n /**\n * Catch-up for ONE conversation: the unit `syncConversations` is built from.\n * Use it to bring the conversation the user is looking at up to date ahead\n * of the rest (a message must be encrypted at the epoch the group is really\n * at, so a host calls this before the first send after a reconnect), or to\n * step a pass in an order of its own. Rejects with the SDK's\n * `unknown conversation` error for an id this client does not hold.\n */\n async syncConversation(id: ConversationId): Promise<IncomingMessage[]> {\n return await this.call({\n kind: \"syncConversation\", id: this.nextId++, conv: id, nowMs: this.now(),\n }) as IncomingMessage[];\n }\n\n async processEnvelope(envelope: MessageEnvelope): Promise<IncomingMessage | null> {\n return await this.call({\n kind: \"processEnvelope\", id: this.nextId++, envelope, nowMs: this.now(),\n }) as IncomingMessage | null;\n }\n\n // ------------------------ Sequenced log sync ------------------------\n // See docs/SYNC_PROTOCOL.md \"Sequenced log sync\". The subscribe path feeds\n // these itself for a transport that hands over sequenced frames; they are\n // public for hosts that drive their own socket.\n\n /**\n * Apply a batch of live frames, each with its server log position, and\n * checkpoint once per touched conversation. Per conversation: the next\n * position applies, one ahead of a hole is held and reported in `gaps`,\n * one at or below the applied position is a duplicate. Welcomes are routed\n * to a join inside the SDK (a join anchors the new conversation at the\n * Welcome's position); own-device echoes advance the position without\n * touching MLS, so pass them through. Frames at `serverSeq` 0 take the\n * legacy per-sender path.\n *\n * The decrypted messages are returned AND delivered: to `onMessageBatch`\n * handlers as one call (source `live`) when any is registered, else per\n * message to `onMessage` handlers. `onConversationUpdated` fires once per\n * entry of `updated`. A reported gap starts {@link fillGap} for that\n * conversation.\n */\n async processSequencedBatch(items: SequencedEnvelope[]): Promise<ApplyBatchResult> {\n const raw = await this.call({\n kind: \"processSequencedBatch\", id: this.nextId++,\n items: items.map(sequencedToWire), nowMs: this.now(),\n }) as ApplyBatchResultWire;\n const result = applyBatchResultFromWire(raw);\n this.fanout.deliverBatch(result.messages, { source: \"live\" });\n this.scheduleGapFills(result);\n return result;\n }\n\n /**\n * ONE page of a conversation's server log through `Transport.fetchLogSince`,\n * applied in order and checkpointed once, then whatever held frames the\n * page made contiguous. `hasMore` means step again. Same delivery as\n * {@link processSequencedBatch}, with source `page`. An ordinary request:\n * it runs ahead of any background pass, so a host can bring the open chat\n * current first. Rejects with the SDK's `unknown conversation` error for an\n * id this client does not hold; the durable cursor is unchanged on a\n * transport failure.\n */\n async syncConversationStep(id: ConversationId): Promise<SyncStepResult> {\n return this.stepConversation(id, false);\n }\n\n /**\n * Fill a conversation's gap: run {@link syncConversationStep} until\n * `hasMore` is false, single-flight per conversation, on the worker's\n * stepped lane so a send posted meanwhile goes between pages. The SDK\n * starts this itself for every gap a batch reports; hosts call it for the\n * heads a socket `resume_ack` shows above the local position. A call\n * while a fill is running rides on it (and the loop runs once more after,\n * in case the running one ended before the new gap's rows were appended).\n */\n fillGap(conversationId: ConversationId): Promise<void> {\n return this.gapFiller.fill(hexOf(conversationId), async () => {\n const page = await this.stepConversation(conversationId, true);\n return page.hasMore;\n });\n }\n\n /**\n * This device's applied position in every conversation it holds, sorted by\n * conversation id: what a host puts in its socket resume frame and\n * compares against the server's heads.\n */\n async logPositions(): Promise<LogPosition[]> {\n const raw = await this.call({ kind: \"logPositions\", id: this.nextId++ }) as LogPositionWire[];\n return raw.map(logPositionFromWire);\n }\n\n /** This device's applied position in one conversation; `null` when not held. */\n async logPosition(id: ConversationId): Promise<LogPosition | null> {\n const raw = await this.call({ kind: \"logPosition\", id: this.nextId++, conv: id }) as LogPositionWire | null;\n return raw === null || raw === undefined ? null : logPositionFromWire(raw);\n }\n\n /**\n * Anchor a conversation whose cursor predates positions at the\n * `(epoch, serverSeq)` the host had recorded for it, so an existing install\n * does not page its whole current epoch again. Resolves `false` (a no-op)\n * when the conversation is already anchored; the MLS epoch is never\n * touched. Call it once at start-up for every conversation the host's own\n * cursor store holds a position for.\n */\n async adoptLogPosition(id: ConversationId, epoch: number, serverSeq: number): Promise<boolean> {\n return await this.call({\n kind: \"adoptLogPosition\", id: this.nextId++, conv: id, epoch, serverSeq,\n }) as boolean;\n }\n\n /**\n * Conversations the server's heads show this device is behind on: not\n * anchored yet, a head above the applied position, or frames held in the\n * reorder buffer. Sorted by id. A held conversation absent from `heads` is\n * not listed.\n */\n async conversationsBehind(heads: LogHead[]): Promise<ConversationId[]> {\n return await this.call({\n kind: \"conversationsBehind\", id: this.nextId++, heads: heads.map(logHeadToWire),\n }) as ConversationId[];\n }\n\n /** Frames held in reorder buffers right now (diagnostics). */\n async heldFrameCount(): Promise<number> {\n return await this.call({ kind: \"heldFrameCount\", id: this.nextId++ }) as number;\n }\n\n /**\n * {@link joinConversation} at the Welcome's log position, so the new\n * conversation is anchored there and its first live frame applies without\n * a page. Pass `null` (or omit) when the position is unknown.\n */\n async joinConversationAt(welcome: MessageEnvelope, position: number | null = null): Promise<Conversation> {\n const idBytes = await this.call({\n kind: \"joinConversationAt\", id: this.nextId++, welcome, position, nowMs: this.now(),\n }) as ConversationId;\n return this.conversationProxy(idBytes);\n }\n\n /**\n * The Welcome routing rule at a known position: joins when the conversation\n * is unknown or held stranded and resolves to it, resolves `null` when it\n * is held healthy (a relay duplicate), rejects when the Welcome is not\n * addressed to this device.\n */\n async processWelcomeAt(welcome: MessageEnvelope, position: number | null = null): Promise<Conversation | null> {\n const idBytes = await this.call({\n kind: \"processWelcomeAt\", id: this.nextId++, welcome, position, nowMs: this.now(),\n }) as ConversationId | null;\n return idBytes === null || idBytes === undefined ? null : this.conversationProxy(idBytes);\n }\n\n /**\n * [D27] Decrypted-but-unconfirmed messages surviving in the pending-apply\n * journal, oldest first.\n *\n * The MLS ratchet advances at decrypt, BEFORE the host persists its own row\n * for the message; a crash inside that gap used to lose the message for good\n * (the server re-delivers, but MLS cannot re-decrypt a consumed generation).\n * The SDK now journals every decrypt in the same checkpoint that persists\n * the ratchet advance.\n *\n * CRASH-RECOVERY CONTRACT: on boot, BEFORE advancing any sync cursor or\n * sending any delivery ack, drain this list through the normal ingest —\n * dedup by `content_hash` / envelope identity exactly as for a redelivered\n * envelope — persist each message, then {@link confirmApplied} the drained\n * ids. Reading does not consume; unconfirmed entries survive further\n * restarts (bounded: 512 entries / 4 MiB, oldest evicted). See\n * docs/PENDING_APPLIES.md.\n */\n async pendingApplies(): Promise<PendingApply[]> {\n return await this.call({ kind: \"pendingApplies\", id: this.nextId++ }) as PendingApply[];\n }\n\n /**\n * [D27] Delete journal entries whose messages the host has durably\n * persisted (`IncomingMessage.journal_id` from live processing, or\n * `PendingApply.journal_id` from a boot drain), and checkpoint so the\n * deletion survives a reload. Unknown ids are ignored (idempotent).\n */\n async confirmApplied(journalIds: string[]): Promise<void> {\n if (journalIds.length === 0) return;\n await this.call({ kind: \"confirmApplied\", id: this.nextId++, journalIds });\n }\n\n /**\n * Build a `LinkingTicket` for a new device.\n *\n * [CR-13] `lastAppEvents` is host-supplied per-conversation \"what you missed\" data\n * (decrypted AppEvent bytes the new device will render before sync catches up).\n * Pass `[]` to suppress catchup data — the new device will see an empty conversation\n * list until normal sync runs.\n *\n * Caller is responsible for HPKE-sealing the returned ticket via\n * `MessagingClient.sealLinkingTicket` before transmitting (CR-3).\n *\n * Rejects (`Invalid`), before anything is sent, a KeyPackage that claims the\n * identity of another account this client knows: a new device links under an\n * identity of its own, or the account's.\n */\n async buildLinkingTicket(\n newDeviceId: DeviceId,\n newDeviceKp: Uint8Array,\n lastAppEvents: CatchupAppEvent[] = [],\n ): Promise<LinkingTicket> {\n return await this.call({\n kind: \"buildLinkingTicket\", id: this.nextId++,\n newDeviceId, newDeviceKp, lastAppEvents, nowMs: this.now(),\n }) as LinkingTicket;\n }\n\n /**\n * Decode a `LinkingTicket.catchup_snapshot` blob ([CR-13]).\n *\n * Pure WASM — runs in an ephemeral worker so the new device can call this before\n * `MessagingClient.init()` completes (just like `openLinkingTicket`). Returns the\n * structured view: per-conversation metas + last-known AppEvent bytes.\n *\n * Throws on malformed or oversized inputs. Empty bytes return `null` — that's the\n * \"no catchup data\" case (sender passed `[]` to buildLinkingTicket).\n */\n static async decodeCatchupSnapshot(\n snapshotBytes: Uint8Array,\n ): Promise<CatchupSnapshotView | null> {\n if (snapshotBytes.length === 0) return null;\n return MessagingClient.ephemeralWorkerCall<CatchupSnapshotView>({\n kind: \"decodeCatchupSnapshot\", id: 1, snapshotBytes,\n });\n }\n\n async consumeLinkingTicket(ticket: LinkingTicket): Promise<void> {\n await this.call({\n kind: \"consumeLinkingTicket\", id: this.nextId++, ticket, nowMs: this.now(),\n });\n }\n\n // ------------------------ Recovery (account backup) ------------------------\n // All static + stateless: they run on an ephemeral worker, so the recovery screen can\n // call them before any client is initialised. Same Argon2id/AES-256-GCM IdentityBackup\n // wire format as the iOS/Android FFI bindings — backups are portable across platforms.\n\n /** Generate a fresh 12-word BIP39 mnemonic, returned as its canonical phrase string. */\n static async generateMnemonicPhrase(): Promise<string> {\n return MessagingClient.ephemeralWorkerCall<string>({\n kind: \"generateMnemonicPhrase\", id: 1,\n });\n }\n\n /** Validate + canonicalise a user-entered phrase (BIP39 wordlist + checksum). Rejects\n * malformed input. Use on the recovery screen before calling `decryptBackup`. */\n static async normalizeMnemonicPhrase(phrase: string): Promise<string> {\n return MessagingClient.ephemeralWorkerCall<string>({\n kind: \"normalizeMnemonicPhrase\", id: 1, phrase,\n });\n }\n\n /** Encrypt an IdentityBackup for `POST /v1/recovery/blobs`. `deviceGroupSnapshot` may be\n * empty (Conservative path) or the DeviceGroup's `exportConversationStateSnapshot`. */\n static async encryptBackup(args: {\n mnemonicPhrase: string;\n accountId: Uint8Array;\n identityExport: Uint8Array;\n deviceGroupSnapshot: Uint8Array;\n /** External conversations to embed so recovery restores them offline. Pass\n * `[]` (the default) for identity + DeviceGroup only. Each `groupStateBytes`\n * is `Conversation.exportConversationStateSnapshot` output. Forward-secrecy\n * trade-off — see the SDK recovery docs. */\n conversationSnapshots?: { conversationId: Uint8Array; groupStateBytes: Uint8Array }[];\n createdAtMs: number;\n }): Promise<Uint8Array> {\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"encryptBackup\", id: 1,\n mnemonicPhrase: args.mnemonicPhrase,\n accountId: args.accountId,\n identityExport: args.identityExport,\n deviceGroupSnapshot: args.deviceGroupSnapshot,\n conversationSnapshots: args.conversationSnapshots ?? [],\n createdAtMs: args.createdAtMs,\n });\n }\n\n /** Decrypt a recovery blob from `GET /v1/recovery/blobs`. Throws on wrong mnemonic or a\n * tampered blob. The returned `identity_export` is the secret seed for `init`. */\n static async decryptBackup(\n blob: Uint8Array,\n mnemonicPhrase: string,\n ): Promise<RecoveryBackup> {\n return MessagingClient.ephemeralWorkerCall<RecoveryBackup>({\n kind: \"decryptBackup\", id: 1, blob, mnemonicPhrase,\n });\n }\n\n // ------------------------ Peer-assisted history transfer ------------------------\n // Authenticated (sign-then-encrypt) device-to-device history used by linking and\n // post-recovery peer re-add. Confidential to the recipient's ephemeral X25519 key AND\n // signed by the account identity key, so the receiver proves the sender. Plaintext-only\n // share — preserves forward secrecy (no MLS keys leave the device).\n\n /** Seal+sign a `HistoryBundle` for a recipient device. `recipientPub` (X25519, 32B) is the\n * recipient's ephemeral pubkey from the linking QR; `senderIdentitySecret` (Ed25519 seed,\n * 32B) is this account's identity key. Returns the blob to POST to /v1/history-transfers. */\n static async sealHistoryBundle(\n bundle: HistoryBundle,\n recipientPub: Uint8Array,\n senderIdentitySecret: Uint8Array,\n ): Promise<Uint8Array> {\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"sealHistoryBundle\", id: 1, bundle, recipientPub, senderIdentitySecret,\n });\n }\n\n /** Open+verify a sealed history bundle. `recipientPriv` (X25519, 32B) is this device's\n * ephemeral private key; `senderIdentityPub` (Ed25519, 32B) is the account identity pubkey\n * from the linking handshake. Throws if the signature doesn't verify. */\n static async openHistoryBundle(\n sealed: Uint8Array,\n recipientPriv: Uint8Array,\n senderIdentityPub: Uint8Array,\n ): Promise<HistoryBundle> {\n return MessagingClient.ephemeralWorkerCall<HistoryBundle>({\n kind: \"openHistoryBundle\", id: 1, sealed, recipientPriv, senderIdentityPub,\n });\n }\n\n /**\n * Post-quantum {@link sealHistoryBundle}: `recipientPub` is the recipient's\n * X-Wing public key ({@link HPKE_PQ_PUBLIC_KEY_BYTES} bytes). Wrapper `v: 2`;\n * the classical open refuses it and vice versa.\n */\n static async sealHistoryBundlePq(\n bundle: HistoryBundle,\n recipientPub: Uint8Array,\n senderIdentitySecret: Uint8Array,\n ): Promise<Uint8Array> {\n if (recipientPub.length !== HPKE_PQ_PUBLIC_KEY_BYTES) {\n throw new Error(`sealHistoryBundlePq: recipientPub must be ${HPKE_PQ_PUBLIC_KEY_BYTES} bytes`);\n }\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"sealHistoryBundlePq\", id: 1, bundle, recipientPub, senderIdentitySecret,\n });\n }\n\n /** Post-quantum {@link openHistoryBundle}: `recipientPriv` is the 32-byte X-Wing seed. */\n static async openHistoryBundlePq(\n sealed: Uint8Array,\n recipientPriv: Uint8Array,\n senderIdentityPub: Uint8Array,\n ): Promise<HistoryBundle> {\n if (recipientPriv.length !== 32) {\n throw new Error(\"openHistoryBundlePq: recipientPriv must be 32 bytes\");\n }\n return MessagingClient.ephemeralWorkerCall<HistoryBundle>({\n kind: \"openHistoryBundlePq\", id: 1, sealed, recipientPriv, senderIdentityPub,\n });\n }\n\n /**\n * Admit a freshly-linked device to every chat in `entries` — one MLS\n * Commit + Welcome per chat, with the Welcome's `?recipient=` priming\n * handled inside the SDK. This is the post-link reconciliation step\n * that follows `consumeLinkingTicket`: the new device has the\n * DeviceGroup (from the ticket) and metadata for external chats (from\n * the catchup snapshot), but its leaf is not yet in any external\n * MLS group. The host on the EXISTING device calls this once the\n * new device shows up in `/v1/auth/sessions` and has uploaded its\n * KeyPackage batch, passing one freshly-claimed KP per chat.\n *\n * Per-chat failures (stale KP, transport error, unknown chat) are\n * captured in the returned outcomes rather than aborting — one bad\n * chat shouldn't lose the user access to all the others.\n *\n * Each KeyPackage must carry this account's identity (a linked device\n * adopts it with the link): one that claims any other identity fails its\n * chat and nothing is sent there.\n */\n async admitDeviceToChats(\n deviceId: DeviceId,\n entries: AdmitChatEntry[],\n ): Promise<AdmitChatOutcome[]> {\n return await this.call({\n kind: \"admitDeviceToChats\", id: this.nextId++,\n deviceId, entries, nowMs: this.now(),\n }) as AdmitChatOutcome[];\n }\n\n /**\n * `admitDeviceToChats` with up to `concurrency` admissions in flight at\n * once. Same input, same per-chat outcomes in INPUT order whatever order\n * the sends finish in; `concurrency` 1 is exactly `admitDeviceToChats`,\n * 0 is treated as 1. Safe because every admission is its own conversation\n * (one Commit + Welcome per chat, the conversation lock is never held\n * across the send), so two admissions never touch the same epoch.\n *\n * This is the ONLY way to overlap admissions on web: the worker runs one\n * call at a time, so several `admitDeviceToChats` calls issued together\n * still run one after another. The overlap happens inside this one call.\n */\n async admitDeviceToChatsConcurrent(\n deviceId: DeviceId,\n entries: AdmitChatEntry[],\n concurrency: number,\n ): Promise<AdmitChatOutcome[]> {\n const lanes = Number.isFinite(concurrency)\n ? Math.min(0xffff_ffff, Math.max(1, Math.floor(concurrency)))\n : 1;\n return await this.call({\n kind: \"admitDeviceToChatsConcurrent\", id: this.nextId++,\n deviceId, entries, nowMs: this.now(), concurrency: lanes,\n }) as AdmitChatOutcome[];\n }\n\n /**\n * Revoke a device ([CR-2]).\n *\n * Removes `deviceId`'s leaf from every conversation where this client locally\n * tracked the device→leaf mapping (i.e. conversations where this client itself\n * admitted the device via `addMembers`, or where this client is the device being\n * revoked). The SDK has already broadcast each Commit envelope via\n * `transport.send`; the returned array is for any additional host-side handling\n * (audit logs, UI). An empty array is a valid outcome — the device wasn't locally\n * known anywhere.\n *\n * **Scope note.** Conversations where a peer admitted the device on this client's\n * behalf are silently skipped — the leaf index isn't locally known. Host can fall\n * back to `transport.discoverDevices` + a manual `remove_members(leafIndex)` for\n * those, or wait for the affected user to revoke from a device that did the admit.\n * See `docs/architecture/multi-device.md §Device removal`.\n */\n async revokeDevice(deviceId: DeviceId): Promise<MessageEnvelope[]> {\n return await this.call({\n kind: \"revokeDevice\", id: this.nextId++, deviceId, nowMs: this.now(),\n }) as MessageEnvelope[];\n }\n\n /**\n * Remove one of THIS account's devices from every group this client is in, the\n * DeviceGroup included, without stopping at a failure, and report where it stands.\n *\n * Unlike {@link revokeDevice}, the device's leaf is read from each ratchet tree (the\n * leaf whose key hashes to the id), so this reaches leaves a sibling or a peer\n * admitted. The id is the server's word that the device is this account's; outside\n * the DeviceGroup a leaf is removed only when its credential names this account, or\n * when the device was seen in the account's DeviceGroup and its credential names no\n * other account this client knows (docs/MULTIDEVICE.md, \"Which leaf\"). An id that\n * names no leaf of this account is rejected before anything is sent. Every held\n * conversation is checked: a Commit of this device in doubt is settled first, and\n * the log is read to its end before the device is reported absent (what that read\n * applies comes with the next batch or page); a conversation that failed to load\n * is a failure with reason `Unloadable`. The DeviceGroup goes first, then the\n * conversations, a few at a time, each a send-then-merge Commit. Persist the report\n * and call again until `failed` is empty and `deviceGroup !== \"failed\"`. A\n * `CommitInDoubt` reason settles on its own backoff ({@link commitsInDoubt});\n * `NotOwnAccount` and `RefusedCommit` never resolve by retrying (for\n * `RefusedCommit`, offer to recreate the conversation). Groups this device joins\n * later are checked for the device too.\n *\n * MLS only: revoke the device on the server yourself. Rejects for this device's own\n * id (leave a conversation with `leaveConversation` instead) and for a device that\n * is not this account's.\n */\n async removeDeviceEverywhere(\n deviceId: DeviceId,\n nowMs: number = this.now(),\n ): Promise<DeviceRemovalReport> {\n return await this.call({\n kind: \"removeDeviceEverywhere\", id: this.nextId++, deviceId, nowMs,\n }) as DeviceRemovalReport;\n }\n\n /**\n * Remove every other device of THIS account from every group this client is in,\n * except the devices in `keep` and this device: the \"secure my account\" sweep.\n *\n * `listed` is the server's list of this account's devices to remove (a reset's\n * `revoked_device_ids`). In the DeviceGroup every leaf but this device's and the\n * kept ones goes. Elsewhere a leaf goes when its credential names this client's\n * account (no device id has to match, so a device that moved its leaf to another\n * signature key is still reached), or when its device is in `listed` and was seen in\n * the account's DeviceGroup, whatever identity its leaf claims. A leaf the sweep\n * leaves although one of those two says it may be the account's (seen but not\n * listed, or listed but not seen) is reported: its conversation fails with\n * `NotOwnAccount`, so the report is never complete over it. Same pass and report as\n * {@link removeDeviceEverywhere}; call again until it is complete. MLS only.\n */\n async removeOwnDevicesExcept(\n keep: DeviceId[],\n listed: DeviceId[],\n nowMs: number = this.now(),\n ): Promise<DeviceRemovalReport> {\n return await this.call({\n kind: \"removeOwnDevicesExcept\", id: this.nextId++, keep, listed, nowMs,\n }) as DeviceRemovalReport;\n }\n\n /**\n * Export a portable MLS state snapshot for one conversation ([CR-7]).\n *\n * Returned bytes can be embedded in a recovery blob or shipped through a\n * linking ticket so another device of the same user identity can re-attach to\n * the group via [[importStateSnapshot]]. The bytes contain past epoch secrets;\n * never log, never persist unencrypted, wipe (`.fill(0)`) after use.\n */\n async exportConversationStateSnapshot(conv: ConversationId): Promise<Uint8Array> {\n return await this.call({\n kind: \"exportConversationStateSnapshot\", id: this.nextId++,\n conv, nowMs: this.now(),\n }) as Uint8Array;\n }\n\n /**\n * Import a `GroupStateSnapshot` from another device of the same user identity\n * ([CR-7]).\n *\n * On success, the conversation appears in [[listConversations]] and decryption\n * of subsequent peer-originated traffic works against the imported state. For\n * full multi-device participation, the recovered device SHOULD then issue an\n * MLS Update Proposal to rotate onto a fresh leaf (post-v1 follow-up — see\n * `docs/design/CR4_CR7_PERSISTENCE.md` open question #3).\n */\n async importStateSnapshot(snapshotBytes: Uint8Array): Promise<ConversationId> {\n return await this.call({\n kind: \"importStateSnapshot\", id: this.nextId++,\n snapshotBytes, nowMs: this.now(),\n }) as ConversationId;\n }\n\n /**\n * Export a derived secret from a conversation's MLS exporter ([CR-8]).\n *\n * Used to seed the ephemeral channel (`ping/ephemeral`), call-media keys\n * (`ping/calls/media/<call_id>`), and call-ephemeral framer keys\n * (`ping/calls/ephemeral/<call_id>`). The returned bytes are a secret — never log,\n * persist only encrypted, and call `bytes.fill(0)` after use to wipe the typed array.\n *\n * Same `(conversationId, current_epoch, label, context, length)` produces the same\n * bytes across every binding (Rust core, native UniFFI, WASM/JS). Cross-platform\n * byte-equality is enforced by `protocol/conformance/export_secret/`.\n */\n async exportConversationSecret(\n conv: ConversationId,\n label: string,\n context: Uint8Array,\n length: number,\n ): Promise<Uint8Array> {\n if (length <= 0 || length > 1024) {\n throw new Error(\"exportConversationSecret: length must be 1..=1024\");\n }\n return await this.call({\n kind: \"exportConversationSecret\", id: this.nextId++,\n conv, label, context, length,\n }) as Uint8Array;\n }\n\n /**\n * Subscribe to decrypted application messages, one call per message. A\n * batch or page result (the sequenced paths) is fanned out here per\n * message only while no {@link onMessageBatch} handler is registered.\n */\n onMessage(handler: (m: IncomingMessage) => void): () => void {\n return this.fanout.onMessage(handler);\n }\n\n /**\n * Subscribe to decrypted messages one BATCH at a time: one call per\n * `processSequencedBatch` result (source `live`) or per page of the server\n * log (source `page`: a gap fill, or the whole-account catch-up), so the\n * host persists the batch in one store transaction. While at least one\n * batch handler is registered, batch and page results go ONLY here, never\n * per message to `onMessage`; the legacy per-envelope path still delivers\n * per message. An empty result is not delivered.\n */\n onMessageBatch(handler: (messages: IncomingMessage[], meta: MessageBatchMeta) => void): () => void {\n return this.fanout.onMessageBatch(handler);\n }\n\n /** Fired after every state-changing event for a conversation (Commit, member changes). */\n /**\n * Fires after every conversation state change — joining via Welcome, processing a Commit,\n * etc. `sender` carries the device id of whoever triggered the event when known (e.g. the\n * inviter's device on auto-join), so the host can label peers in its UI.\n */\n onConversationUpdated(handler: (id: ConversationId, epoch: number, sender?: DeviceId) => void): () => void {\n this.conversationHandlers.add(handler);\n return () => this.conversationHandlers.delete(handler);\n }\n\n /**\n * Stop the live subscription and terminate the worker. Every call still in\n * flight rejects with a {@link MessagingClientClosedError} (reason\n * `closed`), and every later call rejects the same way instead of waiting\n * on a worker that no longer exists. Idempotent.\n */\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n this.subscription?.unsubscribe();\n this.worker.terminate();\n this.failPending(new MessagingClientClosedError(\"closed\"));\n }\n\n /** Reject every pending call with `error` and forget them. */\n private failPending(error: MessagingClientClosedError): void {\n const slots = [...this.pending.values()];\n this.pending.clear();\n for (const slot of slots) slot.reject(error);\n }\n\n // ------------------------ Internals ------------------------\n\n private conversationProxy(id: ConversationId): Conversation {\n const self = this;\n return {\n id,\n async send(plaintext) {\n // The epoch of this client's copy goes with the send. The worker\n // compares it with the epoch the message was encrypted at, so a send\n // that moved nothing reads nothing, and one that did (it settled a\n // Commit, committed pending proposals, refreshed this device's leaf)\n // brings the copy level before it resolves. A send reports no\n // conversation event of its own.\n const heldEpoch = self.metaCache.get(hex(id))?.epoch;\n return await self.call({\n kind: \"send\", id: self.nextId++, conv: id, plaintext, nowMs: self.now(),\n ...(heldEpoch !== undefined ? { heldEpoch } : {}),\n }) as MessageEnvelope;\n },\n async addMembers(entries) {\n await self.call({\n kind: \"addMembers\", id: self.nextId++, conv: id, entries, nowMs: self.now(),\n });\n },\n async addMembersWithVerdicts(entries) {\n const raw = await self.call({\n kind: \"addMembersWithVerdicts\", id: self.nextId++, conv: id, entries, nowMs: self.now(),\n }) as AddMembersReportWire;\n return addMembersReportFromWire(raw);\n },\n async reAdmitDevice(entry) {\n const replaced = await self.call({\n kind: \"reAdmitDevice\", id: self.nextId++, conv: id, entry, nowMs: self.now(),\n }) as DeviceId | null | undefined;\n return replaced ?? null;\n },\n async removeOwnOtherLeaves() {\n return await self.call({\n kind: \"removeOwnOtherLeaves\", id: self.nextId++, conv: id, nowMs: self.now(),\n }) as number;\n },\n async removeMembersByIdentity(identities) {\n return await self.call({\n kind: \"removeMembersByIdentity\", id: self.nextId++, conv: id, identities, nowMs: self.now(),\n }) as number;\n },\n async removeMembers(leaves) {\n await self.call({\n kind: \"removeMembers\", id: self.nextId++, conv: id, leaves, nowMs: self.now(),\n });\n },\n async setConversationName(name) {\n await self.call({\n kind: \"setConversationName\", id: self.nextId++, conv: id, name, nowMs: self.now(),\n });\n },\n async setConversationRoles(owner, admins) {\n await self.call({\n kind: \"setConversationRoles\", id: self.nextId++, conv: id, owner, admins, nowMs: self.now(),\n });\n },\n /**\n * The conversation's MLS GroupContext name as the group holds it now, or\n * `undefined` when it has none or the client holds no metadata for it.\n *\n * This accessor did not exist, and hosts reasonably assumed it did:\n * `getConversation(id).name` read `undefined` on every call, which\n * silently disabled any host logic driven by group state — group titles,\n * rosters, avatars and roles carried in the GroupContext all appeared\n * absent, so a group would materialise unnamed until a best-effort\n * broadcast happened to arrive.\n *\n * A getter rather than a snapshot, so it reflects the client's copy at\n * read time. That copy used to be refilled by `listConversations()`\n * only, and this answered the name from BEFORE a rename until the host\n * listed again; it is now replaced with every change the worker reports\n * (see `metaCache`).\n */\n get name(): string | undefined {\n return self.metaCache.get(hex(id))?.name ?? undefined;\n },\n /** The conversation's current MLS epoch, or `undefined` when the client\n * holds no metadata for it. */\n get epoch(): number | undefined {\n return self.metaCache.get(hex(id))?.epoch;\n },\n meta() {\n const cached = self.metaCache.get(hex(id));\n if (!cached) {\n throw new Error(\"conversation meta not loaded; call readConversationMeta(id) or listConversations() first\");\n }\n return cached;\n },\n };\n }\n\n /** Replace this client's copy of one conversation's metadata with what the\n * worker read; no metadata means the copy is dropped, so the handle answers\n * \"not held\" instead of what the group held before. */\n private storeMeta(id: ConversationId, meta: ConversationMeta | null | undefined): void {\n if (meta === null || meta === undefined) this.metaCache.delete(hex(id));\n else this.metaCache.set(hex(id), meta);\n }\n\n private call(req: Request): Promise<unknown> {\n if (this.closed) return Promise.reject(new MessagingClientClosedError(\"closed\"));\n return new Promise((resolve, reject) => {\n this.pending.set((req as { id: number }).id, { resolve, reject });\n this.worker.postMessage(req);\n });\n }\n\n /** Dispatch a worker-side transport proxy call onto the host transport.\n * `sendBatch` is the one method the worker proxy always declares but a\n * host may not implement: emulate it with sequential sends and report a\n * partial delivery with the sentinel the wasm bridge maps to\n * `TransportPartial`, so the SDK still learns the Commit landed while the\n * Welcome did not (and surfaces `WelcomeUndelivered`). The two\n * sequenced-log methods cross in the wasm's wire shape and are converted\n * to the public shape here, both ways; the worker only asks for them when\n * the host declared them at `init`. */\n private async callTransportMethod(method: string, args: unknown[]): Promise<unknown> {\n const t = this.transport as unknown as Record<string, ((...a: unknown[]) => unknown) | undefined>;\n if (method === \"sendBatch\" && typeof t.sendBatch !== \"function\") {\n await emulateSendBatch(this.transport, (args[0] ?? []) as MessageEnvelope[]);\n return undefined;\n }\n if (method === \"fetchLogSince\") {\n if (typeof this.transport.fetchLogSince !== \"function\") return null;\n const [position, limit] = args as [LogPositionWire, number];\n const rows = await this.transport.fetchLogSince(logPositionFromWire(position), limit);\n return rows === null || rows === undefined ? null : rows.map(sequencedToWire);\n }\n if (method === \"fetchLogHeads\") {\n if (typeof this.transport.fetchLogHeads !== \"function\") return null;\n const heads = await this.transport.fetchLogHeads();\n return heads === null || heads === undefined ? null : heads.map(logHeadToWire);\n }\n return await t[method]?.(...args);\n }\n\n private async handleWorker(msg: Response) {\n switch (msg.kind) {\n case \"result\": {\n const slot = this.pending.get(msg.id);\n if (!slot) return;\n this.pending.delete(msg.id);\n msg.ok ? slot.resolve(msg.value) : slot.reject(errorFromWorker(msg.error));\n return;\n }\n case \"event.message\": {\n this.fanout.deliverOne(msg.msg);\n return;\n }\n case \"event.batch\": {\n this.fanout.deliverBatch(msg.messages, { source: msg.source });\n return;\n }\n case \"event.conversation\": {\n // The metadata FIRST: a listener that reads the conversation handle\n // must read what the group holds now, never what it held before the\n // change it is being told about.\n this.storeMeta(msg.id, msg.meta);\n // Guarded like the message handlers: one throwing handler must not\n // starve the handlers registered after it.\n for (const h of this.conversationHandlers) {\n try {\n h(msg.id, msg.epoch, msg.sender);\n } catch (e) {\n if (typeof console !== \"undefined\") {\n console.debug(\"[ping-sdk] onConversationUpdated handler threw:\", errorKind(e));\n }\n }\n }\n return;\n }\n case \"cache.conversations\": {\n // Upkeep with no listener behind it; the worker posts it before the\n // `result` of the request that caused it.\n for (const meta of msg.held) this.storeMeta(meta.id, meta);\n for (const id of msg.dropped) this.storeMeta(id, null);\n return;\n }\n case \"storage.call\": {\n try {\n // A method the host storage does not have is an ERROR, never an\n // `undefined` success: the worker only calls the optional methods\n // it was told exist, so a miss means the advertised features and\n // this storage disagree, and answering `undefined` would turn a\n // skipped `applyBatch` into an acknowledged write.\n const method = (this.storage as unknown as Record<string, unknown>)[msg.method];\n if (typeof method !== \"function\") {\n throw new Error(`storage.${String(msg.method)} is not implemented by the host storage`);\n }\n const v = await (method as (...a: unknown[]) => unknown).apply(this.storage, msg.args);\n this.worker.postMessage({ kind: \"storage.reply\", id: msg.id, ok: true, value: v } as Request);\n } catch (e) {\n this.worker.postMessage({\n kind: \"storage.reply\", id: msg.id, ok: false, error: String(e),\n } as Request);\n }\n return;\n }\n case \"transport.call\": {\n try {\n const v = await this.callTransportMethod(msg.method, msg.args);\n this.worker.postMessage({ kind: \"transport.reply\", id: msg.id, ok: true, value: v } as Request);\n } catch (e) {\n this.worker.postMessage({\n kind: \"transport.reply\", id: msg.id, ok: false, error: describeTransportError(e),\n } as Request);\n }\n return;\n }\n }\n }\n}\n\n/** A stateless SDK call ran on a one-shot worker that failed before it could answer:\n * the worker could not be created (`spawn`), the request could not be posted (`post`),\n * the worker script failed to load, import or run (`error`), or its reply could not be\n * deserialised (`messageerror`). The worker has already been terminated; the event's\n * details (which may name a script URL) are not carried. */\nexport class EphemeralWorkerError extends Error {\n readonly reason: \"spawn\" | \"post\" | \"error\" | \"messageerror\";\n constructor(reason: \"spawn\" | \"post\" | \"error\" | \"messageerror\") {\n super(`ping-openmls-sdk: one-shot worker failed (${reason})`);\n this.name = \"EphemeralWorkerError\";\n this.reason = reason;\n }\n}\n\n/**\n * The typed rejection every call still pending gets when the client is\n * closed (`reason: \"closed\"`) or the worker reported an uncaught error\n * (`reason: \"worker-error\"`), and what every call made after `close()`\n * rejects with. Before this, `close()` terminated the worker and left those\n * promises pending forever.\n */\nexport class MessagingClientClosedError extends Error {\n readonly reason: \"closed\" | \"worker-error\";\n constructor(reason: \"closed\" | \"worker-error\") {\n super(reason === \"closed\" ? \"MessagingClient is closed\" : \"MessagingClient worker error\");\n this.name = \"MessagingClientClosedError\";\n this.reason = reason;\n }\n}\n\n/** Sentinel prefix for an emulated batch that only partially landed. Kept in\n * lockstep with `core/ping-wasm/src/lib.rs` (`BATCH_PARTIAL_PREFIX`). */\n/** Width of an X-Wing (post-quantum HPKE) public key, `hpkeGenerateKeypairPq().publicKey`. */\nexport const HPKE_PQ_PUBLIC_KEY_BYTES = 1216;\n/** Width of the KEM encapsulation at the front of a post-quantum raw envelope. */\nexport const HPKE_PQ_ENC_BYTES = 1120;\n\nexport const BATCH_PARTIAL_PREFIX = \"batch partial after \";\n\n/** How the rejection of a call reads when the conversation's roles do not\n * permit it (the core's `Error::NotPermitted`): this prefix, then the rule\n * that was broken (fixed text, no id, safe to log). No other failure starts\n * this way (a malformed request reads `invalid input: ...`). Kept in\n * lockstep with the core's display (`stringify` in\n * `core/ping-wasm/src/lib.rs`, pinned by `ping-core/tests/typed_errors.rs`). */\nexport const NOT_PERMITTED_PREFIX = \"not permitted: \";\n\n/** The typed role refusal: what a `MessagingClient` call rejects with when\n * the encrypted group's roles do not permit it. Raised before anything was\n * built or sent, and final until the roles or the membership change: drop\n * the intent (never retry or queue it), read `conversationPolicy()` again.\n * A join from a Welcome and `importStateSnapshot` reject with it too, for a\n * state that names an owner or an admin without a verified leaf: drop that\n * invitation, or skip that conversation of the import. `message` stays the\n * core's text, so `isNotPermittedError` also reads a copy that lost its\n * class (a structured clone, another realm). */\nexport class NotPermittedError extends Error {\n /** The rule that was broken: fixed text, no id, safe to log. */\n readonly rule: string;\n constructor(message: string) {\n super(message);\n this.name = \"NotPermittedError\";\n this.rule = message.startsWith(NOT_PERMITTED_PREFIX)\n ? message.slice(NOT_PERMITTED_PREFIX.length)\n : message;\n }\n}\n\n/** The rule a role refusal names, or `null` when `e` is any other failure.\n * Accepts the rejection itself, any object with a `message`, or the text. */\nexport function notPermittedRule(e: unknown): string | null {\n const text = typeof e === \"string\"\n ? e\n : e !== null && typeof e === \"object\" && typeof (e as { message?: unknown }).message === \"string\"\n ? (e as { message: string }).message\n : null;\n return text !== null && text.startsWith(NOT_PERMITTED_PREFIX)\n ? text.slice(NOT_PERMITTED_PREFIX.length)\n : null;\n}\n\n/** True when `e` is the typed role refusal (\"the encrypted group's roles do\n * not permit this\") and no other failure. */\nexport function isNotPermittedError(e: unknown): boolean {\n return notPermittedRule(e) !== null;\n}\n\n/** How the rejection of a call reads when an envelope names a sender device\n * other than the one that sealed its MLS message (the core's\n * `Error::SenderMismatch`). No other failure starts this way. Kept in\n * lockstep with the core's display (`stringify` in\n * `core/ping-wasm/src/lib.rs`, pinned by `ping-core/tests/typed_errors.rs`). */\nexport const SENDER_MISMATCH_PREFIX = \"sender mismatch: \";\n\n/** The typed refusal of an envelope whose `senderDevice` is not the device\n * that sealed its message (checked after decryption against the sender\n * leaf's signature key). The message was not delivered, a Commit in it was\n * not applied, and no dedupe or ordering mark moved: the named device's own\n * messages are delivered as before. Drop the envelope, never retry it, show\n * nothing. `message` stays the core's text, so `isSenderMismatchError` also\n * reads a copy that lost its class. */\nexport class SenderMismatchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SenderMismatchError\";\n }\n}\n\n/** True when `e` is the typed sender refusal and no other failure. Accepts\n * the rejection itself, any object with a `message`, or the text. */\nexport function isSenderMismatchError(e: unknown): boolean {\n const text = typeof e === \"string\"\n ? e\n : e !== null && typeof e === \"object\" && typeof (e as { message?: unknown }).message === \"string\"\n ? (e as { message: string }).message\n : null;\n return text !== null && text.startsWith(SENDER_MISMATCH_PREFIX);\n}\n\n/** A worker's rejection text as the error a caller catches: the typed role\n * refusal or the typed sender refusal when it is one, a plain `Error`\n * otherwise. */\nfunction errorFromWorker(text: string): Error {\n if (text.startsWith(NOT_PERMITTED_PREFIX)) return new NotPermittedError(text);\n if (text.startsWith(SENDER_MISMATCH_PREFIX)) return new SenderMismatchError(text);\n return new Error(text);\n}\n\n/** Sequential stand-in for a host transport without `sendBatch`: sends in\n * order and reports a failure after at least one success with the partial\n * sentinel, so the SDK learns the Commit landed while the Welcome did not. */\nexport async function emulateSendBatch(\n transport: Pick<Transport, \"send\">,\n envelopes: MessageEnvelope[],\n): Promise<void> {\n let delivered = 0;\n for (const envelope of envelopes) {\n try {\n await transport.send(envelope);\n } catch (e) {\n if (delivered === 0) throw e;\n throw new Error(`${BATCH_PARTIAL_PREFIX}${delivered}: ${describeTransportError(e)}`);\n }\n delivered += 1;\n }\n}\n\n/** Serialise a transport rejection for the worker so the wasm bridge can\n * still classify it: the HTTP status survives as `http <status>` in the\n * text (a definite 4xx lets the SDK roll a staged Commit back), and any\n * server error code rides along for diagnostics. */\nexport function describeTransportError(e: unknown): string {\n if (e && typeof e === \"object\") {\n const rec = e as { status?: unknown; serverError?: unknown; message?: unknown; name?: unknown };\n const status = typeof rec.status === \"number\" ? rec.status : undefined;\n const message = typeof rec.message === \"string\" ? rec.message : String(e);\n if (message.startsWith(BATCH_PARTIAL_PREFIX)) return message;\n const parts: string[] = [];\n if (typeof rec.name === \"string\" && rec.name) parts.push(`${rec.name}:`);\n parts.push(message);\n if (status !== undefined && !message.includes(`http ${status}`)) parts.push(`(http ${status})`);\n if (typeof rec.serverError === \"string\" && rec.serverError) parts.push(`[${rec.serverError}]`);\n return parts.join(\" \");\n }\n return String(e);\n}\n\nfunction hex(b: Uint8Array): string {\n let s = \"\";\n for (const v of b) s += v.toString(16).padStart(2, \"0\");\n return s;\n}\n\n/**\n * Lowercase-hex of an id, used as a Map key. Conversation ids are 16 bytes, so\n * this is a fixed 32-char string — cheap enough to compute on every inbound\n * frame, and it gives the per-conversation dispatch chain a stable key that\n * `Uint8Array` identity cannot (two decodes of the same id are different\n * objects).\n */\nfunction hexOf(bytes: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < bytes.length; i++) out += bytes[i]!.toString(16).padStart(2, \"0\");\n return out;\n}\n\nfunction sameBytesU8(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n}\n"],"mappings":";AAuBO,SAAS,UAAU,GAAoB;AAC5C,MAAI,aAAa,MAAO,QAAO,EAAE;AACjC,SAAO,OAAO;AAChB;AAEO,IAAM,gBAAN,MAAoB;AAAA,EACR,kBAAkB,oBAAI,IAAoB;AAAA,EAC1C,gBAAgB,oBAAI,IAAkB;AAAA,EAEvD,UAAU,SAAqC;AAC7C,SAAK,gBAAgB,IAAI,OAAO;AAChC,WAAO,MAAM,KAAK,gBAAgB,OAAO,OAAO;AAAA,EAClD;AAAA,EAEA,eAAe,SAA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