@dimchansky/meshpost 0.5.0 → 0.7.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 (49) hide show
  1. package/README.md +66 -544
  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 +44 -45
  6. package/dist/channel.d.ts +4 -0
  7. package/dist/channel.js +19 -44
  8. package/dist/combine.d.ts +9 -2
  9. package/dist/combine.js +40 -57
  10. package/dist/crypto.js +10 -9
  11. package/dist/identity.d.ts +2 -0
  12. package/dist/identity.js +39 -71
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +1 -1
  15. package/dist/listeners.js +18 -3
  16. package/dist/mqtt.js +211 -476
  17. package/dist/nostr.js +194 -836
  18. package/dist/peer-link.d.ts +1 -0
  19. package/dist/peer-link.js +983 -0
  20. package/dist/presence.d.ts +1 -0
  21. package/dist/presence.js +74 -0
  22. package/dist/public.d.ts +1 -1
  23. package/dist/public.js +25 -77
  24. package/dist/relay-core.d.ts +1 -0
  25. package/dist/relay-core.js +399 -0
  26. package/dist/room-reclaim.d.ts +1 -0
  27. package/dist/room-reclaim.js +115 -0
  28. package/dist/room-stats.d.ts +1 -0
  29. package/dist/room-stats.js +75 -0
  30. package/dist/room.js +245 -1218
  31. package/dist/rpc.js +25 -28
  32. package/dist/signaling.d.ts +8 -0
  33. package/dist/signaling.js +55 -0
  34. package/dist/state.js +23 -33
  35. package/dist/tabs.js +6 -50
  36. package/dist/voice-mic.d.ts +1 -0
  37. package/dist/voice-mic.js +496 -0
  38. package/dist/voice-remote.d.ts +1 -0
  39. package/dist/voice-remote.js +568 -0
  40. package/dist/voice.d.ts +19 -1
  41. package/dist/voice.js +95 -1036
  42. package/dist/ws.js +56 -197
  43. package/docs/adr/0001-room-internals-and-channel-budget.md +31 -0
  44. package/docs/api.md +219 -0
  45. package/docs/behavior.md +14 -8
  46. package/docs/guide.md +404 -0
  47. package/docs/signaling-and-production.md +312 -0
  48. package/docs/voice-and-media.md +193 -0
  49. package/package.json +6 -3
package/dist/room.js CHANGED
@@ -1,7 +1,8 @@
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 { createPeerLink, maxTrickleCandidates, streamTagPattern } from './peer-link.js';
4
+ import { createSessionReclaim } from './room-reclaim.js';
5
+ import { isSignal, randomUuid, withLoopbackFallback } from './signaling.js';
5
6
  const roomInternals = new WeakMap();
6
7
  /** @internal */
7
8
  export function isRoomClosed(room) {
@@ -43,132 +44,66 @@ export function onRoomClose(room, fn) {
43
44
  export function getRoomRemoteStreams(room) {
44
45
  return roomInternals.get(room)?.getRemoteStreams() ?? [];
45
46
  }
46
- /** Built-in Cloudflare and Google public STUN servers used by default. */
47
- export const defaultIceServers = Object.freeze([
48
- Object.freeze({ urls: 'stun:stun.cloudflare.com:3478' }),
49
- Object.freeze({ urls: 'stun:stun.l.google.com:19302' }),
50
- Object.freeze({ urls: 'stun:stun1.l.google.com:19302' })
51
- ]);
52
- const listeners = createListeners;
53
- 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)
47
+ /** @internal */
48
+ export function bindRoomLifecycle(room, onShutdown) {
49
+ const controller = new AbortController();
50
+ let closed = isRoomClosed(room);
51
+ let offClose;
52
+ const close = () => {
53
+ if (closed)
71
54
  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;
55
+ closed = true;
56
+ offClose?.();
57
+ offClose = undefined;
58
+ controller.abort();
59
+ onShutdown();
60
+ };
61
+ if (closed) {
62
+ controller.abort();
63
+ onShutdown();
96
64
  }
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';
65
+ else {
66
+ const stop = onRoomClose(room, close);
67
+ if (closed)
68
+ stop();
69
+ else
70
+ offClose = stop;
118
71
  }
119
72
  return {
120
- rttMs,
121
- route,
122
- bytesSent,
123
- bytesReceived,
124
- bufferedUnreliable,
125
- bufferedReliable
73
+ signal: controller.signal,
74
+ isClosed: () => closed,
75
+ close
126
76
  };
127
77
  }
128
- const bufferLimit = { unreliable: 64 * 1024, reliable: 256 * 1024 };
78
+ /** Built-in Cloudflare and Google public STUN servers used by default. */
79
+ export const defaultIceServers = Object.freeze([
80
+ Object.freeze({ urls: 'stun:stun.cloudflare.com:3478' }),
81
+ Object.freeze({ urls: 'stun:stun.l.google.com:19302' }),
82
+ Object.freeze({ urls: 'stun:stun1.l.google.com:19302' })
83
+ ]);
129
84
  const establishTimeout = 35_000;
130
85
  const gatherTimeoutDefault = 2_500;
131
86
  const maxPeersDefault = 32;
132
- const disconnectGrace = 8_000;
133
- 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]);
87
+ function parseStreamTarget(toOrOptions, allowTag) {
88
+ if (typeof toOrOptions === 'string')
89
+ return { to: toOrOptions };
90
+ if (toOrOptions === undefined)
91
+ return {};
92
+ if (!toOrOptions || typeof toOrOptions !== 'object' || Array.isArray(toOrOptions)) {
93
+ throw new TypeError(allowTag ? 'Invalid addStream options' : 'Invalid removeStream options');
94
+ }
95
+ if (toOrOptions.to !== undefined && typeof toOrOptions.to !== 'string') {
96
+ throw new TypeError('Invalid target peer ID');
166
97
  }
167
- return out;
98
+ const tag = allowTag ? toOrOptions.tag : undefined;
99
+ if (tag !== undefined && (typeof tag !== 'string' || !streamTagPattern.test(tag))) {
100
+ throw new TypeError('Invalid stream tag');
101
+ }
102
+ return {
103
+ ...(toOrOptions.to !== undefined ? { to: toOrOptions.to } : {}),
104
+ ...(tag !== undefined ? { tag } : {})
105
+ };
168
106
  }
