@dimchansky/meshpost 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +66 -544
  2. package/dist/bip340.d.ts +1 -0
  3. package/dist/bip340.js +346 -0
  4. package/dist/blob.d.ts +1 -1
  5. package/dist/blob.js +15 -16
  6. package/dist/channel.js +15 -44
  7. package/dist/combine.js +5 -24
  8. package/dist/crypto.js +10 -9
  9. package/dist/identity.d.ts +2 -0
  10. package/dist/identity.js +39 -71
  11. package/dist/index.d.ts +2 -2
  12. package/dist/index.js +1 -1
  13. package/dist/listeners.js +18 -3
  14. package/dist/mqtt.js +193 -408
  15. package/dist/nostr.js +163 -745
  16. package/dist/public.d.ts +1 -1
  17. package/dist/public.js +9 -54
  18. package/dist/relay-core.d.ts +1 -0
  19. package/dist/relay-core.js +323 -0
  20. package/dist/room-hello.d.ts +1 -0
  21. package/dist/room-hello.js +129 -0
  22. package/dist/room-ice.d.ts +1 -0
  23. package/dist/room-ice.js +115 -0
  24. package/dist/room-media.d.ts +1 -0
  25. package/dist/room-media.js +477 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +111 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +109 -919
  31. package/dist/signaling.d.ts +8 -0
  32. package/dist/signaling.js +64 -0
  33. package/dist/state.js +1 -2
  34. package/dist/voice-helpers.d.ts +1 -0
  35. package/dist/voice-helpers.js +100 -0
  36. package/dist/voice-meter.d.ts +1 -0
  37. package/dist/voice-meter.js +79 -0
  38. package/dist/voice.d.ts +11 -1
  39. package/dist/voice.js +99 -295
  40. package/dist/ws.js +39 -142
  41. package/docs/api.md +217 -0
  42. package/docs/behavior.md +10 -4
  43. package/docs/guide.md +404 -0
  44. package/docs/signaling-and-production.md +312 -0
  45. package/docs/voice-and-media.md +193 -0
  46. package/package.json +3 -2
