@yrzhao/aves-core 1.0.1 → 1.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.
Files changed (36) hide show
  1. package/README.md +131 -75
  2. package/dist/core/AvesClient.d.ts +35 -8
  3. package/dist/core/AvesClient.js +351 -52
  4. package/dist/core/AvesError.d.ts +1 -1
  5. package/dist/core/EventEmitter.d.ts +8 -16
  6. package/dist/core/EventEmitter.js +41 -10
  7. package/dist/core/SignalingClient.d.ts +39 -44
  8. package/dist/core/SignalingClient.js +434 -78
  9. package/dist/core/WebRTCManager.d.ts +68 -99
  10. package/dist/core/WebRTCManager.js +611 -133
  11. package/dist/core/webrtc/channels.d.ts +6 -0
  12. package/dist/core/webrtc/channels.js +15 -0
  13. package/dist/core/webrtc/fileTransfer.d.ts +46 -3
  14. package/dist/core/webrtc/fileTransfer.js +725 -78
  15. package/dist/core/webrtc/mediaTracks.d.ts +38 -5
  16. package/dist/core/webrtc/mediaTracks.js +269 -58
  17. package/dist/esm/core/AvesClient.d.ts +35 -8
  18. package/dist/esm/core/AvesClient.js +351 -52
  19. package/dist/esm/core/AvesError.d.ts +1 -1
  20. package/dist/esm/core/EventEmitter.d.ts +8 -16
  21. package/dist/esm/core/EventEmitter.js +41 -10
  22. package/dist/esm/core/SignalingClient.d.ts +39 -44
  23. package/dist/esm/core/SignalingClient.js +434 -78
  24. package/dist/esm/core/WebRTCManager.d.ts +68 -99
  25. package/dist/esm/core/WebRTCManager.js +612 -134
  26. package/dist/esm/core/webrtc/channels.d.ts +6 -0
  27. package/dist/esm/core/webrtc/channels.js +14 -0
  28. package/dist/esm/core/webrtc/fileTransfer.d.ts +46 -3
  29. package/dist/esm/core/webrtc/fileTransfer.js +722 -77
  30. package/dist/esm/core/webrtc/mediaTracks.d.ts +38 -5
  31. package/dist/esm/core/webrtc/mediaTracks.js +269 -58
  32. package/dist/esm/index.d.ts +2 -1
  33. package/dist/esm/types/types.d.ts +126 -9
  34. package/dist/index.d.ts +2 -1
  35. package/dist/types/types.d.ts +126 -9
  36. package/package.json +22 -6
@@ -1,18 +1,43 @@
1
1
  import { AvesError } from "./AvesError.js";
2
- import { FILE_CHANNEL_LABEL, MESSAGE_CHANNEL_LABEL, getChannelKind, isPeerChannels, normalizePeerChannels, } from "./webrtc/channels.js";
2
+ import { FILE_CHANNEL_LABEL, MESSAGE_CHANNEL_LABEL, getChannelKind, isPeerChannels, normalizePeerChannels, resolveKnownChannelKind, } from "./webrtc/channels.js";
3
3
  import { DEFAULT_FILE_CHUNK_SIZE, FileTransferManager, isFileControlMessage, } from "./webrtc/fileTransfer.js";
4
4
  import { MediaTrackManager } from "./webrtc/mediaTracks.js";
5
5
  import { errorMessage, serializeUserMessage } from "./webrtc/messages.js";
6
+ const DEFAULT_ICE_DISCONNECT_GRACE_MS = 5000;
7
+ const MAX_PENDING_ICE_CANDIDATES = 200;
8
+ function unrefTimer(timer) {
9
+ const maybeNodeTimer = timer;
10
+ maybeNodeTimer.unref?.();
11
+ }
6
12
  /**
7
- * WebRTCManager - Manages WebRTC PeerConnections, DataChannels, and media tracks
13
+ * WebRTCManager - Manages WebRTC PeerConnections, Perfect Negotiation,
14
+ * ICE candidate buffering, DataChannels, file transfer, media tracks, and RTCStats.
8
15
  */
