@dimchansky/meshpost 0.4.0 → 0.4.2

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
@@ -32,15 +32,16 @@ Meshpost connects peers directly over WebRTC to exchange binary packets, typed m
32
32
  2. Import `joinRoom` and a signaling adapter (used only to help browsers find each other) in your browser app (use `@dimchansky/meshpost` if installed as a package, or `./dist/index.js` from a local build):
33
33
 
34
34
  ```ts
35
- import { joinRoom, mqttSignaling } from '@dimchansky/meshpost'
35
+ import { joinRoom, publicSignaling } from '@dimchansky/meshpost'
36
36
 
37
37
  const encoder = new TextEncoder()
38
38
  const decoder = new TextDecoder()
39
39
 
40
- // Join a room. Browsers with the same appId and room name connect automatically.
40
+ // Join a room. Browsers with the same appId and room name connect automatically
41
+ // over local tabs + public MQTT + port-443 Nostr relays (plus optional wsUrls).
41
42
  const room = joinRoom('lobby', {
42
43
  appId: 'my-chat-app',
43
- signaling: mqttSignaling()
44
+ signaling: publicSignaling()
44
45
  })
45
46
 
46
47
  room.onPeerJoin((peerId) => console.log('Joined:', peerId))
@@ -92,16 +93,18 @@ Meshpost connects peers directly over WebRTC to exchange binary packets, typed m
92
93
 
93
94
  Browsers need a signaling adapter only to find each other and start the connection. After that, data travels directly between browsers.
94
95
 
95
- | Adapter | Best for | Server needed? |
96
- | ---------------------------- | ----------------------------------------------------------------------------- | ------------------- |
97
- | `mqttSignaling(options?)` | Different browsers, devices, and networks out of the box | No (public relays) |
98
- | `nostrSignaling(options?)` | Corporate/school Wi-Fi blocking MQTT ports (runs over port-443 `wss://`) | No (public relays) |
99
- | `wsSignaling(url, options?)` | Production apps with your own WebSocket relay (see `examples/ws-worker/`) | Your WS / CF Worker |
100
- | `tabSignaling()` | Multiple tabs in the same browser profile (works offline) | No |
101
- | `manualSignaling(outgoing)` | Completely offline browsers (no network needed) by copying and pasting text | No |
102
- | `withLocalTabs(primary)` | Instant same-browser tabs + remote MQTT/Nostr/WS with accurate network state | Same as `primary` |
103
- | `combineSignaling(...list)` | Composing multiple network adapters (e.g. `mqttSignaling` + `nostrSignaling`) | Depends on list |
104
- | Custom `Signaling` | Custom transports (such as Server-Sent Events or an existing backend channel) | Your server |
96
+ | Adapter | Best for | Server needed? |
97
+ | --------------------------------- | ------------------------------------------------------------------------------------- | ------------------- |
98
+ | `publicSignaling(options?)` | All-in-one preset: local tabs + MQTT + port-443 Nostr + optional fast `wsUrls` | No (optional WS) |
99
+ | `mqttSignaling(options?)` | Different browsers, devices, and networks out of the box | No (public relays) |
100
+ | `nostrSignaling(options?)` | Corporate/school Wi-Fi blocking MQTT ports (runs over port-443 `wss://`) | No (public relays) |
101
+ | `wsSignaling(url, options?)` | Production apps with a primary WebSocket relay (see `examples/ws-worker/`) | Your WS / CF Worker |
102
+ | `optionalWsSignaling(url, opts?)` | Opportunistic WS fast-path inside `combineSignaling` (silent fallback if unreachable) | Optional WS |
103
+ | `tabSignaling()` | Multiple tabs in the same browser profile (works offline) | No |
104
+ | `manualSignaling(outgoing)` | Completely offline browsers (no network needed) by copying and pasting text | No |
105
+ | `withLocalTabs(primary)` | Instant same-browser tabs + remote MQTT/Nostr/WS with accurate network state | Same as `primary` |
106
+ | `combineSignaling(...list)` | Composing multiple network adapters (e.g. `mqttSignaling` + `nostrSignaling`) | Depends on list |
107
+ | Custom `Signaling` | Custom transports (such as Server-Sent Events or an existing backend channel) | Your server |
105
108
 
