@dimchansky/meshpost 0.1.0 → 0.3.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 CHANGED
@@ -76,7 +76,7 @@ Meshpost connects browsers directly to send small binary packets (up to 16 KiB)
76
76
  3. Use `createChannel` when your app has multiple message types (so modules do not collide):
77
77
 
78
78
  ```ts
79
- import { createChannel } from './dist/index.js'
79
+ import { createChannel } from '@dimchansky/meshpost'
80
80
 
81
81
  const cursors = createChannel(room, 'cursor', { delivery: 'unreliable' })
82
82
  const chat = createChannel(room, 'chat', { delivery: 'reliable' })
@@ -95,17 +95,20 @@ Meshpost connects browsers directly to send small binary packets (up to 16 KiB)
95
95
 
96
96
  Browsers need a signaling adapter only to find each other and start the connection. After that, data travels directly between browsers.
97
97
 
98
- | Adapter | Best for | Server needed? |
99
- | --------------------------- | ------------------------------------------------------------------------------ | ------------------ |
100
- | `mqttSignaling(options?)` | Different browsers, devices, and networks out of the box | No (public relays) |
101
- | `tabSignaling()` | Multiple tabs in the same browser profile (works offline) | No |
102
- | `manualSignaling(outgoing)` | Completely offline browsers (no network needed) by copying and pasting text | No |
103
- | Custom `Signaling` | Production apps with your own server (such as WebSocket or Server-Sent Events) | Your server |
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 |
104
107
 
105
108
  ### Local tabs (`tabSignaling`)
106
109
 
107
110
  ```ts
108
- import { joinRoom, tabSignaling } from './dist/index.js'
111
+ import { joinRoom, tabSignaling } from '@dimchansky/meshpost'
109
112
 
