@yrzhao/aves-core 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,147 +1,236 @@
1
+ const DEFAULT_FILE_CHUNK_SIZE = 16 * 1024;
2
+ const FILE_CHANNEL_LABEL = "file";
3
+ const MESSAGE_CHANNEL_LABEL = "data";
4
+ const FILE_PROTOCOL = "aves:file-control";
5
+ const FILE_READY_TIMEOUT_MS = 10000;
6
+ const FILE_COMPLETE_TIMEOUT_MS = 10000;
7
+ const FILE_END_MARKER_PREFIX = "__aves_file_end__:";
1
8
  /**
2
- * WebRTCManager - Manages WebRTC PeerConnections and DataChannels
3
- *
4
- * This class handles the low-level WebRTC connection management including:
5
- * - Creating and managing RTCPeerConnection instances
6
- * - Creating and managing RTCDataChannel instances
7
- * - Handling ICE candidate exchange
8
- * - Serializing and deserializing messages
9
- * - Managing connection lifecycle and cleanup
9
+ * WebRTCManager - Manages WebRTC PeerConnections, DataChannels, and media tracks
10
10
  */
11
11
  export class WebRTCManager {
12
- constructor(iceServers) {
12
+ constructor(iceServers, fileChunkSize = DEFAULT_FILE_CHUNK_SIZE) {
13
13
  this.peerConnections = new Map();
14
14
  this.dataChannels = new Map();
15
15
  this.iceServers = iceServers;
16
+ this.fileChunkSize = this.validateChunkSize(fileChunkSize);
16
17
  this.messageCallbacks = new Set();
17
18
  this.connectionStateCallbacks = new Map();
18
19
  this.dataChannelStateCallbacks = new Map();
19
20
  this.iceCandidateCallbacks = new Map();
21
+ this.fileTransferStartedCallbacks = new Set();
22
+ this.fileTransferProgressCallbacks = new Set();
23
+ this.fileTransferCompletedCallbacks = new Set();
24
+ this.fileTransferFailedCallbacks = new Set();
25
+ this.remoteAudioTrackCallbacks = new Set();
26
+ this.localAudioStateCallbacks = new Set();
27
+ this.outgoingTransfers = new Map();
28
+ this.incomingTransfers = new Map();
29
+ this.readyResolvers = new Map();
30
+ this.completionResolvers = new Map();
31
+ this.audioSenders = new Map();
32
+ this.remoteAudioStreams = new Map();
33
+ this.localAudioStream = null;
34
+ this.localAudioTrack = null;
35
+ this.isMuted = false;
20
36
  }
21
37
  /**
22
- * Create a new PeerConnection for the specified peer
23
- * If a connection already exists, returns the existing connection
38
+ * Create a new PeerConnection for the specified peer.
39
+ * If a connection already exists, returns the existing connection.
24
40
  */
25
41
  createPeerConnection(peerId) {
26
42
  if (this.peerConnections.has(peerId)) {
27
- console.log(`[WebRTCManager] Reusing existing PeerConnection for ${peerId}`);
28
43
  return this.peerConnections.get(peerId);
29
44
  }
30
- console.log(`[WebRTCManager] Creating new PeerConnection for ${peerId}`);
31
45
  const pc = new RTCPeerConnection({
32
46
  iceServers: this.iceServers,
33
47
  });
34
48
  this.peerConnections.set(peerId, pc);
35
- // Monitor connection state changes
36
- pc.onconnectionstatechange = () => {
37
- console.log(`[WebRTCManager] Connection state for ${peerId}: ${pc.connectionState}`);
38
- const callbacks = this.connectionStateCallbacks.get(peerId);
39
- if (callbacks) {
40
- callbacks.forEach((callback) => callback(pc.connectionState));
41
- }
42
- // Auto-cleanup on failed/closed/disconnected states
43
- if (pc.connectionState === "failed" ||
44
- pc.connectionState === "closed" ||
45
- pc.connectionState === "disconnected") {
46
- this.closePeerConnection(peerId);
47
- }
48
- };
49
+ this.dataChannels.set(peerId, {});
50
+ this.setupPeerConnection(peerId, pc);
49
51
  return pc;
50
52
  }
51
53
  /**
52
- * Create an offer for the specified peer
53
- * This also creates the DataChannel (offer side creates the channel)
54
+ * Create an offer for the specified peer.
55
+ * The offer side creates both the message and file channels.
54
56
  */
55
57
  async createOffer(peerId) {
56
- const pc = this.peerConnections.get(peerId);
57
- if (!pc) {
58
- throw new Error(`No peer connection found for ${peerId}`);
59
- }
60
- console.log(`[WebRTCManager] Creating offer for ${peerId}, current state: ${pc.signalingState}`);
61
- // Create DataChannel (offer side creates it)
62
- const dataChannel = pc.createDataChannel("data");
63
- this.setupDataChannel(peerId, dataChannel);
58
+ const pc = this.getPeerConnection(peerId);
59
+ this.ensureDataChannel(peerId, pc, MESSAGE_CHANNEL_LABEL);
60
+ this.ensureDataChannel(peerId, pc, FILE_CHANNEL_LABEL);
64
61
  const offer = await pc.createOffer();
65
62
  await pc.setLocalDescription(offer);
66
- console.log(`[WebRTCManager] Created offer for ${peerId}, new state: ${pc.signalingState}`);
67
63
  return offer;
68
64
  }
69
65
  /**
70
- * Create an answer for the specified peer
71
- * Sets up the remote offer and creates an answer
66
+ * Create an answer for the specified peer.
67
+ * The answer side receives data channels from the remote offer.
72
68
  */
73
69
  async createAnswer(peerId, offer) {
74
- const pc = this.peerConnections.get(peerId);
75
- if (!pc) {
76
- throw new Error(`No peer connection found for ${peerId}`);
77
- }
78
- // Listen for DataChannel (answer side receives it)
70
+ const pc = this.getPeerConnection(peerId);
79
71
  pc.ondatachannel = (event) => {
80
72
  this.setupDataChannel(peerId, event.channel);
81
73
  };
82
- console.log(`[WebRTCManager] Creating answer for ${peerId}, current state: ${pc.signalingState}`);
83
74
  await pc.setRemoteDescription(new RTCSessionDescription(offer));
84
- console.log(`[WebRTCManager] Set remote offer for ${peerId}, new state: ${pc.signalingState}`);
85
75
  const answer = await pc.createAnswer();
86
76
  await pc.setLocalDescription(answer);
87
- console.log(`[WebRTCManager] Created answer for ${peerId}, new state: ${pc.signalingState}`);
88
77
  return answer;
89
78
  }
90
79
  /**
91
- * Set the remote answer for the specified peer
80
+ * Set the remote answer for the specified peer.
92
81
  */
93
82
  async setRemoteAnswer(peerId, answer) {
94
- const pc = this.peerConnections.get(peerId);
95
- if (!pc) {
96
- throw new Error(`No peer connection found for ${peerId}`);
97
- }
98
- console.log(`[WebRTCManager] Setting remote answer for ${peerId}, current state: ${pc.signalingState}`);
99
- // Check if we're in the correct state to set remote answer
100
- if (pc.signalingState !== "have-local-offer") {
101
- throw new Error(`Cannot set remote answer for ${peerId}: wrong state ${pc.signalingState}, expected have-local-offer`);
102
- }
83
+ const pc = this.getPeerConnection(peerId);
103
84
  await pc.setRemoteDescription(new RTCSessionDescription(answer));
104
- console.log(`[WebRTCManager] Successfully set remote answer for ${peerId}`);
105
85
  }
106
86
  /**
107
- * Add an ICE candidate for the specified peer
87
+ * Add an ICE candidate for the specified peer.
108
88
  */
109
89
  async addIceCandidate(peerId, candidate) {
110
- const pc = this.peerConnections.get(peerId);
111
- if (!pc) {
112
- throw new Error(`No peer connection found for ${peerId}`);
90
+ const pc = this.getPeerConnection(peerId);
91
+ await pc.addIceCandidate(new RTCIceCandidate(candidate));
92
+ }
93
+ /**
94
+ * Send a JSON message to all connected peers.
95
+ */
96
+ sendMessage(message) {
97
+ const errors = [];
98
+ this.dataChannels.forEach((storedChannels, peerId) => {
99
+ const channels = this.normalizePeerChannels(storedChannels);
100
+ if (!channels.message || channels.message.readyState !== "open") {
101
+ errors.push(peerId);
102
+ return;
103
+ }
104
+ try {
105
+ channels.message.send(JSON.stringify(message));
106
+ }
107
+ catch (error) {
108
+ errors.push(peerId);
109
+ }
110
+ });
111
+ if (errors.length > 0) {
112
+ throw new Error(`DataChannel not ready for peers: ${errors.join(", ")}`);
113
113
  }
114
- try {
115
- await pc.addIceCandidate(new RTCIceCandidate(candidate));
114
+ }
115
+ /**
116
+ * Send a JSON message to a specific peer.
117
+ */
118
+ sendMessageToPeer(peerId, message) {
119
+ const dataChannel = this.getMessageChannel(peerId);
120
+ if (dataChannel.readyState !== "open") {
121
+ throw new Error(`DataChannel not ready for ${peerId}, state: ${dataChannel.readyState}`);
116
122
  }
117
- catch (error) {
118
- console.error(`Error adding ICE candidate for ${peerId}:`, error);
119
- throw error;
123
+ dataChannel.send(JSON.stringify(message));
124
+ }
125
+ /**
126
+ * Send a file to one peer or broadcast to every connected peer.
127
+ */
128
+ async sendFile(blob, options = {}) {
129
+ const peerIds = options.peerId
130
+ ? [options.peerId]
131
+ : this.getActivePeers().filter((peerId) => this.isFileChannelReady(peerId));
132
+ if (peerIds.length === 0) {
133
+ throw new Error("No file channel is ready");
134
+ }
135
+ const results = [];
136
+ for (const peerId of peerIds) {
137
+ const info = await this.sendFileToPeer(peerId, blob, options);
138
+ results.push(info);
120
139
  }
140
+ return results;
121
141
  }
122
142
  /**
123
- * Register a callback for ICE candidates from the specified peer
143
+ * Start capturing local audio and bind it to current peer connections.
124
144
  */
125
- onIceCandidate(peerId, callback) {
126
- const pc = this.peerConnections.get(peerId);
127
- if (!pc) {
128
- throw new Error(`No peer connection found for ${peerId}`);
145
+ async startVoice() {
146
+ if (this.localAudioStream && this.localAudioTrack) {
147
+ this.emitLocalAudioState();
148
+ return this.localAudioStream;
149
+ }
150
+ if (typeof navigator === "undefined" ||
151
+ !navigator.mediaDevices ||
152
+ typeof navigator.mediaDevices.getUserMedia !== "function") {
153
+ throw new Error("Audio capture is not available in this environment");
154
+ }
155
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
156
+ const [track] = stream.getAudioTracks();
157
+ if (!track) {
158
+ throw new Error("No audio track available from getUserMedia");
159
+ }
160
+ track.enabled = !this.isMuted;
161
+ this.localAudioStream = stream;
162
+ this.localAudioTrack = track;
163
+ await Promise.all(this.getActivePeers().map((peerId) => this.syncLocalAudioTrack(peerId)));
164
+ this.emitLocalAudioState();
165
+ return stream;
166
+ }
167
+ /**
168
+ * Stop local audio capture and detach it from active peers.
169
+ */
170
+ stopVoice() {
171
+ if (this.localAudioTrack) {
172
+ this.audioSenders.forEach((sender, peerId) => {
173
+ if (sender && typeof sender.replaceTrack === "function") {
174
+ void sender.replaceTrack(null);
175
+ }
176
+ });
177
+ this.localAudioTrack.stop();
129
178
  }
179
+ if (this.localAudioStream) {
180
+ this.localAudioStream.getTracks().forEach((track) => {
181
+ if (track.readyState !== "ended") {
182
+ track.stop();
183
+ }
184
+ });
185
+ }
186
+ this.localAudioTrack = null;
187
+ this.localAudioStream = null;
188
+ this.emitLocalAudioState();
189
+ }
190
+ /**
191
+ * Toggle local mute state.
192
+ */
193
+ setMuted(muted) {
194
+ this.isMuted = muted;
195
+ if (this.localAudioTrack) {
196
+ this.localAudioTrack.enabled = !muted;
197
+ }
198
+ this.emitLocalAudioState();
199
+ }
200
+ /**
201
+ * Read current local audio state.
202
+ */
203
+ getLocalAudioState() {
204
+ return {
205
+ active: !!this.localAudioTrack,
206
+ muted: this.isMuted,
207
+ };
208
+ }
209
+ /**
210
+ * Read current remote audio stream for a peer.
211
+ */
212
+ getRemoteAudioStream(peerId) {
213
+ return this.remoteAudioStreams.get(peerId) ?? null;
214
+ }
215
+ /**
216
+ * Register a callback for ICE candidates from the specified peer.
217
+ */
218
+ onIceCandidate(peerId, callback) {
219
+ const pc = this.getPeerConnection(peerId);
130
220
  if (!this.iceCandidateCallbacks.has(peerId)) {
131
221
  this.iceCandidateCallbacks.set(peerId, new Set());
132
222
  }
133
223
  this.iceCandidateCallbacks.get(peerId).add(callback);
134
224
  pc.onicecandidate = (event) => {
135
- if (event.candidate) {
136
- const callbacks = this.iceCandidateCallbacks.get(peerId);
137
- if (callbacks) {
138
- callbacks.forEach((cb) => cb(event.candidate.toJSON()));
139
- }
225
+ if (!event.candidate) {
226
+ return;
140
227
  }
228
+ const callbacks = this.iceCandidateCallbacks.get(peerId);
229
+ callbacks?.forEach((cb) => cb(event.candidate.toJSON()));
141
230
  };
142
231
  }
143
232
  /**
144
- * Register a callback for connection state changes
233
+ * Register a callback for connection state changes.
145
234
  */
146
235
  onConnectionStateChange(peerId, callback) {
147
236
  if (!this.connectionStateCallbacks.has(peerId)) {
@@ -150,7 +239,7 @@ export class WebRTCManager {
150
239
  this.connectionStateCallbacks.get(peerId).add(callback);
151
240
  }
152
241
  /**
153
- * Register a callback for DataChannel state changes
242
+ * Register a callback for main DataChannel state changes.
154
243
  */
155
244
  onDataChannelStateChange(peerId, callback) {
156
245
  if (!this.dataChannelStateCallbacks.has(peerId)) {
@@ -159,146 +248,547 @@ export class WebRTCManager {
159
248
  this.dataChannelStateCallbacks.get(peerId).add(callback);
160
249
  }
161
250
  /**
162
- * Register a callback for incoming messages
251
+ * Register a callback for incoming user messages.
163
252
  */
164
253
  onMessage(callback) {
165
254
  this.messageCallbacks.add(callback);
166
255
  }
167
- /**
168
- * Setup DataChannel event handlers
169
- */
170
- setupDataChannel(peerId, dataChannel) {
171
- this.dataChannels.set(peerId, dataChannel);
172
- dataChannel.onopen = () => {
173
- const callbacks = this.dataChannelStateCallbacks.get(peerId);
174
- if (callbacks) {
175
- callbacks.forEach((callback) => callback(dataChannel.readyState));
176
- }
177
- };
178
- dataChannel.onclose = () => {
179
- const callbacks = this.dataChannelStateCallbacks.get(peerId);
180
- if (callbacks) {
181
- callbacks.forEach((callback) => callback(dataChannel.readyState));
182
- }
183
- this.dataChannels.delete(peerId);
184
- };
185
- dataChannel.onerror = (error) => {
186
- console.error(`DataChannel error with ${peerId}:`, error);
187
- };
188
- dataChannel.onmessage = (event) => {
189
- try {
190
- // Deserialize JSON message
191
- const message = JSON.parse(event.data);
192
- this.messageCallbacks.forEach((callback) => callback(peerId, message));
193
- }
194
- catch (error) {
195
- // Log error but don't interrupt connection
196
- console.error(`Failed to parse message from ${peerId}:`, error);
197
- }
198
- };
256
+ onFileTransferStarted(callback) {
257
+ this.fileTransferStartedCallbacks.add(callback);
199
258
  }
200
- /**
201
- * Send a message to all connected peers
202
- * Throws error if any DataChannel is not ready
203
- */
204
- sendMessage(message) {
205
- const errors = [];
206
- this.dataChannels.forEach((dataChannel, peerId) => {
207
- if (dataChannel.readyState === "open") {
208
- try {
209
- // Serialize message to JSON
210
- const serialized = JSON.stringify(message);
211
- dataChannel.send(serialized);
212
- }
213
- catch (error) {
214
- console.error(`Failed to send message to ${peerId}:`, error);
215
- errors.push(peerId);
216
- }
217
- }
218
- else {
219
- errors.push(peerId);
220
- }
221
- });
222
- if (errors.length > 0) {
223
- throw new Error(`DataChannel not ready for peers: ${errors.join(", ")}`);
224
- }
259
+ onFileTransferProgress(callback) {
260
+ this.fileTransferProgressCallbacks.add(callback);
225
261
  }
226
- /**
227
- * Send a message to a specific peer
228
- * Throws error if DataChannel is not ready
229
- */
230
- sendMessageToPeer(peerId, message) {
231
- const dataChannel = this.dataChannels.get(peerId);
232
- if (!dataChannel) {
233
- throw new Error(`No DataChannel found for ${peerId}`);
234
- }
235
- if (dataChannel.readyState !== "open") {
236
- throw new Error(`DataChannel not ready for ${peerId}, state: ${dataChannel.readyState}`);
237
- }
238
- try {
239
- // Serialize message to JSON
240
- const serialized = JSON.stringify(message);
241
- dataChannel.send(serialized);
242
- }
243
- catch (error) {
244
- console.error(`Failed to send message to ${peerId}:`, error);
245
- throw error;
246
- }
262
+ onFileTransferCompleted(callback) {
263
+ this.fileTransferCompletedCallbacks.add(callback);
264
+ }
265
+ onFileTransferFailed(callback) {
266
+ this.fileTransferFailedCallbacks.add(callback);
267
+ }
268
+ onRemoteAudioTrack(callback) {
269
+ this.remoteAudioTrackCallbacks.add(callback);
270
+ }
271
+ onLocalAudioStateChange(callback) {
272
+ this.localAudioStateCallbacks.add(callback);
247
273
  }
248
274
  /**
249
- * Close the connection with a specific peer
275
+ * Close the connection with a specific peer.
250
276
  */
251
277
  closePeerConnection(peerId) {
252
- const dataChannel = this.dataChannels.get(peerId);
253
- if (dataChannel) {
254
- dataChannel.close();
255
- this.dataChannels.delete(peerId);
256
- }
278
+ this.failActiveTransfers(peerId, new Error(`Peer connection closed for ${peerId}`));
279
+ const channels = this.normalizePeerChannels(this.dataChannels.get(peerId));
280
+ channels?.message?.close();
281
+ channels?.file?.close();
282
+ this.dataChannels.delete(peerId);
257
283
  const pc = this.peerConnections.get(peerId);
258
284
  if (pc) {
259
285
  pc.close();
260
286
  this.peerConnections.delete(peerId);
261
287
  }
262
- // Clean up callbacks
288
+ this.clearReadyResolver(peerId);
289
+ this.clearCompletionResolver(peerId);
290
+ this.outgoingTransfers.delete(peerId);
291
+ this.incomingTransfers.delete(peerId);
292
+ this.audioSenders.delete(peerId);
293
+ this.remoteAudioStreams.delete(peerId);
263
294
  this.connectionStateCallbacks.delete(peerId);
264
295
  this.dataChannelStateCallbacks.delete(peerId);
265
296
  this.iceCandidateCallbacks.delete(peerId);
266
297
  }
267
298
  /**
268
- * Close all connections and clean up resources
299
+ * Close all connections and clean up resources.
269
300
  */
270
301
  closeAll() {
271
- this.dataChannels.forEach((dataChannel) => {
272
- dataChannel.close();
273
- });
274
- this.dataChannels.clear();
275
- this.peerConnections.forEach((pc) => {
276
- pc.close();
302
+ this.getActivePeers().forEach((peerId) => {
303
+ this.closePeerConnection(peerId);
277
304
  });
278
- this.peerConnections.clear();
305
+ this.stopVoice();
306
+ }
307
+ destroy() {
308
+ this.closeAll();
279
309
  this.messageCallbacks.clear();
280
- this.connectionStateCallbacks.clear();
281
- this.dataChannelStateCallbacks.clear();
282
- this.iceCandidateCallbacks.clear();
310
+ this.fileTransferStartedCallbacks.clear();
311
+ this.fileTransferProgressCallbacks.clear();
312
+ this.fileTransferCompletedCallbacks.clear();
313
+ this.fileTransferFailedCallbacks.clear();
314
+ this.remoteAudioTrackCallbacks.clear();
315
+ this.localAudioStateCallbacks.clear();
283
316
  }
284
317
  /**
285
- * Get all active peer IDs
318
+ * Get all active peer IDs.
286
319
  */
287
320
  getActivePeers() {
288
321
  return Array.from(this.peerConnections.keys());
289
322
  }
290
323
  /**
291
- * Check if connected to a specific peer
324
+ * Check if connected to a specific peer.
292
325
  */
293
326
  isConnected(peerId) {
294
327
  const pc = this.peerConnections.get(peerId);
295
328
  return pc?.connectionState === "connected";
296
329
  }
297
330
  /**
298
- * Check if DataChannel is ready for a specific peer
331
+ * Check if the main DataChannel is ready for a specific peer.
299
332
  */
300
333
  isDataChannelReady(peerId) {
301
- const dataChannel = this.dataChannels.get(peerId);
302
- return dataChannel?.readyState === "open";
334
+ return (this.normalizePeerChannels(this.dataChannels.get(peerId)).message
335
+ ?.readyState === "open");
336
+ }
337
+ /**
338
+ * Check if the file channel is ready for a specific peer.
339
+ */
340
+ isFileChannelReady(peerId) {
341
+ return (this.normalizePeerChannels(this.dataChannels.get(peerId)).file
342
+ ?.readyState === "open");
343
+ }
344
+ setupPeerConnection(peerId, pc) {
345
+ pc.onconnectionstatechange = () => {
346
+ const callbacks = this.connectionStateCallbacks.get(peerId);
347
+ callbacks?.forEach((callback) => callback(pc.connectionState));
348
+ if (pc.connectionState === "failed" ||
349
+ pc.connectionState === "closed" ||
350
+ pc.connectionState === "disconnected") {
351
+ this.closePeerConnection(peerId);
352
+ }
353
+ };
354
+ pc.ontrack = (event) => {
355
+ if (event.track.kind !== "audio") {
356
+ return;
357
+ }
358
+ const stream = event.streams[0] ??
359
+ (typeof MediaStream !== "undefined"
360
+ ? new MediaStream([event.track])
361
+ : null);
362
+ this.remoteAudioStreams.set(peerId, stream);
363
+ this.remoteAudioTrackCallbacks.forEach((callback) => callback(peerId, stream, event.track));
364
+ };
365
+ this.audioSenders.set(peerId, this.createAudioSender(pc));
366
+ void this.syncLocalAudioTrack(peerId);
367
+ }
368
+ createAudioSender(pc) {
369
+ const transceiverCapable = pc;
370
+ if (typeof transceiverCapable.addTransceiver === "function") {
371
+ const transceiver = transceiverCapable.addTransceiver("audio", {
372
+ direction: "sendrecv",
373
+ });
374
+ return transceiver.sender;
375
+ }
376
+ return null;
377
+ }
378
+ async syncLocalAudioTrack(peerId) {
379
+ const pc = this.peerConnections.get(peerId);
380
+ if (!pc) {
381
+ return;
382
+ }
383
+ let sender = this.audioSenders.get(peerId) ?? null;
384
+ if (sender && typeof sender.replaceTrack === "function") {
385
+ await sender.replaceTrack(this.localAudioTrack);
386
+ return;
387
+ }
388
+ if (this.localAudioTrack &&
389
+ typeof pc.addTrack === "function") {
390
+ const addTrackCapable = pc;
391
+ const stream = this.localAudioStream ??
392
+ (typeof MediaStream !== "undefined"
393
+ ? new MediaStream([this.localAudioTrack])
394
+ : undefined);
395
+ sender = stream
396
+ ? addTrackCapable.addTrack(this.localAudioTrack, stream)
397
+ : addTrackCapable.addTrack(this.localAudioTrack);
398
+ this.audioSenders.set(peerId, sender);
399
+ }
400
+ }
401
+ ensureDataChannel(peerId, pc, label) {
402
+ const channels = this.dataChannels.get(peerId) ?? {};
403
+ const kind = label === FILE_CHANNEL_LABEL ? "file" : "message";
404
+ const existing = channels[kind];
405
+ if (existing) {
406
+ return existing;
407
+ }
408
+ const channel = pc.createDataChannel(label);
409
+ this.setupDataChannel(peerId, channel);
410
+ return channel;
411
+ }
412
+ setupDataChannel(peerId, dataChannel) {
413
+ const kind = dataChannel.label === FILE_CHANNEL_LABEL ? "file" : "message";
414
+ const channels = this.normalizePeerChannels(this.dataChannels.get(peerId));
415
+ channels[kind] = dataChannel;
416
+ this.dataChannels.set(peerId, channels);
417
+ if (kind === "file") {
418
+ dataChannel.binaryType = "arraybuffer";
419
+ }
420
+ dataChannel.onopen = () => {
421
+ if (kind !== "message") {
422
+ return;
423
+ }
424
+ const callbacks = this.dataChannelStateCallbacks.get(peerId);
425
+ callbacks?.forEach((callback) => callback(dataChannel.readyState));
426
+ };
427
+ dataChannel.onclose = () => {
428
+ if (kind === "message") {
429
+ const callbacks = this.dataChannelStateCallbacks.get(peerId);
430
+ callbacks?.forEach((callback) => callback(dataChannel.readyState));
431
+ }
432
+ const storedChannels = this.dataChannels.get(peerId);
433
+ if (storedChannels && this.isPeerChannels(storedChannels) && storedChannels[kind] === dataChannel) {
434
+ delete storedChannels[kind];
435
+ if (!storedChannels.message && !storedChannels.file) {
436
+ this.dataChannels.delete(peerId);
437
+ }
438
+ }
439
+ if (kind === "message" || kind === "file") {
440
+ this.failActiveTransfers(peerId, new Error(`${kind} channel closed during file transfer`));
441
+ }
442
+ };
443
+ dataChannel.onerror = (error) => {
444
+ console.error(`DataChannel error with ${peerId}:`, error);
445
+ const transfer = kind === "file"
446
+ ? this.outgoingTransfers.get(peerId) ?? this.incomingTransfers.get(peerId) ?? null
447
+ : null;
448
+ if (transfer) {
449
+ this.emitFileTransferFailed(peerId, transfer, new Error(`DataChannel error on ${kind} channel`));
450
+ }
451
+ };
452
+ dataChannel.onmessage = (event) => {
453
+ if (kind === "file") {
454
+ this.handleFileChunk(peerId, event.data);
455
+ return;
456
+ }
457
+ this.handleMessageChannelMessage(peerId, event.data);
458
+ };
459
+ }
460
+ handleMessageChannelMessage(peerId, rawData) {
461
+ try {
462
+ const message = JSON.parse(rawData);
463
+ if (this.isFileControlMessage(message)) {
464
+ this.handleFileControlMessage(peerId, message);
465
+ return;
466
+ }
467
+ this.messageCallbacks.forEach((callback) => callback(peerId, message));
468
+ }
469
+ catch (error) {
470
+ console.error(`Failed to parse message from ${peerId}:`, error);
471
+ }
472
+ }
473
+ async sendFileToPeer(peerId, blob, options) {
474
+ const messageChannel = this.getMessageChannel(peerId);
475
+ const fileChannel = this.getFileChannel(peerId);
476
+ if (messageChannel.readyState !== "open") {
477
+ throw new Error(`DataChannel not ready for ${peerId}`);
478
+ }
479
+ if (fileChannel.readyState !== "open") {
480
+ throw new Error(`File channel not ready for ${peerId}`);
481
+ }
482
+ if (this.outgoingTransfers.has(peerId)) {
483
+ throw new Error(`A file transfer is already active for ${peerId}`);
484
+ }
485
+ const transfer = {
486
+ transferId: this.generateTransferId(),
487
+ peerId,
488
+ direction: "send",
489
+ name: options.fileName || this.getBlobName(blob),
490
+ size: blob.size,
491
+ mimeType: options.mimeType || blob.type || "application/octet-stream",
492
+ lastModified: options.lastModified ?? this.getBlobLastModified(blob) ?? Date.now(),
493
+ blob,
494
+ chunkSize: options.chunkSize ?? this.fileChunkSize,
495
+ };
496
+ transfer.chunkSize = this.validateChunkSize(transfer.chunkSize);
497
+ this.outgoingTransfers.set(peerId, transfer);
498
+ this.emitFileTransferStarted(peerId, transfer);
499
+ this.emitFileTransferProgress(peerId, transfer, 0);
500
+ try {
501
+ const readyPromise = this.awaitTransferReady(peerId, transfer.transferId);
502
+ this.sendFileControl(peerId, {
503
+ __aves: FILE_PROTOCOL,
504
+ kind: "file-meta",
505
+ transfer: {
506
+ transferId: transfer.transferId,
507
+ name: transfer.name,
508
+ size: transfer.size,
509
+ mimeType: transfer.mimeType,
510
+ lastModified: transfer.lastModified,
511
+ },
512
+ });
513
+ await readyPromise;
514
+ let offset = 0;
515
+ while (offset < transfer.size) {
516
+ const nextChunk = transfer.blob.slice(offset, offset + transfer.chunkSize);
517
+ const buffer = await nextChunk.arrayBuffer();
518
+ fileChannel.send(buffer);
519
+ offset += buffer.byteLength;
520
+ this.emitFileTransferProgress(peerId, transfer, offset);
521
+ }
522
+ const completionPromise = this.awaitTransferCompletion(peerId, transfer.transferId);
523
+ fileChannel.send(`${FILE_END_MARKER_PREFIX}${transfer.transferId}`);
524
+ await completionPromise;
525
+ const result = {
526
+ ...transfer,
527
+ };
528
+ this.fileTransferCompletedCallbacks.forEach((callback) => callback(peerId, result));
529
+ return transfer;
530
+ }
531
+ catch (error) {
532
+ const transferError = error instanceof Error ? error : new Error("File transfer failed");
533
+ this.sendFileControl(peerId, {
534
+ __aves: FILE_PROTOCOL,
535
+ kind: "file-error",
536
+ transferId: transfer.transferId,
537
+ message: transferError.message,
538
+ });
539
+ this.emitFileTransferFailed(peerId, transfer, transferError);
540
+ throw transferError;
541
+ }
542
+ finally {
543
+ this.clearReadyResolver(peerId);
544
+ this.clearCompletionResolver(peerId);
545
+ this.outgoingTransfers.delete(peerId);
546
+ }
547
+ }
548
+ handleFileControlMessage(peerId, message) {
549
+ switch (message.kind) {
550
+ case "file-meta": {
551
+ const transfer = {
552
+ transferId: message.transfer.transferId,
553
+ peerId,
554
+ direction: "receive",
555
+ name: message.transfer.name,
556
+ size: message.transfer.size,
557
+ mimeType: message.transfer.mimeType,
558
+ lastModified: message.transfer.lastModified,
559
+ chunks: [],
560
+ bytesTransferred: 0,
561
+ };
562
+ this.incomingTransfers.set(peerId, transfer);
563
+ this.emitFileTransferStarted(peerId, transfer);
564
+ this.emitFileTransferProgress(peerId, transfer, 0);
565
+ this.sendFileControl(peerId, {
566
+ __aves: FILE_PROTOCOL,
567
+ kind: "file-ready",
568
+ transferId: transfer.transferId,
569
+ });
570
+ break;
571
+ }
572
+ case "file-ready": {
573
+ const resolver = this.readyResolvers.get(peerId);
574
+ if (resolver && resolver.transferId === message.transferId) {
575
+ clearTimeout(resolver.timeoutId);
576
+ this.readyResolvers.delete(peerId);
577
+ resolver.resolve();
578
+ }
579
+ break;
580
+ }
581
+ case "file-complete": {
582
+ const resolver = this.completionResolvers.get(peerId);
583
+ if (resolver && resolver.transferId === message.transferId) {
584
+ clearTimeout(resolver.timeoutId);
585
+ this.completionResolvers.delete(peerId);
586
+ resolver.resolve();
587
+ return;
588
+ }
589
+ break;
590
+ }
591
+ case "file-error": {
592
+ const transfer = this.outgoingTransfers.get(peerId) ??
593
+ this.incomingTransfers.get(peerId) ??
594
+ null;
595
+ this.emitFileTransferFailed(peerId, transfer, new Error(message.message));
596
+ this.outgoingTransfers.delete(peerId);
597
+ this.incomingTransfers.delete(peerId);
598
+ this.clearReadyResolver(peerId);
599
+ this.clearCompletionResolver(peerId);
600
+ break;
601
+ }
602
+ }
603
+ }
604
+ handleFileChunk(peerId, data) {
605
+ const transfer = this.incomingTransfers.get(peerId);
606
+ if (!transfer) {
607
+ return;
608
+ }
609
+ if (typeof data === "string" &&
610
+ data === `${FILE_END_MARKER_PREFIX}${transfer.transferId}`) {
611
+ const result = {
612
+ transferId: transfer.transferId,
613
+ peerId,
614
+ direction: "receive",
615
+ name: transfer.name,
616
+ size: transfer.size,
617
+ mimeType: transfer.mimeType,
618
+ lastModified: transfer.lastModified,
619
+ blob: new Blob(transfer.chunks, { type: transfer.mimeType }),
620
+ };
621
+ this.fileTransferCompletedCallbacks.forEach((callback) => callback(peerId, result));
622
+ this.sendFileControl(peerId, {
623
+ __aves: FILE_PROTOCOL,
624
+ kind: "file-complete",
625
+ transferId: transfer.transferId,
626
+ });
627
+ this.incomingTransfers.delete(peerId);
628
+ return;
629
+ }
630
+ transfer.chunks.push(data);
631
+ transfer.bytesTransferred += this.getChunkSize(data);
632
+ this.emitFileTransferProgress(peerId, transfer, transfer.bytesTransferred);
633
+ }
634
+ emitFileTransferStarted(peerId, info) {
635
+ this.fileTransferStartedCallbacks.forEach((callback) => callback(peerId, info));
636
+ }
637
+ emitFileTransferProgress(peerId, info, bytesTransferred) {
638
+ const progress = {
639
+ ...info,
640
+ bytesTransferred: Math.min(bytesTransferred, info.size),
641
+ progress: info.size === 0
642
+ ? 100
643
+ : Math.min(100, (bytesTransferred / info.size) * 100),
644
+ };
645
+ this.fileTransferProgressCallbacks.forEach((callback) => callback(peerId, progress));
646
+ }
647
+ emitFileTransferFailed(peerId, info, error) {
648
+ this.fileTransferFailedCallbacks.forEach((callback) => callback(peerId, info, error));
649
+ }
650
+ emitLocalAudioState() {
651
+ const state = this.getLocalAudioState();
652
+ this.localAudioStateCallbacks.forEach((callback) => callback(state));
653
+ }
654
+ sendFileControl(peerId, message) {
655
+ const dataChannel = this.getMessageChannel(peerId);
656
+ dataChannel.send(JSON.stringify(message));
657
+ }
658
+ awaitTransferReady(peerId, transferId) {
659
+ return new Promise((resolve, reject) => {
660
+ const timeoutId = setTimeout(() => {
661
+ this.readyResolvers.delete(peerId);
662
+ reject(new Error("Timed out waiting for file receiver readiness"));
663
+ }, FILE_READY_TIMEOUT_MS);
664
+ this.readyResolvers.set(peerId, {
665
+ transferId,
666
+ resolve,
667
+ reject,
668
+ timeoutId,
669
+ });
670
+ });
671
+ }
672
+ clearReadyResolver(peerId) {
673
+ const resolver = this.readyResolvers.get(peerId);
674
+ if (!resolver) {
675
+ return;
676
+ }
677
+ clearTimeout(resolver.timeoutId);
678
+ this.readyResolvers.delete(peerId);
679
+ }
680
+ awaitTransferCompletion(peerId, transferId) {
681
+ return new Promise((resolve, reject) => {
682
+ const timeoutId = setTimeout(() => {
683
+ this.completionResolvers.delete(peerId);
684
+ reject(new Error("Timed out waiting for file receiver confirmation"));
685
+ }, FILE_COMPLETE_TIMEOUT_MS);
686
+ this.completionResolvers.set(peerId, {
687
+ transferId,
688
+ resolve,
689
+ reject,
690
+ timeoutId,
691
+ });
692
+ });
693
+ }
694
+ clearCompletionResolver(peerId) {
695
+ const resolver = this.completionResolvers.get(peerId);
696
+ if (!resolver) {
697
+ return;
698
+ }
699
+ clearTimeout(resolver.timeoutId);
700
+ this.completionResolvers.delete(peerId);
701
+ }
702
+ getPeerConnection(peerId) {
703
+ const pc = this.peerConnections.get(peerId);
704
+ if (!pc) {
705
+ throw new Error(`No peer connection found for ${peerId}`);
706
+ }
707
+ return pc;
708
+ }
709
+ getMessageChannel(peerId) {
710
+ const channel = this.normalizePeerChannels(this.dataChannels.get(peerId)).message;
711
+ if (!channel) {
712
+ throw new Error(`No DataChannel found for ${peerId}`);
713
+ }
714
+ return channel;
715
+ }
716
+ getFileChannel(peerId) {
717
+ const channel = this.normalizePeerChannels(this.dataChannels.get(peerId)).file;
718
+ if (!channel) {
719
+ throw new Error(`No file channel found for ${peerId}`);
720
+ }
721
+ return channel;
722
+ }
723
+ isFileControlMessage(message) {
724
+ if (!message || typeof message !== "object") {
725
+ return false;
726
+ }
727
+ const record = message;
728
+ return record.__aves === FILE_PROTOCOL && typeof record.kind === "string";
729
+ }
730
+ getChunkSize(data) {
731
+ if (typeof data === "string") {
732
+ return data.length;
733
+ }
734
+ if (data instanceof ArrayBuffer) {
735
+ return data.byteLength;
736
+ }
737
+ return data.size;
738
+ }
739
+ getBlobName(blob) {
740
+ const fileBlob = blob;
741
+ return fileBlob.name || "shared-file";
742
+ }
743
+ getBlobLastModified(blob) {
744
+ const fileBlob = blob;
745
+ return typeof fileBlob.lastModified === "number"
746
+ ? fileBlob.lastModified
747
+ : undefined;
748
+ }
749
+ generateTransferId() {
750
+ return `file-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
751
+ }
752
+ validateChunkSize(chunkSize) {
753
+ if (!Number.isInteger(chunkSize) || chunkSize <= 0) {
754
+ throw new Error("chunkSize must be a positive integer");
755
+ }
756
+ return chunkSize;
757
+ }
758
+ failActiveTransfers(peerId, error) {
759
+ const outgoingTransfer = this.outgoingTransfers.get(peerId) ?? null;
760
+ const incomingTransfer = this.incomingTransfers.get(peerId) ?? null;
761
+ if (outgoingTransfer) {
762
+ this.emitFileTransferFailed(peerId, outgoingTransfer, error);
763
+ }
764
+ if (incomingTransfer) {
765
+ this.emitFileTransferFailed(peerId, incomingTransfer, error);
766
+ }
767
+ const readyResolver = this.readyResolvers.get(peerId);
768
+ if (readyResolver) {
769
+ readyResolver.reject(error);
770
+ this.clearReadyResolver(peerId);
771
+ }
772
+ const completionResolver = this.completionResolvers.get(peerId);
773
+ if (completionResolver) {
774
+ completionResolver.reject(error);
775
+ this.clearCompletionResolver(peerId);
776
+ }
777
+ this.outgoingTransfers.delete(peerId);
778
+ this.incomingTransfers.delete(peerId);
779
+ }
780
+ normalizePeerChannels(channels) {
781
+ if (!channels) {
782
+ return {};
783
+ }
784
+ if (this.isPeerChannels(channels)) {
785
+ return channels;
786
+ }
787
+ return {
788
+ message: channels,
789
+ };
790
+ }
791
+ isPeerChannels(value) {
792
+ return !("readyState" in value);
303
793
  }
304
794
  }