@dimchansky/meshpost 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,12 +5,12 @@
5
5
 
6
6
  **Live demo:** [dimchansky.github.io/meshpost](https://dimchansky.github.io/meshpost/) — open on two devices or browser tabs to test direct peer-to-peer cursors and chat.
7
7
 
8
- Meshpost connects browsers directly to send small binary packets (up to 16 KiB) with no backend server for app traffic.
8
+ Meshpost connects peers directly over WebRTC to exchange binary packets, typed messages, RPC calls, per-peer state, large files, and voice/media with **no central backend for app traffic**.
9
9
 
10
- - **Direct peer-to-peer:** Browsers connect directly to each other. There is no host or central relay for your data.
11
- - **Two delivery modes:** Send fast unreliable packets (for cursors or game positions) or ordered reliable packets (for chat or commands).
12
- - **Resilient:** Connected peers keep talking even if the first person leaves or the discovery server goes offline.
13
- - **Zero runtime dependencies:** TypeScript ES modules built on native browser WebRTC.
10
+ - **Direct peer-to-peer:** Browsers (and headless Node.js / Bun / Deno peers) connect directly to each other with no host election or central data relay.
11
+ - **Two delivery modes + batteries included:** Fast unreliable or ordered reliable packets, plus tree-shakeable typed codecs (`createCodecChannel`), request-response RPC (`createRpc`), per-peer state sync (`createPeerState`), chunked transfers (`createBlobChannel`), headless P2P voice (`createVoice`), and DTLS-bound `ECDSA P-256` identity (`createIdentity`).
12
+ - **Flexible E2E-encrypted discovery:** Built-in MQTT, port-443 Nostr (`kind: 25050`), WebSocket (with a ready-to-deploy Cloudflare Durable Object Worker), `BroadcastChannel`, and offline copy-paste signaling — connected peers keep talking even if discovery goes offline.
13
+ - **Zero runtime dependencies:** Pure TypeScript ES modules with granular `@dimchansky/meshpost/*` subpath exports (`importmap`-ready).
14
14
 
15
15
  ## Quick start: 2-browser chat in 30 lines
16
16
 
@@ -32,15 +32,16 @@ Meshpost connects browsers directly to send small binary packets (up to 16 KiB)
32
32
  2. Import `joinRoom` and a signaling adapter (used only to help browsers find each other) in your browser app (use `@dimchansky/meshpost` if installed as a package, or `./dist/index.js` from a local build):
33
33
 
34
34
  ```ts
35
- import { joinRoom, mqttSignaling } from '@dimchansky/meshpost'
35
+ import { joinRoom, publicSignaling } from '@dimchansky/meshpost'
36
36
 
37
37
  const encoder = new TextEncoder()
38
38
  const decoder = new TextDecoder()
39
39
 
40
- // Join a room. Browsers with the same appId and room name connect automatically.
40
+ // Join a room. Browsers with the same appId and room name connect automatically
41
+ // over local tabs + public MQTT + port-443 Nostr relays (plus optional wsUrls).
41
42
  const room = joinRoom('lobby', {
42
43
  appId: 'my-chat-app',
43
- signaling: mqttSignaling()
44
+ signaling: publicSignaling()
44
45
  })
45
46
 
46
47
  room.onPeerJoin((peerId) => console.log('Joined:', peerId))
@@ -62,48 +63,48 @@ Meshpost connects browsers directly to send small binary packets (up to 16 KiB)
62
63
  }
63
64
  }
64
65
 
65
- // Clean up when the tab closes.
66
- window.addEventListener(
67
- 'pagehide',
68
- () => {
69
- stop()
70
- room.leave()
71
- },
72
- { once: true }
73
- )
66
+ // Explicitly leave when your UI unmounts or the user clicks "Leave".
67
+ // (Tab closes and F5 page reloads are handled automatically by Meshpost.)
68
+ function leaveChat() {
69
+ stop()
70
+ room.leave()
71
+ }
74
72
  ```
75
73
 
76
- 3. Use `createChannel` when your app has multiple message types (so modules do not collide):
74
+ 3. Use `createChannel` (or typed `createCodecChannel` with `jsonCodec` / `textCodec`) when your app has multiple message types so modules do not collide:
77
75
 
78
76
  ```ts
79
- import { createChannel } from '@dimchansky/meshpost'
77
+ import { createChannel, createCodecChannel, textCodec } from '@dimchansky/meshpost'
80
78
 
81
79
  const cursors = createChannel(room, 'cursor', { delivery: 'unreliable' })
82
- const chat = createChannel(room, 'chat', { delivery: 'reliable' })
80
+ const chat = createCodecChannel(room, 'chat', textCodec, { delivery: 'reliable' })
83
81
 
84
82
  cursors.onPacket((from, bytes) => updateCursor(from, bytes))
85
- chat.onPacket((from, bytes) => showChat(from, decoder.decode(bytes)))
83
+ chat.onMessage((from, text) => showChat(from, text))
86
84
 
87
85
  // Broadcast a cursor update to everyone.
88
86
  cursors.send(cursorBytes)
89
87
 
90
- // Send a reliable command to one specific peer and inspect the result.
91
- const status = chat.send(encoder.encode('hello'), { to: peerId }).get(peerId)
88
+ // Send a reliable message to one specific peer and inspect the synchronous SendResult.
89
+ const status = chat.send('hello', { to: peerId }).get(peerId)
92
90
  ```
93
91
 
94
92
  ## Choose a signaling adapter
95
93
 
96
94
  Browsers need a signaling adapter only to find each other and start the connection. After that, data travels directly between browsers.
97
95
 
98
- | Adapter | Best for | Server needed? |
99
- | ---------------------------- | ----------------------------------------------------------------------------- | ------------------ |
100
- | `mqttSignaling(options?)` | Different browsers, devices, and networks out of the box | No (public relays) |
101
- | `wsSignaling(url, options?)` | Production apps with your own WebSocket signaling server (`wss://`) | Your WS server |
102
- | `tabSignaling()` | Multiple tabs in the same browser profile (works offline) | No |
103
- | `manualSignaling(outgoing)` | Completely offline browsers (no network needed) by copying and pasting text | No |
104
- | `withLocalTabs(primary)` | Instant same-browser tabs + remote MQTT/WebSocket with accurate network state | Same as `primary` |
105
- | `combineSignaling(...list)` | Composing multiple network adapters (stays `'online'` if any child is online) | Depends on list |
106
- | Custom `Signaling` | Custom transports (such as Server-Sent Events or an existing backend channel) | Your server |
96
+ | Adapter | Best for | Server needed? |
97
+ | --------------------------------- | ------------------------------------------------------------------------------------- | ------------------- |
98
+ | `publicSignaling(options?)` | All-in-one preset: local tabs + MQTT + port-443 Nostr + optional fast `wsUrls` | No (optional WS) |
99
+ | `mqttSignaling(options?)` | Different browsers, devices, and networks out of the box | No (public relays) |
100
+ | `nostrSignaling(options?)` | Corporate/school Wi-Fi blocking MQTT ports (runs over port-443 `wss://`) | No (public relays) |
101
+ | `wsSignaling(url, options?)` | Production apps with a primary WebSocket relay (see `examples/ws-worker/`) | Your WS / CF Worker |
102
+ | `optionalWsSignaling(url, opts?)` | Opportunistic WS fast-path inside `combineSignaling` (silent fallback if unreachable) | Optional WS |
103
+ | `tabSignaling()` | Multiple tabs in the same browser profile (works offline) | No |
104
+ | `manualSignaling(outgoing)` | Completely offline browsers (no network needed) by copying and pasting text | No |
105
+ | `withLocalTabs(primary)` | Instant same-browser tabs + remote MQTT/Nostr/WS with accurate network state | Same as `primary` |
106
+ | `combineSignaling(...list)` | Composing multiple network adapters (e.g. `mqttSignaling` + `nostrSignaling`) | Depends on list |
107
+ | Custom `Signaling` | Custom transports (such as Server-Sent Events or an existing backend channel) | Your server |
107
108
 
108
109
  ### Local tabs (`tabSignaling`)
109
110
 
@@ -136,7 +137,7 @@ manual.accept(pastedTextFromPeer) // Paste incoming contact cards and replies he
136
137
  manual.forget(oldPeerId) // Optional: stop retrying an old contact.
137
138
  ```
138
139
 
139
- > **Password note:** Pass `password: 'secret'` to `joinRoom()` so only peers with the same password can join the room. With `mqttSignaling()`, this also encrypts setup messages. Browsers allow encryption only on `https://` pages or `http://localhost` (`127.0.0.1`), so using `password` with `mqttSignaling()` on `file://` or plain `http://<lan-ip>` throws an error. (`tabSignaling()`, `wsSignaling()`, and `manualSignaling()` support `password` everywhere.)
140
+ > **Password note:** Pass `password: 'secret'` to `joinRoom()` so only peers with the same password can join the room. With `mqttSignaling()`, `nostrSignaling()`, and `wsSignaling()` (by default), this also end-to-end encrypts setup messages with `AES-256-GCM` so relays only see opaque ciphertexts. Browsers expose Web Crypto (`crypto.subtle`) only on `https://` pages or `http://localhost` (`127.0.0.1`), so using `password` with `mqttSignaling()`, `nostrSignaling()`, or default `wsSignaling()` on `file://` or plain `http://<lan-ip>` throws an error (pass `{ encrypt: false }` to `wsSignaling()` only for plaintext HTTP LAN testing; `tabSignaling()` and `manualSignaling()` work everywhere). Pass `{ privateTopic: true }` to `mqttSignaling()`, `nostrSignaling()`, or `wsSignaling()` when you also want to derive the relay topic/tag/room key cryptographically from `password` (disabling `'decrypt-failed'` wrong-password hints).
140
141
 
141
142
  ## Public API reference
142
143
 
@@ -147,42 +148,78 @@ Creates a room, assigns a random peer ID (`room.id`), and immediately starts loo
147
148
  - `name`: Room name. Must match `^[a-zA-Z0-9_-]{1,64}$`.
148
149
  - Throws an error immediately if `name`, `appId`, `password`, timeouts, `maxPeers`, or `rtcConfig` are invalid.
149
150
 
150
- | `RoomOptions` field | Type | Default | Purpose |
151
- | ----------------------- | ------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------- |
152
- | `signaling` | `Signaling` | _(required)_ | Adapter that helps browsers find each other and start direct connections. |
153
- | `appId` | `string` | `'meshpost'` | Keeps your app's rooms separate from other apps on the same relay (`[a-zA-Z0-9._-]{1,64}`). |
154
- | `password` | `string` | `undefined` | Optional shared password. Keeps rooms separate and encrypts setup messages on MQTT. |
155
- | `turnConfig` | `readonly RTCIceServer[]` | `[]` | Extra TURN (or STUN) servers appended to `rtcConfig.iceServers` (or `defaultIceServers` when omitted). |
156
- | `rtcConfig` | `RTCConfiguration` | `defaultIceServers` | Custom WebRTC config. Keeps `defaultIceServers` unless you set `iceServers` (pass `{ iceServers: [] }` offline). |
157
- | `handshakeTimeoutMs` | `number` | `35_000` | Max time to wait per connection attempt before retrying. |
158
- | `iceGatheringTimeoutMs` | `number` | `2_500` | Max time to wait for network addresses before starting a connection. |
159
- | `maxPeers` | `number` | `32` | Maximum simultaneous peer connections. |
151
+ | `RoomOptions` field | Type | Default | Purpose |
152
+ | ----------------------- | ------------------------------ | ------------------------------ | ---------------------------------------------------------------------------------------------------------------- |
153
+ | `signaling` | `Signaling` | _(required)_ | Adapter that helps browsers find each other and start direct connections. |
154
+ | `appId` | `string` | `'meshpost'` | Keeps your app's rooms separate from other apps on the same relay (`[a-zA-Z0-9._-]{1,64}`). |
155
+ | `password` | `string` | `undefined` | Optional shared password. Isolates rooms and end-to-end encrypts setup messages on MQTT, Nostr, & WebSocket. |
156
+ | `turnConfig` | `readonly RTCIceServer[]` | `[]` | Extra TURN (or STUN) servers appended to `rtcConfig.iceServers` (or `defaultIceServers` when omitted). |
157
+ | `rtcConfig` | `RTCConfiguration` | `defaultIceServers` | Custom WebRTC config. Keeps `defaultIceServers` unless you set `iceServers` (pass `{ iceServers: [] }` offline). |
158
+ | `handshakeTimeoutMs` | `number` | `35_000` | Max time to wait per connection attempt before retrying. |
159
+ | `iceGatheringTimeoutMs` | `number` | `2_500` | Max time to wait for network addresses before starting a connection. |
160
+ | `maxPeers` | `number` | `32` | Maximum simultaneous peer connections. |
161
+ | `identity` | `PeerIdentity` | `undefined` | Optional persistent WebCrypto `ECDSA P-256` identity proven to peers over each WebRTC link (`room.peerUserId`). |
162
+ | `RTCPeerConnection` | `RTCPeerConnectionConstructor` | `globalThis.RTCPeerConnection` | Optional custom `RTCPeerConnection` constructor for headless runtimes (Node.js, Bun, Deno) or tests. |
160
163
 
161
164
  ### `Room`
162
165
 
163
- | Member | Description |
164
- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
165
- | `room.id` | Your peer ID (`string`). A page reload creates a new peer ID. |
166
- | `room.peers` | Current list of connected peer IDs (returns a fresh copy each time). |
167
- | `room.signalingState` | Current adapter state: `'connecting' \| 'online' \| 'offline' \| 'closed'`. |
168
- | `room.send(bytes, options?: SendOptions)` | Sends a `Uint8Array`. `options` accepts `{ to?: string, delivery?: Delivery }` (`Delivery` is `'unreliable' \| 'reliable'`, default `'unreliable'`). Returns `ReadonlyMap<string, SendResult>`. |
169
- | `room.getStats(peerId)` | Returns `Promise<PeerStats \| null>` with ping, route, byte counts, and send buffer sizes (`null` if not connected). |
170
- | `room.onPacket(fn, options?: ListenOptions)` | Runs when a packet arrives (`(from, bytes, delivery) => ...`). Returns an unsubscribe function. |
171
- | `room.onDrain(fn, options?: ListenOptions)` | Runs when a full send buffer has space again (`(peerId, delivery) => ...`, after `send()` returned `'busy'`). Returns unsubscribe. |
172
- | `room.onPeerJoin(fn, options?: ListenOptions)` | Runs when a peer finishes connecting and is ready to exchange packets (`(peerId) => ...`). Returns unsubscribe. |
173
- | `room.onPeerLeave(fn, options?: ListenOptions)` | Runs when a connected peer disconnects (`(peerId) => ...`). Returns unsubscribe. |
174
- | `room.onSignalingChange(fn, options?: ListenOptions)` | Runs on future `signalingState` changes (`(state, reason?) => ...`). Returns unsubscribe. |
175
- | `room.onError(fn, options?: ListenOptions)` | Runs on structured room or signaling errors (`(error: RoomError) => ...`, codes `'room-full' \| 'ice-failed' \| 'media-error' \| 'decrypt-failed' \| 'signaling-error'`). Returns unsubscribe. |
176
- | `room.addStream(stream, to?)` | Attaches a local `MediaStream` (audio/video) to all connected and future peers, or selectively to one peer (`to`). |
177
- | `room.removeStream(stream, to?)` | Detaches a previously added local `MediaStream` from all peers, or from one peer (`to`). |
178
- | `room.onPeerStream(fn, options?: ListenOptions)` | Runs when a remote peer adds a `MediaStream` (`(peerId, stream) => ...`). Fires strictly after `onPeerJoin`. Returns unsubscribe. |
179
- | `room.onPeerStreamEnd(fn, options?: ListenOptions)` | Runs when a remote peer removes a `MediaStream` or disconnects (`(peerId, stream) => ...`). Returns unsubscribe. |
180
- | `room.leave()` | Leaves the room, tells peers you left, and closes all connections. Safe to call more than once. |
181
-
182
- All `on*` methods (on `Room`, `Channel`, `BlobChannel`, and `Voice`) optionally accept `ListenOptions` (`{ once?: boolean, signal?: AbortSignal }`) to auto-unsubscribe after the first invocation or when an `AbortSignal` aborts.
166
+ | Member | Description |
167
+ | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
168
+ | `room.id` | Your peer ID (`string`). A page reload creates a new peer ID (and automatically reclaims any stale ghost session from the same tab). |
169
+ | `room.userId` | Your verified 22-char `userId` (`string`) when `options.identity` was passed, or `null` if anonymous. |
170
+ | `room.peers` | Current list of connected peer IDs (returns a fresh copy each time). |
171
+ | `room.signalingState` | Current adapter state: `'connecting' \| 'online' \| 'offline' \| 'closed'`. |
172
+ | `room.peerUserId(peerId)` | Returns the cryptographically verified `userId` (`string`) of a connected peer (already verified before `onPeerJoin` fires), or `null` if anonymous or disconnected. |
173
+ | `room.send(bytes, options?: SendOptions)` | Sends a `Uint8Array`. `options` accepts `{ to?: string, delivery?: Delivery }` (`Delivery` is `'unreliable' \| 'reliable'`, default `'unreliable'`). Returns `ReadonlyMap<string, SendResult>`. |
174
+ | `room.getStats(peerId)` | Returns `Promise<PeerStats \| null>` with ping, route, byte counts, and send buffer sizes (`null` if not connected). |
175
+ | `room.onPacket(fn, options?: ListenOptions)` | Runs when a packet arrives (`(from, bytes, delivery) => ...`). Returns an unsubscribe function. |
176
+ | `room.onDrain(fn, options?: ListenOptions)` | Runs when a full send buffer has space again (`(peerId, delivery) => ...`, after `send()` returned `'busy'`). Returns unsubscribe. |
177
+ | `room.onPeerJoin(fn, options?: ListenOptions)` | Runs when a peer finishes connecting and verifying its handshake (`(peerId) => ...`). Returns unsubscribe. |
178
+ | `room.onPeerLeave(fn, options?: ListenOptions)` | Runs when a connected peer disconnects (`(peerId) => ...`). Returns unsubscribe. |
179
+ | `room.onSignalingChange(fn, options?: ListenOptions)` | Runs on future `signalingState` changes (`(state, reason?) => ...`). Returns unsubscribe. |
180
+ | `room.onError(fn, options?: ListenOptions)` | Runs on structured room or signaling errors (`(error: RoomError) => ...`, codes `'room-full' \| 'ice-failed' \| 'media-error' \| 'auth-failed' \| 'decrypt-failed' \| 'clock-skew' \| 'signaling-error'`). Returns unsubscribe. |
181
+ | `room.addStream(stream, toOrOptions?)` | Attaches a local `MediaStream` to all connected/future peers, or selectively via `peerId` or `AddStreamOptions` (`{ to?: string, tag?: string }`). |
182
+ | `room.removeStream(stream, toOrOptions?)` | Detaches a previously added local `MediaStream` from all peers, or from one peer (`peerId` or `RemoveStreamOptions` `{ to?: string }`). |
183
+ | `room.replaceStreamTrack(stream, oldTrack, newTrack)` | Hot-swaps a track inside an attached `MediaStream` via `RTCRtpSender.replaceTrack()` with zero WebRTC SDP renegotiation (`Promise<void>`). |
184
+ | `room.onPeerStream(fn, options?: ListenOptions)` | Runs when a remote peer adds a `MediaStream` (`(peerId, stream, meta: PeerStreamMeta) => ...`, where `meta` has `{ tag?: string }`). Fires strictly after `onPeerJoin`. Returns unsubscribe. |
185
+ | `room.onPeerStreamEnd(fn, options?: ListenOptions)` | Runs when a remote peer removes a `MediaStream` or disconnects (`(peerId, stream, meta: PeerStreamMeta) => ...`). Returns unsubscribe. |
186
+ | `room.leave()` | Leaves the room, tells peers you left, and closes all connections. Safe to call more than once. |
187
+
188
+ All `on*` methods (on `Room`, `Channel`, `CodecChannel`, `PeerState`, `BlobChannel`, `Voice`, plus `rpc.handle()`) optionally accept `ListenOptions` (`{ once?: boolean, signal?: AbortSignal }`) to auto-unsubscribe after the first invocation or when an `AbortSignal` aborts.
183
189
 
184
190
  `room.onError` emits a `RoomError` object: `{ code: RoomErrorCode, message: string, peerId?: string }`.
185
191
 
192
+ ### Verifiable peer identity (`createIdentity` / `exportIdentity` / `importIdentity`)
193
+
194
+ Zero-dependency persistent peer identity powered by native WebCrypto `ECDSA P-256` (`SHA-256`), with **DTLS certificate fingerprint channel binding** so signatures cannot be MitM-relayed or replayed across rooms, apps, or connections (even on unencrypted signaling relays):
195
+
196
+ - `createIdentity(options?: CreateIdentityOptions): Promise<PeerIdentity>` — generates a fresh `P-256` keypair (`{ extractable?: boolean }`, default `true`) and returns a frozen `{ userId, publicKey }` handle (`userId` is a deterministic 22-char base64url 128-bit fingerprint; private key material stays inside an internal `WeakMap`).
197
+ - `exportIdentity(identity): Promise<SerializedIdentity>` — exports `{ v: 1, crv: 'P-256', x, y, d }` for JSON storage (e.g. `localStorage`).
198
+ - `importIdentity(data, options?: CreateIdentityOptions): Promise<PeerIdentity>` — validates shape, verifies `(x, y)` cryptographically against `d` via a challenge signature, and restores `PeerIdentity`.
199
+ - `isSerializedIdentity(value): value is SerializedIdentity` — runtime type guard for untrusted storage payloads.
200
+
201
+ ```ts
202
+ import {
203
+ createIdentity,
204
+ exportIdentity,
205
+ importIdentity,
206
+ isSerializedIdentity,
207
+ joinRoom
208
+ } from '@dimchansky/meshpost'
209
+
210
+ const raw = JSON.parse(localStorage.getItem('my-id') ?? 'null')
211
+ const identity = isSerializedIdentity(raw) ? await importIdentity(raw) : await createIdentity()
212
+ localStorage.setItem('my-id', JSON.stringify(await exportIdentity(identity)))
213
+
214
+ const room = joinRoom('lobby', { signaling, identity })
215
+ console.log('My verified userId:', room.userId)
216
+
217
+ room.onPeerJoin((peerId) => {
218
+ // Already verified over WebRTC with DTLS channel binding before onPeerJoin fires!
219
+ console.log('Peer joined:', peerId, 'verified userId:', room.peerUserId(peerId))
220
+ })
221
+ ```
222
+
186
223
  ### `createVoice(room, options?: VoiceOptions)`
187
224
 
188
225
  Headless P2P voice chat controller built on top of `room.addStream()` / `room.onPeerStream()`:
@@ -192,34 +229,43 @@ Headless P2P voice chat controller built on top of `room.addStream()` / `room.on
192
229
  - Tracks speaking peers (`speakingPeers`) and local mic activity (`selfSpeaking`) via a shared lazy `AudioContext` + `AnalyserNode` (routed through a `GainNode(0)` sink for WebKit/iOS Safari compatibility).
193
230
  - Handles browser Autoplay Policy & iOS Safari quirks out of the box (lock-free `{ capture: true }` gesture unlocking on `pointerdown`/`pointerup`/`touchend`/`click`/`keydown`, iOS `'interrupted'` `AudioContext` recovery, `visibilitychange` foreground resume, and 6-path `navigator.audioSession` `'play-and-record'` save/restore).
194
231
 
195
- | `VoiceOptions` field | Type | Default | Purpose |
196
- | -------------------- | ------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
197
- | `volume` | `number` | `1` | Initial playback volume (`0` to `1`) for incoming peer audio. |
198
- | `deafened` | `boolean` | `false` | Start with incoming peer audio muted locally (`audio.muted = true`). |
199
- | `audioConstraints` | `MediaTrackConstraints \| true` | `{ echoCancellation: true, noiseSuppression: true, autoGainControl: true }` | Audio track constraints passed to `getUserMedia`. |
200
- | `autoUnlock` | `boolean` | `true` | Attach global `{ capture: true }` gesture & `visibilitychange` listeners to unlock blocked playback. |
201
- | `speakingDetection` | `boolean` | `true` | Enable shared lazy `AudioContext` + `AnalyserNode` speaking detection. |
202
- | `speakingThreshold` | `number` | `0.03` | RMS amplitude threshold (`0` to `1`) for `selfSpeaking` and `speakingPeers`. |
203
- | `speakingIntervalMs` | `number` | `180` | Polling interval in milliseconds (`50` to `60_000`) for speaking detection. |
204
- | `to` | `string` | `undefined` | Scope outgoing microphone audio to a single target peer ID (incoming audio from all peers plays). |
232
+ | `VoiceOptions` field | Type | Default | Purpose |
233
+ | -------------------- | ------------------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
234
+ | `volume` | `number` | `1` | Initial playback volume (`0` to `1`) for incoming peer audio. |
235
+ | `deafened` | `boolean` | `false` | Start with incoming peer audio muted locally (`audio.muted = true`). |
236
+ | `audioConstraints` | `MediaTrackConstraints \| true` | `{ echoCancellation: true, noiseSuppression: true, autoGainControl: true }` | Audio track constraints passed to `getUserMedia`. |
237
+ | `autoUnlock` | `boolean` | `true` | Attach global `{ capture: true }` gesture & `visibilitychange` listeners to unlock blocked playback. |
238
+ | `speakingDetection` | `boolean` | `true` | Enable shared lazy `AudioContext` + `AnalyserNode` speaking detection. |
239
+ | `speakingThreshold` | `number` | `0.03` | RMS amplitude threshold (`0` to `1`) for `selfSpeaking` and `speakingPeers`. |
240
+ | `speakingIntervalMs` | `number` | `180` | Polling interval in milliseconds (`50` to `60_000`) for speaking detection. |
241
+ | `to` | `string` | `undefined` | Scope outgoing microphone audio to a single target peer ID (incoming audio from all peers plays). |
242
+ | `streamTag` | `string` | `'voice'` | Stream tag attached to outgoing mic streams and matched on incoming streams (`[a-zA-Z0-9._-]{1,32}`). |
243
+ | `strictStreamTag` | `boolean` | `false` | When `true`, also ignore untagged (`meta.tag === undefined`) incoming audio streams. |
205
244
 
206
245
  | `Voice` member | Description |
207
246
  | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
208
247
  | `voice.micStatus` | Current `MicStatus`: `'off' \| 'requesting' \| 'live' \| 'muted' \| 'error'`. |
209
248
  | `voice.micError` | `MicError \| null` (`{ code: MicErrorCode, message: string }`; codes: `'permission-denied' \| 'not-found' \| 'in-use' \| 'insecure-context' \| 'room-closed' \| 'unknown'`). |
249
+ | `voice.deviceId` | Active or selected microphone `deviceId` (`string`), or `null` for system default. |
210
250
  | `voice.autoplayBlocked` | `true` while any incoming `<audio>` element was blocked by browser Autoplay Policy and awaits a user gesture. |
211
251
  | `voice.deafened` | Whether incoming peer audio is muted locally. |
212
- | `voice.volume` | Current incoming playback volume (`0` to `1`). |
252
+ | `voice.volume` | Current master incoming playback volume (`0` to `1`). |
213
253
  | `voice.selfSpeaking` | `true` when local microphone is `'live'` and exceeds `speakingThreshold`. |
214
- | `voice.remotePeers` | Snapshot array of peer IDs currently sending audio. |
254
+ | `voice.remotePeers` | Snapshot array of peer IDs currently sending voice audio. |
215
255
  | `voice.speakingPeers` | Snapshot array of remote peer IDs currently exceeding `speakingThreshold`. |
216
- | `voice.getSnapshot()` | Returns an immutable `VoiceSnapshot` object with all 8 state fields above (`Voice extends VoiceSnapshot`). |
256
+ | `voice.mutedPeers` | Snapshot array of remote peer IDs locally muted via `voice.setPeerMuted(peerId, true)`. |
257
+ | `voice.getSnapshot()` | Returns an immutable `VoiceSnapshot` object with all 10 state fields above (`Voice extends VoiceSnapshot`). |
217
258
  | `voice.toggleMic()` | Acquires mic on first call (`'off' \| 'error'` → `'requesting'` → `'live'`), or toggles soft-mute (`'live'` ↔ `'muted'`). Coalesces concurrent `'requesting'` calls. |
218
259
  | `voice.startMic()` | Acquires mic if inactive, or unmutes if `'muted'`. Coalesces concurrent `'requesting'` calls; resolves to `'off'` if closed. |
219
260
  | `voice.setMuted(muted)` | Soft-mutes (`true`) or unmutes (`false`) an already-acquired mic (`'live' \| 'muted'`). No-op otherwise. |
220
261
  | `voice.stopMic()` | Detaches stream from room (`removeStream`), cancels any pending `getUserMedia`, and stops hardware tracks (`track.stop()`). |
221
- | `voice.setVolume(volume)` | Sets incoming playback volume (`0` to `1`, clamped; throws `RangeError` if non-finite). |
262
+ | `voice.switchDevice(deviceId?)` | Selects or hot-swaps microphone device (`string \| null \| undefined`) via `room.replaceStreamTrack()` with zero WebRTC SDP renegotiation (`Promise<MicStatus>`). |
263
+ | `voice.setVolume(volume)` | Sets master incoming playback volume (`0` to `1`, clamped; throws `RangeError` if non-finite). |
264
+ | `voice.setPeerVolume(peerId, volume)` | Sets local playback volume (`0` to `1`, clamped, scaled by master `voice.volume`) for one peer. |
265
+ | `voice.getPeerVolume(peerId)` | Returns configured local playback volume (`0` to `1`, default `1`) for `peerId`. |
222
266
  | `voice.setDeafened(deafened)` | Mutes (`true`) or unmutes (`false`) incoming remote `<audio>` elements locally (unmuting also calls `unlockAudio()`). |
267
+ | `voice.setPeerMuted(peerId, muted)` | Locally mutes (`true`) or unmutes (`false`) incoming audio from one peer (independent of `deafened`). |
268
+ | `voice.isPeerMuted(peerId)` | Returns whether `peerId` is locally muted via `setPeerMuted()`. |
223
269
  | `voice.unlockAudio()` | Synchronously retries `AudioContext.resume()` and `audio.play()` on paused remote streams (e.g. from a custom unlock banner click). |
224
270
  | `voice.onChange(fn, options?: ListenOptions)` | Subscribes to `VoiceSnapshot` changes (`(snapshot: VoiceSnapshot) => ...`). Returns unsubscribe. |
225
271
  | `voice.close()` | Releases mic tracks, removes hidden `<audio>` elements, closes `AudioContext`, restores `audioSession`, and detaches all listeners (runs automatically on `room.leave()`). |
@@ -238,7 +284,7 @@ if (voice.micStatus === 'off' || voice.micStatus === 'error') {
238
284
  await voice.toggleMic() // 1st call: getUserMedia + addStream ('live'); next calls: soft-mute ('muted' <-> 'live')
239
285
 
240
286
  voice.onChange((snap) => {
241
- // snap: { micStatus, micError, autoplayBlocked, deafened, volume, selfSpeaking, remotePeers, speakingPeers }
287
+ // snap: { micStatus, micError, deviceId, autoplayBlocked, deafened, volume, selfSpeaking, remotePeers, speakingPeers, mutedPeers }
242
288
  if (snap.autoplayBlocked) showUnlockBanner()
243
289
  })
244
290
 
@@ -252,22 +298,28 @@ voice.stopMic() // Release microphone hardware while staying in the room (voice.
252
298
  For custom video, screen sharing, or bespoke audio pipelines, use the low-level `Room` methods directly:
253
299
 
254
300
  ```ts
255
- const mic = await navigator.mediaDevices.getUserMedia({ audio: true })
256
- room.addStream(mic) // Broadcast to all current & future peers (or pass peerId as 2nd arg)
301
+ const screen = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: true })
302
+ room.addStream(screen, { tag: 'screen' }) // Tagged so createVoice() will not hijack screen audio!
257
303
 