169
- const trickleBatchMs = 50;
170
- const trickleBatchSize = 16;
171
- const maxTrickleCandidates = 64;
172
107
  /** Start discovery immediately. Membership becomes observable as peer links open. */
173
108
  export function joinRoom(name, options) {
174
109
  if (typeof name !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(name))
@@ -213,112 +148,35 @@ export function joinRoom(name, options) {
213
148
  const self = randomUuid();
214
149
  const peers = new Map();
215
150
  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) {
263
- for (const peer of peers.values()) {
264
- const reliable = peer.link?.channels.reliable;
265
- if (reliable?.readyState === 'open') {
266
- try {
267
- reliable.send(leaveNotice);
268
- }
269
- catch {
270
- // Best-effort unload departure hint.
271
- }
272
- }
273
- }
274
- }
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();
151
+ const joins = createListeners();
152
+ const leaves = createListeners();
153
+ const packets = createListeners();
154
+ const drains = createListeners();
155
+ const status = createListeners();
156
+ const errors = createListeners();
157
+ const peerStreamListeners = createListeners();
158
+ const peerStreamEndListeners = createListeners();
305
159
  let state = 'connecting';
306
160
  // Start attempt numbers from an unpredictable positive offset so observers cannot guess them.
307
161
  let nextAttempt = (crypto.getRandomValues(new Uint32Array(1))[0] & 0x0fffffff) + 1;
308
162
  let stopped = false;
309
163
  let signaling;
310
164
  let useTrickle = false;
311
- const prepareRemoteSdp = (signal) => rtcConfig.iceTransportPolicy === 'relay' ? signal.sdp : withLoopbackFallback(signal).sdp;
312
- const prepareRemoteCandidates = (signal) => rtcConfig.iceTransportPolicy === 'relay'
313
- ? signal.candidates
314
- : withLoopbackFallback(signal).candidates;
315
- const applyRemoteCandidates = (peer, link, candidates) => {
316
- for (const item of candidates) {
317
- if (stopped || peer.link !== link)
318
- return;
319
- void link.pc.addIceCandidate(item).catch(() => { });
165
+ const reclaim = createSessionReclaim({
166
+ appId,
167
+ roomName: name,
168
+ self,
169
+ isStopped: () => stopped,
170
+ sendUnloadLeaveNotices() {
171
+ for (const peer of peers.values()) {
172
+ peer.link?.sendUnloadLeave();
173
+ }
320
174
  }
321
- };
175
+ });
176
+ // Room-level desired local streams & tags (link-level SDP/senders live inside PeerLink).
177
+ const broadcastStreams = new Set();
178
+ const peerStreams = new Map();
179
+ const localStreamTags = new Map();
322
180
  const desiredStreamsFor = (peerId) => {
323
181
  const set = new Set(broadcastStreams);
324
182
  const targeted = peerStreams.get(peerId);
@@ -337,237 +195,13 @@ export function joinRoom(name, options) {
337
195
  }
338
196
  return false;
339
197
  };
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
- };
198
+ const extendedGather = options.iceGatheringTimeoutMs === undefined
199
+ ? Math.min(10_000, Math.floor(timeout / 2))
200
+ : gatherTimeout;
201
+ const prepareRemoteSdp = (signal) => rtcConfig.iceTransportPolicy === 'relay' ? signal.sdp : withLoopbackFallback(signal).sdp;
202
+ const prepareRemoteCandidates = (signal) => rtcConfig.iceTransportPolicy === 'relay'
203
+ ? signal.candidates
204
+ : withLoopbackFallback(signal).candidates;
571
205
  const canReachPeer = (id) => {
572
206
  if (!signaling)
573
207
  return false;
@@ -583,603 +217,138 @@ export function joinRoom(name, options) {
583
217
  discover(peer);
584
218
  }, delay);
585
219
  }
