@yrzhao/aves-core 1.1.0 → 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 +55 -40
  2. package/dist/core/AvesClient.d.ts +32 -8
  3. package/dist/core/AvesClient.js +254 -55
  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 +67 -102
  10. package/dist/core/WebRTCManager.js +607 -136
  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 +32 -8
  18. package/dist/esm/core/AvesClient.js +254 -55
  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 +67 -102
  25. package/dist/esm/core/WebRTCManager.js +608 -137
  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 +106 -9
  34. package/dist/index.d.ts +2 -1
  35. package/dist/types/types.d.ts +106 -9
  36. package/package.json +8 -6
@@ -9,7 +9,7 @@ function errorMessage(error) {
9
9
  return error instanceof Error ? error.message : String(error);
10
10
  }
11
11
  /**
12
- * AvesClient - Main client class for WebRTC communication.
12
+ * AvesClient - Main browser WebRTC client for P2P rooms.
13
13
  */
14
14
  class AvesClient extends EventEmitter_1.EventEmitter {
15
15
  constructor(config) {
@@ -17,11 +17,16 @@ class AvesClient extends EventEmitter_1.EventEmitter {
17
17
  this.currentRoomId = null;
18
18
  this.currentUserId = null;
19
19
  this.currentUserName = null;
20
+ this.currentRoomPassword = undefined;
21
+ this.currentReconnectToken = undefined;
20
22
  this.participants = new Map();
21
- this.preparedPeers = new Set();
23
+ this.preparedPeerConnections = new WeakSet();
22
24
  this.shouldRestoreSession = false;
23
25
  const maxAttempts = config.reconnect?.maxAttempts ?? 5;
24
26
  const delay = config.reconnect?.delay ?? 3000;
27
+ const maxDelay = config.reconnect?.maxDelay ?? 30000;
28
+ const backoffFactor = config.reconnect?.backoffFactor ?? 2;
29
+ const jitter = config.reconnect?.jitter ?? true;
25
30
  const requestTimeoutMs = config.reconnect?.requestTimeoutMs ?? 30000;
26
31
  this.config = {
27
32
  signalingUrl: config.signalingUrl,
@@ -32,18 +37,42 @@ class AvesClient extends EventEmitter_1.EventEmitter {
32
37
  reconnect: {
33
38
  maxAttempts,
34
39
  delay,
40
+ maxDelay,
41
+ backoffFactor,
42
+ jitter,
35
43
  requestTimeoutMs,
36
44
  },
37
45
  debug: config.debug ?? false,
38
46
  };
39
- this.webrtcManager = new WebRTCManager_1.WebRTCManager(this.config.iceServers, this.config.fileChunkSize, config.video);
47
+ this.webrtcManager = new WebRTCManager_1.WebRTCManager({
48
+ iceServers: this.config.iceServers,
49
+ rtcConfiguration: config.rtcConfiguration,
50
+ fileChunkSize: this.config.fileChunkSize,
51
+ fileTransfer: config.fileTransfer,
52
+ videoConstraints: config.video,
53
+ audioConstraints: config.audio,
54
+ iceDisconnectGraceMs: config.iceDisconnectGraceMs,
55
+ });
40
56
  this.signalingClient = new SignalingClient_1.SignalingClient({
41
57
  maxAttempts,
42
58
  delay,
59
+ maxDelay,
60
+ backoffFactor,
61
+ jitter,
43
62
  requestTimeoutMs,
63
+ authToken: config.authToken,
64
+ heartbeatIntervalMs: config.heartbeatIntervalMs,
65
+ heartbeatTimeoutMs: config.heartbeatTimeoutMs,
44
66
  });
45
67
  this.setupEventHandlers();
46
68
  }
69
+ isPoliteForPeer(peerId) {
70
+ if (!this.currentUserId) {
71
+ return true;
72
+ }
73
+ // Initiator (lower lexicographical ID) is impolite; receiver is polite.
74
+ return this.currentUserId > peerId;
75
+ }
47
76
  setupEventHandlers() {
48
77
  this.signalingClient.on("stateChange", (state) => {
49
78
  this.emit("signalingStateChange", state);
@@ -70,20 +99,26 @@ class AvesClient extends EventEmitter_1.EventEmitter {
70
99
  });
71
100
  this.signalingClient.on("userLeft", (userId) => {
72
101
  this.participants.delete(userId);
73
- this.preparedPeers.delete(userId);
74
102
  this.webrtcManager.closePeerConnection(userId);
75
103
  this.emit("userLeft", userId);
76
104
  });
77
105
  this.signalingClient.on("offer", async (fromId, offer) => {
78
106
  try {
79
107
  this.preparePeerConnection(fromId);
80
- const answer = await this.webrtcManager.createAnswer(fromId, offer);
81
- if (this.currentUserId) {
108
+ const answer = await this.webrtcManager.handleRemoteOffer(fromId, offer);
109
+ if (answer && this.currentUserId) {
82
110
  this.signalingClient.sendAnswer(fromId, this.currentUserId, answer);
83
111
  }
84
112
  }
85
113
  catch (error) {
86
- this.emit("error", new AvesError_1.AvesError({ message: `Failed to handle offer from ${fromId}: ${errorMessage(error)}`, code: "SERVER_ERROR", stage: "signaling", retryable: true, peerId: fromId }));
114
+ this.emit("error", new AvesError_1.AvesError({
115
+ message: `Failed to handle offer from ${fromId}: ${errorMessage(error)}`,
116
+ code: "WEBRTC_NEGOTIATION_FAILED",
117
+ stage: "signaling",
118
+ retryable: true,
119
+ peerId: fromId,
120
+ cause: error,
121
+ }));
87
122
  }
88
123
  });
89
124
  this.signalingClient.on("answer", async (fromId, answer) => {
@@ -91,7 +126,14 @@ class AvesClient extends EventEmitter_1.EventEmitter {
91
126
  await this.webrtcManager.setRemoteAnswer(fromId, answer);
92
127
  }
93
128
  catch (error) {
94
- this.emit("error", new AvesError_1.AvesError({ message: `Failed to handle answer from ${fromId}: ${errorMessage(error)}`, code: "SERVER_ERROR", stage: "signaling", retryable: true, peerId: fromId }));
129
+ this.emit("error", new AvesError_1.AvesError({
130
+ message: `Failed to handle answer from ${fromId}: ${errorMessage(error)}`,
131
+ code: "WEBRTC_NEGOTIATION_FAILED",
132
+ stage: "signaling",
133
+ retryable: true,
134
+ peerId: fromId,
135
+ cause: error,
136
+ }));
95
137
  }
96
138
  });
97
139
  this.signalingClient.on("iceCandidate", async (fromId, candidate) => {
@@ -99,7 +141,19 @@ class AvesClient extends EventEmitter_1.EventEmitter {
99
141
  await this.webrtcManager.addIceCandidate(fromId, candidate);
100
142
  }
101
143
  catch (error) {
102
- this.emit("error", new AvesError_1.AvesError({ message: `Failed to add ICE candidate from ${fromId}: ${errorMessage(error)}`, code: "WEBRTC_ICE_FAILED", stage: "transport", retryable: true, peerId: fromId }));
144
+ this.emit("error", new AvesError_1.AvesError({
145
+ message: `Failed to add ICE candidate from ${fromId}: ${errorMessage(error)}`,
146
+ code: "WEBRTC_ICE_FAILED",
147
+ stage: "transport",
148
+ retryable: true,
149
+ peerId: fromId,
150
+ cause: error,
151
+ }));
152
+ }
153
+ });
154
+ this.webrtcManager.onNegotiationOffer((peerId, offer) => {
155
+ if (this.currentUserId) {
156
+ this.signalingClient.sendOffer(peerId, this.currentUserId, offer);
103
157
  }
104
158
  });
105
159
  this.webrtcManager.onMessage((peerId, message) => {
@@ -132,61 +186,112 @@ class AvesClient extends EventEmitter_1.EventEmitter {
132
186
  this.webrtcManager.onScreenShareStateChange((state) => {
133
187
  this.emit("screenShareStateChange", state);
134
188
  });
189
+ this.webrtcManager.onRemoteTrackEnded((peerId, kind, track) => {
190
+ this.emit("remoteTrackEnded", peerId, kind, track);
191
+ });
192
+ this.webrtcManager.onRemoteTrackMuted((peerId, kind, muted, track) => {
193
+ this.emit("remoteTrackMuted", peerId, kind, muted, track);
194
+ });
135
195
  this.webrtcManager.onError((err) => {
136
196
  this.emit("error", err);
137
197
  });
138
198
  }
139
199
  async restoreRoomSession() {
140
- if (!this.currentRoomId || !this.currentUserId || !this.currentUserName) {
200
+ const roomId = this.currentRoomId;
201
+ const userId = this.currentUserId;
202
+ const userName = this.currentUserName;
203
+ const password = this.currentRoomPassword;
204
+ const reconnectToken = this.currentReconnectToken;
205
+ if (!roomId || !userId || !userName) {
141
206
  return;
142
207
  }
143
208
  try {
144
- this.webrtcManager.closeAllPeerConnections();
145
- this.participants.clear();
146
- this.preparedPeers.clear();
147
- const joinResult = await this.signalingClient.joinRoom(this.currentRoomId, this.currentUserId, this.currentUserName);
209
+ // Preserve healthy P2P connections across transient signaling blips instead
210
+ // of tearing them all down (which causes deadlocks with server grace restore
211
+ // and O(N^2) offer/ICE storms).
212
+ const joinResult = reconnectToken !== undefined
213
+ ? await this.signalingClient.joinRoom(roomId, userName, {
214
+ userId,
215
+ ...(password !== undefined ? { password } : {}),
216
+ reconnectToken,
217
+ })
218
+ : password !== undefined
219
+ ? await this.signalingClient.joinRoom(roomId, userId, userName, password)
220
+ : await this.signalingClient.joinRoom(roomId, userId, userName);
148
221
  this.currentUserId = joinResult.userId;
222
+ if (joinResult.reconnectToken !== undefined) {
223
+ this.currentReconnectToken = joinResult.reconnectToken;
224
+ }
149
225
  const participants = joinResult.participants;
226
+ const nextParticipantIds = new Set(participants.map((p) => p.id));
227
+ // Close peers that left the room while signaling was disconnected.
228
+ for (const activePeerId of this.webrtcManager.getActivePeers()) {
229
+ if (!nextParticipantIds.has(activePeerId)) {
230
+ this.webrtcManager.closePeerConnection(activePeerId);
231
+ }
232
+ }
150
233
  this.participants.clear();
151
234
  participants.forEach((participant) => this.participants.set(participant.id, participant));
235
+ this.emit("sessionRestored", participants);
236
+ // Re-initiate only for peers whose PeerConnection is missing, failed, or closed.
152
237
  for (const participant of participants) {
153
- if (participant.id !== this.currentUserId &&
154
- this.currentUserId < participant.id) {
155
- await this.initiateConnection(participant.id);
238
+ if (participant.id === this.currentUserId ||
239
+ !(this.currentUserId < participant.id)) {
240
+ continue;
241
+ }
242
+ const existingState = this.webrtcManager.getConnectionState(participant.id);
243
+ if (existingState === "connected" ||
244
+ existingState === "connecting" ||
245
+ existingState === "new") {
246
+ continue;
156
247
  }
248
+ if (existingState === "disconnected" || existingState === "failed") {
249
+ this.webrtcManager.closePeerConnection(participant.id);
250
+ }
251
+ await this.initiateConnection(participant.id);
157
252
  }
158
253
  }
159
254
  catch (error) {
255
+ this.webrtcManager.closeAllPeerConnections();
160
256
  this.currentRoomId = null;
161
257
  this.currentUserId = null;
162
258
  this.currentUserName = null;
259
+ this.currentRoomPassword = undefined;
260
+ this.currentReconnectToken = undefined;
163
261
  this.participants.clear();
164
- this.preparedPeers.clear();
165
- this.emit("error", new AvesError_1.AvesError({ message: `Failed to restore room session: ${errorMessage(error)}`, code: "SERVER_ERROR", stage: "room", retryable: true, roomId: this.currentRoomId ?? undefined }));
262
+ this.emit("error", new AvesError_1.AvesError({
263
+ message: `Failed to restore room session: ${errorMessage(error)}`,
264
+ code: error instanceof AvesError_1.AvesError ? error.code : "ROOM_JOIN_FAILED",
265
+ stage: "room",
266
+ retryable: true,
267
+ roomId,
268
+ cause: error,
269
+ }));
166
270
  }
167
271
  }
168
272
  preparePeerConnection(peerId) {
169
- const pc = this.webrtcManager.createPeerConnection(peerId);
170
- if (this.preparedPeers.has(peerId)) {
273
+ const polite = this.isPoliteForPeer(peerId);
274
+ const pc = this.webrtcManager.createPeerConnection(peerId, { polite });
275
+ // Key by RTCPeerConnection instance so a recreated PC after close/expiry
276
+ // always receives fresh ICE and state callbacks.
277
+ if (this.preparedPeerConnections.has(pc)) {
171
278
  return pc;
172
279
  }
173
- this.preparedPeers.add(peerId);
280
+ this.preparedPeerConnections.add(pc);
174
281
  this.webrtcManager.onIceCandidate(peerId, (candidate) => {
175
282
  if (this.currentUserId) {
176
283
  this.signalingClient.sendIceCandidate(peerId, this.currentUserId, candidate);
177
284
  }
178
285
  });
179
286
  this.webrtcManager.onConnectionStateChange(peerId, (state) => {
180
- if (state === "failed" ||
181
- state === "disconnected" ||
182
- state === "closed") {
183
- this.preparedPeers.delete(peerId);
184
- }
185
287
  this.emit("connectionStateChange", peerId, state);
186
288
  });
187
289
  this.webrtcManager.onDataChannelStateChange(peerId, (state) => {
188
290
  this.emit("dataChannelStateChange", peerId, state);
189
291
  });
292
+ this.webrtcManager.onFileChannelStateChange(peerId, (state) => {
293
+ this.emit("fileChannelStateChange", peerId, state);
294
+ });
190
295
  return pc;
191
296
  }
192
297
  async initiateConnection(peerId) {
@@ -198,31 +303,76 @@ class AvesClient extends EventEmitter_1.EventEmitter {
198
303
  }
199
304
  }
200
305
  catch (error) {
201
- this.emit("error", new AvesError_1.AvesError({ message: `Failed to initiate connection with ${peerId}: ${errorMessage(error)}`, code: "WEBRTC_CONNECTION_FAILED", stage: "transport", retryable: true, peerId }));
306
+ this.emit("error", new AvesError_1.AvesError({
307
+ message: `Failed to initiate connection with ${peerId}: ${errorMessage(error)}`,
308
+ code: "WEBRTC_CONNECTION_FAILED",
309
+ stage: "transport",
310
+ retryable: true,
311
+ peerId,
312
+ cause: error,
313
+ }));
202
314
  }
203
315
  }
204
- async createRoom() {
316
+ /**
317
+ * Update authentication token for subsequent signaling connections.
318
+ */
319
+ setAuthToken(token) {
320
+ this.signalingClient.setAuthToken(token);
321
+ }
322
+ /**
323
+ * Update ICE/TURN servers dynamically (e.g. rotating time-limited TURN credentials).
324
+ */
325
+ updateIceServers(iceServers) {
326
+ this.config.iceServers = [...iceServers];
327
+ this.webrtcManager.updateIceServers(iceServers);
328
+ }
329
+ /**
330
+ * Create a new room with optional name, capacity, and password.
331
+ */
332
+ async createRoom(options) {
205
333
  if (!this.signalingClient.isConnected()) {
206
334
  await this.signalingClient.connect(this.config.signalingUrl);
207
335
  }
208
- const roomId = await this.signalingClient.createRoom();
336
+ const roomId = await this.signalingClient.createRoom(options);
209
337
  this.currentRoomId = roomId;
210
338
  return roomId;
211
339
  }
212
- async joinRoom(roomId, userIdOrName, maybeUserName) {
340
+ async joinRoom(roomId, userIdOrName, maybeUserNameOrOptions, maybePassword) {
213
341
  if (!this.signalingClient.isConnected()) {
214
342
  await this.signalingClient.connect(this.config.signalingUrl);
215
343
  }
216
- const requestedUserId = maybeUserName ? userIdOrName : null;
217
- const userName = maybeUserName ?? userIdOrName;
218
- this.currentUserId = requestedUserId;
219
- this.currentRoomId = roomId;
220
- this.currentUserName = userName;
344
+ let requestedUserId = null;
345
+ let userName;
346
+ let password;
347
+ if (typeof maybeUserNameOrOptions === "string") {
348
+ requestedUserId = userIdOrName;
349
+ userName = maybeUserNameOrOptions;
350
+ password = maybePassword;
351
+ }
352
+ else if (maybeUserNameOrOptions &&
353
+ typeof maybeUserNameOrOptions === "object") {
354
+ userName = userIdOrName;
355
+ requestedUserId = maybeUserNameOrOptions.userId ?? null;
356
+ password = maybeUserNameOrOptions.password;
357
+ }
358
+ else {
359
+ userName = userIdOrName;
360
+ }
361
+ // Commit session state only AFTER signaling join succeeds so failed joins
362
+ // (wrong password, room full) never pollute credentials or trigger stale restores.
221
363
  const joinResult = requestedUserId
222
- ? await this.signalingClient.joinRoom(roomId, requestedUserId, userName)
223
- : await this.signalingClient.joinRoom(roomId, userName);
364
+ ? password !== undefined
365
+ ? await this.signalingClient.joinRoom(roomId, requestedUserId, userName, password)
366
+ : await this.signalingClient.joinRoom(roomId, requestedUserId, userName)
367
+ : password !== undefined
368
+ ? await this.signalingClient.joinRoom(roomId, userName, { password })
369
+ : await this.signalingClient.joinRoom(roomId, userName);
224
370
  const participants = joinResult.participants;
371
+ this.currentRoomId = roomId;
225
372
  this.currentUserId = joinResult.userId;
373
+ this.currentUserName = userName;
374
+ this.currentRoomPassword = password;
375
+ this.currentReconnectToken = joinResult.reconnectToken;
226
376
  this.participants.clear();
227
377
  participants.forEach((participant) => this.participants.set(participant.id, participant));
228
378
  for (const participant of participants) {
@@ -235,16 +385,22 @@ class AvesClient extends EventEmitter_1.EventEmitter {
235
385
  return participants;
236
386
  }
237
387
  async leaveRoom() {
238
- if (this.currentUserId) {
239
- await this.signalingClient.leaveRoom(this.currentUserId);
388
+ const userId = this.currentUserId;
389
+ try {
390
+ if (userId && this.signalingClient.isConnected()) {
391
+ await this.signalingClient.leaveRoom(userId);
392
+ }
393
+ }
394
+ finally {
395
+ this.webrtcManager.closeAll();
396
+ this.participants.clear();
397
+ this.currentRoomId = null;
398
+ this.currentUserId = null;
399
+ this.currentUserName = null;
400
+ this.currentRoomPassword = undefined;
401
+ this.currentReconnectToken = undefined;
402
+ this.shouldRestoreSession = false;
240
403
  }
241
- this.webrtcManager.closeAll();
242
- this.participants.clear();
243
- this.preparedPeers.clear();
244
- this.currentRoomId = null;
245
- this.currentUserId = null;
246
- this.currentUserName = null;
247
- this.shouldRestoreSession = false;
248
404
  }
249
405
  sendMessage(message) {
250
406
  this.webrtcManager.sendMessage(message);
@@ -255,8 +411,14 @@ class AvesClient extends EventEmitter_1.EventEmitter {
255
411
  async sendFile(blob, options = {}) {
256
412
  return this.webrtcManager.sendFile(blob, options);
257
413
  }
258
- async startVoice() {
259
- return this.webrtcManager.startVoice();
414
+ cancelFileTransfer(peerId, transferId) {
415
+ return this.webrtcManager.cancelFileTransfer(peerId, transferId);
416
+ }
417
+ async startVoice(constraints) {
418
+ return this.webrtcManager.startVoice(constraints);
419
+ }
420
+ async switchAudioDevice(deviceId) {
421
+ return this.webrtcManager.switchAudioDevice(deviceId);
260
422
  }
261
423
  stopVoice() {
262
424
  this.webrtcManager.stopVoice();
@@ -274,6 +436,9 @@ class AvesClient extends EventEmitter_1.EventEmitter {
274
436
  async startVideo(constraints) {
275
437
  return this.webrtcManager.startVideo(constraints);
276
438
  }
439
+ async switchVideoDevice(deviceId) {
440
+ return this.webrtcManager.switchVideoDevice(deviceId);
441
+ }
277
442
  stopVideo() {
278
443
  this.webrtcManager.stopVideo();
279
444
  }
@@ -287,8 +452,8 @@ class AvesClient extends EventEmitter_1.EventEmitter {
287
452
  return this.webrtcManager.getRemoteVideoStream(peerId);
288
453
  }
289
454
  // --- Screen Share ---
290
- async startScreenShare() {
291
- return this.webrtcManager.startScreenShare();
455
+ async startScreenShare(options) {
456
+ return this.webrtcManager.startScreenShare(options);
292
457
  }
293
458
  stopScreenShare() {
294
459
  this.webrtcManager.stopScreenShare();
@@ -296,9 +461,19 @@ class AvesClient extends EventEmitter_1.EventEmitter {
296
461
  getScreenShareState() {
297
462
  return this.webrtcManager.getScreenShareState();
298
463
  }
464
+ // --- Diagnostics & Quality ---
299
465
  getConnectionState(peerId) {
300
466
  return this.webrtcManager.getConnectionState(peerId);
301
467
  }
468
+ async getPeerStats(peerId) {
469
+ return this.webrtcManager.getPeerStats(peerId);
470
+ }
471
+ async getAllPeerStats() {
472
+ return this.webrtcManager.getAllPeerStats();
473
+ }
474
+ async restartPeerIce(peerId) {
475
+ await this.webrtcManager.restartIce(peerId);
476
+ }
302
477
  getConnectionSnapshot() {
303
478
  const participants = this.getParticipants();
304
479
  const participantById = new Map(participants.map((participant) => [participant.id, participant]));
@@ -334,13 +509,28 @@ class AvesClient extends EventEmitter_1.EventEmitter {
334
509
  return new Promise((resolve, reject) => {
335
510
  let timeoutId = null;
336
511
  const cleanup = () => {
337
- this.off("dataChannelStateChange", handleDataChannelStateChange);
512
+ this.off("dataChannelStateChange", handleChannelStateChange);
513
+ this.off("fileChannelStateChange", handleChannelStateChange);
338
514
  this.off("connectionStateChange", handleConnectionStateChange);
515
+ this.off("userLeft", handleUserLeft);
339
516
  if (timeoutId) {
340
517
  clearTimeout(timeoutId);
341
518
  timeoutId = null;
342
519
  }
343
520
  };
521
+ const handleUserLeft = (leftUserId) => {
522
+ if (leftUserId !== peerId) {
523
+ return;
524
+ }
525
+ cleanup();
526
+ reject(new AvesError_1.AvesError({
527
+ message: `Peer ${peerId} left the room`,
528
+ code: "WEBRTC_CONNECTION_FAILED",
529
+ stage: "transport",
530
+ retryable: false,
531
+ peerId,
532
+ }));
533
+ };
344
534
  const resolveIfReady = () => {
345
535
  if (!isReady()) {
346
536
  return;
@@ -348,7 +538,7 @@ class AvesClient extends EventEmitter_1.EventEmitter {
348
538
  cleanup();
349
539
  resolve(getSnapshot());
350
540
  };
351
- const handleDataChannelStateChange = (changedPeerId) => {
541
+ const handleChannelStateChange = (changedPeerId) => {
352
542
  if (changedPeerId === peerId) {
353
543
  resolveIfReady();
354
544
  }
@@ -370,8 +560,10 @@ class AvesClient extends EventEmitter_1.EventEmitter {
370
560
  }
371
561
  resolveIfReady();
372
562
  };
373
- this.on("dataChannelStateChange", handleDataChannelStateChange);
563
+ this.on("dataChannelStateChange", handleChannelStateChange);
564
+ this.on("fileChannelStateChange", handleChannelStateChange);
374
565
  this.on("connectionStateChange", handleConnectionStateChange);
566
+ this.on("userLeft", handleUserLeft);
375
567
  timeoutId = setTimeout(() => {
376
568
  cleanup();
377
569
  reject(new AvesError_1.AvesError({
@@ -382,6 +574,7 @@ class AvesClient extends EventEmitter_1.EventEmitter {
382
574
  peerId,
383
575
  }));
384
576
  }, timeoutMs);
577
+ timeoutId.unref?.();
385
578
  resolveIfReady();
386
579
  });
387
580
  }
@@ -395,9 +588,14 @@ class AvesClient extends EventEmitter_1.EventEmitter {
395
588
  peerId,
396
589
  participant,
397
590
  connectionState: this.webrtcManager.getConnectionState(peerId),
591
+ iceConnectionState: this.webrtcManager.getIceConnectionState(peerId),
592
+ signalingState: this.webrtcManager.getSignalingState(peerId),
398
593
  dataChannelState: messageChannelReady
399
594
  ? "open"
400
595
  : this.webrtcManager.getDataChannelState(peerId),
596
+ fileChannelState: fileChannelReady
597
+ ? "open"
598
+ : this.webrtcManager.getFileChannelState(peerId),
401
599
  messageChannelReady,
402
600
  fileChannelReady,
403
601
  };
@@ -412,9 +610,10 @@ class AvesClient extends EventEmitter_1.EventEmitter {
412
610
  this.currentRoomId = null;
413
611
  this.currentUserId = null;
414
612
  this.currentUserName = null;
613
+ this.currentRoomPassword = undefined;
614
+ this.currentReconnectToken = undefined;
415
615
  this.shouldRestoreSession = false;
416
616
  this.participants.clear();
417
- this.preparedPeers.clear();
418
617
  this.signalingClient.disconnect();
419
618
  this.webrtcManager.destroy();
420
619
  this.removeAllListeners();
@@ -3,7 +3,7 @@ import type { SignalingErrorCode, SignalingErrorStage } from "../types/types";
3
3
  * All error codes used across the aves ecosystem.
4
4
  * Signaling codes come from the shared type; runtime codes extend it.
5
5
  */
6
- export type AvesErrorCode = SignalingErrorCode | "WEBRTC_CONNECTION_FAILED" | "WEBRTC_DATACHANNEL_FAILED" | "WEBRTC_ICE_FAILED" | "MEDIA_CAPTURE_FAILED" | "MEDIA_NOT_AVAILABLE" | "FILE_TRANSFER_FAILED" | "FILE_TRANSFER_TIMEOUT" | "FILE_TRANSFER_REJECTED" | "FILE_CHANNEL_NOT_READY" | "MESSAGE_CHANNEL_NOT_READY" | "MESSAGE_PARSE_FAILED" | "MESSAGE_SEND_FAILED" | "MESSAGE_SERIALIZE_FAILED" | "UNKNOWN_ERROR" | (string & {});
6
+ export type AvesErrorCode = SignalingErrorCode | "SIGNALING_CONNECTION_FAILED" | "SIGNALING_DISCONNECTED" | "WEBRTC_CONNECTION_FAILED" | "WEBRTC_NEGOTIATION_FAILED" | "WEBRTC_DATACHANNEL_FAILED" | "WEBRTC_ICE_FAILED" | "MEDIA_CAPTURE_FAILED" | "MEDIA_NOT_AVAILABLE" | "FILE_TRANSFER_FAILED" | "FILE_TRANSFER_TIMEOUT" | "FILE_TRANSFER_REJECTED" | "FILE_TRANSFER_CANCELLED" | "FILE_TRANSFER_INTEGRITY_FAILED" | "FILE_SIZE_EXCEEDED" | "FILE_CHANNEL_NOT_READY" | "MESSAGE_CHANNEL_NOT_READY" | "MESSAGE_PARSE_FAILED" | "MESSAGE_SEND_FAILED" | "MESSAGE_SERIALIZE_FAILED" | "UNKNOWN_ERROR" | (string & {});
7
7
  /**
8
8
  * Structured error class used throughout aves-core and aves-node.
9
9
  *
@@ -1,29 +1,18 @@
1
1
  /**
2
- * EventEmitter base class with optional type-safe event maps.
3
- *
4
- * When no type parameter is supplied the emitter is untyped (backward-compatible).
5
- * Supply an event map to get full type safety on `on`, `emit`, and `off`:
6
- *
7
- * ```ts
8
- * interface MyEvents {
9
- * data: [payload: string, count: number];
10
- * close: [];
11
- * }
12
- * const emitter = new EventEmitter<MyEvents>();
13
- * emitter.on("data", (payload, count) => { ... }); // payload: string, count: number
14
- * emitter.emit("data", "hello", 42); // type-safe args
15
- * ```
2
+ * EventEmitter base class with type-safe event maps, cancellable `once` listeners,
3
+ * and isolated listener error handling.
16
4
  */
17
5
  type EventArgs<TEvents, TEvent extends keyof TEvents> = TEvents[TEvent] extends unknown[] ? TEvents[TEvent] : never;
18
6
  export declare class EventEmitter<TEvents extends object = Record<string, unknown[]>> {
19
7
  private events;
8
+ private onceWrappers;
20
9
  constructor();
21
10
  /**
22
11
  * Register an event listener.
23
12
  */
24
13
  on<E extends keyof TEvents & string>(event: E, callback: (...args: EventArgs<TEvents, E>) => void): this;
25
14
  /**
26
- * Remove an event listener.
15
+ * Remove an event listener (works for both `on` and `once` registrations).
27
16
  */
28
17
  off<E extends keyof TEvents & string>(event: E, callback: (...args: EventArgs<TEvents, E>) => void): this;
29
18
  /**
@@ -32,11 +21,14 @@ export declare class EventEmitter<TEvents extends object = Record<string, unknow
32
21
  once<E extends keyof TEvents & string>(event: E, callback: (...args: EventArgs<TEvents, E>) => void): this;
33
22
  /**
34
23
  * Emit an event with typed arguments.
24
+ * Individual listener errors are isolated so one faulty handler cannot
25
+ * break subsequent listeners or internal state transitions.
35
26
  */
36
27
  emit<E extends keyof TEvents & string>(event: E, ...args: EventArgs<TEvents, E>): void;
37
28
  /**
38
29
  * Remove all listeners for a specific event or all events.
39
30
  */
40
- removeAllListeners(event?: string): void;
31
+ removeAllListeners<E extends keyof TEvents & string>(event?: E): void;
32
+ protected handleListenerError(_event: string, _error: unknown): void;
41
33
  }
42
34
  export {};