9
16
  export class WebRTCManager {
10
- constructor(iceServers, fileChunkSize = DEFAULT_FILE_CHUNK_SIZE, videoConstraints = {}) {
17
+ constructor(iceServersOrOptions, fileChunkSize = DEFAULT_FILE_CHUNK_SIZE, videoConstraints = {}) {
18
+ this.politeIceRestartTimers = new Map();
19
+ const normalized = Array.isArray(iceServersOrOptions)
20
+ ? {
21
+ iceServers: iceServersOrOptions,
22
+ fileChunkSize,
23
+ videoConstraints,
24
+ }
25
+ : iceServersOrOptions;
11
26
  this.peerConnections = new Map();
12
27
  this.dataChannels = new Map();
13
- this.iceServers = iceServers;
28
+ this.iceServers = normalized.iceServers;
29
+ this.rtcConfiguration = normalized.rtcConfiguration ?? {};
30
+ this.iceDisconnectGraceMs =
31
+ normalized.iceDisconnectGraceMs !== undefined &&
32
+ normalized.iceDisconnectGraceMs >= 0
33
+ ? normalized.iceDisconnectGraceMs
34
+ : DEFAULT_ICE_DISCONNECT_GRACE_MS;
35
+ this.pendingIceCandidates = new Map();
36
+ this.disconnectGraceTimers = new Map();
37
+ this.negotiationStates = new Map();
14
38
  this.fileTransfers = new FileTransferManager({
15
- fileChunkSize,
39
+ fileChunkSize: normalized.fileChunkSize ?? DEFAULT_FILE_CHUNK_SIZE,
40
+ config: normalized.fileTransfer,
16
41
  getActivePeers: () => this.getActivePeers(),
17
42
  isFileChannelReady: (peerId) => this.isFileChannelReady(peerId),
18
43
  getMessageChannel: (peerId) => this.getMessageChannel(peerId),
@@ -21,7 +46,9 @@ export class WebRTCManager {
21
46
  this.messageCallbacks = new Set();
22
47
  this.connectionStateCallbacks = new Map();
23
48
  this.dataChannelStateCallbacks = new Map();
49
+ this.fileChannelStateCallbacks = new Map();
24
50
  this.iceCandidateCallbacks = new Map();
51
+ this.negotiationOfferCallbacks = new Set();
25
52
  this.outgoingTransfers = this.fileTransfers.outgoingTransfers;
26
53
  this.incomingTransfers = this.fileTransfers.incomingTransfers;
27
54
  this.readyResolvers = this.fileTransfers.readyResolvers;
@@ -34,47 +61,134 @@ export class WebRTCManager {
34
61
  this.fileTransfers.fileTransferCompletedCallbacks;
35
62
  this.fileTransferFailedCallbacks =
36
63
  this.fileTransfers.fileTransferFailedCallbacks;
37
- this.mediaTracks = new MediaTrackManager(this.peerConnections, () => this.getActivePeers(), videoConstraints);
64
+ this.errorCallbacks = new Set();
65
+ this.mediaTracks = new MediaTrackManager(this.peerConnections, () => this.getActivePeers(), normalized.videoConstraints ?? {}, normalized.audioConstraints ?? {}, (err) => this.emitError(err));
38
66
  this.videoSenders = this.mediaTracks.videoSenders;
39
67
  this.remoteAudioTrackCallbacks = this.mediaTracks.remoteAudioTrackCallbacks;
40
68
  this.localAudioStateCallbacks = this.mediaTracks.localAudioStateCallbacks;
41
69
  this.remoteVideoTrackCallbacks = this.mediaTracks.remoteVideoTrackCallbacks;
42
70
  this.localVideoStateCallbacks = this.mediaTracks.localVideoStateCallbacks;
43
71
  this.screenShareStateCallbacks = this.mediaTracks.screenShareStateCallbacks;
44
- this.errorCallbacks = new Set();
72
+ }
73
+ /**
74
+ * Update ICE servers dynamically (e.g. when rotating ephemeral TURN credentials).
75
+ * Applies immediately to existing peer connections when supported by the browser.
76
+ */
77
+ updateIceServers(iceServers) {
78
+ this.iceServers = [...iceServers];
79
+ const nextConfig = {
80
+ ...this.rtcConfiguration,
81
+ iceServers: this.iceServers,
82
+ };
83
+ this.peerConnections.forEach((pc, peerId) => {
84
+ const configurablePc = pc;
85
+ if (typeof configurablePc.setConfiguration === "function") {
86
+ try {
87
+ configurablePc.setConfiguration(nextConfig);
88
+ }
89
+ catch (error) {
90
+ this.emitError(new AvesError({
91
+ message: `Failed to update ICE configuration for ${peerId}: ${errorMessage(error)}`,
92
+ code: "WEBRTC_ICE_FAILED",
93
+ stage: "transport",
94
+ retryable: true,
95
+ peerId,
96
+ cause: error,
97
+ }));
98
+ }
99
+ }
100
+ });
101
+ }
102
+ /**
103
+ * Mark a peer as polite (accepts rollback on offer glare) or impolite.
104
+ */
105
+ setPeerPolite(peerId, polite) {
106
+ const state = this.getOrCreateNegotiationState(peerId);
107
+ state.polite = polite;
45
108
  }
46
109
  /**
47
110
  * Create a new PeerConnection for the specified peer.
48
111
  * If a connection already exists, returns the existing connection.
49
112
  */
50
- createPeerConnection(peerId) {
113
+ createPeerConnection(peerId, options) {
51
114
  const existing = this.peerConnections.get(peerId);
52
115
  if (existing) {
116
+ if (options?.polite !== undefined) {
117
+ this.setPeerPolite(peerId, options.polite);
118
+ }
53
119
  return existing;
54
120
  }
55
121
  const pc = new RTCPeerConnection({
122
+ ...this.rtcConfiguration,
56
123
  iceServers: this.iceServers,
57
124
  });
58
125
  this.peerConnections.set(peerId, pc);
59
126
  this.dataChannels.set(peerId, {});
127
+ this.negotiationStates.set(peerId, {
128
+ polite: options?.polite ?? false,
129
+ makingOffer: false,
130
+ ignoreOffer: false,
131
+ isSettingRemoteAnswerPending: false,
132
+ iceRestartAttempted: false,
133
+ });
60
134
  this.setupPeerConnection(peerId, pc);
61
135
  return pc;
62
136
  }
63
137
  /**
64
138
  * Create an offer for the specified peer.
65
- * The offer side creates both the message and file channels.
139
+ * The offer side creates both the message and file channels and pre-creates
140
+ * sendrecv audio/video transceivers.
66
141
  */
67
- async createOffer(peerId) {
142
+ async createOffer(peerId, options) {
68
143
  const pc = this.getPeerConnection(peerId);
144
+ const state = this.getOrCreateNegotiationState(peerId);
69
145
  this.ensureDataChannel(peerId, pc, MESSAGE_CHANNEL_LABEL);
70
146
  this.ensureDataChannel(peerId, pc, FILE_CHANNEL_LABEL);
71
- const offer = await pc.createOffer();
72
- await pc.setLocalDescription(offer);
73
- return offer;
147
+ this.mediaTracks.prepareOfferTransceivers(peerId, pc);
148
+ state.ignoreOffer = false;
149
+ state.makingOffer = true;
150
+ try {
151
+ const offer = await pc.createOffer(options);
152
+ await pc.setLocalDescription(offer);
153
+ return pc.localDescription?.type && pc.localDescription?.sdp
154
+ ? pc.localDescription
155
+ : offer;
156
+ }
157
+ finally {
158
+ state.makingOffer = false;
159
+ }
160
+ }
161
+ /**
162
+ * Create an answer for the specified peer using Perfect Negotiation glare handling.
163
+ * Returns null when an impolite peer intentionally ignores a colliding offer.
164
+ */
165
+ async handleRemoteOffer(peerId, offer) {
166
+ const pc = this.getPeerConnection(peerId);
167
+ const state = this.getOrCreateNegotiationState(peerId);
168
+ const signalingState = pc.signalingState ?? "stable";
169
+ const readyForOffer = !state.makingOffer &&
170
+ (signalingState === "stable" || state.isSettingRemoteAnswerPending);
171
+ const offerCollision = !readyForOffer;
172
+ state.ignoreOffer = !state.polite && offerCollision;
173
+ if (state.ignoreOffer) {
174
+ return null;
175
+ }
176
+ if (offerCollision && signalingState !== "stable") {
177
+ try {
178
+ await pc.setLocalDescription({ type: "rollback" });
179
+ }
180
+ catch {
181
+ // Fallback for mock RTCPeerConnection implementations without rollback support.
182
+ }
183
+ }
184
+ const answer = await this.createAnswer(peerId, offer);
185
+ return pc.localDescription?.type && pc.localDescription?.sdp
186
+ ? pc.localDescription
187
+ : answer;
74
188
  }
75
189
  /**
76
190
  * Create an answer for the specified peer.
77
- * The answer side receives data channels from the remote offer.
191
+ * Preserved for backward compatibility with direct callers and unit tests.
78
192
  */
79
193
  async createAnswer(peerId, offer) {
80
194
  const pc = this.getPeerConnection(peerId);
@@ -82,28 +196,72 @@ export class WebRTCManager {
82
196
  this.setupDataChannel(peerId, event.channel);
83
197
  };
84
198
  await pc.setRemoteDescription(new RTCSessionDescription(offer));
199
+ this.mediaTracks.bindAnswerTransceivers(peerId, pc);
200
+ await this.flushPendingIceCandidates(peerId);
85
201
  const answer = await pc.createAnswer();
86
202
  await pc.setLocalDescription(answer);
87
203
  return answer;
88
204
  }
89
205
  /**
90
- * Set the remote answer for the specified peer.
206
+ * Set the remote answer for the specified peer and flush buffered ICE candidates.
91
207
  */
92
208
  async setRemoteAnswer(peerId, answer) {
93
209
  const pc = this.getPeerConnection(peerId);
94
- await pc.setRemoteDescription(new RTCSessionDescription(answer));
210
+ const state = this.getOrCreateNegotiationState(peerId);
211
+ // Reset glare ignoreOffer flag once our own offer receives an answer so
212
+ // subsequent ICE candidates for this session are never dropped.
213
+ state.ignoreOffer = false;
214
+ state.isSettingRemoteAnswerPending = true;
215
+ try {
216
+ await pc.setRemoteDescription(new RTCSessionDescription(answer));
217
+ }
218
+ finally {
219
+ state.isSettingRemoteAnswerPending = false;
220
+ }
221
+ await this.flushPendingIceCandidates(peerId);
95
222
  }
96
223
  /**
97
224
  * Add an ICE candidate for the specified peer.
225
+ * Buffers candidates arriving before PeerConnection or remoteDescription is ready.
98
226
  */
99
227
  async addIceCandidate(peerId, candidate) {
100
- const pc = this.getPeerConnection(peerId);
101
- await pc.addIceCandidate(new RTCIceCandidate(candidate));
228
+ const pc = this.peerConnections.get(peerId);
229
+ const state = this.negotiationStates.get(peerId);
230
+ // Buffer early candidates when remoteDescription has not been applied yet.
231
+ if (!pc || !pc.remoteDescription) {
232
+ if (state?.ignoreOffer) {
233
+ return;
234
+ }
235
+ this.enqueueIceCandidate(peerId, candidate);
236
+ return;
237
+ }
238
+ // Per W3C Perfect Negotiation: apply candidate and suppress errors only
239
+ // when an offer glare caused us to ignore the remote offer.
240
+ try {
241
+ await pc.addIceCandidate(new RTCIceCandidate(candidate));
242
+ }
243
+ catch (error) {
244
+ if (!state?.ignoreOffer) {
245
+ throw error;
246
+ }
247
+ }
248
+ }
249
+ /**
250
+ * Trigger ICE restart for a peer and emit the fresh offer via onNegotiationOffer.
251
+ */
252
+ async restartIce(peerId) {
253
+ const pc = this.peerConnections.get(peerId);
254
+ if (!pc) {
255
+ return null;
256
+ }
257
+ // Explicitly create an iceRestart offer without also calling pc.restartIce()
258
+ // so browsers do not queue a duplicate onnegotiationneeded offer.
259
+ const offer = await this.createOffer(peerId, { iceRestart: true });
260
+ this.negotiationOfferCallbacks.forEach((cb) => cb(peerId, offer));
261
+ return offer;
102
262
  }
103
263
  /**
104
264
  * Send a JSON message to all connected peers.
105
- * Peers with unavailable channels are skipped gracefully;
106
- * the message is delivered to every ready peer.
107
265
  */
108
266
  sendMessage(message) {
109
267
  const payload = serializeUserMessage(message);
@@ -116,7 +274,14 @@ export class WebRTCManager {
116
274
  channels.message.send(payload);
117
275
  }
118
276
  catch (error) {
119
- this.emitError(new AvesError({ message: `Failed to send message to ${peerId}: ${errorMessage(error)}`, code: "MESSAGE_SEND_FAILED", stage: "transport", retryable: true, peerId }));
277
+ this.emitError(new AvesError({
278
+ message: `Failed to send message to ${peerId}: ${errorMessage(error)}`,
279
+ code: "MESSAGE_SEND_FAILED",
280
+ stage: "transport",
281
+ retryable: true,
282
+ peerId,
283
+ cause: error,
284
+ }));
120
285
  }
121
286
  });
122
287
  }
@@ -126,7 +291,13 @@ export class WebRTCManager {
126
291
  sendMessageToPeer(peerId, message) {
127
292
  const dataChannel = this.getMessageChannel(peerId);
128
293
  if (dataChannel.readyState !== "open") {
129
- throw new AvesError({ message: `DataChannel not ready for ${peerId}, state: ${dataChannel.readyState}`, code: "MESSAGE_CHANNEL_NOT_READY", stage: "transport", retryable: true, peerId });
294
+ throw new AvesError({
295
+ message: `DataChannel not ready for ${peerId}, state: ${dataChannel.readyState}`,
296
+ code: "MESSAGE_CHANNEL_NOT_READY",
297
+ stage: "transport",
298
+ retryable: true,
299
+ peerId,
300
+ });
130
301
  }
131
302
  dataChannel.send(serializeUserMessage(message));
132
303
  }
@@ -137,124 +308,161 @@ export class WebRTCManager {
137
308
  return this.fileTransfers.sendFile(blob, options);
138
309
  }
139
310
  /**
140
- * Start capturing local audio and bind it to current peer connections.
311
+ * Cancel an active file transfer with a peer.
141
312
  */
142
- async startVoice() {
143
- return this.mediaTracks.startVoice();
313
+ cancelFileTransfer(peerId, transferId) {
314
+ return this.fileTransfers.cancelTransfer(peerId, transferId);
315
+ }
316
+ // ========== Voice Methods ==========
317
+ async startVoice(constraints) {
318
+ return this.mediaTracks.startVoice(constraints);
319
+ }
320
+ async switchAudioDevice(deviceId) {
321
+ return this.mediaTracks.switchAudioDevice(deviceId);
144
322
  }
145
- /**
146
- * Stop local audio capture and detach it from active peers.
147
- */
148
323
  stopVoice() {
149
324
  this.mediaTracks.stopVoice();
150
325
  }
151
- /**
152
- * Toggle local mute state.
153
- */
154
326
  setMuted(muted) {
155
327
  this.mediaTracks.setMuted(muted);
156
328
  }
157
- /**
158
- * Read current local audio state.
159
- */
160
329
  getLocalAudioState() {
161
330
  return this.mediaTracks.getLocalAudioState();
162
331
  }
163
- /**
164
- * Read current remote audio stream for a peer.
165
- */
166
332
  getRemoteAudioStream(peerId) {
167
333
  return this.mediaTracks.getRemoteAudioStream(peerId);
168
334
  }
169
335
  // ========== Video Methods ==========
170
- /**
171
- * Start capturing local camera video and bind it to current peer connections.
172
- * Idempotent: returns the existing stream if already active.
173
- */
174
336
  async startVideo(constraints) {
175
337
  return this.mediaTracks.startVideo(constraints);
176
338
  }
177
- /**
178
- * Stop local camera capture and detach it from active peers.
179
- */
339
+ async switchVideoDevice(deviceId) {
340
+ return this.mediaTracks.switchVideoDevice(deviceId);
341
+ }
180
342
  stopVideo() {
181
343
  this.mediaTracks.stopVideo();
182
344
  }
183
- /**
184
- * Toggle local video mute state (camera on/off).
185
- */
186
345
  setVideoMuted(muted) {
187
346
  this.mediaTracks.setVideoMuted(muted);
188
347
  }
189
- /**
190
- * Read current local video state.
191
- */
192
348
  getLocalVideoState() {
193
349
  return this.mediaTracks.getLocalVideoState();
194
350
  }
195
- /**
196
- * Read current remote video stream for a peer.
197
- */
198
351
  getRemoteVideoStream(peerId) {
199
352
  return this.mediaTracks.getRemoteVideoStream(peerId);
200
353
  }
201
354
  // ========== Screen Share Methods ==========
202
- /**
203
- * Start screen sharing. Replaces the camera video track with the display track
204
- * on all active peer connections. The camera track is saved and restored when
205
- * screen sharing stops.
206
- */
207
- async startScreenShare() {
208
- return this.mediaTracks.startScreenShare();
355
+ async startScreenShare(options) {
356
+ return this.mediaTracks.startScreenShare(options);
209
357
  }
210
- /**
211
- * Stop screen sharing and restore the camera video track (if it was active).
212
- */
213
358
  stopScreenShare() {
214
359
  this.mediaTracks.stopScreenShare();
215
360
  }
216
- /**
217
- * Read current screen share state.
218
- */
219
361
  getScreenShareState() {
220
362
  return this.mediaTracks.getScreenShareState();
221
363
  }
222
- // ========== Video / Screen Share Callback Registration ==========
223
- /**
224
- * Register a callback for remote video tracks.
225
- */
364
+ // ========== Quality & Diagnostics (RTCStats) ==========
365
+ async getPeerStats(peerId) {
366
+ const pc = this.peerConnections.get(peerId);
367
+ if (!pc || typeof pc.getStats !== "function") {
368
+ return null;
369
+ }
370
+ const report = await pc.getStats();
371
+ let rttMs = null;
372
+ let bytesSent = 0;
373
+ let bytesReceived = 0;
374
+ let packetsLost = 0;
375
+ let localCandidateId;
376
+ let remoteCandidateId;
377
+ const candidateTypes = new Map();
378
+ report.forEach((stat) => {
379
+ if (stat.type === "local-candidate" || stat.type === "remote-candidate") {
380
+ if (typeof stat.id === "string" && typeof stat.candidateType === "string") {
381
+ candidateTypes.set(stat.id, stat.candidateType);
382
+ }
383
+ }
384
+ else if (stat.type === "candidate-pair" &&
385
+ (stat.state === "succeeded" || stat.nominated === true)) {
386
+ if (typeof stat.currentRoundTripTime === "number") {
387
+ rttMs = Math.round(stat.currentRoundTripTime * 1000);
388
+ }
389
+ if (typeof stat.bytesSent === "number") {
390
+ bytesSent = Math.max(bytesSent, stat.bytesSent);
391
+ }
392
+ if (typeof stat.bytesReceived === "number") {
393
+ bytesReceived = Math.max(bytesReceived, stat.bytesReceived);
394
+ }
395
+ if (typeof stat.localCandidateId === "string") {
396
+ localCandidateId = stat.localCandidateId;
397
+ }
398
+ if (typeof stat.remoteCandidateId === "string") {
399
+ remoteCandidateId = stat.remoteCandidateId;
400
+ }
401
+ }
402
+ else if (stat.type === "inbound-rtp") {
403
+ if (typeof stat.packetsLost === "number" && stat.packetsLost > 0) {
404
+ packetsLost += stat.packetsLost;
405
+ }
406
+ if (typeof stat.bytesReceived === "number") {
407
+ bytesReceived = Math.max(bytesReceived, stat.bytesReceived);
408
+ }
409
+ }
410
+ else if (stat.type === "outbound-rtp") {
411
+ if (typeof stat.bytesSent === "number") {
412
+ bytesSent = Math.max(bytesSent, stat.bytesSent);
413
+ }
414
+ }
415
+ });
416
+ const localCandidateType = localCandidateId
417
+ ? candidateTypes.get(localCandidateId)
418
+ : undefined;
419
+ const remoteCandidateType = remoteCandidateId
420
+ ? candidateTypes.get(remoteCandidateId)
421
+ : undefined;
422
+ const candidatePairType = normalizeCandidatePairType(localCandidateType ?? remoteCandidateType);
423
+ return {
424
+ peerId,
425
+ timestamp: Date.now(),
426
+ rttMs,
427
+ bytesSent,
428
+ bytesReceived,
429
+ packetsLost,
430
+ candidatePairType,
431
+ localCandidateType,
432
+ remoteCandidateType,
433
+ };
434
+ }
435
+ async getAllPeerStats() {
436
+ const peers = this.getActivePeers();
437
+ const results = await Promise.all(peers.map((peerId) => this.getPeerStats(peerId).catch(() => null)));
438
+ return results.filter((stat) => stat !== null);
439
+ }
440
+ // ========== Callback Registration ==========
226
441
  onRemoteVideoTrack(callback) {
227
442
  this.mediaTracks.onRemoteVideoTrack(callback);
228
443
  }
229
- /**
230
- * Register a callback for local video state changes.
231
- */
232
444
  onLocalVideoStateChange(callback) {
233
445
  this.mediaTracks.onLocalVideoStateChange(callback);
234
446
  }
235
- /**
236
- * Register a callback for screen share state changes.
237
- */
238
447
  onScreenShareStateChange(callback) {
239
448
  this.mediaTracks.onScreenShareStateChange(callback);
240
449
  }
241
- // ========== Error Callback Registration ==========
242
- /**
243
- * Register a callback for WebRTCManager-level errors
244
- * (e.g. DataChannel failures, message parse errors).
245
- */
450
+ onRemoteTrackEnded(callback) {
451
+ this.mediaTracks.onRemoteTrackEnded(callback);
452
+ }
453
+ onRemoteTrackMuted(callback) {
454
+ this.mediaTracks.onRemoteTrackMuted(callback);
455
+ }
456
+ onNegotiationOffer(callback) {
457
+ this.negotiationOfferCallbacks.add(callback);
458
+ }
246
459
  onError(callback) {
247
460
  this.errorCallbacks.add(callback);
248
461
  }
249
- // ========== Emit Helpers ==========
250
462
  emitError(error) {
251
463
  this.errorCallbacks.forEach((callback) => callback(error));
252
464
  }
253
- /**
254
- * Register a callback for ICE candidates from the specified peer.
255
- */
256
465
  onIceCandidate(peerId, callback) {
257
- // Ensure the peer connection exists
258
466
  this.getPeerConnection(peerId);
259
467
  let callbacks = this.iceCandidateCallbacks.get(peerId);
260
468
  if (!callbacks) {
@@ -263,9 +471,6 @@ export class WebRTCManager {
263
471
  }
264
472
  callbacks.add(callback);
265
473
  }
266
- /**
267
- * Register a callback for connection state changes.
268
- */
269
474
  onConnectionStateChange(peerId, callback) {
270
475
  let callbacks = this.connectionStateCallbacks.get(peerId);
271
476
  if (!callbacks) {
@@ -274,9 +479,6 @@ export class WebRTCManager {
274
479
  }
275
480
  callbacks.add(callback);
276
481
  }
277
- /**
278
- * Register a callback for main DataChannel state changes.
279
- */
280
482
  onDataChannelStateChange(peerId, callback) {
281
483
  let callbacks = this.dataChannelStateCallbacks.get(peerId);
282
484
  if (!callbacks) {
@@ -285,9 +487,14 @@ export class WebRTCManager {
285
487
  }
286
488
  callbacks.add(callback);
287
489
  }
288
- /**
289
- * Register a callback for incoming user messages.
290
- */
490
+ onFileChannelStateChange(peerId, callback) {
491
+ let callbacks = this.fileChannelStateCallbacks.get(peerId);
492
+ if (!callbacks) {
493
+ callbacks = new Set();
494
+ this.fileChannelStateCallbacks.set(peerId, callbacks);
495
+ }
496
+ callbacks.add(callback);
497
+ }
291
498
  onMessage(callback) {
292
499
  this.messageCallbacks.add(callback);
293
500
  }
@@ -313,16 +520,32 @@ export class WebRTCManager {
313
520
  * Close the connection with a specific peer.
314
521
  */
315
522
  closePeerConnection(peerId) {
316
- this.failActiveTransfers(peerId, new AvesError({ message: `Peer connection closed for ${peerId}`, code: "WEBRTC_CONNECTION_FAILED", stage: "transport", retryable: false, peerId }));
523
+ this.clearDisconnectGraceTimer(peerId);
524
+ this.failActiveTransfers(peerId, new AvesError({
525
+ message: `Peer connection closed for ${peerId}`,
526
+ code: "WEBRTC_CONNECTION_FAILED",
527
+ stage: "transport",
528
+ retryable: false,
529
+ peerId,
530
+ }));
317
531
  const channels = normalizePeerChannels(this.dataChannels.get(peerId));
318
532
  channels?.message?.close();
319
533
  channels?.file?.close();
320
534
  this.dataChannels.delete(peerId);
321
535
  const pc = this.peerConnections.get(peerId);
536
+ const previousState = pc?.connectionState;
537
+ const stateCallbacks = this.connectionStateCallbacks.get(peerId);
322
538
  if (pc) {
539
+ pc.onconnectionstatechange = null;
540
+ pc.onicecandidate = null;
541
+ pc.onnegotiationneeded = null;
542
+ pc.ondatachannel = null;
543
+ pc.ontrack = null;
323
544
  pc.close();
324
545
  this.peerConnections.delete(peerId);
325
546
  }
547
+ this.pendingIceCandidates.delete(peerId);
548
+ this.negotiationStates.delete(peerId);
326
549
  this.clearReadyResolver(peerId);
327
550
  this.clearCompletionResolver(peerId);
328
551
  this.outgoingTransfers.delete(peerId);
@@ -330,20 +553,23 @@ export class WebRTCManager {
330
553
  this.mediaTracks.closePeer(peerId);
331
554
  this.connectionStateCallbacks.delete(peerId);
332
555
  this.dataChannelStateCallbacks.delete(peerId);
556
+ this.fileChannelStateCallbacks.delete(peerId);
333
557
  this.iceCandidateCallbacks.delete(peerId);
558
+ // Notify listeners if we programmatically closed an active/disconnected PC
559
+ // (e.g. grace-window expiry) so upper layers never retain stale peer state.
560
+ if (pc &&
561
+ previousState !== "closed" &&
562
+ previousState !== "failed" &&
563
+ stateCallbacks) {
564
+ stateCallbacks.forEach((cb) => cb("closed"));
565
+ }
334
566
  }
335
- /**
336
- * Close all peer connections while preserving local media capture.
337
- * Used during signaling reconnect restore so camera/mic intent survives.
338
- */
339
567
  closeAllPeerConnections() {
340
568
  this.getActivePeers().forEach((peerId) => {
341
569
  this.closePeerConnection(peerId);
342
570
  });
571
+ this.pendingIceCandidates.clear();
343
572
  }
344
- /**
345
- * Close all connections and clean up resources.
346
- */
347
573
  closeAll() {
348
574
  this.closeAllPeerConnections();
349
575
  this.stopVoice();
@@ -353,52 +579,176 @@ export class WebRTCManager {
353
579
  destroy() {
354
580
  this.closeAll();
355
581
  this.messageCallbacks.clear();
582
+ this.negotiationOfferCallbacks.clear();
356
583
  this.fileTransfers.clearCallbacks();
357
584
  this.mediaTracks.clearCallbacks();
358
585
  this.errorCallbacks.clear();
359
586
  }
360
- /**
361
- * Get all active peer IDs.
362
- */
363
587
  getActivePeers() {
364
588
  return Array.from(this.peerConnections.keys());
365
589
  }
366
- /**
367
- * Check if connected to a specific peer.
368
- */
369
590
  isConnected(peerId) {
370
591
  const pc = this.peerConnections.get(peerId);
371
592
  return pc?.connectionState === "connected";
372
593
  }
373
- /**
374
- * Get the actual RTCPeerConnectionState for a peer.
375
- */
376
594
  getConnectionState(peerId) {
377
595
  const pc = this.peerConnections.get(peerId);
378
596
  return pc?.connectionState ?? "closed";
379
597
  }
380
- /**
381
- * Check if the main DataChannel is ready for a specific peer.
382
- */
598
+ getIceConnectionState(peerId) {
599
+ const pc = this.peerConnections.get(peerId);
600
+ return pc?.iceConnectionState ?? "closed";
601
+ }
602
+ getSignalingState(peerId) {
603
+ const pc = this.peerConnections.get(peerId);
604
+ return pc?.signalingState ?? "closed";
605
+ }
606
+ getDataChannelState(peerId) {
607
+ return (normalizePeerChannels(this.dataChannels.get(peerId)).message
608
+ ?.readyState ?? "closed");
609
+ }
610
+ getFileChannelState(peerId) {
611
+ return (normalizePeerChannels(this.dataChannels.get(peerId)).file
612
+ ?.readyState ?? "closed");
613
+ }
383
614
  isDataChannelReady(peerId) {
384
615
  return (normalizePeerChannels(this.dataChannels.get(peerId)).message
385
616
  ?.readyState === "open");
386
617
  }
387
- /**
388
- * Check if the file channel is ready for a specific peer.
389
- */
390
618
  isFileChannelReady(peerId) {
391
619
  return (normalizePeerChannels(this.dataChannels.get(peerId)).file
392
620
  ?.readyState === "open");
393
621
  }
622
+ getOrCreateNegotiationState(peerId) {
623
+ let state = this.negotiationStates.get(peerId);
624
+ if (!state) {
625
+ state = {
626
+ polite: false,
627
+ makingOffer: false,
628
+ ignoreOffer: false,
629
+ isSettingRemoteAnswerPending: false,
630
+ iceRestartAttempted: false,
631
+ };
632
+ this.negotiationStates.set(peerId, state);
633
+ }
634
+ return state;
635
+ }
636
+ enqueueIceCandidate(peerId, candidate) {
637
+ let queue = this.pendingIceCandidates.get(peerId);
638
+ if (!queue) {
639
+ queue = [];
640
+ this.pendingIceCandidates.set(peerId, queue);
641
+ }
642
+ if (queue.length >= MAX_PENDING_ICE_CANDIDATES) {
643
+ queue.shift();
644
+ }
645
+ queue.push(candidate);
646
+ }
647
+ async flushPendingIceCandidates(peerId) {
648
+ const pc = this.peerConnections.get(peerId);
649
+ const queue = this.pendingIceCandidates.get(peerId);
650
+ if (!pc || !pc.remoteDescription || !queue || queue.length === 0) {
651
+ return;
652
+ }
653
+ this.pendingIceCandidates.delete(peerId);
654
+ for (const candidate of queue) {
655
+ try {
656
+ await pc.addIceCandidate(new RTCIceCandidate(candidate));
657
+ }
658
+ catch (error) {
659
+ this.emitError(new AvesError({
660
+ message: `Failed to flush buffered ICE candidate for ${peerId}: ${errorMessage(error)}`,
661
+ code: "WEBRTC_ICE_FAILED",
662
+ stage: "transport",
663
+ retryable: true,
664
+ peerId,
665
+ cause: error,
666
+ }));
667
+ }
668
+ }
669
+ }
670
+ clearDisconnectGraceTimer(peerId) {
671
+ const timer = this.disconnectGraceTimers.get(peerId);
672
+ if (timer !== undefined) {
673
+ clearTimeout(timer);
674
+ this.disconnectGraceTimers.delete(peerId);
675
+ }
676
+ const politeTimer = this.politeIceRestartTimers.get(peerId);
677
+ if (politeTimer !== undefined) {
678
+ clearTimeout(politeTimer);
679
+ this.politeIceRestartTimers.delete(peerId);
680
+ }
681
+ }
394
682
  setupPeerConnection(peerId, pc) {
395
683
  pc.onconnectionstatechange = () => {
684
+ const state = pc.connectionState;
396
685
  const callbacks = this.connectionStateCallbacks.get(peerId);
397
- callbacks?.forEach((callback) => callback(pc.connectionState));
398
- if (pc.connectionState === "failed" ||
399
- pc.connectionState === "closed" ||
400
- pc.connectionState === "disconnected") {
686
+ callbacks?.forEach((callback) => callback(state));
687
+ if (state === "connected") {
688
+ this.clearDisconnectGraceTimer(peerId);
689
+ const negotiation = this.negotiationStates.get(peerId);
690
+ if (negotiation) {
691
+ negotiation.iceRestartAttempted = false;
692
+ }
693
+ return;
694
+ }
695
+ if (state === "failed" || state === "closed") {
401
696
  this.closePeerConnection(peerId);
697
+ return;
698
+ }
699
+ if (state === "disconnected") {
700
+ if (this.iceDisconnectGraceMs <= 0) {
701
+ this.closePeerConnection(peerId);
702
+ return;
703
+ }
704
+ if (this.disconnectGraceTimers.has(peerId)) {
705
+ return;
706
+ }
707
+ const negotiation = this.negotiationStates.get(peerId);
708
+ const triggerRestart = () => {
709
+ if (!negotiation ||
710
+ negotiation.iceRestartAttempted ||
711
+ this.negotiationOfferCallbacks.size === 0) {
712
+ return;
713
+ }
714
+ negotiation.iceRestartAttempted = true;
715
+ void this.restartIce(peerId).catch((error) => {
716
+ this.emitError(new AvesError({
717
+ message: `ICE restart failed for ${peerId}: ${errorMessage(error)}`,
718
+ code: "WEBRTC_ICE_FAILED",
719
+ stage: "transport",
720
+ retryable: true,
721
+ peerId,
722
+ cause: error,
723
+ }));
724
+ });
725
+ };
726
+ if (negotiation && !negotiation.polite) {
727
+ triggerRestart();
728
+ }
729
+ else if (negotiation && negotiation.polite && this.iceDisconnectGraceMs >= 400) {
730
+ // Allow polite peers to also recover from local network handovers
731
+ // if the impolite peer hasn't restarted halfway through the grace window.
732
+ const politeDelay = Math.min(1500, Math.floor(this.iceDisconnectGraceMs / 2));
733
+ const politeTimer = setTimeout(() => {
734
+ this.politeIceRestartTimers.delete(peerId);
735
+ const currentPc = this.peerConnections.get(peerId);
736
+ if (currentPc && currentPc.connectionState === "disconnected") {
737
+ triggerRestart();
738
+ }
739
+ }, politeDelay);
740
+ unrefTimer(politeTimer);
741
+ this.politeIceRestartTimers.set(peerId, politeTimer);
742
+ }
743
+ const timer = setTimeout(() => {
744
+ this.disconnectGraceTimers.delete(peerId);
745
+ const currentPc = this.peerConnections.get(peerId);
746
+ if (currentPc && currentPc.connectionState === "disconnected") {
747
+ this.closePeerConnection(peerId);
748
+ }
749
+ }, this.iceDisconnectGraceMs);
750
+ unrefTimer(timer);
751
+ this.disconnectGraceTimers.set(peerId, timer);
402
752
  }
403
753
  };
404
754
  pc.onicecandidate = (event) => {
@@ -408,6 +758,47 @@ export class WebRTCManager {
408
758
  const callbacks = this.iceCandidateCallbacks.get(peerId);
409
759
  callbacks?.forEach((cb) => cb(event.candidate.toJSON()));
410
760
  };
761
+ pc.onnegotiationneeded = () => {
762
+ if (this.negotiationOfferCallbacks.size === 0) {
763
+ return;
764
+ }
765
+ const negotiation = this.getOrCreateNegotiationState(peerId);
766
+ if (negotiation.makingOffer) {
767
+ return;
768
+ }
769
+ // Only renegotiate automatically when signaling is stable and initial
770
+ // negotiation has already completed.
771
+ if (!pc.localDescription ||
772
+ !pc.remoteDescription ||
773
+ (pc.signalingState && pc.signalingState !== "stable")) {
774
+ return;
775
+ }
776
+ void (async () => {
777
+ try {
778
+ negotiation.makingOffer = true;
779
+ const offer = await pc.createOffer();
780
+ await pc.setLocalDescription(offer);
781
+ const localOffer = pc.localDescription ?? offer;
782
+ this.negotiationOfferCallbacks.forEach((cb) => cb(peerId, localOffer));
783
+ }
784
+ catch (error) {
785
+ this.emitError(new AvesError({
786
+ message: `Renegotiation failed with ${peerId}: ${errorMessage(error)}`,
787
+ code: "WEBRTC_NEGOTIATION_FAILED",
788
+ stage: "signaling",
789
+ retryable: true,
790
+ peerId,
791
+ cause: error,
792
+ }));
793
+ }
794
+ finally {
795
+ negotiation.makingOffer = false;
796
+ }
797
+ })();
798
+ };
799
+ pc.ondatachannel = (event) => {
800
+ this.setupDataChannel(peerId, event.channel);
801
+ };
411
802
  this.mediaTracks.bindPeerConnection(peerId, pc);
412
803
  }
413
804
  ensureDataChannel(peerId, pc, label) {
@@ -422,18 +813,43 @@ export class WebRTCManager {
422
813
  return channel;
423
814
  }
424
815
  setupDataChannel(peerId, dataChannel) {
425
- const kind = getChannelKind(dataChannel.label);
816
+ const kind = resolveKnownChannelKind(dataChannel.label);
817
+ if (!kind) {
818
+ // Ignore & close unrecognized DataChannel labels so a rogue peer cannot
819
+ // hijack or overwrite the primary message channel.
820
+ try {
821
+ dataChannel.close();
822
+ }
823
+ catch {
824
+ // Ignore close errors
825
+ }
826
+ return;
827
+ }
426
828
  const channels = normalizePeerChannels(this.dataChannels.get(peerId));
829
+ const existing = channels[kind];
830
+ if (existing &&
831
+ existing !== dataChannel &&
832
+ existing.readyState === "open") {
833
+ try {
834
+ dataChannel.close();
835
+ }
836
+ catch {
837
+ // Ignore close errors
838
+ }
839
+ return;
840
+ }
427
841
  channels[kind] = dataChannel;
428
842
  this.dataChannels.set(peerId, channels);
429
843
  if (kind === "file") {
430
844
  dataChannel.binaryType = "arraybuffer";
431
845
  }
432
846
  dataChannel.onopen = () => {
433
- if (kind !== "message") {
847
+ if (kind === "message") {
848
+ const callbacks = this.dataChannelStateCallbacks.get(peerId);
849
+ callbacks?.forEach((callback) => callback(dataChannel.readyState));
434
850
  return;
435
851
  }
436
- const callbacks = this.dataChannelStateCallbacks.get(peerId);
852
+ const callbacks = this.fileChannelStateCallbacks.get(peerId);
437
853
  callbacks?.forEach((callback) => callback(dataChannel.readyState));
438
854
  };
439
855
  dataChannel.onclose = () => {
@@ -441,27 +857,55 @@ export class WebRTCManager {
441
857
  const callbacks = this.dataChannelStateCallbacks.get(peerId);
442
858
  callbacks?.forEach((callback) => callback(dataChannel.readyState));
443
859
  }
860
+ else {
861
+ const callbacks = this.fileChannelStateCallbacks.get(peerId);
862
+ callbacks?.forEach((callback) => callback(dataChannel.readyState));
863
+ }
444
864
  const storedChannels = this.dataChannels.get(peerId);
445
- if (storedChannels && isPeerChannels(storedChannels) && storedChannels[kind] === dataChannel) {
865
+ if (storedChannels &&
866
+ isPeerChannels(storedChannels) &&
867
+ storedChannels[kind] === dataChannel) {
446
868
  delete storedChannels[kind];
447
869
  if (!storedChannels.message && !storedChannels.file) {
448
870
  this.dataChannels.delete(peerId);
449
871
  }
450
872
  }
451
873
  if (kind === "message" || kind === "file") {
452
- this.failActiveTransfers(peerId, new AvesError({ message: `${kind} channel closed during file transfer`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: true, peerId }));
874
+ this.failActiveTransfers(peerId, new AvesError({
875
+ message: `${kind} channel closed during file transfer`,
876
+ code: "WEBRTC_DATACHANNEL_FAILED",
877
+ stage: "transport",
878
+ retryable: true,
879
+ peerId,
880
+ }));
453
881
  }
454
882
  };
455
883
  dataChannel.onerror = (error) => {
456
884
  if (!this.isCurrentDataChannel(peerId, kind, dataChannel)) {
457
885
  return;
458
886
  }
459
- this.emitError(new AvesError({ message: `DataChannel error with ${peerId}: ${errorMessage(error)}`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: true, peerId }));
887
+ this.emitError(new AvesError({
888
+ message: `DataChannel error with ${peerId}: ${errorMessage(error)}`,
889
+ code: "WEBRTC_DATACHANNEL_FAILED",
890
+ stage: "transport",
891
+ retryable: true,
892
+ peerId,
893
+ cause: error,
894
+ }));
460
895
  const transfer = kind === "file"
461
- ? this.outgoingTransfers.get(peerId) ?? this.incomingTransfers.get(peerId) ?? null
896
+ ? this.outgoingTransfers.get(peerId) ??
897
+ this.incomingTransfers.get(peerId) ??
898
+ null
462
899
  : null;
463
900
  if (transfer) {
464
- this.emitFileTransferFailed(peerId, transfer, new AvesError({ message: `DataChannel error on ${kind} channel`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: true, peerId }));
901
+ this.emitFileTransferFailed(peerId, transfer, new AvesError({
902
+ message: `DataChannel error on ${kind} channel`,
903
+ code: "WEBRTC_DATACHANNEL_FAILED",
904
+ stage: "transport",
905
+ retryable: true,
906
+ peerId,
907
+ cause: error,
908
+ }));
465
909
  }
466
910
  };
467
911
  dataChannel.onmessage = (event) => {
@@ -489,7 +933,14 @@ export class WebRTCManager {
489
933
  this.messageCallbacks.forEach((callback) => callback(peerId, message));
490
934
  }
491
935
  catch (error) {
492
- this.emitError(new AvesError({ message: `Failed to parse message from ${peerId}: ${errorMessage(error)}`, code: "MESSAGE_PARSE_FAILED", stage: "transport", retryable: false, peerId }));
936
+ this.emitError(new AvesError({
937
+ message: `Failed to parse message from ${peerId}: ${errorMessage(error)}`,
938
+ code: "MESSAGE_PARSE_FAILED",
939
+ stage: "transport",
940
+ retryable: false,
941
+ peerId,
942
+ cause: error,
943
+ }));
493
944
  }
494
945
  }
495
946
  handleFileControlMessage(peerId, message) {
@@ -510,21 +961,39 @@ export class WebRTCManager {
510
961
  getPeerConnection(peerId) {
511
962
  const pc = this.peerConnections.get(peerId);
512
963
  if (!pc) {
513
- throw new AvesError({ message: `No peer connection found for ${peerId}`, code: "WEBRTC_CONNECTION_FAILED", stage: "transport", retryable: false, peerId });
964
+ throw new AvesError({
965
+ message: `No peer connection found for ${peerId}`,
966
+ code: "WEBRTC_CONNECTION_FAILED",
967
+ stage: "transport",
968
+ retryable: false,
969
+ peerId,
970
+ });
514
971
  }
515
972
  return pc;
516
973
  }
517
974
  getMessageChannel(peerId) {
518
975
  const channel = normalizePeerChannels(this.dataChannels.get(peerId)).message;
519
976
  if (!channel) {
520
- throw new AvesError({ message: `No DataChannel found for ${peerId}`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: false, peerId });
977
+ throw new AvesError({
978
+ message: `No DataChannel found for ${peerId}`,
979
+ code: "WEBRTC_DATACHANNEL_FAILED",
980
+ stage: "transport",
981
+ retryable: false,
982
+ peerId,
983
+ });
521
984
  }
522
985
  return channel;
523
986
  }
524
987
  getFileChannel(peerId) {
525
988
  const channel = normalizePeerChannels(this.dataChannels.get(peerId)).file;
526
989
  if (!channel) {
527
- throw new AvesError({ message: `No file channel found for ${peerId}`, code: "FILE_CHANNEL_NOT_READY", stage: "transport", retryable: false, peerId });
990
+ throw new AvesError({
991
+ message: `No file channel found for ${peerId}`,
992
+ code: "FILE_CHANNEL_NOT_READY",
993
+ stage: "transport",
994
+ retryable: false,
995
+ peerId,
996
+ });
528
997
  }
529
998
  return channel;
530
999
  }
@@ -532,3 +1001,12 @@ export class WebRTCManager {
532
1001
  this.fileTransfers.failActiveTransfers(peerId, error);
533
1002
  }
534
1003
  }
1004
+ function normalizeCandidatePairType(type) {
1005
+ if (type === "host" ||
1006
+ type === "srflx" ||
1007
+ type === "prflx" ||
1008
+ type === "relay") {
1009
+ return type;
1010
+ }
1011
+ return "unknown";
1012
+ }