220
+ function finishDrop(peer, link, endedStreams, wasReady, shouldRetry, error) {
221
+ if (!peer.advertised)
222
+ peers.delete(peer.id);
223
+ for (const [stream, meta] of endedStreams) {
224
+ peerStreamEndListeners.fire(peer.id, stream, meta);
225
+ }
226
+ if (wasReady)
227
+ leaves.fire(peer.id);
228
+ if (shouldRetry)
229
+ retry(peer);
230
+ if (!stopped && !wasReady && error) {
231
+ const flag = error.code === 'ice-failed' ? 'iceFailedReported' : 'authFailedReported';
232
+ if (!peer[flag]) {
233
+ peer[flag] = true;
234
+ errors.fire({ code: error.code, peerId: peer.id, message: error.message });
235
+ }
236
+ }
237
+ void link;
238
+ }
586
239
  function drop(peer, link, flushLeave = false, shouldRetry = true) {
587
240
  if (peer.link !== link)
588
241
  return;
589
242
  delete peer.link;
243
+ const wasReady = link.ready;
590
244
  if (link.accepted)
591
245
  peer.previous = link.attempt;
592
246
  if (peer.earlyIce?.attempt === link.attempt)
593
247
  delete peer.earlyIce;
594
- clearTimeout(link.deadline);
595
- clearTimeout(link.gather);
596
- clearTimeout(link.iceFlush);
597
- clearTimeout(link.grace);
598
- const reliable = link.channels.reliable;
599
- if (flushLeave && reliable.readyState === 'open') {
600
- // Give SCTP a bounded opportunity to deliver the departure before closing DTLS.
601
- const closeTimer = setTimeout(() => link.pc.close(), 750);
602
- reliable.addEventListener('close', () => {
603
- clearTimeout(closeTimer);
604
- link.pc.close();
605
- }, { once: true });
606
- try {
607
- reliable.send(leaveNotice);
608
- reliable.close();
609
- }
610
- catch {
611
- clearTimeout(closeTimer);
612
- link.pc.close();
613
- }
614
- }
615
- else
616
- link.pc.close();
617
- if (!peer.advertised)
618
- peers.delete(peer.id);
619
- if (link.ready) {
620
- for (const stream of [...link.remoteStreams.values()]) {
621
- peerStreamEndListeners.fire(peer.id, stream, remoteMetaFor(link, stream.id));
622
- }
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
- }
635
- if (shouldRetry)
636
- retry(peer);
248
+ const endedStreams = link.close({ flushLeave });
249
+ finishDrop(peer, link, endedStreams, wasReady, shouldRetry);
637
250
  }