110
113
  const room = joinRoom('arena', {
111
114
  appId: 'my-game',
@@ -116,7 +119,7 @@ const room = joinRoom('arena', {
116
119
  ### Offline copy-paste (`manualSignaling`)
117
120
 
118
121
  ```ts
119
- import { joinRoom, manualSignaling } from './dist/index.js'
122
+ import { joinRoom, manualSignaling } from '@dimchansky/meshpost'
120
123
 
121
124
  const manual = manualSignaling((toPeerId, replyText) => {
122
125
  // Show replyText to the user to send to `toPeerId`.
@@ -133,7 +136,7 @@ manual.accept(pastedTextFromPeer) // Paste incoming contact cards and replies he
133
136
  manual.forget(oldPeerId) // Optional: stop retrying an old contact.
134
137
  ```
135
138
 
136
- > **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()` and `manualSignaling()` support `password` everywhere.)
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.)
137
140
 
138
141
  ## Public API reference
139
142
 
@@ -157,19 +160,114 @@ Creates a room, assigns a random peer ID (`room.id`), and immediately starts loo
157
160
 
158
161
  ### `Room`
159
162
 
160
- | Member | Description |
161
- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
162
- | `room.id` | Your peer ID (`string`). A page reload creates a new peer ID. |
163
- | `room.peers` | Current list of connected peer IDs (returns a fresh copy each time). |
164
- | `room.signalingState` | Current adapter state: `'connecting' \| 'online' \| 'offline' \| 'closed'`. |
165
- | `room.send(bytes, options?: SendOptions)` | Sends a `Uint8Array`. `options` accepts `{ to?: string, delivery?: Delivery }` (`Delivery` is `'unreliable' \| 'reliable'`, default `'unreliable'`). Returns `ReadonlyMap<string, SendResult>`. |
166
- | `room.getStats(peerId)` | Returns `Promise<PeerStats \| null>` with ping, route, byte counts, and send buffer sizes (`null` if not connected). |
167
- | `room.onPacket((from, bytes, delivery) => ...)` | Runs when a packet arrives. Returns an unsubscribe function. |
168
- | `room.onDrain((peerId, delivery) => ...)` | Runs when a full send buffer has space again (after `send()` returned `'busy'`). Returns unsubscribe. |
169
- | `room.onPeerJoin((peerId) => ...)` | Runs when a peer finishes connecting and is ready to exchange packets. Returns unsubscribe. |
170
- | `room.onPeerLeave((peerId) => ...)` | Runs when a connected peer disconnects. Returns unsubscribe. |
171
- | `room.onSignalingChange((state, reason?) => ...)` | Runs on future `signalingState` changes. Returns unsubscribe. |
172
- | `room.leave()` | Leaves the room, tells peers you left, and closes all connections. Safe to call more than once. |
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.
183
+
184
+ `room.onError` emits a `RoomError` object: `{ code: RoomErrorCode, message: string, peerId?: string }`.
185
+
186
+ ### `createVoice(room, options?: VoiceOptions)`
187
+
188
+ Headless P2P voice chat controller built on top of `room.addStream()` / `room.onPeerStream()`:
189
+
190
+ - 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).
191
+ - 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.
192
+ - 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
+ - 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
+
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). |
205
+
206
+ | `Voice` member | Description |
207
+ | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
208
+ | `voice.micStatus` | Current `MicStatus`: `'off' \| 'requesting' \| 'live' \| 'muted' \| 'error'`. |
209
+ | `voice.micError` | `MicError \| null` (`{ code: MicErrorCode, message: string }`; codes: `'permission-denied' \| 'not-found' \| 'in-use' \| 'insecure-context' \| 'room-closed' \| 'unknown'`). |
210
+ | `voice.autoplayBlocked` | `true` while any incoming `<audio>` element was blocked by browser Autoplay Policy and awaits a user gesture. |
211
+ | `voice.deafened` | Whether incoming peer audio is muted locally. |
212
+ | `voice.volume` | Current incoming playback volume (`0` to `1`). |
213
+ | `voice.selfSpeaking` | `true` when local microphone is `'live'` and exceeds `speakingThreshold`. |
214
+ | `voice.remotePeers` | Snapshot array of peer IDs currently sending audio. |
215
+ | `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`). |
217
+ | `voice.toggleMic()` | Acquires mic on first call (`'off' \| 'error'` → `'requesting'` → `'live'`), or toggles soft-mute (`'live'` ↔ `'muted'`). Coalesces concurrent `'requesting'` calls. |
218
+ | `voice.startMic()` | Acquires mic if inactive, or unmutes if `'muted'`. Coalesces concurrent `'requesting'` calls; resolves to `'off'` if closed. |
219
+ | `voice.setMuted(muted)` | Soft-mutes (`true`) or unmutes (`false`) an already-acquired mic (`'live' \| 'muted'`). No-op otherwise. |
220
+ | `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). |
222
+ | `voice.setDeafened(deafened)` | Mutes (`true`) or unmutes (`false`) incoming remote `<audio>` elements locally (unmuting also calls `unlockAudio()`). |
223
+ | `voice.unlockAudio()` | Synchronously retries `AudioContext.resume()` and `audio.play()` on paused remote streams (e.g. from a custom unlock banner click). |
224
+ | `voice.onChange(fn, options?: ListenOptions)` | Subscribes to `VoiceSnapshot` changes (`(snapshot: VoiceSnapshot) => ...`). Returns unsubscribe. |
225
+ | `voice.close()` | Releases mic tracks, removes hidden `<audio>` elements, closes `AudioContext`, restores `audioSession`, and detaches all listeners (runs automatically on `room.leave()`). |
226
+
227
+ Exported voice types: `Voice`, `VoiceOptions`, `VoiceSnapshot`, `MicStatus`, `MicError`, `MicErrorCode`.
228
+
229
+ ```ts
230
+ import { createVoice } from '@dimchansky/meshpost'
231
+
232
+ const voice = createVoice(room)
233
+
234
+ // Synchronous state inspection (e.g. exit Pointer Lock in 3D games only before first permission prompt)
235
+ if (voice.micStatus === 'off' || voice.micStatus === 'error') {
236
+ document.exitPointerLock?.()
237
+ }
238
+ await voice.toggleMic() // 1st call: getUserMedia + addStream ('live'); next calls: soft-mute ('muted' <-> 'live')
239
+
240
+ voice.onChange((snap) => {
241
+ // snap: { micStatus, micError, autoplayBlocked, deafened, volume, selfSpeaking, remotePeers, speakingPeers }
242
+ if (snap.autoplayBlocked) showUnlockBanner()
243
+ })
244
+
245
+ voice.setVolume(0.8)
246
+ voice.setDeafened(false)
247
+ voice.stopMic() // Release microphone hardware while staying in the room (voice.close() runs automatically on room.leave())
248
+ ```
249
+
250
+ #### Low-level `MediaStream` API (`addStream` / `onPeerStream`)
251
+
252
+ For custom video, screen sharing, or bespoke audio pipelines, use the low-level `Room` methods directly:
253
+
254
+ ```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)
257
+
258
+ room.onPeerStream((peerId, stream) => {
259
+ const audio = new Audio()
260
+ audio.srcObject = stream
261
+ audio.play()
262
+ })
263
+ room.onPeerStreamEnd((peerId, stream) => console.log('Stream ended:', peerId, stream.id))
264
+
265
+ // Later: detach from room and stop local microphone tracks yourself.
266
+ room.removeStream(mic)
267
+ for (const track of mic.getTracks()) track.stop()
268
+ ```
269
+
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.
173
271
 
174
272
  ### `SendResult`
175
273
 
@@ -201,27 +299,58 @@ Creates a named message stream (such as `'chat'` or `'cursor'`) on your existing
201
299
 
202
300
  - `name`: 1–64 UTF-8 bytes. Uses `1 + nameBytes.length` bytes of the 16,384-byte packet limit.
203
301
  - `options` (`ChannelOptions`): `{ delivery?: Delivery }`. Defaults to `'unreliable'`.
204
- - Returns a `Channel` with `{ name, delivery, send(bytes, options?: ChannelSendOptions), onPacket((from, bytes) => ...) }` (`ChannelSendOptions` is `{ to?: string }`).
302
+ - Returns a `Channel` with `{ name, delivery, send(bytes, options?: ChannelSendOptions), onPacket((from, bytes) => ..., options?: ListenOptions) }` (`ChannelSendOptions` is `{ to?: string }`).
303
+
304
+ ### `createBlobChannel(room, name, options?: BlobChannelOptions)`
305
+
306
+ 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`.
307
+
308
+ - `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.
309
+ - 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 }`.
310
+ - `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'`).
311
+
312
+ ```ts
313
+ import { createBlobChannel } from '@dimchansky/meshpost'
314
+
315
+ const files = createBlobChannel(room, 'file', { maxReceiveBytes: 8 * 1024 * 1024 })
316
+ files.onProgress((from, { receivedBytes, totalBytes }) =>
317
+ console.log(from, receivedBytes, totalBytes)
318
+ )
319
+ files.onBlob((from, bytes) => console.log('Received', bytes.byteLength, 'bytes from', from))
320
+
321
+ const results = await files.send(fileBytes, {
322
+ onProgress: (peerId, sent, total) => console.log(peerId, sent, total)
323
+ })
324
+ ```
205
325
 
206
326
  ### Signaling exports
207
327
 
208
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.
330
+ - `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
+ - `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())`).
209
332
  - `tabSignaling()` — Connects tabs open to the same site (same protocol, domain, and port) in the same browser. Works offline with no server.
210
333
  - `manualSignaling(outgoing)` — Connects completely offline browsers by copying and pasting text. Returns `{ signaling, contact(), accept(text), forget(peerId) }`.
211
334
  - `defaultIceServers` — Built-in Cloudflare and Google public servers (STUN) that help browsers find their public network address.
212
- - Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `Signal`, `ManualSignaling`, `MqttSignalingOptions`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
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).
213
336
 
214
337
  ## Connecting through strict firewalls (TURN)
215
338
 
216
339
  - 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.
217
340
  - 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).
218
- - Add your TURN credentials without replacing the default servers:
341
+ - 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):
219
342
 
220
343
  ```ts
344
+ import { fetchTurnCredentials, joinRoom, mqttSignaling, withLocalTabs } from '@dimchansky/meshpost'
345
+
346
+ const turnConfig = await fetchTurnCredentials('https://your-turn.workers.dev', {
347
+ accessKey: 'shared-key'
348
+ })
349
+
221
350
  const room = joinRoom('lobby', {
222
351
  appId: 'my-app',
223
- signaling: mqttSignaling(),
224
- turnConfig: [{ urls: 'turns:turn.example.org:5349', username: 'user', credential: 'secret' }]
352
+ signaling: withLocalTabs(mqttSignaling()),
353
+ turnConfig
225
354
  })
226
355
  ```
227
356
 
@@ -249,14 +378,21 @@ npm run demo
249
378
 
250
379
  Open **dist/playground.html** directly in two browsers (`file://`). Enter the same room name and click **Join room**.
251
380
 
252
- - By default, `dist/playground.html` uses `mqttSignaling()` when opened via `file://` or hosted on a public `https://` origin (such as GitHub Pages).
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).
253
382
  - For completely offline copy-paste exchange with zero network requests, open `dist/playground.html#mode=manual` (or click **Offline mode** on the join screen).
