@dimchansky/meshpost 0.1.0 → 0.2.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.
package/dist/room.js CHANGED
@@ -6,18 +6,34 @@ export const defaultIceServers = Object.freeze([
6
6
  Object.freeze({ urls: 'stun:stun1.l.google.com:19302' })
7
7
  ]);
8
8
  function listeners() {
9
- const handlers = new Set();
9
+ const entries = new Set();
10
+ let closed = false;
10
11
  return {
11
- add(fn) {
12
- handlers.add(fn);
13
- return () => {
14
- handlers.delete(fn);
12
+ add(fn, options) {
13
+ const signal = options?.signal;
14
+ if (closed || signal?.aborted)
15
+ return () => { };
16
+ const entry = {
17
+ fn,
18
+ once: Boolean(options?.once),
19
+ off() {
20
+ if (!entries.delete(entry))
21
+ return;
22
+ signal?.removeEventListener('abort', entry.off);
23
+ }
15
24
  };
25
+ entries.add(entry);
26
+ signal?.addEventListener('abort', entry.off, { once: true });
27
+ return entry.off;
16
28
  },
17
29
  fire(...args) {
18
- for (const fn of [...handlers]) {
30
+ for (const entry of [...entries]) {
31
+ if (!entries.has(entry))
32
+ continue;
33
+ if (entry.once)
34
+ entry.off();
19
35
  try {
20
- fn(...args);
36
+ entry.fn(...args);
21
37
  }
22
38
  catch (error) {
23
39
  globalThis.reportError?.(error);
@@ -25,7 +41,9 @@ function listeners() {
25
41
  }
26
42
  },
27
43
  clear() {
28
- handlers.clear();
44
+ closed = true;
45
+ for (const entry of [...entries])
46
+ entry.off();
29
47
  }
30
48
  };
31
49
  }
@@ -110,6 +128,13 @@ const gatherTimeoutDefault = 2_500;
110
128
  const maxPeersDefault = 32;
111
129
  const disconnectGrace = 8_000;
112
130
  const leaveNotice = 'meshpost/1/leave';
131
+ const rtcControlPrefix = 'meshpost/1/rtc:';
132
+ const maxRtcControlBytes = 64 * 1024;
133
+ const maxRtcQueueDepth = 16;
134
+ const maxRemoteStreamsPerPeer = 32;
135
+ const trickleBatchMs = 50;
136
+ const trickleBatchSize = 16;
137
+ const maxTrickleCandidates = 64;
113
138
  /** Start discovery immediately. Membership becomes observable as peer links open. */
114
139
  export function joinRoom(name, options) {
115
140
  if (typeof name !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(name))
@@ -144,17 +169,218 @@ export function joinRoom(name, options) {
144
169
  }) ?? false;
145
170
  const self = randomUuid();
146
171
  const peers = new Map();
172
+ const rejectedFull = new Set();
173
+ const broadcastStreams = new Set();
174
+ const peerStreams = new Map();
147
175
  const joins = listeners();
148
176
  const leaves = listeners();
149
177
  const packets = listeners();
150
178
  const drains = listeners();
151
179
  const status = listeners();
180
+ const errors = listeners();
181
+ const peerStreamListeners = listeners();
182
+ const peerStreamEndListeners = listeners();
152
183
  let state = 'connecting';
153
184
  // Start attempt numbers from an unpredictable positive offset so observers cannot guess them.
154
185
  let nextAttempt = (crypto.getRandomValues(new Uint32Array(1))[0] & 0x0fffffff) + 1;
155
186
  let stopped = false;
156
187
  let signaling;
188
+ let useTrickle = false;
157
189
  const prepareRemoteSdp = (signal) => rtcConfig.iceTransportPolicy === 'relay' ? signal.sdp : withLoopbackFallback(signal).sdp;
190
+ const prepareRemoteCandidates = (signal) => rtcConfig.iceTransportPolicy === 'relay'
191
+ ? signal.candidates
192
+ : withLoopbackFallback(signal).candidates;
193
+ const applyRemoteCandidates = (peer, link, candidates) => {
194
+ for (const item of candidates) {
195
+ if (stopped || peer.link !== link)
196
+ return;
197
+ void link.pc.addIceCandidate(item).catch(() => { });
198
+ }
199
+ };
200
+ const desiredStreamsFor = (peerId) => {
201
+ const set = new Set(broadcastStreams);
202
+ const targeted = peerStreams.get(peerId);
203
+ if (targeted) {
204
+ for (const s of targeted)
205
+ set.add(s);
206
+ }
207
+ return set;
208
+ };
209
+ const sendRtcControl = (link, payload) => {
210
+ const reliable = link.channels.reliable;
211
+ if (reliable.readyState !== 'open')
212
+ return false;
213
+ try {
214
+ reliable.send(rtcControlPrefix + JSON.stringify(payload));
215
+ return true;
216
+ }
217
+ catch {
218
+ return false;
219
+ }
220
+ };
221
+ const attachStreamToLink = (link, stream) => {
222
+ if (link.senders.has(stream))
223
+ return false;
224
+ const tracks = stream.getTracks();
225
+ if (tracks.length === 0)
226
+ return false;
227
+ const added = [];
228
+ for (const track of tracks) {
229
+ added.push(link.pc.addTrack(track, stream));
230
+ }
231
+ link.senders.set(stream, added);
232
+ link.pendingStreamEnds.delete(stream.id);
233
+ return true;
234
+ };
235
+ const detachStreamFromLink = (link, stream) => {
236
+ const added = link.senders.get(stream);
237
+ if (!added)
238
+ return false;
239
+ link.senders.delete(stream);
240
+ for (const sender of added) {
241
+ try {
242
+ link.pc.removeTrack(sender);
243
+ }
244
+ catch {
245
+ // Ignore if connection is closing.
246
+ }
247
+ }
248
+ link.pendingStreamEnds.add(stream.id);
249
+ return true;
250
+ };
251
+ const enqueueRenegotiate = (peer, link) => {
252
+ link.renegotiateQueued = true;
253
+ link.rtcQueue = link.rtcQueue.then(async () => {
254
+ if (stopped ||
255
+ peer.link !== link ||
256
+ !link.ready ||
257
+ !link.renegotiateQueued ||
258
+ link.channels.reliable.readyState !== 'open')
259
+ return;
260
+ if (link.pc.signalingState !== 'stable')
261
+ return;
262
+ link.renegotiateQueued = false;
263
+ try {
264
+ const offer = await link.pc.createOffer();
265
+ if (stopped || peer.link !== link)
266
+ return;
267
+ await link.pc.setLocalDescription(offer);
268
+ if (stopped || peer.link !== link || !link.pc.localDescription)
269
+ return;
270
+ if (sendRtcControl(link, { kind: 'offer', sdp: link.pc.localDescription.sdp })) {
271
+ for (const id of link.pendingStreamEnds) {
272
+ sendRtcControl(link, { kind: 'stream-end', id });
273
+ }
274
+ link.pendingStreamEnds.clear();
275
+ }
276
+ }
277
+ catch {
278
+ if (!stopped && peer.link === link) {
279
+ errors.fire({
280
+ code: 'media-error',
281
+ peerId: peer.id,
282
+ message: 'Failed to negotiate media tracks'
283
+ });
284
+ }
285
+ }
286
+ });
287
+ };
288
+ const handleRtcControl = (peer, link, raw) => {
289
+ if (raw.length > maxRtcControlBytes || link.rtcPending >= maxRtcQueueDepth)
290
+ return;
291
+ let msg;
292
+ try {
293
+ const parsed = JSON.parse(raw.slice(rtcControlPrefix.length));
294
+ msg = parsed && typeof parsed === 'object' ? parsed : null;
295
+ }
296
+ catch {
297
+ return;
298
+ }
299
+ if (!msg || typeof msg.kind !== 'string')
300
+ return;
301
+ if (msg.kind === 'stream-end' && typeof msg.id === 'string') {
302
+ const streamId = msg.id;
303
+ link.rtcPending++;
304
+ link.rtcQueue = link.rtcQueue.then(() => {
305
+ link.rtcPending--;
306
+ if (stopped || peer.link !== link || !link.ready)
307
+ return;
308
+ const stream = link.remoteStreams.get(streamId);
309
+ if (stream) {
310
+ link.remoteStreams.delete(streamId);
311
+ peerStreamEndListeners.fire(peer.id, stream);
312
+ }
313
+ });
314
+ return;
315
+ }
316
+ if ((msg.kind !== 'offer' && msg.kind !== 'answer') || typeof msg.sdp !== 'string')
317
+ return;
318
+ const kind = msg.kind;
319
+ const sdp = msg.sdp;
320
+ const polite = self > peer.id;
321
+ link.rtcPending++;
322
+ link.rtcQueue = link.rtcQueue.then(async () => {
323
+ try {
324
+ if (stopped || peer.link !== link || !link.ready)
325
+ return;
326
+ if (kind === 'offer') {
327
+ const collision = link.pc.signalingState !== 'stable';
328
+ if (!polite && collision)
329
+ return;
330
+ try {
331
+ if (polite && collision) {
332
+ await link.pc.setLocalDescription({ type: 'rollback' });
333
+ link.renegotiateQueued = true;
334
+ }
335
+ await link.pc.setRemoteDescription({ type: 'offer', sdp });
336
+ if (stopped || peer.link !== link)
337
+ return;
338
+ const answer = await link.pc.createAnswer();
339
+ if (stopped || peer.link !== link)
340
+ return;
341
+ await link.pc.setLocalDescription(answer);
342
+ if (stopped || peer.link !== link || !link.pc.localDescription)
343
+ return;
344
+ sendRtcControl(link, { kind: 'answer', sdp: link.pc.localDescription.sdp });
345
+ }
346
+ catch {
347
+ if (!stopped && peer.link === link) {
348
+ errors.fire({
349
+ code: 'media-error',
350
+ peerId: peer.id,
351
+ message: 'Failed to apply media offer'
352
+ });
353
+ }
354
+ }
355
+ if (!stopped && peer.link === link && link.renegotiateQueued) {
356
+ enqueueRenegotiate(peer, link);
357
+ }
358
+ }
359
+ else {
360
+ if (link.pc.signalingState !== 'have-local-offer')
361
+ return;
362
+ try {
363
+ await link.pc.setRemoteDescription({ type: 'answer', sdp });
364
+ }
365
+ catch {
366
+ if (!stopped && peer.link === link) {
367
+ errors.fire({
368
+ code: 'media-error',
369
+ peerId: peer.id,
370
+ message: 'Failed to apply media answer'
371
+ });
372
+ }
373
+ }
374
+ if (!stopped && peer.link === link && link.renegotiateQueued) {
375
+ enqueueRenegotiate(peer, link);
376
+ }
377
+ }
378
+ }
379
+ finally {
380
+ link.rtcPending--;
381
+ }
382
+ });
383
+ };
158
384
  function retry(peer) {
159
385
  if (stopped || state !== 'online' || !peer.advertised || peer.retry || peer.link)
160
386
  return;
@@ -171,8 +397,11 @@ export function joinRoom(name, options) {
171
397
  delete peer.link;
172
398
  if (link.accepted)
173
399
  peer.previous = link.attempt;
400
+ if (peer.earlyIce?.attempt === link.attempt)
401
+ delete peer.earlyIce;
174
402
  clearTimeout(link.deadline);
175
403
  clearTimeout(link.gather);
404
+ clearTimeout(link.iceFlush);
176
405
  clearTimeout(link.grace);
177
406
  const reliable = link.channels.reliable;
178
407
  if (flushLeave && reliable.readyState === 'open') {
@@ -195,8 +424,20 @@ export function joinRoom(name, options) {
195
424
  link.pc.close();
196
425
  if (!peer.advertised)
197
426
  peers.delete(peer.id);
198
- if (link.ready)
427
+ if (link.ready) {
428
+ for (const stream of [...link.remoteStreams.values()]) {
429
+ peerStreamEndListeners.fire(peer.id, stream);
430
+ }
431
+ link.remoteStreams.clear();
432
+ link.senders.clear();
433
+ link.pendingStreamEnds.clear();
199
434
  leaves.fire(peer.id);
435
+ }
436
+ else {
437
+ link.remoteStreams.clear();
438
+ link.senders.clear();
439
+ link.pendingStreamEnds.clear();
440
+ }
200
441
  if (shouldRetry)
201
442
  retry(peer);
202
443
  }
@@ -234,14 +475,51 @@ export function joinRoom(name, options) {
234
475
  ready: false,
235
476
  accepted: false,
236
477
  published: false,
237
- answerApplied: false
478
+ answerApplied: false,
479
+ remoteDescApplied: false,
480
+ pendingCandidates: [],
481
+ rtcQueue: Promise.resolve(),
482
+ rtcPending: 0,
483
+ renegotiateQueued: false,
484
+ pendingStreamEnds: new Set(),
485
+ senders: new Map(),
486
+ remoteStreams: new Map()
487
+ };
488
+ // Attach active local streams before initial createOffer() on the offerer for 0-RTT media setup.
489
+ if (self < peer.id) {
490
+ for (const stream of desiredStreamsFor(peer.id)) {
491
+ attachStreamToLink(link, stream);
492
+ }
493
+ }
494
+ const earlyStreams = [];
495
+ pc.ontrack = (event) => {
496
+ if (stopped || peer.link !== link)
497
+ return;
498
+ const stream = event.streams[0] ?? new MediaStream([event.track]);
499
+ if (link.remoteStreams.has(stream.id) || link.remoteStreams.size >= maxRemoteStreamsPerPeer)
500
+ return;
501
+ link.remoteStreams.set(stream.id, stream);
502
+ if (link.ready)
503
+ peerStreamListeners.fire(peer.id, stream);
504
+ else
505
+ earlyStreams.push(stream);
506
+ };
507
+ const reportIceFailed = (message) => {
508
+ const wasReady = link.ready;
509
+ drop(peer, link);
510
+ if (!stopped && !wasReady && !peer.iceFailedReported) {
511
+ peer.iceFailedReported = true;
512
+ errors.fire({ code: 'ice-failed', peerId: peer.id, message });
513
+ }
238
514
  };
239
515
  peer.link = link;
240
- link.deadline = setTimeout(() => drop(peer, link), timeout);
516
+ link.deadline = setTimeout(() => reportIceFailed('Connection handshake timed out'), timeout);
241
517
  pc.onconnectionstatechange = () => {
242
518
  if (peer.link !== link)
243
519
  return;
244
- if (pc.connectionState === 'failed' || pc.connectionState === 'closed')
520
+ if (pc.connectionState === 'failed')
521
+ reportIceFailed('Peer connection failed');
522
+ else if (pc.connectionState === 'closed')
245
523
  drop(peer, link);
246
524
  else if (pc.connectionState === 'disconnected') {
247
525
  link.grace ??= setTimeout(() => drop(peer, link), disconnectGrace);
@@ -252,6 +530,7 @@ export function joinRoom(name, options) {
252
530
  }
253
531
  };
254
532
  const early = [];
533
+ const earlyRtc = [];
255
534
  let earlyBytes = 0;
256
535
  for (const delivery of ['unreliable', 'reliable']) {
257
536
  const channel = channels[delivery];
@@ -268,15 +547,46 @@ export function joinRoom(name, options) {
268
547
  return;
269
548
  if (Object.values(channels).every((c) => c.readyState === 'open')) {
270
549
  clearTimeout(link.deadline);
550
+ clearTimeout(link.iceFlush);
551
+ delete link.iceFlush;
271
552
  link.ready = true;
272
553
  peer.failures = 0;
554
+ peer.iceFailedReported = false;
273
555
  joins.fire(peer.id);
556
+ for (const stream of earlyStreams) {
557
+ if (peer.link !== link || stopped)
558
+ break;
559
+ peerStreamListeners.fire(peer.id, stream);
560
+ }
561
+ earlyStreams.length = 0;
562
+ for (const raw of earlyRtc) {
563
+ if (peer.link !== link || stopped)
564
+ break;
565
+ handleRtcControl(peer, link, raw);
566
+ }
567
+ earlyRtc.length = 0;
274
568
  for (const [bytes, mode] of early) {
275
569
  if (peer.link !== link || stopped)
276
570
  break;
277
571
  packets.fire(peer.id, bytes, mode);
278
572
  }
279
573
  early.length = 0;
574
+ // Reconcile local streams (attach newly desired ones, detach any removed mid-handshake).
575
+ if (!stopped && peer.link === link) {
576
+ const desired = desiredStreamsFor(peer.id);
577
+ let needsRenegotiate = false;
578
+ for (const stream of desired) {
579
+ if (attachStreamToLink(link, stream))
580
+ needsRenegotiate = true;
581
+ }
582
+ for (const stream of [...link.senders.keys()]) {
583
+ if (!desired.has(stream) && detachStreamFromLink(link, stream)) {
584
+ needsRenegotiate = true;
585
+ }
586
+ }
587
+ if (needsRenegotiate)
588
+ enqueueRenegotiate(peer, link);
589
+ }
280
590
  }
281
591
  };
282
592
  channel.onmessage = ({ data }) => {
@@ -287,6 +597,15 @@ export function joinRoom(name, options) {
287
597
  drop(peer, link);
288
598
  return;
289
599
  }
600
+ if (typeof data === 'string' &&
601
+ delivery === 'reliable' &&
602
+ data.startsWith(rtcControlPrefix)) {
603
+ if (link.ready)
604
+ handleRtcControl(peer, link, data);
605
+ else if (earlyRtc.length < 16 && data.length <= maxRtcControlBytes)
606
+ earlyRtc.push(data);
607
+ return;
608
+ }
290
609
  if (!(data instanceof ArrayBuffer))
291
610
  return;
292
611
  if (data.byteLength > maxPacket) {
@@ -320,17 +639,22 @@ export function joinRoom(name, options) {
320
639
  await pc.setRemoteDescription({ type: 'offer', sdp: remoteOffer });
321
640
  if (peer.link !== link)
322
641
  return;
642
+ link.remoteDescApplied = true;
643
+ if (peer.earlyIce?.attempt === attempt) {
644
+ const earlyCandidates = peer.earlyIce.candidates;
645
+ delete peer.earlyIce;
646
+ applyRemoteCandidates(peer, link, earlyCandidates);
647
+ }
648
+ if (link.pendingCandidates.length > 0) {
649
+ const queued = link.pendingCandidates.splice(0);
650
+ applyRemoteCandidates(peer, link, queued);
651
+ }
323
652
  }
324
653
  link.accepted = true;
325
654
  const description = remoteOffer === undefined ? await pc.createOffer() : await pc.createAnswer();
326
655
  if (peer.link !== link)
327
656
  return;
328
- // Send one complete SDP. Publish early after gatherTimeout so unreachable STUN never stalls,
329
- // while allowing extra time when relay/TURN candidates are required or configured.
330
657
  const current = link;
331
- let hasRelay = false;
332
- let hasSrflx = false;
333
- let softExpired = false;
334
658
  const publish = (force = false) => {
335
659
  if (current.published || peer.link !== current)
336
660
  return;
@@ -345,41 +669,103 @@ export function joinRoom(name, options) {
345
669
  if (!signaling?.send(peer.id, { kind: local.type, attempt, sdp: local.sdp }))
346
670
  drop(peer, current);
347
671
  };
348
- pc.onicecandidate = (event) => {
349
- if (peer.link !== current || current.published)
350
- return;
351
- if (!event.candidate) {
352
- publish(true);
672
+ if (useTrickle) {
673
+ const outgoing = [];
674
+ let totalQueued = 0;
675
+ let gatheringDone = false;
676
+ const flushIce = () => {
677
+ clearTimeout(current.iceFlush);
678
+ delete current.iceFlush;
679
+ if (!current.published || peer.link !== current || current.ready || stopped)
680
+ return;
681
+ while (outgoing.length > 0) {
682
+ const batch = outgoing.splice(0, trickleBatchSize);
683
+ signaling?.send(peer.id, { kind: 'ice', attempt, candidates: batch });
684
+ }
685
+ };
686
+ const scheduleFlush = (immediate = false) => {
687
+ if (!current.published || peer.link !== current || current.ready || stopped)
688
+ return;
689
+ if (immediate || outgoing.length >= trickleBatchSize) {
690
+ flushIce();
691
+ }
692
+ else if (!current.iceFlush) {
693
+ current.iceFlush = setTimeout(flushIce, trickleBatchMs);
694
+ }
695
+ };
696
+ pc.onicecandidate = (event) => {
697
+ if (peer.link !== current || current.ready || stopped)
698
+ return;
699
+ if (!event.candidate) {
700
+ gatheringDone = true;
701
+ if (totalQueued < maxTrickleCandidates) {
702
+ outgoing.push({ candidate: '' });
703
+ totalQueued++;
704
+ }
705
+ scheduleFlush(true);
706
+ return;
707
+ }
708
+ if (totalQueued >= maxTrickleCandidates)
709
+ return;
710
+ outgoing.push({
711
+ candidate: event.candidate.candidate,
712
+ ...(event.candidate.sdpMid !== null ? { sdpMid: event.candidate.sdpMid } : {}),
713
+ ...(event.candidate.sdpMLineIndex !== null
714
+ ? { sdpMLineIndex: event.candidate.sdpMLineIndex }
715
+ : {})
716
+ });
717
+ totalQueued++;
718
+ scheduleFlush(false);
719
+ };
720
+ await pc.setLocalDescription(description);
721
+ if (peer.link !== current)
353
722
  return;
354
- }
355
- const type = event.candidate.type;
356
- if (type === 'relay')
357
- hasRelay = true;
358
- else if (type === 'srflx')
359
- hasSrflx = true;
360
- if (softExpired && (hasRelay || (!needsRelay && hasSrflx))) {
361
- publish(true);
362
- }
363
- };
364
- pc.onicegatheringstatechange = () => publish(false);
365
- await pc.setLocalDescription(description);
366
- if (peer.link !== current)
367
- return;
368
- publish(false);
369
- if (!current.published) {
370
- const extendedGather = options.iceGatheringTimeoutMs === undefined
371
- ? Math.min(10_000, Math.floor(timeout / 2))
372
- : gatherTimeout;
373
- current.gather = setTimeout(() => {
374
- softExpired = true;
375
- const waitingForRelay = (needsRelay && !hasRelay) || (hasTurn && !hasRelay && !hasSrflx);
376
- if (waitingForRelay && extendedGather > gatherTimeout) {
377
- current.gather = setTimeout(() => publish(true), extendedGather - gatherTimeout);
723
+ publish(true);
724
+ if (outgoing.length > 0)
725
+ scheduleFlush(gatheringDone);
726
+ }
727
+ else {
728
+ // Send one complete SDP. Publish early after gatherTimeout so unreachable STUN never stalls,
729
+ // while allowing extra time when relay/TURN candidates are required or configured.
730
+ let hasRelay = false;
731
+ let hasSrflx = false;
732
+ let softExpired = false;
733
+ pc.onicecandidate = (event) => {
734
+ if (peer.link !== current || current.published)
735
+ return;
736
+ if (!event.candidate) {
737
+ publish(true);
738
+ return;
378
739
  }
379
- else {
740
+ const type = event.candidate.type;
741
+ if (type === 'relay')
742
+ hasRelay = true;
743
+ else if (type === 'srflx')
744
+ hasSrflx = true;
745
+ if (softExpired && (hasRelay || (!needsRelay && hasSrflx))) {
380
746
  publish(true);
381
747
  }
382
- }, gatherTimeout);
748
+ };
749
+ pc.onicegatheringstatechange = () => publish(false);
750
+ await pc.setLocalDescription(description);
751
+ if (peer.link !== current)
752
+ return;
753
+ publish(false);
754
+ if (!current.published) {
755
+ const extendedGather = options.iceGatheringTimeoutMs === undefined
756
+ ? Math.min(10_000, Math.floor(timeout / 2))
757
+ : gatherTimeout;
758
+ current.gather = setTimeout(() => {
759
+ softExpired = true;
760
+ const waitingForRelay = (needsRelay && !hasRelay) || (hasTurn && !hasRelay && !hasSrflx);
761
+ if (waitingForRelay && extendedGather > gatherTimeout) {
762
+ current.gather = setTimeout(() => publish(true), extendedGather - gatherTimeout);
763
+ }
764
+ else {
765
+ publish(true);
766
+ }
767
+ }, gatherTimeout);
768
+ }
383
769
  }
384
770
  }
385
771
  catch {
@@ -444,7 +830,40 @@ export function joinRoom(name, options) {
444
830
  drop(peer, link, false, false);
445
831
  void negotiate(peer, signal.attempt, prepareRemoteSdp(signal));
446
832
  }
447
- else if (self < id &&
833
+ else if (signal.kind === 'ice') {
834
+ if (link && signal.attempt === link.attempt) {
835
+ const candidates = prepareRemoteCandidates(signal);
836
+ if (link.remoteDescApplied) {
837
+ applyRemoteCandidates(peer, link, candidates);
838
+ }
839
+ else {
840
+ for (const item of candidates) {
841
+ if (link.pendingCandidates.length >= maxTrickleCandidates)
842
+ break;
843
+ link.pendingCandidates.push(item);
844
+ }
845
+ }
846
+ }
847
+ else {
848
+ const baseline = link?.attempt ?? peer.previous ?? 0;
849
+ if (self > id &&
850
+ signal.attempt > baseline &&
851
+ (baseline === 0 || signal.attempt - baseline <= 1024)) {
852
+ if (!peer.earlyIce || signal.attempt > peer.earlyIce.attempt) {
853
+ peer.earlyIce = { attempt: signal.attempt, candidates: [] };
854
+ }
855
+ if (peer.earlyIce.attempt === signal.attempt) {
856
+ for (const item of prepareRemoteCandidates(signal)) {
857
+ if (peer.earlyIce.candidates.length >= maxTrickleCandidates)
858
+ break;
859
+ peer.earlyIce.candidates.push(item);
860
+ }
861
+ }
862
+ }
863
+ }
864
+ }
865
+ else if (signal.kind === 'answer' &&
866
+ self < id &&
448
867
  link &&
449
868
  !link.answerApplied &&
450
869
  link.attempt === signal.attempt &&
@@ -452,6 +871,15 @@ export function joinRoom(name, options) {
452
871
  link.answerApplied = true;
453
872
  void link.pc
454
873
  .setRemoteDescription({ type: 'answer', sdp: prepareRemoteSdp(signal) })
874
+ .then(() => {
875
+ if (stopped || peer.link !== link)
876
+ return;
877
+ link.remoteDescApplied = true;
878
+ if (link.pendingCandidates.length > 0) {
879
+ const queued = link.pendingCandidates.splice(0);
880
+ applyRemoteCandidates(peer, link, queued);
881
+ }
882
+ })
455
883
  .catch(() => drop(peer, link));
456
884
  }
457
885
  }
@@ -481,10 +909,25 @@ export function joinRoom(name, options) {
481
909
  }
482
910
  }
483
911
  },
912
+ error(code, message) {
913
+ if (stopped || (code !== 'decrypt-failed' && code !== 'signaling-error'))
914
+ return;
915
+ errors.fire({
916
+ code,
917
+ message: message ??
918
+ (code === 'decrypt-failed'
919
+ ? 'Failed to decrypt signaling message'
920
+ : 'Signaling adapter error')
921
+ });
922
+ },
484
923
  roster(ids) {
485
924
  if (stopped)
486
925
  return;
487
926
  const present = new Set(ids);
927
+ for (const id of [...rejectedFull]) {
928
+ if (!present.has(id) || peers.has(id))
929
+ rejectedFull.delete(id);
930
+ }
488
931
  for (const peer of peers.values()) {
489
932
  peer.advertised = present.has(peer.id);
490
933
  if (!peer.advertised) {
@@ -494,20 +937,32 @@ export function joinRoom(name, options) {
494
937
  peers.delete(peer.id);
495
938
  }
496
939
  }
940
+ const newlyRejected = [];
497
941
  for (const id of present) {
498
942
  if (id === self)
499
943
  continue;
500
944
  let peer = peers.get(id);
501
945
  if (!peer) {
502
- if (peers.size >= maxPeers)
946
+ if (peers.size >= maxPeers) {
947
+ if (!rejectedFull.has(id)) {
948
+ rejectedFull.add(id);
949
+ newlyRejected.push(id);
950
+ }
503
951
  continue;
952
+ }
504
953
  peer = { id, advertised: true, previous: null, failures: 0 };
505
954
  peers.set(id, peer);
506
955
  }
507
956
  discover(peer);
508
957
  }
958
+ for (const id of newlyRejected) {
959
+ if (stopped)
960
+ return;
961
+ errors.fire({ code: 'room-full', peerId: id, message: 'Room reached maxPeers limit' });
962
+ }
509
963
  }
510
964
  });
965
+ useTrickle = signaling.trickle === true;
511
966
  for (const peer of peers.values())
512
967
  discover(peer);
513
968
  const connected = () => [...peers.values()].filter((p) => p.link?.ready).map((p) => p.id);
@@ -524,6 +979,69 @@ export function joinRoom(name, options) {
524
979
  onPeerJoin: joins.add,
525
980
  onPeerLeave: leaves.add,
526
981
  onSignalingChange: status.add,
982
+ onError: errors.add,
983
+ onPeerStream: peerStreamListeners.add,
984
+ onPeerStreamEnd: peerStreamEndListeners.add,
985
+ addStream(stream, to) {
986
+ if (stopped)
987
+ throw new Error('Room is closed');
988
+ if (!stream || typeof stream.getTracks !== 'function')
989
+ throw new TypeError('Expected a MediaStream');
990
+ if (to === undefined) {
991
+ broadcastStreams.add(stream);
992
+ for (const peer of peers.values()) {
993
+ const link = peer.link;
994
+ if (link?.ready && attachStreamToLink(link, stream)) {
995
+ enqueueRenegotiate(peer, link);
996
+ }
997
+ }
998
+ }
999
+ else {
1000
+ if (to === self)
1001
+ return;
1002
+ let set = peerStreams.get(to);
1003
+ if (!set) {
1004
+ set = new Set();
1005
+ peerStreams.set(to, set);
1006
+ }
1007
+ set.add(stream);
1008
+ const peer = peers.get(to);
1009
+ const link = peer?.link;
1010
+ if (peer && link?.ready && attachStreamToLink(link, stream)) {
1011
+ enqueueRenegotiate(peer, link);
1012
+ }
1013
+ }
1014
+ },
1015
+ removeStream(stream, to) {
1016
+ if (stopped || !stream)
1017
+ return;
1018
+ if (to === undefined) {
1019
+ if (!broadcastStreams.delete(stream))
1020
+ return;
1021
+ for (const peer of peers.values()) {
1022
+ if (peerStreams.get(peer.id)?.has(stream))
1023
+ continue;
1024
+ const link = peer.link;
1025
+ if (link?.ready && detachStreamFromLink(link, stream)) {
1026
+ enqueueRenegotiate(peer, link);
1027
+ }
1028
+ }
1029
+ }
1030
+ else {
1031
+ const set = peerStreams.get(to);
1032
+ if (!set?.delete(stream))
1033
+ return;
1034
+ if (set.size === 0)
1035
+ peerStreams.delete(to);
1036
+ if (broadcastStreams.has(stream))
1037
+ return;
1038
+ const peer = peers.get(to);
1039
+ const link = peer?.link;
1040
+ if (peer && link?.ready && detachStreamFromLink(link, stream)) {
1041
+ enqueueRenegotiate(peer, link);
1042
+ }
1043
+ }
1044
+ },
527
1045
  async getStats(peerId) {
528
1046
  if (stopped || peerId === self)
529
1047
  return null;
@@ -591,9 +1109,21 @@ export function joinRoom(name, options) {
591
1109
  drop(peer, peer.link, true, false);
592
1110
  }
593
1111
  peers.clear();
1112
+ rejectedFull.clear();
1113
+ broadcastStreams.clear();
1114
+ peerStreams.clear();
594
1115
  if (!wasClosed)
595
1116
  status.fire('closed');
596
- for (const group of [joins, leaves, packets, drains, status])
1117
+ for (const group of [
1118
+ joins,
1119
+ leaves,
1120
+ packets,
1121
+ drains,
1122
+ status,
1123
+ errors,
1124
+ peerStreamListeners,
1125
+ peerStreamEndListeners
1126
+ ])
597
1127
  group.clear();
598
1128
  }
599
1129
  };