638
- function createLink(peer, attempt) {
251
+ function negotiate(peer, attempt, remoteOffer) {
252
+ if (stopped || !peer.advertised || !signaling)
253
+ return;
639
254
  clearTimeout(peer.retry);
640
255
  delete peer.retry;
641
- const pc = new PeerConnection(rtcConfig);
642
- // Fixed stream IDs let both endpoints create identical channels without glare.
643
- let channels;
256
+ let link;
644
257
  try {
645
- channels = {
646
- unreliable: pc.createDataChannel('meshpost/1/unreliable', {
647
- negotiated: true,
648
- id: 0,
649
- ordered: false,
650
- maxRetransmits: 0,
651
- protocol: appId
652
- }),
653
- reliable: pc.createDataChannel('meshpost/1/reliable', {
654
- negotiated: true,
655
- id: 1,
656
- ordered: true,
657
- protocol: appId
658
- })
659
- };
660
- }
661
- catch (error) {
662
- pc.close();
663
- throw error;
664
- }
665
- const link = {
666
- pc,
667
- channels,
668
- attempt,
669
- channelsOpen: false,
670
- helloSent: false,
671
- helloReceived: false,
672
- helloVerified: false,
673
- ready: false,
674
- accepted: false,
675
- published: false,
676
- answerApplied: false,
677
- remoteDescApplied: false,
678
- userId: null,
679
- verifiedUserId: null,
680
- reclaimCommit: null,
681
- remoteReclaimCommit: null,
682
- pendingReclaimMatch: null,
683
- pendingCandidates: [],
684
- rtcQueue: Promise.resolve(),
685
- rtcPending: 0,
686
- renegotiateQueued: false,
687
- pendingStreamEnds: new Set(),
688
- senders: new Map(),
689
- remoteStreams: new Map(),
690
- remoteStreamTags: new Map()
691
- };
692
- // Attach active local streams before initial createOffer() on the offerer for 0-RTT media setup.
693
- if (self < peer.id) {
694
- for (const stream of desiredStreamsFor(peer.id)) {
695
- attachStreamToLink(link, stream);
696
- }
697
- }
698
- const earlyStreams = [];
699
- pc.ontrack = (event) => {
700
- if (stopped || peer.link !== link)
701
- return;
702
- const stream = event.streams[0] ??
703
- (typeof MediaStream === 'function' ? new MediaStream([event.track]) : undefined);
704
- if (!stream)
705
- return;
706
- if (link.remoteStreams.has(stream.id) || link.remoteStreams.size >= maxRemoteStreamsPerPeer)
707
- return;
708
- link.remoteStreams.set(stream.id, stream);
709
- if (link.ready)
710
- peerStreamListeners.fire(peer.id, stream, remoteMetaFor(link, stream.id));
711
- else
712
- earlyStreams.push(stream);
713
- };
714
- const reportIceFailed = (message) => {
715
- const wasReady = link.ready;
716
- 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 });
728
- }
729
- };
730
- peer.link = link;
731
- link.deadline = setTimeout(() => reportIceFailed('Connection handshake timed out'), timeout);
732
- pc.onconnectionstatechange = () => {
733
- if (peer.link !== link)
734
- return;
735
- if (pc.connectionState === 'failed')
736
- reportIceFailed('Peer connection failed');
737
- else if (pc.connectionState === 'closed')
738
- drop(peer, link);
739
- else if (pc.connectionState === 'disconnected') {
740
- link.grace ??= setTimeout(() => drop(peer, link), disconnectGrace);
741
- }
742
- else {
743
- clearTimeout(link.grace);
744
- delete link.grace;
745
- }
746
- };
747
- const early = [];
748
- const earlyRtc = [];
749
- let earlyBytes = 0;
750
- const tryPromoteReady = () => {
751
- if (stopped ||
752
- peer.link !== link ||
753
- link.ready ||
754
- !link.channelsOpen ||
755
- !link.helloSent ||
756
- !link.helloVerified) {
757
- return;
758
- }
759
- const reclaimMatch = link.pendingReclaimMatch;
760
- link.pendingReclaimMatch = null;
761
- if (reclaimMatch) {
762
- const oldPeer = peers.get(reclaimMatch.id);
763
- const oldLink = oldPeer?.link;
764
- if (oldPeer && oldLink?.reclaimCommit && oldLink.reclaimCommit === reclaimMatch.commit) {
765
- markSuperseded(oldPeer.id);
766
- oldPeer.advertised = false;
767
- clearTimeout(oldPeer.retry);
768
- delete oldPeer.retry;
769
- drop(oldPeer, oldLink, false, false);
258
+ link = createPeerLink({
259
+ appId,
260
+ roomName: name,
261
+ self,
262
+ peerId: peer.id,
263
+ attempt,
264
+ PeerConnection: PeerConnection,
265
+ rtcConfig,
266
+ useTrickle,
267
+ needsRelay,
268
+ hasTurn,
269
+ timeoutMs: timeout,
270
+ gatherTimeoutMs: gatherTimeout,
271
+ extendedGatherMs: extendedGather,
272
+ identity,
273
+ localReclaimCommitPromise: reclaim.localCommitPromise,
274
+ getPendingReclaim: reclaim.getPendingReclaim,
275
+ getDesiredStreams: () => desiredStreamsFor(peer.id),
276
+ getStreamTag: (stream) => localStreamTags.get(stream),
277
+ onPublishSdp(kind, sdp) {
278
+ return Boolean(signaling?.send(peer.id, { kind, attempt, sdp }));
279
+ },
280
+ onSendIce(candidates) {
281
+ signaling?.send(peer.id, { kind: 'ice', attempt, candidates });
282
+ },
283
+ onReclaim(reclaimMatch) {
284
+ if (stopped || peer.link !== link)
285
+ return false;
286
+ const oldPeer = peers.get(reclaimMatch.id);
287
+ const oldLink = oldPeer?.link;
288
+ if (oldPeer && oldLink?.reclaimCommit && oldLink.reclaimCommit === reclaimMatch.commit) {
289
+ reclaim.markSuperseded(oldPeer.id);
290
+ oldPeer.advertised = false;
291
+ clearTimeout(oldPeer.retry);
292
+ delete oldPeer.retry;
293
+ drop(oldPeer, oldLink, false, false);
294
+ }
295
+ return !stopped && peer.link === link;
296
+ },
297
+ onReady() {
770
298
  if (stopped || peer.link !== link)
771
299
  return;
772
- }
773
- }
774
- clearTimeout(link.deadline);
775
- clearTimeout(link.iceFlush);
776
- delete link.iceFlush;
777
- link.reclaimCommit = link.remoteReclaimCommit;
778
- link.userId = link.verifiedUserId;
779
- link.ready = true;
780
- peer.failures = 0;
781
- peer.iceFailedReported = false;
782
- peer.authFailedReported = false;
783
- joins.fire(peer.id);
784
- for (const stream of earlyStreams) {
785
- if (peer.link !== link || stopped)
786
- break;
787
- peerStreamListeners.fire(peer.id, stream, remoteMetaFor(link, stream.id));
788
- }
789
- earlyStreams.length = 0;
790
- for (const raw of earlyRtc) {
791
- if (peer.link !== link || stopped)
792
- break;
793
- handleRtcControl(peer, link, raw);
794
- }
795
- earlyRtc.length = 0;
796
- for (const [bytes, mode] of early) {
797
- if (peer.link !== link || stopped)
798
- break;
799
- packets.fire(peer.id, bytes, mode);
800
- }
801
- early.length = 0;
802
- // Reconcile local streams (attach newly desired ones, detach any removed mid-handshake).
803
- 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);
817
- }
818
- };
819
- for (const delivery of ['unreliable', 'reliable']) {
820
- const channel = channels[delivery];
821
- channel.binaryType = 'arraybuffer';
822
- channel.bufferedAmountLowThreshold = Math.floor(bufferLimit[delivery] / 2);
823
- channel.onbufferedamountlow = () => {
824
- if (!stopped && peer.link === link && link.ready)
825
- drains.fire(peer.id, delivery);
826
- };
827
- channel.onclose = () => drop(peer, link);
828
- channel.onerror = () => drop(peer, link);
829
- channel.onopen = () => {
830
- if (stopped || peer.link !== link || link.channelsOpen)
831
- return;
832
- if (!Object.values(channels).every((c) => c.readyState === 'open'))
833
- return;
834
- link.channelsOpen = true;
835
- void (async () => {
836
- try {
837
- const rc = await localReclaimCommitPromise;
838
- if (stopped || peer.link !== link)
839
- 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
- if (channels.reliable.readyState !== 'open') {
874
- drop(peer, link);
875
- return;
876
- }
877
- channels.reliable.send(helloPrefix + JSON.stringify(payload));
878
- link.helloSent = true;
879
- tryPromoteReady();
880
- }
881
- catch {
882
- if (!stopped && peer.link === link)
883
- drop(peer, link);
884
- }
885
- })();
886
- };
887
- channel.onmessage = ({ data }) => {
888
- if (stopped || peer.link !== link)
889
- return;
890
- if (data === leaveNotice && delivery === 'reliable') {
891
- peer.advertised = false;
892
- drop(peer, link);
893
- return;
894
- }
895
- if (typeof data === 'string' && delivery === 'reliable' && data.startsWith(helloPrefix)) {
896
- if (link.helloReceived) {
897
- drop(peer, link);
898
- return;
899
- }
900
- link.helloReceived = true;
901
- if (data.length > maxHelloBytes) {
902
- reportAuthFailed('Peer handshake frame exceeded size limit');
300
+ peer.failures = 0;
301
+ peer.iceFailedReported = false;
302
+ peer.authFailedReported = false;
303
+ joins.fire(peer.id);
304
+ },
305
+ onDrop(event) {
306
+ if (peer.link !== link)
903
307
  return;
308
+ delete peer.link;
309
+ const wasReady = link.ready;
310
+ if (link.accepted)
311
+ peer.previous = link.attempt;
312
+ if (peer.earlyIce?.attempt === link.attempt)
313
+ delete peer.earlyIce;
314
+ if (event.remoteLeave)
315
+ peer.advertised = false;
316
+ finishDrop(peer, link, event.endedStreams, wasReady, event.shouldRetry, event.error);
317
+ },
318
+ onPacket(bytes, delivery) {
319
+ if (!stopped && peer.link === link)
320
+ packets.fire(peer.id, bytes, delivery);
321
+ },
322
+ onDrain(delivery) {
323
+ if (!stopped && peer.link === link)
324
+ drains.fire(peer.id, delivery);
325
+ },
326
+ onStream(stream, meta) {
327
+ if (!stopped && peer.link === link)
328
+ peerStreamListeners.fire(peer.id, stream, meta);
329
+ },
330
+ onStreamEnd(stream, meta) {
331
+ if (!stopped && peer.link === link)
332
+ peerStreamEndListeners.fire(peer.id, stream, meta);
333
+ },
334
+ onMediaError(message) {
335
+ if (!stopped && peer.link === link) {
336
+ errors.fire({ code: 'media-error', peerId: peer.id, message });
904
337
  }
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');
918
- return;
919
- }
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');
949
- 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');
956
- return;
957
- }
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;
1001
- link.helloVerified = true;
1002
- tryPromoteReady();
1003
- })();
1004
- return;
1005
- }
1006
- if (typeof data === 'string' &&
1007
- delivery === 'reliable' &&
1008
- data.startsWith(rtcControlPrefix)) {
1009
- if (link.ready)
1010
- handleRtcControl(peer, link, data);
1011
- else if (earlyRtc.length < 16 && data.length <= maxRtcControlBytes)
1012
- earlyRtc.push(data);
1013
- return;
1014
338
  }