254
- - When hosted on `localhost` or a LAN host without the demo's local `/events` relay server, it automatically falls back to `tabSignaling()` (same-browser tabs only).
383
+ - 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).
255
384
 
256
385
  ### Read the example code
257
386
 
258
- - [examples/playground/app.js](examples/playground/app.js) — Shows `joinRoom` (with auto-generated password and invite links), `createChannel('pointer')` (unreliable cursor and click ripples, ignoring out-of-order updates), `createChannel('draw')` (reliable collaborative canvas strokes, late-join snapshots, and clear actions), `createChannel('chat')` (group messages), `createChannel('direct')` (private messages to one peer), `createChannel('profile')` (display names without a server), `room.getStats()` (live ping and route tooltips), checking `SendResult`, and manual exchange.
259
- - [examples/playground/relay.js](examples/playground/relay.js) — Shows how to write a custom `Signaling` adapter using Server-Sent Events with a fallback to `tabSignaling()`.
387
+ All `@dimchansky/meshpost` usage in the playground is intentionally concentrated in **one file** so you can learn the full API in one place:
388
+
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()`.
390
+ - [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.
392
+ - [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()`.
394
+ - [examples/playground/session.js](examples/playground/session.js) — Compact `#c=` invite URLs and `sessionStorage` auto-rejoin.
395
+ - [examples/playground/app.js](examples/playground/app.js) — Thin UI controller connecting DOM controls to `mesh.js` and the helper modules.
260
396
  - [examples/playground/index.html](examples/playground/index.html) — Minimal HTML markup for the playground.
