@dimchansky/meshpost 0.4.1 → 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
@@ -185,7 +185,7 @@ Creates a room, assigns a random peer ID (`room.id`), and immediately starts loo
185
185
  | `room.onPeerStreamEnd(fn, options?: ListenOptions)` | Runs when a remote peer removes a `MediaStream` or disconnects (`(peerId, stream, meta: PeerStreamMeta) => ...`). Returns unsubscribe. |
186
186
  | `room.leave()` | Leaves the room, tells peers you left, and closes all connections. Safe to call more than once. |
187
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.
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
189
 
190
190
  `room.onError` emits a `RoomError` object: `{ code: RoomErrorCode, message: string, peerId?: string }`.
191
191
 
@@ -242,33 +242,34 @@ Headless P2P voice chat controller built on top of `room.addStream()` / `room.on
242
242
  | `streamTag` | `string` | `'voice'` | Stream tag attached to outgoing mic streams and matched on incoming streams (`[a-zA-Z0-9._-]{1,32}`). |
243
243
  | `strictStreamTag` | `boolean` | `false` | When `true`, also ignore untagged (`meta.tag === undefined`) incoming audio streams. |
244
244
 
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 currently exceeding `speakingThreshold`. |
256
- | `voice.mutedPeers` | Snapshot array of remote peer IDs locally muted via `voice.setPeerMuted(peerId, true)`. |
257
- | `voice.getSnapshot()` | Returns an immutable `VoiceSnapshot` object with all 10 state fields above (`Voice extends VoiceSnapshot`). |
258
- | `voice.toggleMic()` | Acquires mic on first call (`'off' \| 'error'` → `'requesting'` → `'live'`), or toggles soft-mute (`'live'` ↔ `'muted'`). Coalesces concurrent `'requesting'` calls. |
259
- | `voice.startMic()` | Acquires mic if inactive, or unmutes if `'muted'`. Coalesces concurrent `'requesting'` calls; resolves to `'off'` if closed. |
260
- | `voice.setMuted(muted)` | Soft-mutes (`true`) or unmutes (`false`) an already-acquired mic (`'live' \| 'muted'`). No-op otherwise. |
261
- | `voice.stopMic()` | Detaches stream from room (`removeStream`), cancels any pending `getUserMedia`, and stops hardware tracks (`track.stop()`). |
262
- | `voice.switchDevice(deviceId?)` | Selects or hot-swaps microphone device (`string \| null \| undefined`) via `room.replaceStreamTrack()` with zero WebRTC SDP renegotiation (`Promise<MicStatus>`). |
263
- | `voice.setVolume(volume)` | Sets master incoming playback volume (`0` to `1`, clamped; throws `RangeError` if non-finite). |
264
- | `voice.setPeerVolume(peerId, volume)` | Sets local playback volume (`0` to `1`, clamped, scaled by master `voice.volume`) for one peer. |
265
- | `voice.getPeerVolume(peerId)` | Returns configured local playback volume (`0` to `1`, default `1`) for `peerId`. |
266
- | `voice.setDeafened(deafened)` | Mutes (`true`) or unmutes (`false`) incoming remote `<audio>` elements locally (unmuting also calls `unlockAudio()`). |
267
- | `voice.setPeerMuted(peerId, muted)` | Locally mutes (`true`) or unmutes (`false`) incoming audio from one peer (independent of `deafened`). |
268
- | `voice.isPeerMuted(peerId)` | Returns whether `peerId` is locally muted via `setPeerMuted()`. |
269
- | `voice.unlockAudio()` | Synchronously retries `AudioContext.resume()` and `audio.play()` on paused remote streams (e.g. from a custom unlock banner click). |
270
- | `voice.onChange(fn, options?: ListenOptions)` | Subscribes to `VoiceSnapshot` changes (`(snapshot: VoiceSnapshot) => ...`). Returns unsubscribe. |
271
- | `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()`). |
272
273
 
273
274
  Exported voice types: `Voice`, `VoiceOptions`, `VoiceSnapshot`, `MicStatus`, `MicError`, `MicErrorCode`.
274
275
 
@@ -284,7 +285,7 @@ if (voice.micStatus === 'off' || voice.micStatus === 'error') {
284
285
  await voice.toggleMic() // 1st call: getUserMedia + addStream ('live'); next calls: soft-mute ('muted' <-> 'live')
285
286
 
286
287
  voice.onChange((snap) => {
287
- // snap: { micStatus, micError, deviceId, autoplayBlocked, deafened, volume, selfSpeaking, remotePeers, speakingPeers, mutedPeers }
288
+ // snap: { micStatus, micError, deviceId, autoplayBlocked, deafened, volume, selfSpeaking, remotePeers, speakingPeers, mutedPeers, peerVolumes }
288
289
  if (snap.autoplayBlocked) showUnlockBanner()
289
290
  })
290
291
 
@@ -402,7 +403,7 @@ const { serverNow } = await ping.call(peerId, { sentAt: Date.now() })
402
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'`.
403
404
 