1015
- if (!(data instanceof ArrayBuffer))
1016
- return;
1017
- if (data.byteLength > maxPacket) {
1018
- if (delivery === 'reliable')
1019
- drop(peer, link);
1020
- return;
1021
- }
1022
- const bytes = new Uint8Array(data);
1023
- if (link.ready)
1024
- packets.fire(peer.id, bytes, delivery);
1025
- else if (early.length >= 64 || earlyBytes + bytes.byteLength > 256 * 1024) {
1026
- if (delivery === 'reliable')
1027
- drop(peer, link);
1028
- }
1029
- else {
1030
- early.push([bytes, delivery]);
1031
- earlyBytes += bytes.byteLength;
1032
- }
1033
- };
339
+ });
1034
340
  }
1035
- return link;
1036
- }
1037
- async function negotiate(peer, attempt, remoteOffer) {
1038
- if (stopped || !peer.advertised || !signaling)
341
+ catch {
342
+ retry(peer);
1039
343
  return;
1040
- let link;
1041
- try {
1042
- link = createLink(peer, attempt);
1043
- const { pc } = link;
1044
- if (remoteOffer !== undefined) {
1045
- await pc.setRemoteDescription({ type: 'offer', sdp: remoteOffer });
1046
- if (peer.link !== link)
1047
- return;
1048
- link.remoteDescApplied = true;
1049
- if (peer.earlyIce?.attempt === attempt) {
1050
- const earlyCandidates = peer.earlyIce.candidates;
1051
- delete peer.earlyIce;
1052
- applyRemoteCandidates(peer, link, earlyCandidates);
1053
- }
1054
- if (link.pendingCandidates.length > 0) {
1055
- const queued = link.pendingCandidates.splice(0);
1056
- applyRemoteCandidates(peer, link, queued);
1057
- }
1058
- }
1059
- link.accepted = true;
1060
- const description = remoteOffer === undefined ? await pc.createOffer() : await pc.createAnswer();
1061
- if (peer.link !== link)
1062
- return;
1063
- 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);
1174
- }
1175
- }
1176
344
  }