261
397
  - [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.
262
398
 
@@ -268,7 +404,7 @@ Open **dist/playground.html** directly in two browsers (`file://`). Enter the sa
268
404
  | `examples/playground/` | Interactive demo source |
269
405
  | `examples/turn-worker/` | Optional Cloudflare Worker credential broker for Metered, CF TURN, or `coturn` |
270
406
  | `examples/build.mjs` | Bundles the playground into one portable HTML file |
271
- | `examples/serve.mjs` | Local dev server with a Server-Sent Events signaling relay |
407
+ | `examples/serve.mjs` | Local dev server with WebSocket (`/ws`) and SSE signaling relays |
272
408
  | `tests/` | Playwright E2E tests using real browser WebRTC data channels |
273
409
  | `dist/` | Built ES modules, `.d.ts` declarations, and `playground.html` |
274
410
 
package/dist/blob.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ import type { ListenOptions, Room } from './room.js';
2
+ export interface BlobChannelOptions {
3
+ /** Maximum total bytes accepted for a single incoming blob. @default 4194304 (4 MiB) */
4
+ maxReceiveBytes?: number;
5
+ /** Maximum payload bytes per chunk (must fit within the 16 KiB channel budget). @default 15360 */
6
+ chunkSize?: number;
7
+ /** Inactivity timeout in milliseconds for an incomplete incoming transfer. @default 30000 */
8
+ receiveTimeoutMs?: number;
9
+ /** Maximum simultaneous incoming transfers tracked per peer. @default 4 */
10
+ maxConcurrentPerPeer?: number;
11
+ }
12
+ export interface BlobSendOptions {
13
+ /** Optional target peer ID. Omit to send to all currently connected peers. */
14
+ to?: string;
15
+ /** Optional progress callback invoked per recipient as chunks are accepted. */
16
+ onProgress?: (peerId: string, sentBytes: number, totalBytes: number) => void;
17
+ /** Optional AbortSignal to cancel in-flight sending. */
18
+ signal?: AbortSignal;
19
+ }
20
+ /** Final per-recipient outcome returned by `blobChannel.send()`. */
21
+ export type BlobSendStatus = 'sent' | 'aborted' | 'unavailable' | 'too-large';
22
+ /** Progress snapshot emitted by `blobChannel.onProgress()`. */
23
+ export interface BlobProgress {
24
+ readonly transferId: number;
25
+ readonly receivedBytes: number;
26
+ readonly totalBytes: number;
27
+ }
28
+ /** Chunked reliable binary transfer helper built on top of a Room and Channel. */
29
+ export interface BlobChannel {
30
+ /** Logical channel name. */
31
+ readonly name: string;
32
+ /** Send a Uint8Array of arbitrary size (including 0 bytes). Resolves with per-peer final status. */
33
+ send(bytes: Uint8Array, options?: BlobSendOptions): Promise<ReadonlyMap<string, BlobSendStatus>>;
34
+ /** Subscribe to completed incoming blobs. Returns an unsubscribe function. */
35
+ onBlob(fn: (from: string, bytes: Uint8Array) => void, options?: ListenOptions): () => void;
36
+ /** Subscribe to incoming transfer progress updates. Returns an unsubscribe function. */
37
+ onProgress(fn: (from: string, progress: BlobProgress) => void, options?: ListenOptions): () => void;
38
+ /** Detach internal room listeners and cancel all active incoming/outgoing transfers. */
39
+ close(): void;
40
+ }
41
+ /**
42
+ * Create a chunked reliable binary channel for payloads larger than Meshpost's 16 KiB packet limit.
43
+ * Built strictly on top of `createChannel(room, name, { delivery: 'reliable' })` and `room.onDrain`.
44
+ */
45
+ export declare function createBlobChannel(room: Room, name: string, options?: BlobChannelOptions): BlobChannel;