@yrzhao/aves-core 0.1.0 → 0.3.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 (46) hide show
  1. package/README.md +157 -343
  2. package/dist/core/AvesClient.d.ts +45 -64
  3. package/dist/core/AvesClient.js +190 -142
  4. package/dist/core/AvesError.d.ts +39 -0
  5. package/dist/core/AvesError.js +42 -0
  6. package/dist/core/EventEmitter.d.ts +26 -24
  7. package/dist/core/EventEmitter.js +12 -23
  8. package/dist/core/SignalingClient.d.ts +30 -7
  9. package/dist/core/SignalingClient.js +177 -41
  10. package/dist/core/WebRTCManager.d.ts +152 -39
  11. package/dist/core/WebRTCManager.js +409 -196
  12. package/dist/core/webrtc/channels.d.ts +10 -0
  13. package/dist/core/webrtc/channels.js +25 -0
  14. package/dist/core/webrtc/fileTransfer.d.ts +84 -0
  15. package/dist/core/webrtc/fileTransfer.js +399 -0
  16. package/dist/core/webrtc/mediaTracks.d.ts +53 -0
  17. package/dist/core/webrtc/mediaTracks.js +385 -0
  18. package/dist/core/webrtc/messages.d.ts +4 -0
  19. package/dist/core/webrtc/messages.js +53 -0
  20. package/dist/esm/core/AvesClient.d.ts +45 -64
  21. package/dist/esm/core/AvesClient.js +193 -145
  22. package/dist/esm/core/AvesError.d.ts +39 -0
  23. package/dist/esm/core/AvesError.js +38 -0
  24. package/dist/esm/core/EventEmitter.d.ts +26 -24
  25. package/dist/esm/core/EventEmitter.js +12 -23
  26. package/dist/esm/core/SignalingClient.d.ts +30 -7
  27. package/dist/esm/core/SignalingClient.js +178 -42
  28. package/dist/esm/core/WebRTCManager.d.ts +152 -39
  29. package/dist/esm/core/WebRTCManager.js +409 -196
  30. package/dist/esm/core/webrtc/channels.d.ts +10 -0
  31. package/dist/esm/core/webrtc/channels.js +19 -0
  32. package/dist/esm/core/webrtc/fileTransfer.d.ts +84 -0
  33. package/dist/esm/core/webrtc/fileTransfer.js +393 -0
  34. package/dist/esm/core/webrtc/mediaTracks.d.ts +53 -0
  35. package/dist/esm/core/webrtc/mediaTracks.js +381 -0
  36. package/dist/esm/core/webrtc/messages.d.ts +4 -0
  37. package/dist/esm/core/webrtc/messages.js +48 -0
  38. package/dist/esm/index.d.ts +4 -1
  39. package/dist/esm/index.js +5 -4
  40. package/dist/esm/package.json +3 -0
  41. package/dist/esm/types/types.d.ts +84 -4
  42. package/dist/index.cjs +3 -1
  43. package/dist/index.d.ts +4 -1
  44. package/dist/index.js +3 -1
  45. package/dist/types/types.d.ts +84 -4
  46. package/package.json +4 -3
@@ -1,308 +1,521 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WebRTCManager = void 0;
4
+ const AvesError_1 = require("./AvesError");
5
+ const channels_1 = require("./webrtc/channels");
6
+ const fileTransfer_1 = require("./webrtc/fileTransfer");
7
+ const mediaTracks_1 = require("./webrtc/mediaTracks");
8
+ const messages_1 = require("./webrtc/messages");
4
9
  /**
5
- * WebRTCManager - Manages WebRTC PeerConnections and DataChannels
6
- *
7
- * This class handles the low-level WebRTC connection management including:
8
- * - Creating and managing RTCPeerConnection instances
9
- * - Creating and managing RTCDataChannel instances
10
- * - Handling ICE candidate exchange
11
- * - Serializing and deserializing messages
12
- * - Managing connection lifecycle and cleanup
10
+ * WebRTCManager - Manages WebRTC PeerConnections, DataChannels, and media tracks
13
11
  */