1177
- catch {
1178
- if (link)
1179
- drop(peer, link);
1180
- else
1181
- retry(peer);
345
+ peer.link = link;
346
+ let earlyCandidates;
347
+ if (remoteOffer !== undefined && peer.earlyIce?.attempt === attempt) {
348
+ earlyCandidates = peer.earlyIce.candidates;
349
+ delete peer.earlyIce;
1182
350
  }
351
+ void link.start(remoteOffer, earlyCandidates);
1183
352
  }
1184
353
  function discover(peer) {
1185
354
  if (stopped ||
@@ -1190,7 +359,7 @@ export function joinRoom(name, options) {
1190
359
  peer.retry)
1191
360
  return;
1192
361
  if (self < peer.id)
1193
- void negotiate(peer, ++nextAttempt);
362
+ negotiate(peer, ++nextAttempt);
1194
363
  else {
1195
364
  signaling.send(peer.id, { kind: 'need', previous: peer.previous });
1196
365
  retry(peer);
@@ -1211,17 +380,8 @@ export function joinRoom(name, options) {
1211
380
  drop(peer, link, false, false);
1212
381
  discover(peer);
1213
382
  }
1214
- else if (!link.ready &&
1215
- !link.answerApplied &&
1216
- link.published &&
1217
- link.pc.signalingState === 'have-local-offer' &&
1218
- link.pc.localDescription?.type === 'offer') {
1219
- if (!signaling?.send(peer.id, {
1220
- kind: 'offer',
1221
- attempt: link.attempt,
1222
- sdp: link.pc.localDescription.sdp
1223
- }))
1224
- drop(peer, link);
383
+ else {
384
+ link.resendOfferIfPending();
1225
385
  }
1226
386
  }
1227
387
  else {
@@ -1239,21 +399,11 @@ export function joinRoom(name, options) {
1239
399
  return;
1240
400
  if (link)
1241
401
  drop(peer, link, false, false);
1242
- void negotiate(peer, signal.attempt, prepareRemoteSdp(signal));
402
+ negotiate(peer, signal.attempt, prepareRemoteSdp(signal));
1243
403
  }
1244
404
  else if (signal.kind === 'ice') {
1245
405
  if (link && signal.attempt === link.attempt) {
1246
- const candidates = prepareRemoteCandidates(signal);
1247
- if (link.remoteDescApplied) {
1248
- applyRemoteCandidates(peer, link, candidates);
1249
- }
1250
- else {
1251
- for (const item of candidates) {
1252
- if (link.pendingCandidates.length >= maxTrickleCandidates)
1253
- break;
1254
- link.pendingCandidates.push(item);
1255
- }
1256
- }
406
+ link.addRemoteCandidates(prepareRemoteCandidates(signal));
1257
407
  }
1258
408
  else {
1259
409
  const baseline = link?.attempt ?? peer.previous ?? 0;
@@ -1273,25 +423,8 @@ export function joinRoom(name, options) {
1273
423
  }
1274
424
  }
1275
425
  }
1276
- else if (signal.kind === 'answer' &&
1277
- self < id &&
1278
- link &&
1279
- !link.answerApplied &&
1280
- link.attempt === signal.attempt &&
1281
- link.pc.signalingState === 'have-local-offer') {
1282
- link.answerApplied = true;
1283
- void link.pc
1284
- .setRemoteDescription({ type: 'answer', sdp: prepareRemoteSdp(signal) })
1285
- .then(() => {
1286
- if (stopped || peer.link !== link)
1287
- return;
1288
- link.remoteDescApplied = true;
1289
- if (link.pendingCandidates.length > 0) {
1290
- const queued = link.pendingCandidates.splice(0);
1291
- applyRemoteCandidates(peer, link, queued);
1292
- }
1293
- })
1294
- .catch(() => drop(peer, link));
426
+ else if (signal.kind === 'answer' && self < id && link && link.attempt === signal.attempt) {
427
+ link.applyAnswer(prepareRemoteSdp(signal));
1295
428
  }
1296
429
  }
1297
430
  signaling = options.signaling({
@@ -1341,7 +474,7 @@ export function joinRoom(name, options) {
1341
474
  return;
1342
475
  const present = new Set();
1343
476
  for (const id of ids) {
1344
- if (!supersededPeers.has(id))
477
+ if (!reclaim.isSuperseded(id))
1345
478
  present.add(id);
1346
479
  }
1347
480
  for (const id of [...rejectedFull]) {
@@ -1382,10 +515,7 @@ export function joinRoom(name, options) {
1382
515
  }
1383
516
  }
1384
517
  });
1385
- if (hasWindowEvents) {
1386
- window.addEventListener('pagehide', onPageHide);
1387
- window.addEventListener('pageshow', onPageShow);
1388
- }
518
+ reclaim.attachWindowListeners();
1389
519
  useTrickle = signaling.trickle === true;
1390
520
  for (const peer of peers.values())
1391
521
  discover(peer);
@@ -1419,70 +549,34 @@ export function joinRoom(name, options) {
1419
549
  throw new Error('Room is closed');
1420
550
  if (!stream || typeof stream.getTracks !== 'function')
1421
551
  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) {
552
+ const { to, tag } = parseStreamTarget(toOrOptions, true);
553
+ if (tag !== undefined)
1442
554
  localStreamTags.set(stream, tag);
1443
- }
1444
555
  if (to === undefined) {
1445
556
  broadcastStreams.add(stream);
1446
557
  for (const peer of peers.values()) {
1447
- const link = peer.link;
1448
- if (link?.ready && attachStreamToLink(link, stream)) {
1449
- enqueueRenegotiate(peer, link);
1450
- }
558
+ if (peer.link?.ready)
559
+ peer.link.attachStream(stream, true);
1451
560
  }
561
+ return;
1452
562
  }
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
- }
563
+ if (to === self) {
564
+ if (!isStreamRegistered(stream))
565
+ localStreamTags.delete(stream);
566
+ return;
1470
567
  }
568
+ let set = peerStreams.get(to);
569
+ if (!set) {
570
+ set = new Set();
571
+ peerStreams.set(to, set);
572
+ }
573
+ set.add(stream);
574
+ const link = peers.get(to)?.link;
575
+ if (link?.ready)
576
+ link.attachStream(stream, true);
1471
577
  },
1472
578
  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
- }
579
+ const { to } = parseStreamTarget(toOrOptions, false);
1486
580
  if (stopped || !stream)
1487
581
  return;
1488
582
  if (to === undefined) {
@@ -1493,28 +587,23 @@ export function joinRoom(name, options) {
1493
587
  for (const peer of peers.values()) {
1494
588
  if (peerStreams.get(peer.id)?.has(stream))
1495
589
  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);
590
+ if (peer.link?.ready)
591
+ peer.link.detachStream(stream, true);
1516
592
  }
593
+ return;
1517
594
  }
595
+ const set = peerStreams.get(to);
596
+ if (!set?.delete(stream))
597
+ return;
598
+ if (set.size === 0)
599
+ peerStreams.delete(to);
600
+ if (!isStreamRegistered(stream))
601
+ localStreamTags.delete(stream);
602
+ if (broadcastStreams.has(stream))
603
+ return;
604
+ const link = peers.get(to)?.link;
605
+ if (link?.ready)
606
+ link.detachStream(stream, true);
1518
607
  },
1519
608
  async replaceStreamTrack(stream, oldTrack, newTrack) {
1520
609
  if (stopped)
@@ -1539,27 +628,8 @@ export function joinRoom(name, options) {
1539
628
  stream.addTrack(newTrack);
1540
629
  const ops = [];
1541
630
  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
- }));
631
+ if (peer.link)
632
+ ops.push(peer.link.replaceTrack(stream, oldTrack, newTrack));
1563
633
  }
