@dimchansky/meshpost 0.4.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +66 -550
  2. package/dist/bip340.d.ts +1 -0
  3. package/dist/bip340.js +346 -0
  4. package/dist/blob.d.ts +1 -1
  5. package/dist/blob.js +15 -16
  6. package/dist/channel.js +15 -44
  7. package/dist/combine.js +25 -39
  8. package/dist/crypto.js +10 -9
  9. package/dist/identity.d.ts +45 -0
  10. package/dist/identity.js +188 -28
  11. package/dist/index.d.ts +6 -6
  12. package/dist/index.js +3 -3
  13. package/dist/listeners.js +18 -3
  14. package/dist/mqtt.js +193 -408
  15. package/dist/nostr.js +163 -745
  16. package/dist/public.d.ts +19 -1
  17. package/dist/public.js +26 -9
  18. package/dist/relay-core.d.ts +1 -0
  19. package/dist/relay-core.js +323 -0
  20. package/dist/room-hello.d.ts +1 -0
  21. package/dist/room-hello.js +129 -0
  22. package/dist/room-ice.d.ts +1 -0
  23. package/dist/room-ice.js +115 -0
  24. package/dist/room-media.d.ts +1 -0
  25. package/dist/room-media.js +477 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +111 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +109 -919
  31. package/dist/signaling.d.ts +8 -0
  32. package/dist/signaling.js +64 -0
  33. package/dist/state.js +1 -2
  34. package/dist/voice-helpers.d.ts +1 -0
  35. package/dist/voice-helpers.js +100 -0
  36. package/dist/voice-meter.d.ts +1 -0
  37. package/dist/voice-meter.js +79 -0
  38. package/dist/voice.d.ts +41 -0
  39. package/dist/voice.js +205 -273
  40. package/dist/ws.js +60 -146
  41. package/docs/api.md +217 -0
  42. package/docs/behavior.md +16 -9
  43. package/docs/guide.md +404 -0
  44. package/docs/signaling-and-production.md +312 -0
  45. package/docs/voice-and-media.md +193 -0
  46. package/package.json +3 -2
package/dist/room.js CHANGED
@@ -1,7 +1,11 @@
1
- import { toBase64Url } from './crypto.js';
2
- import { createListeners } from './listeners.js';
3
- import { decodeCanonicalBase64Url, extractUniqueDtlsFingerprint, isValidPeerIdentity, sha256Base64Url, signIdentityProof, verifyIdentityProof } from './identity.js';
4
- import { isSignal, isUuid, randomUuid, withLoopbackFallback } from './signaling.js';
1
+ import { isValidPeerIdentity } from './identity.js';
2
+ import { createListeners, reportAsyncError } from './listeners.js';
3
+ import { buildHelloFrame, helloPrefix, parseHelloFrame, verifyHelloFrame } from './room-hello.js';
4
+ import { maxTrickleCandidates, setAndPublishLocalDescription } from './room-ice.js';
5
+ import { createRoomMedia, maxRemoteStreamsPerPeer, maxRtcControlBytes, rtcControlPrefix } from './room-media.js';
6
+ import { createSessionReclaim } from './room-reclaim.js';
7
+ import { parsePeerStats } from './room-stats.js';
8
+ import { isSignal, randomUuid, withLoopbackFallback } from './signaling.js';
5
9
  const roomInternals = new WeakMap();
6
10
  /** @internal */