@@ -0,0 +1,312 @@
1
+ # Signaling & Production
2
+
3
+ Meshpost separates **signaling** (peer discovery + WebRTC SDP/ICE exchange) from **data transport** (direct P2P DTLS-encrypted WebRTC). Once peers connect, signaling can go offline without dropping active links.
4
+
5
+ ---
6
+
7
+ ## 1. Choosing a signaling adapter
8
+
9
+ | Scenario | Recommended adapter | Why |
10
+ | ----------------------------------------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------- |
11
+ | Zero-backend internet app (default) | `publicSignaling()` | Combines public MQTT + port-443 Nostr + `withLocalTabs` out of the box |
12
+ | Production app with fast edge relay + public fallback | `publicSignaling({ wsUrls: 'wss://...' })` | Instant roster via your WS relay; silently falls back to MQTT/Nostr if WS is blocked or down |
13
+ | Dedicated private WS backend only | `withLocalTabs(wsSignaling('wss://...'))` | Lowest latency, full Trickle ICE, zero public relay traffic |
14
+ | Firewall-friendly zero-backend (port 443 only) | `withLocalTabs(nostrSignaling())` | Runs strictly over `wss://` port 443 ephemeral events (`kind: 25050`) |
15
+ | Same-browser multi-tab only (zero network) | `tabSignaling()` | Instant `BroadcastChannel` discovery, zero network requests |
16
+ | Completely offline / air-gapped | `manualSignaling(onOutgoing)` | Copy-paste JSON contact cards & replies over any chat/QR channel |
17
+
18
+ ---
19
+
20
+ ## 2. `publicSignaling()` — out-of-the-box composite pool
21
+
22
+ `publicSignaling()` runs zero or more opportunistic WebSocket relays (`wsUrls`), public MQTT brokers (`mqtt`), and port-443 Nostr relays (`nostr`) in parallel inside a single redundant pool, wrapped in `withLocalTabs()` by default (`localTabs: true`).
23
+
24
+ ```ts
25
+ import { joinRoom } from '@dimchansky/meshpost/room'
26
+ import { publicSignaling } from '@dimchansky/meshpost/public'
27
+
28
+ const room = joinRoom('match-42', {
29
+ password: 'shared-secret-passphrase',
30
+ signaling: publicSignaling({
31
+ // Optional: 1..8 fast-path WS relays; rejected/unreachable URLs close silently with zero reconnect storm
32
+ wsUrls: ['wss://meshpost-ws-relay.example.workers.dev/ws'],
33
+ // Hide room topic/tag correlation on shared relays (requires room password)
34
+ privateTopic: true,
35
+ // Observe individual transport health ('ws' | 'mqtt' | 'nostr' | 'tabs')
36
+ onTransportChange(event) {
37
+ // event: { transport, url?, state, reason? }
38
+ console.log(event.transport, event.state, event.reason ?? '')
39
+ }
40
+ })
41
+ })
42
+ ```
43
+
44
+ ### Understanding `onTransportChange` and `reason`
45
+
46
+ - `publicSignaling()` suppresses per-transport `'signaling-error'` as long as any sibling transport is `'online'` or `'connecting'` (for example, corporate Wi-Fi blocking MQTT ports while port-443 Nostr or `wsUrls` connects).
47
+ - Per the **WHATWG WebSocket specification**, browsers intentionally hide HTTP upgrade status codes (such as `403` origin rejections) and TLS handshake details behind opaque close code `1006`. Client-side handshake timeouts (`'WebSocket signaling handshake timed out'`) and non-`1006` numeric close codes (such as `1013` try-again-later) are surfaced in `event.reason`.
48
+
49
+ ---
50
+
51
+ ## 3. Observing & composing adapters
52
+
53
+ ### `observeSignaling(adapter, onChange)`
54
+
55
+ Wrap any `Signaling` adapter (including custom adapters, `wsSignaling()`, or `tabSignaling()`) to observe its per-session `SignalingState` (`'connecting' | 'online' | 'offline' | 'closed'`) without changing `Room` behavior:
56
+
57
+ ```ts
58
+ import { observeSignaling } from '@dimchansky/meshpost/signaling'
59
+ import { optionalWsSignaling } from '@dimchansky/meshpost/ws'
60
+ import { combineSignaling, withLocalTabs } from '@dimchansky/meshpost/combine'
61
+ import { nostrSignaling } from '@dimchansky/meshpost/nostr'
62
+
63
+ const observedWs = observeSignaling(
64
+ optionalWsSignaling('wss://relay.example/ws'),
65
+ (state, reason) => {
66
+ console.log('Custom WS:', state, reason ?? '')
67
+ }
68
+ )
69
+
70
+ const observedNostr = observeSignaling(nostrSignaling(), (state) => {
71
+ console.log('Nostr:', state)
72
+ })
73
+
74
+ const signaling = withLocalTabs(combineSignaling(observedWs, observedNostr))
75
+ ```
76
+
77
+ - `observeSignaling()` deduplicates consecutive identical states, isolates callback errors via `reportError`, and preserves `trickle` and `canReach` on the underlying `SignalingSession`.
78
+ - `withLocalTabs(primary)` keeps `room.signalingState` tied to `primary` (so losing Wi-Fi still reports `'offline'`), while `canReach(peerId)` still lets same-browser tabs connect immediately.
79
+ - `combineSignaling(...adapters)` merges rosters, routes signals to every reachable child advertising a peer, deduplicates Trickle ICE candidates across children, and throttles cross-transport `'decrypt-failed'` / `'clock-skew'` errors.
80
+
81
+ ### Password encryption & `privateTopic`
82
+
83
+ When `joinRoom(name, { password })` is set:
84
+
85
+ - `mqttSignaling()`, `nostrSignaling()`, and `wsSignaling()` (unless `encrypt: false` for plain HTTP LAN testing) derive keys via `PBKDF2-HMAC-SHA256` (`100,000` iterations) + `HKDF-SHA256` and end-to-end encrypt every signaling envelope with `AES-256-GCM`, bound with transport/room/recipient AAD and `±60 s` replay protection.
86
+ - By default (`privateTopic: false`), a peer entering the wrong password still lands on the same hashed room topic and receives an immediate `'decrypt-failed'` event via `room.onError()`.
87
+ - With `privateTopic: true`, the MQTT topic, Nostr `#t` tag, and WS room key are derived cryptographically from `password`, hiding room activity on shared relays (wrong passwords silently land in an empty room instead of emitting `'decrypt-failed'`).
88
+
89
+ ---
90
+
91
+ ## 4. Offline manual exchange (`manualSignaling`)
92
+
93
+ For zero-network environments, `manualSignaling(onOutgoing)` produces JSON envelopes that two users exchange over any trusted text/QR channel:
94
+
95
+ ```ts
96
+ import { joinRoom } from '@dimchansky/meshpost/room'
97
+ import { manualSignaling } from '@dimchansky/meshpost/manual'
98
+
99
+ const manual = manualSignaling((toPeerId, replyJson) => {
100
+ console.log(`Send this reply to ${toPeerId}:`, replyJson)
101
+ })
102
+
103
+ const room = joinRoom('offline-room', {
104
+ password: 'optional-passphrase',
105
+ signaling: manual.signaling
106
+ })
107
+
108
+ // 1. Peer A copies manual.contact() and sends it to Peer B.
109
+ // 2. Peer B calls manual.accept(peerAContact), triggering onOutgoing with an offer/reply JSON.
110
+ // 3. Peer A calls manual.accept(peerBReply), completing the WebRTC handshake.
111
+ ```
112
+
113
+ ---
114
+
115
+ ## 5. NAT traversal, TURN, and edge workers
116
+
117
+ Meshpost uses Cloudflare and Google public STUN servers (`defaultIceServers`) automatically, which connect most peers directly. For symmetric NATs and strict corporate/mobile firewalls, provide short-lived TURN credentials via `fetchTurnCredentials()` and `turnConfig`:
118
+
119
+ ```ts
120
+ import { joinRoom } from '@dimchansky/meshpost/room'
121
+ import { fetchTurnCredentials } from '@dimchansky/meshpost/turn'
122
+ import { publicSignaling } from '@dimchansky/meshpost/public'
123
+
124
+ const turnConfig = await fetchTurnCredentials('https://turn.example.workers.dev', {
125
+ accessKey: 'shared-access-key',
126
+ timeoutMs: 5_000
127
+ })
128
+
129
+ const room = joinRoom('team-call', {
130
+ password: 'secret',
131
+ turnConfig, // appended to defaultIceServers (or rtcConfig.iceServers)
132
+ signaling: publicSignaling()
133
+ })
134
+ ```
135
+
136
+ Ready-to-deploy Cloudflare Worker templates included in this repo:
137
+
138
+ - [examples/ws-worker/README.md](../examples/ws-worker/README.md) — Cloudflare Worker + Durable Object (WebSocket Hibernation) signaling server for `wsSignaling()` / `publicSignaling({ wsUrls })`, with per-room sharding (`?room=<key>`), `Origin` allowlist, rate limits, and zero-wake keepalives.
139
+ - [examples/turn-worker/README.md](../examples/turn-worker/README.md) — Cloudflare Worker short-lived TURN credential broker supporting Metered Open Relay, Cloudflare Realtime TURN, and self-hosted `coturn` behind an `Origin` allowlist and Bearer `ACCESS_KEY`.
140
+
141
+ ---
142
+
143
+ ## 6. Writing a custom `Signaling` adapter
144
+
145
+ A `Signaling` adapter is a single function `(discovery: Discovery) => SignalingSession`. Below is a complete SSE + `POST /signal` adapter matching [examples/serve.mjs](../examples/serve.mjs) (`/events` and `/signal`):
146
+
147
+ ```ts
148
+ import {
149
+ isSignal,
150
+ isUuid,
151
+ withLoopbackFallback,
152
+ type Signaling
153
+ } from '@dimchansky/meshpost/signaling'
154
+
155
+ export function sseSignaling(baseUrl = ''): Signaling {
156
+ return (discovery) => {
157
+ let closed = false
158
+ const params = new URLSearchParams({ room: discovery.room, id: discovery.self })
159
+ const events = new EventSource(`${baseUrl}/events?${params}`)
160
+
161
+ discovery.status('connecting')
162
+
163
+ events.addEventListener('open', () => {
164
+ if (!closed) discovery.status('online')
165
+ })
166
+
167
+ events.addEventListener('roster', (ev) => {
168
+ if (closed) return
169
+ try {
170
+ const ids = JSON.parse((ev as MessageEvent<string>).data)
171
+ if (Array.isArray(ids)) {
172
+ discovery.roster(ids.filter((id): id is string => isUuid(id) && id !== discovery.self))
173
+ }
174
+ } catch {}
175
+ })
176
+
177
+ events.addEventListener('signal', (ev) => {
178
+ if (closed) return
179
+ try {
180
+ const msg = JSON.parse((ev as MessageEvent<string>).data)
181
+ if (msg && isUuid(msg.from) && isSignal(msg.signal)) {
182
+ discovery.receive(msg.from, withLoopbackFallback(msg.signal))
183
+ }
184
+ } catch {}
185
+ })
186
+
187
+ events.addEventListener('error', () => {
188
+ if (!closed) {
189
+ discovery.status('offline', 'SSE signaling disconnected')
190
+ discovery.error?.('signaling-error', 'SSE signaling disconnected')
191
+ }
192
+ })
193
+
194
+ return {
195
+ trickle: true,
196
+ send(to, signal) {
197
+ if (closed || events.readyState !== EventSource.OPEN) return false
198
+ void fetch(`${baseUrl}/signal`, {
199
+ method: 'POST',
200
+ headers: { 'Content-Type': 'application/json' },
201
+ body: JSON.stringify({ room: discovery.room, from: discovery.self, to, signal })
202
+ }).catch(() => {})
203
+ return true
204
+ },
205
+ close() {
206
+ if (closed) return
207
+ closed = true
208
+ events.close()
209
+ discovery.status('closed')
210
+ }
211
+ }
212
+ }
213
+ }
214
+ ```
215
+
216
+ Use `withLoopbackFallback(signal)` on incoming SDP/ICE signals when peers may be co-located on the same machine behind `.local` mDNS candidates. Never transmit the augmented signal back over the wire.
217
+
218
+ ---
219
+
220
+ ## 7. Bundler-free browsers & headless runtimes
221
+
222
+ ### Zero-build `<script type="importmap">`
223
+
224
+ Every subpath is shipped as standard ESM with `"sideEffects": false`, so browsers download only the subpaths you import:
225
+
226
+ ```html
227
+ <script type="importmap">
228
+ {
229
+ "imports": {
230
+ "@dimchansky/meshpost/room": "https://esm.sh/@dimchansky/meshpost/room",
231
+ "@dimchansky/meshpost/public": "https://esm.sh/@dimchansky/meshpost/public",
232
+ "@dimchansky/meshpost/channel": "https://esm.sh/@dimchansky/meshpost/channel"
233
+ }
234
+ }
235
+ </script>
236
+ <script type="module">
237
+ import { joinRoom } from '@dimchansky/meshpost/room'
238
+ import { publicSignaling } from '@dimchansky/meshpost/public'
239
+ import { createCodecChannel, textCodec } from '@dimchansky/meshpost/channel'
240
+
241
+ const room = joinRoom('lobby', { password: 'secret', signaling: publicSignaling() })
242
+ const chat = createCodecChannel(room, 'chat', textCodec, { delivery: 'reliable' })
243
+ </script>
244
+ ```
245
+
246
+ See the complete runnable file in [examples/minimal-chat.html](../examples/minimal-chat.html).
247
+
248
+ ### Headless Node.js 22+, Bun, and Deno
249
+
250
+ Inject a userland `RTCPeerConnection` (such as `werift` or `@roamhq/wrtc`) — and optionally a custom `WebSocket` constructor — without mutating `globalThis`:
251
+
252
+ ```ts
253
+ import { RTCPeerConnection } from 'werift'
254
+ import { joinRoom } from '@dimchansky/meshpost/room'
255
+ import { wsSignaling } from '@dimchansky/meshpost/ws'
256
+
257
+ const room = joinRoom('game-1', {
258
+ password: 'secret',
259
+ RTCPeerConnection,
260
+ signaling: wsSignaling('wss://relay.example/ws') // Node 22+, Bun & Deno include global WebSocket
261
+ })
262
+ ```
263
+
264
+ See the complete runnable bot with `createIdentity({ extractable: false })`, chat echo, and RPC `ping` in [examples/headless-bot.mjs](../examples/headless-bot.mjs).
265
+
266
+ ---
267
+
268
+ ## 8. Production recipes
269
+
270
+ ### Strict validation of user-supplied / invite WS relay URLs
271
+
272
+ If your app accepts custom relay URLs via invite links (like `#c=` in the Playground), always validate the URL before passing it to `wsSignaling()` or `publicSignaling({ wsUrls })`:
273
+
274
+ ```ts
275
+ export function validateRelayUrl(raw: string): string | null {
276
+ let parsed: URL
277
+ try {
278
+ parsed = new URL(raw.trim())
279
+ } catch {
280
+ return null
281
+ }
282
+ if (parsed.username || parsed.password || parsed.hash) return null
283
+ const isLocal =
284
+ parsed.hostname === 'localhost' ||
285
+ parsed.hostname === '127.0.0.1' ||
286
+ parsed.hostname === '[::1]'
287
+ if (parsed.protocol === 'wss:') return parsed.toString()
288
+ if (parsed.protocol === 'ws:' && isLocal) return parsed.toString()
289
+ return null
290
+ }
291
+ ```
292
+
293
+ ### Compact `#c=` invite URLs
294
+
295
+ Store room credentials in the URL **hash** (`#c=...`), never in query parameters (`?pass=...`), because URL fragments are never sent to HTTP servers or recorded in server access logs. See `encodeInvite()` / `decodeInvite()` in [examples/playground/session.js](../examples/playground/session.js) for a ready-to-copy base64url JSON helper.
296
+
297
+ ### Page reload (`F5`) & `bfcache`
298
+
299
+ - Do **not** call `room.leave()` on `pagehide` — `joinRoom()` already hooks `pagehide` to send a best-effort goodbye and persist a one-time Lamport reclaim preimage to `sessionStorage` so refreshing the tab immediately evicts the old ghost session.
300
+ - If your page supports restoring from browser `bfcache` (`window.addEventListener('pageshow', (e) => { if (e.persisted) reconnect() })`), re-create the room when `e.persisted` is `true` because WebRTC peer connections are closed when a page enters `bfcache`.
301
+
302
+ ### Reading departing peer state in `onPeerLeave`
303
+
304
+ Because `room.onPeerLeave` invokes listeners in registration order, always register your `room.onPeerLeave(...)` callback **before** calling `createPeerState(room, ...)` if you want to read `peerState.get(peerId)` for the departing peer. Alternatively, inspect `prev` inside `peerState.onChange((peerId, _next, prev, reason) => { if (reason === 'leave') ... })`.
305
+
306
+ ---
307
+
308
+ ## See also
309
+
310
+ - [Guide](./guide.md) — progressive walkthrough of rooms, channels, state, RPC, blobs, and identity
311
+ - [API Reference](./api.md) — complete signatures and option defaults across all 17 subpaths
312
+ - [Behavior & Security Spec](./behavior.md) — wire protocol, cryptographic details, limits, and edge cases
@@ -0,0 +1,193 @@
1
+ # Voice & Media
2
+
3
+ Meshpost provides a headless P2P voice chat controller (`createVoice`), tree-shakeable microphone device helpers (`listAudioInputs`, `onAudioInputsChange`), and low-level `MediaStream` primitives (`addStream`, `replaceStreamTrack`, `removeStream`) for video or screen sharing.
4
+
5
+ ---
6
+
7
+ ## 1. Quick start with `createVoice()`
8
+
9
+ `createVoice()` handles microphone capture, instant soft-mute (`track.enabled`) vs hardware release (`track.stop()`), hidden remote `<audio autoplay>` playback, speaking detection, iOS Safari `audioSession` restoration, and browser Autoplay Policy unlocking.
10
+
11
+ ```ts
12
+ import { createVoice } from '@dimchansky/meshpost/voice'
13
+
14
+ const voice = createVoice(room, {
15
+ volume: 1,
16
+ speakingDetection: true
17
+ })
18
+
19
+ voice.onChange((snap) => {
20
+ // snap: VoiceSnapshot
21
+ // { micStatus, micError, deviceId, autoplayBlocked, deafened, volume,
22
+ // selfSpeaking, remotePeers, speakingPeers, mutedPeers, peerVolumes }
23
+ micBtn.textContent =
24
+ snap.micStatus === 'live'
25
+ ? 'Mute'
26
+ : snap.micStatus === 'muted'
27
+ ? 'Unmute'
28
+ : snap.micStatus === 'requesting'
29
+ ? 'Starting…'
30
+ : 'Join Voice'
31
+
32
+ autoplayBanner.hidden = !snap.autoplayBlocked
33
+ })
34
+
35
+ micBtn.addEventListener('click', () => voice.toggleMic())
36
+ stopBtn.addEventListener('click', () => voice.stopMic())
37
+ autoplayBanner.addEventListener('click', () => voice.unlockAudio())
38
+ ```
39
+
40
+ `voice.close()` runs automatically when `room.leave()` is called — you do not need to close it manually unless you tear down voice while staying in the room.
41
+
42
+ ---
43
+
44
+ ## 2. Three-state microphone lifecycle
45
+
46
+ | Action | Transition | WebRTC impact |
47
+ | ----------------------------------------------------------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
48
+ | `voice.toggleMic()` (first call) or `voice.startMic()` | `'off' \| 'error'` → `'requesting'` → `'live'` | Acquires mic via `getUserMedia` and calls `room.addStream(stream, { tag: 'voice' })`. Concurrent calls while `'requesting'` coalesce. |
49
+ | `voice.toggleMic()` (when live) or `voice.setMuted(true)` | `'live'` → `'muted'` | Sets `track.enabled = false` (**zero renegotiation**, instant toggle). |
50
+ | `voice.toggleMic()` (when muted) or `voice.setMuted(false)` | `'muted'` → `'live'` | Sets `track.enabled = true` (**zero renegotiation**). |
51
+ | `voice.stopMic()` | any → `'off'` | Detaches stream (`room.removeStream`), cancels any pending `getUserMedia`, and calls `track.stop()` so the OS microphone indicator turns off. |
52
+
53
+ If capture fails, `micStatus` becomes `'error'` and `micError` contains `{ code, message }` where `code` is `'permission-denied' | 'not-found' | 'in-use' | 'insecure-context' | 'room-closed' | 'unknown'`.
54
+
55
+ ---
56
+
57
+ ## 3. Autoplay Policy & iOS Safari unlocking
58
+
59
+ Browsers often block remote `<audio autoplay>` playback until the user interacts with the page.
60
+
61
+ - With `autoUnlock: true` (default), `createVoice()` attaches lock-free `{ capture: true }` gesture listeners (`pointerdown`, `pointerup`, `touchend`, `click`, `keydown`) plus `visibilitychange` to resume the shared `AudioContext` and retry `audio.play()` automatically.
62
+ - Whenever any remote `<audio>` element rejects playback with `NotAllowedError`, `snap.autoplayBlocked` becomes `true`. Show a clickable banner wired to `voice.unlockAudio()` as a clear fallback.
63
+ - On iOS Safari (where `navigator.audioSession` exists), `createVoice()` switches `audioSession.type` to `'play-and-record'` while the mic is active and restores the previous mode across all exit paths (`stopMic`, errors, `close`, `room.leave`).
64
+
65
+ ---
66
+
67
+ ## 4. Microphone device picker & hot-switching
68
+
69
+ Use the tree-shakeable `listAudioInputs()` and `onAudioInputsChange()` helpers to populate a `<select>` both before and during a call, and hot-swap live microphones with zero SDP renegotiation via `voice.switchDevice()`.
70
+
71
+ ```ts
72
+ import {
73
+ createVoice,
74
+ listAudioInputs,
75
+ onAudioInputsChange,
76
+ type AudioInputDevice
77
+ } from '@dimchansky/meshpost/voice'
78
+
79
+ const savedDeviceId = localStorage.getItem('preferred-mic') || null
80
+
81
+ const voice = createVoice(room, {
82
+ deviceId: savedDeviceId,
83
+ // If the saved USB headset was unplugged before joining, silently fall back to
84
+ // the system default on initial startMic()/toggleMic() with no 'error' flash.
85
+ fallbackToDefaultOnNotFound: true
86
+ })
87
+
88
+ function renderMicSelect(devices: readonly AudioInputDevice[]) {
89
+ micSelect.replaceChildren(new Option('Default microphone', ''))
90
+ for (const [i, d] of devices.entries()) {
91
+ micSelect.add(new Option(d.label || `Microphone ${i + 1}`, d.deviceId))
92
+ }
93
+ micSelect.value = voice.deviceId ?? ''
94
+ }
95
+
96
+ // { immediate: true } delivers the initial list through the same race-safe epoch guard
97
+ // as 'devicechange' events — no manual initial enumerateDevices() race needed.
98
+ const ac = new AbortController()
99
+ onAudioInputsChange(renderMicSelect, { immediate: true, signal: ac.signal })
100
+
101
+ // Browsers hide device labels until microphone permission is granted once;
102
+ // refresh labels after the mic first goes live.
103
+ voice.onChange(
104
+ (snap) => {
105
+ if (snap.micStatus === 'live') void listAudioInputs().then(renderMicSelect)
106
+ },
107
+ { signal: ac.signal }
108
+ )
109
+
110
+ micSelect.addEventListener('change', async () => {
111
+ const nextId = micSelect.value || null
112
+ localStorage.setItem('preferred-mic', nextId ?? '')
113
+ // When 'live' or 'muted', swaps the track via room.replaceStreamTrack() with zero SDP renegotiation.
114
+ await voice.switchDevice(nextId)
115
+ })
116
+ ```
117
+
118
+ Key details:
119
+
120
+ - `listAudioInputs()` safely returns `[]` on non-DOM runtimes or if `enumerateDevices()` rejects, filters to `kind === 'audioinput'` entries with non-empty `deviceId`, deduplicates by `deviceId`, and trims labels (if you render a separate `"Default microphone"` option in your UI, you can filter synthetic `'default'` / `'communications'` aliases when real hardware devices are present, as in [examples/playground/voice.js](../examples/playground/voice.js)).
121
+ - `fallbackToDefaultOnNotFound: true` applies **only** to initial mic acquisition (`startMic()` / `toggleMic()`). An explicit live `switchDevice(brokenId)` still reports `'not-found'` so your UI can inform the user.
122
+ - To restore the system default microphone, call `voice.switchDevice(null)` or `voice.switchDevice()`.
123
+
124
+ ---
125
+
126
+ ## 5. Per-peer audio mixer
127
+
128
+ Control master volume, global deafen, and per-peer volume/mute independently:
129
+
130
+ ```ts
131
+ // Master volume (0..1, clamped) and global deafen
132
+ voice.setVolume(0.8)
133
+ voice.setDeafened(false)
134
+
135
+ // Per-peer volume (0..1, multiplied by master voice.volume)
136
+ voice.setPeerVolume(peerId, 0.4)
137
+ console.log(voice.getPeerVolume(peerId)) // 0.4
138
+ console.log(voice.peerVolumes) // sparse map of peers !== 1, e.g. { [peerId]: 0.4 }
139
+
140
+ // Per-peer local mute (independent of deafened; speakingPeers still updates)
141
+ voice.setPeerMuted(peerId, true)
142
+ console.log(voice.isPeerMuted(peerId)) // true
143
+ ```
144
+
145
+ ---
146
+
147
+ ## 6. Custom `MediaStream`s (video & screen sharing)
148
+
149
+ For camera video, screen sharing, or custom Web Audio pipelines, use the room's low-level media API directly. Always pass a distinct `tag` (e.g. `'screen'` or `'camera'`) so `createVoice()` (which defaults to `streamTag: 'voice'`) does not attach your screen-share audio as a voice peer!
150
+
151
+ ```ts
152
+ // Broadcast screen share to all connected and future peers (or pass { to: peerId, tag: 'screen' })
153
+ const screenStream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: true })
154
+ room.addStream(screenStream, { tag: 'screen' })
155
+
156
+ // Receive tagged remote streams (fires strictly after onPeerJoin)
157
+ room.onPeerStream((peerId, stream, meta) => {
158
+ if (meta.tag !== 'screen') return
159
+ const video = document.createElement('video')
160
+ video.srcObject = stream
161
+ video.autoplay = true
162
+ video.playsInline = true
163
+ screenContainer.append(video)
164
+ })
165
+
166
+ room.onPeerStreamEnd((peerId, stream, meta) => {
167
+ if (meta.tag === 'screen') {
168
+ removeVideoFor(peerId, stream)
169
+ }
170
+ })
171
+
172
+ // Hot-swap a track (e.g. switch camera) with zero SDP renegotiation
173
+ async function swapVideoTrack(stream: MediaStream, newTrack: MediaStreamTrack) {
174
+ const [oldTrack] = stream.getVideoTracks()
175
+ if (!oldTrack) return
176
+ await room.replaceStreamTrack(stream, oldTrack, newTrack)
177
+ oldTrack.stop() // room.replaceStreamTrack() never stops oldTrack for you
178
+ }
179
+
180
+ // Stop sharing
181
+ room.removeStream(screenStream)
182
+ for (const track of screenStream.getTracks()) track.stop() // room.removeStream() never stops local tracks
183
+ ```
184
+
185
+ If your app mixes untagged legacy streams with `createVoice()`, set `strictStreamTag: true` on `createVoice()` so only streams explicitly tagged with `streamTag` (`'voice'`) are played by the voice controller.
186
+
187
+ ---
188
+
189
+ ## See also
190
+
191
+ - [Guide](./guide.md) — core rooms, channels, state, RPC, blobs, and identity
192
+ - [API Reference](./api.md#dimchanskymeshpostvoice) — exact `Voice`, `VoiceOptions`, and `VoiceSnapshot` types
193
+ - [examples/playground/voice.js](../examples/playground/voice.js) — complete working voice UI controller
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dimchansky/meshpost",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "author": "Dmitrij Koniajev",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -118,7 +118,8 @@
118
118
  "scripts": {
119
119
  "clean": "node -e \"import('node:fs').then(fs => fs.rmSync('dist', { recursive: true, force: true }))\"",
120
120
  "build": "tsc -p tsconfig.json",
121
- "check:pkg": "publint",
121
+ "check:readme": "node scripts/check-readme.mjs",
122
+ "check:pkg": "publint && npm run check:readme",
122
123
  "demo": "npm run build && node examples/build.mjs",
123
124
  "test": "npm run demo && playwright test",
124
125
  "demo:tabs": "npm run demo && node examples/serve.mjs",