106
109
  ### Local tabs (`tabSignaling`)
107
110
 
@@ -182,7 +185,7 @@ Creates a room, assigns a random peer ID (`room.id`), and immediately starts loo
182
185
  | `room.onPeerStreamEnd(fn, options?: ListenOptions)` | Runs when a remote peer removes a `MediaStream` or disconnects (`(peerId, stream, meta: PeerStreamMeta) => ...`). Returns unsubscribe. |
183
186
  | `room.leave()` | Leaves the room, tells peers you left, and closes all connections. Safe to call more than once. |
184
187
 
185
- 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.
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.
186
189
 
187
190
  `room.onError` emits a `RoomError` object: `{ code: RoomErrorCode, message: string, peerId?: string }`.
188
191
 
@@ -239,33 +242,34 @@ Headless P2P voice chat controller built on top of `room.addStream()` / `room.on
239
242
  | `streamTag` | `string` | `'voice'` | Stream tag attached to outgoing mic streams and matched on incoming streams (`[a-zA-Z0-9._-]{1,32}`). |
240
243
  | `strictStreamTag` | `boolean` | `false` | When `true`, also ignore untagged (`meta.tag === undefined`) incoming audio streams. |
241
244
 
242
- | `Voice` member | Description |
243
- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
244
- | `voice.micStatus` | Current `MicStatus`: `'off' \| 'requesting' \| 'live' \| 'muted' \| 'error'`. |
245
- | `voice.micError` | `MicError \| null` (`{ code: MicErrorCode, message: string }`; codes: `'permission-denied' \| 'not-found' \| 'in-use' \| 'insecure-context' \| 'room-closed' \| 'unknown'`). |
246
- | `voice.deviceId` | Active or selected microphone `deviceId` (`string`), or `null` for system default. |
247
- | `voice.autoplayBlocked` | `true` while any incoming `<audio>` element was blocked by browser Autoplay Policy and awaits a user gesture. |
248
- | `voice.deafened` | Whether incoming peer audio is muted locally. |
249
- | `voice.volume` | Current master incoming playback volume (`0` to `1`). |
250
- | `voice.selfSpeaking` | `true` when local microphone is `'live'` and exceeds `speakingThreshold`. |
251
- | `voice.remotePeers` | Snapshot array of peer IDs currently sending voice audio. |
252
- | `voice.speakingPeers` | Snapshot array of remote peer IDs currently exceeding `speakingThreshold`. |
253
- | `voice.mutedPeers` | Snapshot array of remote peer IDs locally muted via `voice.setPeerMuted(peerId, true)`. |
254
- | `voice.getSnapshot()` | Returns an immutable `VoiceSnapshot` object with all 10 state fields above (`Voice extends VoiceSnapshot`). |
255
- | `voice.toggleMic()` | Acquires mic on first call (`'off' \| 'error'` → `'requesting'` → `'live'`), or toggles soft-mute (`'live'` ↔ `'muted'`). Coalesces concurrent `'requesting'` calls. |
256
- | `voice.startMic()` | Acquires mic if inactive, or unmutes if `'muted'`. Coalesces concurrent `'requesting'` calls; resolves to `'off'` if closed. |
257
- | `voice.setMuted(muted)` | Soft-mutes (`true`) or unmutes (`false`) an already-acquired mic (`'live' \| 'muted'`). No-op otherwise. |
258
- | `voice.stopMic()` | Detaches stream from room (`removeStream`), cancels any pending `getUserMedia`, and stops hardware tracks (`track.stop()`). |
259
- | `voice.switchDevice(deviceId?)` | Selects or hot-swaps microphone device (`string \| null \| undefined`) via `room.replaceStreamTrack()` with zero WebRTC SDP renegotiation (`Promise<MicStatus>`). |
260
- | `voice.setVolume(volume)` | Sets master incoming playback volume (`0` to `1`, clamped; throws `RangeError` if non-finite). |
261
- | `voice.setPeerVolume(peerId, volume)` | Sets local playback volume (`0` to `1`, clamped, scaled by master `voice.volume`) for one peer. |
262
- | `voice.getPeerVolume(peerId)` | Returns configured local playback volume (`0` to `1`, default `1`) for `peerId`. |
263
- | `voice.setDeafened(deafened)` | Mutes (`true`) or unmutes (`false`) incoming remote `<audio>` elements locally (unmuting also calls `unlockAudio()`). |
264
- | `voice.setPeerMuted(peerId, muted)` | Locally mutes (`true`) or unmutes (`false`) incoming audio from one peer (independent of `deafened`). |
265
- | `voice.isPeerMuted(peerId)` | Returns whether `peerId` is locally muted via `setPeerMuted()`. |
266
- | `voice.unlockAudio()` | Synchronously retries `AudioContext.resume()` and `audio.play()` on paused remote streams (e.g. from a custom unlock banner click). |
267
- | `voice.onChange(fn, options?: ListenOptions)` | Subscribes to `VoiceSnapshot` changes (`(snapshot: VoiceSnapshot) => ...`). Returns unsubscribe. |
268
- | `voice.close()` | Releases mic tracks, removes hidden `<audio>` elements, closes `AudioContext`, restores `audioSession`, and detaches all listeners (runs automatically on `room.leave()`). |
245
+ | `Voice` member | Description |
246
+ | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
247
+ | `voice.micStatus` | Current `MicStatus`: `'off' \| 'requesting' \| 'live' \| 'muted' \| 'error'`. |
248
+ | `voice.micError` | `MicError \| null` (`{ code: MicErrorCode, message: string }`; codes: `'permission-denied' \| 'not-found' \| 'in-use' \| 'insecure-context' \| 'room-closed' \| 'unknown'`). |
249
+ | `voice.deviceId` | Active or selected microphone `deviceId` (`string`), or `null` for system default. |
250
+ | `voice.autoplayBlocked` | `true` while any incoming `<audio>` element was blocked by browser Autoplay Policy and awaits a user gesture. |
251
+ | `voice.deafened` | Whether incoming peer audio is muted locally. |
252
+ | `voice.volume` | Current master incoming playback volume (`0` to `1`). |
253
+ | `voice.selfSpeaking` | `true` when local microphone is `'live'` and exceeds `speakingThreshold`. |
254
+ | `voice.remotePeers` | Snapshot array of peer IDs currently sending voice audio. |
255
+ | `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). |
256
+ | `voice.mutedPeers` | Snapshot array of remote peer IDs locally muted via `voice.setPeerMuted(peerId, true)`. |
257
+ | `voice.peerVolumes` | Sparse read-only map (`Readonly<Record<string, number>>`) of overridden per-peer playback volumes (`!== 1`; omitted peers default to `1`). |
258
+ | `voice.getSnapshot()` | Returns an immutable `VoiceSnapshot` object with all 11 state fields above (`Voice extends VoiceSnapshot`). |
259
+ | `voice.toggleMic()` | Acquires mic on first call (`'off' \| 'error'` → `'requesting'` → `'live'`), or toggles soft-mute (`'live'` ↔ `'muted'`). Coalesces concurrent `'requesting'` calls. |
260
+ | `voice.startMic()` | Acquires mic if inactive, or unmutes if `'muted'`. Coalesces concurrent `'requesting'` calls; resolves to `'off'` if closed. |
261
+ | `voice.setMuted(muted)` | Soft-mutes (`true`) or unmutes (`false`) an already-acquired mic (`'live' \| 'muted'`). No-op otherwise. |
262
+ | `voice.stopMic()` | Detaches stream from room (`removeStream`), cancels any pending `getUserMedia`, and stops hardware tracks (`track.stop()`). |
263
+ | `voice.switchDevice(deviceId?)` | Selects or hot-swaps microphone device (`string \| null \| undefined`) via `room.replaceStreamTrack()` with zero WebRTC SDP renegotiation (`Promise<MicStatus>`). |
264
+ | `voice.setVolume(volume)` | Sets master incoming playback volume (`0` to `1`, clamped; throws `RangeError` if non-finite). |
265
+ | `voice.setPeerVolume(peerId, volume)` | Sets local playback volume (`0` to `1`, clamped, scaled by master `voice.volume`) for one peer. |
266
+ | `voice.getPeerVolume(peerId)` | Returns configured local playback volume (`0` to `1`, default `1`) for `peerId`. |
267
+ | `voice.setDeafened(deafened)` | Mutes (`true`) or unmutes (`false`) incoming remote `<audio>` elements locally (unmuting also calls `unlockAudio()`). |
268
+ | `voice.setPeerMuted(peerId, muted)` | Locally mutes (`true`) or unmutes (`false`) incoming audio from one peer (independent of `deafened`). |
269
+ | `voice.isPeerMuted(peerId)` | Returns whether `peerId` is locally muted via `setPeerMuted()`. |
270
+ | `voice.unlockAudio()` | Synchronously retries `AudioContext.resume()` and `audio.play()` on paused remote streams (e.g. from a custom unlock banner click). |
271
+ | `voice.onChange(fn, options?: ListenOptions)` | Subscribes to `VoiceSnapshot` changes (`(snapshot: VoiceSnapshot) => ...`). Returns unsubscribe. |
272
+ | `voice.close()` | Releases mic tracks, removes hidden `<audio>` elements, closes `AudioContext`, restores `audioSession`, and detaches all listeners (runs automatically on `room.leave()`). |
269
273
 
