@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/dist/public.js ADDED
@@ -0,0 +1,133 @@
1
+ import { combineSignaling, withLocalTabs } from './combine.js';
2
+ import { mqttSignaling } from './mqtt.js';
3
+ import { nostrSignaling } from './nostr.js';
4
+ import { optionalWsSignaling } from './ws.js';
5
+ const maxOptionalWsUrls = 8;
6
+ const maxRawWsUrlItems = 64;
7
+ const defaultWsHandshakeTimeoutMs = 4_000;
8
+ const defaultPublicHandshakeTimeoutMs = 10_000;
9
+ function validateTimeoutMs(value, label) {
10
+ if (!Number.isSafeInteger(value) || value <= 0 || value > 2_147_483_647) {
11
+ throw new RangeError(`Invalid ${label}`);
12
+ }
13
+ }
14
+ function normalizeWsUrls(raw) {
15
+ if (raw === undefined)
16
+ return [];
17
+ if (typeof raw === 'string') {
18
+ if (raw.length === 0)
19
+ throw new TypeError('Invalid WebSocket signaling URL');
20
+ return normalizeWsUrls([raw]);
21
+ }
22
+ if (!Array.isArray(raw)) {
23
+ throw new TypeError('wsUrls must be a URL string or an array of URL strings');
24
+ }
25
+ if (raw.length > maxRawWsUrlItems) {
26
+ throw new RangeError(`Too many wsUrls (max ${maxOptionalWsUrls} unique URLs)`);
27
+ }
28
+ const deduped = new Set();
29
+ for (const item of raw) {
30
+ if (typeof item !== 'string' || item.length === 0) {
31
+ throw new TypeError('Invalid WebSocket signaling URL');
32
+ }
33
+ let parsed;
34
+ try {
35
+ parsed = new URL(item);
36
+ }
37
+ catch {
38
+ throw new TypeError('Invalid WebSocket signaling URL');
39
+ }
40
+ if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
41
+ throw new TypeError('WebSocket signaling URL must use ws: or wss:');
42
+ }
43
+ deduped.add(parsed.toString());
44
+ if (deduped.size > maxOptionalWsUrls) {
45
+ throw new RangeError(`Too many wsUrls (max ${maxOptionalWsUrls} unique URLs)`);
46
+ }
47
+ }
48
+ return [...deduped];
49
+ }
50
+ /**
51
+ * Out-of-the-box composite signaling combining public MQTT + port-443 Nostr relays,
52
+ * same-browser `BroadcastChannel` local tabs (`withLocalTabs`), and zero or more
53
+ * app-supplied opportunistic WebSocket relays (`wsUrls`).
54
+ */
55
+ export function publicSignaling(options = {}) {
56
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
57
+ throw new TypeError('Invalid publicSignaling options');
58
+ }
59
+ const { wsUrls, mqtt = true, nostr = true, localTabs = true, wsEncrypt = true, privateTopic = false, appId, wsHandshakeTimeoutMs = defaultWsHandshakeTimeoutMs, handshakeTimeoutMs = defaultPublicHandshakeTimeoutMs, WebSocket: WsCtor } = options;
60
+ if (typeof localTabs !== 'boolean')
61
+ throw new TypeError('Invalid localTabs option');
62
+ if (typeof wsEncrypt !== 'boolean')
63
+ throw new TypeError('Invalid wsEncrypt option');
64
+ if (typeof privateTopic !== 'boolean')
65
+ throw new TypeError('Invalid privateTopic option');
66
+ if (appId !== undefined && (typeof appId !== 'string' || appId.length === 0)) {
67
+ throw new TypeError('Invalid appId option');
68
+ }
69
+ if (WsCtor !== undefined && typeof WsCtor !== 'function') {
70
+ throw new TypeError('Invalid WebSocket constructor');
71
+ }
72
+ if (mqtt !== true && mqtt !== false && !Array.isArray(mqtt)) {
73
+ throw new TypeError('mqtt option must be a boolean or an array of broker URLs');
74
+ }
75
+ if (nostr !== true && nostr !== false && !Array.isArray(nostr)) {
76
+ throw new TypeError('nostr option must be a boolean or an array of relay URLs');
77
+ }
78
+ if (mqtt === false && nostr === false) {
79
+ throw new RangeError('publicSignaling requires at least one public relay transport (mqtt or nostr)');
80
+ }
81
+ validateTimeoutMs(wsHandshakeTimeoutMs, 'wsHandshakeTimeoutMs');
82
+ validateTimeoutMs(handshakeTimeoutMs, 'handshakeTimeoutMs');
83
+ const normalizedWsUrls = normalizeWsUrls(wsUrls);
84
+ const adapters = [];
85
+ for (const url of normalizedWsUrls) {
86
+ adapters.push(optionalWsSignaling(url, {
87
+ handshakeTimeoutMs: wsHandshakeTimeoutMs,
88
+ encrypt: wsEncrypt,
89
+ privateTopic,
90
+ ...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
91
+ }));
92
+ }
93
+ if (mqtt !== false) {
94
+ adapters.push(mqttSignaling({
95
+ ...(Array.isArray(mqtt) ? { urls: mqtt } : {}),
96
+ ...(appId !== undefined ? { appId } : {}),
97
+ privateTopic,
98
+ handshakeTimeoutMs,
99
+ ...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
100
+ }));
101
+ }
102
+ if (nostr !== false) {
103
+ adapters.push(nostrSignaling({
104
+ ...(Array.isArray(nostr) ? { urls: nostr } : {}),
105
+ ...(appId !== undefined ? { appId } : {}),
106
+ privateTopic,
107
+ handshakeTimeoutMs,
108
+ ...(WsCtor !== undefined ? { WebSocket: WsCtor } : {})
109
+ }));
110
+ }
111
+ const network = combineSignaling(...adapters);
112
+ const pooledNetwork = (discovery) => {
113
+ let lastErrorMessage;
114
+ return network({
115
+ ...discovery,
116
+ status(state, reason) {
117
+ discovery.status(state, reason);
118
+ if (state === 'offline') {
119
+ discovery.error?.('signaling-error', reason ?? lastErrorMessage ?? 'Public signaling disconnected');
120
+ }
121
+ },
122
+ error(code, message) {
123
+ if (code === 'signaling-error') {
124
+ if (message)
125
+ lastErrorMessage = message;
126
+ return;
127
+ }
128
+ discovery.error?.(code, message);
129
+ }
130
+ });
131
+ };
132
+ return localTabs ? withLocalTabs(pooledNetwork) : pooledNetwork;
133
+ }
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/dist/ws.d.ts CHANGED
@@ -22,8 +22,37 @@ export interface WsSignalingOptions {
22
22
  /** Optional custom `WebSocket` constructor for headless runtimes or custom transports. */
23
23
  WebSocket?: WebSocketConstructor;
24
24
  }
