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