258
- room.onPeerStream((peerId, stream) => {
259
- const audio = new Audio()
260
- audio.srcObject = stream
261
- audio.play()
304
+ room.onPeerStream((peerId, stream, meta) => {
305
+ if (meta.tag === 'screen') {
306
+ videoEl.srcObject = stream
307
+ }
262
308
  })
263
- room.onPeerStreamEnd((peerId, stream) => console.log('Stream ended:', peerId, stream.id))
309
+ room.onPeerStreamEnd((peerId, stream, meta) =>
310
+ console.log('Stream ended:', peerId, stream.id, meta.tag)
311
+ )
312
+
313
+ // Hot-swap a track (e.g. camera/mic switch) with zero WebRTC SDP renegotiation:
314
+ await room.replaceStreamTrack(screen, oldVideoTrack, newVideoTrack)
315
+ oldVideoTrack.stop()
264
316
 
265
- // Later: detach from room and stop local microphone tracks yourself.
266
- room.removeStream(mic)
267
- for (const track of mic.getTracks()) track.stop()
317
+ // Later: detach from room and stop local tracks yourself.
318
+ room.removeStream(screen)
319
+ for (const track of screen.getTracks()) track.stop()
268
320
  ```
269
321
 
270
- > **Note:** `removeStream()` does not stop local `MediaStreamTrack`s (call `track.stop()` when done, or use `createVoice()`), and streams with 0 tracks or tracks added to a `MediaStream` _after_ `addStream()` are not renegotiated automatically.
322
+ > **Note:** `removeStream()` and `replaceStreamTrack()` do not stop local `MediaStreamTrack`s (call `track.stop()` when done, or use `createVoice()`), and streams with 0 tracks or tracks added manually to a `MediaStream` _without_ `replaceStreamTrack()` are not renegotiated automatically.
271
323
 
272
324
  ### `SendResult`
273
325
 
@@ -295,12 +347,80 @@ for (const track of mic.getTracks()) track.stop()
295
347
 
296
348
  ### `createChannel(room, name, options?: ChannelOptions)`
297
349
 
298
- Creates a named message stream (such as `'chat'` or `'cursor'`) on your existing room connections. Each channel only receives packets sent to its own name.
350
+ Creates a named message stream (such as `'chat'` or `'cursor'`) on your existing room connections, dispatched in `O(1)` time through a single shared per-`Room` router. Each channel only receives packets sent to its own name and delivery mode.
299
351
 
300
352
  - `name`: 1–64 UTF-8 bytes. Uses `1 + nameBytes.length` bytes of the 16,384-byte packet limit.
301
353
  - `options` (`ChannelOptions`): `{ delivery?: Delivery }`. Defaults to `'unreliable'`.
302
354
  - Returns a `Channel` with `{ name, delivery, send(bytes, options?: ChannelSendOptions), onPacket((from, bytes) => ..., options?: ListenOptions) }` (`ChannelSendOptions` is `{ to?: string }`).
303
355
 
356
+ ### `createCodecChannel(room, name, codec, options?: ChannelOptions)`
357
+
358
+ Creates a typed logical channel using a synchronous `Codec<T>` (`{ encode(value: T): Uint8Array, decode(bytes: Uint8Array): T }`), **preserving synchronous `ReadonlyMap<string, SendResult>` backpressure** on `send()` while automatically ignoring malformed incoming frames (without consuming `{ once: true }` subscriptions).
359
+
360
+ - Built-in codecs:
361
+ - `jsonCodec<T>(validate?)` — UTF-8 JSON serializer/deserializer. Pass a TypeScript type guard (`(v): v is ChatMsg => ...`) to validate untrusted peer input and infer `Codec<ChatMsg>` automatically.
362
+ - `textCodec` — Strict UTF-8 string codec (`Codec<string>`).
363
+ - `binaryCodec` — Zero-copy `Uint8Array` identity codec (`Codec<Uint8Array>`).
364
+ - Returns a `CodecChannel<T>` with `{ name, delivery, send(value, options?: ChannelSendOptions), onMessage((from, value) => ..., options?: ListenOptions) }`.
365
+
366
+ ```ts
367
+ import { createCodecChannel, jsonCodec } from '@dimchansky/meshpost'
368
+
369
+ interface ChatMsg {
370
+ text: string
371
+ }
372
+
373
+ const isChatMsg = (v: unknown): v is ChatMsg =>
374
+ Boolean(v) && typeof v === 'object' && typeof (v as ChatMsg).text === 'string'
375
+
376
+ const chat = createCodecChannel(room, 'chat', jsonCodec(isChatMsg), { delivery: 'reliable' })
377
+ chat.onMessage((from, msg) => console.log(from, msg.text))
378
+ chat.send({ text: 'hello!' })
379
+ ```
380
+
381
+ ### `createRpc<Req, Res>(room, name, options?: RpcOptions<Req, Res>)`
382
+
383
+ Creates a lightweight reliable request-response RPC endpoint over `createChannel(room, name, { delivery: 'reliable' })` with automatic correlation IDs, `timeoutMs`, `AbortSignal`, `onPeerLeave` disconnect rejection, anti-spoofing peer verification, and immediate structured `RpcError` codes (`'timeout' | 'aborted' | 'disconnected' | 'unavailable' | 'busy' | 'too-large' | 'unhandled' | 'remote-error' | 'closed'`).
384
+
385
+ - `options` (`RpcOptions<Req, Res>`): `{ timeoutMs?, requestCodec?, responseCodec?, maxPendingCalls?, maxConcurrentPerPeer? }` (defaults: `10_000` ms timeout, `jsonCodec()`, `256` max pending calls, `16` max concurrent incoming requests per peer).
386
+ - Returns an `RpcEndpoint<Req, Res>` with `{ name, call(peerId, request, options?: RpcCallOptions), handle((from, request) => response | Promise<response>, options?: ListenOptions), close() }` (`RpcCallOptions` is `{ timeoutMs?: number, signal?: AbortSignal }`; exported error types: `RpcError`, `RpcErrorCode`).
387
+
388
+ ```ts
389
+ import { createRpc } from '@dimchansky/meshpost'
390
+
391
+ const ping = createRpc<{ sentAt: number }, { serverNow: number }>(room, 'ping', {
392
+ timeoutMs: 5_000
393
+ })
394
+
395
+ ping.handle(() => ({ serverNow: Date.now() }))
396
+
397
+ const { serverNow } = await ping.call(peerId, { sentAt: Date.now() })
398
+ ```
399
+
400
+ ### `createPeerState<T>(room, name, options?: PeerStateOptions<T>)`
401
+
402
+ Creates a single-writer per-peer state synchronization store (zero CRDT bloat): each peer owns its own slot (`set(value)` / `clear()`), while remote peers' latest states are automatically ordered via RFC 1982 `u32` sequence numbers, **hydrated reliably on `onPeerJoin`** (even when live updates use `delivery: 'unreliable'`), cleaned up on `onPeerLeave`, and coalesced in `O(1)` memory on `room.onDrain` when send buffers are `'busy'`.
403
+
404
+ - `options` (`PeerStateOptions<T>`): `{ delivery?: Delivery, codec?: Codec<T>, initial?: T, coalesce?: boolean }` (defaults: `delivery: 'reliable'`, `codec: jsonCodec()`, `coalesce: true`).
405
+ - Returns a `PeerState<T>` with `{ name, delivery, getSelf(), get(peerId), getAll(), set(value), clear(), onChange((peerId, next, prev) => ..., options?: ListenOptions), close() }`.
406
+
407
+ ```ts
408
+ import { createPeerState } from '@dimchansky/meshpost'
409
+
410
+ const cursors = createPeerState<{ x: number; y: number }>(room, 'cursor', {
411
+ delivery: 'unreliable',
412
+ coalesce: true
413
+ })
414
+
415
+ cursors.onChange((peerId, pos) => {
416
+ if (!pos)
417
+ removeCursor(peerId) // Peer left or called clear()
418
+ else renderCursor(peerId, pos.x, pos.y)
419
+ })
420
+
421
+ cursors.set({ x: 0.5, y: 0.25 })
422
+ ```
423
+
304
424
  ### `createBlobChannel(room, name, options?: BlobChannelOptions)`
305
425
 
306
426
  Creates an opt-in chunked reliable transfer helper for payloads larger than Meshpost's `16,384`-byte packet limit (such as files, images, or large state snapshots). Built strictly on top of `createChannel(room, name, { delivery: 'reliable' })` and `room.onDrain`.
@@ -325,14 +445,17 @@ const results = await files.send(fileBytes, {
325
445
 
326
446
  ### Signaling exports
327
447
 
328
- - `mqttSignaling({ urls?, appId?, password?, handshakeTimeoutMs? })` — Connects browsers across different devices and networks using built-in public MQTT relay servers (`defaultMqttRelays`).
329
- - `wsSignaling(url, { reconnect?, handshakeTimeoutMs?, pingIntervalMs? })` — Connects browsers through your own WebSocket (`ws://` / `wss://`) signaling server (defaults: `reconnect: true`, `handshakeTimeoutMs: 10_000`, `pingIntervalMs: 25_000`). See [docs/behavior.md](docs/behavior.md) and [examples/serve.mjs](examples/serve.mjs) for the minimal JSON server protocol.
448
+ - `publicSignaling({ wsUrls?, mqtt?, nostr?, localTabs?, wsEncrypt?, privateTopic?, appId?, wsHandshakeTimeoutMs?, handshakeTimeoutMs?, WebSocket? })` — Ready-made URL-agnostic composite adapter combining `mqttSignaling()` + port-443 `nostrSignaling()`, wrapped in `withLocalTabs(...)` (defaults: `mqtt: true`, `nostr: true`, `localTabs: true`, `wsEncrypt: true`, `privateTopic: false`, `wsHandshakeTimeoutMs: 4_000`, `handshakeTimeoutMs: 10_000`), plus zero or more app-supplied opportunistic WebSocket relays (`wsUrls?: string | readonly string[]`, max `8` unique URLs). Any unreachable or `403`-rejected `wsUrls` entry closes silently without reconnect storms while public relays carry the room.
449
+ - `mqttSignaling({ urls?, appId?, password?, privateTopic?, handshakeTimeoutMs?, WebSocket? })` — Connects browsers across different devices and networks using built-in public MQTT relay servers (`defaultMqttRelays`), with optional `AES-256-GCM` E2E encryption, `privateTopic` topic hiding, and optional custom `WebSocket` constructor injection.
450
+ - `nostrSignaling({ urls?, appId?, password?, privateTopic?, handshakeTimeoutMs?, WebSocket? })` — Zero-server signaling over public **port-443** NIP-01 Nostr relays (`defaultNostrRelays`) using ephemeral `kind: 25050` events (never persisted by relays), pure-TS BIP-340 Schnorr signatures (0 dependencies, tree-shakeable), optional `AES-256-GCM` E2E encryption + `privateTopic` tag hiding, and optional custom `WebSocket` constructor injection.
451
+ - `wsSignaling(url, { reconnect?, handshakeTimeoutMs?, pingIntervalMs?, encrypt?, privateTopic?, WebSocket? })` — Connects browsers through your own WebSocket (`ws://` / `wss://`) signaling server (defaults: `reconnect: true`, `handshakeTimeoutMs: 10_000`, `pingIntervalMs: 25_000`, `encrypt: true`, `privateTopic: false`). Automatically appends `?room=<roomKey>` for stateless per-room sharding and E2E-encrypts signaling (`box` envelopes) when `password` is set. See [examples/ws-worker/](examples/ws-worker/README.md) for a ready-to-deploy Cloudflare Worker + Durable Object (WebSocket Hibernation) relay, or [examples/serve.mjs](examples/serve.mjs) for Node.js.
452
+ - `optionalWsSignaling(url, { handshakeTimeoutMs?, pingIntervalMs?, encrypt?, privateTopic?, WebSocket? })` — Opportunistic `wsSignaling` wrapper (`reconnect: false`, `4,000` ms default handshake timeout) that transitions cleanly to `'closed'` and suppresses `'signaling-error'` if unreachable while preserving `'decrypt-failed'` and `'clock-skew'` diagnostics.
330
453
  - `withLocalTabs(primary)` — Decorates a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant same-browser `BroadcastChannel` discovery (`tabSignaling()`) while **preserving `primary`'s `SignalingState`** for `room.signalingState` / `room.onSignalingChange` (avoiding a stuck `'online'` state when internet connectivity drops, while still connecting local tabs offline). Safely falls back to `primary` on `file:` / opaque origins or when `BroadcastChannel` is unavailable.
331
454
  - `combineSignaling(...adapters)` — Combines multiple `Signaling` adapters, merging peer rosters and keeping discovery online as long as any child adapter is online (e.g. `combineSignaling(wsSignaling('wss://primary.example/ws'), mqttSignaling())`).
332
455
  - `tabSignaling()` — Connects tabs open to the same site (same protocol, domain, and port) in the same browser. Works offline with no server.
333
456
  - `manualSignaling(outgoing)` — Connects completely offline browsers by copying and pasting text. Returns `{ signaling, contact(), accept(text), forget(peerId) }`.
334
457
  - `defaultIceServers` — Built-in Cloudflare and Google public servers (STUN) that help browsers find their public network address.
335
- - Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `RoomError`, `RoomErrorCode`, `ListenOptions`, `ManualSignaling`, `MqttSignalingOptions`, `WsSignalingOptions`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
458
+ - Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `RoomError`, `RoomErrorCode`, `ListenOptions`, `ManualSignaling`, `PublicSignalingOptions`, `MqttSignalingOptions`, `NostrSignalingOptions`, `WsSignalingOptions`, `OptionalWsSignalingOptions`, `RTCPeerConnectionConstructor`, `WebSocketConstructor`, `defaultMqttRelays`, `defaultNostrRelays`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
336
459
 
337
460
  ## Connecting through strict firewalls (TURN)
338
461
 
@@ -354,6 +477,46 @@ const room = joinRoom('lobby', {
354
477
  })
355
478
  ```
356
479
 
480
+ ### Subpath exports & bundler-free `<script type="importmap">`
481
+
482
+ Every feature module is available as a dedicated subpath export (`@dimchansky/meshpost/room`, `/channel`, `/rpc`, `/state`, `/blob`, `/voice`, `/turn`, `/identity`, `/public`, `/mqtt`, `/nostr`, `/ws`, `/tabs`, `/manual`, `/combine`, `/signaling`) so bundler-free `<script type="importmap">` apps only download the modules they actually import:
483
+
484
+ ```html
485
+ <script type="importmap">
486
+ {
487
+ "imports": {
488
+ "@dimchansky/meshpost/room": "https://cdn.jsdelivr.net/npm/@dimchansky/meshpost/dist/room.js",
489
+ "@dimchansky/meshpost/nostr": "https://cdn.jsdelivr.net/npm/@dimchansky/meshpost/dist/nostr.js",
490
+ "@dimchansky/meshpost/channel": "https://cdn.jsdelivr.net/npm/@dimchansky/meshpost/dist/channel.js"
491
+ }
492
+ }
493
+ </script>
494
+ <script type="module">
495
+ import { joinRoom } from '@dimchansky/meshpost/room'
496
+ import { nostrSignaling } from '@dimchansky/meshpost/nostr'
497
+ import { createCodecChannel, textCodec } from '@dimchansky/meshpost/channel'
498
+
499
+ const room = joinRoom('lobby', { password: 'secret', signaling: nostrSignaling() })
500
+ const chat = createCodecChannel(room, 'chat', textCodec, { delivery: 'reliable' })
501
+ </script>
502
+ ```
503
+
504
+ ### Headless peers (Node.js 22+, Bun, Deno)
505
+
506
+ Inject a userland `RTCPeerConnection` implementation (such as `werift` or `@roamhq/wrtc`) — and optionally a custom `WebSocket` constructor — without mutating `globalThis`:
507
+
508
+ ```ts
509
+ import { RTCPeerConnection } from 'werift'
510
+ import { joinRoom } from '@dimchansky/meshpost/room'
511
+ import { wsSignaling } from '@dimchansky/meshpost/ws'
512
+
513
+ const botRoom = joinRoom('game-1', {
514
+ password: 'secret',
515
+ RTCPeerConnection,
516
+ signaling: wsSignaling('wss://relay.example/ws') // Node 22+, Bun, & Deno provide global WebSocket (or pass { WebSocket })
517
+ })
518
+ ```
519
+
357
520
  ## Try the interactive playground
358
521
 
359
522
  ### Option 1: Local dev server (recommended)
@@ -378,7 +541,7 @@ npm run demo
378
541
 
379
542
  Open **dist/playground.html** directly in two browsers (`file://`). Enter the same room name and click **Join room**.
380
543
 
381
- - By default, `dist/playground.html` uses `mqttSignaling()` when opened via `file://` and `withLocalTabs(mqttSignaling())` when hosted on a public `https://` origin (such as GitHub Pages).
544
+ - By default, `dist/playground.html` combines `mqttSignaling()` and port-443 `nostrSignaling()` when opened via `file://` or hosted on a public `https://` origin (wrapped in `withLocalTabs(...)` on HTTP/HTTPS).
382
545
  - For completely offline copy-paste exchange with zero network requests, open `dist/playground.html#mode=manual` (or click **Offline mode** on the join screen).
383
546
  - When hosted on `localhost` or a LAN host without the demo's local `/ws` relay server, it automatically falls back to `tabSignaling()` (same-browser tabs only).
384
547
 
@@ -386,27 +549,29 @@ Open **dist/playground.html** directly in two browsers (`file://`). Enter the sa
386
549
 
387
550
  All `@dimchansky/meshpost` usage in the playground is intentionally concentrated in **one file** so you can learn the full API in one place:
388
551
 
389
- - [examples/playground/mesh.js](examples/playground/mesh.js) — **Start here.** Single facade wiring `joinRoom()`, signaling adapters (`withLocalTabs`, `mqttSignaling`, `wsSignaling`, `manualSignaling`), `fetchTurnCredentials()`, `createChannel()` (`pointer`, `draw`, `chat`, `direct`, `profile`), `createBlobChannel()` (`draw-snap`, `file`), `createVoice()`, `ListenOptions` (`{ signal }`), `room.onError()`, and `room.getStats()`.
552
+ - [examples/playground/mesh.js](examples/playground/mesh.js) — **Start here.** Single facade using `@dimchansky/meshpost/*` subpath imports to wire `joinRoom()`, `createIdentity()` / `exportIdentity()` / `importIdentity()` / `isSerializedIdentity()`, signaling adapters (`withLocalTabs`, `combineSignaling`, `mqttSignaling`, `nostrSignaling`, `wsSignaling`, `manualSignaling`), `fetchTurnCredentials()`, `createPeerState()` (`presence`, `cursor`), `createChannel()` (`ripple`, `draw`), `createCodecChannel()` + `jsonCodec()` (`chat`, `direct`), `createRpc()` (`ping`), `createBlobChannel()` (`draw-snap`, `file`), `createVoice()`, `ListenOptions` (`{ signal }`), `room.onError()`, and `room.getStats()`.
390
553
  - [examples/playground/relay.js](examples/playground/relay.js) — `autoSignaling()` composing `tabSignaling()` and `wsSignaling()` with a silent fallback to `tabSignaling()` on plain static localhost servers.
391
- - [examples/playground/codec.js](examples/playground/codec.js) — Pure binary codecs for pointer updates, canvas strokes, and file metadata envelopes.
554
+ - [examples/playground/codec.js](examples/playground/codec.js) — Pure binary codecs (`cursorCodec`, canvas strokes, file metadata envelopes) and payload type guards.
392
555
  - [examples/playground/canvas.js](examples/playground/canvas.js) — Collaborative 2D drawing canvas and remote cursor/ripple overlays.
393
- - [examples/playground/voice.js](examples/playground/voice.js) — Thin DOM binding connecting microphone buttons, autoplay banner, and `KeyM` to `createVoice()`.
556
+ - [examples/playground/voice.js](examples/playground/voice.js) — Thin DOM binding connecting microphone buttons, zero-renegotiation mic switcher (`switchDevice`), per-peer volume/mute controls, autoplay banner, and `KeyM` to `createVoice()`.
394
557
  - [examples/playground/session.js](examples/playground/session.js) — Compact `#c=` invite URLs and `sessionStorage` auto-rejoin.
395
558
  - [examples/playground/app.js](examples/playground/app.js) — Thin UI controller connecting DOM controls to `mesh.js` and the helper modules.
396
559
  - [examples/playground/index.html](examples/playground/index.html) — Minimal HTML markup for the playground.
560
+ - [examples/ws-worker/](examples/ws-worker/README.md) — Ready-to-deploy Cloudflare Worker + Durable Object (WebSocket Hibernation) signaling server for `wsSignaling()` with per-room sharding and zero-wake keepalives.
397
561
  - [examples/turn-worker/](examples/turn-worker/README.md) — Ready-to-deploy Cloudflare Worker template that issues short-lived TURN credentials (supporting Metered Open Relay, Cloudflare Realtime TURN, and self-hosted `coturn`) behind an `Origin` allowlist and shared access key.
398
562
 
399
563
  ## Project layout and tests
400
564
 
401
- | Path | Purpose |
402
- | ----------------------- | ------------------------------------------------------------------------------ |
403
- | `src/` | Core room lifecycle, channels, and signaling adapters |
404
- | `examples/playground/` | Interactive demo source |
405
- | `examples/turn-worker/` | Optional Cloudflare Worker credential broker for Metered, CF TURN, or `coturn` |
406
- | `examples/build.mjs` | Bundles the playground into one portable HTML file |
407
- | `examples/serve.mjs` | Local dev server with WebSocket (`/ws`) and SSE signaling relays |
408
- | `tests/` | Playwright E2E tests using real browser WebRTC data channels |
409
- | `dist/` | Built ES modules, `.d.ts` declarations, and `playground.html` |
565
+ | Path | Purpose |
566
+ | ----------------------- | --------------------------------------------------------------------------------- |
567
+ | `src/` | Core room lifecycle, channels, state, RPC, voice, and signaling adapters |
568
+ | `examples/playground/` | Interactive demo source |
569
+ | `examples/ws-worker/` | Optional Cloudflare Worker + Durable Object (Hibernation) relay for `wsSignaling` |
570
+ | `examples/turn-worker/` | Optional Cloudflare Worker credential broker for Metered, CF TURN, or `coturn` |
571
+ | `examples/build.mjs` | Bundles the playground into one portable HTML file |
572
+ | `examples/serve.mjs` | Local dev server with WebSocket (`/ws`) and SSE signaling relays |
573
+ | `tests/` | Playwright E2E tests using real browser WebRTC data channels |
574
+ | `dist/` | Built ES modules, `.d.ts` declarations, and `playground.html` |
410
575
 
411
576
  Run the test suite:
412
577
 
@@ -420,10 +585,10 @@ To use an already-installed Google Chrome instead of downloading Chromium, run `
420
585
 
421
586
  For full limits, wire protocol details, edge cases, and the security model, read [docs/behavior.md](docs/behavior.md).
422
587
 
423
- ## Browser support
588
+ ## Runtime support
424
589
 
425
- - Runs in modern browsers (Chrome, Firefox, Safari) with WebRTC `RTCDataChannel`, `WebSocket`, and `BroadcastChannel`. Meshpost is a browser library (not for Node.js).
426
- - `mqttSignaling()` with `password` uses browser Web Crypto (`crypto.subtle`), which requires `https://` or `http://localhost` (`127.0.0.1`).
590
+ - Runs in modern browsers (Chrome, Firefox, Safari) with WebRTC `RTCDataChannel`, `WebSocket`, and `BroadcastChannel`, as well as headless runtimes (Node.js 22+, Bun, Deno) when passing `RTCPeerConnection` (and optional `WebSocket`) constructors.
591
+ - `mqttSignaling()`, `nostrSignaling()`, and `wsSignaling()` (unless `encrypt: false`) with `password` — as well as `createIdentity()` — use Web Crypto (`crypto.subtle`), which in browsers requires `https://` or `http://localhost` (`127.0.0.1`).
427
592
 
428
593
  ## License
429
594