@dimchansky/meshpost 0.5.0 → 0.7.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.
- package/README.md +66 -544
- package/dist/bip340.d.ts +1 -0
- package/dist/bip340.js +346 -0
- package/dist/blob.d.ts +1 -1
- package/dist/blob.js +44 -45
- package/dist/channel.d.ts +4 -0
- package/dist/channel.js +19 -44
- package/dist/combine.d.ts +9 -2
- package/dist/combine.js +40 -57
- package/dist/crypto.js +10 -9
- package/dist/identity.d.ts +2 -0
- package/dist/identity.js +39 -71
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/listeners.js +18 -3
- package/dist/mqtt.js +211 -476
- package/dist/nostr.js +194 -836
- package/dist/peer-link.d.ts +1 -0
- package/dist/peer-link.js +983 -0
- package/dist/presence.d.ts +1 -0
- package/dist/presence.js +74 -0
- package/dist/public.d.ts +1 -1
- package/dist/public.js +25 -77
- package/dist/relay-core.d.ts +1 -0
- package/dist/relay-core.js +399 -0
- package/dist/room-reclaim.d.ts +1 -0
- package/dist/room-reclaim.js +115 -0
- package/dist/room-stats.d.ts +1 -0
- package/dist/room-stats.js +75 -0
- package/dist/room.js +245 -1218
- package/dist/rpc.js +25 -28
- package/dist/signaling.d.ts +8 -0
- package/dist/signaling.js +55 -0
- package/dist/state.js +23 -33
- package/dist/tabs.js +6 -50
- package/dist/voice-mic.d.ts +1 -0
- package/dist/voice-mic.js +496 -0
- package/dist/voice-remote.d.ts +1 -0
- package/dist/voice-remote.js +568 -0
- package/dist/voice.d.ts +19 -1
- package/dist/voice.js +95 -1036
- package/dist/ws.js +56 -197
- package/docs/adr/0001-room-internals-and-channel-budget.md +31 -0
- package/docs/api.md +219 -0
- package/docs/behavior.md +14 -8
- package/docs/guide.md +404 -0
- package/docs/signaling-and-production.md +312 -0
- package/docs/voice-and-media.md +193 -0
- package/package.json +6 -3
package/README.md
CHANGED
|
@@ -3,588 +3,110 @@
|
|
|
3
3
|
[](https://github.com/dimchansky/meshpost/actions/workflows/ci.yml)
|
|
4
4
|
[](https://www.npmjs.com/package/@dimchansky/meshpost)
|
|
5
5
|
|
|
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
|
|
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 chat, canvas, file sharing, and voice.
|
|
7
7
|
|
|
8
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 (and headless Node.js / Bun / Deno peers) connect directly
|
|
11
|
-
- **
|
|
12
|
-
- **Flexible E2E-encrypted discovery:**
|
|
13
|
-
- **Zero runtime dependencies:** Pure TypeScript ES modules with granular `@dimchansky/meshpost/*` subpath exports (`importmap`-ready).
|
|
10
|
+
- **Direct peer-to-peer:** Browsers (and headless Node.js 22+ / Bun / Deno peers) connect directly with no host election or central data relay.
|
|
11
|
+
- **Batteries included:** Reliable and unreliable data channels, typed codecs (`createCodecChannel`), request-response RPC (`createRpc`), replicated per-peer state (`createPeerState`), chunked transfers (`createBlobChannel`), headless P2P voice (`createVoice`), and DTLS-bound `ECDSA P-256` identity (`createIdentity`).
|
|
12
|
+
- **Flexible E2E-encrypted discovery:** Out-of-the-box `publicSignaling()` (public MQTT + port-443 Nostr + local tabs + optional fast-path WebSocket relays), plus standalone WebSocket, `BroadcastChannel`, and offline copy-paste adapters. Connected peers keep talking even if signaling goes offline.
|
|
13
|
+
- **Zero runtime dependencies:** Pure TypeScript ES modules (`"sideEffects": false`) with granular `@dimchansky/meshpost/*` subpath exports (`importmap`-ready).
|
|
14
14
|
|
|
15
|
-
##
|
|
15
|
+
## Install
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
```sh
|
|
20
|
-
npm install @dimchansky/meshpost
|
|
21
|
-
```
|
|
22
|
-
|
|
23
|
-
Or build from source:
|
|
24
|
-
|
|
25
|
-
```sh
|
|
26
|
-
git clone https://github.com/dimchansky/meshpost.git
|
|
27
|
-
cd meshpost
|
|
28
|
-
npm ci
|
|
29
|
-
npm run build
|
|
30
|
-
```
|
|
31
|
-
|
|
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
|
-
|
|
34
|
-
```ts
|
|
35
|
-
import { joinRoom, publicSignaling } from '@dimchansky/meshpost'
|
|
36
|
-
|
|
37
|
-
const encoder = new TextEncoder()
|
|
38
|
-
const decoder = new TextDecoder()
|
|
39
|
-
|
|
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).
|
|
42
|
-
const room = joinRoom('lobby', {
|
|
43
|
-
appId: 'my-chat-app',
|
|
44
|
-
signaling: publicSignaling()
|
|
45
|
-
})
|
|
46
|
-
|
|
47
|
-
room.onPeerJoin((peerId) => console.log('Joined:', peerId))
|
|
48
|
-
room.onPeerLeave((peerId) => console.log('Left:', peerId))
|
|
49
|
-
|
|
50
|
-
// Receive binary packets and decode text.
|
|
51
|
-
const stop = room.onPacket((from, bytes, delivery) => {
|
|
52
|
-
if (delivery === 'reliable') {
|
|
53
|
-
console.log(from, decoder.decode(bytes))
|
|
54
|
-
}
|
|
55
|
-
})
|
|
56
|
-
|
|
57
|
-
// Send a reliable message to all connected peers.
|
|
58
|
-
// Note: delivery defaults to 'unreliable'. Set 'reliable' for messages that must arrive.
|
|
59
|
-
function sendMessage(text: string) {
|
|
60
|
-
const results = room.send(encoder.encode(text), { delivery: 'reliable' })
|
|
61
|
-
for (const [peerId, status] of results) {
|
|
62
|
-
console.log(peerId, status) // 'accepted' | 'busy' | 'unavailable' | 'too-large'
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
|
|
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
|
-
}
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
3. Use `createChannel` (or typed `createCodecChannel` with `jsonCodec` / `textCodec`) when your app has multiple message types so modules do not collide:
|
|
75
|
-
|
|
76
|
-
```ts
|
|
77
|
-
import { createChannel, createCodecChannel, textCodec } from '@dimchansky/meshpost'
|
|
78
|
-
|
|
79
|
-
const cursors = createChannel(room, 'cursor', { delivery: 'unreliable' })
|
|
80
|
-
const chat = createCodecChannel(room, 'chat', textCodec, { delivery: 'reliable' })
|
|
81
|
-
|
|
82
|
-
cursors.onPacket((from, bytes) => updateCursor(from, bytes))
|
|
83
|
-
chat.onMessage((from, text) => showChat(from, text))
|
|
84
|
-
|
|
85
|
-
// Broadcast a cursor update to everyone.
|
|
86
|
-
cursors.send(cursorBytes)
|
|
87
|
-
|
|
88
|
-
// Send a reliable message to one specific peer and inspect the synchronous SendResult.
|
|
89
|
-
const status = chat.send('hello', { to: peerId }).get(peerId)
|
|
90
|
-
```
|
|
91
|
-
|
|
92
|
-
## Choose a signaling adapter
|
|
93
|
-
|
|
94
|
-
Browsers need a signaling adapter only to find each other and start the connection. After that, data travels directly between browsers.
|
|
95
|
-
|
|
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 |
|
|
108
|
-
|
|
109
|
-
### Local tabs (`tabSignaling`)
|
|
110
|
-
|
|
111
|
-
```ts
|
|
112
|
-
import { joinRoom, tabSignaling } from '@dimchansky/meshpost'
|
|
113
|
-
|
|
114
|
-
const room = joinRoom('arena', {
|
|
115
|
-
appId: 'my-game',
|
|
116
|
-
signaling: tabSignaling()
|
|
117
|
-
})
|
|
118
|
-
```
|
|
119
|
-
|
|
120
|
-
### Offline copy-paste (`manualSignaling`)
|
|
121
|
-
|
|
122
|
-
```ts
|
|
123
|
-
import { joinRoom, manualSignaling } from '@dimchansky/meshpost'
|
|
124
|
-
|
|
125
|
-
const manual = manualSignaling((toPeerId, replyText) => {
|
|
126
|
-
// Show replyText to the user to send to `toPeerId`.
|
|
127
|
-
})
|
|
128
|
-
|
|
129
|
-
const room = joinRoom('offline-room', {
|
|
130
|
-
appId: 'my-app',
|
|
131
|
-
signaling: manual.signaling,
|
|
132
|
-
handshakeTimeoutMs: 180_000
|
|
133
|
-
})
|
|
134
|
-
|
|
135
|
-
const myContactCard = manual.contact() // Share this text with the other browser.
|
|
136
|
-
manual.accept(pastedTextFromPeer) // Paste incoming contact cards and replies here.
|
|
137
|
-
manual.forget(oldPeerId) // Optional: stop retrying an old contact.
|
|
138
|
-
```
|
|
139
|
-
|
|
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).
|
|
141
|
-
|
|
142
|
-
## Public API reference
|
|
143
|
-
|
|
144
|
-
### `joinRoom(name, options)`
|
|
145
|
-
|
|
146
|
-
Creates a room, assigns a random peer ID (`room.id`), and immediately starts looking for other peers.
|
|
147
|
-
|
|
148
|
-
- `name`: Room name. Must match `^[a-zA-Z0-9_-]{1,64}$`.
|
|
149
|
-
- Throws an error immediately if `name`, `appId`, `password`, timeouts, `maxPeers`, or `rtcConfig` are invalid.
|
|
150
|
-
|
|
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. |
|
|
163
|
-
|
|
164
|
-
### `Room`
|
|
165
|
-
|
|
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. Meshpost multiplexes all subscriptions sharing the same `AbortSignal` onto a single native `'abort'` listener (avoiding Node.js `MaxListenersExceededWarning`). Note that `room.leave()` automatically unsubscribes all room/module listeners and rejects pending `rpc.call()` promises with `RpcError('closed')`, so a shared `AbortSignal` is only needed for earlier teardown while the room stays open.
|
|
189
|
-
|
|
190
|
-
`room.onError` emits a `RoomError` object: `{ code: RoomErrorCode, message: string, peerId?: string }`.
|
|
191
|
-
|
|
192
|
-
### Verifiable peer identity (`createIdentityStore` / `createIdentity`)
|
|
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
|
-
- `createIdentityStore({ key, storage? }): IdentityStore` — race-safe persistent identity manager (`load()`, `rotate()`, `clear()`) backed by `localStorage` by default (safely degrading to ephemeral in-memory caching on `SecurityError`/non-DOM runtimes, coalescing concurrent `load()` calls, self-healing corrupt storage, and preventing `load()` vs `rotate()` races via a monotonic epoch). _(Security note: `localStorage` stores an extractable JWK readable by same-origin scripts; for stronger XSS isolation, use `createIdentity({ extractable: false })` with IndexedDB.)_
|
|
197
|
-
- Low-level primitives: `createIdentity(options?: CreateIdentityOptions)`, `exportIdentity(identity)`, `importIdentity(data, options?)`, and `isSerializedIdentity(value)`.
|
|
198
|
-
- Exported identity types: `PeerIdentity`, `SerializedIdentity`, `CreateIdentityOptions`, `IdentityStorage`, `IdentityStoreOptions`, `IdentityStore`.
|
|
199
|
-
|
|
200
|
-
```ts
|
|
201
|
-
import { createIdentityStore, joinRoom } from '@dimchansky/meshpost'
|
|
202
|
-
|
|
203
|
-
const identityStore = createIdentityStore({ key: 'my-app:identity' })
|
|
204
|
-
const identity = await identityStore.load()
|
|
205
|
-
|
|
206
|
-
const room = joinRoom('lobby', { signaling, identity })
|
|
207
|
-
console.log('My verified userId:', room.userId)
|
|
208
|
-
|
|
209
|
-
room.onPeerJoin((peerId) => {
|
|
210
|
-
// Already verified over WebRTC with DTLS channel binding before onPeerJoin fires!
|
|
211
|
-
console.log('Peer joined:', peerId, 'verified userId:', room.peerUserId(peerId))
|
|
212
|
-
})
|
|
213
|
-
```
|
|
214
|
-
|
|
215
|
-
### `createVoice(room, options?: VoiceOptions)`
|
|
216
|
-
|
|
217
|
-
Headless P2P voice chat controller built on top of `room.addStream()` / `room.onPeerStream()`:
|
|
218
|
-
|
|
219
|
-
- Plays incoming peer audio streams automatically via hidden `<audio autoplay playsinline>` elements (hydrating any streams already active when `createVoice(room)` is called, up to `4` streams per peer).
|
|
220
|
-
- Manages local microphone capture with instant soft-mute (`track.enabled`, zero WebRTC renegotiation) vs full hardware release (`stopMic()`), plus automatic cleanup when `room.leave()` runs.
|
|
221
|
-
- 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).
|
|
222
|
-
- 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).
|
|
223
|
-
|
|
224
|
-
| `VoiceOptions` field | Type | Default | Purpose |
|
|
225
|
-
| ----------------------------- | ------------------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
|
226
|
-
| `volume` | `number` | `1` | Initial playback volume (`0` to `1`) for incoming peer audio. |
|
|
227
|
-
| `deafened` | `boolean` | `false` | Start with incoming peer audio muted locally (`audio.muted = true`). |
|
|
228
|
-
| `deviceId` | `string \| null` | `null` | Preferred microphone `deviceId` (`null` / `''` for system default). Preserves `defaultAudioConstraints`. |
|
|
229
|
-
| `fallbackToDefaultOnNotFound` | `boolean` | `false` | On initial mic start (`toggleMic` / `startMic`), auto-retry with system default if `deviceId` fails with `'not-found'`. |
|
|
230
|
-
| `audioConstraints` | `MediaTrackConstraints \| true` | `{ echoCancellation: true, noiseSuppression: true, autoGainControl: true }` | Audio track constraints passed to `getUserMedia`. |
|
|
231
|
-
| `autoUnlock` | `boolean` | `true` | Attach global `{ capture: true }` gesture & `visibilitychange` listeners to unlock blocked playback. |
|
|
232
|
-
| `speakingDetection` | `boolean` | `true` | Enable shared lazy `AudioContext` + `AnalyserNode` speaking detection. |
|
|
233
|
-
| `speakingThreshold` | `number` | `0.03` | RMS amplitude threshold (`0` to `1`) for `selfSpeaking` and `speakingPeers`. |
|
|
234
|
-
| `speakingIntervalMs` | `number` | `180` | Polling interval in milliseconds (`50` to `60_000`) for speaking detection. |
|
|
235
|
-
| `to` | `string` | `undefined` | Scope outgoing microphone audio to a single target peer ID (incoming audio from all peers plays). |
|
|
236
|
-
| `streamTag` | `string` | `'voice'` | Stream tag attached to outgoing mic streams and matched on incoming streams (`[a-zA-Z0-9._-]{1,32}`). |
|
|
237
|
-
| `strictStreamTag` | `boolean` | `false` | When `true`, also ignore untagged (`meta.tag === undefined`) incoming audio streams. |
|
|
238
|
-
|
|
239
|
-
| `Voice` member | Description |
|
|
240
|
-
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
241
|
-
| `voice.micStatus` | Current `MicStatus`: `'off' \| 'requesting' \| 'live' \| 'muted' \| 'error'`. |
|
|
242
|
-
| `voice.micError` | `MicError \| null` (`{ code: MicErrorCode, message: string }`; codes: `'permission-denied' \| 'not-found' \| 'in-use' \| 'insecure-context' \| 'room-closed' \| 'unknown'`). |
|
|
243
|
-
| `voice.deviceId` | Active or selected microphone `deviceId` (`string`), or `null` for system default. |
|
|
244
|
-
| `voice.autoplayBlocked` | `true` while any incoming `<audio>` element was blocked by browser Autoplay Policy and awaits a user gesture. |
|
|
245
|
-
| `voice.deafened` | Whether incoming peer audio is muted locally. |
|
|
246
|
-
| `voice.volume` | Current master incoming playback volume (`0` to `1`). |
|
|
247
|
-
| `voice.selfSpeaking` | `true` when local microphone is `'live'` and exceeds `speakingThreshold`. |
|
|
248
|
-
| `voice.remotePeers` | Snapshot array of peer IDs currently sending voice audio. |
|
|
249
|
-
| `voice.speakingPeers` | Snapshot array of remote peer IDs whose incoming audio currently exceeds `speakingThreshold` (independent of `deafened` / `mutedPeers`; filter locally if your UI hides speaking indicators for muted peers). |
|
|
250
|
-
| `voice.mutedPeers` | Snapshot array of remote peer IDs locally muted via `voice.setPeerMuted(peerId, true)`. |
|
|
251
|
-
| `voice.peerVolumes` | Sparse read-only map (`Readonly<Record<string, number>>`) of overridden per-peer playback volumes (`!== 1`; omitted peers default to `1`). |
|
|
252
|
-
| `voice.getSnapshot()` | Returns an immutable `VoiceSnapshot` object with all 11 state fields above (`Voice extends VoiceSnapshot`). |
|
|
253
|
-
| `voice.toggleMic()` | Acquires mic on first call (`'off' \| 'error'` → `'requesting'` → `'live'`), or toggles soft-mute (`'live'` ↔ `'muted'`). Coalesces concurrent `'requesting'` calls. |
|
|
254
|
-
| `voice.startMic()` | Acquires mic if inactive, or unmutes if `'muted'`. Coalesces concurrent `'requesting'` calls; resolves to `'off'` if closed. |
|
|
255
|
-
| `voice.setMuted(muted)` | Soft-mutes (`true`) or unmutes (`false`) an already-acquired mic (`'live' \| 'muted'`). No-op otherwise. |
|
|
256
|
-
| `voice.stopMic()` | Detaches stream from room (`removeStream`), cancels any pending `getUserMedia`, and stops hardware tracks (`track.stop()`). |
|
|
257
|
-
| `voice.switchDevice(deviceId?)` | Selects or hot-swaps microphone device (`string \| null \| undefined`) via `room.replaceStreamTrack()` with zero WebRTC SDP renegotiation (`Promise<MicStatus>`). |
|
|
258
|
-
| `voice.setVolume(volume)` | Sets master incoming playback volume (`0` to `1`, clamped; throws `RangeError` if non-finite). |
|
|
259
|
-
| `voice.setPeerVolume(peerId, volume)` | Sets local playback volume (`0` to `1`, clamped, scaled by master `voice.volume`) for one peer. |
|
|
260
|
-
| `voice.getPeerVolume(peerId)` | Returns configured local playback volume (`0` to `1`, default `1`) for `peerId`. |
|
|
261
|
-
| `voice.setDeafened(deafened)` | Mutes (`true`) or unmutes (`false`) incoming remote `<audio>` elements locally (unmuting also calls `unlockAudio()`). |
|
|
262
|
-
| `voice.setPeerMuted(peerId, muted)` | Locally mutes (`true`) or unmutes (`false`) incoming audio from one peer (independent of `deafened`). |
|
|
263
|
-
| `voice.isPeerMuted(peerId)` | Returns whether `peerId` is locally muted via `setPeerMuted()`. |
|
|
264
|
-
| `voice.unlockAudio()` | Synchronously retries `AudioContext.resume()` and `audio.play()` on paused remote streams (e.g. from a custom unlock banner click). |
|
|
265
|
-
| `voice.onChange(fn, options?: ListenOptions)` | Subscribes to `VoiceSnapshot` changes (`(snapshot: VoiceSnapshot) => ...`). Returns unsubscribe. |
|
|
266
|
-
| `voice.close()` | Releases mic tracks, removes hidden `<audio>` elements, closes `AudioContext`, restores `audioSession`, and detaches all listeners (runs automatically on `room.leave()`). |
|
|
267
|
-
|
|
268
|
-
Exported voice helpers & types: `listAudioInputs()`, `onAudioInputsChange(fn, options?: ListenOptions)`, `AudioInputDevice`, `Voice`, `VoiceOptions`, `VoiceSnapshot`, `MicStatus`, `MicError`, `MicErrorCode`.
|
|
269
|
-
|
|
270
|
-
```ts
|
|
271
|
-
import { createVoice } from '@dimchansky/meshpost'
|
|
272
|
-
|
|
273
|
-
const voice = createVoice(room)
|
|
274
|
-
|
|
275
|
-
// Synchronous state inspection (e.g. exit Pointer Lock in 3D games only before first permission prompt)
|
|
276
|
-
if (voice.micStatus === 'off' || voice.micStatus === 'error') {
|
|
277
|
-
document.exitPointerLock?.()
|
|
278
|
-
}
|
|
279
|
-
await voice.toggleMic() // 1st call: getUserMedia + addStream ('live'); next calls: soft-mute ('muted' <-> 'live')
|
|
280
|
-
|
|
281
|
-
voice.onChange((snap) => {
|
|
282
|
-
// snap: { micStatus, micError, deviceId, autoplayBlocked, deafened, volume, selfSpeaking, remotePeers, speakingPeers, mutedPeers, peerVolumes }
|
|
283
|
-
if (snap.autoplayBlocked) showUnlockBanner()
|
|
284
|
-
})
|
|
285
|
-
|
|
286
|
-
voice.setVolume(0.8)
|
|
287
|
-
voice.setDeafened(false)
|
|
288
|
-
voice.stopMic() // Release microphone hardware while staying in the room (voice.close() runs automatically on room.leave())
|
|
289
|
-
```
|
|
290
|
-
|
|
291
|
-
#### Low-level `MediaStream` API (`addStream` / `onPeerStream`)
|
|
292
|
-
|
|
293
|
-
For custom video, screen sharing, or bespoke audio pipelines, use the low-level `Room` methods directly:
|
|
294
|
-
|
|
295
|
-
```ts
|
|
296
|
-
const screen = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: true })
|
|
297
|
-
room.addStream(screen, { tag: 'screen' }) // Tagged so createVoice() will not hijack screen audio!
|
|
298
|
-
|
|
299
|
-
room.onPeerStream((peerId, stream, meta) => {
|
|
300
|
-
if (meta.tag === 'screen') {
|
|
301
|
-
videoEl.srcObject = stream
|
|
302
|
-
}
|
|
303
|
-
})
|
|
304
|
-
room.onPeerStreamEnd((peerId, stream, meta) =>
|
|
305
|
-
console.log('Stream ended:', peerId, stream.id, meta.tag)
|
|
306
|
-
)
|
|
307
|
-
|
|
308
|
-
// Hot-swap a track (e.g. camera/mic switch) with zero WebRTC SDP renegotiation:
|
|
309
|
-
await room.replaceStreamTrack(screen, oldVideoTrack, newVideoTrack)
|
|
310
|
-
oldVideoTrack.stop()
|
|
311
|
-
|
|
312
|
-
// Later: detach from room and stop local tracks yourself.
|
|
313
|
-
room.removeStream(screen)
|
|
314
|
-
for (const track of screen.getTracks()) track.stop()
|
|
315
|
-
```
|
|
316
|
-
|
|
317
|
-
> **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.
|
|
318
|
-
|
|
319
|
-
### `SendResult`
|
|
320
|
-
|
|
321
|
-
`room.send()` and `channel.send()` return a `ReadonlyMap<string, SendResult>` immediately. Meshpost does not queue failed packets in the background:
|
|
322
|
-
|
|
323
|
-
| Value | Meaning |
|
|
324
|
-
| --------------- | ----------------------------------------------------------------------------------- |
|
|
325
|
-
| `'accepted'` | Browser accepted the packet for sending. |
|
|
326
|
-
| `'busy'` | Send buffer is full (`64 KiB` unreliable / `256 KiB` reliable). Wait for `onDrain`. |
|
|
327
|
-
| `'unavailable'` | Target peer is not connected, unknown, or is yourself. |
|
|
328
|
-
| `'too-large'` | Packet is larger than 16,384 bytes (or larger than the other browser allows). |
|
|
329
|
-
|
|
330
|
-
### `PeerStats`
|
|
331
|
-
|
|
332
|
-
`await room.getStats(peerId)` returns a read-only snapshot for a connected peer, or `null` if the peer is not connected or the room is closed:
|
|
333
|
-
|
|
334
|
-
| Field | Type | Meaning |
|
|
335
|
-
| -------------------- | ---------------- | ----------------------------------------------------------------------------------------------------- |
|
|
336
|
-
| `rttMs` | `number \| null` | Current round-trip ping in whole milliseconds (`null` if not measured yet). |
|
|
337
|
-
| `route` | `PeerRoute` | `'direct'` for peer-to-peer, `'relay'` through a TURN server, or `'unknown'` if not reported yet. |
|
|
338
|
-
| `bytesSent` | `number` | Total app payload bytes sent to this peer across both delivery modes (unreliable and reliable). |
|
|
339
|
-
| `bytesReceived` | `number` | Total app payload bytes received from this peer across both delivery modes (unreliable and reliable). |
|
|
340
|
-
| `bufferedUnreliable` | `number` | Bytes currently waiting in the unreliable send buffer. |
|
|
341
|
-
| `bufferedReliable` | `number` | Bytes currently waiting in the reliable send buffer. |
|
|
342
|
-
|
|
343
|
-
### `createChannel(room, name, options?: ChannelOptions)`
|
|
344
|
-
|
|
345
|
-
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.
|
|
346
|
-
|
|
347
|
-
- `name`: 1–64 UTF-8 bytes. Uses `1 + nameBytes.length` bytes of the 16,384-byte packet limit.
|
|
348
|
-
- `options` (`ChannelOptions`): `{ delivery?: Delivery }`. Defaults to `'unreliable'`.
|
|
349
|
-
- Returns a `Channel` with `{ name, delivery, send(bytes, options?: ChannelSendOptions), onPacket((from, bytes) => ..., options?: ListenOptions) }` (`ChannelSendOptions` is `{ to?: string }`).
|
|
350
|
-
|
|
351
|
-
### `createCodecChannel(room, name, codec, options?: ChannelOptions)`
|
|
352
|
-
|
|
353
|
-
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).
|
|
354
|
-
|
|
355
|
-
- Built-in codecs:
|
|
356
|
-
- `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.
|
|
357
|
-
- `textCodec` — Strict UTF-8 string codec (`Codec<string>`).
|
|
358
|
-
- `binaryCodec` — Zero-copy `Uint8Array` identity codec (`Codec<Uint8Array>`).
|
|
359
|
-
- Returns a `CodecChannel<T>` with `{ name, delivery, send(value, options?: ChannelSendOptions), onMessage((from, value) => ..., options?: ListenOptions) }`.
|
|
360
|
-
|
|
361
|
-
```ts
|
|
362
|
-
import { createCodecChannel, jsonCodec } from '@dimchansky/meshpost'
|
|
363
|
-
|
|
364
|
-
interface ChatMsg {
|
|
365
|
-
text: string
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
const isChatMsg = (v: unknown): v is ChatMsg =>
|
|
369
|
-
Boolean(v) && typeof v === 'object' && typeof (v as ChatMsg).text === 'string'
|
|
370
|
-
|
|
371
|
-
const chat = createCodecChannel(room, 'chat', jsonCodec(isChatMsg), { delivery: 'reliable' })
|
|
372
|
-
chat.onMessage((from, msg) => console.log(from, msg.text))
|
|
373
|
-
chat.send({ text: 'hello!' })
|
|
374
|
-
```
|
|
375
|
-
|
|
376
|
-
### `createRpc<Req, Res>(room, name, options?: RpcOptions<Req, Res>)`
|
|
377
|
-
|
|
378
|
-
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'`).
|
|
379
|
-
|
|
380
|
-
- `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).
|
|
381
|
-
- 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`).
|
|
382
|
-
|
|
383
|
-
```ts
|
|
384
|
-
import { createRpc } from '@dimchansky/meshpost'
|
|
385
|
-
|
|
386
|
-
const ping = createRpc<{ sentAt: number }, { serverNow: number }>(room, 'ping', {
|
|
387
|
-
timeoutMs: 5_000
|
|
388
|
-
})
|
|
389
|
-
|
|
390
|
-
ping.handle(() => ({ serverNow: Date.now() }))
|
|
391
|
-
|
|
392
|
-
const { serverNow } = await ping.call(peerId, { sentAt: Date.now() })
|
|
393
|
-
```
|
|
394
|
-
|
|
395
|
-
### `createPeerState<T>(room, name, options?: PeerStateOptions<T>)`
|
|
396
|
-
|
|
397
|
-
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'`.
|
|
398
|
-
|
|
399
|
-
- `options` (`PeerStateOptions<T>`): `{ delivery?: Delivery, codec?: Codec<T>, initial?: T, coalesce?: boolean }` (defaults: `delivery: 'reliable'`, `codec: jsonCodec()`, `coalesce: true`).
|
|
400
|
-
- Returns a `PeerState<T>` with `{ name, delivery, getSelf(), get(peerId), getAll(), set(value), clear(), onChange((peerId, next, prev, reason: PeerStateChangeReason) => ..., options?: ListenOptions), close() }` where `reason` is `'set' | 'clear' | 'leave'`.
|
|
401
|
-
|
|
402
|
-
```ts
|
|
403
|
-
import { createPeerState } from '@dimchansky/meshpost'
|
|
404
|
-
|
|
405
|
-
const cursors = createPeerState<{ x: number; y: number }>(room, 'cursor', {
|
|
406
|
-
delivery: 'unreliable',
|
|
407
|
-
coalesce: true
|
|
408
|
-
})
|
|
409
|
-
|
|
410
|
-
cursors.onChange((peerId, pos) => {
|
|
411
|
-
if (!pos)
|
|
412
|
-
removeCursor(peerId) // Peer left or called clear()
|
|
413
|
-
else renderCursor(peerId, pos.x, pos.y)
|
|
414
|
-
})
|
|
415
|
-
|
|
416
|
-
cursors.set({ x: 0.5, y: 0.25 })
|
|
417
|
-
```
|
|
418
|
-
|
|
419
|
-
### `createBlobChannel(room, name, options?: BlobChannelOptions)`
|
|
420
|
-
|
|
421
|
-
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`.
|
|
422
|
-
|
|
423
|
-
- `options` (`BlobChannelOptions`): `{ maxReceiveBytes?, chunkSize?, receiveTimeoutMs?, maxConcurrentPerPeer? }`. Defaults: `4 MiB` max receive, `15 KiB` chunk size, `30 s` receive inactivity timeout, `4` concurrent incoming transfers per peer.
|
|
424
|
-
- Returns a `BlobChannel` with `{ name, send(bytes, options?: BlobSendOptions), onBlob((from, bytes) => ..., options?: ListenOptions), onProgress((from, progress: BlobProgress) => ..., options?: ListenOptions), close() }` where `BlobProgress` is `{ transferId, receivedBytes, totalBytes }`.
|
|
425
|
-
- `send(bytes, { to?, onProgress?: (peerId, sentBytes, totalBytes) => void, signal? })` paces each recipient independently using `room.onDrain` and resolves to `ReadonlyMap<string, BlobSendStatus>` (`'sent' | 'aborted' | 'unavailable' | 'too-large'`).
|
|
426
|
-
|
|
427
|
-
```ts
|
|
428
|
-
import { createBlobChannel } from '@dimchansky/meshpost'
|
|
429
|
-
|
|
430
|
-
const files = createBlobChannel(room, 'file', { maxReceiveBytes: 8 * 1024 * 1024 })
|
|
431
|
-
files.onProgress((from, { receivedBytes, totalBytes }) =>
|
|
432
|
-
console.log(from, receivedBytes, totalBytes)
|
|
433
|
-
)
|
|
434
|
-
files.onBlob((from, bytes) => console.log('Received', bytes.byteLength, 'bytes from', from))
|
|
435
|
-
|
|
436
|
-
const results = await files.send(fileBytes, {
|
|
437
|
-
onProgress: (peerId, sent, total) => console.log(peerId, sent, total)
|
|
438
|
-
})
|
|
439
|
-
```
|
|
440
|
-
|
|
441
|
-
### Signaling exports
|
|
442
|
-
|
|
443
|
-
- `publicSignaling({ wsUrls?, mqtt?, nostr?, localTabs?, wsEncrypt?, privateTopic?, appId?, wsHandshakeTimeoutMs?, handshakeTimeoutMs?, WebSocket?, onTransportChange? })` — 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. Pass `onTransportChange?: (event: PublicTransportEvent) => void` to observe per-transport (`'ws' | 'mqtt' | 'nostr' | 'tabs'`) lifecycle transitions (`state`, optional `url` for `'ws'`, and optional `reason`); note that per the WHATWG WebSocket spec, browsers hide HTTP `403`/TLS failure details behind opaque close code `1006`, while client-side handshake timeouts and non-`1006` close codes appear in `reason`.
|
|
444
|
-
- `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.
|
|
445
|
-
- `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.
|
|
446
|
-
- `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.
|
|
447
|
-
- `optionalWsSignaling(url, { handshakeTimeoutMs?, pingIntervalMs?, encrypt?, privateTopic?, WebSocket? })` — Opportunistic `wsSignaling` wrapper (`reconnect: false`, `4,000` ms default handshake timeout) that transitions cleanly to `'closed'` (forwarding the close/timeout `reason`) and suppresses `'signaling-error'` if unreachable while preserving `'decrypt-failed'` and `'clock-skew'` diagnostics.
|
|
448
|
-
- `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.
|
|
449
|
-
- `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())`).
|
|
450
|
-
- `tabSignaling()` — Connects tabs open to the same site (same protocol, domain, and port) in the same browser. Works offline with no server.
|
|
451
|
-
- `manualSignaling(outgoing)` — Connects completely offline browsers by copying and pasting text. Returns `{ signaling, contact(), accept(text), forget(peerId) }`.
|
|
452
|
-
- `defaultIceServers` — Built-in Cloudflare and Google public servers (STUN) that help browsers find their public network address.
|
|
453
|
-
- Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `RoomError`, `RoomErrorCode`, `ListenOptions`, `ManualSignaling`, `PublicSignalingOptions`, `PublicTransportKind`, `PublicTransportEvent`, `MqttSignalingOptions`, `NostrSignalingOptions`, `WsSignalingOptions`, `OptionalWsSignalingOptions`, `RTCPeerConnectionConstructor`, `WebSocketConstructor`, `defaultMqttRelays`, `defaultNostrRelays`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
|
|
454
|
-
|
|
455
|
-
## Connecting through strict firewalls (TURN)
|
|
456
|
-
|
|
457
|
-
- Most home, mobile, and same-computer connections work out of the box using Meshpost's built-in public STUN servers (`defaultIceServers`) and local-device fallback.
|
|
458
|
-
- Strict corporate firewalls and restrictive routers block direct connections. For those networks, add a TURN relay server (a server that forwards traffic when a direct link fails).
|
|
459
|
-
- Add your TURN credentials directly or fetch short-lived credentials from Meshpost's reference Cloudflare Worker ([examples/turn-worker/](examples/turn-worker/README.md)) using `fetchTurnCredentials(url, options?: FetchTurnOptions)` (`options`: `{ accessKey?, signal?, timeoutMs? }`; `5,000` ms default timeout, `timeoutMs: 0` disables timeout, `redirect: 'error'`, `64 KiB` response cap):
|
|
460
|
-
|
|
461
|
-
```ts
|
|
462
|
-
import { fetchTurnCredentials, joinRoom, mqttSignaling, withLocalTabs } from '@dimchansky/meshpost'
|
|
463
|
-
|
|
464
|
-
const turnConfig = await fetchTurnCredentials('https://your-turn.workers.dev', {
|
|
465
|
-
accessKey: 'shared-key'
|
|
466
|
-
})
|
|
467
|
-
|
|
468
|
-
const room = joinRoom('lobby', {
|
|
469
|
-
appId: 'my-app',
|
|
470
|
-
signaling: withLocalTabs(mqttSignaling()),
|
|
471
|
-
turnConfig
|
|
472
|
-
})
|
|
473
|
-
```
|
|
474
|
-
|
|
475
|
-
### Subpath exports & bundler-free `<script type="importmap">`
|
|
476
|
-
|
|
477
|
-
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:
|
|
478
|
-
|
|
479
|
-
```html
|
|
480
|
-
<script type="importmap">
|
|
481
|
-
{
|
|
482
|
-
"imports": {
|
|
483
|
-
"@dimchansky/meshpost/room": "https://cdn.jsdelivr.net/npm/@dimchansky/meshpost/dist/room.js",
|
|
484
|
-
"@dimchansky/meshpost/nostr": "https://cdn.jsdelivr.net/npm/@dimchansky/meshpost/dist/nostr.js",
|
|
485
|
-
"@dimchansky/meshpost/channel": "https://cdn.jsdelivr.net/npm/@dimchansky/meshpost/dist/channel.js"
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
</script>
|
|
489
|
-
<script type="module">
|
|
490
|
-
import { joinRoom } from '@dimchansky/meshpost/room'
|
|
491
|
-
import { nostrSignaling } from '@dimchansky/meshpost/nostr'
|
|
492
|
-
import { createCodecChannel, textCodec } from '@dimchansky/meshpost/channel'
|
|
493
|
-
|
|
494
|
-
const room = joinRoom('lobby', { password: 'secret', signaling: nostrSignaling() })
|
|
495
|
-
const chat = createCodecChannel(room, 'chat', textCodec, { delivery: 'reliable' })
|
|
496
|
-
</script>
|
|
17
|
+
```sh
|
|
18
|
+
npm install @dimchansky/meshpost
|
|
497
19
|
```
|
|
498
20
|
|
|
499
|
-
|
|
21
|
+
Using zero-build browsers (`<script type="importmap">`) or headless Node.js / Bun / Deno? See [Signaling & Production](https://github.com/dimchansky/meshpost/blob/main/docs/signaling-and-production.md#7-bundler-free-browsers--headless-runtimes), [minimal-chat.html](https://github.com/dimchansky/meshpost/blob/main/examples/minimal-chat.html), and [headless-bot.mjs](https://github.com/dimchansky/meshpost/blob/main/examples/headless-bot.mjs).
|
|
500
22
|
|
|
501
|
-
|
|
23
|
+
## Quick start
|
|
502
24
|
|
|
503
25
|
```ts
|
|
504
|
-
import { RTCPeerConnection } from 'werift'
|
|
505
26
|
import { joinRoom } from '@dimchansky/meshpost/room'
|
|
506
|
-
import {
|
|
27
|
+
import { publicSignaling } from '@dimchansky/meshpost/public'
|
|
28
|
+
import { createCodecChannel, textCodec } from '@dimchansky/meshpost/channel'
|
|
507
29
|
|
|
508
|
-
const
|
|
509
|
-
password: 'secret',
|
|
510
|
-
|
|
511
|
-
signaling: wsSignaling('wss://relay.example/ws') // Node 22+, Bun, & Deno provide global WebSocket (or pass { WebSocket })
|
|
30
|
+
const room = joinRoom('team-standup', {
|
|
31
|
+
password: 'shared-room-secret',
|
|
32
|
+
signaling: publicSignaling()
|
|
512
33
|
})
|
|
513
|
-
```
|
|
514
34
|
|
|
515
|
-
|
|
35
|
+
const chat = createCodecChannel(room, 'chat', textCodec, { delivery: 'reliable' })
|
|
516
36
|
|
|
517
|
-
|
|
37
|
+
room.onPeerJoin((peerId) => console.log('Joined:', peerId))
|
|
38
|
+
room.onPeerLeave((peerId) => console.log('Left:', peerId))
|
|
39
|
+
chat.onMessage((from, text) => console.log(from, text))
|
|
518
40
|
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
npm run demo:tabs
|
|
41
|
+
// Broadcast to all connected peers, or pass { to: peerId } for a direct message
|
|
42
|
+
chat.send('Hello mesh!')
|
|
522
43
|
```
|
|
523
44
|
|
|
524
|
-
|
|
45
|
+
- `publicSignaling()` discovers peers across tabs (instant `BroadcastChannel`) and across devices over public MQTT + port-443 Nostr relays.
|
|
46
|
+
- Setting `password` encrypts signaling envelopes end-to-end with `AES-256-GCM`; once connected, all WebRTC data and media are DTLS-encrypted directly between peers.
|
|
47
|
+
- Call `room.leave()` on explicit exit; tab closes and `F5` reload ghost-session reclaim are handled automatically.
|
|
525
48
|
|
|
526
|
-
|
|
527
|
-
- To join from **another browser** (such as Safari or Firefox) or another device, click **Copy invite link** and open that URL there (or enter the same room name and password).
|
|
528
|
-
- To test from another device on your LAN, run `HOST=0.0.0.0 npm run demo:tabs`.
|
|
529
|
-
- Stopping the server does not disconnect active peer-to-peer links.
|
|
49
|
+
## Batteries included
|
|
530
50
|
|
|
531
|
-
|
|
51
|
+
Every module is tree-shakeable via its own `@dimchansky/meshpost/*` subpath (or imported from `@dimchansky/meshpost`):
|
|
532
52
|
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
53
|
+
| Capability | Entry point | Highlights |
|
|
54
|
+
| ----------------------- | -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
55
|
+
| Rooms & binary packets | `@dimchansky/meshpost/room` | `joinRoom()`, `'unreliable'` / `'reliable'` delivery, `onDrain` backpressure, `getStats()`, `addStream()` / `replaceStreamTrack()` |
|
|
56
|
+
| Named & typed channels | `@dimchansky/meshpost/channel` | `createChannel()`, `createCodecChannel()`, `textCodec`, `jsonCodec(guard)`, `binaryCodec`, `O(1)` routing |
|
|
57
|
+
| Replicated peer state | `@dimchansky/meshpost/state` | `createPeerState()` with RFC 1982 `u32` ordering, auto-hydration on join, `onDrain` coalescing, `reason: 'set' \| 'clear' \| 'leave'` |
|
|
58
|
+
| Request-response RPC | `@dimchansky/meshpost/rpc` | `createRpc()`, `RpcError`, timeouts, `AbortSignal`, disconnect cancellation, peer-scoped anti-spoofing |
|
|
59
|
+
| Large files & blobs | `@dimchansky/meshpost/blob` | `createBlobChannel()` for payloads >16 KiB with per-peer `onDrain` pacing, progress, and bounded receive RAM |
|
|
60
|
+
| Voice chat & mic picker | `@dimchansky/meshpost/voice` | `createVoice()`, soft-mute vs stop, speaking detection, autoplay unlock, `listAudioInputs()`, `onAudioInputsChange({ immediate })`, `switchDevice()`, per-peer mixer |
|
|
61
|
+
| Verifiable identity | `@dimchansky/meshpost/identity` | `createIdentity()`, `createIdentityStore()` (`load`, `rotate`, `current`), DTLS-bound `room.peerUserId(peerId)` |
|
|
62
|
+
| TURN credentials | `@dimchansky/meshpost/turn` | `fetchTurnCredentials()` for short-lived TURN servers behind symmetric NATs |
|
|
63
|
+
| Signaling & composition | `@dimchansky/meshpost/public` (+ `/ws`, `/mqtt`, `/nostr`, `/tabs`, `/manual`, `/combine`, `/signaling`) | `publicSignaling()`, `wsSignaling()`, `optionalWsSignaling()`, `mqttSignaling()`, `nostrSignaling()`, `tabSignaling()`, `manualSignaling()`, `combineSignaling()`, `withLocalTabs()`, `observeSignaling()` |
|
|
536
64
|
|
|
537
|
-
|
|
65
|
+
## Signaling at a glance
|
|
538
66
|
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
67
|
+
| Adapter | Best for | Notes |
|
|
68
|
+
| ------------------------------------ | --------------------------------- | ------------------------------------------------------------------------------------------------------ |
|
|
69
|
+
| `publicSignaling(opts?)` | Default internet & multi-tab apps | Combines MQTT + port-443 Nostr + `withLocalTabs`, optional fast-path `wsUrls`, and `onTransportChange` |
|
|
70
|
+
| `wsSignaling(url, opts?)` | Your own fast WebSocket relay | Full Trickle ICE, instant roster, E2E-encrypted by default with `password` |
|
|
71
|
+
| `mqttSignaling(opts?)` | Zero-backend public/custom MQTT | Parallel multi-broker redundancy over WebSocket; works even from `file://` |
|
|
72
|
+
| `nostrSignaling(opts?)` | Firewall-friendly port-443 relays | Ephemeral NIP-01 `kind: 25050` events over `wss://:443` (never stored by relays) |
|
|
73
|
+
| `tabSignaling()` / `withLocalTabs()` | Same-browser tabs | Zero-network `BroadcastChannel` discovery (`withLocalTabs` preserves network `signalingState`) |
|
|
74
|
+
| `manualSignaling(onOut)` | Air-gapped / offline setups | Copy-paste JSON contact cards & replies with zero network requests |
|
|
542
75
|
|
|
543
|
-
|
|
76
|
+
When `password` is set, `mqttSignaling()`, `nostrSignaling()`, and `wsSignaling()` (unless `encrypt: false` for plain HTTP LAN testing) derive keys with `PBKDF2-HMAC-SHA256` + `HKDF-SHA256` and encrypt signaling end-to-end with `AES-256-GCM` + `±60 s` replay protection. Pass `privateTopic: true` to also hide room topic/tag correlation on shared relays.
|
|
544
77
|
|
|
545
|
-
|
|
78
|
+
## Documentation
|
|
546
79
|
|
|
547
|
-
- [
|
|
548
|
-
- [
|
|
549
|
-
- [
|
|
550
|
-
- [
|
|
551
|
-
- [
|
|
552
|
-
- [examples/playground/session.js](examples/playground/session.js) — Compact `#c=` invite URLs and `sessionStorage` auto-rejoin.
|
|
553
|
-
- [examples/playground/app.js](examples/playground/app.js) — Thin UI controller connecting DOM controls to `mesh.js` and the helper modules.
|
|
554
|
-
- [examples/playground/index.html](examples/playground/index.html) — Minimal HTML markup for the playground.
|
|
555
|
-
- [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.
|
|
556
|
-
- [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.
|
|
80
|
+
- [Guide](https://github.com/dimchansky/meshpost/blob/main/docs/guide.md) — progressive walkthrough from 15-line chat to custom binary codecs, backpressure, state, RPC, blobs, identity, and teardown
|
|
81
|
+
- [Voice & Media](https://github.com/dimchansky/meshpost/blob/main/docs/voice-and-media.md) — `createVoice()`, mic switching, autoplay unlock, per-peer mixer, and custom video/screen `MediaStream`s
|
|
82
|
+
- [Signaling & Production](https://github.com/dimchansky/meshpost/blob/main/docs/signaling-and-production.md) — `publicSignaling()`, `observeSignaling()`, TURN, Cloudflare Workers, custom SSE adapter, `importmap`, headless Node/Bun/Deno, and production recipes
|
|
83
|
+
- [API Reference](https://github.com/dimchansky/meshpost/blob/main/docs/api.md) — complete exports, signatures, and option defaults across all 17 subpaths
|
|
84
|
+
- [Behavior & Security Spec](https://github.com/dimchansky/meshpost/blob/main/docs/behavior.md) — wire protocol, invariants, limits, and threat model
|
|
557
85
|
|
|
558
|
-
##
|
|
86
|
+
## Examples & edge templates
|
|
559
87
|
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
| `examples/turn-worker/` | Optional Cloudflare Worker credential broker for Metered, CF TURN, or `coturn` |
|
|
566
|
-
| `examples/build.mjs` | Bundles the playground into one portable HTML file |
|
|
567
|
-
| `examples/serve.mjs` | Local dev server with WebSocket (`/ws`) and SSE signaling relays |
|
|
568
|
-
| `tests/` | Playwright E2E tests using real browser WebRTC data channels |
|
|
569
|
-
| `dist/` | Built ES modules, `.d.ts` declarations, and `playground.html` |
|
|
88
|
+
- [examples/minimal-chat.html](https://github.com/dimchansky/meshpost/blob/main/examples/minimal-chat.html) — zero-build single-file P2P chat using `<script type="importmap">`
|
|
89
|
+
- [examples/headless-bot.mjs](https://github.com/dimchansky/meshpost/blob/main/examples/headless-bot.mjs) — Node.js 22+ / Bun / Deno peer with `werift`, Verified ID, chat echo, and RPC `ping`
|
|
90
|
+
- [examples/playground/](https://github.com/dimchansky/meshpost/blob/main/examples/playground/README.md) — full interactive playground (start with [mesh.js](https://github.com/dimchansky/meshpost/blob/main/examples/playground/mesh.js))
|
|
91
|
+
- [examples/ws-worker/](https://github.com/dimchansky/meshpost/blob/main/examples/ws-worker/README.md) — ready-to-deploy Cloudflare Worker + Durable Object (WebSocket Hibernation) signaling relay
|
|
92
|
+
- [examples/turn-worker/](https://github.com/dimchansky/meshpost/blob/main/examples/turn-worker/README.md) — ready-to-deploy Cloudflare Worker short-lived TURN credential broker
|
|
570
93
|
|
|
571
|
-
|
|
94
|
+
## Local playground & tests
|
|
572
95
|
|
|
573
96
|
```sh
|
|
574
97
|
npm ci
|
|
575
|
-
|
|
576
|
-
npm
|
|
98
|
+
npm run demo:tabs # Local dev server (playground at / and minimal chat at /minimal-chat.html)
|
|
99
|
+
npm run demo # Build standalone dist/playground.html (works via file://)
|
|
100
|
+
npm test # Run Playwright E2E suite (real browser WebRTC)
|
|
577
101
|
```
|
|
578
102
|
|
|
579
103
|
To use an already-installed Google Chrome instead of downloading Chromium, run `MESHPOST_CHROME_CHANNEL=chrome npm test`.
|
|
580
104
|
|
|
581
|
-
For full limits, wire protocol details, edge cases, and the security model, read [docs/behavior.md](docs/behavior.md).
|
|
582
|
-
|
|
583
105
|
## Runtime support
|
|
584
106
|
|
|
585
|
-
-
|
|
586
|
-
- `mqttSignaling
|
|
107
|
+
- Modern browsers (Chrome, Firefox, Safari) with WebRTC `RTCDataChannel`, `WebSocket`, and `BroadcastChannel`, plus headless runtimes (Node.js 22+, Bun, Deno) via injected `RTCPeerConnection` (and optional `WebSocket`).
|
|
108
|
+
- Password-encrypted signaling (`mqttSignaling`, `nostrSignaling`, default `wsSignaling`) and `createIdentity()` use Web Crypto (`crypto.subtle`), which in browsers requires `https://` or `http://localhost` (`127.0.0.1`).
|
|
587
109
|
|
|
588
110
|
## License
|
|
589
111
|
|
|
590
|
-
MIT — see [LICENSE](LICENSE).
|
|
112
|
+
MIT — see [LICENSE](https://github.com/dimchansky/meshpost/blob/main/LICENSE).
|