@ping-app/ping-openmls-sdk 0.10.5 → 0.10.7

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../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/account-setup.ts","../src/wasm-memory.ts","../src/notification-preview.ts"],"sourcesContent":["// 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 BackupCheckFailure, BackupPhraseCheck,\n CatchupAppEvent, CatchupSnapshotView, CommitInDoubt,\n ConversationId, ConversationMeta, ConversationPolicy, DeviceId, DeviceLinkApproval, DeviceLinkPossession,\n ExpectedOwner, ExportedSecret,\n DeviceReauthProof, DeviceRemovalReport, IncomingMessage,\n HistoryBundle, HistoryDeliveryKeyStatement, HistoryShipDecision, OpenedHistory, LogHead, LogHole, LogPosition, MemberInfo, MessageBatchMeta, PendingApply,\n KeyPackageEntry, LinkGeneration, LinkedDevice, LinkingTicketV3, MessageEnvelope, 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 LogHoleWire,\n type LogPositionWire,\n logHeadToWire,\n logHoleFromWire,\n logPositionFromWire,\n sequencedToWire,\n type SyncStepResultWire,\n syncStepResultFromWire,\n} from \"./sequenced\";\n\nexport type * from \"./types\";\nimport type { FetchedSealedGroupInfo, SelfAdmitManyEntry, SelfAdmitResult } from \"./types\";\nimport type { StateRefreshed as StateRefreshedResult } from \"./account-setup\";\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\";\nexport { AccountSetup, AccountSetupClosedError, accountRefusalCode } from \"./account-setup\";\nimport { rotationAnswerFields } from \"./account-setup\";\nexport type { AdoptedGeneration, RotationBuild, RotationKeptRefusal, RotationPlan, RotationStartDevice } from \"./account-setup\";\nimport type {\n AdoptedGeneration as AdoptedGenerationResult,\n RotationBuild as RotationBuildResult,\n RotationAnswer as RotationAnswerInput,\n RotationOutcome as RotationOutcomeResult,\n RotationPlan as RotationPlanResult,\n RotationStart as RotationStartInput,\n RotationStartDevice as RotationStartDeviceInput,\n SealingStatement as SealingStatementInput,\n} from \"./account-setup\";\nexport type {\n AccountBackupParts,\n AccountSetupConfig,\n NewAccountDevice,\n PendingRootStatus,\n PendingRotation,\n RestoreJoined,\n RestoreOpened,\n RotationAnswer,\n RotationBuilt,\n RotationOutcome,\n RotationPhase,\n RotationRecordState,\n RotationRequest,\n RotationStart,\n SealingStatement,\n StateOpened,\n StateRefreshed,\n} from \"./account-setup\";\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\n/**\n * What `MessagingClient.initFromDeviceRecord` takes: the `ClientConfig`. It\n * carries no account identity: the device record in `storage` (written by\n * account set-up, a link or a restore) says which account and device this is.\n * `deviceSigningSecretKey`, when given, is the key the host kept from the\n * call that made the device, and must be the record's own. (The name is kept\n * from the time a second start took an identity export; that start left\n * every binding on 2026-11-28.)\n */\nexport type DeviceRecordClientConfig = ClientConfig;\n\n/**\n * What the start of a NEW device's link takes\n * ({@link MessagingClient.beginDeviceLink}). No key: the SDK draws the device\n * key itself.\n */\nexport type DeviceLinkClientConfig = Omit<ClientConfig, \"deviceSigningSecretKey\" | \"expectedOwners\">;\n\n/**\n * What {@link MessagingClient.beginDeviceLink} answers. `client` is the\n * staging client: it completes the link (`completeDeviceLink`) and is then\n * closed. `deviceSigningSecretKey` and `hpkeSecretKey` are SECRETS, handed\n * over once: keep them where the app keeps a device key. Publish, and show\n * the commitment of, exactly `payload`.\n */\nexport interface DeviceLinkBegun {\n client: MessagingClient;\n payload: Uint8Array;\n deviceId: Uint8Array;\n deviceSigningSecretKey: Uint8Array;\n hpkeSecretKey: Uint8Array;\n}\n\nexport interface ClientConfig {\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 * `true` ONLY for the client of the tab the person is using (ruling V244).\n * It allows this client's Worker to BUILD a rotation\n * (`rotateGenerationWithPending`, `rotateGenerationWithBackup`), the two\n * calls for which the Worker opens the account's root. Leave it out for\n * every background session's client: such a Worker never builds a rotation\n * (`account refused: background-worker`). Only the value `true` counts.\n */\n tabClient?: boolean;\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: DeviceRecordClientConfig, 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 /**\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 /** 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 // ---- The link handshake commitment (2026-11-25) ----\n //\n // REMOVED 2026-11-28 (ruling V576): `openLinkingTicket`, `openLinkingTicketPq`,\n // `sealLinkingTicketFor`, `buildLinkingTicketFor`, `consumeLinkingTicket` and the type\n // `LinkingTicket`. A ticket of version 1 or 2 carries a binding an ACCOUNT KEY signs;\n // the only ticket is version 3 (`buildLinkingTicketV3For`, `completeDeviceLink`).\n // REMOVED 2026-11-25 (ruling ID15): `sealLinkingTicket`, `sealLinkingTicketPq`,\n // `signDeviceLinkApproval` (a raw key) and `buildLinkingTicket(deviceId,\n // keyPackage)`. Every call below takes the handshake payload the relay returned\n // together with what THIS device was shown (`expected`) and verifies inside the\n // call, so nothing can be approved for, built for or sealed to a handshake that\n // was not verified. `hpkeSeal*` refuse the infos `ping/link/*` and\n // `ping/link-auth/*`. Host notes: docs-site/api.md, \"Device link commitment\".\n\n /**\n * The commitment of a handshake payload: what a NEW device shows for the exact\n * bytes it publishes ({@link MessagingClient.linkHandshakePayload}). `qrText` is\n * `{\"v\":3,\"h\":\"<base64url(commitment)>\"}`; `code` is the 20 characters the relay\n * indexes; `codeDisplay` is the same in five groups of four.\n */\n static async linkCommitment(payload: Uint8Array): Promise<LinkCommitment> {\n const parts = await MessagingClient.ephemeralWorkerCall<[Uint8Array, string, string, string]>({\n kind: \"linkCommitment\", id: 1, payload,\n });\n return { commitment: parts[0], qrText: parts[1], code: parts[2], codeDisplay: parts[3] };\n }\n\n /**\n * THE normaliser of a typed link code. Hand it what the person typed; send the\n * relay, and pass to the calls below, only the 20 characters it returns. No host\n * normalises a code itself. Rejects anything that is not a code.\n */\n static async normalizeLinkCode(typed: string): Promise<string> {\n return MessagingClient.ephemeralWorkerCall<string>({ kind: \"normalizeLinkCode\", id: 1, typed });\n }\n\n /** The 32 bytes of a QR text `{\"v\":3,\"h\":\"...\"}`. Rejects any other shape. */\n static async linkQrCommitment(qrText: string): Promise<Uint8Array> {\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({ kind: \"linkQrCommitment\", id: 1, qrText });\n }\n\n /**\n * Verify the handshake payload a relay returned against what this device was\n * shown. Call it BEFORE anything else is done with the handshake. Rejects with\n * {@link LinkCommitmentMismatchError} when the payload is not the committed one:\n * send nothing, open no approval session, ask the person to try again.\n */\n static async verifyLinkHandshake(\n payload: Uint8Array,\n expected: LinkExpected,\n ): Promise<VerifiedLinkHandshakeInfo> {\n const all = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"verifyLinkHandshake\", id: 1, payload, ...linkExpectedFields(expected),\n });\n if (all.length !== 97) {\n throw new Error(\"verifyLinkHandshake: expected 97 bytes\");\n }\n return {\n deviceId: all.slice(0, 32),\n deviceSigningPubkey: all.slice(32, 64),\n commitment: all.slice(64, 96),\n verifiedByQr: all[96] === 1,\n };\n }\n\n /**\n * HPKE-seal the device-linking auth envelope (`ping/link-auth/v2`) to the\n * X-Wing key of the handshake `payload`, verified inside the call.\n */\n static async sealLinkAuthFor(\n plaintext: Uint8Array,\n payload: Uint8Array,\n expected: LinkExpected,\n ): Promise<Uint8Array> {\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"sealLinkAuthFor\", id: 1, plaintext, payload, ...linkExpectedFields(expected),\n });\n }\n\n /**\n * Link verification v2, on the EXISTING device: approve the new device of the\n * handshake `payload`, verified inside the call, on one server link session with\n * this device's signing key. The signed bytes are those of\n * docs/DEVICE_LINK_V2_VECTORS.md; the key that is approved is the handshake's\n * device signing key and cannot be passed separately. `audience` as for\n * {@link signDeviceReauth}. Runs in an ephemeral worker.\n */\n static async signDeviceLinkApprovalFor(params: {\n deviceSigningSecretKey: Uint8Array;\n approvalSessionId: Uint8Array;\n accountId: Uint8Array;\n payload: Uint8Array;\n expected: LinkExpected;\n audience: string;\n }): Promise<DeviceLinkApproval> {\n const { deviceSigningSecretKey, approvalSessionId, accountId, payload, expected, audience } =\n params;\n if (deviceSigningSecretKey.length !== 32) {\n throw new Error(\"signDeviceLinkApprovalFor: deviceSigningSecretKey must be 32 bytes\");\n }\n if (approvalSessionId.length !== 16) {\n throw new Error(\"signDeviceLinkApprovalFor: approvalSessionId must be 16 bytes\");\n }\n if (accountId.length !== 16) {\n throw new Error(\"signDeviceLinkApprovalFor: accountId must be 16 bytes\");\n }\n const all = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"signDeviceLinkApprovalFor\", id: 1,\n deviceSigningSecretKey, approvalSessionId, accountId, payload,\n ...linkExpectedFields(expected), audience,\n });\n if (all.length !== 128) {\n throw new Error(\"signDeviceLinkApprovalFor: 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 a static call 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 /**\n * Start the client FROM THE DEVICE RECORD: the ONE start of a client (after\n * `AccountSetup`, a link or a restore wrote the record into `cfg.storage`).\n * The client holds no account key: every leaf and KeyPackage it builds\n * carries the one credential the device holds (`heldCredential()`). No call\n * starts a client from an account identity and none hands one out (the\n * start from an identity export, `generateIdentity` and `exportIdentity`\n * left every binding on 2026-11-28). Rejects when the\n * store holds no device record, or when `cfg.deviceSigningSecretKey` is not\n * the record's own device key.\n */\n static async initFromDeviceRecord(cfg: DeviceRecordClientConfig): Promise<MessagingClient> {\n return (await MessagingClient.start(cfg, \"record\")).client;\n }\n\n /**\n * Begin a link on a NEW device, in one call: the SDK draws the device key\n * (no field of `cfg` is a key), records \"link begun\" in `cfg.storage`,\n * starts the staging client and builds the handshake payload. A repeat\n * after a reload answers the SAME key and the SAME handshake. Rejects with\n * `account refused: account-already-set-up` over a store that already holds\n * a device.\n */\n static async beginDeviceLink(cfg: DeviceLinkClientConfig): Promise<DeviceLinkBegun> {\n const { client, answer } = await MessagingClient.start(cfg, \"link\");\n const begun = answer as Omit<DeviceLinkBegun, \"client\">;\n return { client, ...begun };\n }\n\n /**\n * HPKE-seal a version 3 ticket to the X-Wing key of the handshake `payload`,\n * verified inside the call (`ping/link/v2`). Rejects a ticket that was built\n * for another device than the handshake's.\n */\n static async sealLinkingTicketV3For(\n ticket: LinkingTicketV3,\n payload: Uint8Array,\n expected: LinkExpected,\n ): Promise<Uint8Array> {\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"sealLinkingTicketV3For\", id: 1, ticket, payload, ...linkExpectedFields(expected),\n });\n }\n\n /**\n * HPKE-open a sealed version 3 ticket with the new device's X-Wing seed.\n * NOT yet verified: `completeDeviceLink` runs every check.\n */\n static async openLinkingTicketV3(\n sealed: Uint8Array,\n newDevicePriv: Uint8Array,\n ): Promise<LinkingTicketV3> {\n return MessagingClient.ephemeralWorkerCall<LinkingTicketV3>({\n kind: \"openLinkingTicketV3\", id: 1, sealed, newDevicePriv,\n });\n }\n\n private static async start(\n cfg: DeviceRecordClientConfig,\n mode: \"record\" | \"link\",\n ): Promise<{ client: MessagingClient; answer: unknown }> {\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 sendExternalCommit: typeof cfg.transport.sendExternalCommit === \"function\",\n fetchSelfAdmissionStates: typeof cfg.transport.fetchSelfAdmissionStates === \"function\",\n fetchSealedGroupInfos: typeof cfg.transport.fetchSealedGroupInfos === \"function\",\n sendExternalCommits: typeof cfg.transport.sendExternalCommits === \"function\",\n fetchSealingStatements: typeof cfg.transport.fetchSealingStatements === \"function\",\n publishSealedGroupInfo: typeof cfg.transport.publishSealedGroupInfo === \"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 const first = {\n id: client.nextId++,\n deviceLabel: cfg.deviceLabel,\n nowMs: client.now(),\n ...(cfg.deviceSigningSecretKey\n ? { deviceSigningSecretKey: cfg.deviceSigningSecretKey }\n : {}),\n ...(cfg.expectedOwners ? { expectedOwners: cfg.expectedOwners } : {}),\n // Handed on as given: the Worker counts only the value `true`.\n ...(cfg.tabClient !== undefined ? { tabClient: cfg.tabClient } : {}),\n transportFeatures,\n storageFeatures,\n };\n const answer = await client.call(\n mode === \"link\"\n ? {\n kind: \"beginDeviceLink\",\n id: first.id, deviceLabel: first.deviceLabel, nowMs: first.nowMs,\n transportFeatures, storageFeatures,\n }\n : { kind: \"initFromDeviceRecord\", ...first },\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, answer };\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 async deviceId(): Promise<DeviceId> {\n return await this.call({ kind: \"deviceId\", id: this.nextId++ }) as DeviceId;\n }\n\n /** The credential this device HOLDS for itself (version 2), which every\n * leaf and KeyPackage it builds carries. A public value. Never absent\n * (2026-11-28): every client starts from a device record. Rejects with\n * `NoDeviceRecord` on a read-only client, which holds no credential. */\n async heldCredential(): Promise<Uint8Array> {\n return await this.call({ kind: \"heldCredential\", id: this.nextId++ }) as Uint8Array;\n }\n\n /** The generation of the held credential. Rejects as `heldCredential` does. */\n async heldGeneration(): Promise<number> {\n return await this.call({ kind: \"heldGeneration\", id: this.nextId++ }) as number;\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 /**\n * SELF-ADMISSION: enter `conversationId` by this device's own act, from\n * what the delivery service returned for it (the sealed GroupInfo and\n * this account's wrap). Every refusal is a VALUE (`kind: \"refused\"`);\n * while the SDK is built without self-admission the answer is `refusal:\n * \"notCompiled\"` and nothing was touched. The client reads the anchor\n * record its device holds by itself, before the join. Rejects only for an\n * id of the wrong length.\n *\n * THE MESSAGES OF A JOIN. `joined` carries `replayed`: messages of this\n * conversation that waited for the join. Show them, save them and\n * confirm them (`confirmApplied`) exactly as the messages of a batch\n * (also for every `joined` entry of `selfAdmitMany`). This client\n * DELIVERS them to its observers by itself (source `live`), as it\n * delivers the messages of `processSequencedBatch`; Swift and Kotlin\n * return them, as they return a batch's messages.\n */\n async selfAdmit(conversationId: ConversationId, fetched: FetchedSealedGroupInfo): Promise<SelfAdmitResult> {\n const result = await this.call({\n kind: \"selfAdmit\", id: this.nextId++, conv: conversationId,\n fetched: {\n blob: fetched.blob, wrap: fetched.wrap, wrapCount: fetched.wrapCount,\n ...(fetched.currentEpoch === undefined ? {} : { currentEpoch: fetched.currentEpoch }),\n },\n nowMs: this.now(),\n }) as SelfAdmitResult;\n if (result.kind === \"joined\") {\n holeOfJoin(result);\n this.fanout.deliverBatch(result.replayed, { source: \"live\" });\n }\n return result;\n }\n\n /**\n * Enter MANY conversations with few requests (the transport's\n * `fetchSelfAdmissionStates`, `fetchSealedGroupInfos` and\n * `sendExternalCommits`): `first` (the conversation on screen) goes to\n * the head, then the order given, each once. One entry per conversation,\n * each judged and answered alone. A conversation this device holds and is\n * not stranded in answers `alreadyHeld` with no request. Nothing is\n * polled: call again when the account event of a publication arrives.\n */\n async selfAdmitMany(\n conversations: ConversationId[], opts: { first?: ConversationId } = {},\n ): Promise<SelfAdmitManyEntry[]> {\n const entries = await this.call({\n kind: \"selfAdmitMany\", id: this.nextId++,\n ...(opts.first === undefined ? {} : { first: opts.first }),\n conversations, nowMs: this.now(),\n }) as SelfAdmitManyEntry[];\n for (const entry of entries) {\n if (entry.result.kind === \"joined\") {\n holeOfJoin(entry.result);\n this.fanout.deliverBatch(entry.result.replayed, { source: \"live\" });\n }\n }\n return entries;\n }\n\n /**\n * THE ONE CALL A HOST REMEMBERS FOR THE ANCHOR RECORD: write the account's\n * state part from the RUNNING client. The record of who may sign a\n * GroupInfo a restoring device enters by is rebuilt from this client's\n * own conversations first (at every call; the SDK also rebuilds it\n * by itself during `processSequencedBatch` and at every rotation), and\n * the part carries it. The host stores the part where it stores every\n * state part. (`AccountSetup.refreshStateBackup` takes a store and\n * carries the record as it was last built.)\n *\n * A LINKED device owes ONE look first: until `AccountSetup.openStateBackup`\n * ran once on it, this rejects with the code `state-part-look-owed` (so does\n * a rotation that keeps the device's key). Pass an EMPTY part there when the\n * service serves none; whatever it answers, the look is made.\n */\n async refreshStateBackup(args: { accountId: Uint8Array; hostState: Uint8Array }): Promise<StateRefreshedResult> {\n return await this.call({\n kind: \"clientRefreshStateBackup\", id: this.nextId++,\n accountId: args.accountId, hostState: args.hostState, nowMs: this.now(),\n }) as StateRefreshedResult;\n }\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 * The holes of one conversation's log on this device, lowest position\n * first: every position at or below the stored position that was not\n * applied, with the reason and the content hashes the envelopes named.\n * `kept: true` entries are rows the SDK still holds and retries by itself.\n */\n async logHoles(id: ConversationId): Promise<LogHole[]> {\n const raw = await this.call({ kind: \"logHoles\", id: this.nextId++, conv: id }) as LogHoleWire[];\n return raw.map(logHoleFromWire);\n }\n\n /**\n * The host filled `fromServerSeq..toServerSeq` (inclusive) of a\n * conversation from elsewhere (the account's other device): take the range\n * out of the recorded holes. Resolves `true` when a recorded hole changed.\n */\n async resolveLogHole(id: ConversationId, fromServerSeq: number, toServerSeq: number): Promise<boolean> {\n return await this.call({\n kind: \"resolveLogHole\", id: this.nextId++, conv: id, fromServerSeq, toServerSeq,\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 * The version 3 handshake payload this NEW device publishes: its own signing key,\n * the id derived from it, `hpkePublicKey` (X-Wing, 1216 bytes) and a KeyPackage it\n * just made. Show {@link MessagingClient.linkCommitment} of exactly these bytes and\n * publish exactly these bytes; nobody re-serialises them.\n */\n async linkHandshakePayload(hpkePublicKey: Uint8Array, keyPackage: Uint8Array): Promise<Uint8Array> {\n return await this.call({\n kind: \"linkHandshakePayload\", id: this.nextId++, hpkePublicKey, keyPackage,\n }) as Uint8Array;\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 /**\n * The linking ticket, version 3, for the handshake `payload`, verified\n * inside the call: for a client started from a device record. The new\n * device's credential is signed by THIS device's key. Rejects when this\n * device's own chain is at its limit (show the \"link from another device\"\n * copy) or it holds no device record. Seal it with\n * {@link MessagingClient.sealLinkingTicketV3For} and the SAME payload and\n * `expected`.\n */\n async buildLinkingTicketV3For(\n payload: Uint8Array,\n expected: LinkExpected,\n lastAppEvents: CatchupAppEvent[] = [],\n ): Promise<LinkingTicketV3> {\n return await this.call({\n kind: \"buildLinkingTicketV3For\", id: this.nextId++,\n payload, ...linkExpectedFields(expected), lastAppEvents, nowMs: this.now(),\n }) as LinkingTicketV3;\n }\n\n /**\n * The generation and its secret for the link-auth envelope, version 6:\n * answered only for a handshake whose version 3 ticket this client built\n * since it started.\n */\n async linkGenerationFor(payload: Uint8Array, expected: LinkExpected): Promise<LinkGeneration> {\n return await this.call({\n kind: \"linkGenerationFor\", id: this.nextId++, payload, ...linkExpectedFields(expected),\n }) as LinkGeneration;\n }\n\n /**\n * Complete the link on the NEW device, on the staging client of\n * {@link MessagingClient.beginDeviceLink}: every check of the ticket and of\n * the envelope's two values, then the DeviceGroup, then the device record.\n * Rejects with `account refused: link-refused` when anything does not fit:\n * nothing was kept. Afterwards close this client and start\n * {@link MessagingClient.initFromDeviceRecord} on the same store.\n */\n async completeDeviceLink(\n ticket: LinkingTicketV3,\n generation: number,\n generationSecret: Uint8Array,\n ): Promise<LinkedDevice> {\n return await this.call({\n kind: \"completeDeviceLink\", id: this.nextId++,\n ticket, generation, generationSecret, nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as LinkedDevice;\n }\n\n /**\n * Create the DeviceGroup anew after a take-over (the account identity\n * contract, 3.13, \"The DeviceGroup reset\"): drops what this device holds\n * under the DeviceGroup's id, then creates the group alone. Call it ONLY\n * after the server answered the DeviceGroup reset with `200` or with the\n * reason `already_reset`. There is no call that joins a DeviceGroup from\n * outside.\n */\n async recreateDeviceGroup(): Promise<void> {\n await this.call({ kind: \"recreateDeviceGroup\", id: this.nextId++, nowMs: this.now() });\n }\n\n /**\n * Step 0 of a rotation (removing a device, Secure my account): the next\n * generation is the pinned one plus one, proven by the root's own\n * statement, or the call rejects (`account refused:\n * pinned-generation-unproven`, `generation-ahead`). A listed device is\n * offered only when its signed delivery key verifies under a leaf of THIS\n * device's own DeviceGroup. Signs nothing.\n */\n async planRotation(\n start: RotationStartInput, devices: RotationStartDeviceInput[], rootPartGeneration = 0,\n ): Promise<RotationPlanResult> {\n return await this.call({\n kind: \"planRotation\", id: this.nextId++, start, devices, rootPartGeneration,\n }) as RotationPlanResult;\n }\n\n /**\n * Step 1 of a rotation, THE BUILD, with the pending item of `slot` as the\n * root's source (an account with no backup yet). It runs in this client's\n * Worker, which opens the root itself for the length of the call (rulings\n * V136 and V244): nothing of the root reaches this realm or any other\n * Worker, in the answer or in a refusal. Only the tab's own client builds\n * (`ClientConfig.tabClient`); any other answers `account refused:\n * background-worker`. `kept` is every device that stays, this one\n * included. The answer is the request for the server (public values and\n * ciphertext) with the record's id, or `keptSetRefused` naming the one\n * device that cannot be kept: a value, final for that kept set. The\n * request carries no root part. No request is made by this call.\n */\n async rotateGenerationWithPending(args: {\n slot: string; start: RotationStartInput; devices: RotationStartDeviceInput[]; kept: Uint8Array[];\n reason: \"remove\" | \"secure_account\"; accountId: Uint8Array; hostState: Uint8Array;\n }): Promise<RotationBuildResult> {\n return await this.call({\n kind: \"rotateGenerationWithPending\", id: this.nextId++, slot: args.slot,\n start: args.start, devices: args.devices, kept: args.kept, reason: args.reason,\n accountId: args.accountId, hostState: args.hostState, nowMs: this.now(),\n }) as RotationBuildResult;\n }\n\n /**\n * Step 1 of a rotation, THE BUILD, with the backup as the root's source:\n * the root part as the server holds it and the CURRENT recovery phrase,\n * and `newPhrase` when the person asked for a new one. As\n * {@link rotateGenerationWithPending}: the root part is opened inside this\n * client's Worker for the length of the call. The phrases cross to the\n * Worker as bytes; the Worker zeroes its copy when the call has answered\n * and this call zeroes the copy it made. The strings themselves are the\n * host's: drop them. A phrase that does not open the root part answers\n * `account refused: backup-authentication` and nothing of the cause.\n */\n async rotateGenerationWithBackup(args: {\n rootPart: Uint8Array; phrase: string; newPhrase?: string;\n start: RotationStartInput; devices: RotationStartDeviceInput[]; kept: Uint8Array[];\n reason: \"remove\" | \"secure_account\"; accountId: Uint8Array; hostState: Uint8Array;\n }): Promise<RotationBuildResult> {\n const encoder = new TextEncoder();\n const phrase = encoder.encode(args.phrase);\n const newPhrase = args.newPhrase === undefined ? undefined : encoder.encode(args.newPhrase);\n try {\n return await this.call({\n kind: \"rotateGenerationWithBackup\", id: this.nextId++, rootPart: args.rootPart,\n phrase, ...(newPhrase ? { newPhrase } : {}),\n start: args.start, devices: args.devices, kept: args.kept, reason: args.reason,\n accountId: args.accountId, hostState: args.hostState, nowMs: this.now(),\n }) as RotationBuildResult;\n } finally {\n phrase.fill(0);\n newPhrase?.fill(0);\n }\n }\n\n /**\n * Step 3 of a rotation this device built, on the running client: the\n * server's answer AS RECEIVED, judged inside the SDK (ruling V161; no\n * value says \"applied\"). When the device adopts, this client runs on the\n * new record from that moment. `\"undecided\"`: nothing changed, the record\n * stays.\n */\n async completeRotation(\n recordId: Uint8Array, answer: RotationAnswerInput,\n ): Promise<RotationOutcomeResult> {\n return await this.call({\n kind: \"completeRotationOnClient\", id: this.nextId++, recordId,\n answer: rotationAnswerFields(answer),\n }) as RotationOutcomeResult;\n }\n\n /**\n * Step 7 of a rotation, on every other kept device: this device's mailbox\n * row (`GET /v1/devices/self/credential`). The credential must be this\n * device's and the root's own; the wrap must open with this device's\n * delivery key and match the root's statement. On any refusal the device\n * stays on its generation. From the adoption on, this device's next Commit\n * in each conversation carries its new credential.\n */\n async adoptGeneration(row: {\n generation: number; credential: Uint8Array; gsWrap: Uint8Array; statement: SealingStatementInput;\n }): Promise<AdoptedGenerationResult> {\n return await this.call({\n kind: \"adoptGeneration\", id: this.nextId++, generation: row.generation,\n credential: row.credential, gsWrap: row.gsWrap, statement: row.statement, nowMs: this.now(),\n }) as AdoptedGenerationResult;\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. `encryptBackup` and `decryptBackup`\n // (the version 1 blob) took and returned the account identity and left every\n // binding on 2026-11-28: a backup is made, proven and opened by `AccountSetup`\n // and the restore calls, which hand no root to a host.\n\n /**\n * The one switch of self-admission as the wasm module of this package was\n * COMPILED (a constant of the SDK's source: the same value in every artifact\n * built from one commit). Read-only. `false`: the module refuses every\n * external Commit, lists no capability marker and sends nothing of the\n * feature. A host that ships more than one artifact asserts at start that\n * they agree.\n */\n static async selfAdmissionCompiled(): Promise<boolean> {\n return MessagingClient.ephemeralWorkerCall<boolean>({\n kind: \"selfAdmissionCompiled\", id: 1,\n });\n }\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. */\n static async normalizeMnemonicPhrase(phrase: string): Promise<string> {\n return MessagingClient.ephemeralWorkerCall<string>({\n kind: \"normalizeMnemonicPhrase\", id: 1, phrase,\n });\n }\n\n /**\n * Whether `mnemonicPhrase` opens `blob` (a recovery backup as the server returned\n * it), with THREE answers to switch on:\n *\n * - `{ outcome: \"opens\" }`;\n * - `{ outcome: \"authenticationFailed\" }`: PROOF. The backup's own authentication\n * check failed under the key derived from the phrase, so the phrase does not open\n * these exact bytes (wrong words, or bytes that are not what the words sealed: an\n * AEAD cannot tell a changed or shortened ciphertext from wrong words, so hand in\n * the complete bytes). The only answer on which to delete a stored phrase;\n * - `{ outcome: \"couldNotCheck\", reason }`: DOUBT. A phrase that is not a phrase, a\n * version or a format this build cannot read, a payload it cannot decode, a\n * failure inside the SDK. Delete nothing, claim nothing, ask again later.\n *\n * This call NEVER rejects: a wasm trap, an out-of-memory failure and a one-shot\n * worker that could not be created or did not answer are `couldNotCheck` with\n * `reason: \"internal\"`. It resolves nothing of the backup: the decrypted identity\n * is wiped inside the SDK. One Argon2id derivation, on a one-shot worker.\n */\n static async checkBackupPhrase(\n blob: Uint8Array,\n mnemonicPhrase: string,\n ): Promise<BackupPhraseCheck> {\n try {\n return backupPhraseCheckFromWire(\n await MessagingClient.ephemeralWorkerCall<unknown>({\n kind: \"checkBackupPhrase\", id: 1, blob, mnemonicPhrase,\n }),\n );\n } catch {\n // Whatever stopped the check says nothing about the phrase.\n return { outcome: \"couldNotCheck\", reason: \"internal\" };\n }\n }\n\n // ------------------------ Peer-assisted history transfer ------------------------\n // History, version 3 (2026-11-25, rulings V88 to V92). A bundle is signed by\n // this DEVICE's key and sealed only to a key the SDK verified itself: the\n // signed delivery key of a device that is a verified leaf of this device's own\n // tree, or the key of a link handshake verified against what the person was\n // shown. No call takes a recipient key, so a server that answers a key request\n // with a key of its own gets nothing. The raw-key, seed-signed forms\n // (sealHistoryBundle, openHistoryBundle and their Pq twins) are REMOVED.\n\n /** The counter the next {@link publishHistoryDeliveryKey} with this floor will\n * sign. A host that keeps the device key outside the SDK's store writes this\n * number beside that key BEFORE the publish, and passes what it kept as\n * `counterFloor` from then on (0 when it keeps none). Never a server's number. */\n async historyDeliveryKeyNextCounter(counterFloor = 0): Promise<number> {\n return await this.call({\n kind: \"historyDeliveryKeyNextCounter\", id: this.nextId++, counterFloor,\n }) as number;\n }\n\n /** This device's signed history delivery key: post it at every start. The key\n * pair is made once, inside the SDK; the device signs only the key it holds. */\n async publishHistoryDeliveryKey(counterFloor = 0): Promise<HistoryDeliveryKeyStatement> {\n return await this.call({\n kind: \"publishHistoryDeliveryKey\", id: this.nextId++, counterFloor,\n }) as HistoryDeliveryKeyStatement;\n }\n\n /** The server refused the publication (`409 delivery_key_counter_behind`) and\n * answered with the statement IT holds. Taken only when that statement\n * verifies strictly under THIS device's own key and is not older than this\n * device's own; resolves with the statement to publish once more. Anything\n * else rejects ({@link NotPermittedError}) and nothing is signed. */\n async adoptHistoryDeliveryKeyCounter(\n stored: HistoryDeliveryKeyStatement,\n ): Promise<HistoryDeliveryKeyStatement> {\n return await this.call({\n kind: \"adoptHistoryDeliveryKeyCounter\", id: this.nextId++, stored,\n }) as HistoryDeliveryKeyStatement;\n }\n\n /**\n * Verify `recipient` (the statement a server returned for the device the bundle\n * names) in this device's own tree, then sign the bundle with the device key and\n * seal it to that key. `ownAccount` is what the host believes (true: a device of\n * this account, looked up in the DeviceGroup; false: another account's device,\n * looked up in the tree of the bundle's conversation). It decides nothing: the\n * SDK takes the path the recipient's verified identity gives and rejects\n * ({@link NotPermittedError}) when the host said the other one.\n */\n async sealHistoryBundleV3(\n bundle: HistoryBundle,\n recipient: HistoryDeliveryKeyStatement,\n ownAccount: boolean,\n ): Promise<Uint8Array> {\n return await this.call({\n kind: \"sealHistoryBundleV3\", id: this.nextId++, bundle, recipient, ownAccount,\n }) as Uint8Array;\n }\n\n /** The link's own transfer. The handshake `payload` is verified inside the call\n * against what this device was shown, and the bundle is sealed to the verified\n * handshake's key: no key can be passed. Rejects with\n * {@link LinkCommitmentMismatchError} when the payload is not the committed one. */\n async sealLinkHistoryBundle(\n bundle: HistoryBundle,\n payload: Uint8Array,\n expected: LinkExpected,\n ): Promise<Uint8Array> {\n return await this.call({\n kind: \"sealLinkHistoryBundle\", id: this.nextId++, bundle, payload,\n ...linkExpectedFields(expected),\n }) as Uint8Array;\n }\n\n /** Open a transfer sealed to this device's published delivery key. `ownAccount`\n * as in {@link sealHistoryBundleV3}, and as there only a reason to refuse. A\n * bundle whose import the host CONFIRMED ({@link confirmHistoryImport}) is never\n * returned again: the transfer then rejects with {@link HistoryRefusedError}\n * `replayed`, and the host drops it. Until the confirmation the same transfer\n * opens again (the host's import is idempotent by event id). */\n async openHistoryBundleV3(sealed: Uint8Array, ownAccount: boolean): Promise<OpenedHistory> {\n return await this.call({\n kind: \"openHistoryBundleV3\", id: this.nextId++, sealed, ownAccount,\n }) as OpenedHistory;\n }\n\n /** The NEW device opens its link's own transfer, sealed to the X-Wing key of the\n * handshake it published; `recipientPriv` is that key's 32-byte seed. */\n async openLinkHistoryBundle(sealed: Uint8Array, recipientPriv: Uint8Array): Promise<OpenedHistory> {\n return await this.call({\n kind: \"openLinkHistoryBundle\", id: this.nextId++, sealed, recipientPriv,\n }) as OpenedHistory;\n }\n\n /** Ruling V177: call AFTER the host's own store holds the events of a bundle an\n * open returned, with that result's `import_id`. From then on the same bundle\n * (sealed afresh or not, from any sender) is refused as a replay. `true` when\n * this call recorded it, `false` when it was recorded before. The id may be\n * kept and confirmed after a restart. A local write; no request. */\n async confirmHistoryImport(importId: Uint8Array): Promise<boolean> {\n return await this.call({\n kind: \"confirmHistoryImport\", id: this.nextId++, importId,\n }) as boolean;\n }\n\n /** Whether this device's trust record names `deviceId` for history. */\n async historyTrust(deviceId: Uint8Array): Promise<boolean> {\n return await this.call({\n kind: \"historyTrust\", id: this.nextId++, deviceId,\n }) as boolean;\n }\n\n /** Record that this device shipped history to `deviceId`, once the server\n * accepted the transfer and never before. */\n async recordHistoryShipped(deviceId: Uint8Array): Promise<void> {\n await this.call({ kind: \"recordHistoryShipped\", id: this.nextId++, deviceId });\n }\n\n /** For a device of this account: ship history by itself, only after the person\n * confirms on this device, or not at all. Ask it for every entry of the\n * admission ledger and before the \"send your chats\" prompt; a link's own\n * transfer does not ask. */\n async historyShipDecision(deviceId: Uint8Array): Promise<HistoryShipDecision> {\n return await this.call({\n kind: \"historyShipDecision\", id: this.nextId++, deviceId,\n }) as HistoryShipDecision;\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 * THE ONE TAP AFTER A RESTORE BESIDE DEVICES THAT STAY (ruling V123). Call it on\n * a KEPT device when the person confirmed, on that device, the device `deviceId`\n * that restored with the recovery phrase and waits for its DeviceGroup.\n * `keyPackage` is a KeyPackage of that device, as the host fetched it. Nothing\n * the server says is believed: the KeyPackage must be the named device's, and its\n * credential must verify for THIS device's own account root, be signed by the\n * root itself (a linked device enters by its ticket) and stand at the generation\n * this device holds; anything else rejects (`NotPermitted`; `StaleGeneration`\n * when this device is behind its account). Then the DeviceGroup's ordinary Add,\n * sent with its Welcome and merged only when the delivery service accepted. As\n * every Commit there it rejects with `DeviceGroupBehind` while this device is\n * behind or may not commit yet after a rotation (catch up, or run the sweep, and\n * call again), and with `WelcomeUndelivered` when the Add is in and the Welcome is\n * not (call again). The waiting device calls nothing: the Welcome reaches it by\n * the transport. MLS only.\n */\n async addRestoredDevice(\n deviceId: DeviceId,\n keyPackage: Uint8Array,\n nowMs: number = this.now(),\n ): Promise<void> {\n await this.call({\n kind: \"addRestoredDevice\", id: this.nextId++, deviceId, keyPackage, nowMs,\n });\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 * {@link exportConversationSecret} together with the MLS epoch the secret was\n * exported at, from one read under one lock inside the core: the pair can\n * never disagree across a Commit.\n *\n * A host that files a key under an epoch number (a call's media key ring)\n * takes BOTH from this call. A conversation handle's `epoch` is this thread's\n * copy and any other read is a second request, so either may be a Commit away\n * from the secret.\n *\n * Same derivation, same arguments and the same refusals as\n * {@link exportConversationSecret}: at one epoch both answer the same bytes.\n * `secret` is a secret: never log it, persist it only encrypted, and call\n * `secret.fill(0)` after use. `epoch` is a plain number and may be logged.\n */\n async exportConversationSecretWithEpoch(\n conv: ConversationId,\n label: string,\n context: Uint8Array,\n length: number,\n ): Promise<ExportedSecret> {\n if (length <= 0 || length > 1024) {\n throw new Error(\"exportConversationSecretWithEpoch: length must be 1..=1024\");\n }\n return await this.call({\n kind: \"exportConversationSecretWithEpoch\", id: this.nextId++,\n conv, label, context, length,\n }) as ExportedSecret;\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 if (method === \"send\" || method === \"sendBatch\") {\n // The service's `409 stale_generation` (ruling S75) must reach the\n // wasm as itself: the host's `staleGeneration` flag becomes the text\n // the bridge reads, as \"the epoch has moved\" does below.\n try {\n return await t[method]?.(...args);\n } catch (e) {\n if ((e as { staleGeneration?: unknown } | null)?.staleGeneration === true) {\n throw new Error(TRANSPORT_STALE_GENERATION);\n }\n throw e;\n }\n }\n if (method === \"sendExternalCommit\" || method === \"sendExternalCommits\" || method === \"publishSealedGroupInfo\") {\n // \"The epoch has moved\" must reach the wasm as itself (the join then\n // answers `stale`); an error is a string once it crossed the Worker\n // boundary, so the host's flag becomes the text the bridge reads.\n try {\n return (await t[method]?.(...args)) ?? null;\n } catch (e) {\n if ((e as { epochOccupied?: unknown } | null)?.epochOccupied === true) {\n throw new Error(EXTERNAL_COMMIT_EPOCH_OCCUPIED);\n }\n if ((e as { staleGeneration?: unknown } | null)?.staleGeneration === true) {\n throw new Error(TRANSPORT_STALE_GENERATION);\n }\n throw e;\n }\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\nconst BACKUP_CHECK_FAILURES: readonly BackupCheckFailure[] = [\n \"invalidPhrase\", \"unsupportedVersion\", \"malformed\", \"undecodable\", \"internal\",\n];\n\n/**\n * Read a `{ outcome, reason? }` answer of the SDK's backup phrase check (the wasm\n * `checkBackupPhrase`, the React Native bridge) as a {@link BackupPhraseCheck}.\n *\n * The rule: ONLY the exact code `\"authenticationFailed\"` is proof that the phrase\n * does not open the backup, and only the exact code `\"opens\"` says that it does.\n * Everything else is a doubt: a value that is not such an object, an outcome this\n * build does not know, and a `couldNotCheck` whose reason it does not know (read as\n * `\"internal\"`). Nothing but the codes is carried over.\n */\nexport function backupPhraseCheckFromWire(raw: unknown): BackupPhraseCheck {\n const rec = raw !== null && typeof raw === \"object\"\n ? (raw as { outcome?: unknown; reason?: unknown })\n : {};\n if (rec.outcome === \"opens\") return { outcome: \"opens\" };\n if (rec.outcome === \"authenticationFailed\") return { outcome: \"authenticationFailed\" };\n const reason = rec.outcome === \"couldNotCheck\"\n ? BACKUP_CHECK_FAILURES.find((known) => known === rec.reason)\n : undefined;\n return { outcome: \"couldNotCheck\", reason: reason ?? \"internal\" };\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/** How the rejection of a call reads when another writer wrote this client's\n * MLS store since the client loaded it (the core's `Error::StoreMoved`). No\n * other failure starts this way. Kept in lockstep with the core's display\n * (`stringify` in `core/ping-wasm/src/lib.rs`, pinned by\n * `ping-core/tests/release_after_durable.rs`). Raised by the file-backed\n * store of the native builds only: the web SDK's stores have no writer\n * claim yet, so a browser never sees it today; the class exists so the API\n * is the same on every platform. */\nexport const STORE_MOVED_PREFIX = \"store moved: \";\n\n/** The stale-writer failure. Nothing was written and nothing was released (a\n * message being sent did not leave). The client is stale: drop it,\n * initialise a new one on the same store, then retry the operation.\n * `message` stays the core's text, so `isStoreMovedError` also reads a copy\n * that lost its class. */\nexport class StoreMovedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StoreMovedError\";\n }\n}\n\n/** True when `e` is the stale-writer failure and no other. Accepts the\n * rejection itself, any object with a `message`, or the text. */\nexport function isStoreMovedError(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(STORE_MOVED_PREFIX);\n}\n\n/** How the rejection of a call reads when it was asked of a client opened\n * read-only (`openReadOnly`; the core's `Error::ReadOnly`). No other failure\n * starts this way. Kept in lockstep with the core's display (`stringify` in\n * `core/ping-wasm/src/lib.rs`, pinned by\n * `ping-core/tests/whole_operations.rs`). */\nexport const READ_ONLY_PREFIX = \"read-only client: \";\n\n/** The refusal of an operation on a client opened read-only. Such a client\n * loads the tab's MLS state and stores nothing: it can preview a received\n * message (`previewEnvelope`) and can never seal one (a message, a\n * proposal, a Commit, a leave, a KeyPackage, a linking ticket) or change MLS\n * state, because the ratchet step would not be stored and the tab would\n * seal again under the same key. The call was refused before anything was\n * encrypted or sent; nothing changed. Do the operation on the writing\n * client; never retry it on the reader. `message` stays the core's text, so\n * `isReadOnlyError` also reads a copy that lost its class. */\nexport class ReadOnlyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ReadOnlyError\";\n }\n}\n\n/** True when `e` is the read-only refusal and no other. Accepts the\n * rejection itself, any object with a `message`, or the text. */\nexport function isReadOnlyError(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(READ_ONLY_PREFIX);\n}\n\n/** What an existing device was shown for a link: the 20 characters\n * `MessagingClient.normalizeLinkCode` returned, or the 32 bytes of the scanned QR\n * (`MessagingClient.linkQrCommitment`, or the hash of a link URL decoded by the host). */\nexport type LinkExpected = { code: string } | { qrCommitment: Uint8Array };\n\n/** What a new device shows for the handshake it published. */\nexport interface LinkCommitment {\n commitment: Uint8Array;\n qrText: string;\n code: string;\n codeDisplay: string;\n}\n\n/** What `MessagingClient.verifyLinkHandshake` reports of a verified handshake. Not\n * a capability: the calls that act on a handshake verify it again themselves. */\nexport interface VerifiedLinkHandshakeInfo {\n deviceId: Uint8Array;\n deviceSigningPubkey: Uint8Array;\n commitment: Uint8Array;\n verifiedByQr: boolean;\n}\n\nfunction linkExpectedFields(expected: LinkExpected): { expectedCode?: string; expectedQr?: Uint8Array } {\n return \"code\" in expected ? { expectedCode: expected.code } : { expectedQr: expected.qrCommitment };\n}\n\n/** How the core's link commitment refusal reads as text (`ping_core`'s\n * `Error::LinkCommitmentMismatch`). No other failure starts this way. */\nexport const LINK_COMMITMENT_MISMATCH_PREFIX = \"link commitment mismatch: \";\n\n/** The handshake a relay returned is not the one the new device showed: the person\n * mistyped, or the handshake was swapped on the way. Nothing was parsed or sent.\n * Show: \"We couldn't verify the new device, so nothing was sent to it. Try again.\n * Scan the QR code if you can.\" */\nexport class LinkCommitmentMismatchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"LinkCommitmentMismatchError\";\n }\n}\n\n/** True for a {@link LinkCommitmentMismatchError} or its text. */\nexport function isLinkCommitmentMismatchError(e: unknown): boolean {\n if (e instanceof LinkCommitmentMismatchError) return true;\n const text = e instanceof Error ? e.message : typeof e === \"string\" ? e : null;\n return text !== null && text.startsWith(LINK_COMMITMENT_MISMATCH_PREFIX);\n}\n\n/** How the rejection of a join reads when the Welcome joins a group other\n * than the conversation its envelope names (the core's\n * `Error::WelcomeMislabeled`). 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\n * `ping-core/tests/conversation_scope.rs`). */\nexport const WELCOME_MISLABELED_PREFIX = \"welcome mislabeled: \";\n\n/** The refusal of a Welcome that joins a group other than the conversation\n * its envelope names. An honest sender names the group it built the Welcome\n * for, so the two differ only when the envelope was rewritten on its way.\n * The Welcome was refused as soon as it was opened: the KeyPackage it is\n * sealed to is kept, no conversation appeared under either id, and the\n * Welcome as it was sent still joins. Drop that envelope: never retry it,\n * file no re-admission request for it, show nothing. `message` stays the\n * core's text, so `isWelcomeMislabeledError` also reads a copy that lost\n * its class. */\nexport class WelcomeMislabeledError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"WelcomeMislabeledError\";\n }\n}\n\n/** True when `e` is the refusal of a mislabeled Welcome and no other.\n * Accepts the rejection itself, any object with a `message`, or the text. */\nexport function isWelcomeMislabeledError(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(WELCOME_MISLABELED_PREFIX);\n}\n\n/** How the refusal reads when this device is behind its own account and so\n * builds no Commit (the core's `Error::StaleGeneration`). No other failure\n * starts this way. Kept in lockstep with the core's display (`stringify`\n * in `core/ping-wasm/src/lib.rs`, pinned by\n * `ping-core/tests/generation_sender_rules.rs`). */\nexport const STALE_GENERATION_PREFIX = \"stale generation: \";\n\n/** This device is behind its own account: a newer generation of the account\n * exists than this device carries, so it builds no Commit (every member\n * would refuse what it did with its account's devices). Nothing was built\n * or sent. The device is still a member: it sends and receives messages.\n * Adopt the account's newest generation, then repeat the call; do not drop\n * the intent, and do not retry before the adoption. */\nexport class StaleGenerationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StaleGenerationError\";\n }\n}\n\n/** True for a {@link StaleGenerationError}, any object with its `message`,\n * or the text. */\nexport function isStaleGenerationError(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(STALE_GENERATION_PREFIX);\n}\n\n/** How the refusal reads when this device cannot approve a link because its\n * DeviceGroup is behind (the core's `Error::DeviceGroupBehind`). No other\n * failure starts this way. Kept in lockstep with the core's display. */\nexport const DEVICE_GROUP_BEHIND_PREFIX = \"device group behind: \";\n\n/** This device cannot approve a link now: it holds no position in its\n * DeviceGroup's log, holds frames it could not apply, or the delivery\n * service refused its Add. Nothing left the device and no ticket was built.\n * Catch the DeviceGroup up, then repeat the call once. */\nexport class DeviceGroupBehindError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DeviceGroupBehindError\";\n }\n}\n\n/** True for a {@link DeviceGroupBehindError}, any object with its `message`,\n * or the text. */\nexport function isDeviceGroupBehindError(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(DEVICE_GROUP_BEHIND_PREFIX);\n}\n\n/** How the refusal reads when this device cannot approve a link because its\n * own credential's chain is at the limit (the core's\n * `Error::LinkChainTooDeep`, ruling V178). Kept in lockstep with the core's\n * display. */\nexport const LINK_CHAIN_TOO_DEEP_PREFIX = \"link chain too deep: \";\n\n/** This device cannot approve a link, now or later: its credential's chain\n * is at the limit. FINAL: show the \"link from another device\" copy, never\n * repeat the call. Nothing was signed and no ticket was built. */\nexport class LinkChainTooDeepError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"LinkChainTooDeepError\";\n }\n}\n\n/** How the refusal reads when the delivery service refuses this device's\n * DeviceGroup Add for a link and a catch-up did not cure it (the core's\n * `Error::LinkAddRefused`, ruling V138). */\nexport const LINK_ADD_REFUSED_PREFIX = \"link add refused: \";\n\n/** The delivery service refuses this device's DeviceGroup Add, and the\n * catch-up that followed a {@link DeviceGroupBehindError} changed nothing.\n * FINAL: never repeat the call. Nothing left the device. */\nexport class LinkAddRefusedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"LinkAddRefusedError\";\n }\n}\n\n/** How the answer reads when a Welcome handed to a direct join call waits\n * for its turn (the core's `Error::WelcomeWaits`, rulings V186, V194). */\nexport const WELCOME_WAITS_PREFIX = \"welcome waits: \";\n\n/** NOT a failure: the Welcome is kept and joins by itself once the rows of\n * the log before it were handed or the conversation was paged. Show\n * nothing, ask for no re-admission, queue no retry of the Welcome. */\nexport class WelcomeWaitsError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"WelcomeWaitsError\";\n }\n}\n\nfunction startsWithPrefix(e: unknown, prefix: string): 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(prefix);\n}\n\n/** True for a {@link LinkChainTooDeepError}, any object with its `message`,\n * or the text. */\nexport function isLinkChainTooDeepError(e: unknown): boolean {\n return startsWithPrefix(e, LINK_CHAIN_TOO_DEEP_PREFIX);\n}\n\n/** True for a {@link LinkAddRefusedError}, any object with its `message`, or\n * the text. */\nexport function isLinkAddRefusedError(e: unknown): boolean {\n return startsWithPrefix(e, LINK_ADD_REFUSED_PREFIX);\n}\n\n/** True for a {@link WelcomeWaitsError}, any object with its `message`, or\n * the text. */\nexport function isWelcomeWaitsError(e: unknown): boolean {\n return startsWithPrefix(e, WELCOME_WAITS_PREFIX);\n}\n\n/** How a refusal of the version 3 history rules reads as text (a contract with\n * `core/ping-wasm/src/lib.rs`, `HISTORY_REFUSED_PREFIX`). What follows is the\n * reason. Carries nothing of the bundle. */\nexport const HISTORY_REFUSED_PREFIX = \"history refused: \";\n\n/** Why a history bundle was not sealed or not taken. `replayed`: this device\n * already accepted this very bundle; drop the transfer. `too-large`: over\n * 2 MiB sealed or over 256 events. `recipient-key`: the recipient's verified\n * key may not seal this bundle (another conversation's tree, or its leaf is\n * gone). `recipient`, `sender`, `signature`: the bundle is not for this\n * device, its sender is not a verified leaf this device accepts history\n * from, or its signature does not verify. */\nexport type HistoryRefusalReason =\n | \"recipient\" | \"sender\" | \"signature\" | \"recipient-key\" | \"too-large\" | \"replayed\";\n\n/** A history bundle was refused. Nothing of it was applied or sent. */\nexport class HistoryRefusedError extends Error {\n readonly reason: HistoryRefusalReason | \"unknown\";\n constructor(message: string) {\n super(message);\n this.name = \"HistoryRefusedError\";\n const reason = message.slice(HISTORY_REFUSED_PREFIX.length);\n this.reason = (HISTORY_REFUSAL_REASONS as readonly string[]).includes(reason)\n ? reason as HistoryRefusalReason\n : \"unknown\";\n }\n}\n\nconst HISTORY_REFUSAL_REASONS: readonly HistoryRefusalReason[] = [\n \"recipient\", \"sender\", \"signature\", \"recipient-key\", \"too-large\", \"replayed\",\n];\n\n/** Whether `e` is a refusal of the history rules, typed or as a worker's text. */\nexport function isHistoryRefusedError(e: unknown): boolean {\n if (e instanceof HistoryRefusedError) return true;\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(HISTORY_REFUSED_PREFIX);\n}\n\n/** How the refusal reads when the SDK's pending-apply journal is full (the\n * core's `Error::JournalFull`). No other failure starts this way. Kept in\n * lockstep with the core's display. */\nexport const JOURNAL_FULL_PREFIX = \"journal full: \";\n\n/** The pending-apply journal has no room for the message this envelope would\n * decrypt into, and the journal never drops a message the host has not\n * confirmed. NOTHING of the envelope was taken: no key was spent, no\n * position moved, it is not kept and it is not a hole. Save the messages\n * already handed over, call `confirmApplied`, then hand the same envelope\n * again. A batch and a page report it in `journalFull` instead. */\nexport class JournalFullError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"JournalFullError\";\n }\n}\n\n/** True for a {@link JournalFullError}, any object with its `message`, or\n * the text. */\nexport function isJournalFullError(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(JOURNAL_FULL_PREFIX);\n}\n\n/** A worker's rejection text as the error a caller catches: the typed role\n * refusal, the typed sender refusal, the stale-writer failure, the\n * read-only refusal or the refusal of a mislabeled Welcome when it is one,\n * a plain `Error` 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 if (text.startsWith(STORE_MOVED_PREFIX)) return new StoreMovedError(text);\n if (text.startsWith(READ_ONLY_PREFIX)) return new ReadOnlyError(text);\n if (text.startsWith(WELCOME_MISLABELED_PREFIX)) return new WelcomeMislabeledError(text);\n if (text.startsWith(LINK_COMMITMENT_MISMATCH_PREFIX)) return new LinkCommitmentMismatchError(text);\n if (text.startsWith(STALE_GENERATION_PREFIX)) return new StaleGenerationError(text);\n if (text.startsWith(DEVICE_GROUP_BEHIND_PREFIX)) return new DeviceGroupBehindError(text);\n if (text.startsWith(JOURNAL_FULL_PREFIX)) return new JournalFullError(text);\n if (text.startsWith(LINK_CHAIN_TOO_DEEP_PREFIX)) return new LinkChainTooDeepError(text);\n if (text.startsWith(LINK_ADD_REFUSED_PREFIX)) return new LinkAddRefusedError(text);\n if (text.startsWith(WELCOME_WAITS_PREFIX)) return new WelcomeWaitsError(text);\n if (text.startsWith(HISTORY_REFUSED_PREFIX)) return new HistoryRefusedError(text);\n return new Error(text);\n}\n\n/** The text of the error that tells the wasm \"the epoch has moved\" for an\n * external Commit's post (`core/ping-wasm`, the same constant). */\nconst EXTERNAL_COMMIT_EPOCH_OCCUPIED = \"external commit: epoch occupied\";\n/** The text that carries a host's `staleGeneration` flag (the service's\n * `409 stale_generation` on a post) across the Worker boundary; kept in\n * step with `core/ping-wasm/src/lib.rs`. */\nconst TRANSPORT_STALE_GENERATION = \"transport: stale generation\";\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\n/** RULING V406 (b): the join's typed hole arrives in the wire form of\n * `logHoles`; hand it on in the form every other hole has. */\nfunction holeOfJoin(result: Extract<SelfAdmitResult, { kind: \"joined\" }>): void {\n if (result.beforeReturn !== undefined && result.beforeReturn !== null) {\n result.beforeReturn = logHoleFromWire(result.beforeReturn as unknown as LogHoleWire);\n }\n}\n","// 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 SelfAdmission,\n HoleReason,\n LogAck,\n JournalFullAt,\n LogHole,\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 sealed_group_info_wanted?: boolean;\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 SelfAdmissionWire {\n conversation_id: Uint8Array;\n identity: Uint8Array;\n device_id: Uint8Array;\n replaced_own_leaf: boolean;\n own_account: boolean;\n epoch: number;\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 self_admissions?: SelfAdmissionWire[];\n holes?: LogHoleWire[];\n acks?: LogAckWire[];\n journal_full?: JournalFullAtWire[];\n /** Set by the wasm bridge on every batch answer (not a field of the core's\n * result): the anchor record changed and the state part is owed a write. */\n state_backup_owed?: boolean;\n}\n\nexport interface LogHoleWire {\n conversation_id: Uint8Array;\n from_server_seq: number;\n to_server_seq: number;\n /** `\"RefusedCommit\"`, `\"CannotDecrypt\"`, `\"NotHeld\"`, `\"Invalid\"`, `\"Internal\"`, `\"BeforeReturn\"`. */\n reason: string;\n content_hashes: ArrayLike<number>[];\n kept: boolean;\n}\n\nexport interface LogAckWire {\n conversation_id: Uint8Array;\n server_seq: number;\n}\n\nexport interface JournalFullAtWire {\n conversation_id: Uint8Array;\n server_seq: number;\n rows: number;\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 self_admissions?: SelfAdmissionWire[];\n holes?: LogHoleWire[];\n acks?: LogAckWire[];\n journal_full?: JournalFullAtWire[];\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 ...(h.sealedGroupInfoWanted === true ? { sealed_group_info_wanted: true } : {}),\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 ...(h.sealed_group_info_wanted === true ? { sealedGroupInfoWanted: true } : {}),\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\nexport function selfAdmissionFromWire(a: SelfAdmissionWire): SelfAdmission {\n return {\n conversationId: a.conversation_id,\n identity: a.identity,\n deviceId: a.device_id,\n replacedOwnLeaf: a.replaced_own_leaf,\n ownAccount: a.own_account,\n epoch: a.epoch,\n };\n}\n\nexport function logHoleFromWire(h: LogHoleWire): LogHole {\n return {\n conversationId: h.conversation_id,\n fromServerSeq: h.from_server_seq,\n toServerSeq: h.to_server_seq,\n reason: variant<HoleReason>(h.reason),\n contentHashes: h.content_hashes.map((c) => Uint8Array.from(c)),\n kept: h.kept,\n };\n}\n\nexport function logAckFromWire(a: LogAckWire): LogAck {\n return { conversationId: a.conversation_id, serverSeq: a.server_seq };\n}\n\nexport function journalFullAtFromWire(j: JournalFullAtWire): JournalFullAt {\n return { conversationId: j.conversation_id, serverSeq: j.server_seq, rows: j.rows };\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 self_admissions?: SelfAdmissionWire[];\n holes?: LogHoleWire[];\n acks?: LogAckWire[];\n journal_full?: JournalFullAtWire[];\n}): Pick<\n ApplyBatchResult,\n | \"removed\" | \"welcomeFailures\" | \"stranded\" | \"proposalsPending\" | \"overflow\" | \"selfAdmissions\"\n | \"holes\" | \"acks\" | \"journalFull\"\n> {\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 selfAdmissions: (r.self_admissions ?? []).map(selfAdmissionFromWire),\n // Absent from an older wasm: nothing recorded, nothing safe to acknowledge.\n holes: (r.holes ?? []).map(logHoleFromWire),\n acks: (r.acks ?? []).map(logAckFromWire),\n // Absent from an older wasm, which never stopped for the journal.\n journalFull: (r.journal_full ?? []).map(journalFullAtFromWire),\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 // Present only when the SDK says it: said once, with the batch at which\n // the anchor record was seen to change.\n ...(r.state_backup_owed === true ? { stateBackupOwed: true } : {}),\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\n/**\n * Every write transaction asks for STRICT durability: `oncomplete` fires only\n * after the data was flushed to the device, so a write this store reported\n * done also survives an operating-system crash or a power loss. The default\n * of the browsers is weaker (Chromium has used `relaxed` since version 121:\n * `oncomplete` can fire before the flush, which survives a tab or browser\n * crash only). The SDK releases a sealed message only after the write of its\n * ratchet step and of its send counter completed; with a relaxed write a\n * power loss could roll both back after the message left, and the next\n * message would be sealed under a key that was used before. Reads are not\n * affected. A browser that does not know the option ignores it and keeps its\n * default.\n */\nconst DURABLE: IDBTransactionOptions = { durability: \"strict\" };\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\", DURABLE);\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\", DURABLE);\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\", DURABLE);\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","// Account set-up and the first backup, from the main realm (the account\n// identity contract, sections 3.3 and 13.1; rules R7, R10, R32 to R34; rulings\n// ID38 to ID42, V102, V103).\n//\n// The calls run in a dedicated Worker of the SDK that this class owns and that\n// never runs a messaging client. The pending root is wrapped and unwrapped\n// there, by the SDK's own store (`pending-root-store.ts`): no message between\n// this realm and that Worker carries a root seed, a wrapping key or the store.\n// What crosses: the slot's name, the sign-in's `identity_state`, the browser's\n// answer to the persistent-storage request, the phrase the person typed, the\n// two parts of a backup (ciphertext), public values, and ONCE the device key\n// of a device the call made, for the host's protected store (ruling V103).\n//\n// A set-up session whose root is in memory only (rule R34 a) lives in that\n// Worker between calls: closing this object, or the tab, wipes it.\n\nimport type { Request, Response } from \"./protocol\";\nimport { scopeStorage, storageFeaturesOf } from \"./storage/scope\";\nimport type { Storage } from \"./types\";\n\n/** The root's sealing key statement of one generation. Public values. */\nexport interface SealingStatement {\n generation: number;\n sealingPublicKey: Uint8Array;\n signature: Uint8Array;\n}\n\n/**\n * What a call that MADE a device answers: the public values the host registers\n * with the server, and the device key for the host's protected store.\n * `deviceSigningSecretKey` is a secret: keep it where a device key is kept\n * today, pass it to `MessagingClient.initFromDeviceRecord`, never log it.\n */\nexport interface NewAccountDevice {\n userId: Uint8Array;\n deviceId: Uint8Array;\n generation: number;\n statement: SealingStatement;\n deviceSigningSecretKey: Uint8Array;\n}\n\n/** The two parts of a backup (ciphertext) and how many conversations' anchors\n * did not fit the state part. */\n/** The recovery phrase as it crosses to the account Worker (ruling V253):\n * UTF-8 bytes, never a string, so that the copy on each side of the\n * boundary can be zeroed after the call (a string cannot be). The page's\n * copy is zeroed by `AccountSetup` when the call has answered, the\n * Worker's by the Worker, the wasm's by the wasm. THE HOST'S OWN STRING\n * (the argument it passed in, and whatever input field it came from)\n * cannot be wiped by anyone: keep it no longer than the call. */\nfunction phraseBytes(phrase: string): Uint8Array {\n return new TextEncoder().encode(phrase);\n}\n\nexport interface AccountBackupParts {\n rootPart: Uint8Array;\n statePart: Uint8Array;\n droppedAnchors: number;\n}\n\n/** `present`, `absent`, or `mismatch` (the pending root is LOST: copy B6). */\nexport type PendingRootStatus = \"present\" | \"absent\" | \"mismatch\";\n\n/** What `POST /v1/account/generation/start` answered, as the host parsed it\n * (the account identity contract, 12.3). Public values, and the server's\n * word: the SDK believes it only as far as the root's signature goes. */\nexport interface RotationStart {\n rotationId: Uint8Array;\n rootPublicKey: Uint8Array;\n generation: number;\n /** The root-signed statement of the pinned generation. A device handed\n * none signs nothing (`pinned-generation-unproven`). */\n statement?: SealingStatement | null;\n}\n\n/** The fields of the `rotation` object the SDK builds (contract 12.3). The\n * host adds `new_user_pubkey` and `new_key_sig` and encodes every binary\n * field as base64url with no padding. Public values and ciphertext. */\nexport interface RotationRequest {\n rotationId: Uint8Array;\n generation: number;\n reason: \"remove\" | \"secure_account\" | \"restore\";\n credentials: { deviceId: Uint8Array; credential: Uint8Array }[];\n sealingPublicKey: Uint8Array;\n sealingSignature: Uint8Array;\n wraps: { deviceId: Uint8Array; wrap: Uint8Array }[];\n recoveryRootPart?: Uint8Array;\n recoveryStatePart: Uint8Array;\n}\n\n/** What a call that BUILT a rotation answers. `newDevice` is the device a\n * take-over makes; its `deviceSigningSecretKey` is a SECRET. */\n/** One device of the rotation start route's answer: the server's word. A\n * device is kept only when its delivery key verifies under a leaf of the\n * rotating device's own DeviceGroup tree. */\nexport interface RotationStartDevice {\n deviceId: Uint8Array;\n credentialGeneration?: number | null;\n historyDeliveryKey?: { device_id: Uint8Array; counter: number; public_key: Uint8Array; signature: Uint8Array } | null;\n}\n\n/** What `MessagingClient.planRotation` answers. */\nexport interface RotationPlan {\n /** The generation the rotation would pin: the pinned one plus one. */\n nextGeneration: number;\n offered: { deviceId: Uint8Array; own: boolean }[];\n notOffered: { deviceId: Uint8Array; reason: \"no-delivery-key\" | \"not-verified\" }[];\n}\n\n/** What `MessagingClient.adoptGeneration` answers. `changed` is false when\n * the row was the generation the device already held. */\nexport interface AdoptedGeneration {\n generation: number;\n changed: boolean;\n}\n\nexport interface RotationBuilt {\n request: RotationRequest;\n recordId: Uint8Array;\n newDevice?: NewAccountDevice;\n}\n\n/** Why one device of the kept set cannot be kept (ruling V138). */\nexport type RotationKeptRefusal = \"caller_not_kept\" | \"not_offered\" | \"not_verified\";\n\n/** What the two builds of a rotation on the client answer\n * (`MessagingClient.rotateGenerationWithPending`, `rotateGenerationWithBackup`).\n * `keptSetRefused` is a VALUE, not an exception, and FINAL for that kept set:\n * nothing was signed or written, and the same call answers the same. It\n * names the device so that the host can take it out of the kept set or tell\n * the person; `deviceId` is an identifier, never a log value. */\nexport type RotationBuild =\n | { built: RotationBuilt }\n | { keptSetRefused: { deviceId: Uint8Array; reason: RotationKeptRefusal } };\n\nexport type RotationPhase = \"built\" | \"applied\" | \"adopted\" | \"device_group_done\" | \"queued\";\n\n/** Ruling V232: what the store says of a rotation this device built\n * (`rotationRecordState`). `\"pending\"`: the server has not refused it, send the\n * identical request again. `\"adopted\"`: the device runs on it; it ends by\n * `finishRotation`. `\"refused\"`, `\"root_part_required\"`: the person may abandon it\n * (`abandonRotation`). */\nexport type RotationRecordState = \"no_record\" | \"pending\" | \"adopted\" | \"refused\" | \"root_part_required\";\n\n/** A rotation this device built and has not finished. */\nexport interface PendingRotation {\n recordId: Uint8Array;\n generation: number;\n reason: RotationRequest[\"reason\"];\n phase: RotationPhase;\n request: RotationRequest;\n newDevice?: NewAccountDevice;\n}\n\n/** What the server answered a rotation request with, AS RECEIVED (ruling\n * V161): the HTTP `status` (0 when there was no answer) and what the body\n * states, each when present: its `error` code, its `generation`, its\n * `statement`. The host parses and hands over; it decides nothing, and no\n * value of this type says \"applied\". */\nexport interface RotationAnswer {\n status: number;\n error?: string | null;\n generation?: number | null;\n statement?: SealingStatement | null;\n}\n\n/** `\"undecided\"`: the answer was none the SDK acts on (a `200` that states\n * the record's generation, `409 generation_conflict`, the final refusals\n * below). Nothing changed and the record stays: send the\n * identical request again at the next start.\n *\n * `\"refused\"` (rulings V212 and V245): the server refused this rotation FOR\n * GOOD (`403 caller_not_kept`, `400 credential_invalid`, `409\n * identity_key_retired`, `400 rotation_invalid`; no answer of a server\n * discards a record by itself, so there is no `\"discarded\"` outcome);\n * the identical request will be refused again. `\"root_part_required\"` (`409\n * recovery_root_part_required`): the account has a backup and the request\n * was built without the recovery phrase; the person supplies it. In both\n * nothing changed and the record STAYS; no other rotation starts until the\n * person chooses to start over and the host calls `abandonRotation`. */\nexport type RotationRefusal =\n | \"caller_not_kept\" | \"credential_invalid\" | \"identity_key_retired\" | \"rotation_invalid\";\nexport type RotationOutcome =\n | { outcome: \"adopted\"; userId: Uint8Array; deviceId: Uint8Array; generation: number }\n | { outcome: \"lost\"; pinnedStatement: SealingStatement }\n | { outcome: \"undecided\" }\n | { outcome: \"refused\"; reason: RotationRefusal }\n | { outcome: \"root_part_required\" };\n\n/** The four fields of a {@link RotationAnswer} and nothing else, so that\n * nothing a host left on the object crosses to a Worker with it. */\nexport function rotationAnswerFields(answer: RotationAnswer): Required<RotationAnswer> {\n return {\n status: answer.status,\n error: answer.error ?? null,\n generation: answer.generation ?? null,\n statement: answer.statement ?? null,\n };\n}\n\n/** What step 3 of a restore found. `hostState` (the hosts' own data, with\n * the OLD sign-in key companion) is absent when no state part was given or\n * the root part's secret does not open it. */\nexport interface RestoreOpened {\n userId: Uint8Array;\n rootPublicKey: Uint8Array;\n accountId: Uint8Array;\n generation: number;\n hostState?: Uint8Array;\n anchoredConversations: number;\n}\n\nexport interface RestoreJoined {\n device: NewAccountDevice;\n credential: Uint8Array;\n hostState: Uint8Array;\n}\n\nexport interface StateOpened {\n hostState: Uint8Array;\n anchoredConversations: number;\n}\n\nexport interface StateRefreshed {\n statePart: Uint8Array;\n droppedAnchors: number;\n}\n\nexport interface AccountSetupConfig {\n /** The device's own store: the one the client will be started on. */\n storage: Storage;\n /** The same per-account scoping `MessagingClient` applies (see `ClientConfig`). */\n accountNamespace?: string;\n /** Override the wall clock (tests only). */\n now?: () => number;\n}\n\n/** Every refusal of these calls reads `account refused: <code>`. */\nexport function accountRefusalCode(error: unknown): string | null {\n const text = error instanceof Error ? error.message : String(error);\n const at = text.indexOf(\"account refused: \");\n return at < 0 ? null : text.slice(at + \"account refused: \".length).trim();\n}\n\nexport class AccountSetupClosedError extends Error {\n constructor() {\n super(\"AccountSetup is closed\");\n this.name = \"AccountSetupClosedError\";\n }\n}\n\nexport class AccountSetup {\n private readonly worker: Worker;\n private readonly storage: Storage;\n private readonly now: () => number;\n private readonly pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: unknown) => void }>();\n private nextId = 1;\n private closed = false;\n\n private constructor(cfg: AccountSetupConfig, worker: Worker) {\n this.worker = worker;\n this.storage =\n cfg.accountNamespace !== undefined && cfg.accountNamespace.length > 0\n ? scopeStorage(cfg.storage, cfg.accountNamespace)\n : cfg.storage;\n this.now = cfg.now ?? (() => Date.now());\n this.worker.onmessage = (ev) => void this.handleWorker(ev.data as Response);\n this.worker.onerror = () => this.fail(new AccountSetupClosedError());\n }\n\n /** Start the SDK's set-up Worker over the device's own store. */\n static open(cfg: AccountSetupConfig): AccountSetup {\n const worker = new Worker(new URL(\"./worker.js\", import.meta.url), { type: \"module\" });\n return new AccountSetup(cfg, worker);\n }\n\n /**\n * Set a NEW account up on this browser after \"Not now\" (rule R34 b): the\n * pending root first, then the device record. `identityState` is the\n * sign-in body's `identity_state` field as the server sent it; only\n * `\"none_pinned\"` lets the call run (ruling V102). `persistentStorage` is the\n * browser's answer to `navigator.storage.persist()`, which the host asked\n * for before this call (ruling ID39).\n */\n createAccount(args: {\n slot: string;\n identityState: string | undefined;\n persistentStorage?: boolean;\n }): Promise<NewAccountDevice> {\n return this.call({\n kind: \"createAccount\",\n id: this.nextId++,\n slot: args.slot,\n identityState: args.identityState,\n persistentStorage: args.persistentStorage,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<NewAccountDevice>;\n }\n\n /** Whether the slot holds the pending root this device expects (rule R32).\n * No prompt, no read of the seed. */\n pendingStatus(slot: string): Promise<PendingRootStatus> {\n return this.call({\n kind: \"pendingStatus\",\n id: this.nextId++,\n slot,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<PendingRootStatus>;\n }\n\n /** The first backup of a PENDING account. `accountId` is the account's\n * 16-byte id at the auth layer. */\n makeBackup(args: {\n slot: string;\n phrase: string;\n accountId: Uint8Array;\n hostState: Uint8Array;\n }): Promise<AccountBackupParts> {\n return this.call({\n kind: \"makeBackup\",\n id: this.nextId++,\n slot: args.slot,\n phrase: phraseBytes(args.phrase),\n accountId: args.accountId,\n hostState: args.hostState,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<AccountBackupParts>;\n }\n\n /** Rule R10 (b): the root part READ BACK from where it was stored opens to\n * this account. Answers the fingerprint `endPending` asks for. */\n async proveBackup(args: { readBackRootPart: Uint8Array; phrase: string }): Promise<Uint8Array> {\n const proof = (await this.call({\n kind: \"proveBackup\",\n id: this.nextId++,\n readBackRootPart: args.readBackRootPart,\n phrase: phraseBytes(args.phrase),\n storageFeatures: storageFeaturesOf(this.storage),\n })) as { fingerprint: Uint8Array };\n return proof.fingerprint;\n }\n\n /** End PENDING: delete the pending item, only against the proof on record. */\n async endPending(args: { slot: string; fingerprint: Uint8Array }): Promise<void> {\n await this.call({\n kind: \"endPending\",\n id: this.nextId++,\n slot: args.slot,\n fingerprint: args.fingerprint,\n storageFeatures: storageFeaturesOf(this.storage),\n });\n }\n\n // ---- The restore as a rotation (the account identity contract, sections\n // 3.9, 3.13, 13.1). None of these needs a client or a session: the backup\n // is opened and the whole `rotation` object is built before the device\n // exists at the server. No call takes or returns a root. ----\n\n /** Step 3 of a restore: the root part opens with the phrase to the PINNED\n * root; `hostState` is there when the root part's secret opens the state\n * part. Writes nothing. */\n openBackupForRestore(args: {\n rootPart: Uint8Array;\n phrase: string;\n statePart?: Uint8Array;\n pinnedRootPublicKey: Uint8Array;\n }): Promise<RestoreOpened> {\n return this.call({\n kind: \"openBackupForRestore\",\n id: this.nextId++,\n rootPart: args.rootPart,\n phrase: phraseBytes(args.phrase),\n statePart: args.statePart,\n pinnedRootPublicKey: args.pinnedRootPublicKey,\n }) as Promise<RestoreOpened>;\n }\n\n /**\n * M1, take the account over: the next generation (the pinned one plus one,\n * or a refusal), a NEW device key, the new generation secret, the device's\n * credential, the statement, its wrap, the new backup parts, and the\n * rotation record. `oldStatePart` gives its anchors only; `hostState` is\n * the NEW host state with the NEW sign-in key companion. Called again with\n * the same rotation id it answers the same request and the same device key.\n */\n restoreTakeOver(args: {\n rootPart: Uint8Array;\n phrase: string;\n start: RotationStart;\n oldStatePart?: Uint8Array;\n accountId: Uint8Array;\n hostState: Uint8Array;\n }): Promise<RotationBuilt> {\n return this.call({\n kind: \"restoreTakeOver\",\n id: this.nextId++,\n rootPart: args.rootPart,\n phrase: phraseBytes(args.phrase),\n start: args.start,\n oldStatePart: args.oldStatePart,\n accountId: args.accountId,\n hostState: args.hostState,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<RotationBuilt>;\n }\n\n /** \"Take your account back\": the take-over with the pending root of the\n * slot. The pending item is read, never written and never deleted.\n * `oldStatePart` is the account's state part as the escrow served it\n * (it gives its anchors only); `undefined` only when none was served.\n * ON AN EMPTY STORE EVERY JOIN IS UNCHECKED: never empty the SDK's\n * store on the service's word while the slot holds a pending item\n * (ruling V538). */\n takeAccountBack(args: {\n slot: string;\n start: RotationStart;\n oldStatePart: Uint8Array | undefined;\n accountId: Uint8Array;\n hostState: Uint8Array;\n }): Promise<RotationBuilt> {\n return this.call({\n kind: \"takeAccountBack\",\n id: this.nextId++,\n slot: args.slot,\n start: args.start,\n oldStatePart: args.oldStatePart,\n accountId: args.accountId,\n hostState: args.hostState,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<RotationBuilt>;\n }\n\n /** At every start: the rotation this device built and has not finished, or\n * `null`. While its phase is `\"built\"` the host sends the identical\n * request again. */\n resumeRotation(): Promise<PendingRotation | null> {\n return this.call({\n kind: \"resumeRotation\",\n id: this.nextId++,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<PendingRotation | null>;\n }\n\n /** `resumeRotation` WITH THE HOST'S CLOCK (ruling V461; `nowMs`, by default\n * this client's own): the call an app makes at every start. A take-over\n * the server never answered loses the sealing seed it kept once 30 days\n * have passed since its record was made; the record itself stays. */\n resumeRotationAt(nowMs: number = this.now()): Promise<PendingRotation | null> {\n return this.call({\n kind: \"resumeRotation\",\n id: this.nextId++,\n nowMs,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<PendingRotation | null>;\n }\n\n /** The server's answer to the request of record `recordId`, AS RECEIVED\n * and judged inside the SDK (ruling V161): the device adopts, or discards\n * the record only against a DIFFERENT pinned statement the root signed\n * (`\"lost\"`); a final refusal of the server (`\"refused\"`, `400\n * rotation_invalid` included) keeps the record until `abandonRotation`; any\n * other answer is `\"undecided\"` and changes nothing. */\n completeRotation(recordId: Uint8Array, answer: RotationAnswer): Promise<RotationOutcome> {\n return this.call({\n kind: \"completeRotation\",\n id: this.nextId++,\n recordId,\n answer: rotationAnswerFields(answer),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<RotationOutcome>;\n }\n\n /** Move an adopted rotation forward. */\n async setRotationPhase(recordId: Uint8Array, phase: \"device_group_done\" | \"queued\"): Promise<void> {\n await this.call({\n kind: \"setRotationPhase\",\n id: this.nextId++,\n recordId,\n phase,\n storageFeatures: storageFeaturesOf(this.storage),\n });\n }\n\n /** Step 6: delete the record of an adopted rotation. */\n async finishRotation(recordId: Uint8Array): Promise<void> {\n await this.call({\n kind: \"finishRotation\",\n id: this.nextId++,\n recordId,\n storageFeatures: storageFeaturesOf(this.storage),\n });\n }\n\n /** Ruling V212: ABANDON a rotation that was never adopted. Its record is\n * deleted, so that another rotation can start. THE PERSON'S CHOICE (after\n * `\"refused\"`, or to supply the phrase after `\"root_part_required\"`): the\n * SDK never calls it. ONLY a record the server answered with one of\n * those two is deleted (ruling V227): a record the server never answered\n * is refused (`rotation-refused`) and its request is sent again, because\n * the server may have applied it and the record then holds the only copy\n * of the new device's key. An adopted rotation is refused\n * (`rotation-refused`); it ends by `finishRotation`. */\n async abandonRotation(recordId: Uint8Array): Promise<void> {\n await this.call({\n kind: \"abandonRotation\",\n id: this.nextId++,\n recordId,\n storageFeatures: storageFeaturesOf(this.storage),\n });\n }\n\n /** Ruling V232: whether this store holds a rotation record and whether the\n * server refused it for good, so a screen can offer \"start over\" after a\n * restart without sending the request once more. One local read: no secret,\n * no id, no request. The refusal it reports is the server's unauthenticated\n * word; this read decides nothing. */\n rotationRecordState(): Promise<RotationRecordState> {\n return this.call({\n kind: \"rotationRecordState\",\n id: this.nextId++,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<RotationRecordState>;\n }\n\n /** M2, join beside the devices that stay: no rotation; a depth 0 credential\n * at the pinned generation. `restore-join-not-current`: offer M1 or a link. */\n restoreJoin(args: {\n rootPart: Uint8Array;\n phrase: string;\n statePart: Uint8Array;\n start: RotationStart;\n }): Promise<RestoreJoined> {\n return this.call({\n kind: \"restoreJoin\",\n id: this.nextId++,\n rootPart: args.rootPart,\n phrase: phraseBytes(args.phrase),\n statePart: args.statePart,\n start: args.start,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<RestoreJoined>;\n }\n\n /** Open the account's state part with the generation secret this device\n * holds, and keep its anchors. No phrase, no root.\n * It is also the ONE look a linked device owes before it writes a state\n * part: until this ran once, `refreshStateBackup` and a rotation that keeps\n * the device's key reject with the code `state-part-look-owed`. Pass an\n * EMPTY part when the service serves none; whatever this answers, the look\n * is made. */\n openStateBackup(statePart: Uint8Array): Promise<StateOpened> {\n return this.call({\n kind: \"openStateBackup\",\n id: this.nextId++,\n statePart,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<StateOpened>;\n }\n\n /** Write the account's state part anew under the generation secret this\n * device holds. */\n refreshStateBackup(args: { accountId: Uint8Array; hostState: Uint8Array }): Promise<StateRefreshed> {\n return this.call({\n kind: \"refreshStateBackup\",\n id: this.nextId++,\n accountId: args.accountId,\n hostState: args.hostState,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<StateRefreshed>;\n }\n\n /**\n * Begin a set-up session whose root is in memory only (rule R34 a): for the\n * person who makes the backup during set-up. One session per object; it\n * lives in the Worker until `sessionFinish`, `sessionKeepAsPending` or\n * `close`.\n */\n async beginInMemory(identityState: string | undefined): Promise<void> {\n await this.call({\n kind: \"beginAccountSetupInMemory\",\n id: this.nextId++,\n identityState,\n nowMs: this.now(),\n });\n }\n\n /** The session's backup. */\n sessionMakeBackup(args: { phrase: string; accountId: Uint8Array; hostState: Uint8Array }): Promise<AccountBackupParts> {\n return this.call({\n kind: \"setupSessionMakeBackup\",\n id: this.nextId++,\n phrase: phraseBytes(args.phrase),\n accountId: args.accountId,\n hostState: args.hostState,\n nowMs: this.now(),\n }) as Promise<AccountBackupParts>;\n }\n\n /** Rule R10 (b) for the session. Answers the fingerprint. */\n async sessionProveBackup(args: { readBackRootPart: Uint8Array; phrase: string }): Promise<Uint8Array> {\n const proof = (await this.call({\n kind: \"setupSessionProveBackup\",\n id: this.nextId++,\n readBackRootPart: args.readBackRootPart,\n phrase: phraseBytes(args.phrase),\n })) as { fingerprint: Uint8Array };\n return proof.fingerprint;\n }\n\n /** End the session after the proof: the device record is written, the root\n * is wiped. Only then does the host upload KeyPackages. */\n sessionFinish(): Promise<NewAccountDevice> {\n return this.call({\n kind: \"setupSessionFinish\",\n id: this.nextId++,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<NewAccountDevice>;\n }\n\n /** \"Not now\" after the session began (ruling ID42): THIS session's root\n * becomes the pending item, then the device record is written. */\n sessionKeepAsPending(args: { slot: string; persistentStorage?: boolean }): Promise<NewAccountDevice> {\n return this.call({\n kind: \"setupSessionKeepAsPending\",\n id: this.nextId++,\n slot: args.slot,\n persistentStorage: args.persistentStorage,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<NewAccountDevice>;\n }\n\n /** Stop the Worker. A session still open there is wiped with it. */\n close(): void {\n if (this.closed) return;\n this.closed = true;\n try {\n this.worker.postMessage({ kind: \"endAccountSetupSession\", id: this.nextId++ } as Request);\n } catch {\n // The worker is gone already: nothing is left to wipe.\n }\n this.worker.onmessage = null;\n this.worker.onerror = null;\n this.worker.terminate();\n this.fail(new AccountSetupClosedError());\n }\n\n private fail(error: unknown): void {\n const waiting = [...this.pending.values()];\n this.pending.clear();\n for (const slot of waiting) slot.reject(error);\n }\n\n /** Post a request. A recovery phrase in it crossed as bytes (ruling\n * V253): this side's copy is zeroed when the call has answered, whatever\n * it answered; the Worker zeroes its own. */\n private call(req: Request): Promise<unknown> {\n const phrase = (req as { phrase?: unknown }).phrase;\n const answered = this.post(req);\n return phrase instanceof Uint8Array ? answered.finally(() => { phrase.fill(0); }) : answered;\n }\n\n private post(req: Request): Promise<unknown> {\n if (this.closed) return Promise.reject(new AccountSetupClosedError());\n return new Promise((resolve, reject) => {\n this.pending.set((req as { id: number }).id, { resolve, reject });\n try {\n this.worker.postMessage(req);\n } catch (e) {\n this.pending.delete((req as { id: number }).id);\n reject(e);\n }\n });\n }\n\n private async handleWorker(msg: Response): Promise<void> {\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 if (msg.ok) slot.resolve(msg.value);\n else slot.reject(new Error(msg.error));\n return;\n }\n case \"storage.call\": {\n try {\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 value = await (method as (...a: unknown[]) => unknown).apply(this.storage, msg.args);\n if (!this.closed) this.worker.postMessage({ kind: \"storage.reply\", id: msg.id, ok: true, value } as Request);\n } catch (e) {\n if (!this.closed) {\n this.worker.postMessage({ kind: \"storage.reply\", id: msg.id, ok: false, error: String(e) } as Request);\n }\n }\n return;\n }\n case \"transport.call\": {\n // Set-up sends nothing and reads nothing from the server.\n this.worker.postMessage({\n kind: \"transport.reply\", id: msg.id, ok: false, error: \"account set-up has no transport\",\n } as Request);\n return;\n }\n default:\n return;\n }\n }\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 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 // Label is unused on the read-only path (no LocalDevice is ever minted).\n const client =\n await wasm.PingClient.openReadOnlyFromDeviceRecord(\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACuBO,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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-coalescer.ts","../src/storage/scope.ts","../src/sequenced.ts","../src/storage/indexeddb.ts","../src/wire-contract.ts","../src/transport/websocket.ts","../src/account-setup.ts","../src/wasm-memory.ts","../src/notification-preview.ts"],"sourcesContent":["// 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 BackupCheckFailure, BackupPhraseCheck,\n CatchupAppEvent, CatchupSnapshotView, CommitInDoubt,\n ConversationId, ConversationMeta, ConversationPolicy, DeviceId, DeviceLinkApproval, DeviceLinkPossession,\n ExpectedOwner, ExportedSecret,\n DeviceReauthProof, DeviceRemovalReport, IncomingMessage,\n HistoryBundle, HistoryDeliveryKeyStatement, HistoryShipDecision, OpenedHistory, LogHead, LogHole, LogPosition, MemberInfo, MessageBatchMeta, PendingApply,\n KeyPackageEntry, LinkGeneration, LinkedDevice, LinkingTicketV3, MessageEnvelope, 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 LogHoleWire,\n type LogPositionWire,\n logHeadToWire,\n logHoleFromWire,\n logPositionFromWire,\n sequencedToWire,\n type SyncStepResultWire,\n syncStepResultFromWire,\n} from \"./sequenced\";\n\nexport type * from \"./types\";\nimport type { FetchedSealedGroupInfo, SelfAdmitManyEntry, SelfAdmitResult } from \"./types\";\nimport type { StateRefreshed as StateRefreshedResult } from \"./account-setup\";\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\";\nexport { AccountSetup, AccountSetupClosedError, accountRefusalCode } from \"./account-setup\";\nimport { rotationAnswerFields } from \"./account-setup\";\nexport type { AdoptedGeneration, RotationBuild, RotationKeptRefusal, RotationPlan, RotationStartDevice } from \"./account-setup\";\nimport type {\n AdoptedGeneration as AdoptedGenerationResult,\n RotationBuild as RotationBuildResult,\n RotationAnswer as RotationAnswerInput,\n RotationOutcome as RotationOutcomeResult,\n RotationPlan as RotationPlanResult,\n RotationStart as RotationStartInput,\n RotationStartDevice as RotationStartDeviceInput,\n SealingStatement as SealingStatementInput,\n} from \"./account-setup\";\nexport type {\n AccountBackupParts,\n AccountSetupConfig,\n DeviceStartCheck,\n NewAccountDevice,\n PendingRootDiscard,\n PendingRootStatus,\n PreparedDeviceKey,\n PendingRotation,\n RestoreJoined,\n RestoreOpened,\n RotationAnswer,\n RotationBuilt,\n RotationOutcome,\n RotationPhase,\n RotationRecordState,\n RotationRequest,\n RotationStart,\n SealingStatement,\n StateOpened,\n StateRefreshed,\n} from \"./account-setup\";\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\n/**\n * What `MessagingClient.initFromDeviceRecord` takes: the `ClientConfig`. It\n * carries no account identity: the device record in `storage` (written by\n * account set-up, a link or a restore) says which account and device this is.\n * `deviceSigningSecretKey`, when given, is the key the host kept from the\n * call that made the device, and must be the record's own. (The name is kept\n * from the time a second start took an identity export; that start left\n * every binding on 2026-11-28.)\n */\nexport type DeviceRecordClientConfig = ClientConfig;\n\n/**\n * What the start of a NEW device's link takes\n * ({@link MessagingClient.beginDeviceLink}). No key: the SDK draws the device\n * key itself.\n */\nexport type DeviceLinkClientConfig = Omit<ClientConfig, \"deviceSigningSecretKey\" | \"expectedOwners\">;\n\n/**\n * What {@link MessagingClient.beginDeviceLink} answers. `client` is the\n * staging client: it completes the link (`completeDeviceLink`) and is then\n * closed. `deviceSigningSecretKey` and `hpkeSecretKey` are SECRETS, handed\n * over once: keep them where the app keeps a device key. Publish, and show\n * the commitment of, exactly `payload`.\n */\nexport interface DeviceLinkBegun {\n client: MessagingClient;\n payload: Uint8Array;\n deviceId: Uint8Array;\n deviceSigningSecretKey: Uint8Array;\n hpkeSecretKey: Uint8Array;\n}\n\nexport interface ClientConfig {\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 * `true` ONLY for the client of the tab the person is using (ruling V244).\n * It allows this client's Worker to BUILD a rotation\n * (`rotateGenerationWithPending`, `rotateGenerationWithBackup`), the two\n * calls for which the Worker opens the account's root. Leave it out for\n * every background session's client: such a Worker never builds a rotation\n * (`account refused: background-worker`). Only the value `true` counts.\n */\n tabClient?: boolean;\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 * ONE lane of sequenced live frames for every conversation: the first\n * frame goes to the worker at once, frames that arrive while that batch is\n * in flight go out as ONE `processSequencedBatch` when it returns, in\n * arrival order. Rows the engine did not take (`notTaken`) stay in the\n * lane and are handed again after the next `confirmApplied`. See\n * {@link dispatchIncoming}.\n */\n private readonly coalescer = new InboundCoalescer<SequencedEnvelope>(\n (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: DeviceRecordClientConfig, 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 /**\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 /** 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 // ---- The link handshake commitment (2026-11-25) ----\n //\n // REMOVED 2026-11-28 (ruling V576): `openLinkingTicket`, `openLinkingTicketPq`,\n // `sealLinkingTicketFor`, `buildLinkingTicketFor`, `consumeLinkingTicket` and the type\n // `LinkingTicket`. A ticket of version 1 or 2 carries a binding an ACCOUNT KEY signs;\n // the only ticket is version 3 (`buildLinkingTicketV3For`, `completeDeviceLink`).\n // REMOVED 2026-11-25 (ruling ID15): `sealLinkingTicket`, `sealLinkingTicketPq`,\n // `signDeviceLinkApproval` (a raw key) and `buildLinkingTicket(deviceId,\n // keyPackage)`. Every call below takes the handshake payload the relay returned\n // together with what THIS device was shown (`expected`) and verifies inside the\n // call, so nothing can be approved for, built for or sealed to a handshake that\n // was not verified. `hpkeSeal*` refuse the infos `ping/link/*` and\n // `ping/link-auth/*`. Host notes: docs-site/api.md, \"Device link commitment\".\n\n /**\n * The commitment of a handshake payload: what a NEW device shows for the exact\n * bytes it publishes ({@link MessagingClient.linkHandshakePayload}). `qrText` is\n * `{\"v\":3,\"h\":\"<base64url(commitment)>\"}`; `code` is the 20 characters the relay\n * indexes; `codeDisplay` is the same in five groups of four.\n */\n static async linkCommitment(payload: Uint8Array): Promise<LinkCommitment> {\n const parts = await MessagingClient.ephemeralWorkerCall<[Uint8Array, string, string, string]>({\n kind: \"linkCommitment\", id: 1, payload,\n });\n return { commitment: parts[0], qrText: parts[1], code: parts[2], codeDisplay: parts[3] };\n }\n\n /**\n * THE normaliser of a typed link code. Hand it what the person typed; send the\n * relay, and pass to the calls below, only the 20 characters it returns. No host\n * normalises a code itself. Rejects anything that is not a code.\n */\n static async normalizeLinkCode(typed: string): Promise<string> {\n return MessagingClient.ephemeralWorkerCall<string>({ kind: \"normalizeLinkCode\", id: 1, typed });\n }\n\n /** The 32 bytes of a QR text `{\"v\":3,\"h\":\"...\"}`. Rejects any other shape. */\n static async linkQrCommitment(qrText: string): Promise<Uint8Array> {\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({ kind: \"linkQrCommitment\", id: 1, qrText });\n }\n\n /**\n * Verify the handshake payload a relay returned against what this device was\n * shown. Call it BEFORE anything else is done with the handshake. Rejects with\n * {@link LinkCommitmentMismatchError} when the payload is not the committed one:\n * send nothing, open no approval session, ask the person to try again.\n */\n static async verifyLinkHandshake(\n payload: Uint8Array,\n expected: LinkExpected,\n ): Promise<VerifiedLinkHandshakeInfo> {\n const all = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"verifyLinkHandshake\", id: 1, payload, ...linkExpectedFields(expected),\n });\n if (all.length !== 97) {\n throw new Error(\"verifyLinkHandshake: expected 97 bytes\");\n }\n return {\n deviceId: all.slice(0, 32),\n deviceSigningPubkey: all.slice(32, 64),\n commitment: all.slice(64, 96),\n verifiedByQr: all[96] === 1,\n };\n }\n\n /**\n * HPKE-seal the device-linking auth envelope (`ping/link-auth/v2`) to the\n * X-Wing key of the handshake `payload`, verified inside the call.\n */\n static async sealLinkAuthFor(\n plaintext: Uint8Array,\n payload: Uint8Array,\n expected: LinkExpected,\n ): Promise<Uint8Array> {\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"sealLinkAuthFor\", id: 1, plaintext, payload, ...linkExpectedFields(expected),\n });\n }\n\n /**\n * Link verification v2, on the EXISTING device: approve the new device of the\n * handshake `payload`, verified inside the call, on one server link session with\n * this device's signing key. The signed bytes are those of\n * docs/DEVICE_LINK_V2_VECTORS.md; the key that is approved is the handshake's\n * device signing key and cannot be passed separately. `audience` as for\n * {@link signDeviceReauth}. Runs in an ephemeral worker.\n */\n static async signDeviceLinkApprovalFor(params: {\n deviceSigningSecretKey: Uint8Array;\n approvalSessionId: Uint8Array;\n accountId: Uint8Array;\n payload: Uint8Array;\n expected: LinkExpected;\n audience: string;\n }): Promise<DeviceLinkApproval> {\n const { deviceSigningSecretKey, approvalSessionId, accountId, payload, expected, audience } =\n params;\n if (deviceSigningSecretKey.length !== 32) {\n throw new Error(\"signDeviceLinkApprovalFor: deviceSigningSecretKey must be 32 bytes\");\n }\n if (approvalSessionId.length !== 16) {\n throw new Error(\"signDeviceLinkApprovalFor: approvalSessionId must be 16 bytes\");\n }\n if (accountId.length !== 16) {\n throw new Error(\"signDeviceLinkApprovalFor: accountId must be 16 bytes\");\n }\n const all = await MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"signDeviceLinkApprovalFor\", id: 1,\n deviceSigningSecretKey, approvalSessionId, accountId, payload,\n ...linkExpectedFields(expected), audience,\n });\n if (all.length !== 128) {\n throw new Error(\"signDeviceLinkApprovalFor: 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 a static call 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 /**\n * Start the client FROM THE DEVICE RECORD: the ONE start of a client (after\n * `AccountSetup`, a link or a restore wrote the record into `cfg.storage`).\n * The client holds no account key: every leaf and KeyPackage it builds\n * carries the one credential the device holds (`heldCredential()`). No call\n * starts a client from an account identity and none hands one out (the\n * start from an identity export, `generateIdentity` and `exportIdentity`\n * left every binding on 2026-11-28). Rejects when the\n * store holds no device record, or when `cfg.deviceSigningSecretKey` is not\n * the record's own device key.\n */\n static async initFromDeviceRecord(cfg: DeviceRecordClientConfig): Promise<MessagingClient> {\n return (await MessagingClient.start(cfg, \"record\")).client;\n }\n\n /**\n * Begin a link on a NEW device, in one call: the SDK draws the device key\n * (no field of `cfg` is a key), records \"link begun\" in `cfg.storage`,\n * starts the staging client and builds the handshake payload. A repeat\n * after a reload answers the SAME key and the SAME handshake. Rejects with\n * `account refused: account-already-set-up` over a store that already holds\n * a device.\n */\n static async beginDeviceLink(cfg: DeviceLinkClientConfig): Promise<DeviceLinkBegun> {\n const { client, answer } = await MessagingClient.start(cfg, \"link\");\n const begun = answer as Omit<DeviceLinkBegun, \"client\">;\n return { client, ...begun };\n }\n\n /**\n * HPKE-seal a version 3 ticket to the X-Wing key of the handshake `payload`,\n * verified inside the call (`ping/link/v2`). Rejects a ticket that was built\n * for another device than the handshake's.\n */\n static async sealLinkingTicketV3For(\n ticket: LinkingTicketV3,\n payload: Uint8Array,\n expected: LinkExpected,\n ): Promise<Uint8Array> {\n return MessagingClient.ephemeralWorkerCall<Uint8Array>({\n kind: \"sealLinkingTicketV3For\", id: 1, ticket, payload, ...linkExpectedFields(expected),\n });\n }\n\n /**\n * HPKE-open a sealed version 3 ticket with the new device's X-Wing seed.\n * NOT yet verified: `completeDeviceLink` runs every check.\n */\n static async openLinkingTicketV3(\n sealed: Uint8Array,\n newDevicePriv: Uint8Array,\n ): Promise<LinkingTicketV3> {\n return MessagingClient.ephemeralWorkerCall<LinkingTicketV3>({\n kind: \"openLinkingTicketV3\", id: 1, sealed, newDevicePriv,\n });\n }\n\n private static async start(\n cfg: DeviceRecordClientConfig,\n mode: \"record\" | \"link\",\n ): Promise<{ client: MessagingClient; answer: unknown }> {\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 sendExternalCommit: typeof cfg.transport.sendExternalCommit === \"function\",\n fetchSelfAdmissionStates: typeof cfg.transport.fetchSelfAdmissionStates === \"function\",\n fetchSealedGroupInfos: typeof cfg.transport.fetchSealedGroupInfos === \"function\",\n sendExternalCommits: typeof cfg.transport.sendExternalCommits === \"function\",\n fetchSealingStatements: typeof cfg.transport.fetchSealingStatements === \"function\",\n publishSealedGroupInfo: typeof cfg.transport.publishSealedGroupInfo === \"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 const first = {\n id: client.nextId++,\n deviceLabel: cfg.deviceLabel,\n nowMs: client.now(),\n ...(cfg.deviceSigningSecretKey\n ? { deviceSigningSecretKey: cfg.deviceSigningSecretKey }\n : {}),\n ...(cfg.expectedOwners ? { expectedOwners: cfg.expectedOwners } : {}),\n // Handed on as given: the Worker counts only the value `true`.\n ...(cfg.tabClient !== undefined ? { tabClient: cfg.tabClient } : {}),\n transportFeatures,\n storageFeatures,\n };\n const answer = await client.call(\n mode === \"link\"\n ? {\n kind: \"beginDeviceLink\",\n id: first.id, deviceLabel: first.deviceLabel, nowMs: first.nowMs,\n transportFeatures, storageFeatures,\n }\n : { kind: \"initFromDeviceRecord\", ...first },\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, answer };\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 goes to the worker at once as a batch of one,\n * and frames of ANY conversation that arrive while that batch is in flight\n * accumulate and go out as ONE `processSequencedBatch` when it returns, in\n * arrival order (one lane for all conversations: a catch-up of 200\n * conversations is about 20 Worker calls, not 400); no timer ever delays a\n * frame. Rows the engine did not take because the pending-apply journal\n * had no room (`notTaken`) stay in the lane, in order, and are handed\n * again after the next `confirmApplied`. 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 // The dispatch promise resolves either way, exactly as the legacy\n // path treats a failed envelope: the core retains anything it could\n // not apply yet. A frame the engine did not TAKE (the journal had no\n // room) stays pending here until a later batch takes it.\n return this.coalescer.push(hexOf(frame.envelope.conversation_id), frame).catch((e: unknown) => {\n if (typeof console !== \"undefined\") console.debug(\"[ping-sdk] sequenced batch failed:\", errorKind(e));\n });\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, of any number of conversations.\n * Answers the indexes of the rows the engine did not take (the journal\n * had no room): the lane keeps those and hands them again after the next\n * `confirmApplied`. A rejection goes to the lane, which hands a refused\n * batch again one conversation at a time; `dispatchIncoming` logs what\n * still fails at debug and resolves.\n */\n private async applyLiveBatch(items: SequencedEnvelope[]): Promise<readonly number[]> {\n const result = await this.processSequencedBatch(items);\n return result.notTaken;\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 async deviceId(): Promise<DeviceId> {\n return await this.call({ kind: \"deviceId\", id: this.nextId++ }) as DeviceId;\n }\n\n /** The credential this device HOLDS for itself (version 2), which every\n * leaf and KeyPackage it builds carries. A public value. Never absent\n * (2026-11-28): every client starts from a device record. Rejects with\n * `NoDeviceRecord` on a read-only client, which holds no credential. */\n async heldCredential(): Promise<Uint8Array> {\n return await this.call({ kind: \"heldCredential\", id: this.nextId++ }) as Uint8Array;\n }\n\n /** The generation of the held credential. Rejects as `heldCredential` does. */\n async heldGeneration(): Promise<number> {\n return await this.call({ kind: \"heldGeneration\", id: this.nextId++ }) as number;\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 * Rejects with `StoreMovedError` when the client failed closed: before the\n * pass (it then asks nothing of the server), inside one of its steps (no\n * later conversation is asked; the pages before it were delivered), or\n * during its last step. A client that failed closed before or during the\n * pass never resolves at all, with an empty list or with any other. The\n * host drops the client and starts a new one on the same store, which\n * hands what was stored (`pendingApplies`).\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 /**\n * SELF-ADMISSION: enter `conversationId` by this device's own act, from\n * what the delivery service returned for it (the sealed GroupInfo and\n * this account's wrap). Every refusal is a VALUE (`kind: \"refused\"`);\n * while the SDK is built without self-admission the answer is `refusal:\n * \"notCompiled\"` and nothing was touched. The client reads the anchor\n * record its device holds by itself, before the join. Rejects only for an\n * id of the wrong length.\n *\n * THE MESSAGES OF A JOIN. `joined` carries `replayed`: messages of this\n * conversation that waited for the join. Show them, save them and\n * confirm them (`confirmApplied`) exactly as the messages of a batch\n * (also for every `joined` entry of `selfAdmitMany`). This client\n * DELIVERS them to its observers by itself (source `live`), as it\n * delivers the messages of `processSequencedBatch`; Swift and Kotlin\n * return them, as they return a batch's messages.\n */\n async selfAdmit(conversationId: ConversationId, fetched: FetchedSealedGroupInfo): Promise<SelfAdmitResult> {\n const result = await this.call({\n kind: \"selfAdmit\", id: this.nextId++, conv: conversationId,\n fetched: {\n blob: fetched.blob, wrap: fetched.wrap, wrapCount: fetched.wrapCount,\n ...(fetched.currentEpoch === undefined ? {} : { currentEpoch: fetched.currentEpoch }),\n },\n nowMs: this.now(),\n }) as SelfAdmitResult;\n if (result.kind === \"joined\") {\n holeOfJoin(result);\n this.fanout.deliverBatch(result.replayed, { source: \"live\" });\n }\n return result;\n }\n\n /**\n * Enter MANY conversations with few requests (the transport's\n * `fetchSelfAdmissionStates`, `fetchSealedGroupInfos` and\n * `sendExternalCommits`): `first` (the conversation on screen) goes to\n * the head, then the order given, each once. One entry per conversation,\n * each judged and answered alone. A conversation this device holds and is\n * not stranded in answers `alreadyHeld` with no request. Nothing is\n * polled: call again when the account event of a publication arrives.\n */\n async selfAdmitMany(\n conversations: ConversationId[], opts: { first?: ConversationId } = {},\n ): Promise<SelfAdmitManyEntry[]> {\n const entries = await this.call({\n kind: \"selfAdmitMany\", id: this.nextId++,\n ...(opts.first === undefined ? {} : { first: opts.first }),\n conversations, nowMs: this.now(),\n }) as SelfAdmitManyEntry[];\n for (const entry of entries) {\n if (entry.result.kind === \"joined\") {\n holeOfJoin(entry.result);\n this.fanout.deliverBatch(entry.result.replayed, { source: \"live\" });\n }\n }\n return entries;\n }\n\n /**\n * THE ONE CALL A HOST REMEMBERS FOR THE ANCHOR RECORD: write the account's\n * state part from the RUNNING client. The record of who may sign a\n * GroupInfo a restoring device enters by is rebuilt from this client's\n * own conversations first (at every call; the SDK also rebuilds it\n * by itself during `processSequencedBatch` and at every rotation), and\n * the part carries it. The host stores the part where it stores every\n * state part. (`AccountSetup.refreshStateBackup` takes a store and\n * carries the record as it was last built.)\n *\n * A LINKED device owes ONE look first: until `AccountSetup.openStateBackup`\n * ran once on it, this rejects with the code `state-part-look-owed` (so does\n * a rotation that keeps the device's key). Pass an EMPTY part there when the\n * service serves none; whatever it answers, the look is made.\n */\n async refreshStateBackup(args: { accountId: Uint8Array; hostState: Uint8Array }): Promise<StateRefreshedResult> {\n return await this.call({\n kind: \"clientRefreshStateBackup\", id: this.nextId++,\n accountId: args.accountId, hostState: args.hostState, nowMs: this.now(),\n }) as StateRefreshedResult;\n }\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 * The holes of one conversation's log on this device, lowest position\n * first: every position at or below the stored position that was not\n * applied, with the reason and the content hashes the envelopes named.\n * `kept: true` entries are rows the SDK still holds and retries by itself.\n */\n async logHoles(id: ConversationId): Promise<LogHole[]> {\n const raw = await this.call({ kind: \"logHoles\", id: this.nextId++, conv: id }) as LogHoleWire[];\n return raw.map(logHoleFromWire);\n }\n\n /**\n * The host filled `fromServerSeq..toServerSeq` (inclusive) of a\n * conversation from elsewhere (the account's other device): take the range\n * out of the recorded holes. Resolves `true` when a recorded hole changed.\n */\n async resolveLogHole(id: ConversationId, fromServerSeq: number, toServerSeq: number): Promise<boolean> {\n return await this.call({\n kind: \"resolveLogHole\", id: this.nextId++, conv: id, fromServerSeq, toServerSeq,\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 // The journal has room again: the live frames the last batch did not\n // take are handed now.\n this.coalescer.roomFreed();\n }\n\n /**\n * The version 3 handshake payload this NEW device publishes: its own signing key,\n * the id derived from it, `hpkePublicKey` (X-Wing, 1216 bytes) and a KeyPackage it\n * just made. Show {@link MessagingClient.linkCommitment} of exactly these bytes and\n * publish exactly these bytes; nobody re-serialises them.\n */\n async linkHandshakePayload(hpkePublicKey: Uint8Array, keyPackage: Uint8Array): Promise<Uint8Array> {\n return await this.call({\n kind: \"linkHandshakePayload\", id: this.nextId++, hpkePublicKey, keyPackage,\n }) as Uint8Array;\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 /**\n * The linking ticket, version 3, for the handshake `payload`, verified\n * inside the call: for a client started from a device record. The new\n * device's credential is signed by THIS device's key. Rejects when this\n * device's own chain is at its limit (show the \"link from another device\"\n * copy) or it holds no device record. Seal it with\n * {@link MessagingClient.sealLinkingTicketV3For} and the SAME payload and\n * `expected`.\n */\n async buildLinkingTicketV3For(\n payload: Uint8Array,\n expected: LinkExpected,\n lastAppEvents: CatchupAppEvent[] = [],\n ): Promise<LinkingTicketV3> {\n return await this.call({\n kind: \"buildLinkingTicketV3For\", id: this.nextId++,\n payload, ...linkExpectedFields(expected), lastAppEvents, nowMs: this.now(),\n }) as LinkingTicketV3;\n }\n\n /**\n * The generation and its secret for the link-auth envelope, version 6:\n * answered only for a handshake whose version 3 ticket this client built\n * since it started.\n */\n async linkGenerationFor(payload: Uint8Array, expected: LinkExpected): Promise<LinkGeneration> {\n return await this.call({\n kind: \"linkGenerationFor\", id: this.nextId++, payload, ...linkExpectedFields(expected),\n }) as LinkGeneration;\n }\n\n /**\n * Complete the link on the NEW device, on the staging client of\n * {@link MessagingClient.beginDeviceLink}: every check of the ticket and of\n * the envelope's two values, then the DeviceGroup, then the device record.\n * Rejects with `account refused: link-refused` when anything does not fit:\n * nothing was kept. Afterwards close this client and start\n * {@link MessagingClient.initFromDeviceRecord} on the same store.\n */\n async completeDeviceLink(\n ticket: LinkingTicketV3,\n generation: number,\n generationSecret: Uint8Array,\n ): Promise<LinkedDevice> {\n return await this.call({\n kind: \"completeDeviceLink\", id: this.nextId++,\n ticket, generation, generationSecret, nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as LinkedDevice;\n }\n\n /**\n * Create the DeviceGroup anew after a take-over (the account identity\n * contract, 3.13, \"The DeviceGroup reset\"): drops what this device holds\n * under the DeviceGroup's id, then creates the group alone. Call it ONLY\n * after the server answered the DeviceGroup reset with `200` or with the\n * reason `already_reset`. There is no call that joins a DeviceGroup from\n * outside.\n */\n async recreateDeviceGroup(): Promise<void> {\n await this.call({ kind: \"recreateDeviceGroup\", id: this.nextId++, nowMs: this.now() });\n }\n\n /**\n * Step 0 of a rotation (removing a device, Secure my account): the next\n * generation is the pinned one plus one, proven by the root's own\n * statement, or the call rejects (`account refused:\n * pinned-generation-unproven`, `generation-ahead`). A listed device is\n * offered only when its signed delivery key verifies under a leaf of THIS\n * device's own DeviceGroup. Signs nothing.\n */\n async planRotation(\n start: RotationStartInput, devices: RotationStartDeviceInput[], rootPartGeneration = 0,\n ): Promise<RotationPlanResult> {\n return await this.call({\n kind: \"planRotation\", id: this.nextId++, start, devices, rootPartGeneration,\n }) as RotationPlanResult;\n }\n\n /**\n * Step 1 of a rotation, THE BUILD, with the pending item of `slot` as the\n * root's source (an account with no backup yet). It runs in this client's\n * Worker, which opens the root itself for the length of the call (rulings\n * V136 and V244): nothing of the root reaches this realm or any other\n * Worker, in the answer or in a refusal. Only the tab's own client builds\n * (`ClientConfig.tabClient`); any other answers `account refused:\n * background-worker`. `kept` is every device that stays, this one\n * included. The answer is the request for the server (public values and\n * ciphertext) with the record's id, or `keptSetRefused` naming the one\n * device that cannot be kept: a value, final for that kept set. The\n * request carries no root part. No request is made by this call.\n */\n async rotateGenerationWithPending(args: {\n slot: string; start: RotationStartInput; devices: RotationStartDeviceInput[]; kept: Uint8Array[];\n reason: \"remove\" | \"secure_account\"; accountId: Uint8Array; hostState: Uint8Array;\n }): Promise<RotationBuildResult> {\n return await this.call({\n kind: \"rotateGenerationWithPending\", id: this.nextId++, slot: args.slot,\n start: args.start, devices: args.devices, kept: args.kept, reason: args.reason,\n accountId: args.accountId, hostState: args.hostState, nowMs: this.now(),\n }) as RotationBuildResult;\n }\n\n /**\n * Step 1 of a rotation, THE BUILD, with the backup as the root's source:\n * the root part as the server holds it and the CURRENT recovery phrase,\n * and `newPhrase` when the person asked for a new one. As\n * {@link rotateGenerationWithPending}: the root part is opened inside this\n * client's Worker for the length of the call. The phrases cross to the\n * Worker as bytes; the Worker zeroes its copy when the call has answered\n * and this call zeroes the copy it made. The strings themselves are the\n * host's: drop them. A phrase that does not open the root part answers\n * `account refused: backup-authentication` and nothing of the cause.\n */\n async rotateGenerationWithBackup(args: {\n rootPart: Uint8Array; phrase: string; newPhrase?: string;\n start: RotationStartInput; devices: RotationStartDeviceInput[]; kept: Uint8Array[];\n reason: \"remove\" | \"secure_account\"; accountId: Uint8Array; hostState: Uint8Array;\n }): Promise<RotationBuildResult> {\n const encoder = new TextEncoder();\n const phrase = encoder.encode(args.phrase);\n const newPhrase = args.newPhrase === undefined ? undefined : encoder.encode(args.newPhrase);\n try {\n return await this.call({\n kind: \"rotateGenerationWithBackup\", id: this.nextId++, rootPart: args.rootPart,\n phrase, ...(newPhrase ? { newPhrase } : {}),\n start: args.start, devices: args.devices, kept: args.kept, reason: args.reason,\n accountId: args.accountId, hostState: args.hostState, nowMs: this.now(),\n }) as RotationBuildResult;\n } finally {\n phrase.fill(0);\n newPhrase?.fill(0);\n }\n }\n\n /**\n * Step 3 of a rotation this device built, on the running client: the\n * server's answer AS RECEIVED, judged inside the SDK (ruling V161; no\n * value says \"applied\"). When the device adopts, this client runs on the\n * new record from that moment. `\"undecided\"`: nothing changed, the record\n * stays.\n */\n async completeRotation(\n recordId: Uint8Array, answer: RotationAnswerInput,\n ): Promise<RotationOutcomeResult> {\n return await this.call({\n kind: \"completeRotationOnClient\", id: this.nextId++, recordId,\n answer: rotationAnswerFields(answer),\n }) as RotationOutcomeResult;\n }\n\n /**\n * Step 7 of a rotation, on every other kept device: this device's mailbox\n * row (`GET /v1/devices/self/credential`). The credential must be this\n * device's and the root's own; the wrap must open with this device's\n * delivery key and match the root's statement. On any refusal the device\n * stays on its generation. From the adoption on, this device's next Commit\n * in each conversation carries its new credential.\n */\n async adoptGeneration(row: {\n generation: number; credential: Uint8Array; gsWrap: Uint8Array; statement: SealingStatementInput;\n }): Promise<AdoptedGenerationResult> {\n return await this.call({\n kind: \"adoptGeneration\", id: this.nextId++, generation: row.generation,\n credential: row.credential, gsWrap: row.gsWrap, statement: row.statement, nowMs: this.now(),\n }) as AdoptedGenerationResult;\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. `encryptBackup` and `decryptBackup`\n // (the version 1 blob) took and returned the account identity and left every\n // binding on 2026-11-28: a backup is made, proven and opened by `AccountSetup`\n // and the restore calls, which hand no root to a host.\n\n /**\n * The one switch of self-admission as the wasm module of this package was\n * COMPILED (a constant of the SDK's source: the same value in every artifact\n * built from one commit). Read-only. `false`: the module refuses every\n * external Commit, lists no capability marker and sends nothing of the\n * feature. A host that ships more than one artifact asserts at start that\n * they agree.\n */\n static async selfAdmissionCompiled(): Promise<boolean> {\n return MessagingClient.ephemeralWorkerCall<boolean>({\n kind: \"selfAdmissionCompiled\", id: 1,\n });\n }\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. */\n static async normalizeMnemonicPhrase(phrase: string): Promise<string> {\n return MessagingClient.ephemeralWorkerCall<string>({\n kind: \"normalizeMnemonicPhrase\", id: 1, phrase,\n });\n }\n\n /**\n * Whether `mnemonicPhrase` opens `blob` (a recovery backup as the server returned\n * it), with THREE answers to switch on:\n *\n * - `{ outcome: \"opens\" }`;\n * - `{ outcome: \"authenticationFailed\" }`: PROOF. The backup's own authentication\n * check failed under the key derived from the phrase, so the phrase does not open\n * these exact bytes (wrong words, or bytes that are not what the words sealed: an\n * AEAD cannot tell a changed or shortened ciphertext from wrong words, so hand in\n * the complete bytes). The only answer on which to delete a stored phrase;\n * - `{ outcome: \"couldNotCheck\", reason }`: DOUBT. A phrase that is not a phrase, a\n * version or a format this build cannot read, a payload it cannot decode, a\n * failure inside the SDK. Delete nothing, claim nothing, ask again later.\n *\n * This call NEVER rejects: a wasm trap, an out-of-memory failure and a one-shot\n * worker that could not be created or did not answer are `couldNotCheck` with\n * `reason: \"internal\"`. It resolves nothing of the backup: the decrypted identity\n * is wiped inside the SDK. One Argon2id derivation, on a one-shot worker.\n */\n static async checkBackupPhrase(\n blob: Uint8Array,\n mnemonicPhrase: string,\n ): Promise<BackupPhraseCheck> {\n try {\n return backupPhraseCheckFromWire(\n await MessagingClient.ephemeralWorkerCall<unknown>({\n kind: \"checkBackupPhrase\", id: 1, blob, mnemonicPhrase,\n }),\n );\n } catch {\n // Whatever stopped the check says nothing about the phrase.\n return { outcome: \"couldNotCheck\", reason: \"internal\" };\n }\n }\n\n // ------------------------ Peer-assisted history transfer ------------------------\n // History, version 3 (2026-11-25, rulings V88 to V92). A bundle is signed by\n // this DEVICE's key and sealed only to a key the SDK verified itself: the\n // signed delivery key of a device that is a verified leaf of this device's own\n // tree, or the key of a link handshake verified against what the person was\n // shown. No call takes a recipient key, so a server that answers a key request\n // with a key of its own gets nothing. The raw-key, seed-signed forms\n // (sealHistoryBundle, openHistoryBundle and their Pq twins) are REMOVED.\n\n /** The counter the next {@link publishHistoryDeliveryKey} with this floor will\n * sign. A host that keeps the device key outside the SDK's store writes this\n * number beside that key BEFORE the publish, and passes what it kept as\n * `counterFloor` from then on (0 when it keeps none). Never a server's number. */\n async historyDeliveryKeyNextCounter(counterFloor = 0): Promise<number> {\n return await this.call({\n kind: \"historyDeliveryKeyNextCounter\", id: this.nextId++, counterFloor,\n }) as number;\n }\n\n /** This device's signed history delivery key: post it at every start. The key\n * pair is made once, inside the SDK; the device signs only the key it holds. */\n async publishHistoryDeliveryKey(counterFloor = 0): Promise<HistoryDeliveryKeyStatement> {\n return await this.call({\n kind: \"publishHistoryDeliveryKey\", id: this.nextId++, counterFloor,\n }) as HistoryDeliveryKeyStatement;\n }\n\n /** The server refused the publication (`409 delivery_key_counter_behind`) and\n * answered with the statement IT holds. Taken only when that statement\n * verifies strictly under THIS device's own key and is not older than this\n * device's own; resolves with the statement to publish once more. Anything\n * else rejects ({@link NotPermittedError}) and nothing is signed. */\n async adoptHistoryDeliveryKeyCounter(\n stored: HistoryDeliveryKeyStatement,\n ): Promise<HistoryDeliveryKeyStatement> {\n return await this.call({\n kind: \"adoptHistoryDeliveryKeyCounter\", id: this.nextId++, stored,\n }) as HistoryDeliveryKeyStatement;\n }\n\n /**\n * Verify `recipient` (the statement a server returned for the device the bundle\n * names) in this device's own tree, then sign the bundle with the device key and\n * seal it to that key. `ownAccount` is what the host believes (true: a device of\n * this account, looked up in the DeviceGroup; false: another account's device,\n * looked up in the tree of the bundle's conversation). It decides nothing: the\n * SDK takes the path the recipient's verified identity gives and rejects\n * ({@link NotPermittedError}) when the host said the other one.\n */\n async sealHistoryBundleV3(\n bundle: HistoryBundle,\n recipient: HistoryDeliveryKeyStatement,\n ownAccount: boolean,\n ): Promise<Uint8Array> {\n return await this.call({\n kind: \"sealHistoryBundleV3\", id: this.nextId++, bundle, recipient, ownAccount,\n }) as Uint8Array;\n }\n\n /** The link's own transfer. The handshake `payload` is verified inside the call\n * against what this device was shown, and the bundle is sealed to the verified\n * handshake's key: no key can be passed. Rejects with\n * {@link LinkCommitmentMismatchError} when the payload is not the committed one. */\n async sealLinkHistoryBundle(\n bundle: HistoryBundle,\n payload: Uint8Array,\n expected: LinkExpected,\n ): Promise<Uint8Array> {\n return await this.call({\n kind: \"sealLinkHistoryBundle\", id: this.nextId++, bundle, payload,\n ...linkExpectedFields(expected),\n }) as Uint8Array;\n }\n\n /** Open a transfer sealed to this device's published delivery key. `ownAccount`\n * as in {@link sealHistoryBundleV3}, and as there only a reason to refuse. A\n * bundle whose import the host CONFIRMED ({@link confirmHistoryImport}) is never\n * returned again: the transfer then rejects with {@link HistoryRefusedError}\n * `replayed`, and the host drops it. Until the confirmation the same transfer\n * opens again (the host's import is idempotent by event id). */\n async openHistoryBundleV3(sealed: Uint8Array, ownAccount: boolean): Promise<OpenedHistory> {\n return await this.call({\n kind: \"openHistoryBundleV3\", id: this.nextId++, sealed, ownAccount,\n }) as OpenedHistory;\n }\n\n /** The NEW device opens its link's own transfer, sealed to the X-Wing key of the\n * handshake it published; `recipientPriv` is that key's 32-byte seed. */\n async openLinkHistoryBundle(sealed: Uint8Array, recipientPriv: Uint8Array): Promise<OpenedHistory> {\n return await this.call({\n kind: \"openLinkHistoryBundle\", id: this.nextId++, sealed, recipientPriv,\n }) as OpenedHistory;\n }\n\n /** Ruling V177: call AFTER the host's own store holds the events of a bundle an\n * open returned, with that result's `import_id`. From then on the same bundle\n * (sealed afresh or not, from any sender) is refused as a replay. `true` when\n * this call recorded it, `false` when it was recorded before. The id may be\n * kept and confirmed after a restart. A local write; no request. */\n async confirmHistoryImport(importId: Uint8Array): Promise<boolean> {\n return await this.call({\n kind: \"confirmHistoryImport\", id: this.nextId++, importId,\n }) as boolean;\n }\n\n /** Whether this device's trust record names `deviceId` for history. */\n async historyTrust(deviceId: Uint8Array): Promise<boolean> {\n return await this.call({\n kind: \"historyTrust\", id: this.nextId++, deviceId,\n }) as boolean;\n }\n\n /** Record that this device shipped history to `deviceId`, once the server\n * accepted the transfer and never before. */\n async recordHistoryShipped(deviceId: Uint8Array): Promise<void> {\n await this.call({ kind: \"recordHistoryShipped\", id: this.nextId++, deviceId });\n }\n\n /** For a device of this account: ship history by itself, only after the person\n * confirms on this device, or not at all. Ask it for every entry of the\n * admission ledger and before the \"send your chats\" prompt; a link's own\n * transfer does not ask. */\n async historyShipDecision(deviceId: Uint8Array): Promise<HistoryShipDecision> {\n return await this.call({\n kind: \"historyShipDecision\", id: this.nextId++, deviceId,\n }) as HistoryShipDecision;\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 * THE ONE TAP AFTER A RESTORE BESIDE DEVICES THAT STAY (ruling V123). Call it on\n * a KEPT device when the person confirmed, on that device, the device `deviceId`\n * that restored with the recovery phrase and waits for its DeviceGroup.\n * `keyPackage` is a KeyPackage of that device, as the host fetched it. Nothing\n * the server says is believed: the KeyPackage must be the named device's, and its\n * credential must verify for THIS device's own account root, be signed by the\n * root itself (a linked device enters by its ticket) and stand at the generation\n * this device holds; anything else rejects (`NotPermitted`; `StaleGeneration`\n * when this device is behind its account). Then the DeviceGroup's ordinary Add,\n * sent with its Welcome and merged only when the delivery service accepted. As\n * every Commit there it rejects with `DeviceGroupBehind` while this device is\n * behind or may not commit yet after a rotation (catch up, or run the sweep, and\n * call again), and with `WelcomeUndelivered` when the Add is in and the Welcome is\n * not (call again). The waiting device calls nothing: the Welcome reaches it by\n * the transport. MLS only.\n */\n async addRestoredDevice(\n deviceId: DeviceId,\n keyPackage: Uint8Array,\n nowMs: number = this.now(),\n ): Promise<void> {\n await this.call({\n kind: \"addRestoredDevice\", id: this.nextId++, deviceId, keyPackage, nowMs,\n });\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 * {@link exportConversationSecret} together with the MLS epoch the secret was\n * exported at, from one read under one lock inside the core: the pair can\n * never disagree across a Commit.\n *\n * A host that files a key under an epoch number (a call's media key ring)\n * takes BOTH from this call. A conversation handle's `epoch` is this thread's\n * copy and any other read is a second request, so either may be a Commit away\n * from the secret.\n *\n * Same derivation, same arguments and the same refusals as\n * {@link exportConversationSecret}: at one epoch both answer the same bytes.\n * `secret` is a secret: never log it, persist it only encrypted, and call\n * `secret.fill(0)` after use. `epoch` is a plain number and may be logged.\n */\n async exportConversationSecretWithEpoch(\n conv: ConversationId,\n label: string,\n context: Uint8Array,\n length: number,\n ): Promise<ExportedSecret> {\n if (length <= 0 || length > 1024) {\n throw new Error(\"exportConversationSecretWithEpoch: length must be 1..=1024\");\n }\n return await this.call({\n kind: \"exportConversationSecretWithEpoch\", id: this.nextId++,\n conv, label, context, length,\n }) as ExportedSecret;\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 if (method === \"send\" || method === \"sendBatch\") {\n // The service's `409 stale_generation` (ruling S75) must reach the\n // wasm as itself: the host's `staleGeneration` flag becomes the text\n // the bridge reads, as \"the epoch has moved\" does below.\n try {\n return await t[method]?.(...args);\n } catch (e) {\n if ((e as { staleGeneration?: unknown } | null)?.staleGeneration === true) {\n throw new Error(TRANSPORT_STALE_GENERATION);\n }\n throw e;\n }\n }\n if (method === \"sendExternalCommit\" || method === \"sendExternalCommits\" || method === \"publishSealedGroupInfo\") {\n // \"The epoch has moved\" must reach the wasm as itself (the join then\n // answers `stale`); an error is a string once it crossed the Worker\n // boundary, so the host's flag becomes the text the bridge reads.\n try {\n return (await t[method]?.(...args)) ?? null;\n } catch (e) {\n if ((e as { epochOccupied?: unknown } | null)?.epochOccupied === true) {\n throw new Error(EXTERNAL_COMMIT_EPOCH_OCCUPIED);\n }\n if ((e as { staleGeneration?: unknown } | null)?.staleGeneration === true) {\n throw new Error(TRANSPORT_STALE_GENERATION);\n }\n throw e;\n }\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\nconst BACKUP_CHECK_FAILURES: readonly BackupCheckFailure[] = [\n \"invalidPhrase\", \"unsupportedVersion\", \"malformed\", \"undecodable\", \"internal\",\n];\n\n/**\n * Read a `{ outcome, reason? }` answer of the SDK's backup phrase check (the wasm\n * `checkBackupPhrase`, the React Native bridge) as a {@link BackupPhraseCheck}.\n *\n * The rule: ONLY the exact code `\"authenticationFailed\"` is proof that the phrase\n * does not open the backup, and only the exact code `\"opens\"` says that it does.\n * Everything else is a doubt: a value that is not such an object, an outcome this\n * build does not know, and a `couldNotCheck` whose reason it does not know (read as\n * `\"internal\"`). Nothing but the codes is carried over.\n */\nexport function backupPhraseCheckFromWire(raw: unknown): BackupPhraseCheck {\n const rec = raw !== null && typeof raw === \"object\"\n ? (raw as { outcome?: unknown; reason?: unknown })\n : {};\n if (rec.outcome === \"opens\") return { outcome: \"opens\" };\n if (rec.outcome === \"authenticationFailed\") return { outcome: \"authenticationFailed\" };\n const reason = rec.outcome === \"couldNotCheck\"\n ? BACKUP_CHECK_FAILURES.find((known) => known === rec.reason)\n : undefined;\n return { outcome: \"couldNotCheck\", reason: reason ?? \"internal\" };\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/** How the rejection of a call reads when this client can store nothing more\n * (the core's `Error::StoreMoved`). No other failure starts this way. Kept\n * in lockstep with the core's display (`stringify` in\n * `core/ping-wasm/src/lib.rs`, pinned by\n * `ping-core/tests/release_after_durable.rs`). Two causes. Another writer\n * wrote the client's MLS store since the client loaded it: raised by the\n * file-backed store of the native builds only (the web SDK's stores have no\n * writer claim yet). And THE CLIENT FAILED CLOSED, which a browser does\n * see: a run of rows could not store its message secrets, or a panic inside\n * the wasm closed the instance (every client of that Worker). The calls\n * that store, seal, send or acknowledge then reject with this text, and so\n * does `syncConversations()`. */\nexport const STORE_MOVED_PREFIX = \"store moved: \";\n\n/** The stale-writer failure. Nothing was written and nothing was released (a\n * message being sent did not leave). The client is stale: drop it,\n * initialise a new one on the same store, then retry the operation.\n * `message` stays the core's text, so `isStoreMovedError` also reads a copy\n * that lost its class. */\nexport class StoreMovedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StoreMovedError\";\n }\n}\n\n/** True when `e` is the stale-writer failure and no other. Accepts the\n * rejection itself, any object with a `message`, or the text. */\nexport function isStoreMovedError(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(STORE_MOVED_PREFIX);\n}\n\n/** How the rejection of a call reads when it was asked of a client opened\n * read-only (`openReadOnly`; the core's `Error::ReadOnly`). No other failure\n * starts this way. Kept in lockstep with the core's display (`stringify` in\n * `core/ping-wasm/src/lib.rs`, pinned by\n * `ping-core/tests/whole_operations.rs`). */\nexport const READ_ONLY_PREFIX = \"read-only client: \";\n\n/** The refusal of an operation on a client opened read-only. Such a client\n * loads the tab's MLS state and stores nothing: it can preview a received\n * message (`previewEnvelope`) and can never seal one (a message, a\n * proposal, a Commit, a leave, a KeyPackage, a linking ticket) or change MLS\n * state, because the ratchet step would not be stored and the tab would\n * seal again under the same key. The call was refused before anything was\n * encrypted or sent; nothing changed. Do the operation on the writing\n * client; never retry it on the reader. `message` stays the core's text, so\n * `isReadOnlyError` also reads a copy that lost its class. */\nexport class ReadOnlyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ReadOnlyError\";\n }\n}\n\n/** True when `e` is the read-only refusal and no other. Accepts the\n * rejection itself, any object with a `message`, or the text. */\nexport function isReadOnlyError(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(READ_ONLY_PREFIX);\n}\n\n/** What an existing device was shown for a link: the 20 characters\n * `MessagingClient.normalizeLinkCode` returned, or the 32 bytes of the scanned QR\n * (`MessagingClient.linkQrCommitment`, or the hash of a link URL decoded by the host). */\nexport type LinkExpected = { code: string } | { qrCommitment: Uint8Array };\n\n/** What a new device shows for the handshake it published. */\nexport interface LinkCommitment {\n commitment: Uint8Array;\n qrText: string;\n code: string;\n codeDisplay: string;\n}\n\n/** What `MessagingClient.verifyLinkHandshake` reports of a verified handshake. Not\n * a capability: the calls that act on a handshake verify it again themselves. */\nexport interface VerifiedLinkHandshakeInfo {\n deviceId: Uint8Array;\n deviceSigningPubkey: Uint8Array;\n commitment: Uint8Array;\n verifiedByQr: boolean;\n}\n\nfunction linkExpectedFields(expected: LinkExpected): { expectedCode?: string; expectedQr?: Uint8Array } {\n return \"code\" in expected ? { expectedCode: expected.code } : { expectedQr: expected.qrCommitment };\n}\n\n/** How the core's link commitment refusal reads as text (`ping_core`'s\n * `Error::LinkCommitmentMismatch`). No other failure starts this way. */\nexport const LINK_COMMITMENT_MISMATCH_PREFIX = \"link commitment mismatch: \";\n\n/** The handshake a relay returned is not the one the new device showed: the person\n * mistyped, or the handshake was swapped on the way. Nothing was parsed or sent.\n * Show: \"We couldn't verify the new device, so nothing was sent to it. Try again.\n * Scan the QR code if you can.\" */\nexport class LinkCommitmentMismatchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"LinkCommitmentMismatchError\";\n }\n}\n\n/** True for a {@link LinkCommitmentMismatchError} or its text. */\nexport function isLinkCommitmentMismatchError(e: unknown): boolean {\n if (e instanceof LinkCommitmentMismatchError) return true;\n const text = e instanceof Error ? e.message : typeof e === \"string\" ? e : null;\n return text !== null && text.startsWith(LINK_COMMITMENT_MISMATCH_PREFIX);\n}\n\n/** How the rejection of a join reads when the Welcome joins a group other\n * than the conversation its envelope names (the core's\n * `Error::WelcomeMislabeled`). 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\n * `ping-core/tests/conversation_scope.rs`). */\nexport const WELCOME_MISLABELED_PREFIX = \"welcome mislabeled: \";\n\n/** The refusal of a Welcome that joins a group other than the conversation\n * its envelope names. An honest sender names the group it built the Welcome\n * for, so the two differ only when the envelope was rewritten on its way.\n * The Welcome was refused as soon as it was opened: the KeyPackage it is\n * sealed to is kept, no conversation appeared under either id, and the\n * Welcome as it was sent still joins. Drop that envelope: never retry it,\n * file no re-admission request for it, show nothing. `message` stays the\n * core's text, so `isWelcomeMislabeledError` also reads a copy that lost\n * its class. */\nexport class WelcomeMislabeledError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"WelcomeMislabeledError\";\n }\n}\n\n/** True when `e` is the refusal of a mislabeled Welcome and no other.\n * Accepts the rejection itself, any object with a `message`, or the text. */\nexport function isWelcomeMislabeledError(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(WELCOME_MISLABELED_PREFIX);\n}\n\n/** How the refusal reads when this device is behind its own account and so\n * builds no Commit (the core's `Error::StaleGeneration`). No other failure\n * starts this way. Kept in lockstep with the core's display (`stringify`\n * in `core/ping-wasm/src/lib.rs`, pinned by\n * `ping-core/tests/generation_sender_rules.rs`). */\nexport const STALE_GENERATION_PREFIX = \"stale generation: \";\n\n/** This device is behind its own account: a newer generation of the account\n * exists than this device carries, so it builds no Commit (every member\n * would refuse what it did with its account's devices). Nothing was built\n * or sent. The device is still a member: it sends and receives messages.\n * Adopt the account's newest generation, then repeat the call; do not drop\n * the intent, and do not retry before the adoption. */\nexport class StaleGenerationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StaleGenerationError\";\n }\n}\n\n/** True for a {@link StaleGenerationError}, any object with its `message`,\n * or the text. */\nexport function isStaleGenerationError(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(STALE_GENERATION_PREFIX);\n}\n\n/** How the refusal reads when this device cannot approve a link because its\n * DeviceGroup is behind (the core's `Error::DeviceGroupBehind`). No other\n * failure starts this way. Kept in lockstep with the core's display. */\nexport const DEVICE_GROUP_BEHIND_PREFIX = \"device group behind: \";\n\n/** This device cannot approve a link now: it holds no position in its\n * DeviceGroup's log, holds frames it could not apply, or the delivery\n * service refused its Add. Nothing left the device and no ticket was built.\n * Catch the DeviceGroup up, then repeat the call once. */\nexport class DeviceGroupBehindError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DeviceGroupBehindError\";\n }\n}\n\n/** True for a {@link DeviceGroupBehindError}, any object with its `message`,\n * or the text. */\nexport function isDeviceGroupBehindError(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(DEVICE_GROUP_BEHIND_PREFIX);\n}\n\n/** How the refusal reads when this device cannot approve a link because its\n * own credential's chain is at the limit (the core's\n * `Error::LinkChainTooDeep`, ruling V178). Kept in lockstep with the core's\n * display. */\nexport const LINK_CHAIN_TOO_DEEP_PREFIX = \"link chain too deep: \";\n\n/** This device cannot approve a link, now or later: its credential's chain\n * is at the limit. FINAL: show the \"link from another device\" copy, never\n * repeat the call. Nothing was signed and no ticket was built. */\nexport class LinkChainTooDeepError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"LinkChainTooDeepError\";\n }\n}\n\n/** How the refusal reads when the delivery service refuses this device's\n * DeviceGroup Add for a link and a catch-up did not cure it (the core's\n * `Error::LinkAddRefused`, ruling V138). */\nexport const LINK_ADD_REFUSED_PREFIX = \"link add refused: \";\n\n/** The delivery service refuses this device's DeviceGroup Add, and the\n * catch-up that followed a {@link DeviceGroupBehindError} changed nothing.\n * FINAL: never repeat the call. Nothing left the device. */\nexport class LinkAddRefusedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"LinkAddRefusedError\";\n }\n}\n\n/** How the answer reads when a Welcome handed to a direct join call waits\n * for its turn (the core's `Error::WelcomeWaits`, rulings V186, V194). */\nexport const WELCOME_WAITS_PREFIX = \"welcome waits: \";\n\n/** NOT a failure: the Welcome is kept and joins by itself once the rows of\n * the log before it were handed or the conversation was paged. Show\n * nothing, ask for no re-admission, queue no retry of the Welcome. */\nexport class WelcomeWaitsError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"WelcomeWaitsError\";\n }\n}\n\nfunction startsWithPrefix(e: unknown, prefix: string): 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(prefix);\n}\n\n/** True for a {@link LinkChainTooDeepError}, any object with its `message`,\n * or the text. */\nexport function isLinkChainTooDeepError(e: unknown): boolean {\n return startsWithPrefix(e, LINK_CHAIN_TOO_DEEP_PREFIX);\n}\n\n/** True for a {@link LinkAddRefusedError}, any object with its `message`, or\n * the text. */\nexport function isLinkAddRefusedError(e: unknown): boolean {\n return startsWithPrefix(e, LINK_ADD_REFUSED_PREFIX);\n}\n\n/** True for a {@link WelcomeWaitsError}, any object with its `message`, or\n * the text. */\nexport function isWelcomeWaitsError(e: unknown): boolean {\n return startsWithPrefix(e, WELCOME_WAITS_PREFIX);\n}\n\n/** How a refusal of the version 3 history rules reads as text (a contract with\n * `core/ping-wasm/src/lib.rs`, `HISTORY_REFUSED_PREFIX`). What follows is the\n * reason. Carries nothing of the bundle. */\nexport const HISTORY_REFUSED_PREFIX = \"history refused: \";\n\n/** Why a history bundle was not sealed or not taken. `replayed`: this device\n * already accepted this very bundle; drop the transfer. `too-large`: over\n * 2 MiB sealed or over 256 events. `recipient-key`: the recipient's verified\n * key may not seal this bundle (another conversation's tree, or its leaf is\n * gone). `recipient`, `sender`, `signature`: the bundle is not for this\n * device, its sender is not a verified leaf this device accepts history\n * from, or its signature does not verify. */\nexport type HistoryRefusalReason =\n | \"recipient\" | \"sender\" | \"signature\" | \"recipient-key\" | \"too-large\" | \"replayed\";\n\n/** A history bundle was refused. Nothing of it was applied or sent. */\nexport class HistoryRefusedError extends Error {\n readonly reason: HistoryRefusalReason | \"unknown\";\n constructor(message: string) {\n super(message);\n this.name = \"HistoryRefusedError\";\n const reason = message.slice(HISTORY_REFUSED_PREFIX.length);\n this.reason = (HISTORY_REFUSAL_REASONS as readonly string[]).includes(reason)\n ? reason as HistoryRefusalReason\n : \"unknown\";\n }\n}\n\nconst HISTORY_REFUSAL_REASONS: readonly HistoryRefusalReason[] = [\n \"recipient\", \"sender\", \"signature\", \"recipient-key\", \"too-large\", \"replayed\",\n];\n\n/** Whether `e` is a refusal of the history rules, typed or as a worker's text. */\nexport function isHistoryRefusedError(e: unknown): boolean {\n if (e instanceof HistoryRefusedError) return true;\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(HISTORY_REFUSED_PREFIX);\n}\n\n/** How the refusal reads when the SDK's pending-apply journal is full (the\n * core's `Error::JournalFull`). No other failure starts this way. Kept in\n * lockstep with the core's display. */\nexport const JOURNAL_FULL_PREFIX = \"journal full: \";\n\n/** The pending-apply journal has no room for the message this envelope would\n * decrypt into, and the journal never drops a message the host has not\n * confirmed. NOTHING of the envelope was taken: no key was spent, no\n * position moved, it is not kept and it is not a hole. Save the messages\n * already handed over, call `confirmApplied`, then hand the same envelope\n * again. A batch and a page report it in `journalFull` instead. */\nexport class JournalFullError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"JournalFullError\";\n }\n}\n\n/** True for a {@link JournalFullError}, any object with its `message`, or\n * the text. */\nexport function isJournalFullError(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(JOURNAL_FULL_PREFIX);\n}\n\n/** A worker's rejection text as the error a caller catches: the typed role\n * refusal, the typed sender refusal, the stale-writer failure, the\n * read-only refusal or the refusal of a mislabeled Welcome when it is one,\n * a plain `Error` 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 if (text.startsWith(STORE_MOVED_PREFIX)) return new StoreMovedError(text);\n if (text.startsWith(READ_ONLY_PREFIX)) return new ReadOnlyError(text);\n if (text.startsWith(WELCOME_MISLABELED_PREFIX)) return new WelcomeMislabeledError(text);\n if (text.startsWith(LINK_COMMITMENT_MISMATCH_PREFIX)) return new LinkCommitmentMismatchError(text);\n if (text.startsWith(STALE_GENERATION_PREFIX)) return new StaleGenerationError(text);\n if (text.startsWith(DEVICE_GROUP_BEHIND_PREFIX)) return new DeviceGroupBehindError(text);\n if (text.startsWith(JOURNAL_FULL_PREFIX)) return new JournalFullError(text);\n if (text.startsWith(LINK_CHAIN_TOO_DEEP_PREFIX)) return new LinkChainTooDeepError(text);\n if (text.startsWith(LINK_ADD_REFUSED_PREFIX)) return new LinkAddRefusedError(text);\n if (text.startsWith(WELCOME_WAITS_PREFIX)) return new WelcomeWaitsError(text);\n if (text.startsWith(HISTORY_REFUSED_PREFIX)) return new HistoryRefusedError(text);\n return new Error(text);\n}\n\n/** The text of the error that tells the wasm \"the epoch has moved\" for an\n * external Commit's post (`core/ping-wasm`, the same constant). */\nconst EXTERNAL_COMMIT_EPOCH_OCCUPIED = \"external commit: epoch occupied\";\n/** The text that carries a host's `staleGeneration` flag (the service's\n * `409 stale_generation` on a post) across the Worker boundary; kept in\n * step with `core/ping-wasm/src/lib.rs`. */\nconst TRANSPORT_STALE_GENERATION = \"transport: stale generation\";\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\n/** RULING V406 (b): the join's typed hole arrives in the wire form of\n * `logHoles`; hand it on in the form every other hole has. */\nfunction holeOfJoin(result: Extract<SelfAdmitResult, { kind: \"joined\" }>): void {\n if (result.beforeReturn !== undefined && result.beforeReturn !== null) {\n result.beforeReturn = logHoleFromWire(result.beforeReturn as unknown as LogHoleWire);\n }\n}\n","// 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","// ONE lane of sequenced live frames, for every conversation.\n//\n// The first frame is applied at once, as a batch of one. Frames of ANY\n// conversation that arrive while that batch is in flight accumulate and go\n// out as ONE batch the moment it returns, in arrival order; no timer ever\n// holds a frame back. The core orders the frames of a conversation by their\n// server position and applies the conversations of one batch one after the\n// other, so what this buys is not ordering but cost: one Worker call, one\n// MLS checkpoint and one host transaction per burst instead of one per frame\n// (see docs/SYNC_PROTOCOL.md \"Sequenced log sync\", cost model).\n//\n// There used to be one lane a conversation, so that a busy group could not\n// hold another one back. A catch-up of 200 conversations then cost two\n// Worker calls a conversation (about 400); in one lane it costs one call per\n// `maxBatch` frames (about 20). What the lanes protected against is kept\n// another way: a hand the engine REFUSES as a whole is handed again one\n// conversation at a time, so one bad conversation fails alone.\n//\n// THE JOURNAL'S PACE IS THE SDK'S. A batch answers the indexes of the rows\n// it did not take because the pending-apply journal had no room\n// (`ApplyBatchResult.notTaken`). Those frames go back to the FRONT of the\n// lane, in order, their promises still pending, and nothing is handed until\n// the host confirmed something (`roomFreed`, called after `confirmApplied`):\n// a call that could take nothing is never made, and no frame is dropped.\n//\n// Lives outside `index.ts` so it is testable without a Worker.\n\n/**\n * Applies one batch. Resolves with the indexes, into `items`, of the rows\n * that were NOT taken (none, or nothing, when all were).\n */\nexport type BatchApplier<T> = (items: T[]) => Promise<readonly number[] | void>;\n\ninterface Entry<T> {\n key: string;\n item: T;\n resolve(): void;\n reject(error: unknown): void;\n}\n\nexport class InboundCoalescer<T> {\n private readonly queue: Entry<T>[] = [];\n private running = false;\n /** The last batch left rows for want of room and no confirm came since. */\n private waitingForRoom = false;\n /** Confirms seen, so that one landing while a batch is in flight is not lost. */\n private confirms = 0;\n\n /**\n * @param apply Applies one batch. A rejection of a batch that carries\n * several conversations hands it again one conversation at a time; the\n * frames of a conversation whose own batch is rejected settle with the\n * error and the lane moves on, so one bad batch cannot wedge it.\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 of the conversation `key`. Resolves when the batch that\n * carried it has been applied (rejects if that batch failed), so a\n * transport that awaits the dispatch to ack a watermark still sees the\n * truth: a frame the engine did not take stays pending until it is.\n */\n push(key: string, item: T): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.queue.push({ key, item, resolve, reject });\n this.pump();\n });\n }\n\n /**\n * The host confirmed messages (`confirmApplied` returned): the journal has\n * room again, and the frames kept for want of it are handed now.\n */\n roomFreed(): void {\n this.confirms += 1;\n if (this.waitingForRoom) {\n this.waitingForRoom = false;\n this.pump();\n }\n }\n\n /** Batches in flight: 0 or 1 (diagnostics / tests). */\n get inFlight(): number {\n return this.running ? 1 : 0;\n }\n\n /** Frames waiting in the lane (diagnostics / tests). */\n get queued(): number {\n return this.queue.length;\n }\n\n private pump(): void {\n if (this.running || this.waitingForRoom || this.queue.length === 0) return;\n this.running = true;\n const batch = this.queue.splice(0, this.maxBatch);\n // `run` never rejects: every failure reaches the frames' own promises.\n void this.run(batch).then(() => {\n this.running = false;\n this.pump();\n });\n }\n\n private async run(batch: Entry<T>[]): Promise<void> {\n const confirmsAtHand = this.confirms;\n let left: Entry<T>[] = [];\n try {\n left = await this.hand(batch);\n } catch (e) {\n const groups = new Map<string, Entry<T>[]>();\n for (const entry of batch) {\n const group = groups.get(entry.key);\n if (group === undefined) groups.set(entry.key, [entry]);\n else group.push(entry);\n }\n if (groups.size <= 1) {\n for (const entry of batch) entry.reject(e);\n return;\n }\n // Refused as a whole: one conversation at a time, in the order each\n // first appeared. Only the conversation that is refused alone fails.\n for (const group of groups.values()) {\n try {\n left.push(...(await this.hand(group)));\n } catch (error) {\n for (const entry of group) entry.reject(error);\n }\n }\n const order = new Map(batch.map((entry, index) => [entry, index] as const));\n left.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0));\n }\n if (left.length > 0) {\n // In front of anything newer, in arrival order.\n this.queue.unshift(...left);\n // A confirm that landed while this batch was in flight may already\n // have made the room: hand again at once instead of waiting for one\n // that might never come.\n this.waitingForRoom = this.confirms === confirmsAtHand;\n }\n }\n\n /** Hand `entries`; settle the taken ones; return the ones not taken, in order. */\n private async hand(entries: Entry<T>[]): Promise<Entry<T>[]> {\n let attempt: Promise<readonly number[] | void>;\n try {\n attempt = this.apply(entries.map((entry) => entry.item));\n } catch (e) {\n attempt = Promise.reject(e);\n }\n const notTaken = new Set<number>((await attempt) ?? []);\n const back: Entry<T>[] = [];\n entries.forEach((entry, index) => {\n if (notTaken.has(index)) back.push(entry);\n else entry.resolve();\n });\n return back;\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 SelfAdmission,\n HoleReason,\n LogAck,\n JournalFullAt,\n LogHole,\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 sealed_group_info_wanted?: boolean;\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 SelfAdmissionWire {\n conversation_id: Uint8Array;\n identity: Uint8Array;\n device_id: Uint8Array;\n replaced_own_leaf: boolean;\n own_account: boolean;\n epoch: number;\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 self_admissions?: SelfAdmissionWire[];\n holes?: LogHoleWire[];\n acks?: LogAckWire[];\n journal_full?: JournalFullAtWire[];\n /** Set by the wasm bridge on every batch answer (not a field of the core's\n * result): the anchor record changed and the state part is owed a write. */\n state_backup_owed?: boolean;\n /** The indexes of the rows of the hand that were not taken (the journal\n * had no room), ascending. */\n not_taken?: number[];\n journal_room_rows?: number;\n journal_room_bytes?: number;\n}\n\nexport interface LogHoleWire {\n conversation_id: Uint8Array;\n from_server_seq: number;\n to_server_seq: number;\n /** `\"RefusedCommit\"`, `\"CannotDecrypt\"`, `\"NotHeld\"`, `\"Invalid\"`, `\"Internal\"`, `\"BeforeReturn\"`. */\n reason: string;\n content_hashes: ArrayLike<number>[];\n kept: boolean;\n}\n\nexport interface LogAckWire {\n conversation_id: Uint8Array;\n server_seq: number;\n}\n\nexport interface JournalFullAtWire {\n conversation_id: Uint8Array;\n server_seq: number;\n rows: number;\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 self_admissions?: SelfAdmissionWire[];\n holes?: LogHoleWire[];\n acks?: LogAckWire[];\n journal_full?: JournalFullAtWire[];\n journal_room_rows?: number;\n journal_room_bytes?: number;\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 ...(h.sealedGroupInfoWanted === true ? { sealed_group_info_wanted: true } : {}),\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 ...(h.sealed_group_info_wanted === true ? { sealedGroupInfoWanted: true } : {}),\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\nexport function selfAdmissionFromWire(a: SelfAdmissionWire): SelfAdmission {\n return {\n conversationId: a.conversation_id,\n identity: a.identity,\n deviceId: a.device_id,\n replacedOwnLeaf: a.replaced_own_leaf,\n ownAccount: a.own_account,\n epoch: a.epoch,\n };\n}\n\nexport function logHoleFromWire(h: LogHoleWire): LogHole {\n return {\n conversationId: h.conversation_id,\n fromServerSeq: h.from_server_seq,\n toServerSeq: h.to_server_seq,\n reason: variant<HoleReason>(h.reason),\n contentHashes: h.content_hashes.map((c) => Uint8Array.from(c)),\n kept: h.kept,\n };\n}\n\nexport function logAckFromWire(a: LogAckWire): LogAck {\n return { conversationId: a.conversation_id, serverSeq: a.server_seq };\n}\n\nexport function journalFullAtFromWire(j: JournalFullAtWire): JournalFullAt {\n return { conversationId: j.conversation_id, serverSeq: j.server_seq, rows: j.rows };\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 self_admissions?: SelfAdmissionWire[];\n holes?: LogHoleWire[];\n acks?: LogAckWire[];\n journal_full?: JournalFullAtWire[];\n journal_room_rows?: number;\n journal_room_bytes?: number;\n}): Pick<\n ApplyBatchResult,\n | \"removed\" | \"welcomeFailures\" | \"stranded\" | \"proposalsPending\" | \"overflow\" | \"selfAdmissions\"\n | \"holes\" | \"acks\" | \"journalFull\" | \"journalRoomRows\" | \"journalRoomBytes\"\n> {\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 selfAdmissions: (r.self_admissions ?? []).map(selfAdmissionFromWire),\n // Absent from an older wasm: nothing recorded, nothing safe to acknowledge.\n holes: (r.holes ?? []).map(logHoleFromWire),\n acks: (r.acks ?? []).map(logAckFromWire),\n // Absent from an older wasm, which never stopped for the journal.\n journalFull: (r.journal_full ?? []).map(journalFullAtFromWire),\n // Absent from an older wasm, which did not state its room: 0, so a host\n // that cuts its hand by the room waits for a confirm instead of guessing.\n journalRoomRows: Number(r.journal_room_rows ?? 0),\n journalRoomBytes: Number(r.journal_room_bytes ?? 0),\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 // Absent from an older wasm, which named no row: nothing to hand again.\n notTaken: (r.not_taken ?? []).map(Number),\n // Present only when the SDK says it: said once, with the batch at which\n // the anchor record was seen to change.\n ...(r.state_backup_owed === true ? { stateBackupOwed: true } : {}),\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\n/**\n * Every write transaction asks for STRICT durability: `oncomplete` fires only\n * after the data was flushed to the device, so a write this store reported\n * done also survives an operating-system crash or a power loss. The default\n * of the browsers is weaker (Chromium has used `relaxed` since version 121:\n * `oncomplete` can fire before the flush, which survives a tab or browser\n * crash only). The SDK releases a sealed message only after the write of its\n * ratchet step and of its send counter completed; with a relaxed write a\n * power loss could roll both back after the message left, and the next\n * message would be sealed under a key that was used before. Reads are not\n * affected. A browser that does not know the option ignores it and keeps its\n * default.\n */\nconst DURABLE: IDBTransactionOptions = { durability: \"strict\" };\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\", DURABLE);\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\", DURABLE);\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\", DURABLE);\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","// Account set-up and the first backup, from the main realm (the account\n// identity contract, sections 3.3 and 13.1; rules R7, R10, R32 to R34; rulings\n// ID38 to ID42, V102, V103).\n//\n// The calls run in a dedicated Worker of the SDK that this class owns and that\n// never runs a messaging client. The pending root is wrapped and unwrapped\n// there, by the SDK's own store (`pending-root-store.ts`): no message between\n// this realm and that Worker carries a root seed, a wrapping key or the store.\n// What crosses: the slot's name, the sign-in's `identity_state`, the browser's\n// answer to the persistent-storage request, the phrase the person typed, the\n// two parts of a backup (ciphertext), public values, and ONCE the device key\n// of a device the call made, for the host's protected store (ruling V103).\n//\n// A set-up session whose root is in memory only (rule R34 a) lives in that\n// Worker between calls: closing this object, or the tab, wipes it.\n\nimport type { Request, Response } from \"./protocol\";\nimport { scopeStorage, storageFeaturesOf } from \"./storage/scope\";\nimport type { Storage } from \"./types\";\n\n/** The root's sealing key statement of one generation. Public values. */\nexport interface SealingStatement {\n generation: number;\n sealingPublicKey: Uint8Array;\n signature: Uint8Array;\n}\n\n/**\n * What a call that MADE a device answers: the public values the host registers\n * with the server, and the device key for the host's protected store.\n * `devicePublicKey` is the device's public key (32 bytes; `deviceId` is its\n * SHA-256): the value a host registers, so no host derives it from the secret.\n * `deviceSigningSecretKey` is a secret: keep it where a device key is kept\n * today, pass it to `MessagingClient.initFromDeviceRecord`, never log it.\n */\nexport interface NewAccountDevice {\n userId: Uint8Array;\n deviceId: Uint8Array;\n devicePublicKey: Uint8Array;\n generation: number;\n statement: SealingStatement;\n deviceSigningSecretKey: Uint8Array;\n}\n\n/**\n * What `AccountSetup.prepareDeviceKey` answers: the device id (SHA-256 of the\n * public key) and the public key a sign-in BY CODE names, and the device key\n * for the host's protected store. `deviceSigningSecretKey` is a secret: store\n * it BEFORE any request names the key, never log it.\n */\nexport interface PreparedDeviceKey {\n deviceId: Uint8Array;\n devicePublicKey: Uint8Array;\n deviceSigningSecretKey: Uint8Array;\n}\n\n/**\n * What `AccountSetup.deviceStartCheck` answers (ruling V904): what a start from\n * the device record would answer on this store. `startable`: the store holds a\n * device record and its device key (if it holds one yet) is the record's.\n * `no-device-record`: set up, link or restore. `device-key-mismatch`: the\n * store's device key, or the expected device id, is not the record's.\n */\nexport type DeviceStartCheck = \"startable\" | \"no-device-record\" | \"device-key-mismatch\";\n\n/** The two parts of a backup (ciphertext) and how many conversations' anchors\n * did not fit the state part. */\n/** The recovery phrase as it crosses to the account Worker (ruling V253):\n * UTF-8 bytes, never a string, so that the copy on each side of the\n * boundary can be zeroed after the call (a string cannot be). The page's\n * copy is zeroed by `AccountSetup` when the call has answered, the\n * Worker's by the Worker, the wasm's by the wasm. THE HOST'S OWN STRING\n * (the argument it passed in, and whatever input field it came from)\n * cannot be wiped by anyone: keep it no longer than the call. */\nfunction phraseBytes(phrase: string): Uint8Array {\n return new TextEncoder().encode(phrase);\n}\n\nexport interface AccountBackupParts {\n rootPart: Uint8Array;\n statePart: Uint8Array;\n droppedAnchors: number;\n}\n\n/** `present`, `absent`, or `mismatch` (the pending root is LOST: copy B6). */\nexport type PendingRootStatus = \"present\" | \"absent\" | \"mismatch\";\n\n/** What `discardPendingRoot` answers. `deleted`: the slot's pending root was\n * deleted. `nothing-there`: the slot holds none. The other three are\n * REFUSALS that deleted nothing: the slot's store holds a device record (the\n * root may be an account's pinned root), a rotation record, or a begun link.\n * Treat a value you do not know as a refusal. */\nexport type PendingRootDiscard =\n | \"deleted\" | \"nothing-there\" | \"device-record-held\" | \"rotation-record-held\" | \"link-begun\";\n\n/** What `POST /v1/account/generation/start` answered, as the host parsed it\n * (the account identity contract, 12.3). Public values, and the server's\n * word: the SDK believes it only as far as the root's signature goes. */\nexport interface RotationStart {\n rotationId: Uint8Array;\n rootPublicKey: Uint8Array;\n generation: number;\n /** The root-signed statement of the pinned generation. A device handed\n * none signs nothing (`pinned-generation-unproven`). */\n statement?: SealingStatement | null;\n}\n\n/** The fields of the `rotation` object the SDK builds (contract 12.3). The\n * host adds `new_user_pubkey` and `new_key_sig` and encodes every binary\n * field as base64url with no padding. Public values and ciphertext. */\nexport interface RotationRequest {\n rotationId: Uint8Array;\n generation: number;\n reason: \"remove\" | \"secure_account\" | \"restore\";\n credentials: { deviceId: Uint8Array; credential: Uint8Array }[];\n sealingPublicKey: Uint8Array;\n sealingSignature: Uint8Array;\n wraps: { deviceId: Uint8Array; wrap: Uint8Array }[];\n recoveryRootPart?: Uint8Array;\n recoveryStatePart: Uint8Array;\n}\n\n/** What a call that BUILT a rotation answers. `newDevice` is the device a\n * take-over makes; its `deviceSigningSecretKey` is a SECRET. */\n/** One device of the rotation start route's answer: the server's word. A\n * device is kept only when its delivery key verifies under a leaf of the\n * rotating device's own DeviceGroup tree. */\nexport interface RotationStartDevice {\n deviceId: Uint8Array;\n credentialGeneration?: number | null;\n historyDeliveryKey?: { device_id: Uint8Array; counter: number; public_key: Uint8Array; signature: Uint8Array } | null;\n}\n\n/** What `MessagingClient.planRotation` answers. */\nexport interface RotationPlan {\n /** The generation the rotation would pin: the pinned one plus one. */\n nextGeneration: number;\n offered: { deviceId: Uint8Array; own: boolean }[];\n notOffered: { deviceId: Uint8Array; reason: \"no-delivery-key\" | \"not-verified\" }[];\n}\n\n/** What `MessagingClient.adoptGeneration` answers. `changed` is false when\n * the row was the generation the device already held. */\nexport interface AdoptedGeneration {\n generation: number;\n changed: boolean;\n}\n\nexport interface RotationBuilt {\n request: RotationRequest;\n recordId: Uint8Array;\n newDevice?: NewAccountDevice;\n}\n\n/** Why one device of the kept set cannot be kept (ruling V138). */\nexport type RotationKeptRefusal = \"caller_not_kept\" | \"not_offered\" | \"not_verified\";\n\n/** What the two builds of a rotation on the client answer\n * (`MessagingClient.rotateGenerationWithPending`, `rotateGenerationWithBackup`).\n * `keptSetRefused` is a VALUE, not an exception, and FINAL for that kept set:\n * nothing was signed or written, and the same call answers the same. It\n * names the device so that the host can take it out of the kept set or tell\n * the person; `deviceId` is an identifier, never a log value. */\nexport type RotationBuild =\n | { built: RotationBuilt }\n | { keptSetRefused: { deviceId: Uint8Array; reason: RotationKeptRefusal } };\n\nexport type RotationPhase = \"built\" | \"applied\" | \"adopted\" | \"device_group_done\" | \"queued\";\n\n/** Ruling V232: what the store says of a rotation this device built\n * (`rotationRecordState`). `\"pending\"`: the server has not refused it, send the\n * identical request again. `\"adopted\"`: the device runs on it; it ends by\n * `finishRotation`. `\"refused\"`, `\"root_part_required\"`: the person may abandon it\n * (`abandonRotation`). */\nexport type RotationRecordState = \"no_record\" | \"pending\" | \"adopted\" | \"refused\" | \"root_part_required\";\n\n/** A rotation this device built and has not finished. */\nexport interface PendingRotation {\n recordId: Uint8Array;\n generation: number;\n reason: RotationRequest[\"reason\"];\n phase: RotationPhase;\n request: RotationRequest;\n newDevice?: NewAccountDevice;\n}\n\n/** What the server answered a rotation request with, AS RECEIVED (ruling\n * V161): the HTTP `status` (0 when there was no answer) and what the body\n * states, each when present: its `error` code, its `generation`, its\n * `statement`. The host parses and hands over; it decides nothing, and no\n * value of this type says \"applied\". */\nexport interface RotationAnswer {\n status: number;\n error?: string | null;\n generation?: number | null;\n statement?: SealingStatement | null;\n}\n\n/** `\"undecided\"`: the answer was none the SDK acts on (a `200` that states\n * the record's generation, `409 generation_conflict`, the final refusals\n * below). Nothing changed and the record stays: send the\n * identical request again at the next start.\n *\n * `\"refused\"` (rulings V212 and V245): the server refused this rotation FOR\n * GOOD (`403 caller_not_kept`, `400 credential_invalid`, `409\n * identity_key_retired`, `400 rotation_invalid`; no answer of a server\n * discards a record by itself, so there is no `\"discarded\"` outcome);\n * the identical request will be refused again. `\"root_part_required\"` (`409\n * recovery_root_part_required`): the account has a backup and the request\n * was built without the recovery phrase; the person supplies it. In both\n * nothing changed and the record STAYS; no other rotation starts until the\n * person chooses to start over and the host calls `abandonRotation`. */\nexport type RotationRefusal =\n | \"caller_not_kept\" | \"credential_invalid\" | \"identity_key_retired\" | \"rotation_invalid\";\nexport type RotationOutcome =\n | { outcome: \"adopted\"; userId: Uint8Array; deviceId: Uint8Array; generation: number }\n | { outcome: \"lost\"; pinnedStatement: SealingStatement }\n | { outcome: \"undecided\" }\n | { outcome: \"refused\"; reason: RotationRefusal }\n | { outcome: \"root_part_required\" };\n\n/** The four fields of a {@link RotationAnswer} and nothing else, so that\n * nothing a host left on the object crosses to a Worker with it. */\nexport function rotationAnswerFields(answer: RotationAnswer): Required<RotationAnswer> {\n return {\n status: answer.status,\n error: answer.error ?? null,\n generation: answer.generation ?? null,\n statement: answer.statement ?? null,\n };\n}\n\n/** What step 3 of a restore found. `hostState` (the hosts' own data, with\n * the OLD sign-in key companion) is absent when no state part was given or\n * the root part's secret does not open it. */\nexport interface RestoreOpened {\n userId: Uint8Array;\n rootPublicKey: Uint8Array;\n accountId: Uint8Array;\n generation: number;\n hostState?: Uint8Array;\n anchoredConversations: number;\n}\n\nexport interface RestoreJoined {\n device: NewAccountDevice;\n credential: Uint8Array;\n hostState: Uint8Array;\n}\n\nexport interface StateOpened {\n hostState: Uint8Array;\n anchoredConversations: number;\n}\n\nexport interface StateRefreshed {\n statePart: Uint8Array;\n droppedAnchors: number;\n}\n\nexport interface AccountSetupConfig {\n /** The device's own store: the one the client will be started on. */\n storage: Storage;\n /** The same per-account scoping `MessagingClient` applies (see `ClientConfig`). */\n accountNamespace?: string;\n /** Override the wall clock (tests only). */\n now?: () => number;\n}\n\n/** Every refusal of these calls reads `account refused: <code>`. */\nexport function accountRefusalCode(error: unknown): string | null {\n const text = error instanceof Error ? error.message : String(error);\n const at = text.indexOf(\"account refused: \");\n return at < 0 ? null : text.slice(at + \"account refused: \".length).trim();\n}\n\nexport class AccountSetupClosedError extends Error {\n constructor() {\n super(\"AccountSetup is closed\");\n this.name = \"AccountSetupClosedError\";\n }\n}\n\nexport class AccountSetup {\n private readonly worker: Worker;\n private readonly storage: Storage;\n private readonly now: () => number;\n private readonly pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: unknown) => void }>();\n private nextId = 1;\n private closed = false;\n\n private constructor(cfg: AccountSetupConfig, worker: Worker) {\n this.worker = worker;\n this.storage =\n cfg.accountNamespace !== undefined && cfg.accountNamespace.length > 0\n ? scopeStorage(cfg.storage, cfg.accountNamespace)\n : cfg.storage;\n this.now = cfg.now ?? (() => Date.now());\n this.worker.onmessage = (ev) => void this.handleWorker(ev.data as Response);\n this.worker.onerror = () => this.fail(new AccountSetupClosedError());\n }\n\n /** Start the SDK's set-up Worker over the device's own store. */\n static open(cfg: AccountSetupConfig): AccountSetup {\n const worker = new Worker(new URL(\"./worker.js\", import.meta.url), { type: \"module\" });\n return new AccountSetup(cfg, worker);\n }\n\n /**\n * Set a NEW account up on this browser after \"Not now\" (rule R34 b): the\n * pending root first, then the device record. `identityState` is the\n * sign-in body's `identity_state` field as the server sent it; only\n * `\"none_pinned\"` lets the call run (ruling V102). `persistentStorage` is the\n * browser's answer to `navigator.storage.persist()`, which the host asked\n * for before this call (ruling ID39).\n */\n createAccount(args: {\n slot: string;\n identityState: string | undefined;\n persistentStorage?: boolean;\n }): Promise<NewAccountDevice> {\n return this.call({\n kind: \"createAccount\",\n id: this.nextId++,\n slot: args.slot,\n identityState: args.identityState,\n persistentStorage: args.persistentStorage,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<NewAccountDevice>;\n }\n\n /**\n * THE PREPARED DEVICE KEY (rulings V895 to V900, V913, V965): the device key\n * a sign-in BY CODE names on a store with no device record, before the\n * account exists. The SDK draws it (no argument is a key), keeps it in one\n * row of this store and answers it; a repeat answers the SAME key, and two\n * tabs that call at once answer one key (the origin's account lock).\n * `createAccount`, the in-memory session and `MessagingClient.beginDeviceLink`\n * then make the device with that key; a restore or a take-back never uses\n * it. Store the secret BEFORE any request names the key. Refusals:\n * `account-already-set-up` (the store holds a device), `rotation-in-progress`,\n * `device-key-held-by-link` (a link was begun in this slot: offer \"Finish\n * linking\" or \"Start over\", never a retry), `prepared-key-mismatch`.\n */\n prepareDeviceKey(): Promise<PreparedDeviceKey> {\n return this.call({\n kind: \"prepareDeviceKey\",\n id: this.nextId++,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<PreparedDeviceKey>;\n }\n\n /** Delete a FREE prepared device key and nothing else; answers whether a\n * row was deleted. Log the key's session out FIRST, and delete the host's\n * own copy of the secret last. Refuses as `prepareDeviceKey` does. */\n discardPreparedDeviceKey(): Promise<boolean> {\n return this.call({\n kind: \"discardPreparedDeviceKey\",\n id: this.nextId++,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<boolean>;\n }\n\n /** THE PREDICATE (ruling V904): what a start from the device record would\n * answer on this store, as a typed value. It starts nothing, writes\n * nothing and sends nothing. `expectedDeviceId` is the PUBLIC device id\n * the host keeps, if it keeps one. Decide stop or retry on the answer,\n * never on the words of an error. */\n deviceStartCheck(expectedDeviceId?: Uint8Array): Promise<DeviceStartCheck> {\n return this.call({\n kind: \"deviceStartCheck\",\n id: this.nextId++,\n expectedDeviceId,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<DeviceStartCheck>;\n }\n\n /** Whether the slot holds the pending root this device expects (rule R32).\n * No prompt, no read of the seed. */\n pendingStatus(slot: string): Promise<PendingRootStatus> {\n return this.call({\n kind: \"pendingStatus\",\n id: this.nextId++,\n slot,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<PendingRootStatus>;\n }\n\n /** The first backup of a PENDING account. `accountId` is the account's\n * 16-byte id at the auth layer. */\n makeBackup(args: {\n slot: string;\n phrase: string;\n accountId: Uint8Array;\n hostState: Uint8Array;\n }): Promise<AccountBackupParts> {\n return this.call({\n kind: \"makeBackup\",\n id: this.nextId++,\n slot: args.slot,\n phrase: phraseBytes(args.phrase),\n accountId: args.accountId,\n hostState: args.hostState,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<AccountBackupParts>;\n }\n\n /** Rule R10 (b): the root part READ BACK from where it was stored opens to\n * this account. Answers the fingerprint `endPending` asks for. */\n async proveBackup(args: { readBackRootPart: Uint8Array; phrase: string }): Promise<Uint8Array> {\n const proof = (await this.call({\n kind: \"proveBackup\",\n id: this.nextId++,\n readBackRootPart: args.readBackRootPart,\n phrase: phraseBytes(args.phrase),\n storageFeatures: storageFeaturesOf(this.storage),\n })) as { fingerprint: Uint8Array };\n return proof.fingerprint;\n }\n\n /** End PENDING: delete the pending item, only against the proof on record. */\n async endPending(args: { slot: string; fingerprint: Uint8Array }): Promise<void> {\n await this.call({\n kind: \"endPending\",\n id: this.nextId++,\n slot: args.slot,\n fingerprint: args.fingerprint,\n storageFeatures: storageFeaturesOf(this.storage),\n });\n }\n\n /** \"Start over\" on an account that was started on this device and never\n * finished (rulings V1201, V1277): deletes the pending root of ONE slot and\n * nothing else, or refuses with a typed answer (see `PendingRootDiscard`).\n * THE HOST'S DUTY, which the SDK cannot check: the person chose it, the\n * slot's stored account is the account signed in now, this sign-in's fresh\n * answer is exactly `none_pinned`, and the slot's SDK store is emptied in\n * the same erase. Never call it from a sweep. */\n discardPendingRoot(slot: string): Promise<PendingRootDiscard> {\n return this.call({\n kind: \"discardPendingRoot\",\n id: this.nextId++,\n slot,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<PendingRootDiscard>;\n }\n\n // ---- The restore as a rotation (the account identity contract, sections\n // 3.9, 3.13, 13.1). None of these needs a client or a session: the backup\n // is opened and the whole `rotation` object is built before the device\n // exists at the server. No call takes or returns a root. ----\n\n /** Step 3 of a restore: the root part opens with the phrase to the PINNED\n * root; `hostState` is there when the root part's secret opens the state\n * part. Writes nothing. */\n openBackupForRestore(args: {\n rootPart: Uint8Array;\n phrase: string;\n statePart?: Uint8Array;\n pinnedRootPublicKey: Uint8Array;\n }): Promise<RestoreOpened> {\n return this.call({\n kind: \"openBackupForRestore\",\n id: this.nextId++,\n rootPart: args.rootPart,\n phrase: phraseBytes(args.phrase),\n statePart: args.statePart,\n pinnedRootPublicKey: args.pinnedRootPublicKey,\n }) as Promise<RestoreOpened>;\n }\n\n /**\n * M1, take the account over: the next generation (the pinned one plus one,\n * or a refusal), a NEW device key, the new generation secret, the device's\n * credential, the statement, its wrap, the new backup parts, and the\n * rotation record. `oldStatePart` gives its anchors only; `hostState` is\n * the NEW host state with the NEW sign-in key companion. Called again with\n * the same rotation id it answers the same request and the same device key.\n */\n restoreTakeOver(args: {\n rootPart: Uint8Array;\n phrase: string;\n start: RotationStart;\n oldStatePart?: Uint8Array;\n accountId: Uint8Array;\n hostState: Uint8Array;\n }): Promise<RotationBuilt> {\n return this.call({\n kind: \"restoreTakeOver\",\n id: this.nextId++,\n rootPart: args.rootPart,\n phrase: phraseBytes(args.phrase),\n start: args.start,\n oldStatePart: args.oldStatePart,\n accountId: args.accountId,\n hostState: args.hostState,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<RotationBuilt>;\n }\n\n /** \"Take your account back\": the take-over with the pending root of the\n * slot. The pending item is read, never written and never deleted.\n * `oldStatePart` is the account's state part as the escrow served it\n * (it gives its anchors only); `undefined` only when none was served.\n * ON AN EMPTY STORE EVERY JOIN IS UNCHECKED: never empty the SDK's\n * store on the service's word while the slot holds a pending item\n * (ruling V538). */\n takeAccountBack(args: {\n slot: string;\n start: RotationStart;\n oldStatePart: Uint8Array | undefined;\n accountId: Uint8Array;\n hostState: Uint8Array;\n }): Promise<RotationBuilt> {\n return this.call({\n kind: \"takeAccountBack\",\n id: this.nextId++,\n slot: args.slot,\n start: args.start,\n oldStatePart: args.oldStatePart,\n accountId: args.accountId,\n hostState: args.hostState,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<RotationBuilt>;\n }\n\n /** At every start: the rotation this device built and has not finished, or\n * `null`. While its phase is `\"built\"` the host sends the identical\n * request again. */\n resumeRotation(): Promise<PendingRotation | null> {\n return this.call({\n kind: \"resumeRotation\",\n id: this.nextId++,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<PendingRotation | null>;\n }\n\n /** `resumeRotation` WITH THE HOST'S CLOCK (ruling V461; `nowMs`, by default\n * this client's own): the call an app makes at every start. A take-over\n * the server never answered loses the sealing seed it kept once 30 days\n * have passed since its record was made; the record itself stays. */\n resumeRotationAt(nowMs: number = this.now()): Promise<PendingRotation | null> {\n return this.call({\n kind: \"resumeRotation\",\n id: this.nextId++,\n nowMs,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<PendingRotation | null>;\n }\n\n /** The server's answer to the request of record `recordId`, AS RECEIVED\n * and judged inside the SDK (ruling V161): the device adopts, or discards\n * the record only against a DIFFERENT pinned statement the root signed\n * (`\"lost\"`); a final refusal of the server (`\"refused\"`, `400\n * rotation_invalid` included) keeps the record until `abandonRotation`; any\n * other answer is `\"undecided\"` and changes nothing. */\n completeRotation(recordId: Uint8Array, answer: RotationAnswer): Promise<RotationOutcome> {\n return this.call({\n kind: \"completeRotation\",\n id: this.nextId++,\n recordId,\n answer: rotationAnswerFields(answer),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<RotationOutcome>;\n }\n\n /** Move an adopted rotation forward. */\n async setRotationPhase(recordId: Uint8Array, phase: \"device_group_done\" | \"queued\"): Promise<void> {\n await this.call({\n kind: \"setRotationPhase\",\n id: this.nextId++,\n recordId,\n phase,\n storageFeatures: storageFeaturesOf(this.storage),\n });\n }\n\n /** Step 6: delete the record of an adopted rotation. */\n async finishRotation(recordId: Uint8Array): Promise<void> {\n await this.call({\n kind: \"finishRotation\",\n id: this.nextId++,\n recordId,\n storageFeatures: storageFeaturesOf(this.storage),\n });\n }\n\n /** Ruling V212: ABANDON a rotation that was never adopted. Its record is\n * deleted, so that another rotation can start. THE PERSON'S CHOICE (after\n * `\"refused\"`, or to supply the phrase after `\"root_part_required\"`): the\n * SDK never calls it. ONLY a record the server answered with one of\n * those two is deleted (ruling V227): a record the server never answered\n * is refused (`rotation-refused`) and its request is sent again, because\n * the server may have applied it and the record then holds the only copy\n * of the new device's key. An adopted rotation is refused\n * (`rotation-refused`); it ends by `finishRotation`. */\n async abandonRotation(recordId: Uint8Array): Promise<void> {\n await this.call({\n kind: \"abandonRotation\",\n id: this.nextId++,\n recordId,\n storageFeatures: storageFeaturesOf(this.storage),\n });\n }\n\n /** Ruling V232: whether this store holds a rotation record and whether the\n * server refused it for good, so a screen can offer \"start over\" after a\n * restart without sending the request once more. One local read: no secret,\n * no id, no request. The refusal it reports is the server's unauthenticated\n * word; this read decides nothing. */\n rotationRecordState(): Promise<RotationRecordState> {\n return this.call({\n kind: \"rotationRecordState\",\n id: this.nextId++,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<RotationRecordState>;\n }\n\n /** M2, join beside the devices that stay: no rotation; a depth 0 credential\n * at the pinned generation. `restore-join-not-current`: offer M1 or a link. */\n restoreJoin(args: {\n rootPart: Uint8Array;\n phrase: string;\n statePart: Uint8Array;\n start: RotationStart;\n }): Promise<RestoreJoined> {\n return this.call({\n kind: \"restoreJoin\",\n id: this.nextId++,\n rootPart: args.rootPart,\n phrase: phraseBytes(args.phrase),\n statePart: args.statePart,\n start: args.start,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<RestoreJoined>;\n }\n\n /** Open the account's state part with the generation secret this device\n * holds, and keep its anchors. No phrase, no root.\n * It is also the ONE look a linked device owes before it writes a state\n * part: until this ran once, `refreshStateBackup` and a rotation that keeps\n * the device's key reject with the code `state-part-look-owed`. Pass an\n * EMPTY part when the service serves none; whatever this answers, the look\n * is made. */\n openStateBackup(statePart: Uint8Array): Promise<StateOpened> {\n return this.call({\n kind: \"openStateBackup\",\n id: this.nextId++,\n statePart,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<StateOpened>;\n }\n\n /** Write the account's state part anew under the generation secret this\n * device holds. */\n refreshStateBackup(args: { accountId: Uint8Array; hostState: Uint8Array }): Promise<StateRefreshed> {\n return this.call({\n kind: \"refreshStateBackup\",\n id: this.nextId++,\n accountId: args.accountId,\n hostState: args.hostState,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<StateRefreshed>;\n }\n\n /**\n * Begin a set-up session whose root is in memory only (rule R34 a): for the\n * person who makes the backup during set-up. One session per object; it\n * lives in the Worker until `sessionFinish`, `sessionKeepAsPending` or\n * `close`. It begins ON THIS STORE (read, nothing written): the session's\n * device is made for the store's free prepared device key, when\n * `prepareDeviceKey` made one. `device-key-held-by-link`: a link was begun\n * in this slot.\n */\n async beginInMemory(identityState: string | undefined): Promise<void> {\n await this.call({\n kind: \"beginAccountSetupInMemory\",\n id: this.nextId++,\n identityState,\n nowMs: this.now(),\n storageFeatures: storageFeaturesOf(this.storage),\n });\n }\n\n /** The session's backup. */\n sessionMakeBackup(args: { phrase: string; accountId: Uint8Array; hostState: Uint8Array }): Promise<AccountBackupParts> {\n return this.call({\n kind: \"setupSessionMakeBackup\",\n id: this.nextId++,\n phrase: phraseBytes(args.phrase),\n accountId: args.accountId,\n hostState: args.hostState,\n nowMs: this.now(),\n }) as Promise<AccountBackupParts>;\n }\n\n /** Rule R10 (b) for the session. Answers the fingerprint. */\n async sessionProveBackup(args: { readBackRootPart: Uint8Array; phrase: string }): Promise<Uint8Array> {\n const proof = (await this.call({\n kind: \"setupSessionProveBackup\",\n id: this.nextId++,\n readBackRootPart: args.readBackRootPart,\n phrase: phraseBytes(args.phrase),\n })) as { fingerprint: Uint8Array };\n return proof.fingerprint;\n }\n\n /** End the session after the proof: the device record is written, the root\n * is wiped. Only then does the host upload KeyPackages. */\n sessionFinish(): Promise<NewAccountDevice> {\n return this.call({\n kind: \"setupSessionFinish\",\n id: this.nextId++,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<NewAccountDevice>;\n }\n\n /** \"Not now\" after the session began (ruling ID42): THIS session's root\n * becomes the pending item, then the device record is written. */\n sessionKeepAsPending(args: { slot: string; persistentStorage?: boolean }): Promise<NewAccountDevice> {\n return this.call({\n kind: \"setupSessionKeepAsPending\",\n id: this.nextId++,\n slot: args.slot,\n persistentStorage: args.persistentStorage,\n storageFeatures: storageFeaturesOf(this.storage),\n }) as Promise<NewAccountDevice>;\n }\n\n /** Stop the Worker. A session still open there is wiped with it. */\n close(): void {\n if (this.closed) return;\n this.closed = true;\n try {\n this.worker.postMessage({ kind: \"endAccountSetupSession\", id: this.nextId++ } as Request);\n } catch {\n // The worker is gone already: nothing is left to wipe.\n }\n this.worker.onmessage = null;\n this.worker.onerror = null;\n this.worker.terminate();\n this.fail(new AccountSetupClosedError());\n }\n\n private fail(error: unknown): void {\n const waiting = [...this.pending.values()];\n this.pending.clear();\n for (const slot of waiting) slot.reject(error);\n }\n\n /** Post a request. A recovery phrase in it crossed as bytes (ruling\n * V253): this side's copy is zeroed when the call has answered, whatever\n * it answered; the Worker zeroes its own. */\n private call(req: Request): Promise<unknown> {\n const phrase = (req as { phrase?: unknown }).phrase;\n const answered = this.post(req);\n return phrase instanceof Uint8Array ? answered.finally(() => { phrase.fill(0); }) : answered;\n }\n\n private post(req: Request): Promise<unknown> {\n if (this.closed) return Promise.reject(new AccountSetupClosedError());\n return new Promise((resolve, reject) => {\n this.pending.set((req as { id: number }).id, { resolve, reject });\n try {\n this.worker.postMessage(req);\n } catch (e) {\n this.pending.delete((req as { id: number }).id);\n reject(e);\n }\n });\n }\n\n private async handleWorker(msg: Response): Promise<void> {\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 if (msg.ok) slot.resolve(msg.value);\n else slot.reject(new Error(msg.error));\n return;\n }\n case \"storage.call\": {\n try {\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 value = await (method as (...a: unknown[]) => unknown).apply(this.storage, msg.args);\n if (!this.closed) this.worker.postMessage({ kind: \"storage.reply\", id: msg.id, ok: true, value } as Request);\n } catch (e) {\n if (!this.closed) {\n this.worker.postMessage({ kind: \"storage.reply\", id: msg.id, ok: false, error: String(e) } as Request);\n }\n }\n return;\n }\n case \"transport.call\": {\n // Set-up sends nothing and reads nothing from the server.\n this.worker.postMessage({\n kind: \"transport.reply\", id: msg.id, ok: false, error: \"account set-up has no transport\",\n } as Request);\n return;\n }\n default:\n return;\n }\n }\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 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 // Label is unused on the read-only path (no LocalDevice is ever minted).\n const client =\n await wasm.PingClient.openReadOnlyFromDeviceRecord(\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: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