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