@dimchansky/meshpost 0.2.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 +86 -12
- package/dist/combine.d.ts +12 -1
- package/dist/combine.js +304 -213
- package/dist/index.d.ts +5 -1
- package/dist/index.js +3 -1
- package/dist/room.d.ts +6 -0
- package/dist/room.js +75 -6
- package/dist/signaling.d.ts +5 -0
- package/dist/tabs.js +8 -1
- package/dist/turn.d.ts +13 -0
- package/dist/turn.js +213 -0
- package/dist/voice.d.ts +81 -0
- package/dist/voice.js +838 -0
- package/docs/behavior.md +20 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -101,7 +101,8 @@ Browsers need a signaling adapter only to find each other and start the connecti
|
|
|
101
101
|
| `wsSignaling(url, options?)` | Production apps with your own WebSocket signaling server (`wss://`) | Your WS server |
|
|
102
102
|
| `tabSignaling()` | Multiple tabs in the same browser profile (works offline) | No |
|
|
103
103
|
| `manualSignaling(outgoing)` | Completely offline browsers (no network needed) by copying and pasting text | No |
|
|
104
|
-
| `
|
|
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 |
|
|
105
106
|
| Custom `Signaling` | Custom transports (such as Server-Sent Events or an existing backend channel) | Your server |
|
|
106
107
|
|
|
107
108
|
### Local tabs (`tabSignaling`)
|
|
@@ -178,11 +179,77 @@ Creates a room, assigns a random peer ID (`room.id`), and immediately starts loo
|
|
|
178
179
|
| `room.onPeerStreamEnd(fn, options?: ListenOptions)` | Runs when a remote peer removes a `MediaStream` or disconnects (`(peerId, stream) => ...`). Returns unsubscribe. |
|
|
179
180
|
| `room.leave()` | Leaves the room, tells peers you left, and closes all connections. Safe to call more than once. |
|
|
180
181
|
|
|
181
|
-
All `on*` methods (on `Room`, `Channel`, and `
|
|
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.
|
|
182
183
|
|
|
183
184
|
`room.onError` emits a `RoomError` object: `{ code: RoomErrorCode, message: string, peerId?: string }`.
|
|
184
185
|
|
|
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:
|
|
186
253
|
|
|
187
254
|
```ts
|
|
188
255
|
const mic = await navigator.mediaDevices.getUserMedia({ audio: true })
|
|
@@ -200,7 +267,7 @@ room.removeStream(mic)
|
|
|
200
267
|
for (const track of mic.getTracks()) track.stop()
|
|
201
268
|
```
|
|
202
269
|
|
|
203
|
-
> **Note:** `removeStream()` does not stop local `MediaStreamTrack`s (call `track.stop()` when done), and streams with 0 tracks or tracks added to a `MediaStream` _after_ `addStream()` are not renegotiated automatically.
|
|
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.
|
|
204
271
|
|
|
205
272
|
### `SendResult`
|
|
206
273
|
|
|
@@ -260,7 +327,8 @@ const results = await files.send(fileBytes, {
|
|
|
260
327
|
|
|
261
328
|
- `mqttSignaling({ urls?, appId?, password?, handshakeTimeoutMs? })` — Connects browsers across different devices and networks using built-in public MQTT relay servers (`defaultMqttRelays`).
|
|
262
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.
|
|
263
|
-
- `
|
|
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())`).
|
|
264
332
|
- `tabSignaling()` — Connects tabs open to the same site (same protocol, domain, and port) in the same browser. Works offline with no server.
|
|
265
333
|
- `manualSignaling(outgoing)` — Connects completely offline browsers by copying and pasting text. Returns `{ signaling, contact(), accept(text), forget(peerId) }`.
|
|
266
334
|
- `defaultIceServers` — Built-in Cloudflare and Google public servers (STUN) that help browsers find their public network address.
|
|
@@ -270,13 +338,19 @@ const results = await files.send(fileBytes, {
|
|
|
270
338
|
|
|
271
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.
|
|
272
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).
|
|
273
|
-
- Add your TURN credentials
|
|
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):
|
|
274
342
|
|
|
275
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
|
+
|
|
276
350
|
const room = joinRoom('lobby', {
|
|
277
351
|
appId: 'my-app',
|
|
278
|
-
signaling: mqttSignaling(),
|
|
279
|
-
turnConfig
|
|
352
|
+
signaling: withLocalTabs(mqttSignaling()),
|
|
353
|
+
turnConfig
|
|
280
354
|
})
|
|
281
355
|
```
|
|
282
356
|
|
|
@@ -304,7 +378,7 @@ npm run demo
|
|
|
304
378
|
|
|
305
379
|
Open **dist/playground.html** directly in two browsers (`file://`). Enter the same room name and click **Join room**.
|
|
306
380
|
|
|
307
|
-
- By default, `dist/playground.html` uses `mqttSignaling()` when opened via `file://`
|
|
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).
|
|
308
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).
|
|
309
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).
|
|
310
384
|
|
|
@@ -312,12 +386,12 @@ Open **dist/playground.html** directly in two browsers (`file://`). Enter the sa
|
|
|
312
386
|
|
|
313
387
|
All `@dimchansky/meshpost` usage in the playground is intentionally concentrated in **one file** so you can learn the full API in one place:
|
|
314
388
|
|
|
315
|
-
- [examples/playground/mesh.js](examples/playground/mesh.js) — **Start here.** Single facade wiring `joinRoom()`, signaling adapters (`
|
|
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()`.
|
|
316
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.
|
|
317
391
|
- [examples/playground/codec.js](examples/playground/codec.js) — Pure binary codecs for pointer updates, canvas strokes, and file metadata envelopes.
|
|
318
392
|
- [examples/playground/canvas.js](examples/playground/canvas.js) — Collaborative 2D drawing canvas and remote cursor/ripple overlays.
|
|
319
|
-
- [examples/playground/voice.js](examples/playground/voice.js) —
|
|
320
|
-
- [examples/playground/session.js](examples/playground/session.js) — Compact `#c=` invite URLs
|
|
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.
|
|
321
395
|
- [examples/playground/app.js](examples/playground/app.js) — Thin UI controller connecting DOM controls to `mesh.js` and the helper modules.
|
|
322
396
|
- [examples/playground/index.html](examples/playground/index.html) — Minimal HTML markup for the playground.
|
|
323
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.
|
package/dist/combine.d.ts
CHANGED
|
@@ -1,7 +1,18 @@
|
|
|
1
1
|
import type { Signaling } from './signaling.js';
|
|
2
2
|
/**
|
|
3
3
|
* Combine multiple signaling adapters into one composite adapter.
|
|
4
|
-
* Merges peer rosters across all children, routes signals to
|
|
4
|
+
* Merges peer rosters across all children, routes signals to reachable children that advertise the target peer,
|
|
5
5
|
* and stays `'online'` as long as at least one child adapter is `'online'`.
|
|
6
6
|
*/
|
|
7
7
|
export declare function combineSignaling(...adapters: readonly Signaling[]): Signaling;
|
|
8
|
+
/**
|
|
9
|
+
* Decorate a network signaling adapter (`mqttSignaling()`, `wsSignaling()`, etc.) with instant
|
|
10
|
+
* same-browser `BroadcastChannel` discovery (`tabSignaling()`).
|
|
11
|
+
*
|
|
12
|
+
* - Exposes `primary`'s `SignalingState` and errors for `room.signalingState` / `room.onSignalingChange`
|
|
13
|
+
* (avoiding a permanently `'online'` indicator when network connectivity is lost).
|
|
14
|
+
* - Still connects same-browser tabs locally even while `primary` is `'connecting'` or `'offline'`.
|
|
15
|
+
* - Safely falls back to `primary` alone when `BroadcastChannel` is unavailable, on `file:` / opaque
|
|
16
|
+
* origins, or if `new BroadcastChannel(...)` throws `SecurityError`.
|
|
17
|
+
*/
|
|
18
|
+
export declare function withLocalTabs(primary: Signaling): Signaling;
|