270
274
  Exported voice types: `Voice`, `VoiceOptions`, `VoiceSnapshot`, `MicStatus`, `MicError`, `MicErrorCode`.
271
275
 
@@ -281,7 +285,7 @@ if (voice.micStatus === 'off' || voice.micStatus === 'error') {
281
285
  await voice.toggleMic() // 1st call: getUserMedia + addStream ('live'); next calls: soft-mute ('muted' <-> 'live')
282
286
 
283
287
  voice.onChange((snap) => {
284
- // snap: { micStatus, micError, deviceId, autoplayBlocked, deafened, volume, selfSpeaking, remotePeers, speakingPeers, mutedPeers }
288
+ // snap: { micStatus, micError, deviceId, autoplayBlocked, deafened, volume, selfSpeaking, remotePeers, speakingPeers, mutedPeers, peerVolumes }
285
289
  if (snap.autoplayBlocked) showUnlockBanner()
286
290
  })
287
291
 
@@ -399,7 +403,7 @@ const { serverNow } = await ping.call(peerId, { sentAt: Date.now() })
399
403
  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'`.
400
404
 
401
405
  - `options` (`PeerStateOptions<T>`): `{ delivery?: Delivery, codec?: Codec<T>, initial?: T, coalesce?: boolean }` (defaults: `delivery: 'reliable'`, `codec: jsonCodec()`, `coalesce: true`).
402
- - Returns a `PeerState<T>` with `{ name, delivery, getSelf(), get(peerId), getAll(), set(value), clear(), onChange((peerId, next, prev) => ..., options?: ListenOptions), close() }`.
406
+ - 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'`.
403
407
 
404
408
  ```ts
405
409
  import { createPeerState } from '@dimchansky/meshpost'
@@ -442,15 +446,17 @@ const results = await files.send(fileBytes, {
442
446
 
443
447
  ### Signaling exports
444
448
 
449
+ - `publicSignaling({ wsUrls?, mqtt?, nostr?, localTabs?, wsEncrypt?, privateTopic?, appId?, wsHandshakeTimeoutMs?, handshakeTimeoutMs?, WebSocket? })` — Ready-made URL-agnostic composite adapter combining `mqttSignaling()` + port-443 `nostrSignaling()`, wrapped in `withLocalTabs(...)` (defaults: `mqtt: true`, `nostr: true`, `localTabs: true`, `wsEncrypt: true`, `privateTopic: false`, `wsHandshakeTimeoutMs: 4_000`, `handshakeTimeoutMs: 10_000`), plus zero or more app-supplied opportunistic WebSocket relays (`wsUrls?: string | readonly string[]`, max `8` unique URLs). Any unreachable or `403`-rejected `wsUrls` entry closes silently without reconnect storms while public relays carry the room.
445
450
  - `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.
446
451
  - `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.
447
452
  - `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.
453
+ - `optionalWsSignaling(url, { handshakeTimeoutMs?, pingIntervalMs?, encrypt?, privateTopic?, WebSocket? })` — Opportunistic `wsSignaling` wrapper (`reconnect: false`, `4,000` ms default handshake timeout) that transitions cleanly to `'closed'` and suppresses `'signaling-error'` if unreachable while preserving `'decrypt-failed'` and `'clock-skew'` diagnostics.
448
454
  - `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
455
  - `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
456
  - `tabSignaling()` — Connects tabs open to the same site (same protocol, domain, and port) in the same browser. Works offline with no server.
451
457
  - `manualSignaling(outgoing)` — Connects completely offline browsers by copying and pasting text. Returns `{ signaling, contact(), accept(text), forget(peerId) }`.
452
458
  - `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`, `MqttSignalingOptions`, `NostrSignalingOptions`, `WsSignalingOptions`, `RTCPeerConnectionConstructor`, `WebSocketConstructor`, `defaultMqttRelays`, `defaultNostrRelays`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
459
+ - Custom adapter types and helpers: `Signaling`, `Discovery`, `SignalingSession`, `SignalingState`, `SignalingErrorCode`, `Signal`, `IceCandidatePayload`, `RoomError`, `RoomErrorCode`, `ListenOptions`, `ManualSignaling`, `PublicSignalingOptions`, `MqttSignalingOptions`, `NostrSignalingOptions`, `WsSignalingOptions`, `OptionalWsSignalingOptions`, `RTCPeerConnectionConstructor`, `WebSocketConstructor`, `defaultMqttRelays`, `defaultNostrRelays`, `isSignal`, `isUuid`, and `withLoopbackFallback` (adds a local `127.0.0.1` fallback for same-machine connections).
454
460
 
455
461
  ## Connecting through strict firewalls (TURN)
456
462
 
@@ -474,7 +480,7 @@ const room = joinRoom('lobby', {
474
480
 
475
481
  ### Subpath exports & bundler-free `<script type="importmap">`
476
482
 
477
- Every feature module is available as a dedicated subpath export (`@dimchansky/meshpost/room`, `/channel`, `/rpc`, `/state`, `/blob`, `/voice`, `/turn`, `/identity`, `/mqtt`, `/nostr`, `/ws`, `/tabs`, `/manual`, `/combine`, `/signaling`) so bundler-free `<script type="importmap">` apps only download the modules they actually import:
483
+ 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
484
 
479
485
  ```html
480
486
  <script type="importmap">
package/dist/blob.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createChannel } from './channel.js';
2
+ import { bindAbort, createListeners } from './listeners.js';
2
3
  const opStart = 0x01;
3
4
  const opData = 0x02;
4
5
  const opAbort = 0x03;
@@ -12,48 +13,7 @@ const defaultChunkSize = 15 * 1024;
12
13
  const defaultReceiveTimeoutMs = 30_000;
13
14
  const defaultMaxConcurrentPerPeer = 4;
14
15
  const encoder = new TextEncoder();
15
- function listeners() {
16
- const entries = new Set();
17
- let closed = false;
18
- return {
19
- add(fn, options) {
20
- const signal = options?.signal;
21
- if (closed || signal?.aborted)
22
- return () => { };
23
- const entry = {
24
- fn,
25
- once: Boolean(options?.once),
26
- off() {
27
- if (!entries.delete(entry))
28
- return;
29
- signal?.removeEventListener('abort', entry.off);
30
- }
31
- };
32
- entries.add(entry);
33
- signal?.addEventListener('abort', entry.off, { once: true });
34
- return entry.off;
35
- },
36
- fire(...args) {
37
- for (const entry of [...entries]) {
38
- if (!entries.has(entry))
39
- continue;
40
- if (entry.once)
41
- entry.off();
42
- try {
43
- entry.fn(...args);
44
- }
45
- catch (error) {
46
- globalThis.reportError?.(error);
47
- }
48
- }
49
- },
50
- clear() {
51
- closed = true;
52
- for (const entry of [...entries])
53
- entry.off();
54
- }
55
- };
56
- }
16
+ const listeners = createListeners;
57
17
  /**
58
18
  * Create a chunked reliable binary channel for payloads larger than Meshpost's 16 KiB packet limit.
59
19
  * Built strictly on top of `createChannel(room, name, { delivery: 'reliable' })` and `room.onDrain`.
@@ -145,19 +105,20 @@ export function createBlobChannel(room, name, options = {}) {
145
105
  }
146
106
  const ctrl = new AbortController();
147
107
  let settled = false;
108
+ let unbindAbort;
148
109
  const done = (outcome) => {
149
110
  if (settled)
150
111
  return;
151
112
  settled = true;
152
113
  ctrl.abort();
153
114
  closeWaiters.delete(onClose);
154
- signal?.removeEventListener('abort', onAbort);
115
+ unbindAbort?.();
155
116
  resolve(outcome);
156
117
  };
157
118
  const onClose = () => done('abort');
158
119
  const onAbort = () => done('abort');
159
120
  closeWaiters.add(onClose);
160
- signal?.addEventListener('abort', onAbort, { once: true });
121
+ unbindAbort = bindAbort(signal, onAbort);
161
122
  room.onDrain((id, delivery) => {
162
123
  if (id === peerId && delivery === 'reliable')
163
124
  done('drain');
package/dist/channel.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { bindAbort } from './listeners.js';
1
2
  import { isRoomClosed, onRoomClose } from './room.js';
2
3
  const encoder = new TextEncoder();
3
4
  const strictDecoder = new TextDecoder('utf-8', { fatal: true });
@@ -101,6 +102,7 @@ function getRouter(room) {
101
102
  table.lengthCounts[nameLen] = (table.lengthCounts[nameLen] ?? 0) + 1;
102
103
  }
103
104
  let removed = false;
105
+ let unbindAbort;
104
106
  const entry = {
105
107
  fn,
106
108
  once: Boolean(options?.once),
@@ -108,7 +110,7 @@ function getRouter(room) {
108
110
  if (removed)
109
111
  return;
110
112
  removed = true;
111
- signal?.removeEventListener('abort', entry.off);
113
+ unbindAbort?.();
112
114
  const current = table.byName.get(name);
113
115
  if (current?.delete(entry)) {
114
116
  activeSubs = Math.max(0, activeSubs - 1);
@@ -123,7 +125,7 @@ function getRouter(room) {
123
125
  };
124
126
  subs.add(entry);
125
127
  activeSubs++;
126
- signal?.addEventListener('abort', entry.off, { once: true });
128
+ unbindAbort = bindAbort(signal, entry.off);
127
129
  return entry.off;
128
130
  }
129
131
  };
package/dist/combine.js CHANGED
@@ -2,6 +2,7 @@ import { tabSignaling } from './tabs.js';
2
2
  const maxSeenIcePeers = 256;
3
3
  const maxSeenIceAttemptsPerPeer = 4;
4
4
  const maxSeenIceKeysPerAttempt = 64;
5
+ const compositeErrorCooldownMs = 15_000;
5
6
  function iceCandidateKey(item) {
6
7
  return item.candidate + '\0' + (item.sdpMid ?? '') + '\0' + (item.sdpMLineIndex ?? '');
7
8
  }
@@ -33,6 +34,8 @@ function createCompositeSession(discovery, list, primaryIndex) {
33
34
  let closed = false;
34
35
  let aggState = 'connecting';
35
36
  let lastReason;
37
+ let lastDecryptErrorAt = -Infinity;
38
+ let lastClockSkewErrorAt = -Infinity;
36
39
  let publishedRoster = new Set();
37
40
  let rosterDirty = false;
38
41
  const computeAggregateState = () => {
@@ -204,6 +207,18 @@ function createCompositeSession(discovery, list, primaryIndex) {
204
207
  return;
205
208
  if (primaryIndex !== null && index !== primaryIndex)
206
209
  return;
210
+ if (code === 'decrypt-failed') {
211
+ const now = Date.now();
212
+ if (now - lastDecryptErrorAt < compositeErrorCooldownMs)
213
+ return;
214
+ lastDecryptErrorAt = now;
215
+ }
216
+ else if (code === 'clock-skew') {
217
+ const now = Date.now();
218
+ if (now - lastClockSkewErrorAt < compositeErrorCooldownMs)
219
+ return;
220
+ lastClockSkewErrorAt = now;
221
+ }
207
222
  if (initializing) {
208
223
  buffered.push({ kind: 'error', code, message });
209
224
  return;
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ export type { Channel, ChannelOptions, ChannelSendOptions, Codec, CodecChannel }
7
7
  export { createRpc, RpcError } from './rpc.js';
8
8
  export type { RpcCallOptions, RpcEndpoint, RpcErrorCode, RpcOptions } from './rpc.js';
9
9
  export { createPeerState } from './state.js';
10
- export type { PeerState, PeerStateOptions } from './state.js';
10
+ export type { PeerState, PeerStateChangeReason, PeerStateOptions } from './state.js';
11
11
  export { createBlobChannel } from './blob.js';
12
12
  export type { BlobChannel, BlobChannelOptions, BlobProgress, BlobSendOptions, BlobSendStatus } from './blob.js';
13
13
  export { createVoice } from './voice.js';
@@ -21,8 +21,10 @@ export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
21
21
  export type { MqttSignalingOptions } from './mqtt.js';
22
22
  export { defaultNostrRelays, nostrSignaling } from './nostr.js';
23
23
  export type { NostrSignalingOptions } from './nostr.js';
24
- export { wsSignaling } from './ws.js';
25
- export type { WsSignalingOptions } from './ws.js';
24
+ export { optionalWsSignaling, wsSignaling } from './ws.js';
25
+ export type { OptionalWsSignalingOptions, WsSignalingOptions } from './ws.js';
26
+ export { publicSignaling } from './public.js';
27
+ export type { PublicSignalingOptions } from './public.js';
26
28
  export { combineSignaling, withLocalTabs } from './combine.js';
27
29
  export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
28
30
  export type { Discovery, IceCandidatePayload, Signal, Signaling, SignalingErrorCode, SignalingSession, SignalingState, WebSocketConstructor } from './signaling.js';
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ export { tabSignaling } from './tabs.js';
10
10
  export { manualSignaling } from './manual.js';
11
11
  export { defaultMqttRelays, mqttSignaling } from './mqtt.js';
12
12
  export { defaultNostrRelays, nostrSignaling } from './nostr.js';
13
- export { wsSignaling } from './ws.js';
13
+ export { optionalWsSignaling, wsSignaling } from './ws.js';
14
+ export { publicSignaling } from './public.js';
14
15
  export { combineSignaling, withLocalTabs } from './combine.js';
15
16
  export { isSignal, isUuid, withLoopbackFallback } from './signaling.js';
@@ -0,0 +1,4 @@
1
+ export interface ListenerOptionsLike {
2
+ once?: boolean;
3
+ signal?: AbortSignal;
4
+ }
@@ -0,0 +1,97 @@
1
+ const abortHub = new WeakMap();
2
+ /**
3
+ * Subscribe `fn` to an `AbortSignal` while attaching at most ONE native `'abort'`
4
+ * listener per `AbortSignal` across all Meshpost primitives (preventing Node.js
5
+ * `MaxListenersExceededWarning` when many subscriptions share one `AbortController`).
6
+ *
7
+ * Callers should check `signal?.aborted` before calling `bindAbort`.
8
+ * @internal
9
+ */
10
+ export function bindAbort(signal, fn) {
11
+ if (!signal || signal.aborted)
12
+ return () => { };
13
+ let entry = abortHub.get(signal);
14
+ if (!entry) {
15
+ const callbacks = new Set();
16
+ const onAbort = () => {
17
+ if (abortHub.get(signal) === hubEntry) {
18
+ abortHub.delete(signal);
19
+ }
20
+ for (const cb of [...callbacks]) {
21
+ if (!callbacks.has(cb))
22
+ continue;
23
+ callbacks.delete(cb);
24
+ try {
25
+ cb();
26
+ }
27
+ catch (error) {
28
+ globalThis.reportError?.(error);
29
+ }
30
+ }
31
+ };
32
+ const hubEntry = { callbacks, onAbort };
33
+ entry = hubEntry;
34
+ abortHub.set(signal, hubEntry);
35
+ signal.addEventListener('abort', onAbort, { once: true });
36
+ }
37
+ const currentEntry = entry;
38
+ currentEntry.callbacks.add(fn);
39
+ let bound = true;
40
+ return () => {
41
+ if (!bound)
42
+ return;
43
+ bound = false;
44
+ if (!currentEntry.callbacks.delete(fn))
45
+ return;
46
+ if (currentEntry.callbacks.size === 0 && abortHub.get(signal) === currentEntry) {
47
+ abortHub.delete(signal);
48
+ signal.removeEventListener('abort', currentEntry.onAbort);
49
+ }
50
+ };
51
+ }
52
+ /** @internal */
53
+ export function createListeners() {
54
+ const entries = new Set();
55
+ let closed = false;
56
+ return {
57
+ add(fn, options) {
58
+ if (typeof fn !== 'function')
59
+ throw new TypeError('Expected a listener function');
60
+ const signal = options?.signal;
61
+ if (closed || signal?.aborted)
62
+ return () => { };
63
+ let unbindAbort;
64
+ const entry = {
65
+ fn,
66
+ once: Boolean(options?.once),
67
+ off() {
68
+ if (!entries.delete(entry))
69
+ return;
70
+ unbindAbort?.();
71
+ }
72
+ };
73
+ entries.add(entry);
74
+ unbindAbort = bindAbort(signal, entry.off);
75
+ return entry.off;
76
+ },
77
+ fire(...args) {
78
+ for (const entry of [...entries]) {
79
+ if (!entries.has(entry))
80
+ continue;
81
+ if (entry.once)
82
+ entry.off();
83
+ try {
84
+ entry.fn(...args);
85
+ }
86
+ catch (error) {
87
+ globalThis.reportError?.(error);
88
+ }
89
+ }
90
+ },
91
+ clear() {
92
+ closed = true;
93
+ for (const entry of [...entries])
94
+ entry.off();
95
+ }
96
+ };
97
+ }
@@ -0,0 +1,52 @@
1
+ import type { Signaling, WebSocketConstructor } from './signaling.js';
2
+ export interface PublicSignalingOptions {
3
+ /**
4
+ * Optional opportunistic WebSocket signaling URL(s) (`ws://` or `wss://`, max 8 unique URLs)
5
+ * tried in parallel alongside public relays for low-latency discovery and instant rosters.
6
+ * Empty array `[]` or `undefined` skips WebSocket relays.
7
+ * Any unreachable or rejected (`403` / quota / blocked) URL closes silently without reconnect storms.
8
+ */
9
+ wsUrls?: string | readonly string[];
10
+ /**
11
+ * Public MQTT-over-WebSocket broker URLs, `true` for `defaultMqttRelays`, or `false` to disable MQTT.
12
+ * @default true
13
+ */
14
+ mqtt?: boolean | readonly string[];
15
+ /**
16
+ * Public port-443 Nostr relay URLs, `true` for `defaultNostrRelays`, or `false` to disable Nostr.
17
+ * @default true
18
+ */
19
+ nostr?: boolean | readonly string[];
20
+ /**
21
+ * Wrap the network transports with `withLocalTabs(...)` for instant same-browser tab discovery
22
+ * while keeping `room.signalingState` tied to network connectivity.
23
+ * @default true
24
+ */
25
+ localTabs?: boolean;
26
+ /**
27
+ * Encrypt `wsUrls` signaling payloads end-to-end with AES-256-GCM when a room `password` is set.
28
+ * (MQTT and Nostr always require `crypto.subtle` encryption when `password` is set.)
29
+ * @default true
30
+ */
31
+ wsEncrypt?: boolean;
32
+ /**
33
+ * Derive room topics/keys cryptographically from `password` across all enabled transports
34
+ * so room activity is hidden on relays (requires a room `password`).
35
+ * @default false
36
+ */
37
+ privateTopic?: boolean;
38
+ /** Optional application namespace override forwarded to MQTT and Nostr relays. */
39
+ appId?: string;
40
+ /** Handshake timeout in milliseconds for opportunistic `wsUrls` relays. @default 4000 */
41
+ wsHandshakeTimeoutMs?: number;
42
+ /** Handshake timeout in milliseconds for MQTT and Nostr relays. @default 10000 */
43
+ handshakeTimeoutMs?: number;
44
+ /** Optional custom `WebSocket` constructor forwarded to WS, MQTT, and Nostr transports. */
45
+ WebSocket?: WebSocketConstructor;
46
+ }
47
+ /**
48
+ * Out-of-the-box composite signaling combining public MQTT + port-443 Nostr relays,
49
+ * same-browser `BroadcastChannel` local tabs (`withLocalTabs`), and zero or more
50
+ * app-supplied opportunistic WebSocket relays (`wsUrls`).
51
+ */
52
+ export declare function publicSignaling(options?: PublicSignalingOptions): Signaling;