25
+ export interface OptionalWsSignalingOptions {
26
+ /** Maximum time in milliseconds to wait for the WebSocket handshake before abandoning it. @default 4000 */
27
+ handshakeTimeoutMs?: number;
28
+ /** Interval in milliseconds for client keepalive pings (`{ type: 'ping' }`). @default 25000 */
29
+ pingIntervalMs?: number;
30
+ /**
31
+ * Encrypt signaling payloads end-to-end with AES-256-GCM when a room `password` is set
32
+ * so the WebSocket server sees only opaque `box` ciphertexts.
33
+ * Set `false` only for plain HTTP LAN testing where `crypto.subtle` is unavailable.
34
+ * @default true
35
+ */
36
+ encrypt?: boolean;
37
+ /**
38
+ * Derive the WebSocket room key cryptographically from `password` so room membership is isolated on the server
39
+ * (disables `'decrypt-failed'` detection when a peer enters the wrong password).
40
+ * @default false
41
+ */
42
+ privateTopic?: boolean;
43
+ /** Optional custom `WebSocket` constructor for headless runtimes or custom transports. */
44
+ WebSocket?: WebSocketConstructor;
45
+ }
25
46
  /**
26
47
  * Connect peers through a WebSocket signaling server (`ws://` or `wss://`).
27
48
  * When a room `password` is set, SDP and ICE payloads are end-to-end encrypted with AES-256-GCM by default.
28
49
  */