1564
634
  if (ops.length > 0)
1565
635
  await Promise.all(ops);
@@ -1567,19 +637,7 @@ export function joinRoom(name, options) {
1567
637
  async getStats(peerId) {
1568
638
  if (stopped || peerId === self)
1569
639
  return null;
1570
- const peer = peers.get(peerId);
1571
- const link = peer?.link;
1572
- if (!peer || !link?.ready)
1573
- return null;
1574
- try {
1575
- const report = await link.pc.getStats();
1576
- if (stopped || peer.link !== link || !link.ready)
1577
- return null;
1578
- return parsePeerStats(report, link.channels.unreliable.bufferedAmount, link.channels.reliable.bufferedAmount);
1579
- }
1580
- catch {
1581
- return null;
1582
- }
640
+ return (await peers.get(peerId)?.link?.getStats()) ?? null;
1583
641
  },
1584
642
  send(bytes, { to, delivery = 'unreliable' } = {}) {
1585
643
  if (stopped)
@@ -1592,28 +650,7 @@ export function joinRoom(name, options) {
1592
650
  const targets = to === undefined ? connected() : [to];
1593
651
  for (const id of targets) {
1594
652
  const link = peers.get(id)?.link;
1595
- const channel = link?.channels[delivery];
1596
- if (!link?.ready || channel?.readyState !== 'open')
1597
- result.set(id, 'unavailable');
1598
- else if (bytes.byteLength > Math.min(maxPacket, link.pc.sctp?.maxMessageSize || Infinity))
1599
- result.set(id, 'too-large');
1600
- else if (channel.bufferedAmount + bytes.byteLength > bufferLimit[delivery])
1601
- result.set(id, 'busy');
1602
- else {
1603
- try {
1604
- // Copy shared memory views to a browser-supported non-shared buffer.
1605
- channel.send(bytes.buffer instanceof ArrayBuffer
1606
- ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)
1607
- : Uint8Array.from(bytes));
1608
- result.set(id, 'accepted');
1609
- }
1610
- catch (error) {
1611
- const isOpError = ((typeof DOMException === 'function' && error instanceof DOMException) ||
1612
- error instanceof Error) &&
1613
- error.name === 'OperationError';
1614
- result.set(id, isOpError ? 'busy' : 'unavailable');
1615
- }
1616
- }
653
+ result.set(id, link ? link.send(bytes, delivery) : 'unavailable');
1617
654
  }
1618
655
  return result;
1619
656
  },
@@ -1629,19 +666,10 @@ export function joinRoom(name, options) {
1629
666
  fn();
1630
667
  }
1631
668
  catch (error) {
1632
- globalThis.reportError?.(error);
669
+ reportAsyncError(error);
1633
670
  }
1634
671
  }
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
- }
672
+ reclaim.cleanup();
1645
673
  signaling?.close();
1646
674
  for (const peer of peers.values()) {
1647
675
  peer.advertised = false;
@@ -1652,7 +680,6 @@ export function joinRoom(name, options) {
1652
680
  }
1653
681
  peers.clear();
1654
682
  rejectedFull.clear();
1655
- supersededPeers.clear();
1656
683
  broadcastStreams.clear();
1657
684
  peerStreams.clear();
1658
685
  localStreamTags.clear();
@@ -1691,8 +718,8 @@ export function joinRoom(name, options) {
1691
718
  const link = peer.link;
1692
719
  if (!link?.ready)
1693
720
  continue;
1694
- for (const stream of link.remoteStreams.values()) {
1695
- out.push([peer.id, stream, remoteMetaFor(link, stream.id)]);
721
+ for (const [stream, meta] of link.getRemoteStreams()) {
722
+ out.push([peer.id, stream, meta]);
1696
723
  }
1697
724
  }
1698
725
  return out;