7
11
  export function isRoomClosed(room) {
@@ -49,126 +53,13 @@ export const defaultIceServers = Object.freeze([
49
53
  Object.freeze({ urls: 'stun:stun.l.google.com:19302' }),
50
54
  Object.freeze({ urls: 'stun:stun1.l.google.com:19302' })
51
55
  ]);
52
- const listeners = createListeners;
53
56
  const maxPacket = 16 * 1024;
54
- function asStat(value) {
55
- return value && typeof value === 'object' ? value : undefined;
56
- }
57
- function nonNegativeNumber(value) {
58
- return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
59
- }
60
- function parsePeerStats(report, bufferedUnreliable, bufferedReliable) {
61
- const byId = new Map();
62
- let bytesSent = 0;
63
- let bytesReceived = 0;
64
- let selectedId;
65
- let selectedPair;
66
- let nominatedPair;
67
- let succeededPair;
68
- report.forEach((raw, id) => {
69
- const stat = asStat(raw);
70
- if (!stat)
71
- return;
72
- byId.set(id, stat);
73
- if (stat.type === 'data-channel') {
74
- bytesSent += nonNegativeNumber(stat.bytesSent) ?? 0;
75
- bytesReceived += nonNegativeNumber(stat.bytesReceived) ?? 0;
76
- }
77
- else if (stat.type === 'transport' && typeof stat.selectedCandidatePairId === 'string') {
78
- selectedId = stat.selectedCandidatePairId;
79
- }
80
- else if (stat.type === 'candidate-pair') {
81
- if (stat.selected === true && !selectedPair)
82
- selectedPair = stat;
83
- if (stat.state === 'succeeded') {
84
- if (stat.nominated === true && !nominatedPair)
85
- nominatedPair = stat;
86
- if (!succeededPair)
87
- succeededPair = stat;
88
- }
89
- }
90
- });
91
- let activePair;
92
- if (selectedId) {
93
- const pair = byId.get(selectedId);
94
- if (pair?.type === 'candidate-pair')
95
- activePair = pair;
96
- }
97
- activePair ??= selectedPair ?? nominatedPair ?? succeededPair;
98
- const rttSec = activePair ? nonNegativeNumber(activePair.currentRoundTripTime) : null;
99
- const rttMs = rttSec !== null ? Math.round(rttSec * 1000) : null;
100
- let route = 'unknown';
101
- if (activePair) {
102
- const local = typeof activePair.localCandidateId === 'string'
103
- ? byId.get(activePair.localCandidateId)
104
- : undefined;
105
- const remote = typeof activePair.remoteCandidateId === 'string'
106
- ? byId.get(activePair.remoteCandidateId)
107
- : undefined;
108
- const localType = local?.type === 'local-candidate' && typeof local.candidateType === 'string'
109
- ? local.candidateType
110
- : undefined;
111
- const remoteType = remote?.type === 'remote-candidate' && typeof remote.candidateType === 'string'
112
- ? remote.candidateType
113
- : undefined;
114
- if (localType === 'relay' || remoteType === 'relay')
115
- route = 'relay';
116
- else if (localType && remoteType)
117
- route = 'direct';
118
- }
119
- return {
120
- rttMs,
121
- route,
122
- bytesSent,
123
- bytesReceived,
124
- bufferedUnreliable,
125
- bufferedReliable
126
- };
127
- }
128
57
  const bufferLimit = { unreliable: 64 * 1024, reliable: 256 * 1024 };
129
58
  const establishTimeout = 35_000;
130
59
  const gatherTimeoutDefault = 2_500;
131
60
  const maxPeersDefault = 32;
132
61
  const disconnectGrace = 8_000;
133
62
  const leaveNotice = 'meshpost/1/leave';
134
- const helloPrefix = 'meshpost/1/hello:';
135
- const maxHelloBytes = 4096;
136
- const reclaimTtlMs = 60_000;
137
- const maxSupersededPeers = 128;
138
- const rtcControlPrefix = 'meshpost/1/rtc:';
139
- const maxRtcControlBytes = 64 * 1024;
140
- const maxRtcQueueDepth = 16;
141
- const maxRemoteStreamsPerPeer = 32;
142
- const maxRemoteStreamTags = 64;
143
- const streamTagPattern = /^[a-zA-Z0-9._-]{1,32}$/;
144
- const emptyStreamMeta = Object.freeze({});
145
- function buildStreamMeta(tag) {
146
- return tag !== undefined ? Object.freeze({ tag }) : emptyStreamMeta;
147
- }
148
- function parseIncomingStreamTags(raw) {
149
- if (!raw || typeof raw !== 'object' || Array.isArray(raw))
150
- return null;
151
- const entries = Object.entries(raw);
152
- if (entries.length > maxRemoteStreamsPerPeer)
153
- return null;
154
- const out = [];
155
- for (const [id, tag] of entries) {
156
- if (id.length === 0 ||
157
- id.length > 128 ||
158
- id === '__proto__' ||
159
- id === 'constructor' ||
160
- id === 'prototype' ||
161
- typeof tag !== 'string' ||
162
- !streamTagPattern.test(tag)) {
163
- return null;
164
- }
165
- out.push([id, tag]);
166
- }
167
- return out;
168
- }
169
- const trickleBatchMs = 50;
170
- const trickleBatchSize = 16;
171
- const maxTrickleCandidates = 64;
172
63
  /** Start discovery immediately. Membership becomes observable as peer links open. */
173
64
  export function joinRoom(name, options) {
174
65
  if (typeof name !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(name))
@@ -213,53 +104,26 @@ export function joinRoom(name, options) {
213
104
  const self = randomUuid();
214
105
  const peers = new Map();
215
106
  const rejectedFull = new Set();
216
- const supersededPeers = new Set();
217
- const markSuperseded = (id) => {
218
- supersededPeers.delete(id);
219
- supersededPeers.add(id);
220
- if (supersededPeers.size > maxSupersededPeers) {
221
- const oldest = supersededPeers.values().next().value;
222
- if (oldest !== undefined)
223
- supersededPeers.delete(oldest);
224
- }
225
- };
226
- const reclaimStorageKey = `meshpost/1/reclaim:${appId}:${name}`;
227
- let pendingReclaim = null;
228
- try {
229
- const raw = globalThis.sessionStorage?.getItem(reclaimStorageKey);
230
- if (raw) {
231
- globalThis.sessionStorage?.removeItem(reclaimStorageKey);
232
- const parsed = JSON.parse(raw);
233
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
234
- const rec = parsed;
235
- if (typeof rec.id === 'string' &&
236
- isUuid(rec.id) &&
237
- rec.id !== self &&
238
- decodeCanonicalBase64Url(rec.secret, 22, 16) !== null &&
239
- typeof rec.ts === 'number' &&
240
- Number.isFinite(rec.ts) &&
241
- Math.abs(Date.now() - rec.ts) <= reclaimTtlMs) {
242
- pendingReclaim = { id: rec.id, secret: rec.secret, ts: rec.ts };
243
- }
244
- }
245
- }
246
- }
247
- catch {
248
- // Ignore storage restrictions on opaque origins or non-browser runtimes.
249
- }
250
- const localReclaimSecret = globalThis.crypto?.subtle
251
- ? toBase64Url(crypto.getRandomValues(new Uint8Array(16)))
252
- : null;
253
- const localReclaimCommitPromise = localReclaimSecret
254
- ? sha256Base64Url(`meshpost/1/reclaim:${self}:${localReclaimSecret}`)
255
- : Promise.resolve(null);
256
- const hasWindowEvents = typeof window !== 'undefined' &&
257
- typeof window.addEventListener === 'function' &&
258
- typeof window.removeEventListener === 'function';
259
- const onPageHide = (event) => {
260
- if (stopped)
261
- return;
262
- if (!event.persisted) {
107
+ const joins = createListeners();
108
+ const leaves = createListeners();
109
+ const packets = createListeners();
110
+ const drains = createListeners();
111
+ const status = createListeners();
112
+ const errors = createListeners();
113
+ const peerStreamListeners = createListeners();
114
+ const peerStreamEndListeners = createListeners();
115
+ let state = 'connecting';
116
+ // Start attempt numbers from an unpredictable positive offset so observers cannot guess them.
117
+ let nextAttempt = (crypto.getRandomValues(new Uint32Array(1))[0] & 0x0fffffff) + 1;
118
+ let stopped = false;
119
+ let signaling;
120
+ let useTrickle = false;
121
+ const reclaim = createSessionReclaim({
122
+ appId,
123
+ roomName: name,
124
+ self,
125
+ isStopped: () => stopped,
126
+ sendUnloadLeaveNotices() {
263
127
  for (const peer of peers.values()) {
264
128
  const reliable = peer.link?.channels.reliable;
265
129
  if (reliable?.readyState === 'open') {
@@ -272,42 +136,14 @@ export function joinRoom(name, options) {
272
136
  }
273
137
  }
274
138
  }
275
- if (localReclaimSecret) {
276
- try {
277
- globalThis.sessionStorage?.setItem(reclaimStorageKey, JSON.stringify({ id: self, secret: localReclaimSecret, ts: Date.now() }));
278
- }
279
- catch {
280
- // Ignore storage quota or security errors.
281
- }
282
- }
283
- };
284
- const onPageShow = () => {
285
- if (stopped)
286
- return;
287
- try {
288
- globalThis.sessionStorage?.removeItem(reclaimStorageKey);
289
- }
290
- catch {
291
- // Ignore storage errors.
292
- }
293
- };
294
- const broadcastStreams = new Set();
295
- const peerStreams = new Map();
296
- const localStreamTags = new Map();
297
- const joins = listeners();
298
- const leaves = listeners();
299
- const packets = listeners();
300
- const drains = listeners();
301
- const status = listeners();
302
- const errors = listeners();
303
- const peerStreamListeners = listeners();
304
- const peerStreamEndListeners = listeners();
305
- let state = 'connecting';
306
- // Start attempt numbers from an unpredictable positive offset so observers cannot guess them.
307
- let nextAttempt = (crypto.getRandomValues(new Uint32Array(1))[0] & 0x0fffffff) + 1;
308
- let stopped = false;
309
- let signaling;
310
- let useTrickle = false;
139
+ });
140
+ const media = createRoomMedia({
141
+ self,
142
+ isStopped: () => stopped,
143
+ peers,
144
+ onError: (err) => errors.fire(err),
145
+ onStreamEnd: (peerId, stream, meta) => peerStreamEndListeners.fire(peerId, stream, meta)
146
+ });
311
147
  const prepareRemoteSdp = (signal) => rtcConfig.iceTransportPolicy === 'relay' ? signal.sdp : withLoopbackFallback(signal).sdp;
312
148
  const prepareRemoteCandidates = (signal) => rtcConfig.iceTransportPolicy === 'relay'
313
149
  ? signal.candidates
@@ -319,255 +155,6 @@ export function joinRoom(name, options) {
319
155
  void link.pc.addIceCandidate(item).catch(() => { });
320
156
  }
321
157
  };
322
- const desiredStreamsFor = (peerId) => {
323
- const set = new Set(broadcastStreams);
324
- const targeted = peerStreams.get(peerId);
325
- if (targeted) {
326
- for (const s of targeted)
327
- set.add(s);
328
- }
329
- return set;
330
- };
331
- const isStreamRegistered = (stream) => {
332
- if (broadcastStreams.has(stream))
333
- return true;
334
- for (const set of peerStreams.values()) {
335
- if (set.has(stream))
336
- return true;
337
- }
338
- return false;
339
- };
340
- const collectLinkStreamTags = (link) => {
341
- let out;
342
- for (const stream of link.senders.keys()) {
343
- const tag = localStreamTags.get(stream);
344
- if (tag !== undefined) {
345
- out ??= {};
346
- out[stream.id] = tag;
347
- }
348
- }
349
- return out;
350
- };
351
- const mergeRemoteStreamTags = (link, entries) => {
352
- for (const [id, tag] of entries) {
353
- if (link.remoteStreamTags.has(id)) {
354
- link.remoteStreamTags.delete(id);
355
- link.remoteStreamTags.set(id, tag);
356
- continue;
357
- }
358
- if (link.remoteStreamTags.size >= maxRemoteStreamTags) {
359
- let evicted = false;
360
- for (const existingId of link.remoteStreamTags.keys()) {
361
- if (!link.remoteStreams.has(existingId)) {
362
- link.remoteStreamTags.delete(existingId);
363
- evicted = true;
364
- break;
365
- }
366
- }
367
- if (!evicted)
368
- continue;
369
- }
370
- link.remoteStreamTags.set(id, tag);
371
- }
372
- };
373
- const remoteMetaFor = (link, streamId) => buildStreamMeta(link.remoteStreamTags.get(streamId));
374
- const sendRtcControl = (link, payload) => {
375
- const reliable = link.channels.reliable;
376
- if (reliable.readyState !== 'open')
377
- return false;
378
- try {
379
- reliable.send(rtcControlPrefix + JSON.stringify(payload));
380
- return true;
381
- }
382
- catch {
383
- return false;
384
- }
385
- };
386
- const attachStreamToLink = (link, stream) => {
387
- if (link.senders.has(stream))
388
- return false;
389
- const tracks = stream.getTracks();
390
- if (tracks.length === 0)
391
- return false;
392
- const added = [];
393
- for (const track of tracks) {
394
- added.push(link.pc.addTrack(track, stream));
395
- }
396
- link.senders.set(stream, added);
397
- link.pendingStreamEnds.delete(stream.id);
398
- return true;
399
- };
400
- const detachStreamFromLink = (link, stream) => {
401
- const added = link.senders.get(stream);
402
- if (!added)
403
- return false;
404
- link.senders.delete(stream);
405
- for (const sender of added) {
406
- try {
407
- link.pc.removeTrack(sender);
408
- }
409
- catch {
410
- // Ignore if connection is closing.
411
- }
412
- }
413
- link.pendingStreamEnds.add(stream.id);
414
- return true;
415
- };
416
- const enqueueRenegotiate = (peer, link) => {
417
- link.renegotiateQueued = true;
418
- link.rtcQueue = link.rtcQueue.then(async () => {
419
- if (stopped ||
420
- peer.link !== link ||
421
- !link.ready ||
422
- !link.renegotiateQueued ||
423
- link.channels.reliable.readyState !== 'open')
424
- return;
425
- if (link.pc.signalingState !== 'stable')
426
- return;
427
- link.renegotiateQueued = false;
428
- try {
429
- const offer = await link.pc.createOffer();
430
- if (stopped || peer.link !== link)
431
- return;
432
- await link.pc.setLocalDescription(offer);
433
- if (stopped || peer.link !== link || !link.pc.localDescription)
434
- return;
435
- const tags = collectLinkStreamTags(link);
436
- if (sendRtcControl(link, {
437
- kind: 'offer',
438
- sdp: link.pc.localDescription.sdp,
439
- ...(tags ? { tags } : {})
440
- })) {
441
- for (const id of link.pendingStreamEnds) {
442
- sendRtcControl(link, { kind: 'stream-end', id });
443
- }
444
- link.pendingStreamEnds.clear();
445
- }
446
- }
447
- catch {
448
- if (!stopped && peer.link === link) {
449
- errors.fire({
450
- code: 'media-error',
451
- peerId: peer.id,
452
- message: 'Failed to negotiate media tracks'
453
- });
454
- }
455
- }
456
- });
457
- };
458
- const handleRtcControl = (peer, link, raw) => {
459
- if (raw.length > maxRtcControlBytes || link.rtcPending >= maxRtcQueueDepth)
460
- return;
461
- let msg;
462
- try {
463
- const parsed = JSON.parse(raw.slice(rtcControlPrefix.length));
464
- msg = parsed && typeof parsed === 'object' ? parsed : null;
465
- }
466
- catch {
467
- return;
468
- }
469
- if (!msg || typeof msg.kind !== 'string')
470
- return;
471
- if (msg.kind === 'stream-end' && typeof msg.id === 'string') {
472
- const streamId = msg.id;
473
- link.rtcPending++;
474
- link.rtcQueue = link.rtcQueue.then(() => {
475
- link.rtcPending--;
476
- if (stopped || peer.link !== link || !link.ready)
477
- return;
478
- const stream = link.remoteStreams.get(streamId);
479
- const meta = remoteMetaFor(link, streamId);
480
- link.remoteStreamTags.delete(streamId);
481
- if (stream) {
482
- link.remoteStreams.delete(streamId);
483
- peerStreamEndListeners.fire(peer.id, stream, meta);
484
- }
485
- });
486
- return;
487
- }
488
- if ((msg.kind !== 'offer' && msg.kind !== 'answer') || typeof msg.sdp !== 'string')
489
- return;
490
- let incomingTags = null;
491
- if (msg.tags !== undefined) {
492
- incomingTags = parseIncomingStreamTags(msg.tags);
493
- if (!incomingTags)
494
- return;
495
- }
496
- const kind = msg.kind;
497
- const sdp = msg.sdp;
498
- const polite = self > peer.id;
499
- link.rtcPending++;
500
- link.rtcQueue = link.rtcQueue.then(async () => {
501
- try {
502
- if (stopped || peer.link !== link || !link.ready)
503
- return;
504
- if (kind === 'offer') {
505
- const collision = link.pc.signalingState !== 'stable';
506
- if (!polite && collision)
507
- return;
508
- try {
509
- if (polite && collision) {
510
- await link.pc.setLocalDescription({ type: 'rollback' });
511
- link.renegotiateQueued = true;
512
- }
513
- if (incomingTags)
514
- mergeRemoteStreamTags(link, incomingTags);
515
- await link.pc.setRemoteDescription({ type: 'offer', sdp });
516
- if (stopped || peer.link !== link)
517
- return;
518
- const answer = await link.pc.createAnswer();
519
- if (stopped || peer.link !== link)
520
- return;
521
- await link.pc.setLocalDescription(answer);
522
- if (stopped || peer.link !== link || !link.pc.localDescription)
523
- return;
524
- const answerTags = collectLinkStreamTags(link);
525
- sendRtcControl(link, {
526
- kind: 'answer',
527
- sdp: link.pc.localDescription.sdp,
528
- ...(answerTags ? { tags: answerTags } : {})
529
- });
530
- }
531
- catch {
532
- if (!stopped && peer.link === link) {
533
- errors.fire({
534
- code: 'media-error',
535
- peerId: peer.id,
536
- message: 'Failed to apply media offer'
537
- });
538
- }
539
- }
540
- if (!stopped && peer.link === link && link.renegotiateQueued) {
541
- enqueueRenegotiate(peer, link);
542
- }
543
- }
544
- else {
545
- if (link.pc.signalingState !== 'have-local-offer')
546
- return;
547
- try {
548
- if (incomingTags)
549
- mergeRemoteStreamTags(link, incomingTags);
550
- await link.pc.setRemoteDescription({ type: 'answer', sdp });
551
- }
552
- catch {
553
- if (!stopped && peer.link === link) {
554
- errors.fire({
555
- code: 'media-error',
556
- peerId: peer.id,
557
- message: 'Failed to apply media answer'
558
- });
559
- }
560
- }
561
- if (!stopped && peer.link === link && link.renegotiateQueued) {
562
- enqueueRenegotiate(peer, link);
563
- }
564
- }
565
- }
566
- finally {
567
- link.rtcPending--;
568
- }
569
- });
570
- };
571
158
  const canReachPeer = (id) => {
572
159
  if (!signaling)
573
160
  return false;
@@ -618,20 +205,12 @@ export function joinRoom(name, options) {
618
205
  peers.delete(peer.id);
619
206
  if (link.ready) {
620
207
  for (const stream of [...link.remoteStreams.values()]) {
621
- peerStreamEndListeners.fire(peer.id, stream, remoteMetaFor(link, stream.id));
208
+ peerStreamEndListeners.fire(peer.id, stream, media.remoteMetaFor(link, stream.id));
622
209
  }
623
- link.remoteStreams.clear();
624
- link.remoteStreamTags.clear();
625
- link.senders.clear();
626
- link.pendingStreamEnds.clear();
627
- leaves.fire(peer.id);
628
- }
629
- else {
630
- link.remoteStreams.clear();
631
- link.remoteStreamTags.clear();
632
- link.senders.clear();
633
- link.pendingStreamEnds.clear();
634
210
  }
211
+ media.clearLinkMedia(link);
212
+ if (link.ready)
213
+ leaves.fire(peer.id);
635
214
  if (shouldRetry)
636
215
  retry(peer);
637
216
  }
@@ -691,8 +270,8 @@ export function joinRoom(name, options) {
691
270
  };
692
271
  // Attach active local streams before initial createOffer() on the offerer for 0-RTT media setup.
693
272
  if (self < peer.id) {
694
- for (const stream of desiredStreamsFor(peer.id)) {
695
- attachStreamToLink(link, stream);
273
+ for (const stream of media.desiredStreamsFor(peer.id)) {
274
+ media.attachStreamToLink(link, stream);
696
275
  }
697
276
  }
698
277
  const earlyStreams = [];
@@ -707,26 +286,20 @@ export function joinRoom(name, options) {
707
286
  return;
708
287
  link.remoteStreams.set(stream.id, stream);
709
288
  if (link.ready)
710
- peerStreamListeners.fire(peer.id, stream, remoteMetaFor(link, stream.id));
289
+ peerStreamListeners.fire(peer.id, stream, media.remoteMetaFor(link, stream.id));
711
290
  else
712
291
  earlyStreams.push(stream);
713
292
  };
714
- const reportIceFailed = (message) => {
293
+ const failHandshake = (code, flag, message) => {
715
294
  const wasReady = link.ready;
716
295
  drop(peer, link);
717
- if (!stopped && !wasReady && !peer.iceFailedReported) {
718
- peer.iceFailedReported = true;
719
- errors.fire({ code: 'ice-failed', peerId: peer.id, message });
720
- }
721
- };
722
- const reportAuthFailed = (message) => {
723
- const wasReady = link.ready;
724
- drop(peer, link);
725
- if (!stopped && !wasReady && !peer.authFailedReported) {
726
- peer.authFailedReported = true;
727
- errors.fire({ code: 'auth-failed', peerId: peer.id, message });
296
+ if (!stopped && !wasReady && !peer[flag]) {
297
+ peer[flag] = true;
298
+ errors.fire({ code, peerId: peer.id, message });
728
299
  }
729
300
  };
301
+ const reportIceFailed = (message) => failHandshake('ice-failed', 'iceFailedReported', message);
302
+ const reportAuthFailed = (message) => failHandshake('auth-failed', 'authFailedReported', message);
730
303
  peer.link = link;
731
304
  link.deadline = setTimeout(() => reportIceFailed('Connection handshake timed out'), timeout);
732
305
  pc.onconnectionstatechange = () => {
@@ -762,7 +335,7 @@ export function joinRoom(name, options) {
762
335
  const oldPeer = peers.get(reclaimMatch.id);
763
336
  const oldLink = oldPeer?.link;
764
337
  if (oldPeer && oldLink?.reclaimCommit && oldLink.reclaimCommit === reclaimMatch.commit) {
765
- markSuperseded(oldPeer.id);
338
+ reclaim.markSuperseded(oldPeer.id);
766
339
  oldPeer.advertised = false;
767
340
  clearTimeout(oldPeer.retry);
768
341
  delete oldPeer.retry;
@@ -784,13 +357,13 @@ export function joinRoom(name, options) {
784
357
  for (const stream of earlyStreams) {
785
358
  if (peer.link !== link || stopped)
786
359
  break;
787
- peerStreamListeners.fire(peer.id, stream, remoteMetaFor(link, stream.id));
360
+ peerStreamListeners.fire(peer.id, stream, media.remoteMetaFor(link, stream.id));
788
361
  }
789
362
  earlyStreams.length = 0;
790
363
  for (const raw of earlyRtc) {
791
364
  if (peer.link !== link || stopped)
792
365
  break;
793
- handleRtcControl(peer, link, raw);
366
+ media.handleRtcControl(peer, link, raw);
794
367
  }
795
368
  earlyRtc.length = 0;
796
369
  for (const [bytes, mode] of early) {
@@ -801,19 +374,7 @@ export function joinRoom(name, options) {
801
374
  early.length = 0;
802
375
  // Reconcile local streams (attach newly desired ones, detach any removed mid-handshake).
803
376
  if (!stopped && peer.link === link) {
804
- const desired = desiredStreamsFor(peer.id);
805
- let needsRenegotiate = false;
806
- for (const stream of desired) {
807
- if (attachStreamToLink(link, stream))
808
- needsRenegotiate = true;
809
- }
810
- for (const stream of [...link.senders.keys()]) {
811
- if (!desired.has(stream) && detachStreamFromLink(link, stream)) {
812
- needsRenegotiate = true;
813
- }
814
- }
815
- if (needsRenegotiate)
816
- enqueueRenegotiate(peer, link);
377
+ media.reconcileLinkStreams(peer, link);
817
378
  }
818
379
  };
819
380
  for (const delivery of ['unreliable', 'reliable']) {
@@ -834,47 +395,24 @@ export function joinRoom(name, options) {
834
395
  link.channelsOpen = true;
835
396
  void (async () => {
836
397
  try {
837
- const rc = await localReclaimCommitPromise;
398
+ const frame = await buildHelloFrame({
399
+ localReclaimCommitPromise: reclaim.localCommitPromise,
400
+ initialTags: media.collectLinkStreamTags(link),
401
+ pendingReclaim: reclaim.getPendingReclaim(),
402
+ identity,
403
+ appId,
404
+ roomName: name,
405
+ self,
406
+ peerId: peer.id,
407
+ pc
408
+ });
838
409
  if (stopped || peer.link !== link)
839
410
  return;
840
- const payload = { v: 1 };
841
- if (rc)
842
- payload.rc = rc;
843
- const initialTags = collectLinkStreamTags(link);
844
- if (initialTags)
845
- payload.st = initialTags;
846
- if (pendingReclaim) {
847
- if (Math.abs(Date.now() - pendingReclaim.ts) <= reclaimTtlMs) {
848
- payload.reclaim = { id: pendingReclaim.id, secret: pendingReclaim.secret };
849
- }
850
- else {
851
- pendingReclaim = null;
852
- }
853
- }
854
- if (identity) {
855
- const localSdp = pc.currentLocalDescription?.sdp ?? pc.localDescription?.sdp;
856
- const remoteSdp = pc.currentRemoteDescription?.sdp ?? pc.remoteDescription?.sdp;
857
- const localFp = extractUniqueDtlsFingerprint(localSdp);
858
- const remoteFp = extractUniqueDtlsFingerprint(remoteSdp);
859
- if (!localFp || !remoteFp) {
860
- throw new Error('Missing unique DTLS fingerprint for identity binding');
861
- }
862
- payload.id = await signIdentityProof(identity, {
863
- appId,
864
- room: name,
865
- signerId: self,
866
- verifierId: peer.id,
867
- signerFp: localFp,
868
- verifierFp: remoteFp
869
- });
870
- if (stopped || peer.link !== link)
871
- return;
872
- }
873
411
  if (channels.reliable.readyState !== 'open') {
874
412
  drop(peer, link);
875
413
  return;
876
414
  }
877
- channels.reliable.send(helloPrefix + JSON.stringify(payload));
415
+ channels.reliable.send(frame);
878
416
  link.helloSent = true;
879
417
  tryPromoteReady();
880
418
  }
@@ -898,116 +436,34 @@ export function joinRoom(name, options) {
898
436
  return;
899
437
  }
900
438
  link.helloReceived = true;
901
- if (data.length > maxHelloBytes) {
902
- reportAuthFailed('Peer handshake frame exceeded size limit');
903
- return;
904
- }
905
- let parsed = null;
906
- try {
907
- const raw = JSON.parse(data.slice(helloPrefix.length));
908
- parsed =
909
- raw && typeof raw === 'object' && !Array.isArray(raw)
910
- ? raw
911
- : null;
912
- }
913
- catch {
914
- parsed = null;
915
- }
916
- if (!parsed || parsed.v !== 1) {
917
- reportAuthFailed('Invalid peer handshake frame');
439
+ const parsedRes = parseHelloFrame(data, self, peer.id);
440
+ if (!parsedRes.ok) {
441
+ reportAuthFailed(parsedRes.error);
918
442
  return;
919
443
  }
920
- let rc = null;
921
- if (parsed.rc !== undefined) {
922
- if (decodeCanonicalBase64Url(parsed.rc, 43, 32) === null) {
923
- reportAuthFailed('Invalid peer handshake commitment');
924
- return;
925
- }
926
- rc = parsed.rc;
927
- }
928
- let reclaimCandidate = null;
929
- if (parsed.reclaim !== undefined) {
930
- const rec = parsed.reclaim && typeof parsed.reclaim === 'object' && !Array.isArray(parsed.reclaim)
931
- ? parsed.reclaim
932
- : null;
933
- if (!rec ||
934
- typeof rec.id !== 'string' ||
935
- !isUuid(rec.id) ||
936
- rec.id === self ||
937
- rec.id === peer.id ||
938
- decodeCanonicalBase64Url(rec.secret, 22, 16) === null) {
939
- reportAuthFailed('Invalid peer session reclaim proof');
940
- return;
941
- }
942
- reclaimCandidate = { id: rec.id, secret: rec.secret };
943
- }
944
- let initialStreamTags = null;
945
- if (parsed.st !== undefined) {
946
- initialStreamTags = parseIncomingStreamTags(parsed.st);
947
- if (!initialStreamTags) {
948
- reportAuthFailed('Invalid peer stream metadata');
444
+ const { parsed } = parsedRes;
445
+ void verifyHelloFrame(parsed, { appId, roomName: name, self, peerId: peer.id, pc }).then((verified) => {
446
+ if (stopped || peer.link !== link)
949
447
  return;
950
- }
951
- }
952
- let idProof = null;
953
- if (parsed.id !== undefined) {
954
- if (!parsed.id || typeof parsed.id !== 'object' || Array.isArray(parsed.id)) {
955
- reportAuthFailed('Invalid peer identity proof');
448
+ if (!verified.ok) {
449
+ reportAuthFailed(verified.error);
956
450
  return;
957
451
  }
958
- idProof = parsed.id;
959
- }
960
- void (async () => {
961
- let verifiedUserId = null;
962
- if (idProof) {
963
- const localSdp = pc.currentLocalDescription?.sdp ?? pc.localDescription?.sdp;
964
- const remoteSdp = pc.currentRemoteDescription?.sdp ?? pc.remoteDescription?.sdp;
965
- const localFp = extractUniqueDtlsFingerprint(localSdp);
966
- const remoteFp = extractUniqueDtlsFingerprint(remoteSdp);
967
- if (!localFp || !remoteFp) {
968
- if (!stopped && peer.link === link) {
969
- reportAuthFailed('Missing unique DTLS fingerprint for identity verification');
970
- }
971
- return;
972
- }
973
- verifiedUserId = await verifyIdentityProof(idProof, {
974
- appId,
975
- room: name,
976
- signerId: peer.id,
977
- verifierId: self,
978
- signerFp: remoteFp,
979
- verifierFp: localFp
980
- });
981
- if (stopped || peer.link !== link)
982
- return;
983
- if (!verifiedUserId) {
984
- reportAuthFailed('Peer identity verification failed');
985
- return;
986
- }
987
- }
988
- let reclaimMatch = null;
989
- if (reclaimCandidate) {
990
- const commit = await sha256Base64Url(`meshpost/1/reclaim:${reclaimCandidate.id}:${reclaimCandidate.secret}`);
991
- if (stopped || peer.link !== link)
992
- return;
993
- if (commit)
994
- reclaimMatch = { id: reclaimCandidate.id, commit };
995
- }
996
- if (initialStreamTags)
997
- mergeRemoteStreamTags(link, initialStreamTags);
998
- link.verifiedUserId = verifiedUserId;
999
- link.remoteReclaimCommit = rc;
1000
- link.pendingReclaimMatch = reclaimMatch;
452
+ if (parsed.initialStreamTags)
453
+ media.mergeRemoteStreamTags(link, parsed.initialStreamTags);
454
+ link.verifiedUserId = verified.verifiedUserId;
455
+ link.remoteReclaimCommit = parsed.rc;
456
+ link.pendingReclaimMatch = verified.reclaimMatch;
1001
457
  link.helloVerified = true;
1002
458
  tryPromoteReady();
1003
- })();
459
+ });
1004
460
  return;
1005
461
  }
1006
462
  if (typeof data === 'string' &&
1007
463
  delivery === 'reliable' &&
1008
464
  data.startsWith(rtcControlPrefix)) {
1009
465
  if (link.ready)
1010
- handleRtcControl(peer, link, data);
466
+ media.handleRtcControl(peer, link, data);
1011
467
  else if (earlyRtc.length < 16 && data.length <= maxRtcControlBytes)
1012
468
  earlyRtc.push(data);
1013
469
  return;
@@ -1061,118 +517,27 @@ export function joinRoom(name, options) {
1061
517
  if (peer.link !== link)
1062
518
  return;
1063
519
  const current = link;
1064
- const publish = (force = false) => {
1065
- if (current.published || peer.link !== current)
1066
- return;
1067
- if (!force && pc.iceGatheringState !== 'complete')
1068
- return;
1069
- const local = pc.localDescription;
1070
- if (!local || (local.type !== 'offer' && local.type !== 'answer'))
1071
- return;
1072
- clearTimeout(current.gather);
1073
- delete current.gather;
1074
- current.published = true;
1075
- if (!signaling?.send(peer.id, { kind: local.type, attempt, sdp: local.sdp }))
1076
- drop(peer, current);
1077
- };
1078
- if (useTrickle) {
1079
- const outgoing = [];
1080
- let totalQueued = 0;
1081
- let gatheringDone = false;
1082
- const flushIce = () => {
1083
- clearTimeout(current.iceFlush);
1084
- delete current.iceFlush;
1085
- if (!current.published || peer.link !== current || current.ready || stopped)
1086
- return;
1087
- while (outgoing.length > 0) {
1088
- const batch = outgoing.splice(0, trickleBatchSize);
1089
- signaling?.send(peer.id, { kind: 'ice', attempt, candidates: batch });
1090
- }
1091
- };
1092
- const scheduleFlush = (immediate = false) => {
1093
- if (!current.published || peer.link !== current || current.ready || stopped)
1094
- return;
1095
- if (immediate || outgoing.length >= trickleBatchSize) {
1096
- flushIce();
1097
- }
1098
- else if (!current.iceFlush) {
1099
- current.iceFlush = setTimeout(flushIce, trickleBatchMs);
1100
- }
1101
- };
1102
- pc.onicecandidate = (event) => {
1103
- if (peer.link !== current || current.ready || stopped)
1104
- return;
1105
- if (!event.candidate) {
1106
- gatheringDone = true;
1107
- if (totalQueued < maxTrickleCandidates) {
1108
- outgoing.push({ candidate: '' });
1109
- totalQueued++;
1110
- }
1111
- scheduleFlush(true);
1112
- return;
1113
- }
1114
- if (totalQueued >= maxTrickleCandidates)
1115
- return;
1116
- outgoing.push({
1117
- candidate: event.candidate.candidate,
1118
- ...(event.candidate.sdpMid !== null ? { sdpMid: event.candidate.sdpMid } : {}),
1119
- ...(event.candidate.sdpMLineIndex !== null
1120
- ? { sdpMLineIndex: event.candidate.sdpMLineIndex }
1121
- : {})
1122
- });
1123
- totalQueued++;
1124
- scheduleFlush(false);
1125
- };
1126
- await pc.setLocalDescription(description);
1127
- if (peer.link !== current)
1128
- return;
1129
- publish(true);
1130
- if (outgoing.length > 0)
1131
- scheduleFlush(gatheringDone);
1132
- }
1133
- else {
1134
- // Send one complete SDP. Publish early after gatherTimeout so unreachable STUN never stalls,
1135
- // while allowing extra time when relay/TURN candidates are required or configured.
1136
- let hasRelay = false;
1137
- let hasSrflx = false;
1138
- let softExpired = false;
1139
- pc.onicecandidate = (event) => {
1140
- if (peer.link !== current || current.published)
1141
- return;
1142
- if (!event.candidate) {
1143
- publish(true);
1144
- return;
1145
- }
1146
- const type = event.candidate.type;
1147
- if (type === 'relay')
1148
- hasRelay = true;
1149
- else if (type === 'srflx')
1150
- hasSrflx = true;
1151
- if (softExpired && (hasRelay || (!needsRelay && hasSrflx))) {
1152
- publish(true);
1153
- }
1154
- };
1155
- pc.onicegatheringstatechange = () => publish(false);
1156
- await pc.setLocalDescription(description);
1157
- if (peer.link !== current)
1158
- return;
1159
- publish(false);
1160
- if (!current.published) {
1161
- const extendedGather = options.iceGatheringTimeoutMs === undefined
1162
- ? Math.min(10_000, Math.floor(timeout / 2))
1163
- : gatherTimeout;
1164
- current.gather = setTimeout(() => {
1165
- softExpired = true;
1166
- const waitingForRelay = (needsRelay && !hasRelay) || (hasTurn && !hasRelay && !hasSrflx);
1167
- if (waitingForRelay && extendedGather > gatherTimeout) {
1168
- current.gather = setTimeout(() => publish(true), extendedGather - gatherTimeout);
1169
- }
1170
- else {
1171
- publish(true);
1172
- }
1173
- }, gatherTimeout);
520
+ const extendedGather = options.iceGatheringTimeoutMs === undefined
521
+ ? Math.min(10_000, Math.floor(timeout / 2))
522
+ : gatherTimeout;
523
+ await setAndPublishLocalDescription({
524
+ link: current,
525
+ description,
526
+ useTrickle,
527
+ needsRelay,
528
+ hasTurn,
529
+ gatherTimeout,
530
+ extendedGather,
531
+ isCurrent: () => peer.link === current,
532
+ isStopped: () => stopped,
533
+ onPublishSdp(kind, sdp) {
534
+ if (!signaling?.send(peer.id, { kind, attempt, sdp }))
535
+ drop(peer, current);
536
+ },
537
+ onSendIce(candidates) {
538
+ signaling?.send(peer.id, { kind: 'ice', attempt, candidates });
1174
539
  }
1175
- }
540
+ });
1176
541
  }
1177
542
  catch {
1178
543
  if (link)
@@ -1341,7 +706,7 @@ export function joinRoom(name, options) {
1341
706
  return;
1342
707
  const present = new Set();
1343
708
  for (const id of ids) {
1344
- if (!supersededPeers.has(id))
709
+ if (!reclaim.isSuperseded(id))
1345
710
  present.add(id);
1346
711
  }
1347
712
  for (const id of [...rejectedFull]) {
@@ -1382,10 +747,7 @@ export function joinRoom(name, options) {
1382
747
  }
1383
748
  }
1384
749
  });
1385
- if (hasWindowEvents) {
1386
- window.addEventListener('pagehide', onPageHide);
1387
- window.addEventListener('pageshow', onPageShow);
1388
- }
750
+ reclaim.attachWindowListeners();
1389
751
  useTrickle = signaling.trickle === true;
1390
752
  for (const peer of peers.values())
1391
753
  discover(peer);
@@ -1414,156 +776,9 @@ export function joinRoom(name, options) {
1414
776
  onError: errors.add,
1415
777
  onPeerStream: peerStreamListeners.add,
1416
778
  onPeerStreamEnd: peerStreamEndListeners.add,
1417
- addStream(stream, toOrOptions) {
1418
- if (stopped)
1419
- throw new Error('Room is closed');
1420
- if (!stream || typeof stream.getTracks !== 'function')
1421
- throw new TypeError('Expected a MediaStream');
1422
- let to;
1423
- let tag;
1424
- if (typeof toOrOptions === 'string') {
1425
- to = toOrOptions;
1426
- }
1427
- else if (toOrOptions !== undefined) {
1428
- if (!toOrOptions || typeof toOrOptions !== 'object' || Array.isArray(toOrOptions)) {
1429
- throw new TypeError('Invalid addStream options');
1430
- }
1431
- if (toOrOptions.to !== undefined && typeof toOrOptions.to !== 'string') {
1432
- throw new TypeError('Invalid target peer ID');
1433
- }
1434
- if (toOrOptions.tag !== undefined &&
1435
- (typeof toOrOptions.tag !== 'string' || !streamTagPattern.test(toOrOptions.tag))) {
1436
- throw new TypeError('Invalid stream tag');
1437
- }
1438
- to = toOrOptions.to;
1439
- tag = toOrOptions.tag;
1440
- }
1441
- if (tag !== undefined) {
1442
- localStreamTags.set(stream, tag);
1443
- }
1444
- if (to === undefined) {
1445
- broadcastStreams.add(stream);
1446
- for (const peer of peers.values()) {
1447
- const link = peer.link;
1448
- if (link?.ready && attachStreamToLink(link, stream)) {
1449
- enqueueRenegotiate(peer, link);
1450
- }
1451
- }
1452
- }
1453
- else {
1454
- if (to === self) {
1455
- if (!isStreamRegistered(stream))
1456
- localStreamTags.delete(stream);
1457
- return;
1458
- }
1459
- let set = peerStreams.get(to);
1460
- if (!set) {
1461
- set = new Set();
1462
- peerStreams.set(to, set);
1463
- }
1464
- set.add(stream);
1465
- const peer = peers.get(to);
1466
- const link = peer?.link;
1467
- if (peer && link?.ready && attachStreamToLink(link, stream)) {
1468
- enqueueRenegotiate(peer, link);
1469
- }
1470
- }
1471
- },
1472
- removeStream(stream, toOrOptions) {
1473
- let to;
1474
- if (typeof toOrOptions === 'string') {
1475
- to = toOrOptions;
1476
- }
1477
- else if (toOrOptions !== undefined) {
1478
- if (!toOrOptions || typeof toOrOptions !== 'object' || Array.isArray(toOrOptions)) {
1479
- throw new TypeError('Invalid removeStream options');
1480
- }
1481
- if (toOrOptions.to !== undefined && typeof toOrOptions.to !== 'string') {
1482
- throw new TypeError('Invalid target peer ID');
1483
- }
1484
- to = toOrOptions.to;
1485
- }
1486
- if (stopped || !stream)
1487
- return;
1488
- if (to === undefined) {
1489
- if (!broadcastStreams.delete(stream))
1490
- return;
1491
- if (!isStreamRegistered(stream))
1492
- localStreamTags.delete(stream);
1493
- for (const peer of peers.values()) {
1494
- if (peerStreams.get(peer.id)?.has(stream))
1495
- continue;
1496
- const link = peer.link;
1497
- if (link?.ready && detachStreamFromLink(link, stream)) {
1498
- enqueueRenegotiate(peer, link);
1499
- }
1500
- }
1501
- }
1502
- else {
1503
- const set = peerStreams.get(to);
1504
- if (!set?.delete(stream))
1505
- return;
1506
- if (set.size === 0)
1507
- peerStreams.delete(to);
1508
- if (!isStreamRegistered(stream))
1509
- localStreamTags.delete(stream);
1510
- if (broadcastStreams.has(stream))
1511
- return;
1512
- const peer = peers.get(to);
1513
- const link = peer?.link;
1514
- if (peer && link?.ready && detachStreamFromLink(link, stream)) {
1515
- enqueueRenegotiate(peer, link);
1516
- }
1517
- }
1518
- },
1519
- async replaceStreamTrack(stream, oldTrack, newTrack) {
1520
- if (stopped)
1521
- throw new Error('Room is closed');
1522
- if (!stream || typeof stream.getTracks !== 'function')
1523
- throw new TypeError('Expected a MediaStream');
1524
- if (!oldTrack ||
1525
- typeof oldTrack.kind !== 'string' ||
1526
- !newTrack ||
1527
- typeof newTrack.kind !== 'string' ||
1528
- oldTrack.kind !== newTrack.kind) {
1529
- throw new TypeError('Expected matching-kind MediaStreamTrack instances');
1530
- }
1531
- if (!isStreamRegistered(stream)) {
1532
- throw new Error('Stream is not attached to this room');
1533
- }
1534
- if (oldTrack === newTrack)
1535
- return;
1536
- if (stream.getTracks().includes(oldTrack))
1537
- stream.removeTrack(oldTrack);
1538
- if (!stream.getTracks().includes(newTrack))
1539
- stream.addTrack(newTrack);
1540
- const ops = [];
1541
- for (const peer of peers.values()) {
1542
- const link = peer.link;
1543
- const senderList = link?.senders.get(stream);
1544
- if (!peer || !link || !senderList)
1545
- continue;
1546
- let targetSender = senderList.find((s) => s.track === oldTrack);
1547
- if (!targetSender) {
1548
- const sameKind = senderList.filter((s) => s.track?.kind === newTrack.kind);
1549
- if (sameKind.length === 1)
1550
- targetSender = sameKind[0];
1551
- }
1552
- if (!targetSender)
1553
- continue;
1554
- ops.push(targetSender.replaceTrack(newTrack).catch(() => {
1555
- if (!stopped && peer.link === link && link.ready) {
1556
- errors.fire({
1557
- code: 'media-error',
1558
- peerId: peer.id,
1559
- message: 'Failed to replace media track'
1560
- });
1561
- }
1562
- }));
1563
- }
1564
- if (ops.length > 0)
1565
- await Promise.all(ops);
1566
- },
779
+ addStream: media.addStream,
780
+ removeStream: media.removeStream,
781
+ replaceStreamTrack: media.replaceStreamTrack,
1567
782
  async getStats(peerId) {
1568
783
  if (stopped || peerId === self)
1569
784
  return null;
@@ -1629,19 +844,10 @@ export function joinRoom(name, options) {
1629
844
  fn();
1630
845
  }
1631
846
  catch (error) {
1632
- globalThis.reportError?.(error);
847
+ reportAsyncError(error);
1633
848
  }
1634
849
  }
1635
- if (hasWindowEvents) {
1636
- window.removeEventListener('pagehide', onPageHide);
1637
- window.removeEventListener('pageshow', onPageShow);
1638
- }
1639
- try {
1640
- globalThis.sessionStorage?.removeItem(reclaimStorageKey);
1641
- }
1642
- catch {
1643
- // Ignore storage errors.
1644
- }
850
+ reclaim.cleanup();
1645
851
  signaling?.close();
1646
852
  for (const peer of peers.values()) {
1647
853
  peer.advertised = false;
@@ -1652,10 +858,7 @@ export function joinRoom(name, options) {
1652
858
  }
1653
859
  peers.clear();
1654
860
  rejectedFull.clear();
1655
- supersededPeers.clear();
1656
- broadcastStreams.clear();
1657
- peerStreams.clear();
1658
- localStreamTags.clear();
861
+ media.clearAll();
1659
862
  if (!wasClosed)
1660
863
  status.fire('closed');
1661
864
  for (const group of [
@@ -1683,20 +886,7 @@ export function joinRoom(name, options) {
1683
886
  closeHooks.delete(fn);
1684
887
  };
1685
888
  },
1686
- getRemoteStreams() {
1687
- const out = [];
1688
- if (stopped)
1689
- return out;
1690
- for (const peer of peers.values()) {
1691
- const link = peer.link;
1692
- if (!link?.ready)
1693
- continue;
1694
- for (const stream of link.remoteStreams.values()) {
1695
- out.push([peer.id, stream, remoteMetaFor(link, stream.id)]);
1696
- }
1697
- }
1698
- return out;
1699
- }
889
+ getRemoteStreams: media.getRemoteStreams
1700
890
  });
1701
891
  return room;
1702
892
  }