14
12
  class WebRTCManager {
15
- constructor(iceServers) {
13
+ constructor(iceServers, fileChunkSize = fileTransfer_1.DEFAULT_FILE_CHUNK_SIZE, videoConstraints = {}) {
16
14
  this.peerConnections = new Map();
17
15
  this.dataChannels = new Map();
18
16
  this.iceServers = iceServers;
17
+ this.fileTransfers = new fileTransfer_1.FileTransferManager({
18
+ fileChunkSize,
19
+ getActivePeers: () => this.getActivePeers(),
20
+ isFileChannelReady: (peerId) => this.isFileChannelReady(peerId),
21
+ getMessageChannel: (peerId) => this.getMessageChannel(peerId),
22
+ getFileChannel: (peerId) => this.getFileChannel(peerId),
23
+ });
19
24
  this.messageCallbacks = new Set();
20
25
  this.connectionStateCallbacks = new Map();
21
26
  this.dataChannelStateCallbacks = new Map();
22
27
  this.iceCandidateCallbacks = new Map();
28
+ this.outgoingTransfers = this.fileTransfers.outgoingTransfers;
29
+ this.incomingTransfers = this.fileTransfers.incomingTransfers;
30
+ this.readyResolvers = this.fileTransfers.readyResolvers;
31
+ this.completionResolvers = this.fileTransfers.completionResolvers;
32
+ this.fileTransferStartedCallbacks =
33
+ this.fileTransfers.fileTransferStartedCallbacks;
34
+ this.fileTransferProgressCallbacks =
35
+ this.fileTransfers.fileTransferProgressCallbacks;
36
+ this.fileTransferCompletedCallbacks =
37
+ this.fileTransfers.fileTransferCompletedCallbacks;
38
+ this.fileTransferFailedCallbacks =
39
+ this.fileTransfers.fileTransferFailedCallbacks;
40
+ this.mediaTracks = new mediaTracks_1.MediaTrackManager(this.peerConnections, () => this.getActivePeers(), videoConstraints);
41
+ this.videoSenders = this.mediaTracks.videoSenders;
42
+ this.remoteAudioTrackCallbacks = this.mediaTracks.remoteAudioTrackCallbacks;
43
+ this.localAudioStateCallbacks = this.mediaTracks.localAudioStateCallbacks;
44
+ this.remoteVideoTrackCallbacks = this.mediaTracks.remoteVideoTrackCallbacks;
45
+ this.localVideoStateCallbacks = this.mediaTracks.localVideoStateCallbacks;
46
+ this.screenShareStateCallbacks = this.mediaTracks.screenShareStateCallbacks;
47
+ this.errorCallbacks = new Set();
23
48
  }
24
49
  /**
25
- * Create a new PeerConnection for the specified peer
26
- * If a connection already exists, returns the existing connection
50
+ * Create a new PeerConnection for the specified peer.
51
+ * If a connection already exists, returns the existing connection.
27
52
  */
28
53
  createPeerConnection(peerId) {
29
- if (this.peerConnections.has(peerId)) {
30
- console.log(`[WebRTCManager] Reusing existing PeerConnection for ${peerId}`);
31
- return this.peerConnections.get(peerId);
54
+ const existing = this.peerConnections.get(peerId);
55
+ if (existing) {
56
+ return existing;
32
57
  }
33
- console.log(`[WebRTCManager] Creating new PeerConnection for ${peerId}`);
34
58
  const pc = new RTCPeerConnection({
35
59
  iceServers: this.iceServers,
36
60
  });
37
61
  this.peerConnections.set(peerId, pc);
38
- // Monitor connection state changes
39
- pc.onconnectionstatechange = () => {
40
- console.log(`[WebRTCManager] Connection state for ${peerId}: ${pc.connectionState}`);
41
- const callbacks = this.connectionStateCallbacks.get(peerId);
42
- if (callbacks) {
43
- callbacks.forEach((callback) => callback(pc.connectionState));
44
- }
45
- // Auto-cleanup on failed/closed/disconnected states
46
- if (pc.connectionState === "failed" ||
47
- pc.connectionState === "closed" ||
48
- pc.connectionState === "disconnected") {
49
- this.closePeerConnection(peerId);
50
- }
51
- };
62
+ this.dataChannels.set(peerId, {});
63
+ this.setupPeerConnection(peerId, pc);
52
64
  return pc;
53
65
  }
54
66
  /**
55
- * Create an offer for the specified peer
56
- * This also creates the DataChannel (offer side creates the channel)
67
+ * Create an offer for the specified peer.
68
+ * The offer side creates both the message and file channels.
57
69
  */
58
70
  async createOffer(peerId) {
59
- const pc = this.peerConnections.get(peerId);
60
- if (!pc) {
61
- throw new Error(`No peer connection found for ${peerId}`);
62
- }
63
- console.log(`[WebRTCManager] Creating offer for ${peerId}, current state: ${pc.signalingState}`);
64
- // Create DataChannel (offer side creates it)
65
- const dataChannel = pc.createDataChannel("data");
66
- this.setupDataChannel(peerId, dataChannel);
71
+ const pc = this.getPeerConnection(peerId);
72
+ this.ensureDataChannel(peerId, pc, channels_1.MESSAGE_CHANNEL_LABEL);
73
+ this.ensureDataChannel(peerId, pc, channels_1.FILE_CHANNEL_LABEL);
67
74
  const offer = await pc.createOffer();
68
75
  await pc.setLocalDescription(offer);
69
- console.log(`[WebRTCManager] Created offer for ${peerId}, new state: ${pc.signalingState}`);
70
76
  return offer;
71
77
  }
72
78
  /**
73
- * Create an answer for the specified peer
74
- * Sets up the remote offer and creates an answer
79
+ * Create an answer for the specified peer.
80
+ * The answer side receives data channels from the remote offer.
75
81
  */
76
82
  async createAnswer(peerId, offer) {
77
- const pc = this.peerConnections.get(peerId);
78
- if (!pc) {
79
- throw new Error(`No peer connection found for ${peerId}`);
80
- }
81
- // Listen for DataChannel (answer side receives it)
83
+ const pc = this.getPeerConnection(peerId);
82
84
  pc.ondatachannel = (event) => {
83
85
  this.setupDataChannel(peerId, event.channel);
84
86
  };
85
- console.log(`[WebRTCManager] Creating answer for ${peerId}, current state: ${pc.signalingState}`);
86
87
  await pc.setRemoteDescription(new RTCSessionDescription(offer));
87
- console.log(`[WebRTCManager] Set remote offer for ${peerId}, new state: ${pc.signalingState}`);
88
88
  const answer = await pc.createAnswer();
89
89
  await pc.setLocalDescription(answer);
90
- console.log(`[WebRTCManager] Created answer for ${peerId}, new state: ${pc.signalingState}`);
91
90
  return answer;
92
91
  }
93
92
  /**
94
- * Set the remote answer for the specified peer
93
+ * Set the remote answer for the specified peer.
95
94
  */
96
95
  async setRemoteAnswer(peerId, answer) {
97
- const pc = this.peerConnections.get(peerId);
98
- if (!pc) {
99
- throw new Error(`No peer connection found for ${peerId}`);
100
- }
101
- console.log(`[WebRTCManager] Setting remote answer for ${peerId}, current state: ${pc.signalingState}`);
102
- // Check if we're in the correct state to set remote answer
103
- if (pc.signalingState !== "have-local-offer") {
104
- throw new Error(`Cannot set remote answer for ${peerId}: wrong state ${pc.signalingState}, expected have-local-offer`);
105
- }
96
+ const pc = this.getPeerConnection(peerId);
106
97
  await pc.setRemoteDescription(new RTCSessionDescription(answer));
107
- console.log(`[WebRTCManager] Successfully set remote answer for ${peerId}`);
108
98
  }
109
99
  /**
110
- * Add an ICE candidate for the specified peer
100
+ * Add an ICE candidate for the specified peer.
111
101
  */
112
102
  async addIceCandidate(peerId, candidate) {
113
- const pc = this.peerConnections.get(peerId);
114
- if (!pc) {
115
- throw new Error(`No peer connection found for ${peerId}`);
116
- }
117
- try {
118
- await pc.addIceCandidate(new RTCIceCandidate(candidate));
119
- }
120
- catch (error) {
121
- console.error(`Error adding ICE candidate for ${peerId}:`, error);
122
- throw error;
123
- }
103
+ const pc = this.getPeerConnection(peerId);
104
+ await pc.addIceCandidate(new RTCIceCandidate(candidate));
124
105
  }
125
106
  /**
126
- * Register a callback for ICE candidates from the specified peer
107
+ * Send a JSON message to all connected peers.
108
+ * Peers with unavailable channels are skipped gracefully;
109
+ * the message is delivered to every ready peer.
127
110
  */
128
- onIceCandidate(peerId, callback) {
129
- const pc = this.peerConnections.get(peerId);
130
- if (!pc) {
131
- throw new Error(`No peer connection found for ${peerId}`);
132
- }
133
- if (!this.iceCandidateCallbacks.has(peerId)) {
134
- this.iceCandidateCallbacks.set(peerId, new Set());
135
- }
136
- this.iceCandidateCallbacks.get(peerId).add(callback);
137
- pc.onicecandidate = (event) => {
138
- if (event.candidate) {
139
- const callbacks = this.iceCandidateCallbacks.get(peerId);
140
- if (callbacks) {
141
- callbacks.forEach((cb) => cb(event.candidate.toJSON()));
142
- }
111
+ sendMessage(message) {
112
+ const payload = (0, messages_1.serializeUserMessage)(message);
113
+ this.dataChannels.forEach((storedChannels, peerId) => {
114
+ const channels = (0, channels_1.normalizePeerChannels)(storedChannels);
115
+ if (!channels.message || channels.message.readyState !== "open") {
116
+ return;
143
117
  }
144
- };
118
+ try {
119
+ channels.message.send(payload);
120
+ }
121
+ catch (error) {
122
+ this.emitError(new AvesError_1.AvesError({ message: `Failed to send message to ${peerId}: ${(0, messages_1.errorMessage)(error)}`, code: "MESSAGE_SEND_FAILED", stage: "transport", retryable: true, peerId }));
123
+ }
124
+ });
145
125
  }
146
126
  /**
147
- * Register a callback for connection state changes
127
+ * Send a JSON message to a specific peer.
148
128
  */
149
- onConnectionStateChange(peerId, callback) {
150
- if (!this.connectionStateCallbacks.has(peerId)) {
151
- this.connectionStateCallbacks.set(peerId, new Set());
129
+ sendMessageToPeer(peerId, message) {
130
+ const dataChannel = this.getMessageChannel(peerId);
131
+ if (dataChannel.readyState !== "open") {
132
+ throw new AvesError_1.AvesError({ message: `DataChannel not ready for ${peerId}, state: ${dataChannel.readyState}`, code: "MESSAGE_CHANNEL_NOT_READY", stage: "transport", retryable: true, peerId });
152
133
  }
153
- this.connectionStateCallbacks.get(peerId).add(callback);
134
+ dataChannel.send((0, messages_1.serializeUserMessage)(message));
154
135
  }
155
136
  /**
156
- * Register a callback for DataChannel state changes
137
+ * Send a file to one peer or broadcast to every connected peer.
157
138
  */
158
- onDataChannelStateChange(peerId, callback) {
159
- if (!this.dataChannelStateCallbacks.has(peerId)) {
160
- this.dataChannelStateCallbacks.set(peerId, new Set());
161
- }
162
- this.dataChannelStateCallbacks.get(peerId).add(callback);
139
+ async sendFile(blob, options = {}) {
140
+ return this.fileTransfers.sendFile(blob, options);
163
141
  }
164
142
  /**
165
- * Register a callback for incoming messages
143
+ * Start capturing local audio and bind it to current peer connections.
166
144
  */
167
- onMessage(callback) {
168
- this.messageCallbacks.add(callback);
145
+ async startVoice() {
146
+ return this.mediaTracks.startVoice();
169
147
  }
170
148
  /**
171
- * Setup DataChannel event handlers
149
+ * Stop local audio capture and detach it from active peers.
172
150
  */
173
- setupDataChannel(peerId, dataChannel) {
174
- this.dataChannels.set(peerId, dataChannel);
175
- dataChannel.onopen = () => {
176
- const callbacks = this.dataChannelStateCallbacks.get(peerId);
177
- if (callbacks) {
178
- callbacks.forEach((callback) => callback(dataChannel.readyState));
179
- }
180
- };
181
- dataChannel.onclose = () => {
182
- const callbacks = this.dataChannelStateCallbacks.get(peerId);
183
- if (callbacks) {
184
- callbacks.forEach((callback) => callback(dataChannel.readyState));
185
- }
186
- this.dataChannels.delete(peerId);
187
- };
188
- dataChannel.onerror = (error) => {
189
- console.error(`DataChannel error with ${peerId}:`, error);
190
- };
191
- dataChannel.onmessage = (event) => {
192
- try {
193
- // Deserialize JSON message
194
- const message = JSON.parse(event.data);
195
- this.messageCallbacks.forEach((callback) => callback(peerId, message));
196
- }
197
- catch (error) {
198
- // Log error but don't interrupt connection
199
- console.error(`Failed to parse message from ${peerId}:`, error);
200
- }
201
- };
151
+ stopVoice() {
152
+ this.mediaTracks.stopVoice();
202
153
  }
203
154
  /**
204
- * Send a message to all connected peers
205
- * Throws error if any DataChannel is not ready
155
+ * Toggle local mute state.
206
156
  */
207
- sendMessage(message) {
208
- const errors = [];
209
- this.dataChannels.forEach((dataChannel, peerId) => {
210
- if (dataChannel.readyState === "open") {
211
- try {
212
- // Serialize message to JSON
213
- const serialized = JSON.stringify(message);
214
- dataChannel.send(serialized);
215
- }
216
- catch (error) {
217
- console.error(`Failed to send message to ${peerId}:`, error);
218
- errors.push(peerId);
219
- }
220
- }
221
- else {
222
- errors.push(peerId);
223
- }
224
- });
225
- if (errors.length > 0) {
226
- throw new Error(`DataChannel not ready for peers: ${errors.join(", ")}`);
227
- }
157
+ setMuted(muted) {
158
+ this.mediaTracks.setMuted(muted);
228
159
  }
229
160
  /**
230
- * Send a message to a specific peer
231
- * Throws error if DataChannel is not ready
161
+ * Read current local audio state.
232
162
  */
233
- sendMessageToPeer(peerId, message) {
234
- const dataChannel = this.dataChannels.get(peerId);
235
- if (!dataChannel) {
236
- throw new Error(`No DataChannel found for ${peerId}`);
237
- }
238
- if (dataChannel.readyState !== "open") {
239
- throw new Error(`DataChannel not ready for ${peerId}, state: ${dataChannel.readyState}`);
163
+ getLocalAudioState() {
164
+ return this.mediaTracks.getLocalAudioState();
165
+ }
166
+ /**
167
+ * Read current remote audio stream for a peer.
168
+ */
169
+ getRemoteAudioStream(peerId) {
170
+ return this.mediaTracks.getRemoteAudioStream(peerId);
171
+ }
172
+ // ========== Video Methods ==========
173
+ /**
174
+ * Start capturing local camera video and bind it to current peer connections.
175
+ * Idempotent: returns the existing stream if already active.
176
+ */
177
+ async startVideo(constraints) {
178
+ return this.mediaTracks.startVideo(constraints);
179
+ }
180
+ /**
181
+ * Stop local camera capture and detach it from active peers.
182
+ */
183
+ stopVideo() {
184
+ this.mediaTracks.stopVideo();
185
+ }
186
+ /**
187
+ * Toggle local video mute state (camera on/off).
188
+ */
189
+ setVideoMuted(muted) {
190
+ this.mediaTracks.setVideoMuted(muted);
191
+ }
192
+ /**
193
+ * Read current local video state.
194
+ */
195
+ getLocalVideoState() {
196
+ return this.mediaTracks.getLocalVideoState();
197
+ }
198
+ /**
199
+ * Read current remote video stream for a peer.
200
+ */
201
+ getRemoteVideoStream(peerId) {
202
+ return this.mediaTracks.getRemoteVideoStream(peerId);
203
+ }
204
+ // ========== Screen Share Methods ==========
205
+ /**
206
+ * Start screen sharing. Replaces the camera video track with the display track
207
+ * on all active peer connections. The camera track is saved and restored when
208
+ * screen sharing stops.
209
+ */
210
+ async startScreenShare() {
211
+ return this.mediaTracks.startScreenShare();
212
+ }
213
+ /**
214
+ * Stop screen sharing and restore the camera video track (if it was active).
215
+ */
216
+ stopScreenShare() {
217
+ this.mediaTracks.stopScreenShare();
218
+ }
219
+ /**
220
+ * Read current screen share state.
221
+ */
222
+ getScreenShareState() {
223
+ return this.mediaTracks.getScreenShareState();
224
+ }
225
+ // ========== Video / Screen Share Callback Registration ==========
226
+ /**
227
+ * Register a callback for remote video tracks.
228
+ */
229
+ onRemoteVideoTrack(callback) {
230
+ this.mediaTracks.onRemoteVideoTrack(callback);
231
+ }
232
+ /**
233
+ * Register a callback for local video state changes.
234
+ */
235
+ onLocalVideoStateChange(callback) {
236
+ this.mediaTracks.onLocalVideoStateChange(callback);
237
+ }
238
+ /**
239
+ * Register a callback for screen share state changes.
240
+ */
241
+ onScreenShareStateChange(callback) {
242
+ this.mediaTracks.onScreenShareStateChange(callback);
243
+ }
244
+ // ========== Error Callback Registration ==========
245
+ /**
246
+ * Register a callback for WebRTCManager-level errors
247
+ * (e.g. DataChannel failures, message parse errors).
248
+ */
249
+ onError(callback) {
250
+ this.errorCallbacks.add(callback);
251
+ }
252
+ // ========== Emit Helpers ==========
253
+ emitError(error) {
254
+ this.errorCallbacks.forEach((callback) => callback(error));
255
+ }
256
+ /**
257
+ * Register a callback for ICE candidates from the specified peer.
258
+ */
259
+ onIceCandidate(peerId, callback) {
260
+ // Ensure the peer connection exists
261
+ this.getPeerConnection(peerId);
262
+ let callbacks = this.iceCandidateCallbacks.get(peerId);
263
+ if (!callbacks) {
264
+ callbacks = new Set();
265
+ this.iceCandidateCallbacks.set(peerId, callbacks);
240
266
  }
241
- try {
242
- // Serialize message to JSON
243
- const serialized = JSON.stringify(message);
244
- dataChannel.send(serialized);
267
+ callbacks.add(callback);
268
+ }
269
+ /**
270
+ * Register a callback for connection state changes.
271
+ */
272
+ onConnectionStateChange(peerId, callback) {
273
+ let callbacks = this.connectionStateCallbacks.get(peerId);
274
+ if (!callbacks) {
275
+ callbacks = new Set();
276
+ this.connectionStateCallbacks.set(peerId, callbacks);
245
277
  }
246
- catch (error) {
247
- console.error(`Failed to send message to ${peerId}:`, error);
248
- throw error;
278
+ callbacks.add(callback);
279
+ }
280
+ /**
281
+ * Register a callback for main DataChannel state changes.
282
+ */
283
+ onDataChannelStateChange(peerId, callback) {
284
+ let callbacks = this.dataChannelStateCallbacks.get(peerId);
285
+ if (!callbacks) {
286
+ callbacks = new Set();
287
+ this.dataChannelStateCallbacks.set(peerId, callbacks);
249
288
  }
289
+ callbacks.add(callback);
250
290
  }
251
291
  /**
252
- * Close the connection with a specific peer
292
+ * Register a callback for incoming user messages.
293
+ */
294
+ onMessage(callback) {
295
+ this.messageCallbacks.add(callback);
296
+ }
297
+ onFileTransferStarted(callback) {
298
+ this.fileTransfers.onStarted(callback);
299
+ }
300
+ onFileTransferProgress(callback) {
301
+ this.fileTransfers.onProgress(callback);
302
+ }
303
+ onFileTransferCompleted(callback) {
304
+ this.fileTransfers.onCompleted(callback);
305
+ }
306
+ onFileTransferFailed(callback) {
307
+ this.fileTransfers.onFailed(callback);
308
+ }
309
+ onRemoteAudioTrack(callback) {
310
+ this.mediaTracks.onRemoteAudioTrack(callback);
311
+ }
312
+ onLocalAudioStateChange(callback) {
313
+ this.mediaTracks.onLocalAudioStateChange(callback);
314
+ }
315
+ /**
316
+ * Close the connection with a specific peer.
253
317
  */
254
318
  closePeerConnection(peerId) {
255
- const dataChannel = this.dataChannels.get(peerId);
256
- if (dataChannel) {
257
- dataChannel.close();
258
- this.dataChannels.delete(peerId);
259
- }
319
+ this.failActiveTransfers(peerId, new AvesError_1.AvesError({ message: `Peer connection closed for ${peerId}`, code: "WEBRTC_CONNECTION_FAILED", stage: "transport", retryable: false, peerId }));
320
+ const channels = (0, channels_1.normalizePeerChannels)(this.dataChannels.get(peerId));
321
+ channels?.message?.close();
322
+ channels?.file?.close();
323
+ this.dataChannels.delete(peerId);
260
324
  const pc = this.peerConnections.get(peerId);
261
325
  if (pc) {
262
326
  pc.close();
263
327
  this.peerConnections.delete(peerId);
264
328
  }
265
- // Clean up callbacks
329
+ this.clearReadyResolver(peerId);
330
+ this.clearCompletionResolver(peerId);
331
+ this.outgoingTransfers.delete(peerId);
332
+ this.incomingTransfers.delete(peerId);
333
+ this.mediaTracks.closePeer(peerId);
266
334
  this.connectionStateCallbacks.delete(peerId);
267
335
  this.dataChannelStateCallbacks.delete(peerId);
268
336
  this.iceCandidateCallbacks.delete(peerId);
269
337
  }
270
338
  /**
271
- * Close all connections and clean up resources
339
+ * Close all connections and clean up resources.
272
340
  */
273
341
  closeAll() {
274
- this.dataChannels.forEach((dataChannel) => {
275
- dataChannel.close();
342
+ this.getActivePeers().forEach((peerId) => {
343
+ this.closePeerConnection(peerId);
276
344
  });
277
- this.dataChannels.clear();
278
- this.peerConnections.forEach((pc) => {
279
- pc.close();
280
- });
281
- this.peerConnections.clear();
345
+ this.stopVoice();
346
+ this.stopVideo();
347
+ this.stopScreenShare();
348
+ }
349
+ destroy() {
350
+ this.closeAll();
282
351
  this.messageCallbacks.clear();
283
- this.connectionStateCallbacks.clear();
284
- this.dataChannelStateCallbacks.clear();
285
- this.iceCandidateCallbacks.clear();
352
+ this.fileTransfers.clearCallbacks();
353
+ this.mediaTracks.clearCallbacks();
354
+ this.errorCallbacks.clear();
286
355
  }
287
356
  /**
288
- * Get all active peer IDs
357
+ * Get all active peer IDs.
289
358
  */
290
359
  getActivePeers() {
291
360
  return Array.from(this.peerConnections.keys());
292
361
  }
293
362
  /**
294
- * Check if connected to a specific peer
363
+ * Check if connected to a specific peer.
295
364
  */
296
365
  isConnected(peerId) {
297
366
  const pc = this.peerConnections.get(peerId);
298
367
  return pc?.connectionState === "connected";
299
368
  }
300
369
  /**
301
- * Check if DataChannel is ready for a specific peer
370
+ * Get the actual RTCPeerConnectionState for a peer.
371
+ */
372
+ getConnectionState(peerId) {
373
+ const pc = this.peerConnections.get(peerId);
374
+ return pc?.connectionState ?? "closed";
375
+ }
376
+ /**
377
+ * Check if the main DataChannel is ready for a specific peer.
302
378
  */
303
379
  isDataChannelReady(peerId) {
304
- const dataChannel = this.dataChannels.get(peerId);
305
- return dataChannel?.readyState === "open";
380
+ return ((0, channels_1.normalizePeerChannels)(this.dataChannels.get(peerId)).message
381
+ ?.readyState === "open");
382
+ }
383
+ /**
384
+ * Check if the file channel is ready for a specific peer.
385
+ */
386
+ isFileChannelReady(peerId) {
387
+ return ((0, channels_1.normalizePeerChannels)(this.dataChannels.get(peerId)).file
388
+ ?.readyState === "open");
389
+ }
390
+ setupPeerConnection(peerId, pc) {
391
+ pc.onconnectionstatechange = () => {
392
+ const callbacks = this.connectionStateCallbacks.get(peerId);
393
+ callbacks?.forEach((callback) => callback(pc.connectionState));
394
+ if (pc.connectionState === "failed" ||
395
+ pc.connectionState === "closed" ||
396
+ pc.connectionState === "disconnected") {
397
+ this.closePeerConnection(peerId);
398
+ }
399
+ };
400
+ pc.onicecandidate = (event) => {
401
+ if (!event.candidate) {
402
+ return;
403
+ }
404
+ const callbacks = this.iceCandidateCallbacks.get(peerId);
405
+ callbacks?.forEach((cb) => cb(event.candidate.toJSON()));
406
+ };
407
+ this.mediaTracks.bindPeerConnection(peerId, pc);
408
+ }
409
+ ensureDataChannel(peerId, pc, label) {
410
+ const channels = this.dataChannels.get(peerId) ?? {};
411
+ const kind = (0, channels_1.getChannelKind)(label);
412
+ const existing = channels[kind];
413
+ if (existing) {
414
+ return existing;
415
+ }
416
+ const channel = pc.createDataChannel(label);
417
+ this.setupDataChannel(peerId, channel);
418
+ return channel;
419
+ }
420
+ setupDataChannel(peerId, dataChannel) {
421
+ const kind = (0, channels_1.getChannelKind)(dataChannel.label);
422
+ const channels = (0, channels_1.normalizePeerChannels)(this.dataChannels.get(peerId));
423
+ channels[kind] = dataChannel;
424
+ this.dataChannels.set(peerId, channels);
425
+ if (kind === "file") {
426
+ dataChannel.binaryType = "arraybuffer";
427
+ }
428
+ dataChannel.onopen = () => {
429
+ if (kind !== "message") {
430
+ return;
431
+ }
432
+ const callbacks = this.dataChannelStateCallbacks.get(peerId);
433
+ callbacks?.forEach((callback) => callback(dataChannel.readyState));
434
+ };
435
+ dataChannel.onclose = () => {
436
+ if (kind === "message") {
437
+ const callbacks = this.dataChannelStateCallbacks.get(peerId);
438
+ callbacks?.forEach((callback) => callback(dataChannel.readyState));
439
+ }
440
+ const storedChannels = this.dataChannels.get(peerId);
441
+ if (storedChannels && (0, channels_1.isPeerChannels)(storedChannels) && storedChannels[kind] === dataChannel) {
442
+ delete storedChannels[kind];
443
+ if (!storedChannels.message && !storedChannels.file) {
444
+ this.dataChannels.delete(peerId);
445
+ }
446
+ }
447
+ if (kind === "message" || kind === "file") {
448
+ this.failActiveTransfers(peerId, new AvesError_1.AvesError({ message: `${kind} channel closed during file transfer`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: true, peerId }));
449
+ }
450
+ };
451
+ dataChannel.onerror = (error) => {
452
+ this.emitError(new AvesError_1.AvesError({ message: `DataChannel error with ${peerId}: ${(0, messages_1.errorMessage)(error)}`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: true, peerId }));
453
+ const transfer = kind === "file"
454
+ ? this.outgoingTransfers.get(peerId) ?? this.incomingTransfers.get(peerId) ?? null
455
+ : null;
456
+ if (transfer) {
457
+ this.emitFileTransferFailed(peerId, transfer, new AvesError_1.AvesError({ message: `DataChannel error on ${kind} channel`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: true, peerId }));
458
+ }
459
+ };
460
+ dataChannel.onmessage = (event) => {
461
+ if (kind === "file") {
462
+ this.handleFileChunk(peerId, event.data);
463
+ return;
464
+ }
465
+ this.handleMessageChannelMessage(peerId, event.data);
466
+ };
467
+ }
468
+ handleMessageChannelMessage(peerId, rawData) {
469
+ try {
470
+ const message = JSON.parse(rawData);
471
+ if ((0, fileTransfer_1.isFileControlMessage)(message)) {
472
+ this.handleFileControlMessage(peerId, message);
473
+ return;
474
+ }
475
+ this.messageCallbacks.forEach((callback) => callback(peerId, message));
476
+ }
477
+ catch (error) {
478
+ this.emitError(new AvesError_1.AvesError({ message: `Failed to parse message from ${peerId}: ${(0, messages_1.errorMessage)(error)}`, code: "MESSAGE_PARSE_FAILED", stage: "transport", retryable: false, peerId }));
479
+ }
480
+ }
481
+ handleFileControlMessage(peerId, message) {
482
+ this.fileTransfers.handleControlMessage(peerId, message);
483
+ }
484
+ handleFileChunk(peerId, data) {
485
+ this.fileTransfers.handleChunk(peerId, data);
486
+ }
487
+ emitFileTransferFailed(peerId, info, error) {
488
+ this.fileTransfers.reportFailure(peerId, info, error);
489
+ }
490
+ clearReadyResolver(peerId) {
491
+ this.fileTransfers.clearReadyResolver(peerId);
492
+ }
493
+ clearCompletionResolver(peerId) {
494
+ this.fileTransfers.clearCompletionResolver(peerId);
495
+ }
496
+ getPeerConnection(peerId) {
497
+ const pc = this.peerConnections.get(peerId);
498
+ if (!pc) {
499
+ throw new AvesError_1.AvesError({ message: `No peer connection found for ${peerId}`, code: "WEBRTC_CONNECTION_FAILED", stage: "transport", retryable: false, peerId });
500
+ }
501
+ return pc;
502
+ }
503
+ getMessageChannel(peerId) {
504
+ const channel = (0, channels_1.normalizePeerChannels)(this.dataChannels.get(peerId)).message;
505
+ if (!channel) {
506
+ throw new AvesError_1.AvesError({ message: `No DataChannel found for ${peerId}`, code: "WEBRTC_DATACHANNEL_FAILED", stage: "transport", retryable: false, peerId });
507
+ }
508
+ return channel;
509
+ }
510
+ getFileChannel(peerId) {
511
+ const channel = (0, channels_1.normalizePeerChannels)(this.dataChannels.get(peerId)).file;
512
+ if (!channel) {
513
+ throw new AvesError_1.AvesError({ message: `No file channel found for ${peerId}`, code: "FILE_CHANNEL_NOT_READY", stage: "transport", retryable: false, peerId });
514
+ }
515
+ return channel;
516
+ }
517
+ failActiveTransfers(peerId, error) {
518
+ this.fileTransfers.failActiveTransfers(peerId, error);
306
519
  }
307
520
  }
308
521
  exports.WebRTCManager = WebRTCManager;