29
50
  export declare function wsSignaling(url: string, options?: WsSignalingOptions): Signaling;
51
+ /**
52
+ * Opportunistic WebSocket signaling adapter designed for composition inside `combineSignaling(...)` or `publicSignaling(...)`:
53
+ * - Uses `reconnect: false` so an absent `/ws` endpoint, `403` origin check, ISP block, or exhausted quota
54
+ * transitions cleanly to `'closed'` without reconnect storms.
55
+ * - Suppresses `'signaling-error'` so sibling relays (`tabSignaling`, `mqttSignaling`, `nostrSignaling`) carry
56
+ * the room silently, while still forwarding `'decrypt-failed'` and `'clock-skew'` diagnostics.
57
+ */
58
+ export declare function optionalWsSignaling(url: string, options?: OptionalWsSignalingOptions): Signaling;
package/dist/ws.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createReplayGuard, deriveSignalingKeys, errorCooldownMs, fromBase64Url, openEnvelope, sealEnvelope, toBase64Url } from './crypto.js';
2
2
  import { isSignal, isUuid, namespaceHash } from './signaling.js';
3
3
  const wsOpen = 1;
4
+ const defaultOptionalHandshakeTimeoutMs = 4_000;
4
5
  const maxFrameBytes = 128 * 1024;
5
6
  const maxPeers = 256;
6
7
  const maxEncryptQueueDepth = 128;
@@ -485,3 +486,61 @@ export function wsSignaling(url, options = {}) {
485
486
  };
486
487
  };
487
488
  }
489
+ /**
490
+ * Opportunistic WebSocket signaling adapter designed for composition inside `combineSignaling(...)` or `publicSignaling(...)`:
491
+ * - Uses `reconnect: false` so an absent `/ws` endpoint, `403` origin check, ISP block, or exhausted quota
492
+ * transitions cleanly to `'closed'` without reconnect storms.
493
+ * - Suppresses `'signaling-error'` so sibling relays (`tabSignaling`, `mqttSignaling`, `nostrSignaling`) carry
494
+ * the room silently, while still forwarding `'decrypt-failed'` and `'clock-skew'` diagnostics.
495
+ */
496
+ export function optionalWsSignaling(url, options = {}) {
497
+ const baseWs = wsSignaling(url, {
498
+ handshakeTimeoutMs: options.handshakeTimeoutMs ?? defaultOptionalHandshakeTimeoutMs,
499
+ ...(options.pingIntervalMs !== undefined ? { pingIntervalMs: options.pingIntervalMs } : {}),
500
+ ...(options.encrypt !== undefined ? { encrypt: options.encrypt } : {}),
501
+ ...(options.privateTopic !== undefined ? { privateTopic: options.privateTopic } : {}),
502
+ ...(options.WebSocket !== undefined ? { WebSocket: options.WebSocket } : {}),
503
+ reconnect: false
504
+ });
505
+ return (discovery) => {
506
+ let abandoned = false;
507
+ let session;
508
+ session = baseWs({
509
+ ...discovery,
510
+ status(state, reason) {
511
+ if (abandoned)
512
+ return;
513
+ if (state === 'online') {
514
+ discovery.status('online', reason);
515
+ }
516
+ else {
517
+ abandoned = true;
518
+ session?.close();
519
+ discovery.status('closed');
520
+ }
521
+ },
522
+ error(code, message) {
523
+ if (abandoned)
524
+ return;
525
+ if (code === 'decrypt-failed' || code === 'clock-skew') {
526
+ discovery.error?.(code, message);
527
+ }
528
+ }
529
+ });
530
+ if (abandoned) {
531
+ session.close();
532
+ }
533
+ return {
534
+ ...(session.trickle !== undefined ? { trickle: session.trickle } : {}),
535
+ send(to, signal) {
536
+ if (abandoned)
537
+ return false;
538
+ return session.send(to, signal);
539
+ },
540
+ close() {
541
+ abandoned = true;
542
+ session.close();
543
+ }
544
+ };
545
+ };
546
+ }