404
405
  - `options` (`PeerStateOptions<T>`): `{ delivery?: Delivery, codec?: Codec<T>, initial?: T, coalesce?: boolean }` (defaults: `delivery: 'reliable'`, `codec: jsonCodec()`, `coalesce: true`).
405
- - 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'`.
406
407
 
407
408
  ```ts
408
409
  import { createPeerState } from '@dimchansky/meshpost'
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/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';
@@ -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
+ }
package/dist/room.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { toBase64Url } from './crypto.js';
2
+ import { createListeners } from './listeners.js';
2
3
  import { decodeCanonicalBase64Url, extractUniqueDtlsFingerprint, isValidPeerIdentity, sha256Base64Url, signIdentityProof, verifyIdentityProof } from './identity.js';
3
4
  import { isSignal, isUuid, randomUuid, withLoopbackFallback } from './signaling.js';
4
5
  const roomInternals = new WeakMap();
@@ -11,9 +12,30 @@ export function isRoomClosed(room) {
11
12
  export function onRoomClose(room, fn) {
12
13
  const internal = roomInternals.get(room);
13
14
  if (!internal) {
14
- if (room.signalingState === 'closed')
15
+ if (room.signalingState === 'closed') {
15
16
  fn();
16
- return () => { };
17
+ return () => { };
18
+ }
19
+ if (typeof room.onSignalingChange !== 'function')
20
+ return () => { };
21
+ let active = true;
22
+ let off;
23
+ const unsubscribe = () => {
24
+ if (!active)
25
+ return;
26
+ active = false;
27
+ if (typeof off === 'function')
28
+ off();
29
+ };
30
+ off = room.onSignalingChange((state) => {
31
+ if (state === 'closed' && active) {
32
+ unsubscribe();
33
+ fn();
34
+ }
35
+ });
36
+ if (!active && typeof off === 'function')
37
+ off();
38
+ return unsubscribe;
17
39
  }
18
40
  return internal.onClose(fn);
19
41
  }
@@ -27,48 +49,7 @@ export const defaultIceServers = Object.freeze([
27
49
  Object.freeze({ urls: 'stun:stun.l.google.com:19302' }),
28
50
  Object.freeze({ urls: 'stun:stun1.l.google.com:19302' })
29
51
  ]);
30
- function listeners() {
31
- const entries = new Set();
32
- let closed = false;
33
- return {
34
- add(fn, options) {
35
- const signal = options?.signal;
36
- if (closed || signal?.aborted)
37
- return () => { };
38
- const entry = {
39
- fn,
40
- once: Boolean(options?.once),
41
- off() {
42
- if (!entries.delete(entry))
43
- return;
44
- signal?.removeEventListener('abort', entry.off);
45
- }
46
- };
47
- entries.add(entry);
48
- signal?.addEventListener('abort', entry.off, { once: true });
49
- return entry.off;
50
- },
51
- fire(...args) {
52
- for (const entry of [...entries]) {
53
- if (!entries.has(entry))
54
- continue;
55
- if (entry.once)
56
- entry.off();
57
- try {
58
- entry.fn(...args);
59
- }
60
- catch (error) {
61
- globalThis.reportError?.(error);
62
- }
63
- }
64
- },
65
- clear() {
66
- closed = true;
67
- for (const entry of [...entries])
68
- entry.off();
69
- }
70
- };
71
- }
52
+ const listeners = createListeners;
72
53
  const maxPacket = 16 * 1024;
73
54
  function asStat(value) {
74
55
  return value && typeof value === 'object' ? value : undefined;
package/dist/rpc.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createChannel, isValidCodec, jsonCodec } from './channel.js';
2
+ import { bindAbort } from './listeners.js';
2
3
  import { isRoomClosed, onRoomClose } from './room.js';
3
4
  /** Error rejected by `rpc.call()` with a structured `code` and target `peerId`. */
4
5
  export class RpcError extends Error {
@@ -314,16 +315,17 @@ export function createRpc(room, name, options = {}) {
314
315
  item.reject(new RpcError('timeout', peerId, `RPC call timed out after ${timeoutMs}ms`));
315
316
  });
316
317
  }, timeoutMs);
318
+ let unbindAbort;
317
319
  pending.set(reqId, {
318
320
  peerId,
319
321
  resolve,
320
322
  reject,
321
323
  cleanup() {
322
324
  clearTimeout(timer);
323
- signal?.removeEventListener('abort', onAbort);
325
+ unbindAbort?.();
324
326
  }
325
327
  });
326
- signal?.addEventListener('abort', onAbort, { once: true });
328
+ unbindAbort = bindAbort(signal, onAbort);
327
329
  let sendStatus;
328
330
  try {
329
331
  sendStatus = channel.send(frame, { to: peerId }).get(peerId);
@@ -361,6 +363,7 @@ export function createRpc(room, name, options = {}) {
361
363
  throw new Error(`RPC handler already registered for channel "${channel.name}"`);
362
364
  }
363
365
  let removed = false;
366
+ let unbindAbort;
364
367
  const entry = {
365
368
  fn,
366
369
  once: Boolean(listenOptions?.once),
@@ -368,13 +371,13 @@ export function createRpc(room, name, options = {}) {
368
371
  if (removed)
369
372
  return;
370
373
  removed = true;
371
- signal?.removeEventListener('abort', entry.off);
374
+ unbindAbort?.();
372
375
  if (activeHandler === entry)
373
376
  activeHandler = undefined;
374
377
  }
375
378
  };
376
379
  activeHandler = entry;
377
- signal?.addEventListener('abort', entry.off, { once: true });
380
+ unbindAbort = bindAbort(signal, entry.off);
378
381
  return entry.off;
379
382
  },
380
383
  close: shutdown
package/dist/state.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type Codec } from './channel.js';
2
2
  import { type Delivery, type ListenOptions, type Room, type SendResult } from './room.js';
3
+ /** Reason why a remote peer's `PeerState` changed in `onChange()`. */
4
+ export type PeerStateChangeReason = 'set' | 'clear' | 'leave';
3
5
  export interface PeerStateOptions<T> {
4
6
  /**
5
7
  * Delivery mode for live `set()` updates (`initial`, `onPeerJoin` hydration, and `clear()` always use `'reliable'`).
@@ -41,10 +43,11 @@ export interface PeerState<T> {
41
43
  */
42
44
  clear(): ReadonlyMap<string, SendResult>;
43
45
  /**
44
- * Subscribe to remote peer state updates and removals (`next` is `undefined` when cleared or when the peer leaves).
46
+ * Subscribe to remote peer state updates and removals (`next` is `undefined` when cleared or when the peer leaves;
47
+ * inspect `reason` (`'set' | 'clear' | 'leave'`) to distinguish explicit `clear()` from `onPeerLeave`).
45
48
  * Returns an idempotent unsubscribe function.
46
49
  */
47
- onChange(fn: (peerId: string, next: T | undefined, prev: T | undefined) => void, options?: ListenOptions): () => void;
50
+ onChange(fn: (peerId: string, next: T | undefined, prev: T | undefined, reason: PeerStateChangeReason) => void, options?: ListenOptions): () => void;
48
51
  /** Detach internal room listeners without broadcasting a clear frame (also runs automatically on `room.leave()`). */
49
52
  close(): void;
50
53
  }
package/dist/state.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createChannel, isValidCodec, jsonCodec } from './channel.js';
2
+ import { createListeners } from './listeners.js';
2
3
  import { isRoomClosed, onRoomClose } from './room.js';
3
4
  const opSet = 0x01;
4
5
  const opClear = 0x02;
@@ -25,53 +26,7 @@ function buildClearFrame(seq) {
25
26
  new DataView(frame.buffer).setUint32(1, seq >>> 0);
26
27
  return frame;
27
28
  }
28
- function listeners() {
29
- const entries = new Set();
30
- let closed = false;
31
- return {
32
- add(fn, options) {
33
- if (typeof fn !== 'function')
34
- throw new TypeError('Expected a listener function');
35
- const signal = options?.signal;
36
- if (closed || signal?.aborted)
37
- return () => { };
38
- let removed = false;
39
- const entry = {
40
- fn,
41
- once: Boolean(options?.once),
42
- off() {
43
- if (removed)
44
- return;
45
- removed = true;
46
- entries.delete(entry);
47
- signal?.removeEventListener('abort', entry.off);
48
- }
49
- };
50
- entries.add(entry);
51
- signal?.addEventListener('abort', entry.off, { once: true });
52
- return entry.off;
53
- },
54
- fire(...args) {
55
- for (const entry of [...entries]) {
56
- if (!entries.has(entry))
57
- continue;
58
- if (entry.once)
59
- entry.off();
60
- try {
61
- entry.fn(...args);
62
- }
63
- catch (error) {
64
- globalThis.reportError?.(error);
65
- }
66
- }
67
- },
68
- clear() {
69
- closed = true;
70
- for (const entry of [...entries])
71
- entry.off();
72
- }
73
- };
74
- }
29
+ const listeners = createListeners;
75
30
  /**
76
31
  * Create a single-writer per-peer state synchronization store over a named logical channel.
77
32
  * Filters out-of-order updates via RFC 1982 `u32` sequence numbers, hydrates state reliably
@@ -185,7 +140,7 @@ export function createPeerState(room, name, options = {}) {
185
140
  lastSeqByPeer.set(from, seq);
186
141
  const prev = peersState.get(from);
187
142
  peersState.set(from, decoded);
188
- changes.fire(from, decoded, prev);
143
+ changes.fire(from, decoded, prev, 'set');
189
144
  }
190
145
  else if (op === opClear) {
191
146
  if (bytes.byteLength !== headerBytes)
@@ -194,7 +149,7 @@ export function createPeerState(room, name, options = {}) {
194
149
  if (peersState.has(from)) {
195
150
  const prev = peersState.get(from);
196
151
  peersState.delete(from);
197
- changes.fire(from, undefined, prev);
152
+ changes.fire(from, undefined, prev, 'clear');
198
153
  }
199
154
  }
200
155
  };
@@ -231,7 +186,7 @@ export function createPeerState(room, name, options = {}) {
231
186
  if (peersState.has(peerId)) {
232
187
  const prev = peersState.get(peerId);
233
188
  peersState.delete(peerId);
234
- changes.fire(peerId, undefined, prev);
189
+ changes.fire(peerId, undefined, prev, 'leave');
235
190
  }
236
191
  }, internalListen);
237
192
  if (coalesce) {
package/dist/voice.d.ts CHANGED
@@ -18,8 +18,11 @@ export interface VoiceSnapshot {
18
18
  readonly volume: number;
19
19
  readonly selfSpeaking: boolean;
20
20
  readonly remotePeers: readonly string[];
21
+ /** Remote peer IDs whose incoming audio currently exceeds `speakingThreshold` (independent of `deafened` / `mutedPeers`). */
21
22
  readonly speakingPeers: readonly string[];
22
23
  readonly mutedPeers: readonly string[];
24
+ /** Sparse map of overridden per-peer playback volumes (`!== 1`). Peers absent from this map default to `1`. */
25
+ readonly peerVolumes: Readonly<Record<string, number>>;
23
26
  }
24
27
  /** Configuration options for `createVoice()`. */
25
28
  export interface VoiceOptions {
package/dist/voice.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createListeners } from './listeners.js';
1
2
  import { getRoomRemoteStreams, isRoomClosed, onRoomClose } from './room.js';
2
3
  const defaultAudioConstraints = Object.freeze({
3
4
  echoCancellation: true,
@@ -57,48 +58,7 @@ function classifyMicError(err) {
57
58
  message: 'Could not access microphone'
58
59
  });
59
60
  }
60
- function listeners() {
61
- const entries = new Set();
62
- let closed = false;
63
- return {
64
- add(fn, options) {
65
- const signal = options?.signal;
66
- if (closed || signal?.aborted)
67
- return () => { };
68
- const entry = {
69
- fn,
70
- once: Boolean(options?.once),
71
- off() {
72
- if (!entries.delete(entry))
73
- return;
74
- signal?.removeEventListener('abort', entry.off);
75
- }
76
- };
77
- entries.add(entry);
78
- signal?.addEventListener('abort', entry.off, { once: true });
79
- return entry.off;
80
- },
81
- fire(...args) {
82
- for (const entry of [...entries]) {
83
- if (!entries.has(entry))
84
- continue;
85
- if (entry.once)
86
- entry.off();
87
- try {
88
- entry.fn(...args);
89
- }
90
- catch (error) {
91
- globalThis.reportError?.(error);
92
- }
93
- }
94
- },
95
- clear() {
96
- closed = true;
97
- for (const entry of [...entries])
98
- entry.off();
99
- }
100
- };
101
- }
61
+ const listeners = createListeners;
102
62
  function applyAudioVolume(audio, volume) {
103
63
  try {
104
64
  audio.volume = volume;
@@ -169,27 +129,30 @@ export function createVoice(room, options) {
169
129
  const autoUnlock = options?.autoUnlock !== false;
170
130
  const speakingDetection = options?.speakingDetection !== false;
171
131
  let selectedDeviceId = null;
132
+ let selectedDeviceExact = false;
172
133
  if (typeof baseConstraints === 'object' && baseConstraints.deviceId !== undefined) {
173
134
  const rawDev = baseConstraints.deviceId;
174
135
  if (typeof rawDev === 'string' && rawDev.trim().length > 0) {
175
136
  selectedDeviceId = rawDev;
137
+ selectedDeviceExact = false;
176
138
  }
177
139
  else if (rawDev && typeof rawDev === 'object' && !Array.isArray(rawDev)) {
178
- const candidate = typeof rawDev.exact === 'string'
179
- ? rawDev.exact
180
- : typeof rawDev.ideal === 'string'
181
- ? rawDev.ideal
182
- : null;
183
- if (candidate && candidate.trim().length > 0)
184
- selectedDeviceId = candidate;
140
+ if (typeof rawDev.exact === 'string' && rawDev.exact.trim().length > 0) {
141
+ selectedDeviceId = rawDev.exact;
142
+ selectedDeviceExact = true;
143
+ }
144
+ else if (typeof rawDev.ideal === 'string' && rawDev.ideal.trim().length > 0) {
145
+ selectedDeviceId = rawDev.ideal;
146
+ selectedDeviceExact = false;
147
+ }
185
148
  }
186
149
  }
187
- function buildAudioConstraints(deviceOverride) {
150
+ function buildAudioConstraints(deviceOverride, exact) {
188
151
  if (deviceOverride !== null) {
189
152
  const base = typeof baseConstraints === 'object'
190
153
  ? { ...baseConstraints }
191
154
  : { ...defaultAudioConstraints };
192
- base.deviceId = { exact: deviceOverride };
155
+ base.deviceId = exact ? { exact: deviceOverride } : { ideal: deviceOverride };
193
156
  return base;
194
157
  }
195
158
  if (baseConstraints === true)
@@ -235,6 +198,9 @@ export function createVoice(room, options) {
235
198
  throw new TypeError('Expected a non-empty peerId string');
236
199
  }
237
200
  }
201
+ function buildPeerVolumes() {
202
+ return Object.freeze(Object.fromEntries(peerVolumes));
203
+ }
238
204
  function buildSnapshot() {
239
205
  return Object.freeze({
240
206
  micStatus,
@@ -246,7 +212,8 @@ export function createVoice(room, options) {
246
212
  selfSpeaking,
247
213
  remotePeers: Object.freeze([...remotePeers.keys()]),
248
214
  speakingPeers: Object.freeze([...speakingPeers]),
249
- mutedPeers: Object.freeze([...mutedPeers])
215
+ mutedPeers: Object.freeze([...mutedPeers]),
216
+ peerVolumes: buildPeerVolumes()
250
217
  });
251
218
  }
252
219
  function emitChange() {
@@ -572,6 +539,7 @@ export function createVoice(room, options) {
572
539
  }
573
540
  const epoch = ++micEpoch;
574
541
  const requestedDeviceId = selectedDeviceId;
542
+ const requestedDeviceExact = selectedDeviceExact;
575
543
  micStatus = 'requesting';
576
544
  micError = null;
577
545
  emitChange();
@@ -582,7 +550,7 @@ export function createVoice(room, options) {
582
550
  let stream;
583
551
  try {
584
552
  stream = await navigator.mediaDevices.getUserMedia({
585
- audio: buildAudioConstraints(requestedDeviceId)
553
+ audio: buildAudioConstraints(requestedDeviceId, requestedDeviceExact)
586
554
  });
587
555
  }
588
556
  catch (err) {
@@ -818,6 +786,9 @@ export function createVoice(room, options) {
818
786
  get mutedPeers() {
819
787
  return Object.freeze([...mutedPeers]);
820
788
  },
789
+ get peerVolumes() {
790
+ return buildPeerVolumes();
791
+ },
821
792
  getSnapshot: buildSnapshot,
822
793
  toggleMic() {
823
794
  if (closed)
@@ -898,11 +869,19 @@ export function createVoice(room, options) {
898
869
  switchEpoch++;
899
870
  inFlightMic = null;
900
871
  selectedDeviceId = nextDeviceId;
872
+ selectedDeviceExact = nextDeviceId !== null;
901
873
  return acquireMic();
902
874
  }
903
875
  if (!localStream || (micStatus !== 'live' && micStatus !== 'muted')) {
904
- if (selectedDeviceId !== nextDeviceId) {
905
- selectedDeviceId = nextDeviceId;
876
+ const hadError = micStatus === 'error' || micError !== null;
877
+ const deviceChanged = selectedDeviceId !== nextDeviceId;
878
+ selectedDeviceId = nextDeviceId;
879
+ selectedDeviceExact = nextDeviceId !== null;
880
+ if (hadError) {
881
+ micStatus = 'off';
882
+ micError = null;
883
+ }
884
+ if (hadError || deviceChanged) {
906
885
  emitChange();
907
886
  }
908
887
  return micStatus;
@@ -923,7 +902,7 @@ export function createVoice(room, options) {
923
902
  let newStream;
924
903
  try {
925
904
  newStream = await navigator.mediaDevices.getUserMedia({
926
- audio: buildAudioConstraints(nextDeviceId)
905
+ audio: buildAudioConstraints(nextDeviceId, nextDeviceId !== null)
927
906
  });
928
907
  }
929
908
  catch (err) {
@@ -1022,6 +1001,7 @@ export function createVoice(room, options) {
1022
1001
  selectedDeviceId =
1023
1002
  nextDeviceId ??
1024
1003
  (typeof actualDeviceId === 'string' && actualDeviceId.length > 0 ? actualDeviceId : null);
1004
+ selectedDeviceExact = nextDeviceId !== null;
1025
1005
  micError = null;
1026
1006
  emitChange();
1027
1007
  resultStatus = micStatus;
package/docs/behavior.md CHANGED
@@ -193,7 +193,7 @@ Each `RTCPeerConnection` creates two pre-negotiated channels with `protocol` set
193
193
  - `0x01` `SET`: `[0x01, seq, ...codec.encode(value)]`
194
194
  - `0x02` `CLEAR`: `[0x02, seq]` (exact 5 bytes).
195
195
  - Live `set(value)` uses `options.delivery` (`'reliable'` default or `'unreliable'`), while `options.initial`, `onPeerJoin` hydration, and `clear()` always transmit on the `'reliable'` channel for `name`. Both channels feed a single per-peer RFC 1982 `u32` sequence table (`lastSeqByPeer`), updated only after `codec.decode` succeeds (`!== undefined`), so out-of-order unreliable packets or racing hydration frames never regress state or resurrect cleared state.
196
- - When `coalesce` is `true` (default), `createPeerState` retains only the single latest encoded frame (`O(1)` memory) and flushes `'busy'` peers on `room.onDrain` (keeping `dirtyReliable` independent of unreliable `'accepted'` returns so UDP loss cannot drop pending reliable hydrations). Disconnecting peers (`onPeerLeave`) are automatically removed and emit `onChange(peerId, undefined, prev)`.
196
+ - When `coalesce` is `true` (default), `createPeerState` retains only the single latest encoded frame (`O(1)` memory) and flushes `'busy'` peers on `room.onDrain` (keeping `dirtyReliable` independent of unreliable `'accepted'` returns so UDP loss cannot drop pending reliable hydrations). `onChange(peerId, next, prev, reason)` passes `reason` (`'set' | 'clear' | 'leave'`) so apps can distinguish explicit `clear()` from `onPeerLeave` without relying on listener registration order; disconnecting peers (`onPeerLeave`) are automatically removed and emit `onChange(peerId, undefined, prev, 'leave')`.
197
197
 
198
198
  ### Chunked transfers (`createBlobChannel`)
199
199
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dimchansky/meshpost",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "author": "Dmitrij Koniajev",
5
5
  "license": "MIT",
6
6
  "type": "module",