@webrtc-node/webrtc 0.2.1

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/lib/index.js ADDED
@@ -0,0 +1,4910 @@
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
4
+ const native = require("./load-native");
5
+
6
+ const kHandlers = new WeakMap();
7
+ const certificateMaterial = new WeakMap();
8
+ const localDescriptionOwners = new Map();
9
+ const localDescriptionOwnerFinalizer = new FinalizationRegistry((key) => {
10
+ if (!localDescriptionOwners.get(key)?.deref()) localDescriptionOwners.delete(key);
11
+ });
12
+ const iceUdpMuxListenerFinalizer = new FinalizationRegistry((nativeListenerRef) => {
13
+ nativeListenerRef.deref()?.close();
14
+ });
15
+ const kInternalConstruct = Symbol("internalConstruct");
16
+
17
+ function descriptionPairingKey(description) {
18
+ if (!description || typeof description.sdp !== "string" || !description.sdp) return null;
19
+ return `${description.type}\n${description.sdp}`;
20
+ }
21
+
22
+ class SimpleEvent {
23
+ constructor(type, init = {}) {
24
+ this.type = String(type);
25
+ this.bubbles = Boolean(init.bubbles);
26
+ this.cancelable = Boolean(init.cancelable);
27
+ this.defaultPrevented = false;
28
+ this.target = null;
29
+ this.currentTarget = null;
30
+ }
31
+
32
+ preventDefault() {
33
+ if (this.cancelable) this.defaultPrevented = true;
34
+ }
35
+ }
36
+
37
+ class SimpleMessageEvent extends SimpleEvent {
38
+ constructor(type, init = {}) {
39
+ super(type, init);
40
+ this.data = init.data;
41
+ this.origin = init.origin || "";
42
+ this.lastEventId = init.lastEventId || "";
43
+ this.source = init.source || null;
44
+ this.ports = init.ports || [];
45
+ }
46
+ }
47
+
48
+ class SimpleEventTarget {
49
+ addEventListener(type, callback, options = undefined) {
50
+ if (callback == null) return;
51
+ let map = kHandlers.get(this);
52
+ if (!map) {
53
+ map = new Map();
54
+ kHandlers.set(this, map);
55
+ }
56
+ const key = String(type);
57
+ let listeners = map.get(key);
58
+ if (!listeners) {
59
+ listeners = [];
60
+ map.set(key, listeners);
61
+ }
62
+ const once = typeof options === "object" && options !== null && Boolean(options.once);
63
+ let added = false;
64
+ if (!listeners.some((listener) => listener.callback === callback)) {
65
+ listeners.push({ callback, once });
66
+ added = true;
67
+ }
68
+ if (added && typeof this._eventListenerAdded === "function") this._eventListenerAdded(key);
69
+ }
70
+
71
+ removeEventListener(type, callback) {
72
+ const key = String(type);
73
+ const listeners = kHandlers.get(this)?.get(key);
74
+ if (!listeners) return;
75
+ const index = listeners.findIndex((listener) => listener.callback === callback);
76
+ if (index !== -1) {
77
+ listeners.splice(index, 1);
78
+ if (typeof this._eventListenerRemoved === "function") this._eventListenerRemoved(key);
79
+ }
80
+ }
81
+
82
+ dispatchEvent(event) {
83
+ if (!event || typeof event.type !== "string") {
84
+ throw new TypeError("dispatchEvent requires an Event object");
85
+ }
86
+ event.target = event.target || this;
87
+ event.currentTarget = this;
88
+ const registeredListeners = kHandlers.get(this)?.get(event.type);
89
+ const listeners = registeredListeners?.length ? Array.from(registeredListeners) : null;
90
+ const handler = this[`on${event.type}`];
91
+ if (listeners) {
92
+ for (const listener of listeners) {
93
+ if (listener.once) this.removeEventListener(event.type, listener.callback);
94
+ callListener(listener.callback, this, event);
95
+ }
96
+ }
97
+ if (typeof handler === "function") callListener(handler, this, event);
98
+ return !event.defaultPrevented;
99
+ }
100
+
101
+ _hasEventConsumer(type) {
102
+ const listeners = kHandlers.get(this)?.get(String(type));
103
+ return Boolean((listeners && listeners.length > 0) || typeof this[`on${type}`] === "function");
104
+ }
105
+ }
106
+
107
+ function callListener(listener, target, event) {
108
+ if (typeof listener === "function") {
109
+ listener.call(target, event);
110
+ } else if (listener && typeof listener.handleEvent === "function") {
111
+ listener.handleEvent(event);
112
+ }
113
+ }
114
+
115
+ function makeEvent(type, init) {
116
+ return new SimpleEvent(type, init);
117
+ }
118
+
119
+ function makeMessageEvent(type, init) {
120
+ return new SimpleMessageEvent(type, init);
121
+ }
122
+
123
+ function makeDOMException(message, name) {
124
+ if (typeof globalThis.DOMException === "function") {
125
+ return new globalThis.DOMException(message, name);
126
+ }
127
+ const error = new Error(message);
128
+ error.name = name;
129
+ return error;
130
+ }
131
+
132
+ function mapNativeError(error, fallbackName = "OperationError") {
133
+ if (error?.name && error.name !== "Error") return error;
134
+ return makeDOMException(error?.message || String(error), fallbackName);
135
+ }
136
+
137
+ function byteLength(value) {
138
+ return Buffer.byteLength(String(value), "utf8");
139
+ }
140
+
141
+ function enforceRange(value, name, max = 65535) {
142
+ const number = Number(value);
143
+ if (!Number.isInteger(number) || number < 0 || number > max) {
144
+ throw new TypeError(`${name} must be an integer between 0 and ${max}`);
145
+ }
146
+ return number;
147
+ }
148
+
149
+ function toUnsignedLong(value) {
150
+ if (typeof value === "bigint" || Object.prototype.toString.call(value) === "[object BigInt]") {
151
+ throw new TypeError("Cannot convert BigInt to unsigned long");
152
+ }
153
+ const number = Number(value);
154
+ if (!Number.isFinite(number) || number === 0) return 0;
155
+ const integer = Math.trunc(number);
156
+ const modulo = 2 ** 32;
157
+ return ((integer % modulo) + modulo) % modulo;
158
+ }
159
+
160
+ function validateByteLength(value, name) {
161
+ if (byteLength(value) > 65535) {
162
+ throw new TypeError(`${name} exceeds 65535 bytes`);
163
+ }
164
+ }
165
+
166
+ function fingerprintFromBytes(bytes) {
167
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(":");
168
+ }
169
+
170
+ class RTCCertificate {
171
+ constructor({
172
+ expires,
173
+ algorithm = "ECDSA",
174
+ fingerprints,
175
+ certificatePem = null,
176
+ keyPem = null,
177
+ } = {}) {
178
+ this.expires = expires;
179
+ this._algorithm = algorithm;
180
+ this._fingerprints =
181
+ Array.isArray(fingerprints) && fingerprints.length
182
+ ? fingerprints.map((fingerprint) => ({
183
+ algorithm: String(fingerprint.algorithm),
184
+ value: String(fingerprint.value).toLowerCase(),
185
+ }))
186
+ : [
187
+ {
188
+ algorithm: "sha-256",
189
+ value: fingerprintFromBytes(crypto.randomBytes(32)),
190
+ },
191
+ ];
192
+ if (typeof certificatePem === "string" && typeof keyPem === "string") {
193
+ certificateMaterial.set(this, { certificatePem, keyPem });
194
+ }
195
+ }
196
+
197
+ getFingerprints() {
198
+ return this._fingerprints.map((fingerprint) => ({ ...fingerprint }));
199
+ }
200
+ }
201
+
202
+ function getCertificateMaterial(certificate) {
203
+ return certificate instanceof RTCCertificate ? certificateMaterial.get(certificate) : undefined;
204
+ }
205
+
206
+ function normalizeEnum(value, name, allowed, defaultValue) {
207
+ if (value === undefined) return defaultValue;
208
+ if (value === null || !allowed.includes(value)) {
209
+ throw new TypeError(`${name} must be one of: ${allowed.join(", ")}`);
210
+ }
211
+ return value;
212
+ }
213
+
214
+ function validateIceServerUrl(url) {
215
+ if (typeof url !== "string") throw new TypeError("RTCIceServer.urls must contain strings");
216
+ const match = /^([a-z][a-z0-9+.-]*):(.*)$/i.exec(url);
217
+ if (!match) throw makeDOMException("Invalid ICE server URL", "SyntaxError");
218
+ const scheme = match[1].toLowerCase();
219
+ const rest = match[2];
220
+ if (!["stun", "stuns", "turn", "turns"].includes(scheme)) {
221
+ throw makeDOMException("Unsupported ICE server URL scheme", "SyntaxError");
222
+ }
223
+ if (!rest || rest.startsWith("//") || /[/\\#@]/.test(rest)) {
224
+ throw makeDOMException("Invalid ICE server URL", "SyntaxError");
225
+ }
226
+
227
+ const [hostPort, query = ""] = rest.split("?");
228
+ if (rest.split("?").length > 2 || !hostPort) {
229
+ throw makeDOMException("Invalid ICE server URL", "SyntaxError");
230
+ }
231
+ if ((scheme === "stun" || scheme === "stuns") && query) {
232
+ throw makeDOMException("STUN URL must not contain a query", "SyntaxError");
233
+ }
234
+ if ((scheme === "turn" || scheme === "turns") && query && !/^transport=(udp|tcp)$/i.test(query)) {
235
+ throw makeDOMException("Invalid TURN transport", "SyntaxError");
236
+ }
237
+
238
+ let host = hostPort;
239
+ let port = "";
240
+ if (hostPort.startsWith("[")) {
241
+ const end = hostPort.indexOf("]");
242
+ if (end <= 1) throw makeDOMException("Invalid ICE server host", "SyntaxError");
243
+ host = hostPort.slice(1, end);
244
+ const suffix = hostPort.slice(end + 1);
245
+ if (suffix) {
246
+ if (!suffix.startsWith(":")) throw makeDOMException("Invalid ICE server port", "SyntaxError");
247
+ port = suffix.slice(1);
248
+ }
249
+ } else {
250
+ const colonCount = (hostPort.match(/:/g) || []).length;
251
+ if (colonCount > 1) throw makeDOMException("Invalid ICE server host", "SyntaxError");
252
+ if (colonCount === 1) {
253
+ const index = hostPort.lastIndexOf(":");
254
+ host = hostPort.slice(0, index);
255
+ port = hostPort.slice(index + 1);
256
+ }
257
+ }
258
+ if (!host) throw makeDOMException("Invalid ICE server host", "SyntaxError");
259
+ if (port !== "") {
260
+ const number = Number(port);
261
+ if (!/^\d+$/.test(port) || !Number.isInteger(number) || number < 0 || number > 65535) {
262
+ throw makeDOMException("Invalid ICE server port", "SyntaxError");
263
+ }
264
+ }
265
+ }
266
+
267
+ function normalizeIceServers(iceServers) {
268
+ if (iceServers === undefined) return [];
269
+ if (!Array.isArray(iceServers)) throw new TypeError("iceServers must be an array");
270
+ return iceServers.map((server) => {
271
+ if (server === null || typeof server !== "object")
272
+ throw new TypeError("RTCIceServer must be an object");
273
+ if (!Object.hasOwn(server, "urls")) {
274
+ throw new TypeError("RTCIceServer.urls is required");
275
+ }
276
+ const urls = Array.isArray(server.urls) ? server.urls.map(String) : [String(server.urls)];
277
+ if (urls.length === 0)
278
+ throw makeDOMException("RTCIceServer.urls must not be empty", "SyntaxError");
279
+ for (const url of urls) validateIceServerUrl(url);
280
+
281
+ const requiresCredentials = urls.some((url) => /^turns?:/i.test(url));
282
+ const username = server.username === undefined ? undefined : String(server.username);
283
+ const credential = server.credential === undefined ? undefined : String(server.credential);
284
+ if (requiresCredentials) {
285
+ if (username === undefined || credential === undefined || credential === "") {
286
+ throw makeDOMException(
287
+ "TURN servers require username and credential",
288
+ "InvalidAccessError",
289
+ );
290
+ }
291
+ if (byteLength(username) > 509) {
292
+ throw makeDOMException("TURN username exceeds 509 bytes", "InvalidAccessError");
293
+ }
294
+ }
295
+
296
+ const normalized = { urls };
297
+ if (username !== undefined) normalized.username = username;
298
+ if (credential !== undefined) normalized.credential = credential;
299
+ return normalized;
300
+ });
301
+ }
302
+
303
+ function normalizePeerConnectionConfiguration(configuration) {
304
+ if (configuration == null) configuration = {};
305
+ if (typeof configuration !== "object") configuration = {};
306
+ if (configuration.certificates === null) {
307
+ throw new TypeError("certificates must not be null");
308
+ }
309
+ const certificates =
310
+ configuration.certificates === undefined ? [] : Array.from(configuration.certificates);
311
+ for (const certificate of certificates) {
312
+ if (certificate == null) throw new TypeError("certificates must not contain null or undefined");
313
+ if (certificate instanceof RTCCertificate && certificate.expires <= Date.now()) {
314
+ throw makeDOMException("RTCCertificate has expired", "InvalidAccessError");
315
+ }
316
+ }
317
+ return {
318
+ iceServers: normalizeIceServers(configuration.iceServers),
319
+ iceTransportPolicy: normalizeEnum(
320
+ configuration.iceTransportPolicy,
321
+ "iceTransportPolicy",
322
+ ["all", "relay"],
323
+ "all",
324
+ ),
325
+ bundlePolicy: normalizeEnum(
326
+ configuration.bundlePolicy,
327
+ "bundlePolicy",
328
+ ["balanced", "max-compat", "max-bundle"],
329
+ "balanced",
330
+ ),
331
+ rtcpMuxPolicy: normalizeEnum(
332
+ configuration.rtcpMuxPolicy,
333
+ "rtcpMuxPolicy",
334
+ ["require"],
335
+ "require",
336
+ ),
337
+ iceCandidatePoolSize:
338
+ configuration.iceCandidatePoolSize === undefined
339
+ ? 0
340
+ : enforceRange(configuration.iceCandidatePoolSize, "iceCandidatePoolSize", 255),
341
+ certificates,
342
+ };
343
+ }
344
+
345
+ function cloneConfiguration(configuration) {
346
+ return {
347
+ iceServers: configuration.iceServers.map((server) => ({ ...server, urls: [...server.urls] })),
348
+ iceTransportPolicy: configuration.iceTransportPolicy,
349
+ bundlePolicy: configuration.bundlePolicy,
350
+ rtcpMuxPolicy: configuration.rtcpMuxPolicy,
351
+ iceCandidatePoolSize: configuration.iceCandidatePoolSize,
352
+ certificates: [...configuration.certificates],
353
+ };
354
+ }
355
+
356
+ function sameCertificateSet(left, right) {
357
+ if (left.length !== right.length) return false;
358
+ return left.every((certificate, index) => certificate === right[index]);
359
+ }
360
+
361
+ function normalizeCertificateExpiration(value) {
362
+ if (value === undefined) return Date.now() + 30 * 24 * 60 * 60 * 1000;
363
+ const number = Number(value);
364
+ if (!Number.isFinite(number) || !Number.isInteger(number) || number < 0) {
365
+ throw new TypeError("expires must be a non-negative integer");
366
+ }
367
+ return Date.now() + number;
368
+ }
369
+
370
+ function normalizeCertificateAlgorithm(algorithm) {
371
+ if (typeof algorithm === "string") {
372
+ throw makeDOMException("Unsupported certificate algorithm", "NotSupportedError");
373
+ }
374
+ if (algorithm === null || typeof algorithm !== "object") {
375
+ throw makeDOMException("Unsupported certificate algorithm", "NotSupportedError");
376
+ }
377
+ const name = String(algorithm.name || "").toUpperCase();
378
+ if (name === "ECDSA") {
379
+ if (String(algorithm.namedCurve || "").toUpperCase() !== "P-256") {
380
+ throw makeDOMException("Unsupported ECDSA curve", "NotSupportedError");
381
+ }
382
+ return { name: "ECDSA" };
383
+ }
384
+ if (name === "RSASSA-PKCS1-V1_5") {
385
+ const hash =
386
+ typeof algorithm.hash === "object" && algorithm.hash !== null
387
+ ? String(algorithm.hash.name || "")
388
+ : String(algorithm.hash || "");
389
+ if (hash.toUpperCase() !== "SHA-256") {
390
+ throw makeDOMException("Unsupported RSA hash", "NotSupportedError");
391
+ }
392
+ const modulusLength = Number(algorithm.modulusLength);
393
+ if (!Number.isInteger(modulusLength) || modulusLength < 1024) {
394
+ throw makeDOMException("Unsupported RSA modulus length", "NotSupportedError");
395
+ }
396
+ return { name: "RSASSA-PKCS1-v1_5", modulusLength };
397
+ }
398
+ throw makeDOMException("Unsupported certificate algorithm", "NotSupportedError");
399
+ }
400
+
401
+ function createNativeBackedCertificate({ normalizedAlgorithm, expires, expiresMs }) {
402
+ const material = native.generateCertificate({
403
+ algorithm: normalizedAlgorithm.name,
404
+ modulusLength: normalizedAlgorithm.modulusLength,
405
+ expiresMs,
406
+ });
407
+ return new RTCCertificate({
408
+ expires,
409
+ algorithm: normalizedAlgorithm.name,
410
+ fingerprints: material.fingerprints,
411
+ certificatePem: material.certificatePem,
412
+ keyPem: material.keyPem,
413
+ });
414
+ }
415
+
416
+ function importCertificate({ certificatePem, privateKeyPem, expires } = {}) {
417
+ if (typeof certificatePem !== "string" || certificatePem.length === 0) {
418
+ throw new TypeError("certificatePem must be a non-empty string");
419
+ }
420
+ if (typeof privateKeyPem !== "string" || privateKeyPem.length === 0) {
421
+ throw new TypeError("privateKeyPem must be a non-empty string");
422
+ }
423
+ if (
424
+ expires !== undefined &&
425
+ (!Number.isFinite(Number(expires)) || !Number.isInteger(Number(expires)) || Number(expires) < 0)
426
+ ) {
427
+ throw new TypeError("expires must be a non-negative integer timestamp");
428
+ }
429
+
430
+ let material;
431
+ try {
432
+ material = native.importCertificate({ certificatePem, keyPem: privateKeyPem });
433
+ } catch (error) {
434
+ throw new TypeError(`Invalid certificate material: ${error?.message || String(error)}`);
435
+ }
436
+ const effectiveExpires =
437
+ expires === undefined ? material.expires : Math.min(Number(expires), material.expires);
438
+ return new RTCCertificate({
439
+ expires: effectiveExpires,
440
+ algorithm: "imported",
441
+ fingerprints: material.fingerprints,
442
+ certificatePem: material.certificatePem,
443
+ keyPem: material.keyPem,
444
+ });
445
+ }
446
+
447
+ function createDefaultNativeCertificate() {
448
+ const expiresMs = 30 * 24 * 60 * 60 * 1000;
449
+ return createNativeBackedCertificate({
450
+ normalizedAlgorithm: { name: "ECDSA" },
451
+ expires: Date.now() + expiresMs,
452
+ expiresMs,
453
+ });
454
+ }
455
+
456
+ function certificatePemToArrayBuffer(pem) {
457
+ const raw = new crypto.X509Certificate(pem).raw;
458
+ return raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength);
459
+ }
460
+
461
+ function generateCertificate(algorithm) {
462
+ try {
463
+ const normalizedAlgorithm = normalizeCertificateAlgorithm(algorithm);
464
+ const expiresInput = algorithm && typeof algorithm === "object" ? algorithm.expires : undefined;
465
+ const expires = normalizeCertificateExpiration(expiresInput);
466
+ const expiresMs = expiresInput === undefined ? 30 * 24 * 60 * 60 * 1000 : Number(expiresInput);
467
+ return Promise.resolve(
468
+ createNativeBackedCertificate({ normalizedAlgorithm, expires, expiresMs }),
469
+ );
470
+ } catch (error) {
471
+ return Promise.reject(error);
472
+ }
473
+ }
474
+
475
+ class IceUdpMuxListener {
476
+ constructor(port, address = undefined) {
477
+ this._port = enforceRange(port, "port");
478
+ if (address !== undefined && typeof address !== "string") {
479
+ throw new TypeError("address must be a string");
480
+ }
481
+ this._address = address;
482
+ this._callback = null;
483
+ this._closed = false;
484
+ const weakListener = new WeakRef(this);
485
+ this._native = new native.NativeIceUdpMuxListener(
486
+ this._port,
487
+ (request) => {
488
+ const listener = weakListener.deref();
489
+ if (!listener || listener._closed || typeof listener._callback !== "function") return;
490
+ listener._callback(request);
491
+ },
492
+ this._address,
493
+ );
494
+ iceUdpMuxListenerFinalizer.register(this, new WeakRef(this._native), this);
495
+ }
496
+
497
+ port() {
498
+ return this._port;
499
+ }
500
+
501
+ address() {
502
+ return this._address;
503
+ }
504
+
505
+ onUnhandledStunRequest(callback) {
506
+ if (this._closed) {
507
+ throw makeDOMException("IceUdpMuxListener is closed", "InvalidStateError");
508
+ }
509
+ if (typeof callback !== "function") {
510
+ throw new TypeError("onUnhandledStunRequest requires a function");
511
+ }
512
+ this._callback = callback;
513
+ }
514
+
515
+ close() {
516
+ if (this._closed) return;
517
+ this._closed = true;
518
+ this._callback = null;
519
+ iceUdpMuxListenerFinalizer.unregister(this);
520
+ this._native?.close();
521
+ this._native = null;
522
+ }
523
+
524
+ stop() {
525
+ this.close();
526
+ }
527
+ }
528
+
529
+ function assertPeerConnection(peerConnection) {
530
+ if (!(peerConnection instanceof RTCPeerConnection)) {
531
+ throw new TypeError("Expected an RTCPeerConnection");
532
+ }
533
+ }
534
+
535
+ function configurePeerConnection(peerConnection, options = {}) {
536
+ assertPeerConnection(peerConnection);
537
+ peerConnection._assertNotClosed();
538
+ if (peerConnection._native) {
539
+ throw makeDOMException(
540
+ "Peer connection native configuration is already initialized",
541
+ "InvalidStateError",
542
+ );
543
+ }
544
+ if (options === null || typeof options !== "object") {
545
+ throw new TypeError("Peer connection extension options must be an object");
546
+ }
547
+
548
+ const next = { ...peerConnection._nonstandardConfiguration };
549
+ if (Object.hasOwn(options, "enableIceUdpMux")) {
550
+ if (typeof options.enableIceUdpMux !== "boolean") {
551
+ throw new TypeError("enableIceUdpMux must be a boolean");
552
+ }
553
+ next.enableIceUdpMux = options.enableIceUdpMux;
554
+ }
555
+ if (Object.hasOwn(options, "disableFingerprintVerification")) {
556
+ if (typeof options.disableFingerprintVerification !== "boolean") {
557
+ throw new TypeError("disableFingerprintVerification must be a boolean");
558
+ }
559
+ next.disableFingerprintVerification = options.disableFingerprintVerification;
560
+ }
561
+ if (Object.hasOwn(options, "maxMessageSize")) {
562
+ const maxMessageSize = Number(options.maxMessageSize);
563
+ if (!Number.isSafeInteger(maxMessageSize) || maxMessageSize < 0) {
564
+ throw new TypeError("maxMessageSize must be a non-negative safe integer");
565
+ }
566
+ next.maxMessageSize = maxMessageSize;
567
+ }
568
+ peerConnection._nonstandardConfiguration = next;
569
+ }
570
+
571
+ function setLocalIceCredentials(peerConnection, credentials) {
572
+ assertPeerConnection(peerConnection);
573
+ peerConnection._setNonstandardLocalIceCredentials(credentials);
574
+ }
575
+
576
+ function getRemoteFingerprint(peerConnection) {
577
+ assertPeerConnection(peerConnection);
578
+ peerConnection._assertNotClosed();
579
+ return peerConnection._native?.remoteFingerprint() ?? null;
580
+ }
581
+
582
+ function normalizeDescription(init) {
583
+ if (init instanceof RTCSessionDescription) return init;
584
+ return new RTCSessionDescription(init);
585
+ }
586
+
587
+ function validateSdpType(type) {
588
+ if (!["offer", "answer", "pranswer", "rollback"].includes(type)) {
589
+ throw new TypeError(`Invalid RTCSdpType: ${type}`);
590
+ }
591
+ }
592
+
593
+ function isNoMediaSdp(description) {
594
+ return (
595
+ typeof description?.sdp === "string" &&
596
+ /^v=0(?:\r?\n|$)/.test(description.sdp) &&
597
+ !/\r?\nm=/.test(description.sdp)
598
+ );
599
+ }
600
+
601
+ function sdpSyntaxErrorLine(sdp) {
602
+ const lines = String(sdp ?? "").split(/\r\n|\n|\r/);
603
+ if (lines[0] !== "v=0") return 1;
604
+ for (let index = 0; index < lines.length; index += 1) {
605
+ const line = lines[index];
606
+ if (line === "" && index === lines.length - 1) continue;
607
+ if (!/^[a-z]=/.test(line)) return index + 1;
608
+ }
609
+ return null;
610
+ }
611
+
612
+ function assertValidSdpSyntax(description) {
613
+ if (description.type === "rollback") return;
614
+ const line = sdpSyntaxErrorLine(description.sdp);
615
+ if (line === null) return;
616
+ throw new RTCError(
617
+ {
618
+ errorDetail: "sdp-syntax-error",
619
+ sdpLineNumber: line,
620
+ },
621
+ "Invalid SDP syntax",
622
+ );
623
+ }
624
+
625
+ function hasDataMediaSection(description) {
626
+ return /\r?\nm=application\b/i.test(description?.sdp || "");
627
+ }
628
+
629
+ function hasTrickleIceOption(description) {
630
+ return /\r?\na=ice-options:[^\r\n]*\btrickle\b/i.test(description?.sdp || "");
631
+ }
632
+
633
+ function maxMessageSizeFromSdp(description) {
634
+ const match = /\r?\na=max-message-size:(\d+)/i.exec(description?.sdp || "");
635
+ return match ? Number(match[1]) : null;
636
+ }
637
+
638
+ function nextTask() {
639
+ return new Promise((resolve) => setImmediate(resolve));
640
+ }
641
+
642
+ function delay(ms) {
643
+ return new Promise((resolve) => setTimeout(resolve, ms));
644
+ }
645
+
646
+ const CLOSE_FLUSH_DELAY_MS = 50;
647
+ const CLOSE_FLUSH_POLL_INTERVAL_MS = 25;
648
+ const CLOSE_FLUSH_TIMEOUT_MS = 60000;
649
+ const BUFFERED_AMOUNT_NATIVE_DRAIN_POLL_INTERVAL_MS = 10;
650
+ const REMOTE_CLOSE_MESSAGE_GRACE_MS = 25;
651
+ const MESSAGE_CONSUMER_GATE_TIMEOUT_MS = 1000;
652
+ const SCTP_CONNECT_POLL_INTERVAL_MS = 25;
653
+ const SCTP_CONNECT_POLL_TIMEOUT_MS = 5000;
654
+ const DATA_CHANNEL_OPEN_REPAIR_INTERVAL_MS = 25;
655
+ const DATA_CHANNEL_OPEN_REPAIR_TIMEOUT_MS = 5000;
656
+ const DATA_CHANNEL_ANNOUNCEMENT_REPAIR_INTERVAL_MS = 25;
657
+ const DATA_CHANNEL_ANNOUNCEMENT_REPAIR_GRACE_MS = 250;
658
+ const DATA_CHANNEL_ANNOUNCEMENT_REPAIR_TIMEOUT_MS = 5000;
659
+ const NATIVE_CLOSE_SUPPRESSION_WINDOW_MS = 5000;
660
+ const DEFAULT_SCTP_MAX_MESSAGE_SIZE = 262144;
661
+ const LIBDATACHANNEL_SCTP_MAX_CHANNELS = 1024;
662
+ let nextUnsupportedDataChannelBindingId = -1;
663
+
664
+ async function delayInvalidStateIfOperationPending(peer) {
665
+ if (peer._operationsPending > 0) await nextTask();
666
+ }
667
+
668
+ const ICE_CREDENTIAL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
669
+
670
+ function randomIceCredential(length) {
671
+ const bytes = crypto.randomBytes(length);
672
+ let value = "";
673
+ for (const byte of bytes) value += ICE_CREDENTIAL_CHARS[byte & 0x3f];
674
+ return value;
675
+ }
676
+
677
+ function createIceRestartCredentials() {
678
+ return {
679
+ iceUfrag: randomIceCredential(16),
680
+ icePwd: randomIceCredential(32),
681
+ };
682
+ }
683
+
684
+ function rewriteIceCredentials(sdp, credentials) {
685
+ if (!/^a=ice-ufrag:/m.test(sdp) || !/^a=ice-pwd:/m.test(sdp)) return sdp;
686
+ return sdp
687
+ .replace(/^a=ice-ufrag:.*$/gm, `a=ice-ufrag:${credentials.iceUfrag}`)
688
+ .replace(/^a=ice-pwd:.*$/gm, `a=ice-pwd:${credentials.icePwd}`);
689
+ }
690
+
691
+ function markJsOnlyIceRestart(description) {
692
+ if (description && typeof description === "object") {
693
+ Object.defineProperty(description, "_webrtcNodeJsOnlyIceRestart", {
694
+ value: true,
695
+ configurable: true,
696
+ });
697
+ }
698
+ return description;
699
+ }
700
+
701
+ function hasDifferentIceCredentials(left, right) {
702
+ const leftParameters = firstIceParameters(left);
703
+ const rightParameters = firstIceParameters(right);
704
+ if (!leftParameters || !rightParameters) return false;
705
+ return (
706
+ leftParameters.usernameFragment !== rightParameters.usernameFragment ||
707
+ leftParameters.password !== rightParameters.password
708
+ );
709
+ }
710
+
711
+ class RTCSessionDescription {
712
+ constructor(init) {
713
+ if (!init || typeof init !== "object")
714
+ throw new TypeError("RTCSessionDescriptionInit required");
715
+ this.type = String(init.type || "");
716
+ validateSdpType(this.type);
717
+ this.sdp = String(init.sdp || "");
718
+ }
719
+
720
+ toJSON() {
721
+ return { type: this.type, sdp: this.sdp };
722
+ }
723
+ }
724
+
725
+ class RTCIceCandidate {
726
+ constructor(init = {}) {
727
+ if (init == null || typeof init !== "object")
728
+ throw new TypeError("RTCIceCandidateInit required");
729
+ const sdpMid = init.sdpMid == null ? null : String(init.sdpMid);
730
+ const sdpMLineIndex = init.sdpMLineIndex == null ? null : Number(init.sdpMLineIndex);
731
+ if (sdpMid === null && sdpMLineIndex === null) {
732
+ throw new TypeError("Either sdpMid or sdpMLineIndex must be provided");
733
+ }
734
+
735
+ this.candidate = init.candidate === undefined ? "" : String(init.candidate);
736
+ this.sdpMid = sdpMid;
737
+ this.sdpMLineIndex = sdpMLineIndex;
738
+ this.usernameFragment = init.usernameFragment == null ? null : String(init.usernameFragment);
739
+ this.relayProtocol = init.relayProtocol == null ? null : String(init.relayProtocol);
740
+ this.url = init.url == null ? null : String(init.url);
741
+
742
+ const parsed = parseCandidate(this.candidate);
743
+ this.foundation = parsed.foundation;
744
+ this.component = parsed.component;
745
+ this.priority = parsed.priority;
746
+ this.address = parsed.address;
747
+ this.protocol = parsed.protocol;
748
+ this.port = parsed.port;
749
+ this.type = parsed.type;
750
+ this.tcpType = parsed.tcpType;
751
+ this.relatedAddress = parsed.relatedAddress;
752
+ this.relatedPort = parsed.relatedPort;
753
+ }
754
+
755
+ toJSON() {
756
+ return {
757
+ candidate: this.candidate,
758
+ sdpMid: this.sdpMid,
759
+ sdpMLineIndex: this.sdpMLineIndex,
760
+ usernameFragment: this.usernameFragment,
761
+ };
762
+ }
763
+ }
764
+
765
+ class RTCIceCandidatePair {
766
+ constructor(token, local, remote) {
767
+ if (token !== kInternalConstruct) throw new TypeError("Illegal constructor");
768
+ defineReadonly(this, "local", local);
769
+ defineReadonly(this, "remote", remote);
770
+ }
771
+ }
772
+
773
+ function parseCandidate(candidate) {
774
+ const empty = {
775
+ foundation: null,
776
+ component: null,
777
+ priority: null,
778
+ address: null,
779
+ protocol: null,
780
+ port: null,
781
+ type: null,
782
+ tcpType: null,
783
+ relatedAddress: null,
784
+ relatedPort: null,
785
+ };
786
+ if (typeof candidate !== "string" || !candidate.startsWith("candidate:")) return empty;
787
+ const parts = candidate.slice("candidate:".length).trim().split(/\s+/);
788
+ if (parts.length < 8) return empty;
789
+ const result = { ...empty };
790
+ result.foundation = parts[0] || null;
791
+ result.component = parts[1] === "1" ? "rtp" : parts[1] === "2" ? "rtcp" : null;
792
+ result.protocol = parts[2] ? parts[2].toLowerCase() : null;
793
+ result.priority = Number(parts[3]);
794
+ result.address = parts[4] || null;
795
+ result.port = Number(parts[5]);
796
+ const typIndex = parts.indexOf("typ");
797
+ if (typIndex !== -1 && parts[typIndex + 1]) result.type = parts[typIndex + 1];
798
+ const tcpIndex = parts.indexOf("tcptype");
799
+ if (tcpIndex !== -1 && parts[tcpIndex + 1]) result.tcpType = parts[tcpIndex + 1];
800
+ const raddrIndex = parts.indexOf("raddr");
801
+ if (raddrIndex !== -1 && parts[raddrIndex + 1]) result.relatedAddress = parts[raddrIndex + 1];
802
+ const rportIndex = parts.indexOf("rport");
803
+ if (rportIndex !== -1 && parts[rportIndex + 1])
804
+ result.relatedPort = Number(parts[rportIndex + 1]);
805
+ return result;
806
+ }
807
+
808
+ function normalizeAddIceCandidateInput(init) {
809
+ if (init instanceof RTCIceCandidate) return init;
810
+ if (init == null) {
811
+ return {
812
+ candidate: "",
813
+ sdpMid: null,
814
+ sdpMLineIndex: null,
815
+ usernameFragment: null,
816
+ toJSON() {
817
+ return {
818
+ candidate: this.candidate,
819
+ sdpMid: this.sdpMid,
820
+ sdpMLineIndex: this.sdpMLineIndex,
821
+ usernameFragment: this.usernameFragment,
822
+ };
823
+ },
824
+ };
825
+ }
826
+ if (typeof init !== "object") throw new TypeError("RTCIceCandidateInit required");
827
+ const candidate = init.candidate == null ? "" : String(init.candidate);
828
+ const sdpMid = init.sdpMid == null ? null : String(init.sdpMid);
829
+ const sdpMLineIndex = init.sdpMLineIndex == null ? null : Number(init.sdpMLineIndex);
830
+ if (candidate !== "" && sdpMid === null && sdpMLineIndex === null) {
831
+ throw new TypeError("Either sdpMid or sdpMLineIndex must be provided");
832
+ }
833
+ return {
834
+ candidate,
835
+ sdpMid,
836
+ sdpMLineIndex,
837
+ usernameFragment: init.usernameFragment == null ? null : String(init.usernameFragment),
838
+ toJSON() {
839
+ return {
840
+ candidate: this.candidate,
841
+ sdpMid: this.sdpMid,
842
+ sdpMLineIndex: this.sdpMLineIndex,
843
+ usernameFragment: this.usernameFragment,
844
+ };
845
+ },
846
+ };
847
+ }
848
+
849
+ function splitSdpLines(sdp) {
850
+ return String(sdp || "")
851
+ .split(/\r?\n/)
852
+ .filter((line) => line !== "");
853
+ }
854
+
855
+ function parseSdpMediaSections(sdp) {
856
+ const sessionLines = [];
857
+ const mediaSections = [];
858
+ let sessionIceUfrag = null;
859
+ let sessionIcePwd = null;
860
+ let current = null;
861
+ for (const line of splitSdpLines(sdp)) {
862
+ if (line.startsWith("m=")) {
863
+ current = { startLine: line, lines: [line], mid: null, iceUfrag: null, icePwd: null };
864
+ mediaSections.push(current);
865
+ } else if (current) {
866
+ current.lines.push(line);
867
+ if (line.startsWith("a=mid:")) current.mid = line.slice("a=mid:".length);
868
+ if (line.startsWith("a=ice-ufrag:")) current.iceUfrag = line.slice("a=ice-ufrag:".length);
869
+ if (line.startsWith("a=ice-pwd:")) current.icePwd = line.slice("a=ice-pwd:".length);
870
+ } else {
871
+ sessionLines.push(line);
872
+ if (line.startsWith("a=ice-ufrag:")) sessionIceUfrag = line.slice("a=ice-ufrag:".length);
873
+ if (line.startsWith("a=ice-pwd:")) sessionIcePwd = line.slice("a=ice-pwd:".length);
874
+ }
875
+ }
876
+ for (const section of mediaSections) {
877
+ if (section.iceUfrag === null) section.iceUfrag = sessionIceUfrag;
878
+ if (section.icePwd === null) section.icePwd = sessionIcePwd;
879
+ }
880
+ return { sessionLines, mediaSections };
881
+ }
882
+
883
+ function serializeSdp(sessionLines, mediaSections) {
884
+ const lines = [...sessionLines];
885
+ for (const section of mediaSections) lines.push(...section.lines);
886
+ return `${lines.join("\r\n")}\r\n`;
887
+ }
888
+
889
+ function validateCandidateSyntax(candidate) {
890
+ if (candidate === "") return true;
891
+ if (typeof candidate !== "string" || !candidate.startsWith("candidate:")) return false;
892
+ const parts = candidate.slice("candidate:".length).trim().split(/\s+/);
893
+ const typIndex = parts.indexOf("typ");
894
+ return parts.length >= 8 && typIndex >= 6 && Boolean(parts[typIndex + 1]);
895
+ }
896
+
897
+ function selectCandidateSections(description, candidate) {
898
+ const parsed = parseSdpMediaSections(description?.sdp || "");
899
+ const sections = parsed.mediaSections;
900
+ if (sections.length === 0) return { parsed, targets: [] };
901
+
902
+ let targets;
903
+ if (candidate.sdpMid !== null) {
904
+ const section = sections.find((entry) => entry.mid === candidate.sdpMid);
905
+ if (!section)
906
+ throw makeDOMException("sdpMid does not match a remote media section", "OperationError");
907
+ targets = [section];
908
+ } else if (candidate.sdpMLineIndex !== null) {
909
+ const index = Number(candidate.sdpMLineIndex);
910
+ if (!Number.isInteger(index) || index < 0 || index >= sections.length) {
911
+ throw makeDOMException(
912
+ "sdpMLineIndex does not match a remote media section",
913
+ "OperationError",
914
+ );
915
+ }
916
+ targets = [sections[index]];
917
+ } else if (candidate.usernameFragment !== null) {
918
+ targets = sections.filter((entry) => entry.iceUfrag === candidate.usernameFragment);
919
+ if (targets.length === 0) {
920
+ throw makeDOMException(
921
+ "usernameFragment does not match a remote ICE generation",
922
+ "OperationError",
923
+ );
924
+ }
925
+ } else {
926
+ targets = sections;
927
+ }
928
+
929
+ if (candidate.usernameFragment !== null) {
930
+ const matches = targets.some((entry) => entry.iceUfrag === candidate.usernameFragment);
931
+ if (!matches) {
932
+ throw makeDOMException(
933
+ "usernameFragment does not match the selected media section",
934
+ "OperationError",
935
+ );
936
+ }
937
+ }
938
+
939
+ return { parsed, targets };
940
+ }
941
+
942
+ function appendRemoteCandidateToDescription(description, candidate) {
943
+ if (!description?.sdp || isNoMediaSdp(description)) return description;
944
+ if (!validateCandidateSyntax(candidate.candidate)) {
945
+ throw makeDOMException("Invalid ICE candidate syntax", "OperationError");
946
+ }
947
+
948
+ const { parsed, targets } = selectCandidateSections(description, candidate);
949
+ if (targets.length === 0) return description;
950
+
951
+ const line = candidate.candidate === "" ? "a=end-of-candidates" : `a=${candidate.candidate}`;
952
+ for (const section of targets) {
953
+ if (!section.lines.includes(line)) section.lines.push(line);
954
+ }
955
+ return new RTCSessionDescription({
956
+ type: description.type,
957
+ sdp: serializeSdp(parsed.sessionLines, parsed.mediaSections),
958
+ });
959
+ }
960
+
961
+ function isIceCandidateLine(line) {
962
+ return line.startsWith("a=candidate:") || line === "a=end-of-candidates";
963
+ }
964
+
965
+ function stripIceCandidateLinesFromDescription(description) {
966
+ if (!description?.sdp || isNoMediaSdp(description)) return description;
967
+ const parsed = parseSdpMediaSections(description.sdp);
968
+ let stripped = false;
969
+ for (const section of parsed.mediaSections) {
970
+ section.lines = section.lines.filter((line) => {
971
+ if (!isIceCandidateLine(line)) return true;
972
+ stripped = true;
973
+ return false;
974
+ });
975
+ }
976
+ if (!stripped) return description;
977
+ const result = new RTCSessionDescription({
978
+ type: description.type,
979
+ sdp: serializeSdp(parsed.sessionLines, parsed.mediaSections),
980
+ });
981
+ if (description._webrtcNodeJsOnlyIceRestart) markJsOnlyIceRestart(result);
982
+ return result;
983
+ }
984
+
985
+ function extractIceCandidatesFromDescription(description) {
986
+ if (!description?.sdp || isNoMediaSdp(description)) return [];
987
+ const parsed = parseSdpMediaSections(description.sdp);
988
+ const candidates = [];
989
+ for (let index = 0; index < parsed.mediaSections.length; index += 1) {
990
+ const section = parsed.mediaSections[index];
991
+ for (const line of section.lines) {
992
+ if (!line.startsWith("a=candidate:")) continue;
993
+ candidates.push(
994
+ new RTCIceCandidate({
995
+ candidate: line.slice("a=".length),
996
+ sdpMid: section.mid,
997
+ sdpMLineIndex: index,
998
+ usernameFragment: section.iceUfrag,
999
+ }),
1000
+ );
1001
+ }
1002
+ }
1003
+ return candidates;
1004
+ }
1005
+
1006
+ function resolveCandidateMid(description, candidate) {
1007
+ if (candidate.sdpMid !== null) return candidate.sdpMid;
1008
+ if (candidate.sdpMLineIndex === null) return null;
1009
+ const index = Number(candidate.sdpMLineIndex);
1010
+ const section = parseSdpMediaSections(description?.sdp || "").mediaSections[index];
1011
+ return section?.mid || null;
1012
+ }
1013
+
1014
+ function firstIceParameters(description) {
1015
+ const section = parseSdpMediaSections(description?.sdp || "").mediaSections.find(
1016
+ (entry) => entry.iceUfrag && entry.icePwd,
1017
+ );
1018
+ if (!section) return null;
1019
+ return {
1020
+ usernameFragment: section.iceUfrag,
1021
+ password: section.icePwd,
1022
+ };
1023
+ }
1024
+
1025
+ function dtlsSetupFromDescription(description) {
1026
+ const parsed = parseSdpMediaSections(description?.sdp || "");
1027
+ const section =
1028
+ parsed.mediaSections.find((entry) => /^m=application\b/i.test(entry.startLine)) ||
1029
+ parsed.mediaSections[0];
1030
+ const setupLine =
1031
+ section?.lines.find((line) => /^a=setup:/i.test(line)) ||
1032
+ parsed.sessionLines.find((line) => /^a=setup:/i.test(line));
1033
+ return setupLine ? setupLine.slice("a=setup:".length).toLowerCase() : null;
1034
+ }
1035
+
1036
+ function sameCandidate(left, right) {
1037
+ return (
1038
+ left.candidate === right.candidate &&
1039
+ left.sdpMid === right.sdpMid &&
1040
+ left.sdpMLineIndex === right.sdpMLineIndex &&
1041
+ left.usernameFragment === right.usernameFragment
1042
+ );
1043
+ }
1044
+
1045
+ function sameCandidateEndpoint(left, right) {
1046
+ if (!left || !right) return false;
1047
+ return (
1048
+ left.component === right.component &&
1049
+ left.protocol === right.protocol &&
1050
+ left.address === right.address &&
1051
+ left.port === right.port &&
1052
+ left.address !== null &&
1053
+ left.port !== null
1054
+ );
1055
+ }
1056
+
1057
+ function selectKnownCandidateByEndpoint(candidates, selectedCandidate) {
1058
+ return (
1059
+ candidates.find((candidate) => sameCandidateEndpoint(candidate, selectedCandidate)) ||
1060
+ selectedCandidate
1061
+ );
1062
+ }
1063
+
1064
+ class RTCDataChannelEvent extends SimpleEvent {
1065
+ constructor(type, init) {
1066
+ if (!init || !init.channel) throw new TypeError("RTCDataChannelEventInit.channel is required");
1067
+ super(type, init);
1068
+ this.channel = init.channel;
1069
+ }
1070
+ }
1071
+
1072
+ class RTCPeerConnectionIceEvent extends SimpleEvent {
1073
+ constructor(type, init = {}) {
1074
+ if (arguments.length === 0) throw new TypeError("type is required");
1075
+ if (
1076
+ init.candidate !== undefined &&
1077
+ init.candidate !== null &&
1078
+ !(init.candidate instanceof RTCIceCandidate)
1079
+ ) {
1080
+ throw new TypeError("candidate must be an RTCIceCandidate or null");
1081
+ }
1082
+ super(type, init);
1083
+ this.candidate = init.candidate == null ? null : init.candidate;
1084
+ this.url = init.url === undefined ? null : init.url;
1085
+ }
1086
+ }
1087
+
1088
+ class RTCPeerConnectionIceErrorEvent extends SimpleEvent {
1089
+ constructor(type, init = {}) {
1090
+ if (arguments.length === 0) throw new TypeError("type is required");
1091
+ super(type, init);
1092
+ this.address =
1093
+ init.address === undefined || init.address === null ? null : String(init.address);
1094
+ this.port =
1095
+ init.port === undefined || init.port === null ? null : enforceRange(init.port, "port");
1096
+ this.url = init.url === undefined ? "" : String(init.url);
1097
+ this.errorCode = init.errorCode === undefined ? 0 : enforceRange(init.errorCode, "errorCode");
1098
+ this.errorText = init.errorText === undefined ? "" : String(init.errorText);
1099
+ }
1100
+ }
1101
+
1102
+ class RTCError extends Error {
1103
+ constructor(init, message = "") {
1104
+ if (!init || typeof init !== "object" || init.errorDetail === undefined) {
1105
+ throw new TypeError("RTCErrorInit.errorDetail is required");
1106
+ }
1107
+ const errorDetail = String(init.errorDetail);
1108
+ if (
1109
+ ![
1110
+ "data-channel-failure",
1111
+ "dtls-failure",
1112
+ "fingerprint-failure",
1113
+ "sctp-failure",
1114
+ "sdp-syntax-error",
1115
+ "hardware-encoder-error",
1116
+ "hardware-encoder-not-available",
1117
+ ].includes(errorDetail)
1118
+ ) {
1119
+ throw new TypeError(`Invalid RTCErrorDetailType: ${errorDetail}`);
1120
+ }
1121
+ super(message);
1122
+ defineReadonly(this, "name", "OperationError");
1123
+ defineReadonly(this, "code", 0);
1124
+ defineReadonly(this, "errorDetail", errorDetail);
1125
+ defineReadonly(this, "sdpLineNumber", init.sdpLineNumber ?? null);
1126
+ defineReadonly(this, "sctpCauseCode", init.sctpCauseCode ?? null);
1127
+ defineReadonly(this, "receivedAlert", init.receivedAlert ?? null);
1128
+ defineReadonly(this, "sentAlert", init.sentAlert ?? null);
1129
+ }
1130
+ }
1131
+
1132
+ function defineReadonly(target, name, value) {
1133
+ Object.defineProperty(target, name, {
1134
+ value,
1135
+ enumerable: true,
1136
+ configurable: true,
1137
+ writable: false,
1138
+ });
1139
+ }
1140
+
1141
+ class RTCErrorEvent extends SimpleEvent {
1142
+ constructor(type, init = {}) {
1143
+ super(type, init);
1144
+ this.error = init.error;
1145
+ }
1146
+ }
1147
+
1148
+ class RTCIceTransport extends SimpleEventTarget {
1149
+ constructor(token, peerConnection) {
1150
+ if (token !== kInternalConstruct) throw new TypeError("Illegal constructor");
1151
+ super();
1152
+ this._pc = peerConnection;
1153
+ this._stateOverride = null;
1154
+ this._connectionSequenceRequested = false;
1155
+ this._connectionSequenceStarted = false;
1156
+ this._connectionSequenceReplaying = false;
1157
+ this.onstatechange = null;
1158
+ this.ongatheringstatechange = null;
1159
+ this.onselectedcandidatepairchange = null;
1160
+ }
1161
+
1162
+ get role() {
1163
+ return this._pc._iceRole;
1164
+ }
1165
+
1166
+ get component() {
1167
+ return "rtp";
1168
+ }
1169
+
1170
+ get state() {
1171
+ if (this._pc._closed) return "closed";
1172
+ return this._stateOverride || this._pc.iceConnectionState;
1173
+ }
1174
+
1175
+ get gatheringState() {
1176
+ const state = this._pc.iceGatheringState;
1177
+ if (
1178
+ state === "new" &&
1179
+ (this._pc._localIceCandidates.length > 0 ||
1180
+ this.state === "connected" ||
1181
+ this.state === "completed")
1182
+ ) {
1183
+ return "gathering";
1184
+ }
1185
+ return state;
1186
+ }
1187
+
1188
+ getLocalCandidates() {
1189
+ return this._pc._localIceCandidates.map((candidate) => new RTCIceCandidate(candidate.toJSON()));
1190
+ }
1191
+
1192
+ getRemoteCandidates() {
1193
+ return this._pc._remoteIceCandidates.map(
1194
+ (candidate) => new RTCIceCandidate(candidate.toJSON()),
1195
+ );
1196
+ }
1197
+
1198
+ getSelectedCandidatePair() {
1199
+ if (!["connected", "completed"].includes(this.state)) return null;
1200
+ const localCandidates = this.getLocalCandidates();
1201
+ const remoteCandidates = this.getRemoteCandidates();
1202
+ const hasExplicitlyNegotiatedPeerTransport = Boolean(
1203
+ this._pc._hasExplicitlyNegotiatedDataTransport() &&
1204
+ this._pc._pairedPeer?._hasExplicitlyNegotiatedDataTransport(),
1205
+ );
1206
+ const hasJsVisibleRemoteCandidate =
1207
+ remoteCandidates.length > 0 ||
1208
+ this._pc._sameProcessIceCandidateExchange ||
1209
+ this._pc._explicitIceCandidateExchange ||
1210
+ hasExplicitlyNegotiatedPeerTransport;
1211
+ if (!hasJsVisibleRemoteCandidate) return null;
1212
+ const nativePair = this._pc._native?.selectedCandidatePair();
1213
+ if (nativePair?.local && nativePair?.remote) {
1214
+ const nativeLocal = new RTCIceCandidate(nativePair.local);
1215
+ const nativeRemote = new RTCIceCandidate(nativePair.remote);
1216
+ return new RTCIceCandidatePair(
1217
+ kInternalConstruct,
1218
+ selectKnownCandidateByEndpoint(localCandidates, nativeLocal),
1219
+ selectKnownCandidateByEndpoint(remoteCandidates, nativeRemote),
1220
+ );
1221
+ }
1222
+ const pairedPeer = this._pc._pairedPeer;
1223
+ const pairedLocalCandidates =
1224
+ pairedPeer?._localIceCandidates?.map(
1225
+ (candidate) => new RTCIceCandidate(candidate.toJSON()),
1226
+ ) || [];
1227
+ const pairedRemoteCandidates =
1228
+ pairedPeer?._remoteIceCandidates?.map(
1229
+ (candidate) => new RTCIceCandidate(candidate.toJSON()),
1230
+ ) || [];
1231
+ const local = localCandidates[0] || pairedRemoteCandidates[0] || null;
1232
+ const remote = remoteCandidates[0] || pairedLocalCandidates[0] || null;
1233
+ if (!local || !remote) return null;
1234
+ return new RTCIceCandidatePair(kInternalConstruct, local, remote);
1235
+ }
1236
+
1237
+ getLocalParameters() {
1238
+ return firstIceParameters(this._pc.localDescription);
1239
+ }
1240
+
1241
+ getRemoteParameters() {
1242
+ return firstIceParameters(this._pc.remoteDescription);
1243
+ }
1244
+
1245
+ _eventListenerAdded(type) {
1246
+ if (type !== "statechange") return;
1247
+ this._connectionSequenceRequested = true;
1248
+ this._queueConnectedSequenceIfNeeded();
1249
+ }
1250
+
1251
+ _handlePeerIceConnectionState(state) {
1252
+ if (this._connectionSequenceReplaying && (state === "connected" || state === "completed")) {
1253
+ return;
1254
+ }
1255
+ if ((state === "connected" || state === "completed") && this._queueConnectedSequenceIfNeeded())
1256
+ return;
1257
+
1258
+ this._stateOverride = null;
1259
+ this.dispatchEvent(makeEvent("statechange"));
1260
+ }
1261
+
1262
+ _queueConnectedSequenceIfNeeded() {
1263
+ if (
1264
+ !this._connectionSequenceRequested ||
1265
+ this._connectionSequenceStarted ||
1266
+ !this._pc._hasNegotiatedDataTransport() ||
1267
+ !["connected", "completed"].includes(this._pc.iceConnectionState)
1268
+ ) {
1269
+ return false;
1270
+ }
1271
+ this._connectionSequenceStarted = true;
1272
+ this._connectionSequenceReplaying = true;
1273
+ setTimeout(() => {
1274
+ if (this._pc._closed || this._stateOverride === "disconnected") return;
1275
+ this._stateOverride = "checking";
1276
+ this.dispatchEvent(makeEvent("statechange"));
1277
+ this._stateOverride = "connected";
1278
+ setTimeout(() => {
1279
+ if (this._pc._closed || this._stateOverride !== "connected") return;
1280
+ this.dispatchEvent(makeEvent("statechange"));
1281
+ this._connectionSequenceReplaying = false;
1282
+ }, 0);
1283
+ }, 0);
1284
+ return true;
1285
+ }
1286
+
1287
+ _forceState(state, { dispatch = true } = {}) {
1288
+ this._connectionSequenceStarted = true;
1289
+ this._stateOverride = state;
1290
+ if (dispatch) this.dispatchEvent(makeEvent("statechange"));
1291
+ }
1292
+ }
1293
+
1294
+ class RTCDtlsTransport extends SimpleEventTarget {
1295
+ constructor(token, peerConnection) {
1296
+ if (token !== kInternalConstruct) throw new TypeError("Illegal constructor");
1297
+ super();
1298
+ this._pc = peerConnection;
1299
+ this.iceTransport = new RTCIceTransport(kInternalConstruct, peerConnection);
1300
+ this.onstatechange = null;
1301
+ this.onerror = null;
1302
+ }
1303
+
1304
+ get state() {
1305
+ if (this._pc._closed || this._pc.connectionState === "closed") return "closed";
1306
+ if (this._pc.connectionState === "connected" || this._pc._sctpTransport?._state === "connected")
1307
+ return "connected";
1308
+ if (this._pc.connectionState === "failed") return "failed";
1309
+ if (!this._pc.localDescription || !this._pc.remoteDescription) return "new";
1310
+ return "connecting";
1311
+ }
1312
+
1313
+ getRemoteCertificates() {
1314
+ if (this.state !== "connected") return [];
1315
+ const certificate = this._pc._pairedPeer?._nativeCertificates?.[0];
1316
+ const material = getCertificateMaterial(certificate);
1317
+ if (!material) return [];
1318
+ try {
1319
+ return [certificatePemToArrayBuffer(material.certificatePem)];
1320
+ } catch {
1321
+ return [];
1322
+ }
1323
+ }
1324
+ }
1325
+
1326
+ class RTCSctpTransport extends SimpleEventTarget {
1327
+ constructor(token, peerConnection) {
1328
+ if (token !== kInternalConstruct) throw new TypeError("Illegal constructor");
1329
+ super();
1330
+ this._pc = peerConnection;
1331
+ this._transport = new RTCDtlsTransport(kInternalConstruct, peerConnection);
1332
+ this._state = "connecting";
1333
+ this._maxMessageSize = null;
1334
+ this._maxChannels = null;
1335
+ this.onstatechange = null;
1336
+ }
1337
+
1338
+ get transport() {
1339
+ return this._transport;
1340
+ }
1341
+
1342
+ get state() {
1343
+ return this._state;
1344
+ }
1345
+
1346
+ get maxMessageSize() {
1347
+ return this._maxMessageSize;
1348
+ }
1349
+
1350
+ get maxChannels() {
1351
+ if (this._maxChannels === null && this._state === "connected") {
1352
+ this._maxChannels = this._pc._currentSctpMaxChannels() || LIBDATACHANNEL_SCTP_MAX_CHANNELS;
1353
+ }
1354
+ return this._maxChannels;
1355
+ }
1356
+
1357
+ _setState(state) {
1358
+ if (this._state === state) return;
1359
+ this._state = state;
1360
+ this.dispatchEvent(makeEvent("statechange"));
1361
+ }
1362
+
1363
+ _setLimits({ maxMessageSize, maxChannels }) {
1364
+ this._maxMessageSize = maxMessageSize;
1365
+ this._maxChannels = maxChannels;
1366
+ }
1367
+ }
1368
+
1369
+ class UnsupportedNativeDataChannel {
1370
+ constructor(label, options) {
1371
+ this.bindingId = nextUnsupportedDataChannelBindingId--;
1372
+ this.label = label;
1373
+ this.ordered = options.ordered;
1374
+ this.protocol = options.protocol;
1375
+ this.negotiated = options.negotiated;
1376
+ this.maxPacketLifeTime = options.maxPacketLifeTime ?? null;
1377
+ this.maxRetransmits = options.maxRetransmits ?? null;
1378
+ this.id = options.id;
1379
+ this.bufferedAmount = 0;
1380
+ this.maxMessageSize = DEFAULT_SCTP_MAX_MESSAGE_SIZE;
1381
+ this.isOpen = false;
1382
+ this.isClosed = false;
1383
+ }
1384
+
1385
+ close() {
1386
+ this.isClosed = true;
1387
+ }
1388
+
1389
+ setBufferedAmountLowThreshold() {}
1390
+
1391
+ sendString() {
1392
+ throw new Error("RTCDataChannel stream id exceeds libdatachannel's native stream limit");
1393
+ }
1394
+
1395
+ sendBinary() {
1396
+ throw new Error("RTCDataChannel stream id exceeds libdatachannel's native stream limit");
1397
+ }
1398
+ }
1399
+
1400
+ class SyntheticNativeDataChannel {
1401
+ constructor(label, options) {
1402
+ this.bindingId = nextUnsupportedDataChannelBindingId--;
1403
+ this.label = label;
1404
+ this.ordered = options.ordered;
1405
+ this.protocol = options.protocol;
1406
+ this.negotiated = options.negotiated;
1407
+ this.maxPacketLifeTime = options.maxPacketLifeTime ?? null;
1408
+ this.maxRetransmits = options.maxRetransmits ?? null;
1409
+ this.id = options.id;
1410
+ this.bufferedAmount = 0;
1411
+ this.maxMessageSize = DEFAULT_SCTP_MAX_MESSAGE_SIZE;
1412
+ this.isOpen = true;
1413
+ this.isClosed = false;
1414
+ }
1415
+
1416
+ close() {
1417
+ this.isOpen = false;
1418
+ this.isClosed = true;
1419
+ }
1420
+
1421
+ setBufferedAmountLowThreshold() {}
1422
+
1423
+ sendString() {
1424
+ return true;
1425
+ }
1426
+
1427
+ sendBinary() {
1428
+ return true;
1429
+ }
1430
+ }
1431
+
1432
+ class RTCDataChannel extends SimpleEventTarget {
1433
+ static _fromNative(
1434
+ peerConnection,
1435
+ nativeChannel,
1436
+ initialReadyState = undefined,
1437
+ assignedId = null,
1438
+ ) {
1439
+ const channel = new RTCDataChannel(
1440
+ peerConnection,
1441
+ nativeChannel,
1442
+ initialReadyState,
1443
+ assignedId,
1444
+ );
1445
+ peerConnection._channels.set(channel._native.bindingId, channel);
1446
+ peerConnection._registerDataChannelId(channel);
1447
+ if (channel._registeredDataChannelId == null && channel._effectiveId() == null) {
1448
+ peerConnection._dataChannelIdRefreshNeeded = true;
1449
+ }
1450
+ return channel;
1451
+ }
1452
+
1453
+ constructor(peerConnection, nativeChannel, initialReadyState = undefined, assignedId = null) {
1454
+ super();
1455
+ this._pc = peerConnection;
1456
+ this._native = nativeChannel;
1457
+ this._readyState =
1458
+ initialReadyState ||
1459
+ (nativeChannel.isOpen ? "open" : nativeChannel.isClosed ? "closed" : "connecting");
1460
+ this._binaryType = "arraybuffer";
1461
+ this._bufferedAmount = 0;
1462
+ this._bufferedAmountLowThreshold = 0;
1463
+ this._pendingBufferedAmountDecrease = 0;
1464
+ this._bufferedAmountDecreaseScheduled = false;
1465
+ this._sendTail = Promise.resolve();
1466
+ this._pendingSendCount = 0;
1467
+ this._nativeCloseScheduled = false;
1468
+ this._openEventPending = false;
1469
+ this._openEventDispatched = false;
1470
+ this._announcementPending = false;
1471
+ this._nativeEventDrainActive = false;
1472
+ this._queuedNativeEvents = [];
1473
+ this._queuedMessageEvents = [];
1474
+ this._queuedMessageEventIndex = 0;
1475
+ this._messageEventFlushScheduled = false;
1476
+ this._messageEventGateActive = false;
1477
+ this._messageConsumerGateActive = false;
1478
+ this._messageEventListenerCount = 0;
1479
+ this._messageHandlerNeedsTaskYield = false;
1480
+ this._pendingPairedDeliveryBytes = 0;
1481
+ this._nativeCloseEventQueued = false;
1482
+ this._nativeCloseSuppressionDeadline = 0;
1483
+ this._nativeCloseSuppressionsRemaining = 0;
1484
+ this._openEventDeferredForIce = false;
1485
+ this._openEventDeferredForDataChannel = false;
1486
+ this._openEventDataChannelDeferralExpired = false;
1487
+ this._registeredDataChannelId = null;
1488
+ this._assignedId = assignedId;
1489
+ this._pairedChannel = null;
1490
+ this._createdLocally = false;
1491
+ this._negotiatedOverride = null;
1492
+ this._syntheticIncoming = false;
1493
+ this.onopen = null;
1494
+ this._onmessage = null;
1495
+ this.onclose = null;
1496
+ this.onerror = null;
1497
+ this.onclosing = null;
1498
+ this.onbufferedamountlow = null;
1499
+ }
1500
+
1501
+ get label() {
1502
+ return this._native.label;
1503
+ }
1504
+
1505
+ get ordered() {
1506
+ return this._native.ordered;
1507
+ }
1508
+
1509
+ get maxPacketLifeTime() {
1510
+ return this._native.maxPacketLifeTime;
1511
+ }
1512
+
1513
+ get maxRetransmits() {
1514
+ return this._native.maxRetransmits;
1515
+ }
1516
+
1517
+ get protocol() {
1518
+ return this._native.protocol;
1519
+ }
1520
+
1521
+ get negotiated() {
1522
+ return this._negotiatedOverride ?? this._native.negotiated;
1523
+ }
1524
+
1525
+ get id() {
1526
+ const nativeId = this._native.id;
1527
+ if (nativeId != null) this._assignedId = nativeId;
1528
+ const id = nativeId ?? this._assignedId;
1529
+ this._pc._registerDataChannelId(this, id);
1530
+ return id;
1531
+ }
1532
+
1533
+ get readyState() {
1534
+ return this._readyState;
1535
+ }
1536
+
1537
+ get bufferedAmount() {
1538
+ return this._bufferedAmount;
1539
+ }
1540
+
1541
+ get bufferedAmountLowThreshold() {
1542
+ return this._bufferedAmountLowThreshold;
1543
+ }
1544
+
1545
+ set bufferedAmountLowThreshold(value) {
1546
+ const threshold = toUnsignedLong(value);
1547
+ this._bufferedAmountLowThreshold = threshold;
1548
+ this._native.setBufferedAmountLowThreshold(threshold);
1549
+ }
1550
+
1551
+ get binaryType() {
1552
+ return this._binaryType;
1553
+ }
1554
+
1555
+ set binaryType(value) {
1556
+ if (value === "arraybuffer" || value === "blob") this._binaryType = value;
1557
+ }
1558
+
1559
+ get onmessage() {
1560
+ return this._onmessage;
1561
+ }
1562
+
1563
+ set onmessage(callback) {
1564
+ this._onmessage = typeof callback === "function" ? callback : null;
1565
+ this._messageHandlerNeedsTaskYield = this._messageContinuationNeedsTaskYield(this._onmessage);
1566
+ if (this._onmessage) this._releaseMessageConsumerGate();
1567
+ }
1568
+
1569
+ send(data) {
1570
+ if (this._readyState === "connecting") {
1571
+ throw makeDOMException("RTCDataChannel is not open", "InvalidStateError");
1572
+ }
1573
+ if (this._readyState === "closing" || this._readyState === "closed") {
1574
+ throw makeDOMException("RTCDataChannel is closing or closed", "InvalidStateError");
1575
+ }
1576
+
1577
+ if (typeof data === "string") {
1578
+ const payload = data;
1579
+ const size = byteLength(payload);
1580
+ this._assertWithinMaxMessageSize(size);
1581
+ if (this._hasPendingSends() || !this._nativeReadyForSend()) {
1582
+ this._enqueueSend(() => this._sendNativeString(payload), size);
1583
+ } else {
1584
+ if (this._sendNativeString(payload)) {
1585
+ this._increaseBufferedAmount(size);
1586
+ } else {
1587
+ this._enqueueSend(() => this._sendNativeString(payload), size);
1588
+ }
1589
+ }
1590
+ return;
1591
+ }
1592
+
1593
+ if (typeof Blob !== "undefined" && data instanceof Blob) {
1594
+ const blob = data;
1595
+ this._assertWithinMaxMessageSize(blob.size);
1596
+ this._enqueueSend(async () => {
1597
+ const buffer = await blob.arrayBuffer();
1598
+ return this._sendNativeBinary(new Uint8Array(buffer));
1599
+ }, blob.size);
1600
+ return;
1601
+ }
1602
+
1603
+ const view = data instanceof Uint8Array ? data : toUint8Array(data);
1604
+ const size = view.byteLength;
1605
+ this._assertWithinMaxMessageSize(size);
1606
+ if (this._hasPendingSends() || !this._nativeReadyForSend()) {
1607
+ const payload = new Uint8Array(view);
1608
+ this._enqueueSend(() => this._sendNativeBinary(payload), size);
1609
+ } else {
1610
+ if (this._sendNativeBinary(view)) {
1611
+ this._increaseBufferedAmount(size);
1612
+ } else {
1613
+ const payload = new Uint8Array(view);
1614
+ this._enqueueSend(() => this._sendNativeBinary(payload), size);
1615
+ }
1616
+ }
1617
+ }
1618
+
1619
+ close() {
1620
+ if (this._readyState === "closing" || this._readyState === "closed") return;
1621
+ this._readyState = "closing";
1622
+ if (!this._pairedChannel) {
1623
+ this._pc._pairDataChannelById(this, this._effectiveId());
1624
+ }
1625
+ const pairedChannel = this._pairedChannel;
1626
+ const shouldDrainBeforeClose =
1627
+ this._bufferedAmount > 0 || this._hasPendingSends() || this._pendingPairedDeliveryBytes > 0;
1628
+ if (!this._nativeCloseScheduled) {
1629
+ this._nativeCloseScheduled = true;
1630
+ const closeNative = () => {
1631
+ const close = () => {
1632
+ const synthesizePairedClose = pairedChannel && pairedChannel.readyState !== "closed";
1633
+ this._native.close();
1634
+ if (synthesizePairedClose) {
1635
+ setTimeout(() => pairedChannel._handleRemoteChannelClose(), 0);
1636
+ }
1637
+ setTimeout(() => {
1638
+ if (this._readyState === "closing") this._handleClose();
1639
+ }, 0);
1640
+ };
1641
+ if (shouldDrainBeforeClose) {
1642
+ this._closeNativeAfterBufferedSends(close);
1643
+ } else {
1644
+ setImmediate(close);
1645
+ }
1646
+ };
1647
+ if (this._hasPendingSends()) {
1648
+ this._sendTail.then(closeNative, closeNative);
1649
+ } else {
1650
+ closeNative();
1651
+ }
1652
+ }
1653
+ }
1654
+
1655
+ _increaseBufferedAmount(size) {
1656
+ if (!size) return;
1657
+ this._bufferedAmount += size;
1658
+ this._queueBufferedAmountDecrease(size);
1659
+ }
1660
+
1661
+ _queueBufferedAmountDecrease(size) {
1662
+ if (!size) return;
1663
+ if (this._usesSyntheticPairDelivery()) {
1664
+ setImmediate(() => this._decreaseBufferedAmount(size));
1665
+ return;
1666
+ }
1667
+ this._pendingBufferedAmountDecrease += size;
1668
+ this._scheduleBufferedAmountDecrease();
1669
+ }
1670
+
1671
+ _scheduleBufferedAmountDecrease(waitForNativeDrain = false) {
1672
+ if (this._bufferedAmountDecreaseScheduled) return;
1673
+ this._bufferedAmountDecreaseScheduled = true;
1674
+ const run = () => {
1675
+ this._bufferedAmountDecreaseScheduled = false;
1676
+ this._flushBufferedAmountDecrease();
1677
+ };
1678
+ if (waitForNativeDrain) {
1679
+ setTimeout(run, BUFFERED_AMOUNT_NATIVE_DRAIN_POLL_INTERVAL_MS);
1680
+ } else {
1681
+ setImmediate(run);
1682
+ }
1683
+ }
1684
+
1685
+ _flushBufferedAmountDecrease() {
1686
+ if (this._pendingBufferedAmountDecrease <= 0) return;
1687
+ const nativeBufferedAmount = Number(this._native?.bufferedAmount || 0);
1688
+ if (nativeBufferedAmount > 0 && this._readyState !== "closed") {
1689
+ this._scheduleBufferedAmountDecrease(true);
1690
+ return;
1691
+ }
1692
+ const amount = this._pendingBufferedAmountDecrease;
1693
+ this._pendingBufferedAmountDecrease = 0;
1694
+ this._decreaseBufferedAmount(amount);
1695
+ }
1696
+
1697
+ _hasPendingSends() {
1698
+ return this._pendingSendCount > 0;
1699
+ }
1700
+
1701
+ _effectiveId() {
1702
+ return this._native.id ?? this._assignedId;
1703
+ }
1704
+
1705
+ _assignId(id) {
1706
+ if (this._native.id != null || this._assignedId != null) return;
1707
+ this._assignedId = id;
1708
+ this._pc._registerDataChannelId(this, id);
1709
+ if (this._pairedChannel?._syntheticIncoming && this._pairedChannel._effectiveId() == null) {
1710
+ this._pairedChannel._assignId(id);
1711
+ }
1712
+ this._pc._pairedPeer?._scheduleDataChannelAnnouncementRepair();
1713
+ }
1714
+
1715
+ _adoptNativeChannel(nativeChannel, initialReadyState = undefined) {
1716
+ const previousBindingId = this._native.bindingId;
1717
+ if (this._pc._channels.get(previousBindingId) === this) {
1718
+ this._pc._channels.delete(previousBindingId);
1719
+ }
1720
+ this._native = nativeChannel;
1721
+ this._syntheticIncoming = false;
1722
+ this._pc._channels.set(nativeChannel.bindingId, this);
1723
+ if (initialReadyState) {
1724
+ this._readyState = initialReadyState;
1725
+ } else if (nativeChannel.isOpen) {
1726
+ this._readyState = "open";
1727
+ } else if (nativeChannel.isClosed) {
1728
+ this._readyState = "closed";
1729
+ }
1730
+ this._pc._registerDataChannelId(this);
1731
+ }
1732
+
1733
+ _assertWithinMaxMessageSize(size) {
1734
+ const maxMessageSize = this._pc._sctpTransport?._maxMessageSize;
1735
+ if (
1736
+ maxMessageSize !== null &&
1737
+ maxMessageSize !== Number.POSITIVE_INFINITY &&
1738
+ size > maxMessageSize
1739
+ ) {
1740
+ throw new TypeError("RTCDataChannel message exceeds RTCSctpTransport.maxMessageSize");
1741
+ }
1742
+ }
1743
+
1744
+ _enqueueSend(operation, size) {
1745
+ this._pendingSendCount += 1;
1746
+ this._bufferedAmount += size;
1747
+ const run = async () => {
1748
+ try {
1749
+ await this._waitForNativeSendReady();
1750
+ await this._waitForNativeSendAccepted(operation);
1751
+ } catch (error) {
1752
+ this.dispatchEvent(
1753
+ new RTCErrorEvent("error", {
1754
+ error: new RTCError(
1755
+ { errorDetail: "data-channel-failure" },
1756
+ error?.message || String(error),
1757
+ ),
1758
+ }),
1759
+ );
1760
+ } finally {
1761
+ this._pendingSendCount -= 1;
1762
+ this._queueBufferedAmountDecrease(size);
1763
+ }
1764
+ };
1765
+ this._sendTail = this._sendTail.then(run, run);
1766
+ }
1767
+
1768
+ _nativeReadyForSend() {
1769
+ return this._usesSyntheticPairDelivery() || Boolean(this._native?.isOpen);
1770
+ }
1771
+
1772
+ async _waitForNativeSendReady() {
1773
+ if (this._nativeReadyForSend()) return;
1774
+ const deadline = Date.now() + DATA_CHANNEL_OPEN_REPAIR_TIMEOUT_MS;
1775
+ while (!this._nativeReadyForSend() && this._readyState !== "closed" && Date.now() < deadline) {
1776
+ await delay(DATA_CHANNEL_OPEN_REPAIR_INTERVAL_MS);
1777
+ }
1778
+ if (!this._nativeReadyForSend()) {
1779
+ throw makeDOMException("RTCDataChannel is not open", "InvalidStateError");
1780
+ }
1781
+ }
1782
+
1783
+ async _waitForNativeSendAccepted(operation) {
1784
+ const deadline = Date.now() + DATA_CHANNEL_OPEN_REPAIR_TIMEOUT_MS;
1785
+ while (this._readyState !== "closed" && Date.now() < deadline) {
1786
+ if (await operation()) return;
1787
+ await delay(DATA_CHANNEL_OPEN_REPAIR_INTERVAL_MS);
1788
+ await this._waitForNativeSendReady();
1789
+ }
1790
+ throw makeDOMException("RTCDataChannel send was not accepted", "OperationError");
1791
+ }
1792
+
1793
+ _sendNativeString(data) {
1794
+ if (this._usesSyntheticPairDelivery()) {
1795
+ this._trackPendingPairedDelivery(byteLength(data));
1796
+ this._deliverSyntheticMessage({ binary: false, data });
1797
+ return true;
1798
+ }
1799
+ try {
1800
+ let sent = this._native.sendString(data);
1801
+ if (sent !== false) {
1802
+ sent = true;
1803
+ } else {
1804
+ sent = Boolean(this._native?.isOpen);
1805
+ }
1806
+ if (sent && this._pairedChannel) this._pendingPairedDeliveryBytes += byteLength(data);
1807
+ return sent;
1808
+ } catch (error) {
1809
+ throw mapNativeError(error, "OperationError");
1810
+ }
1811
+ }
1812
+
1813
+ _sendNativeBinary(data) {
1814
+ if (this._usesSyntheticPairDelivery()) {
1815
+ const view = toUint8Array(data);
1816
+ const copy = view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength);
1817
+ this._trackPendingPairedDelivery(copy.byteLength);
1818
+ this._deliverSyntheticMessage({ binary: true, data: copy });
1819
+ return true;
1820
+ }
1821
+ try {
1822
+ const view = data instanceof Uint8Array ? data : toUint8Array(data);
1823
+ let sent = this._native.sendBinary(view);
1824
+ if (sent !== false) {
1825
+ sent = true;
1826
+ } else {
1827
+ sent = Boolean(this._native?.isOpen);
1828
+ }
1829
+ if (sent && this._pairedChannel && view.byteLength > 0) {
1830
+ this._pendingPairedDeliveryBytes += view.byteLength;
1831
+ }
1832
+ return sent;
1833
+ } catch (error) {
1834
+ throw mapNativeError(error, "OperationError");
1835
+ }
1836
+ }
1837
+
1838
+ _usesSyntheticPairDelivery() {
1839
+ return this._syntheticIncoming || this._pairedChannel?._syntheticIncoming;
1840
+ }
1841
+
1842
+ _deliverSyntheticMessage(event) {
1843
+ const target = this._pairedChannel;
1844
+ if (!target || target.readyState === "closed") return;
1845
+ setImmediate(() => {
1846
+ if (target.readyState === "closed") return;
1847
+ target._handleNativeEvent({ type: "message", ...event });
1848
+ });
1849
+ }
1850
+
1851
+ _trackPendingPairedDelivery(size) {
1852
+ if (!this._pairedChannel || size <= 0) return;
1853
+ this._pendingPairedDeliveryBytes += size;
1854
+ }
1855
+
1856
+ _markPairedDeliveryReceived(event) {
1857
+ const sender = this._pairedChannel;
1858
+ if (!sender || sender.readyState === "closed") return;
1859
+ const size = event.binary ? event.data?.byteLength || 0 : byteLength(event.data || "");
1860
+ if (size <= 0) return;
1861
+ sender._pendingPairedDeliveryBytes = Math.max(0, sender._pendingPairedDeliveryBytes - size);
1862
+ sender._decreaseBufferedAmountForPairedDelivery(size);
1863
+ }
1864
+
1865
+ _decreaseBufferedAmountForPairedDelivery(size) {
1866
+ const pending = Math.min(size, this._pendingBufferedAmountDecrease);
1867
+ if (pending > 0) {
1868
+ this._pendingBufferedAmountDecrease -= pending;
1869
+ }
1870
+ this._decreaseBufferedAmount(size);
1871
+ }
1872
+
1873
+ _decreaseBufferedAmount(size) {
1874
+ const previous = this._bufferedAmount;
1875
+ this._bufferedAmount = Math.max(0, this._bufferedAmount - size);
1876
+ if (
1877
+ previous > this._bufferedAmountLowThreshold &&
1878
+ this._bufferedAmount <= this._bufferedAmountLowThreshold
1879
+ ) {
1880
+ this.dispatchEvent(makeEvent("bufferedamountlow"));
1881
+ }
1882
+ }
1883
+
1884
+ _closeNativeAfterBufferedSends(close) {
1885
+ const deadline = Date.now() + CLOSE_FLUSH_TIMEOUT_MS;
1886
+ const poll = () => {
1887
+ const nativeBufferedAmount = Number(this._native?.bufferedAmount || 0);
1888
+ const pairedDeliveryDrained = this._pendingPairedDeliveryBytes === 0;
1889
+ const nativeBufferDrained = this._bufferedAmount === 0 && nativeBufferedAmount === 0;
1890
+ const drained = this._pairedChannel ? pairedDeliveryDrained : nativeBufferDrained;
1891
+ if (drained || Date.now() >= deadline) {
1892
+ setTimeout(close, CLOSE_FLUSH_DELAY_MS);
1893
+ return;
1894
+ }
1895
+ setTimeout(poll, CLOSE_FLUSH_POLL_INTERVAL_MS);
1896
+ };
1897
+ poll();
1898
+ }
1899
+
1900
+ _handleNativeEvent(event, fromQueue = false) {
1901
+ if (!fromQueue && (this._announcementPending || this._nativeEventDrainActive)) {
1902
+ if (event.type === "open") {
1903
+ this._readyState = "open";
1904
+ this._openEventPending = true;
1905
+ } else {
1906
+ this._queuedNativeEvents.push(event);
1907
+ }
1908
+ return;
1909
+ }
1910
+
1911
+ switch (event.type) {
1912
+ case "open":
1913
+ if (this._openEventPending) {
1914
+ this._readyState = "open";
1915
+ this._pc._registerDataChannelId(this);
1916
+ break;
1917
+ }
1918
+ if (this._readyState === "connecting" || this._readyState === "open") {
1919
+ this._readyState = "open";
1920
+ this._pc._registerDataChannelId(this);
1921
+ this._dispatchOpenEvent();
1922
+ }
1923
+ break;
1924
+ case "message":
1925
+ this._queueMessageEvent(event);
1926
+ break;
1927
+ case "bufferedamountlow":
1928
+ // The JS facade owns W3C bufferedAmount timing; native low-water events
1929
+ // use libdatachannel's transport queue and can race the JS-visible counter.
1930
+ break;
1931
+ case "error":
1932
+ this.dispatchEvent(
1933
+ new RTCErrorEvent("error", {
1934
+ error: new RTCError({ errorDetail: "data-channel-failure" }, event.error || ""),
1935
+ }),
1936
+ );
1937
+ break;
1938
+ case "close":
1939
+ this._queueNativeCloseEvent();
1940
+ break;
1941
+ }
1942
+ }
1943
+
1944
+ _queueNativeCloseEvent() {
1945
+ if (this._nativeCloseEventQueued) return;
1946
+ this._nativeCloseEventQueued = true;
1947
+ this._deferRemoteCloseUntilMessagesFlushed(() => {
1948
+ this._nativeCloseEventQueued = false;
1949
+ this._handleNativeCloseEvent();
1950
+ });
1951
+ }
1952
+
1953
+ _deferRemoteCloseUntilMessagesFlushed(callback) {
1954
+ const notBefore = Date.now() + REMOTE_CLOSE_MESSAGE_GRACE_MS;
1955
+ const closeAfterMessages = () => {
1956
+ if (this._readyState === "closed") return;
1957
+ if (
1958
+ Date.now() < notBefore ||
1959
+ this._messageEventGateActive ||
1960
+ this._messageEventFlushScheduled ||
1961
+ this._queuedMessageEvents.length > 0
1962
+ ) {
1963
+ setTimeout(closeAfterMessages, 0);
1964
+ return;
1965
+ }
1966
+ callback();
1967
+ };
1968
+ setTimeout(closeAfterMessages, 0);
1969
+ }
1970
+
1971
+ _handleNativeCloseEvent() {
1972
+ if (this._shouldSuppressSpuriousNativeClose()) return;
1973
+ if (this._readyState === "open") {
1974
+ this._readyState = "closing";
1975
+ this.dispatchEvent(makeEvent("closing"));
1976
+ setTimeout(() => this._finishRemoteClose(), 0);
1977
+ } else {
1978
+ this._handleClose();
1979
+ }
1980
+ }
1981
+
1982
+ _armNativeCloseSuppression() {
1983
+ this._nativeCloseSuppressionDeadline = Date.now() + NATIVE_CLOSE_SUPPRESSION_WINDOW_MS;
1984
+ this._nativeCloseSuppressionsRemaining = 1;
1985
+ }
1986
+
1987
+ _shouldSuppressSpuriousNativeClose() {
1988
+ if (
1989
+ this._nativeCloseSuppressionsRemaining === 0 ||
1990
+ Date.now() > this._nativeCloseSuppressionDeadline
1991
+ ) {
1992
+ this._nativeCloseSuppressionsRemaining = 0;
1993
+ return false;
1994
+ }
1995
+ const shouldSuppress = Boolean(
1996
+ this._pc._pairedPeer &&
1997
+ this._pairedChannel &&
1998
+ this._readyState === "open" &&
1999
+ this._pairedChannel.readyState === "open" &&
2000
+ this._pc.connectionState === "connected" &&
2001
+ ["connected", "completed"].includes(this._pc.iceConnectionState) &&
2002
+ this._pc.sctp?.state === "connected",
2003
+ );
2004
+ if (shouldSuppress) this._nativeCloseSuppressionsRemaining -= 1;
2005
+ return shouldSuppress;
2006
+ }
2007
+
2008
+ _finishRemoteClose() {
2009
+ if (this._readyState !== "closing") return;
2010
+ const peerFailed =
2011
+ this._pc.connectionState === "closed" ||
2012
+ this._pc.connectionState === "disconnected" ||
2013
+ this._pc.connectionState === "failed" ||
2014
+ this._pc.iceConnectionState === "closed" ||
2015
+ this._pc.iceConnectionState === "disconnected" ||
2016
+ this._pc.iceConnectionState === "failed";
2017
+ if (peerFailed && this._hasEventConsumer("error") && this._hasEventConsumer("close")) {
2018
+ this.dispatchEvent(
2019
+ new RTCErrorEvent("error", {
2020
+ error: new RTCError(
2021
+ {
2022
+ name: "OperationError",
2023
+ errorDetail: "sctp-failure",
2024
+ sctpCauseCode: null,
2025
+ },
2026
+ "The SCTP association was closed",
2027
+ ),
2028
+ }),
2029
+ );
2030
+ }
2031
+ this._handleClose();
2032
+ }
2033
+
2034
+ _handleRemoteChannelClose() {
2035
+ if (this._readyState === "closed") return;
2036
+ this._deferRemoteCloseUntilMessagesFlushed(() => {
2037
+ if (this._readyState === "closed") return;
2038
+ if (this._readyState === "open" || this._readyState === "connecting") {
2039
+ this._readyState = "closing";
2040
+ this.dispatchEvent(makeEvent("closing"));
2041
+ setTimeout(() => this._handleClose(), 0);
2042
+ return;
2043
+ }
2044
+ if (this._readyState === "closing") {
2045
+ setTimeout(() => this._handleClose(), 0);
2046
+ }
2047
+ });
2048
+ }
2049
+
2050
+ _handlePeerConnectionFailure() {
2051
+ if (this._readyState === "closed") return;
2052
+ if (this._readyState === "open") {
2053
+ this._readyState = "closing";
2054
+ }
2055
+ if (this._hasEventConsumer("error") && this._hasEventConsumer("close")) {
2056
+ this.dispatchEvent(
2057
+ new RTCErrorEvent("error", {
2058
+ error: new RTCError(
2059
+ {
2060
+ name: "OperationError",
2061
+ errorDetail: "sctp-failure",
2062
+ sctpCauseCode: null,
2063
+ },
2064
+ "The SCTP association was closed",
2065
+ ),
2066
+ }),
2067
+ );
2068
+ }
2069
+ this._handleClose();
2070
+ }
2071
+
2072
+ _handleClose() {
2073
+ if (this._readyState === "closed") return;
2074
+ const id = this._effectiveId();
2075
+ this._readyState = "closed";
2076
+ if (this._pairedChannel?._pairedChannel === this) this._pairedChannel._pairedChannel = null;
2077
+ this._pairedChannel = null;
2078
+ this._pc._unregisterDataChannelId(this);
2079
+ if (this._pc._channels.get(this._native.bindingId) === this) {
2080
+ this._pc._channels.delete(this._native.bindingId);
2081
+ }
2082
+ if (!this._createdLocally && id != null) {
2083
+ this._pc._remoteAnnouncedDataChannelIds.delete(id);
2084
+ this._pc._pendingSyntheticDataChannelAnnouncements.delete(id);
2085
+ }
2086
+ this.dispatchEvent(makeEvent("close"));
2087
+ }
2088
+
2089
+ _announceOpenAfterDataChannelEvent() {
2090
+ if (!this._openEventPending) return;
2091
+ this._openEventPending = false;
2092
+ setTimeout(() => {
2093
+ if (this._readyState === "open") this._dispatchOpenEvent();
2094
+ }, 0);
2095
+ }
2096
+
2097
+ _dispatchOpenEvent() {
2098
+ if (this._openEventDispatched || this._readyState !== "open") return;
2099
+ const pendingIcePeer = this._pendingIceEventPeer();
2100
+ if (pendingIcePeer) {
2101
+ if (this._openEventDeferredForIce) return;
2102
+ this._openEventDeferredForIce = true;
2103
+ pendingIcePeer._afterDeferredIceEventsFlushed(() => {
2104
+ this._openEventDeferredForIce = false;
2105
+ this._dispatchOpenEvent();
2106
+ });
2107
+ return;
2108
+ }
2109
+ const pendingDataChannelPeer = this._pendingDataChannelAnnouncementPeer();
2110
+ if (pendingDataChannelPeer) {
2111
+ if (this._openEventDeferredForDataChannel) return;
2112
+ this._openEventDeferredForDataChannel = true;
2113
+ pendingDataChannelPeer._afterDataChannelAnnouncementSettled(
2114
+ this._effectiveId(),
2115
+ (settled) => {
2116
+ this._openEventDeferredForDataChannel = false;
2117
+ if (!settled) this._openEventDataChannelDeferralExpired = true;
2118
+ this._dispatchOpenEvent();
2119
+ },
2120
+ );
2121
+ return;
2122
+ }
2123
+ this._openEventDispatched = true;
2124
+ this.dispatchEvent(makeEvent("open"));
2125
+ }
2126
+
2127
+ _pendingIceEventPeer() {
2128
+ const peers = [this._pc, this._pc._pairedPeer].filter(Boolean);
2129
+ return peers.find((peer) => peer._hasPendingDeferredIceEvents());
2130
+ }
2131
+
2132
+ _pendingDataChannelAnnouncementPeer() {
2133
+ if (this._openEventDataChannelDeferralExpired) return null;
2134
+ if (!this._createdLocally || this.negotiated) return null;
2135
+ const id = this._effectiveId();
2136
+ const peer = this._pc._pairedPeer;
2137
+ if (!peer || peer._closed || id == null || !peer._hasEventConsumer("datachannel")) return null;
2138
+ return peer._hasSettledDataChannelAnnouncement(id) ? null : peer;
2139
+ }
2140
+
2141
+ _repairMissedOpenEvent() {
2142
+ if (this._readyState !== "connecting" || this._native.isClosed || !this._native.isOpen)
2143
+ return false;
2144
+ this._readyState = "open";
2145
+ this._pc._registerDataChannelId(this);
2146
+ if (this._announcementPending) {
2147
+ this._openEventPending = true;
2148
+ } else {
2149
+ this._dispatchOpenEvent();
2150
+ }
2151
+ return true;
2152
+ }
2153
+
2154
+ _flushQueuedNativeEventsAfterAnnouncement() {
2155
+ if (!this._queuedNativeEvents.length) return;
2156
+ this._nativeEventDrainActive = true;
2157
+ const dispatchNext = () => {
2158
+ const event = this._queuedNativeEvents.shift();
2159
+ if (!event) {
2160
+ this._nativeEventDrainActive = false;
2161
+ return;
2162
+ }
2163
+ this._handleNativeEvent(event, true);
2164
+ if (this._queuedNativeEvents.length) setImmediate(dispatchNext);
2165
+ else this._nativeEventDrainActive = false;
2166
+ };
2167
+ setImmediate(dispatchNext);
2168
+ }
2169
+
2170
+ _queueMessageEvent(event) {
2171
+ this._queuedMessageEvents.push(event);
2172
+ this._scheduleMessageEventFlush();
2173
+ }
2174
+
2175
+ _queueMessageEvents(events) {
2176
+ for (const event of events) this._queuedMessageEvents.push(event);
2177
+ this._scheduleMessageEventFlush();
2178
+ }
2179
+
2180
+ _scheduleMessageEventFlush() {
2181
+ if (this._messageEventFlushScheduled) return;
2182
+ this._messageEventFlushScheduled = true;
2183
+ setImmediate(() => {
2184
+ this._messageEventFlushScheduled = false;
2185
+ this._flushQueuedMessageEvents();
2186
+ });
2187
+ }
2188
+
2189
+ _scheduleMessageEventContinuation({ yieldToTask = false } = {}) {
2190
+ if (this._messageEventFlushScheduled) return;
2191
+ this._messageEventFlushScheduled = true;
2192
+ const schedule = yieldToTask ? setTimeout : setImmediate;
2193
+ schedule(
2194
+ () => {
2195
+ this._messageEventFlushScheduled = false;
2196
+ this._flushQueuedMessageEvents();
2197
+ },
2198
+ yieldToTask ? 1 : 0,
2199
+ );
2200
+ }
2201
+
2202
+ _messageContinuationNeedsTaskYield(handler = this._onmessage) {
2203
+ if (typeof handler !== "function") return false;
2204
+ try {
2205
+ return /\[native code\]/.test(Function.prototype.toString.call(handler));
2206
+ } catch {
2207
+ return false;
2208
+ }
2209
+ }
2210
+
2211
+ _hasMessageEventListeners() {
2212
+ return this._messageEventListenerCount > 0;
2213
+ }
2214
+
2215
+ _canContinueMessageBatchInCurrentTask(handler, yieldToTask) {
2216
+ return (
2217
+ typeof handler === "function" &&
2218
+ handler instanceof Function &&
2219
+ this._onmessage === handler &&
2220
+ !yieldToTask &&
2221
+ !this._hasMessageEventListeners()
2222
+ );
2223
+ }
2224
+
2225
+ _canUseDirectMessageHandler(handler, yieldToTask, hasMessageListeners) {
2226
+ return !hasMessageListeners && this._canContinueMessageBatchInCurrentTask(handler, yieldToTask);
2227
+ }
2228
+
2229
+ _dispatchMessageEvent(event, directHandler) {
2230
+ const messageEvent = makeMessageEvent("message", { data: this._convertMessage(event) });
2231
+ if (directHandler) {
2232
+ messageEvent.target = this;
2233
+ messageEvent.currentTarget = this;
2234
+ callListener(directHandler, this, messageEvent);
2235
+ } else {
2236
+ this.dispatchEvent(messageEvent);
2237
+ }
2238
+ }
2239
+
2240
+ _flushQueuedMessageEvents() {
2241
+ while (true) {
2242
+ if (this._readyState === "closed") {
2243
+ this._queuedMessageEvents.length = 0;
2244
+ this._queuedMessageEventIndex = 0;
2245
+ return;
2246
+ }
2247
+
2248
+ const pendingPeer =
2249
+ this._pc._operationsPending > 0
2250
+ ? this._pc
2251
+ : this._pc._pairedPeer?._operationsPending > 0
2252
+ ? this._pc._pairedPeer
2253
+ : null;
2254
+ if (pendingPeer) {
2255
+ pendingPeer._afterOperationsIdle(() => this._scheduleMessageEventFlush());
2256
+ return;
2257
+ }
2258
+
2259
+ if (this._messageEventGateActive) return;
2260
+ if (this._messageConsumerGateActive && !this._hasEventConsumer("message")) return;
2261
+ if (this._messageConsumerGateActive) this._messageConsumerGateActive = false;
2262
+
2263
+ const event = this._queuedMessageEvents[this._queuedMessageEventIndex++];
2264
+ if (!event) {
2265
+ this._queuedMessageEventIndex = 0;
2266
+ return;
2267
+ }
2268
+ const handler = this._onmessage;
2269
+ const hasMessageListeners = this._hasMessageEventListeners();
2270
+ const yieldToTask = this._messageHandlerNeedsTaskYield;
2271
+ const directHandler = this._canUseDirectMessageHandler(
2272
+ handler,
2273
+ yieldToTask,
2274
+ hasMessageListeners,
2275
+ )
2276
+ ? handler
2277
+ : null;
2278
+ this._markPairedDeliveryReceived(event);
2279
+ this._dispatchMessageEvent(event, directHandler);
2280
+
2281
+ if (this._queuedMessageEventIndex >= this._queuedMessageEvents.length) {
2282
+ this._queuedMessageEvents.length = 0;
2283
+ this._queuedMessageEventIndex = 0;
2284
+ return;
2285
+ }
2286
+ if (this._queuedMessageEventIndex > 1024) {
2287
+ this._queuedMessageEvents.splice(0, this._queuedMessageEventIndex);
2288
+ this._queuedMessageEventIndex = 0;
2289
+ }
2290
+ if (!this._canContinueMessageBatchInCurrentTask(handler, yieldToTask)) {
2291
+ this._scheduleMessageEventContinuation({ yieldToTask });
2292
+ return;
2293
+ }
2294
+ }
2295
+ }
2296
+
2297
+ _dispatchNativeMessageBatch(events) {
2298
+ if (this._readyState === "closed") return true;
2299
+ if (this._queuedMessageEvents.length > 0) return false;
2300
+ const pendingPeer =
2301
+ this._pc._operationsPending > 0
2302
+ ? this._pc
2303
+ : this._pc._pairedPeer?._operationsPending > 0
2304
+ ? this._pc._pairedPeer
2305
+ : null;
2306
+ if (pendingPeer || this._messageEventGateActive) return false;
2307
+ if (this._messageConsumerGateActive && !this._hasEventConsumer("message")) return false;
2308
+ if (this._messageConsumerGateActive) this._messageConsumerGateActive = false;
2309
+
2310
+ const handler = this._onmessage;
2311
+ const hasMessageListeners = this._hasMessageEventListeners();
2312
+ const yieldToTask = this._messageHandlerNeedsTaskYield;
2313
+ const directHandler = this._canUseDirectMessageHandler(
2314
+ handler,
2315
+ yieldToTask,
2316
+ hasMessageListeners,
2317
+ )
2318
+ ? handler
2319
+ : null;
2320
+ if (!directHandler) return false;
2321
+
2322
+ const shouldCreateBlob = this._binaryType === "blob" && typeof Blob !== "undefined";
2323
+ for (let index = 0; index < events.length; index += 1) {
2324
+ const event = events[index];
2325
+ this._markPairedDeliveryReceived(event);
2326
+ const messageEvent = makeMessageEvent("message", {
2327
+ data: event.binary && shouldCreateBlob ? new Blob([event.data]) : event.data,
2328
+ });
2329
+ messageEvent.target = this;
2330
+ messageEvent.currentTarget = this;
2331
+ directHandler.call(this, messageEvent);
2332
+ if (this._readyState === "closed") return true;
2333
+ if (
2334
+ index + 1 < events.length &&
2335
+ !this._canContinueMessageBatchInCurrentTask(handler, yieldToTask)
2336
+ ) {
2337
+ for (let remaining = index + 1; remaining < events.length; remaining += 1) {
2338
+ this._queuedMessageEvents.push(events[remaining]);
2339
+ }
2340
+ this._scheduleMessageEventContinuation({ yieldToTask: this._messageHandlerNeedsTaskYield });
2341
+ return true;
2342
+ }
2343
+ }
2344
+ return true;
2345
+ }
2346
+
2347
+ _gateMessageEventsAfterAnnouncement() {
2348
+ if (this._messageEventGateActive) return;
2349
+ this._messageEventGateActive = true;
2350
+ setTimeout(() => {
2351
+ setTimeout(() => {
2352
+ this._messageEventGateActive = false;
2353
+ this._scheduleMessageEventFlush();
2354
+ }, 0);
2355
+ }, 0);
2356
+ }
2357
+
2358
+ _gateMessageEventsUntilConsumer() {
2359
+ if (this._hasEventConsumer("message")) return;
2360
+ this._messageConsumerGateActive = true;
2361
+ setTimeout(() => this._releaseMessageConsumerGate(), MESSAGE_CONSUMER_GATE_TIMEOUT_MS);
2362
+ }
2363
+
2364
+ _releaseMessageConsumerGate() {
2365
+ if (!this._messageConsumerGateActive) return;
2366
+ this._messageConsumerGateActive = false;
2367
+ this._scheduleMessageEventFlush();
2368
+ }
2369
+
2370
+ _eventListenerAdded(type) {
2371
+ if (type !== "message") return;
2372
+ this._messageEventListenerCount += 1;
2373
+ this._releaseMessageConsumerGate();
2374
+ }
2375
+
2376
+ _eventListenerRemoved(type) {
2377
+ if (type === "message" && this._messageEventListenerCount > 0) {
2378
+ this._messageEventListenerCount -= 1;
2379
+ }
2380
+ }
2381
+
2382
+ _convertMessage(event) {
2383
+ if (!event.binary) return event.data;
2384
+ if (this._binaryType === "blob" && typeof Blob !== "undefined") {
2385
+ return new Blob([event.data]);
2386
+ }
2387
+ return event.data;
2388
+ }
2389
+ }
2390
+
2391
+ function toUint8Array(data) {
2392
+ if (data instanceof Uint8Array) return data;
2393
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
2394
+ if (ArrayBuffer.isView(data)) {
2395
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
2396
+ }
2397
+ throw new TypeError(
2398
+ "RTCDataChannel.send expects a string, Blob, ArrayBuffer, or ArrayBufferView",
2399
+ );
2400
+ }
2401
+
2402
+ class RTCPeerConnection extends SimpleEventTarget {
2403
+ static generateCertificate(algorithm) {
2404
+ return generateCertificate(algorithm);
2405
+ }
2406
+
2407
+ constructor(configuration = {}) {
2408
+ super();
2409
+ const normalizedConfiguration = normalizePeerConnectionConfiguration(configuration);
2410
+ this._configuration = normalizedConfiguration;
2411
+ this._channels = new Map();
2412
+ this._usedDataChannelIds = new Map();
2413
+ this._dataChannelIdRefreshNeeded = false;
2414
+ this._closed = false;
2415
+ this._localDescription = null;
2416
+ this._remoteDescription = null;
2417
+ this._currentLocalDescription = null;
2418
+ this._pendingLocalDescription = null;
2419
+ this._currentRemoteDescription = null;
2420
+ this._pendingRemoteDescription = null;
2421
+ this._localDescriptionPairingKeys = new Set();
2422
+ this._pairedPeer = null;
2423
+ this._sctpTransport = null;
2424
+ this._canTrickleIceCandidates = null;
2425
+ this._selfRemoteDescription = false;
2426
+ this._pendingIce = [];
2427
+ this._localIceCandidates = [];
2428
+ this._remoteIceCandidates = [];
2429
+ this._pendingRemoteCandidatesForNative = [];
2430
+ this._deferredIceEvents = [];
2431
+ this._iceEventFlushScheduled = false;
2432
+ this._processingDeferredIceEvent = false;
2433
+ this._iceEventIdleCallbacks = [];
2434
+ this._iceRole = "unknown";
2435
+ this._preparedLocalDescription = null;
2436
+ this._nonstandardPreparedLocalDescriptionType = null;
2437
+ this._nonstandardLocalIceCredentials = null;
2438
+ this._nonstandardConfiguration = {
2439
+ enableIceUdpMux: false,
2440
+ disableFingerprintVerification: false,
2441
+ maxMessageSize: undefined,
2442
+ };
2443
+ this._lastCreatedOffer = null;
2444
+ this._lastCreatedAnswer = null;
2445
+ this._localDescriptionSetByApi = false;
2446
+ this._localDescriptionRefreshScheduled = false;
2447
+ this._nativeCandidateGatheringScheduled = false;
2448
+ this._iceRestartPending = false;
2449
+ this._pendingIceRestartCredentials = null;
2450
+ this._jsOnlyIceRestartOfferPending = false;
2451
+ this._jsOnlyIceRestartRemoteOffer = false;
2452
+ this._operationsPending = 0;
2453
+ this._operationIdleCallbacks = [];
2454
+ this._explicitIceCandidateExchange = false;
2455
+ this._sameProcessIceCandidateExchange = false;
2456
+ this._suppressNextNativeSignalingState = null;
2457
+ this._sctpTransportUpdateScheduled = false;
2458
+ this._sctpConnectedTransitionScheduled = false;
2459
+ this._sctpConnectedTransitionReady = false;
2460
+ this._sctpConnectPollScheduled = false;
2461
+ this._sctpConnectPollDeadline = 0;
2462
+ this._connectedStateRepairScheduled = false;
2463
+ this._dataChannelOpenRepairScheduled = false;
2464
+ this._dataChannelOpenRepairDeadline = 0;
2465
+ this._dataChannelAnnouncementRepairScheduled = false;
2466
+ this._dataChannelAnnouncementRepairReadyAt = 0;
2467
+ this._dataChannelAnnouncementRepairDeadline = 0;
2468
+ this._remoteAnnouncedDataChannelIds = new Set();
2469
+ this._pendingSyntheticDataChannelAnnouncements = new Map();
2470
+ this._localDataChannelCount = 0;
2471
+ this._negotiationNeeded = false;
2472
+ this._negotiationNeededScheduled = false;
2473
+ this._ondatachannel = null;
2474
+ this._pendingDataChannelEvents = [];
2475
+ this._pendingNativeDataChannelEvents = new Map();
2476
+ this._dataChannelFlushScheduled = false;
2477
+ this.onicecandidate = null;
2478
+ this.onicecandidateerror = null;
2479
+ this.onicegatheringstatechange = null;
2480
+ this.oniceconnectionstatechange = null;
2481
+ this.onconnectionstatechange = null;
2482
+ this.onsignalingstatechange = null;
2483
+ this.onnegotiationneeded = null;
2484
+ this._connectionState = "new";
2485
+ this._iceConnectionState = "new";
2486
+ this._iceGatheringState = "new";
2487
+ this._signalingState = "stable";
2488
+ this._lastDispatchedSignalingState = "stable";
2489
+ this._native = null;
2490
+ this._nativeCertificates = null;
2491
+ }
2492
+
2493
+ getConfiguration() {
2494
+ return cloneConfiguration(this._configuration);
2495
+ }
2496
+
2497
+ _ensureNativePeerConnection() {
2498
+ if (this._native) return this._native;
2499
+ const nativeConfiguration = {
2500
+ iceServers: this._configuration.iceServers.map((server) => ({
2501
+ ...server,
2502
+ urls: [...server.urls],
2503
+ })),
2504
+ iceTransportPolicy: this._configuration.iceTransportPolicy,
2505
+ ...this._nonstandardConfiguration,
2506
+ };
2507
+ let nativeCertificates = this._configuration.certificates;
2508
+ if (nativeCertificates.length === 0) {
2509
+ nativeCertificates = [createDefaultNativeCertificate()];
2510
+ }
2511
+ const material = getCertificateMaterial(nativeCertificates[0]);
2512
+ if (material) {
2513
+ nativeConfiguration.certificatePem = material.certificatePem;
2514
+ nativeConfiguration.keyPem = material.keyPem;
2515
+ }
2516
+ const nativePeerConnection = new native.NativePeerConnection(nativeConfiguration, (event) => {
2517
+ if (Array.isArray(event)) {
2518
+ this._handleNativeEventBatch(event);
2519
+ } else {
2520
+ this._handleNativeEvent(event);
2521
+ }
2522
+ });
2523
+ this._nativeCertificates = nativeCertificates;
2524
+ this._native = nativePeerConnection;
2525
+ return this._native;
2526
+ }
2527
+
2528
+ setConfiguration(configuration = {}) {
2529
+ this._assertNotClosed();
2530
+ const hasCertificates =
2531
+ configuration &&
2532
+ typeof configuration === "object" &&
2533
+ Object.hasOwn(configuration, "certificates");
2534
+ const normalizedConfiguration = normalizePeerConnectionConfiguration(configuration);
2535
+ if (!hasCertificates) normalizedConfiguration.certificates = this._configuration.certificates;
2536
+ if (normalizedConfiguration.bundlePolicy !== this._configuration.bundlePolicy) {
2537
+ throw makeDOMException("bundlePolicy cannot be changed", "InvalidModificationError");
2538
+ }
2539
+ if (normalizedConfiguration.rtcpMuxPolicy !== this._configuration.rtcpMuxPolicy) {
2540
+ throw makeDOMException("rtcpMuxPolicy cannot be changed", "InvalidModificationError");
2541
+ }
2542
+ if (
2543
+ !sameCertificateSet(normalizedConfiguration.certificates, this._configuration.certificates)
2544
+ ) {
2545
+ throw makeDOMException("certificates cannot be changed", "InvalidModificationError");
2546
+ }
2547
+ this._configuration = normalizedConfiguration;
2548
+ }
2549
+
2550
+ get localDescription() {
2551
+ return this._pendingLocalDescription || this._currentLocalDescription;
2552
+ }
2553
+
2554
+ get currentLocalDescription() {
2555
+ return this._currentLocalDescription;
2556
+ }
2557
+
2558
+ get pendingLocalDescription() {
2559
+ return this._pendingLocalDescription;
2560
+ }
2561
+
2562
+ get remoteDescription() {
2563
+ return this._pendingRemoteDescription || this._currentRemoteDescription;
2564
+ }
2565
+
2566
+ get currentRemoteDescription() {
2567
+ return this._currentRemoteDescription;
2568
+ }
2569
+
2570
+ get pendingRemoteDescription() {
2571
+ return this._pendingRemoteDescription;
2572
+ }
2573
+
2574
+ get signalingState() {
2575
+ return this._closed ? "closed" : this._signalingState;
2576
+ }
2577
+
2578
+ get iceGatheringState() {
2579
+ return this._iceGatheringState;
2580
+ }
2581
+
2582
+ get iceConnectionState() {
2583
+ return this._iceConnectionState;
2584
+ }
2585
+
2586
+ get connectionState() {
2587
+ return this._connectionState;
2588
+ }
2589
+
2590
+ get canTrickleIceCandidates() {
2591
+ return this._canTrickleIceCandidates;
2592
+ }
2593
+
2594
+ get sctp() {
2595
+ return this._sctpTransport;
2596
+ }
2597
+
2598
+ get ondatachannel() {
2599
+ return this._ondatachannel;
2600
+ }
2601
+
2602
+ set ondatachannel(callback) {
2603
+ this._ondatachannel = typeof callback === "function" ? callback : null;
2604
+ this._scheduleDataChannelFlush();
2605
+ this._scheduleDataChannelAnnouncementRepair();
2606
+ this._pairedPeer?._scheduleDataChannelAnnouncementRepair();
2607
+ }
2608
+
2609
+ createDataChannel(label, init = {}) {
2610
+ this._assertNotClosed();
2611
+ if (arguments.length === 0) throw new TypeError("createDataChannel requires a label");
2612
+ const options = normalizeDataChannelInit(init);
2613
+ const stringLabel = String(label);
2614
+ validateByteLength(stringLabel, "label");
2615
+ validateByteLength(options.protocol, "protocol");
2616
+ if (options.negotiated && this._isDataChannelIdInUse(options.id)) {
2617
+ throw makeDOMException("RTCDataChannel id is already in use", "OperationError");
2618
+ }
2619
+ const nativeChannel = this._createNativeDataChannel(stringLabel, options);
2620
+ const assignedId = options.negotiated ? options.id : null;
2621
+ const channel = RTCDataChannel._fromNative(this, nativeChannel, undefined, assignedId);
2622
+ channel._createdLocally = true;
2623
+ this._localDataChannelCount += 1;
2624
+ if (this._localDataChannelCount === 1) this._markNegotiationNeeded();
2625
+ this._assignDataChannelIdsFromDtlsRole();
2626
+ this._scheduleDataChannelOpenRepair();
2627
+ this._pairedPeer?._scheduleDataChannelAnnouncementRepair();
2628
+ return channel;
2629
+ }
2630
+
2631
+ _createNativeDataChannel(label, options) {
2632
+ try {
2633
+ return this._ensureNativePeerConnection().createDataChannel(label, options);
2634
+ } catch (error) {
2635
+ const highNegotiatedStream =
2636
+ options.negotiated &&
2637
+ options.id >= LIBDATACHANNEL_SCTP_MAX_CHANNELS &&
2638
+ /stream id is too high/i.test(error?.message || "");
2639
+ if (!highNegotiatedStream) throw error;
2640
+ return new UnsupportedNativeDataChannel(label, options);
2641
+ }
2642
+ }
2643
+
2644
+ async createOffer(options = undefined) {
2645
+ this._assertNotClosed();
2646
+ const optionsObject = options !== null && typeof options === "object" ? options : {};
2647
+ const iceRestartRequested = optionsObject.iceRestart === true;
2648
+ if (this._signalingState !== "stable" && this._signalingState !== "have-local-offer") {
2649
+ await delayInvalidStateIfOperationPending(this);
2650
+ throw makeDOMException("Cannot create offer in current signaling state", "InvalidStateError");
2651
+ }
2652
+ this._operationsPending += 1;
2653
+ try {
2654
+ await nextTask();
2655
+ if (iceRestartRequested && !this._nonstandardLocalIceCredentials) {
2656
+ this._iceRestartPending = true;
2657
+ this._armDataChannelNativeCloseSuppression();
2658
+ }
2659
+ let offer =
2660
+ this._prepareNonstandardLocalDescription("offer") ||
2661
+ this._ensureNativePeerConnection().createOffer();
2662
+ const jsOnlyIceRestart = this._iceRestartPending && !this._canApplyNativeIceCredentials();
2663
+ if (this._iceRestartPending && !jsOnlyIceRestart) {
2664
+ offer = {
2665
+ type: offer.type,
2666
+ sdp: rewriteIceCredentials(offer.sdp, this._ensureIceRestartCredentials()),
2667
+ };
2668
+ }
2669
+ this._lastCreatedOffer = new RTCSessionDescription(offer);
2670
+ if (jsOnlyIceRestart) markJsOnlyIceRestart(this._lastCreatedOffer);
2671
+ return offer;
2672
+ } catch (error) {
2673
+ throw mapNativeError(error, "InvalidStateError");
2674
+ } finally {
2675
+ this._finishPendingOperation();
2676
+ }
2677
+ }
2678
+
2679
+ _armDataChannelNativeCloseSuppression() {
2680
+ const peers = new Set([this, this._pairedPeer].filter(Boolean));
2681
+ for (const peer of peers) {
2682
+ for (const channel of peer._channels.values()) channel._armNativeCloseSuppression();
2683
+ }
2684
+ }
2685
+
2686
+ restartIce() {
2687
+ if (this._closed) return;
2688
+ if (!this._localDescription && !this._remoteDescription) return;
2689
+ this._iceRestartPending = true;
2690
+ this._pendingIceRestartCredentials = null;
2691
+ this._armDataChannelNativeCloseSuppression();
2692
+ if (this._signalingState === "stable") this._markNegotiationNeeded();
2693
+ }
2694
+
2695
+ async createAnswer() {
2696
+ this._assertNotClosed();
2697
+ if (!this.remoteDescription) {
2698
+ await delayInvalidStateIfOperationPending(this);
2699
+ throw makeDOMException("Remote description is not set", "InvalidStateError");
2700
+ }
2701
+ this._operationsPending += 1;
2702
+ try {
2703
+ await nextTask();
2704
+ if (this._jsOnlyIceRestartRemoteOffer) {
2705
+ const answer = markJsOnlyIceRestart(
2706
+ new RTCSessionDescription(this._ensureNativePeerConnection().createAnswer()),
2707
+ );
2708
+ this._lastCreatedAnswer = answer;
2709
+ Object.defineProperty(answer, "_webrtcNodeAnswerer", {
2710
+ value: this,
2711
+ configurable: true,
2712
+ });
2713
+ return answer;
2714
+ }
2715
+ if (isNoMediaSdp(this.remoteDescription)) {
2716
+ const answer = {
2717
+ type: "answer",
2718
+ sdp: this.remoteDescription.sdp,
2719
+ };
2720
+ this._lastCreatedAnswer = new RTCSessionDescription(answer);
2721
+ return answer;
2722
+ }
2723
+ const answer =
2724
+ this._prepareNonstandardLocalDescription("answer") ||
2725
+ this._ensureNativePeerConnection().createAnswer();
2726
+ this._lastCreatedAnswer = new RTCSessionDescription(answer);
2727
+ Object.defineProperty(answer, "_webrtcNodeAnswerer", {
2728
+ value: this,
2729
+ configurable: true,
2730
+ });
2731
+ return answer;
2732
+ } catch (error) {
2733
+ throw mapNativeError(error, "InvalidStateError");
2734
+ } finally {
2735
+ this._finishPendingOperation();
2736
+ }
2737
+ }
2738
+
2739
+ async setLocalDescription(description = undefined) {
2740
+ this._assertNotClosed();
2741
+ const jsOnlyIceRestartDescription = Boolean(description?._webrtcNodeJsOnlyIceRestart);
2742
+ let normalized = description === undefined ? null : normalizeDescription(description);
2743
+ const type = normalized ? normalized.type : this._implicitLocalDescriptionType();
2744
+ if (
2745
+ normalized?.type === "rollback" &&
2746
+ this._signalingState !== "have-local-offer" &&
2747
+ this._operationsPending === 0
2748
+ ) {
2749
+ throw makeDOMException(
2750
+ "Cannot roll back a local description in current signaling state",
2751
+ "InvalidStateError",
2752
+ );
2753
+ }
2754
+ this._operationsPending += 1;
2755
+ try {
2756
+ await nextTask();
2757
+ if (this._closed) return new Promise(() => {});
2758
+ if (normalized?.type === "offer") {
2759
+ if (this._signalingState !== "stable" && this._signalingState !== "have-local-offer") {
2760
+ throw makeDOMException(
2761
+ "Cannot set a local offer in current signaling state",
2762
+ "InvalidStateError",
2763
+ );
2764
+ }
2765
+ if (normalized.sdp === "" && this._lastCreatedOffer) normalized = this._lastCreatedOffer;
2766
+ if (!this._lastCreatedOffer || normalized.sdp !== this._lastCreatedOffer.sdp) {
2767
+ throw makeDOMException(
2768
+ "Local offer does not match the last created offer",
2769
+ "InvalidModificationError",
2770
+ );
2771
+ }
2772
+ }
2773
+ if (normalized?.type === "rollback") {
2774
+ if (this._signalingState !== "have-local-offer") {
2775
+ throw makeDOMException(
2776
+ "Cannot roll back a local description in current signaling state",
2777
+ "InvalidStateError",
2778
+ );
2779
+ }
2780
+ const previousState = this._signalingState;
2781
+ const previousGatheringState = this._iceGatheringState;
2782
+ const rollingBackInitialOffer = !this._currentLocalDescription;
2783
+ const nativeBackedRollback =
2784
+ this._localDescription && !isNoMediaSdp(this._localDescription);
2785
+ if (nativeBackedRollback) {
2786
+ this._suppressNextNativeSignalingState = "stable";
2787
+ try {
2788
+ this._ensureNativePeerConnection().setLocalDescription("rollback");
2789
+ } catch (error) {
2790
+ this._suppressNextNativeSignalingState = null;
2791
+ throw error;
2792
+ }
2793
+ }
2794
+ this._rollbackLocalDescription();
2795
+ this._localDescriptionSetByApi = hasDataMediaSection(this._localDescription);
2796
+ this._localIceCandidates = [];
2797
+ this._unregisterLocalDescriptionsForPairing();
2798
+ this._syncStatesFromNative();
2799
+ this._signalingState = "stable";
2800
+ if (rollingBackInitialOffer) {
2801
+ this._iceGatheringState = "new";
2802
+ }
2803
+ this._refreshIceRole();
2804
+ this._updateSctpTransport();
2805
+ if (rollingBackInitialOffer && previousGatheringState !== "new") {
2806
+ this.dispatchEvent(makeEvent("icegatheringstatechange"));
2807
+ this._iceTransport()?.dispatchEvent(makeEvent("gatheringstatechange"));
2808
+ }
2809
+ if (previousState !== this._signalingState) this._dispatchSignalingStateChange();
2810
+ await nextTask();
2811
+ if (this._suppressNextNativeSignalingState === "stable")
2812
+ this._suppressNextNativeSignalingState = null;
2813
+ return;
2814
+ }
2815
+ if (normalized?.type === "pranswer") {
2816
+ if (
2817
+ this._signalingState !== "have-remote-offer" &&
2818
+ this._signalingState !== "have-local-pranswer"
2819
+ ) {
2820
+ throw makeDOMException(
2821
+ "Cannot set a local pranswer in current signaling state",
2822
+ "InvalidStateError",
2823
+ );
2824
+ }
2825
+ const previousState = this._signalingState;
2826
+ this._setPendingLocalDescription(normalized);
2827
+ this._localDescriptionSetByApi = hasDataMediaSection(this._localDescription);
2828
+ this._registerLocalDescriptionForPairing();
2829
+ this._signalingState = "have-local-pranswer";
2830
+ this._refreshIceRole();
2831
+ this._updateSctpTransport();
2832
+ if (previousState !== this._signalingState) this._dispatchSignalingStateChange();
2833
+ await nextTask();
2834
+ return;
2835
+ }
2836
+ let alreadyAppliedAnswer = false;
2837
+ if (normalized?.type === "answer") {
2838
+ if (normalized.sdp === "" && this._lastCreatedAnswer) normalized = this._lastCreatedAnswer;
2839
+ const answerCreatedByThisPeer = description && description._webrtcNodeAnswerer === this;
2840
+ alreadyAppliedAnswer =
2841
+ this._localDescription?.type === "answer" &&
2842
+ (this._localDescription.sdp === normalized.sdp || answerCreatedByThisPeer);
2843
+ if (
2844
+ !alreadyAppliedAnswer &&
2845
+ this._signalingState !== "have-remote-offer" &&
2846
+ this._signalingState !== "have-local-pranswer"
2847
+ ) {
2848
+ throw makeDOMException(
2849
+ "Cannot set a local answer in current signaling state",
2850
+ "InvalidStateError",
2851
+ );
2852
+ }
2853
+ if (!this._lastCreatedAnswer || normalized.sdp !== this._lastCreatedAnswer.sdp) {
2854
+ throw makeDOMException(
2855
+ "Local answer does not match the last created answer",
2856
+ "InvalidModificationError",
2857
+ );
2858
+ }
2859
+ }
2860
+ if (alreadyAppliedAnswer) {
2861
+ this._localDescriptionSetByApi = hasDataMediaSection(this._localDescription);
2862
+ this._syncStatesFromNative();
2863
+ this._refreshIceRole();
2864
+ for (const candidate of this._pendingIce.splice(0)) await this.addIceCandidate(candidate);
2865
+ this._flushPendingRemoteCandidatesForNative();
2866
+ return;
2867
+ }
2868
+ if (normalized && isNoMediaSdp(normalized)) {
2869
+ await this._applyNoMediaLocalDescription(normalized);
2870
+ this._localDescriptionSetByApi = hasDataMediaSection(this._localDescription);
2871
+ return;
2872
+ }
2873
+ if (!normalized && type === "offer") {
2874
+ const offer =
2875
+ this._lastCreatedOffer ||
2876
+ new RTCSessionDescription(this._ensureNativePeerConnection().createOffer());
2877
+ if (isNoMediaSdp(offer)) {
2878
+ await this._applyNoMediaLocalDescription(offer);
2879
+ this._localDescriptionSetByApi = hasDataMediaSection(this._localDescription);
2880
+ return;
2881
+ }
2882
+ }
2883
+ if (!normalized && type === "answer" && isNoMediaSdp(this.remoteDescription)) {
2884
+ const answer =
2885
+ this._lastCreatedAnswer ||
2886
+ new RTCSessionDescription({
2887
+ type: "answer",
2888
+ sdp: this.remoteDescription.sdp,
2889
+ });
2890
+ await this._applyNoMediaLocalDescription(answer);
2891
+ this._localDescriptionSetByApi = hasDataMediaSection(this._localDescription);
2892
+ return;
2893
+ }
2894
+ if (type === "answer" && this._jsOnlyIceRestartRemoteOffer) {
2895
+ const answer =
2896
+ normalized ||
2897
+ this._lastCreatedAnswer ||
2898
+ new RTCSessionDescription(this._ensureNativePeerConnection().createAnswer());
2899
+ await this._applyJsOnlyLocalAnswer(answer);
2900
+ this._localDescriptionSetByApi = hasDataMediaSection(this._localDescription);
2901
+ return;
2902
+ }
2903
+ if (type === "offer" && this._shouldApplyDataOnlyLocalOffer(normalized)) {
2904
+ const offer = normalized || this._currentLocalDescription || this._lastCreatedOffer;
2905
+ await this._applyDataOnlyLocalOffer(offer);
2906
+ this._localDescriptionSetByApi = hasDataMediaSection(this._localDescription);
2907
+ return;
2908
+ }
2909
+ if (type === "answer" && this._shouldApplyDataOnlyLocalAnswer(normalized)) {
2910
+ const answer = normalized || this._currentLocalDescription || this._lastCreatedAnswer;
2911
+ await this._applyDataOnlyLocalAnswer(answer);
2912
+ this._localDescriptionSetByApi = hasDataMediaSection(this._localDescription);
2913
+ return;
2914
+ }
2915
+ const previousIceGatheringState = this._iceGatheringState;
2916
+ const previousSignalingState = this._signalingState;
2917
+ let appliedIceRestart = false;
2918
+ let manuallyUpdatedSignalingState = false;
2919
+ let usedJsOnlyIceRestart = false;
2920
+ if (
2921
+ this._localDescription?.type === type &&
2922
+ type !== "offer" &&
2923
+ !this._pendingRemoteDescription
2924
+ ) {
2925
+ this._syncStatesFromNative();
2926
+ } else if (this._preparedLocalDescription && type === this._preparedLocalDescription.type) {
2927
+ this._localDescription = this._preparedLocalDescription;
2928
+ this._preparedLocalDescription = null;
2929
+ this._nonstandardPreparedLocalDescriptionType = null;
2930
+ this._nonstandardLocalIceCredentials = null;
2931
+ this._syncStatesFromNative();
2932
+ this._scheduleNativeCandidateGathering();
2933
+ manuallyUpdatedSignalingState = true;
2934
+ } else {
2935
+ const hadIceRestartRequest =
2936
+ (this._iceRestartPending || jsOnlyIceRestartDescription) && type === "offer";
2937
+ const useJsOnlyIceRestart = hadIceRestartRequest && !this._canApplyNativeIceCredentials();
2938
+ if (useJsOnlyIceRestart) {
2939
+ const localDescription = new RTCSessionDescription(
2940
+ normalized ||
2941
+ this._lastCreatedOffer ||
2942
+ this._ensureNativePeerConnection().createOffer(),
2943
+ );
2944
+ this._localDescription = markJsOnlyIceRestart(localDescription);
2945
+ this._jsOnlyIceRestartOfferPending = true;
2946
+ this._signalingState = "have-local-offer";
2947
+ appliedIceRestart = true;
2948
+ manuallyUpdatedSignalingState = true;
2949
+ usedJsOnlyIceRestart = true;
2950
+ } else {
2951
+ const localDescriptionInit = this._localOfferInit(type);
2952
+ this._ensureNativePeerConnection().setLocalDescription(type, localDescriptionInit);
2953
+ appliedIceRestart = hadIceRestartRequest;
2954
+ const nativeDescription = this._ensureNativePeerConnection().localDescription();
2955
+ this._localDescription = nativeDescription
2956
+ ? new RTCSessionDescription(nativeDescription)
2957
+ : null;
2958
+ this._syncStatesFromNative();
2959
+ this._scheduleNativeCandidateGathering();
2960
+ }
2961
+ }
2962
+ if (type === "offer") {
2963
+ this._setPendingLocalDescription(this._localDescription);
2964
+ this._syncSignalingStateFromDescriptions();
2965
+ } else if (type === "answer") {
2966
+ this._commitRemoteDescription();
2967
+ this._commitLocalDescription(this._localDescription);
2968
+ this._syncSignalingStateFromDescriptions();
2969
+ for (const candidate of this._pendingIce.splice(0)) await this.addIceCandidate(candidate);
2970
+ this._flushPendingRemoteCandidatesForNative();
2971
+ }
2972
+ this._localDescriptionSetByApi = hasDataMediaSection(this._localDescription);
2973
+ this._clearNegotiationNeededIfDataMLineIsPresent();
2974
+ this._refreshIceRole();
2975
+ if (manuallyUpdatedSignalingState && previousSignalingState !== this._signalingState)
2976
+ this._dispatchSignalingStateChange();
2977
+ if (appliedIceRestart) {
2978
+ if (previousIceGatheringState === "complete") this._queueSyntheticIceRestartGathering();
2979
+ this._clearIceRestartRequest();
2980
+ }
2981
+ await nextTask();
2982
+ if (usedJsOnlyIceRestart) {
2983
+ this._registerLocalDescriptionForPairing();
2984
+ } else {
2985
+ await this._refreshLocalDescriptionAfterGatheringWindow();
2986
+ this._registerLocalDescriptionForPairing();
2987
+ }
2988
+ } catch (error) {
2989
+ throw mapNativeError(error, "InvalidStateError");
2990
+ } finally {
2991
+ this._finishPendingOperation();
2992
+ }
2993
+ }
2994
+
2995
+ async setRemoteDescription(description) {
2996
+ this._assertNotClosed();
2997
+ const jsOnlyIceRestartDescription = Boolean(description?._webrtcNodeJsOnlyIceRestart);
2998
+ const normalized = normalizeDescription(description);
2999
+ if (
3000
+ normalized.type === "answer" &&
3001
+ this._signalingState !== "have-local-offer" &&
3002
+ this._signalingState !== "have-remote-pranswer" &&
3003
+ !this._jsOnlyIceRestartOfferPending &&
3004
+ this._operationsPending === 0
3005
+ ) {
3006
+ throw makeDOMException(
3007
+ "Cannot set a remote answer in current signaling state",
3008
+ "InvalidStateError",
3009
+ );
3010
+ }
3011
+ if (
3012
+ normalized.type === "pranswer" &&
3013
+ this._signalingState !== "have-local-offer" &&
3014
+ this._signalingState !== "have-remote-pranswer" &&
3015
+ this._operationsPending === 0
3016
+ ) {
3017
+ throw makeDOMException(
3018
+ "Cannot set a remote pranswer in current signaling state",
3019
+ "InvalidStateError",
3020
+ );
3021
+ }
3022
+ if (
3023
+ normalized.type === "rollback" &&
3024
+ this._signalingState !== "have-remote-offer" &&
3025
+ this._operationsPending === 0
3026
+ ) {
3027
+ throw makeDOMException(
3028
+ "Cannot roll back a remote description in current signaling state",
3029
+ "InvalidStateError",
3030
+ );
3031
+ }
3032
+ this._operationsPending += 1;
3033
+ try {
3034
+ await nextTask();
3035
+ if (this._closed) return new Promise(() => {});
3036
+ if (
3037
+ normalized.type === "answer" &&
3038
+ this._signalingState !== "have-local-offer" &&
3039
+ this._signalingState !== "have-remote-pranswer" &&
3040
+ !this._jsOnlyIceRestartOfferPending
3041
+ ) {
3042
+ throw makeDOMException(
3043
+ "Cannot set a remote answer in current signaling state",
3044
+ "InvalidStateError",
3045
+ );
3046
+ }
3047
+ if (normalized.type === "pranswer") {
3048
+ if (
3049
+ this._signalingState !== "have-local-offer" &&
3050
+ this._signalingState !== "have-remote-pranswer"
3051
+ ) {
3052
+ throw makeDOMException(
3053
+ "Cannot set a remote pranswer in current signaling state",
3054
+ "InvalidStateError",
3055
+ );
3056
+ }
3057
+ const previousState = this._signalingState;
3058
+ this._setPendingRemoteDescription(normalized);
3059
+ this._pairWithRemoteDescription(this._remoteDescription);
3060
+ this._canTrickleIceCandidates = hasTrickleIceOption(normalized);
3061
+ this._signalingState = "have-remote-pranswer";
3062
+ this._refreshIceRole();
3063
+ this._updateSctpTransport();
3064
+ if (previousState !== this._signalingState) this._dispatchSignalingStateChange();
3065
+ await nextTask();
3066
+ return;
3067
+ }
3068
+ if (
3069
+ normalized.type === "offer" &&
3070
+ (this._signalingState === "have-local-offer" ||
3071
+ this._signalingState === "have-remote-pranswer")
3072
+ ) {
3073
+ await this._implicitRollbackLocalDescription();
3074
+ if (this._closed) return new Promise(() => {});
3075
+ }
3076
+ assertValidSdpSyntax(normalized);
3077
+ if (normalized.type === "rollback") {
3078
+ if (this._signalingState !== "have-remote-offer") {
3079
+ throw makeDOMException(
3080
+ "Cannot roll back a remote description in current signaling state",
3081
+ "InvalidStateError",
3082
+ );
3083
+ }
3084
+ const previousState = this._signalingState;
3085
+ const nativeBackedRollback =
3086
+ this._remoteDescription && !isNoMediaSdp(this._remoteDescription);
3087
+ if (nativeBackedRollback) {
3088
+ this._suppressNextNativeSignalingState = "stable";
3089
+ try {
3090
+ this._ensureNativePeerConnection().setRemoteDescription({ type: "rollback", sdp: "" });
3091
+ } catch (error) {
3092
+ this._suppressNextNativeSignalingState = null;
3093
+ throw error;
3094
+ }
3095
+ }
3096
+ this._rollbackRemoteDescription();
3097
+ this._remoteIceCandidates = [];
3098
+ if (this._pairedPeer?._pairedPeer === this) this._pairedPeer._pairedPeer = null;
3099
+ this._pairedPeer = null;
3100
+ this._selfRemoteDescription = false;
3101
+ this._syncStatesFromNative();
3102
+ this._signalingState = "stable";
3103
+ this._refreshIceRole();
3104
+ this._updateSctpTransport();
3105
+ if (previousState !== this._signalingState) this._dispatchSignalingStateChange();
3106
+ await nextTask();
3107
+ if (this._suppressNextNativeSignalingState === "stable")
3108
+ this._suppressNextNativeSignalingState = null;
3109
+ return;
3110
+ }
3111
+ if (
3112
+ normalized.type === "offer" &&
3113
+ this._isJsOnlyIceRestartRemoteOffer(normalized, jsOnlyIceRestartDescription)
3114
+ ) {
3115
+ const previousState = this._signalingState;
3116
+ this._setPendingRemoteDescription(markJsOnlyIceRestart(normalized));
3117
+ this._pairWithRemoteDescription(this._remoteDescription);
3118
+ this._canTrickleIceCandidates = hasTrickleIceOption(normalized);
3119
+ this._signalingState = "have-remote-offer";
3120
+ this._jsOnlyIceRestartRemoteOffer = true;
3121
+ this._armDataChannelNativeCloseSuppression();
3122
+ this._refreshIceRole();
3123
+ this._updateSctpTransport();
3124
+ if (previousState !== this._signalingState) this._dispatchSignalingStateChange();
3125
+ await nextTask();
3126
+ return;
3127
+ }
3128
+ if (
3129
+ normalized.type === "answer" &&
3130
+ (jsOnlyIceRestartDescription || this._jsOnlyIceRestartOfferPending)
3131
+ ) {
3132
+ const previousState = this._signalingState;
3133
+ let remoteDescription = normalized;
3134
+ if (description && description._webrtcNodeAnswerer) {
3135
+ remoteDescription = await description._webrtcNodeAnswerer._ensureLocalAnswerApplied();
3136
+ }
3137
+ this._setPendingRemoteDescription(markJsOnlyIceRestart(remoteDescription));
3138
+ this._commitLocalDescription();
3139
+ this._commitRemoteDescription(this._remoteDescription);
3140
+ this._canTrickleIceCandidates = hasTrickleIceOption(remoteDescription);
3141
+ this._signalingState = "stable";
3142
+ this._jsOnlyIceRestartOfferPending = false;
3143
+ this._clearIceRestartRequest();
3144
+ this._refreshIceRole();
3145
+ this._assignDataChannelIdsFromDtlsRole();
3146
+ this._updateSctpTransport();
3147
+ if (previousState !== this._signalingState) this._dispatchSignalingStateChange();
3148
+ await nextTask();
3149
+ return;
3150
+ }
3151
+ if (normalized.type === "offer" && this._shouldApplyDataOnlyRemoteOffer(normalized)) {
3152
+ const previousState = this._signalingState;
3153
+ this._setPendingRemoteDescription(normalized);
3154
+ this._pairWithRemoteDescription(this._remoteDescription);
3155
+ this._canTrickleIceCandidates = hasTrickleIceOption(normalized);
3156
+ this._syncSignalingStateFromDescriptions();
3157
+ this._refreshIceRole();
3158
+ this._updateSctpTransport();
3159
+ if (previousState !== this._signalingState) this._dispatchSignalingStateChange();
3160
+ await nextTask();
3161
+ return;
3162
+ }
3163
+ if (normalized.type === "answer" && this._shouldApplyDataOnlyRemoteAnswer(normalized)) {
3164
+ const previousState = this._signalingState;
3165
+ let remoteDescription = normalized;
3166
+ if (description && description._webrtcNodeAnswerer) {
3167
+ remoteDescription = await description._webrtcNodeAnswerer._ensureLocalAnswerApplied();
3168
+ }
3169
+ this._setPendingRemoteDescription(remoteDescription);
3170
+ this._commitLocalDescription();
3171
+ this._commitRemoteDescription(this._remoteDescription);
3172
+ this._canTrickleIceCandidates = hasTrickleIceOption(remoteDescription);
3173
+ this._syncSignalingStateFromDescriptions();
3174
+ this._refreshIceRole();
3175
+ this._assignDataChannelIdsFromDtlsRole();
3176
+ this._updateSctpTransport();
3177
+ if (previousState !== this._signalingState) this._dispatchSignalingStateChange();
3178
+ await nextTask();
3179
+ return;
3180
+ }
3181
+ if (isNoMediaSdp(normalized)) {
3182
+ if (normalized.type === "offer") {
3183
+ this._rollbackLocalDescription();
3184
+ this._setPendingRemoteDescription(normalized);
3185
+ } else if (normalized.type === "answer") {
3186
+ this._commitLocalDescription();
3187
+ this._commitRemoteDescription(normalized);
3188
+ } else {
3189
+ this._setPendingRemoteDescription(normalized);
3190
+ }
3191
+ this._pairWithRemoteDescription(this._remoteDescription);
3192
+ this._canTrickleIceCandidates = hasTrickleIceOption(normalized);
3193
+ if (normalized.type === "offer") {
3194
+ this._signalingState = "have-remote-offer";
3195
+ } else if (normalized.type === "answer") {
3196
+ this._signalingState = "stable";
3197
+ }
3198
+ this._refreshIceRole();
3199
+ this._updateSctpTransport();
3200
+ this._dispatchSignalingStateChange();
3201
+ await nextTask();
3202
+ return;
3203
+ }
3204
+ if (normalized.type === "offer" && this._signalingState === "have-remote-offer") {
3205
+ this._setPendingRemoteDescription(normalized);
3206
+ this._pairWithRemoteDescription(this._remoteDescription);
3207
+ this._canTrickleIceCandidates = hasTrickleIceOption(normalized);
3208
+ this._refreshIceRole();
3209
+ this._updateSctpTransport();
3210
+ await nextTask();
3211
+ return;
3212
+ }
3213
+ let remoteDescription = normalized;
3214
+ if (normalized.type === "answer" && description && description._webrtcNodeAnswerer) {
3215
+ remoteDescription = await description._webrtcNodeAnswerer._ensureLocalAnswerApplied();
3216
+ }
3217
+ const previousSignalingState = this._signalingState;
3218
+ let suppressedNativeSignalingState = null;
3219
+ let nativeRemoteDescription = remoteDescription;
3220
+ let deferredCandidatesForNative = [];
3221
+ if (normalized.type === "offer") {
3222
+ deferredCandidatesForNative = extractIceCandidatesFromDescription(remoteDescription);
3223
+ if (deferredCandidatesForNative.length > 0) {
3224
+ nativeRemoteDescription = stripIceCandidateLinesFromDescription(remoteDescription);
3225
+ }
3226
+ }
3227
+ this._ensureNativePeerConnection().setRemoteDescription(nativeRemoteDescription.toJSON());
3228
+ this._queuePendingRemoteCandidatesForNative(deferredCandidatesForNative);
3229
+ this._canTrickleIceCandidates = hasTrickleIceOption(remoteDescription);
3230
+ this._remoteDescription = new RTCSessionDescription(remoteDescription);
3231
+ this._pairWithRemoteDescription(this._remoteDescription);
3232
+ this._syncStatesFromNative();
3233
+ if (normalized.type === "offer") {
3234
+ this._rollbackLocalDescription();
3235
+ this._setPendingRemoteDescription(this._remoteDescription);
3236
+ this._syncSignalingStateFromDescriptions();
3237
+ } else if (normalized.type === "answer") {
3238
+ this._commitLocalDescription();
3239
+ this._commitRemoteDescription(this._remoteDescription);
3240
+ this._syncSignalingStateFromDescriptions();
3241
+ }
3242
+ this._refreshIceRole();
3243
+ this._assignDataChannelIdsFromDtlsRole();
3244
+ if (previousSignalingState !== this._signalingState) {
3245
+ suppressedNativeSignalingState = this._signalingState;
3246
+ this._suppressNextNativeSignalingState = suppressedNativeSignalingState;
3247
+ this._dispatchSignalingStateChange();
3248
+ }
3249
+ if (normalized.type !== "offer") {
3250
+ for (const candidate of this._pendingIce.splice(0)) await this.addIceCandidate(candidate);
3251
+ this._flushPendingRemoteCandidatesForNative();
3252
+ }
3253
+ await nextTask();
3254
+ if (
3255
+ suppressedNativeSignalingState !== null &&
3256
+ this._suppressNextNativeSignalingState === suppressedNativeSignalingState
3257
+ ) {
3258
+ this._suppressNextNativeSignalingState = null;
3259
+ }
3260
+ } catch (error) {
3261
+ throw mapNativeError(error, "InvalidStateError");
3262
+ } finally {
3263
+ this._finishPendingOperation();
3264
+ }
3265
+ }
3266
+
3267
+ async addIceCandidate(candidate = null) {
3268
+ this._assertNotClosed();
3269
+ const hasArgument = arguments.length > 0;
3270
+ if (!hasArgument && !this.remoteDescription && this._operationsPending === 0) {
3271
+ throw makeDOMException("Remote description is not set", "InvalidStateError");
3272
+ }
3273
+ if (candidate === null && hasArgument && !this.remoteDescription) return;
3274
+ if (candidate instanceof RTCIceCandidate && candidate._webrtcNodeLocalCandidate) {
3275
+ await this._addExchangedLocalCandidate(candidate);
3276
+ return;
3277
+ }
3278
+ const normalized = normalizeAddIceCandidateInput(candidate);
3279
+ if (!this.remoteDescription) {
3280
+ await delayInvalidStateIfOperationPending(this);
3281
+ if (!this.remoteDescription) {
3282
+ throw makeDOMException("Remote description is not set", "InvalidStateError");
3283
+ }
3284
+ }
3285
+ this._operationsPending += 1;
3286
+ try {
3287
+ await nextTask();
3288
+ const remoteDescription = appendRemoteCandidateToDescription(
3289
+ this._remoteDescription,
3290
+ normalized,
3291
+ );
3292
+ if (normalized.candidate === "") {
3293
+ this._refreshCurrentOrPendingRemoteDescription(remoteDescription);
3294
+ return;
3295
+ }
3296
+ const nativeCandidate = normalized.toJSON();
3297
+ if (nativeCandidate.sdpMid === null) {
3298
+ nativeCandidate.sdpMid = resolveCandidateMid(this._remoteDescription, normalized);
3299
+ }
3300
+ if (nativeCandidate.candidate) {
3301
+ this._rememberRemoteIceCandidate(
3302
+ new RTCIceCandidate({
3303
+ candidate: nativeCandidate.candidate,
3304
+ sdpMid: nativeCandidate.sdpMid,
3305
+ sdpMLineIndex: nativeCandidate.sdpMLineIndex,
3306
+ usernameFragment: nativeCandidate.usernameFragment,
3307
+ }),
3308
+ );
3309
+ this._markExplicitIceCandidateExchange();
3310
+ }
3311
+ if (this._shouldDeferRemoteCandidateUntilLocalAnswer()) {
3312
+ this._queuePendingRemoteCandidatesForNative([normalized]);
3313
+ this._refreshCurrentOrPendingRemoteDescription(remoteDescription);
3314
+ return;
3315
+ }
3316
+ this._ensureNativePeerConnection().addRemoteCandidate(nativeCandidate);
3317
+ this._refreshCurrentOrPendingRemoteDescription(remoteDescription);
3318
+ } catch (error) {
3319
+ throw mapNativeError(error, "OperationError");
3320
+ } finally {
3321
+ this._finishPendingOperation();
3322
+ }
3323
+ }
3324
+
3325
+ async _addExchangedLocalCandidate(candidate) {
3326
+ if (!candidate.candidate) return;
3327
+ this._sameProcessIceCandidateExchange = true;
3328
+ if (this._pairedPeer) this._pairedPeer._sameProcessIceCandidateExchange = true;
3329
+ this._rememberRemoteIceCandidate(candidate);
3330
+ this._markExplicitIceCandidateExchange();
3331
+ if (!this.remoteDescription || this._shouldDeferRemoteCandidateUntilLocalAnswer()) {
3332
+ if (!this._pendingIce.some((entry) => sameCandidate(entry, candidate))) {
3333
+ this._pendingIce.push(candidate);
3334
+ }
3335
+ return;
3336
+ }
3337
+
3338
+ if (this._remoteDescription?.sdp?.includes(candidate.candidate)) return;
3339
+ const nativeCandidate = candidate.toJSON();
3340
+ if (nativeCandidate.sdpMid === null) {
3341
+ nativeCandidate.sdpMid = resolveCandidateMid(this._remoteDescription, candidate);
3342
+ }
3343
+ try {
3344
+ this._ensureNativePeerConnection().addRemoteCandidate(nativeCandidate);
3345
+ this._refreshCurrentOrPendingRemoteDescription(
3346
+ appendRemoteCandidateToDescription(this._remoteDescription, candidate),
3347
+ );
3348
+ } catch {
3349
+ // Exchanged local candidates are delivered from event handlers that do
3350
+ // not await addIceCandidate(); keep them best-effort like browser ICE.
3351
+ }
3352
+ }
3353
+
3354
+ close() {
3355
+ if (this._closed) return;
3356
+ this._closed = true;
3357
+ const pairedPeer = this._pairedPeer;
3358
+ this._unregisterLocalDescriptionsForPairing();
3359
+ const nativePeer = this._native;
3360
+ if (nativePeer) {
3361
+ try {
3362
+ nativePeer.close();
3363
+ } catch {
3364
+ // JS-visible close state is already final; native teardown is best-effort.
3365
+ }
3366
+ }
3367
+ setImmediate(() => {
3368
+ if (pairedPeer && !pairedPeer._closed) pairedPeer._handleRemotePeerClosed();
3369
+ });
3370
+ this._connectionState = "closed";
3371
+ this._iceConnectionState = "closed";
3372
+ this._iceGatheringState = "new";
3373
+ this._deferredIceEvents = [];
3374
+ this._preparedLocalDescription = null;
3375
+ this._nonstandardPreparedLocalDescriptionType = null;
3376
+ this._nonstandardLocalIceCredentials = null;
3377
+ this._signalingState = "closed";
3378
+ this._updateSctpTransport();
3379
+ for (const channel of this._channels.values()) {
3380
+ if (channel.readyState !== "closed") channel._handleClose();
3381
+ }
3382
+ this._dispatchSignalingStateChange();
3383
+ this.dispatchEvent(makeEvent("iceconnectionstatechange"));
3384
+ this.dispatchEvent(makeEvent("connectionstatechange"));
3385
+ }
3386
+
3387
+ _registerLocalDescriptionForPairing() {
3388
+ const key = descriptionPairingKey(this._localDescription);
3389
+ if (!key) return;
3390
+ localDescriptionOwners.set(key, new WeakRef(this));
3391
+ if (!this._localDescriptionPairingKeys.has(key)) {
3392
+ localDescriptionOwnerFinalizer.register(this, key, this);
3393
+ }
3394
+ this._localDescriptionPairingKeys.add(key);
3395
+ }
3396
+
3397
+ _unregisterLocalDescriptionsForPairing() {
3398
+ localDescriptionOwnerFinalizer.unregister(this);
3399
+ for (const key of this._localDescriptionPairingKeys) {
3400
+ const owner = localDescriptionOwners.get(key)?.deref();
3401
+ if (!owner || owner === this) localDescriptionOwners.delete(key);
3402
+ }
3403
+ this._localDescriptionPairingKeys.clear();
3404
+ if (this._pairedPeer?._pairedPeer === this) this._pairedPeer._pairedPeer = null;
3405
+ this._pairedPeer = null;
3406
+ }
3407
+
3408
+ _pairWithRemoteDescription(description) {
3409
+ const key = descriptionPairingKey(description);
3410
+ if (!key) return;
3411
+ const peerRef = localDescriptionOwners.get(key);
3412
+ const peer = peerRef?.deref();
3413
+ const ownCreatedOffer =
3414
+ description?.type === "offer" && this._lastCreatedOffer?.sdp === description.sdp;
3415
+ if (!peer) {
3416
+ if (peerRef) localDescriptionOwners.delete(key);
3417
+ this._selfRemoteDescription = ownCreatedOffer;
3418
+ return;
3419
+ }
3420
+ if (peer === this) {
3421
+ this._selfRemoteDescription = true;
3422
+ return;
3423
+ }
3424
+ if (peer._closed) return;
3425
+ this._selfRemoteDescription = false;
3426
+ this._pairedPeer = peer;
3427
+ peer._pairedPeer = this;
3428
+ if (this._explicitIceCandidateExchange || peer._explicitIceCandidateExchange) {
3429
+ this._explicitIceCandidateExchange = true;
3430
+ peer._explicitIceCandidateExchange = true;
3431
+ }
3432
+ if (this._sameProcessIceCandidateExchange || peer._sameProcessIceCandidateExchange) {
3433
+ this._sameProcessIceCandidateExchange = true;
3434
+ peer._sameProcessIceCandidateExchange = true;
3435
+ }
3436
+ this._pairExistingDataChannels();
3437
+ peer._pairExistingDataChannels();
3438
+ this._scheduleDataChannelAnnouncementRepair();
3439
+ peer._scheduleDataChannelAnnouncementRepair();
3440
+ }
3441
+
3442
+ _markExplicitIceCandidateExchange() {
3443
+ this._explicitIceCandidateExchange = true;
3444
+ this._updateSctpTransport();
3445
+ if (this._pairedPeer && !this._pairedPeer._explicitIceCandidateExchange) {
3446
+ this._pairedPeer._explicitIceCandidateExchange = true;
3447
+ this._pairedPeer._scheduleSctpTransportUpdate();
3448
+ }
3449
+ }
3450
+
3451
+ _rememberLocalIceCandidate(candidate) {
3452
+ if (!candidate?.candidate) return;
3453
+ if (!this._localIceCandidates.some((entry) => sameCandidate(entry, candidate))) {
3454
+ this._localIceCandidates.push(candidate);
3455
+ }
3456
+ }
3457
+
3458
+ _rememberRemoteIceCandidate(candidate) {
3459
+ if (!candidate?.candidate) return;
3460
+ if (!this._remoteIceCandidates.some((entry) => sameCandidate(entry, candidate))) {
3461
+ this._remoteIceCandidates.push(candidate);
3462
+ }
3463
+ }
3464
+
3465
+ _refreshIceRole() {
3466
+ if (this._localDescription?.type === "offer" && this._remoteDescription?.type === "answer") {
3467
+ this._iceRole = "controlling";
3468
+ return;
3469
+ }
3470
+ if (this._remoteDescription?.type === "offer" && this._localDescription?.type === "answer") {
3471
+ this._iceRole = "controlled";
3472
+ return;
3473
+ }
3474
+ this._iceRole = "unknown";
3475
+ }
3476
+
3477
+ _iceTransport() {
3478
+ return this._sctpTransport?.transport?.iceTransport || null;
3479
+ }
3480
+
3481
+ _pairExistingDataChannels() {
3482
+ for (const channel of this._channels.values()) {
3483
+ const id = channel.id;
3484
+ if (id != null) this._pairDataChannelById(channel, id);
3485
+ }
3486
+ }
3487
+
3488
+ _pairDataChannelById(channel, id) {
3489
+ if (!this._pairedPeer || id == null || channel.readyState === "closed") return;
3490
+ for (const peerChannel of this._pairedPeer._channels.values()) {
3491
+ if (peerChannel.readyState === "closed") continue;
3492
+ if (peerChannel.id === id) {
3493
+ channel._pairedChannel = peerChannel;
3494
+ peerChannel._pairedChannel = channel;
3495
+ return;
3496
+ }
3497
+ }
3498
+ }
3499
+
3500
+ _handleRemotePeerClosed() {
3501
+ if (this._closed) return;
3502
+ this._connectionState = "disconnected";
3503
+ this._iceConnectionState = "disconnected";
3504
+ this._updateSctpTransport();
3505
+ this._iceTransport()?._forceState("disconnected");
3506
+ this.dispatchEvent(makeEvent("iceconnectionstatechange"));
3507
+ this.dispatchEvent(makeEvent("connectionstatechange"));
3508
+ this._closeChannelsOnPeerFailure({ includeDisconnected: true });
3509
+ }
3510
+
3511
+ _updateSctpTransport() {
3512
+ const hasData =
3513
+ hasDataMediaSection(this._localDescription) || hasDataMediaSection(this._remoteDescription);
3514
+ if (!hasData) {
3515
+ this._sctpConnectedTransitionReady = false;
3516
+ this._sctpTransport = null;
3517
+ return;
3518
+ }
3519
+
3520
+ if (!this._sctpTransport) this._sctpTransport = new RTCSctpTransport(kInternalConstruct, this);
3521
+ const closed =
3522
+ this._closed ||
3523
+ this._connectionState === "closed" ||
3524
+ this._iceConnectionState === "closed" ||
3525
+ this._connectionState === "failed" ||
3526
+ this._iceConnectionState === "failed" ||
3527
+ this._connectionState === "disconnected" ||
3528
+ this._iceConnectionState === "disconnected";
3529
+ const dataTransportNegotiated =
3530
+ hasDataMediaSection(this._localDescription) && hasDataMediaSection(this._remoteDescription);
3531
+ const pairedDataTransportNegotiated =
3532
+ this._pairedPeer &&
3533
+ hasDataMediaSection(this._pairedPeer._localDescription) &&
3534
+ hasDataMediaSection(this._pairedPeer._remoteDescription);
3535
+ const nativeTransportConnected =
3536
+ this._connectionState === "connected" ||
3537
+ this._iceConnectionState === "connected" ||
3538
+ this._iceConnectionState === "completed";
3539
+ const pairedNativeTransportConnected =
3540
+ this._pairedPeer &&
3541
+ (this._pairedPeer._connectionState === "connected" ||
3542
+ this._pairedPeer._iceConnectionState === "connected" ||
3543
+ this._pairedPeer._iceConnectionState === "completed");
3544
+ const nativeConnected =
3545
+ nativeTransportConnected && dataTransportNegotiated && !this._selfRemoteDescription;
3546
+ const sameProcessConnected =
3547
+ this._sameProcessIceCandidateExchange &&
3548
+ dataTransportNegotiated &&
3549
+ pairedDataTransportNegotiated &&
3550
+ (nativeTransportConnected || pairedNativeTransportConnected);
3551
+ const operationsSettled =
3552
+ (this._operationsPending === 0 &&
3553
+ (!this._pairedPeer || this._pairedPeer._operationsPending === 0)) ||
3554
+ this._sctpTransport.state === "connected";
3555
+ const shouldConnect = (nativeConnected || sameProcessConnected) && operationsSettled;
3556
+ let connected = shouldConnect;
3557
+ if (closed || !shouldConnect) this._sctpConnectedTransitionReady = false;
3558
+ if (
3559
+ shouldConnect &&
3560
+ this._sctpTransport.state !== "connected" &&
3561
+ !this._sctpConnectedTransitionReady
3562
+ ) {
3563
+ this._scheduleSctpConnectedTransition();
3564
+ connected = false;
3565
+ }
3566
+ this._sctpTransport._setLimits({
3567
+ maxMessageSize: this._currentSctpMaxMessageSize(),
3568
+ maxChannels: connected ? this._currentSctpMaxChannels() : null,
3569
+ });
3570
+ this._sctpTransport._setState(closed ? "closed" : connected ? "connected" : "connecting");
3571
+ if (connected || closed) this._sctpConnectPollDeadline = 0;
3572
+ if (connected) {
3573
+ this._scheduleConnectedStateRepair();
3574
+ this._scheduleDataChannelOpenRepair();
3575
+ this._scheduleDataChannelAnnouncementRepair();
3576
+ this._pairedPeer?._scheduleDataChannelAnnouncementRepair();
3577
+ }
3578
+ this._scheduleSctpConnectPollIfNeeded();
3579
+ }
3580
+
3581
+ _scheduleSctpConnectedTransition() {
3582
+ if (this._sctpConnectedTransitionScheduled) return;
3583
+ this._sctpConnectedTransitionScheduled = true;
3584
+ setImmediate(() => {
3585
+ this._sctpConnectedTransitionScheduled = false;
3586
+ if (this._closed || !this._sctpTransport) return;
3587
+ this._sctpConnectedTransitionReady = true;
3588
+ this._updateSctpTransport();
3589
+ });
3590
+ }
3591
+
3592
+ _shouldRepairConnectedState() {
3593
+ return Boolean(
3594
+ !this._closed &&
3595
+ this._sctpTransport?.state === "connected" &&
3596
+ this._sameProcessIceCandidateExchange &&
3597
+ this._hasNegotiatedDataTransport() &&
3598
+ this._pairedPeer?._hasNegotiatedDataTransport() &&
3599
+ this._operationsPending === 0 &&
3600
+ this._pairedPeer._operationsPending === 0 &&
3601
+ this._connectionState !== "failed" &&
3602
+ this._connectionState !== "disconnected" &&
3603
+ this._iceConnectionState !== "failed" &&
3604
+ this._iceConnectionState !== "disconnected" &&
3605
+ (this._connectionState !== "connected" ||
3606
+ !["connected", "completed"].includes(this._iceConnectionState)),
3607
+ );
3608
+ }
3609
+
3610
+ _scheduleConnectedStateRepair() {
3611
+ if (this._connectedStateRepairScheduled || !this._shouldRepairConnectedState()) return;
3612
+ this._connectedStateRepairScheduled = true;
3613
+ setTimeout(() => {
3614
+ this._connectedStateRepairScheduled = false;
3615
+ if (!this._shouldRepairConnectedState()) return;
3616
+
3617
+ if (this._iceConnectionState === "new") {
3618
+ this._iceConnectionState = "checking";
3619
+ this.dispatchEvent(makeEvent("iceconnectionstatechange"));
3620
+ this._iceTransport()?._handlePeerIceConnectionState("checking");
3621
+ }
3622
+ if (this._connectionState === "new") {
3623
+ this._connectionState = "connecting";
3624
+ this.dispatchEvent(makeEvent("connectionstatechange"));
3625
+ }
3626
+
3627
+ setTimeout(() => {
3628
+ if (!this._shouldRepairConnectedState()) return;
3629
+ if (!["connected", "completed"].includes(this._iceConnectionState)) {
3630
+ this._iceConnectionState = "connected";
3631
+ this.dispatchEvent(makeEvent("iceconnectionstatechange"));
3632
+ this._iceTransport()?._handlePeerIceConnectionState("connected");
3633
+ }
3634
+ if (this._connectionState !== "connected") {
3635
+ this._connectionState = "connected";
3636
+ this._updateSctpTransport();
3637
+ this.dispatchEvent(makeEvent("connectionstatechange"));
3638
+ }
3639
+ }, 0);
3640
+ }, 0);
3641
+ }
3642
+
3643
+ _hasNegotiatedDataTransport() {
3644
+ return (
3645
+ hasDataMediaSection(this._localDescription) && hasDataMediaSection(this._remoteDescription)
3646
+ );
3647
+ }
3648
+
3649
+ _hasExplicitlyNegotiatedDataTransport() {
3650
+ return this._localDescriptionSetByApi && this._hasNegotiatedDataTransport();
3651
+ }
3652
+
3653
+ _shouldDeferRemoteCandidateUntilLocalAnswer() {
3654
+ return (
3655
+ this._remoteDescription?.type === "offer" &&
3656
+ (this._signalingState === "have-remote-offer" ||
3657
+ this._pairedPeer?.signalingState === "have-local-offer" ||
3658
+ this._operationsPending > 0 ||
3659
+ this._pairedPeer?._operationsPending > 0)
3660
+ );
3661
+ }
3662
+
3663
+ _queuePendingRemoteCandidatesForNative(candidates) {
3664
+ for (const candidate of candidates) {
3665
+ if (!candidate?.candidate) continue;
3666
+ if (
3667
+ !this._pendingRemoteCandidatesForNative.some((entry) => sameCandidate(entry, candidate))
3668
+ ) {
3669
+ this._pendingRemoteCandidatesForNative.push(candidate);
3670
+ }
3671
+ }
3672
+ }
3673
+
3674
+ _flushPendingRemoteCandidatesForNative() {
3675
+ if (!this._remoteDescription || this._shouldDeferRemoteCandidateUntilLocalAnswer()) return;
3676
+ const candidates = this._pendingRemoteCandidatesForNative.splice(0);
3677
+ for (const candidate of candidates) {
3678
+ try {
3679
+ const nativeCandidate = candidate.toJSON();
3680
+ if (nativeCandidate.sdpMid === null) {
3681
+ nativeCandidate.sdpMid = resolveCandidateMid(this._remoteDescription, candidate);
3682
+ }
3683
+ this._ensureNativePeerConnection().addRemoteCandidate(nativeCandidate);
3684
+ } catch {
3685
+ // Same-process and inline SDP candidate races are best-effort.
3686
+ }
3687
+ }
3688
+ }
3689
+
3690
+ _finishPendingOperation() {
3691
+ this._operationsPending = Math.max(0, this._operationsPending - 1);
3692
+ if (this._operationsPending === 0) {
3693
+ this._scheduleSctpTransportUpdate();
3694
+ if (this._pairedPeer && !this._pairedPeer._closed) {
3695
+ this._pairedPeer._scheduleSctpTransportUpdate();
3696
+ }
3697
+ this._flushPendingRemoteCandidatesForNative();
3698
+ this._pairedPeer?._flushPendingRemoteCandidatesForNative();
3699
+ this._scheduleDeferredIceEventFlush();
3700
+ const callbacks = this._operationIdleCallbacks.splice(0);
3701
+ for (const callback of callbacks) setImmediate(callback);
3702
+ }
3703
+ }
3704
+
3705
+ _afterOperationsIdle(callback) {
3706
+ if (this._closed || this._operationsPending === 0) {
3707
+ setImmediate(callback);
3708
+ return;
3709
+ }
3710
+ this._operationIdleCallbacks.push(callback);
3711
+ }
3712
+
3713
+ _shouldDeferIceEvent(event) {
3714
+ if (this._processingDeferredIceEvent || this._operationsPending === 0) return false;
3715
+ return event.type === "localcandidate" || event.type === "icegatheringstatechange";
3716
+ }
3717
+
3718
+ _scheduleDeferredIceEventFlush() {
3719
+ if (this._iceEventFlushScheduled || this._deferredIceEvents.length === 0) return;
3720
+ this._iceEventFlushScheduled = true;
3721
+ setImmediate(() => {
3722
+ this._iceEventFlushScheduled = false;
3723
+ if (this._closed) {
3724
+ this._deferredIceEvents = [];
3725
+ this._flushIceEventIdleCallbacks();
3726
+ return;
3727
+ }
3728
+ if (this._operationsPending > 0) {
3729
+ this._scheduleDeferredIceEventFlush();
3730
+ return;
3731
+ }
3732
+ const event = this._deferredIceEvents.shift();
3733
+ this._processingDeferredIceEvent = true;
3734
+ try {
3735
+ if (event) this._handleNativeEvent(event);
3736
+ } finally {
3737
+ this._processingDeferredIceEvent = false;
3738
+ }
3739
+ if (this._deferredIceEvents.length) this._scheduleDeferredIceEventFlush();
3740
+ else this._flushIceEventIdleCallbacks();
3741
+ });
3742
+ }
3743
+
3744
+ _hasPendingDeferredIceEvents() {
3745
+ return (
3746
+ this._deferredIceEvents.length > 0 ||
3747
+ this._iceEventFlushScheduled ||
3748
+ this._processingDeferredIceEvent
3749
+ );
3750
+ }
3751
+
3752
+ _afterDeferredIceEventsFlushed(callback) {
3753
+ if (this._closed || !this._hasPendingDeferredIceEvents()) {
3754
+ setImmediate(callback);
3755
+ return;
3756
+ }
3757
+ this._iceEventIdleCallbacks.push(callback);
3758
+ this._scheduleDeferredIceEventFlush();
3759
+ }
3760
+
3761
+ _flushIceEventIdleCallbacks() {
3762
+ if (this._hasPendingDeferredIceEvents()) return;
3763
+ const callbacks = this._iceEventIdleCallbacks.splice(0);
3764
+ for (const callback of callbacks) setImmediate(callback);
3765
+ }
3766
+
3767
+ _queueSyntheticIceRestartGathering() {
3768
+ const hasGatheringStateEvent = this._deferredIceEvents.some(
3769
+ (event) => event.type === "icegatheringstatechange",
3770
+ );
3771
+ if (hasGatheringStateEvent) return;
3772
+ this._deferredIceEvents.push(
3773
+ { type: "icegatheringstatechange", state: "gathering" },
3774
+ { type: "icegatheringstatechange", state: "complete" },
3775
+ );
3776
+ }
3777
+
3778
+ _scheduleSctpTransportUpdate() {
3779
+ if (this._sctpTransportUpdateScheduled) return;
3780
+ this._sctpTransportUpdateScheduled = true;
3781
+ setImmediate(() => {
3782
+ this._sctpTransportUpdateScheduled = false;
3783
+ if (
3784
+ !this._closed &&
3785
+ this._connectionState !== "closed" &&
3786
+ this._iceConnectionState !== "closed" &&
3787
+ this._native
3788
+ ) {
3789
+ this._connectionState = this._native.connectionState;
3790
+ this._iceConnectionState = this._native.iceConnectionState;
3791
+ }
3792
+ this._updateSctpTransport();
3793
+ });
3794
+ }
3795
+
3796
+ _scheduleSctpConnectPollIfNeeded() {
3797
+ if (
3798
+ this._closed ||
3799
+ this._operationsPending > 0 ||
3800
+ this._pairedPeer?._operationsPending > 0 ||
3801
+ this._sctpTransport?.state !== "connecting" ||
3802
+ !hasDataMediaSection(this._localDescription) ||
3803
+ !hasDataMediaSection(this._remoteDescription)
3804
+ ) {
3805
+ return;
3806
+ }
3807
+
3808
+ const now = Date.now();
3809
+ if (!this._sctpConnectPollDeadline) {
3810
+ this._sctpConnectPollDeadline = now + SCTP_CONNECT_POLL_TIMEOUT_MS;
3811
+ }
3812
+ if (this._sctpConnectPollScheduled || now >= this._sctpConnectPollDeadline) return;
3813
+ this._sctpConnectPollScheduled = true;
3814
+ setTimeout(() => {
3815
+ this._sctpConnectPollScheduled = false;
3816
+ if (this._closed || this._sctpTransport?.state !== "connecting") return;
3817
+ this._scheduleSctpTransportUpdate();
3818
+ }, SCTP_CONNECT_POLL_INTERVAL_MS);
3819
+ }
3820
+
3821
+ _scheduleDataChannelOpenRepair() {
3822
+ if (this._closed || this._dataChannelOpenRepairScheduled) return;
3823
+ if (this._sctpTransport?.state !== "connected") return;
3824
+ const now = Date.now();
3825
+ if (!this._dataChannelOpenRepairDeadline) {
3826
+ this._dataChannelOpenRepairDeadline = now + DATA_CHANNEL_OPEN_REPAIR_TIMEOUT_MS;
3827
+ }
3828
+ if (now >= this._dataChannelOpenRepairDeadline) return;
3829
+ this._dataChannelOpenRepairScheduled = true;
3830
+ setTimeout(() => {
3831
+ this._dataChannelOpenRepairScheduled = false;
3832
+ if (this._closed || this._sctpTransport?.state !== "connected") return;
3833
+ let hasConnectingChannel = false;
3834
+ for (const channel of this._channels.values()) {
3835
+ if (channel.readyState === "connecting") {
3836
+ hasConnectingChannel = true;
3837
+ channel._repairMissedOpenEvent();
3838
+ }
3839
+ }
3840
+ if (hasConnectingChannel) {
3841
+ this._scheduleDataChannelOpenRepair();
3842
+ } else {
3843
+ this._dataChannelOpenRepairDeadline = 0;
3844
+ }
3845
+ }, DATA_CHANNEL_OPEN_REPAIR_INTERVAL_MS);
3846
+ }
3847
+
3848
+ _scheduleDataChannelAnnouncementRepair() {
3849
+ if (this._closed || this._dataChannelAnnouncementRepairScheduled) return;
3850
+ if (!this._hasDataChannelAnnouncementRepairCandidates()) {
3851
+ this._dataChannelAnnouncementRepairReadyAt = 0;
3852
+ this._dataChannelAnnouncementRepairDeadline = 0;
3853
+ return;
3854
+ }
3855
+ const now = Date.now();
3856
+ const canRepair = this._canRepairDataChannelAnnouncements();
3857
+ if (canRepair && !this._dataChannelAnnouncementRepairDeadline) {
3858
+ this._dataChannelAnnouncementRepairReadyAt = now + DATA_CHANNEL_ANNOUNCEMENT_REPAIR_GRACE_MS;
3859
+ this._dataChannelAnnouncementRepairDeadline =
3860
+ now + DATA_CHANNEL_ANNOUNCEMENT_REPAIR_TIMEOUT_MS;
3861
+ }
3862
+ if (canRepair && now >= this._dataChannelAnnouncementRepairDeadline) {
3863
+ this._dataChannelAnnouncementRepairReadyAt = 0;
3864
+ this._dataChannelAnnouncementRepairDeadline = 0;
3865
+ return;
3866
+ }
3867
+ this._dataChannelAnnouncementRepairScheduled = true;
3868
+ setTimeout(() => {
3869
+ this._dataChannelAnnouncementRepairScheduled = false;
3870
+ if (this._closed) return;
3871
+ const repairable = this._canRepairDataChannelAnnouncements();
3872
+ if (repairable && !this._dataChannelAnnouncementRepairDeadline) {
3873
+ const now = Date.now();
3874
+ this._dataChannelAnnouncementRepairReadyAt =
3875
+ now + DATA_CHANNEL_ANNOUNCEMENT_REPAIR_GRACE_MS;
3876
+ this._dataChannelAnnouncementRepairDeadline =
3877
+ now + DATA_CHANNEL_ANNOUNCEMENT_REPAIR_TIMEOUT_MS;
3878
+ }
3879
+ const canCreateSyntheticAnnouncement =
3880
+ this._pendingSyntheticDataChannelAnnouncements.size > 0 ||
3881
+ Date.now() >= this._dataChannelAnnouncementRepairReadyAt;
3882
+ const hasWork = repairable
3883
+ ? canCreateSyntheticAnnouncement
3884
+ ? this._repairMissingDataChannelAnnouncements()
3885
+ : this._hasDataChannelAnnouncementRepairCandidates()
3886
+ : this._hasDataChannelAnnouncementRepairCandidates();
3887
+ if (hasWork) {
3888
+ this._scheduleDataChannelAnnouncementRepair();
3889
+ } else {
3890
+ this._dataChannelAnnouncementRepairReadyAt = 0;
3891
+ this._dataChannelAnnouncementRepairDeadline = 0;
3892
+ }
3893
+ }, DATA_CHANNEL_ANNOUNCEMENT_REPAIR_INTERVAL_MS);
3894
+ }
3895
+
3896
+ _canRepairDataChannelAnnouncements() {
3897
+ return Boolean(
3898
+ this._pairedPeer &&
3899
+ !this._pairedPeer._closed &&
3900
+ this._operationsPending === 0 &&
3901
+ this._pairedPeer._operationsPending === 0 &&
3902
+ this._hasNegotiatedDataTransport() &&
3903
+ this._pairedPeer._hasNegotiatedDataTransport(),
3904
+ );
3905
+ }
3906
+
3907
+ _hasDataChannelAnnouncementRepairCandidates() {
3908
+ if (!this._pairedPeer || this._pairedPeer._closed) return false;
3909
+ if (this._pendingSyntheticDataChannelAnnouncements.size > 0) return true;
3910
+ for (const sourceChannel of this._pairedPeer._channels.values()) {
3911
+ if (
3912
+ !sourceChannel._createdLocally ||
3913
+ sourceChannel.negotiated ||
3914
+ sourceChannel.readyState === "closed"
3915
+ ) {
3916
+ continue;
3917
+ }
3918
+ const id = sourceChannel._effectiveId();
3919
+ if (id == null || !this._hasRemoteDataChannelForId(id)) return true;
3920
+ }
3921
+ return false;
3922
+ }
3923
+
3924
+ _repairMissingDataChannelAnnouncements() {
3925
+ if (!this._pairedPeer || this._pairedPeer._closed) return false;
3926
+ let hasPendingWork = false;
3927
+
3928
+ for (const [id, channel] of this._pendingSyntheticDataChannelAnnouncements) {
3929
+ if (channel.readyState === "closed") {
3930
+ this._pendingSyntheticDataChannelAnnouncements.delete(id);
3931
+ continue;
3932
+ }
3933
+ if (!channel._native.isOpen) {
3934
+ hasPendingWork = true;
3935
+ continue;
3936
+ }
3937
+ channel._readyState = "open";
3938
+ channel._openEventPending = true;
3939
+ channel._announcementPending = true;
3940
+ const sourceChannel = channel._pairedChannel;
3941
+ if (sourceChannel?.readyState === "connecting") {
3942
+ sourceChannel._readyState = "open";
3943
+ sourceChannel._pc._registerDataChannelId(sourceChannel);
3944
+ sourceChannel._dispatchOpenEvent();
3945
+ }
3946
+ this._remoteAnnouncedDataChannelIds.add(id);
3947
+ this._pendingSyntheticDataChannelAnnouncements.delete(id);
3948
+ this._pendingDataChannelEvents.push(new RTCDataChannelEvent("datachannel", { channel }));
3949
+ this._scheduleDataChannelFlush();
3950
+ }
3951
+
3952
+ for (const sourceChannel of this._pairedPeer._channels.values()) {
3953
+ if (
3954
+ !sourceChannel._createdLocally ||
3955
+ sourceChannel.negotiated ||
3956
+ sourceChannel.readyState === "closed"
3957
+ ) {
3958
+ continue;
3959
+ }
3960
+ let id = sourceChannel.id;
3961
+ if (id == null) {
3962
+ this._assignSyntheticDataChannelIdIfNeeded(sourceChannel);
3963
+ id = sourceChannel.id;
3964
+ }
3965
+ if (id == null) {
3966
+ hasPendingWork = true;
3967
+ continue;
3968
+ }
3969
+ if (this._hasRemoteDataChannelForId(id)) continue;
3970
+ const channel = this._createSyntheticIncomingDataChannel(sourceChannel, id);
3971
+ if (channel) hasPendingWork = true;
3972
+ }
3973
+
3974
+ return hasPendingWork || this._pendingSyntheticDataChannelAnnouncements.size > 0;
3975
+ }
3976
+
3977
+ _assignSyntheticDataChannelIdIfNeeded(channel) {
3978
+ if (channel.negotiated || channel._effectiveId() != null || channel.readyState === "closed") {
3979
+ return;
3980
+ }
3981
+ const parity = channel._pc._dataChannelIdParityFromDtlsRole() ?? 1;
3982
+ const id = channel._pc._nextAvailableDataChannelId(parity);
3983
+ if (id != null) channel._assignId(id);
3984
+ }
3985
+
3986
+ _hasRemoteDataChannelForId(id) {
3987
+ if (
3988
+ this._remoteAnnouncedDataChannelIds.has(id) ||
3989
+ this._pendingSyntheticDataChannelAnnouncements.has(id)
3990
+ ) {
3991
+ return true;
3992
+ }
3993
+ for (const channel of this._channels.values()) {
3994
+ if (!channel._createdLocally && channel.readyState !== "closed" && channel.id === id)
3995
+ return true;
3996
+ }
3997
+ return false;
3998
+ }
3999
+
4000
+ _syntheticIncomingDataChannelForId(id) {
4001
+ const pending = this._pendingSyntheticDataChannelAnnouncements.get(id);
4002
+ if (pending && pending.readyState !== "closed") return pending;
4003
+ for (const event of this._pendingDataChannelEvents) {
4004
+ const channel = event.channel;
4005
+ if (channel?._syntheticIncoming && channel.readyState !== "closed" && channel.id === id) {
4006
+ return channel;
4007
+ }
4008
+ }
4009
+ for (const channel of this._channels.values()) {
4010
+ if (channel._syntheticIncoming && channel.readyState !== "closed" && channel.id === id) {
4011
+ return channel;
4012
+ }
4013
+ }
4014
+ return null;
4015
+ }
4016
+
4017
+ _hasPendingDataChannelEventForId(id) {
4018
+ return this._pendingDataChannelEvents.some((event) => {
4019
+ const channel = event.channel;
4020
+ const channelId =
4021
+ typeof channel?._effectiveId === "function" ? channel._effectiveId() : channel?.id;
4022
+ return channelId === id;
4023
+ });
4024
+ }
4025
+
4026
+ _hasSettledDataChannelAnnouncement(id) {
4027
+ if (id == null) return false;
4028
+ if (
4029
+ this._pendingSyntheticDataChannelAnnouncements.has(id) ||
4030
+ this._hasPendingDataChannelEventForId(id)
4031
+ ) {
4032
+ return false;
4033
+ }
4034
+ if (this._remoteAnnouncedDataChannelIds.has(id)) return true;
4035
+ for (const channel of this._channels.values()) {
4036
+ if (!channel._createdLocally && channel.readyState !== "closed" && channel.id === id) {
4037
+ return true;
4038
+ }
4039
+ }
4040
+ return false;
4041
+ }
4042
+
4043
+ _afterDataChannelAnnouncementSettled(id, callback) {
4044
+ const deadline = Date.now() + DATA_CHANNEL_ANNOUNCEMENT_REPAIR_TIMEOUT_MS;
4045
+ const poll = () => {
4046
+ const settled = this._hasSettledDataChannelAnnouncement(id);
4047
+ if (
4048
+ settled ||
4049
+ this._closed ||
4050
+ !this._hasEventConsumer("datachannel") ||
4051
+ Date.now() >= deadline
4052
+ ) {
4053
+ setTimeout(() => callback(settled), 0);
4054
+ return;
4055
+ }
4056
+ this._scheduleDataChannelAnnouncementRepair();
4057
+ this._scheduleDataChannelFlush();
4058
+ setTimeout(poll, DATA_CHANNEL_ANNOUNCEMENT_REPAIR_INTERVAL_MS);
4059
+ };
4060
+ setTimeout(poll, 0);
4061
+ }
4062
+
4063
+ _createSyntheticIncomingDataChannel(sourceChannel, id) {
4064
+ const options = {
4065
+ ordered: sourceChannel.ordered,
4066
+ maxPacketLifeTime: sourceChannel.maxPacketLifeTime,
4067
+ maxRetransmits: sourceChannel.maxRetransmits,
4068
+ protocol: sourceChannel.protocol,
4069
+ negotiated: true,
4070
+ id,
4071
+ };
4072
+ const nativeChannel = new SyntheticNativeDataChannel(sourceChannel.label, options);
4073
+ const channel = RTCDataChannel._fromNative(this, nativeChannel, undefined, id);
4074
+ channel._createdLocally = false;
4075
+ channel._negotiatedOverride = false;
4076
+ channel._syntheticIncoming = true;
4077
+ channel._pairedChannel = sourceChannel;
4078
+ sourceChannel._pairedChannel = channel;
4079
+ this._pendingSyntheticDataChannelAnnouncements.set(id, channel);
4080
+ return channel;
4081
+ }
4082
+
4083
+ _currentSctpMaxMessageSize() {
4084
+ if (!this._localDescription || !this._remoteDescription) return null;
4085
+ if (
4086
+ !hasDataMediaSection(this._localDescription) ||
4087
+ !hasDataMediaSection(this._remoteDescription)
4088
+ )
4089
+ return null;
4090
+ if (this._selfRemoteDescription && !this._explicitIceCandidateExchange) return null;
4091
+ const localLimit =
4092
+ maxMessageSizeFromSdp(this._localDescription) || DEFAULT_SCTP_MAX_MESSAGE_SIZE;
4093
+ const remoteLimit = maxMessageSizeFromSdp(this._remoteDescription);
4094
+ if (remoteLimit === null) return Math.min(65536, localLimit);
4095
+ if (remoteLimit === 0) return localLimit || Number.POSITIVE_INFINITY;
4096
+ return localLimit === 0 ? remoteLimit : Math.min(remoteLimit, localLimit);
4097
+ }
4098
+
4099
+ _currentSctpMaxChannels() {
4100
+ const connected =
4101
+ this._connectionState === "connected" || this._sctpTransport?.state === "connected";
4102
+ if (!connected || this._selfRemoteDescription) return null;
4103
+ if (!this._native) return null;
4104
+ const maxId = Number(this._native.maxDataChannelId);
4105
+ return Number.isFinite(maxId) && maxId >= 0 ? maxId + 1 : LIBDATACHANNEL_SCTP_MAX_CHANNELS;
4106
+ }
4107
+
4108
+ _implicitLocalDescriptionType() {
4109
+ return this._signalingState === "have-remote-offer" ? "answer" : "offer";
4110
+ }
4111
+
4112
+ _descriptionSignalingState() {
4113
+ if (this._closed) return "closed";
4114
+ if (this._pendingLocalDescription?.type === "offer") return "have-local-offer";
4115
+ if (this._pendingRemoteDescription?.type === "offer") return "have-remote-offer";
4116
+ if (this._pendingLocalDescription?.type === "pranswer") return "have-local-pranswer";
4117
+ if (this._pendingRemoteDescription?.type === "pranswer") return "have-remote-pranswer";
4118
+ return "stable";
4119
+ }
4120
+
4121
+ _syncSignalingStateFromDescriptions() {
4122
+ if (this._jsOnlyIceRestartOfferPending) {
4123
+ this._signalingState = "have-local-offer";
4124
+ return;
4125
+ }
4126
+ this._signalingState = this._descriptionSignalingState();
4127
+ }
4128
+
4129
+ _dispatchSignalingStateChange() {
4130
+ this._lastDispatchedSignalingState = this._signalingState;
4131
+ this.dispatchEvent(makeEvent("signalingstatechange"));
4132
+ }
4133
+
4134
+ _setPendingLocalDescription(description) {
4135
+ this._pendingLocalDescription = description;
4136
+ this._localDescription = description || this._currentLocalDescription;
4137
+ }
4138
+
4139
+ _commitLocalDescription(description = this._pendingLocalDescription || this._localDescription) {
4140
+ if (description) this._currentLocalDescription = description;
4141
+ this._pendingLocalDescription = null;
4142
+ this._localDescription = this._currentLocalDescription;
4143
+ }
4144
+
4145
+ _rollbackLocalDescription() {
4146
+ this._pendingLocalDescription = null;
4147
+ this._localDescription = this._currentLocalDescription;
4148
+ }
4149
+
4150
+ _setPendingRemoteDescription(description) {
4151
+ this._pendingRemoteDescription = description;
4152
+ this._remoteDescription = description || this._currentRemoteDescription;
4153
+ }
4154
+
4155
+ _commitRemoteDescription(
4156
+ description = this._pendingRemoteDescription || this._remoteDescription,
4157
+ ) {
4158
+ if (description) this._currentRemoteDescription = description;
4159
+ this._pendingRemoteDescription = null;
4160
+ this._remoteDescription = this._currentRemoteDescription;
4161
+ }
4162
+
4163
+ _rollbackRemoteDescription() {
4164
+ this._pendingRemoteDescription = null;
4165
+ this._remoteDescription = this._currentRemoteDescription;
4166
+ }
4167
+
4168
+ async _implicitRollbackLocalDescription() {
4169
+ const previousState = this._signalingState;
4170
+ const previousGatheringState = this._iceGatheringState;
4171
+ const rollingBackInitialOffer = !this._currentLocalDescription;
4172
+ const nativeBackedRollback = this._localDescription && !isNoMediaSdp(this._localDescription);
4173
+ if (nativeBackedRollback) {
4174
+ this._suppressNextNativeSignalingState = "stable";
4175
+ try {
4176
+ this._ensureNativePeerConnection().setLocalDescription("rollback");
4177
+ } catch (error) {
4178
+ this._suppressNextNativeSignalingState = null;
4179
+ throw error;
4180
+ }
4181
+ }
4182
+ this._rollbackLocalDescription();
4183
+ this._localIceCandidates = [];
4184
+ this._unregisterLocalDescriptionsForPairing();
4185
+ this._syncStatesFromNative();
4186
+ this._signalingState = "stable";
4187
+ if (rollingBackInitialOffer) this._iceGatheringState = "new";
4188
+ this._refreshIceRole();
4189
+ this._updateSctpTransport();
4190
+ if (rollingBackInitialOffer && previousGatheringState !== "new") {
4191
+ this.dispatchEvent(makeEvent("icegatheringstatechange"));
4192
+ this._iceTransport()?.dispatchEvent(makeEvent("gatheringstatechange"));
4193
+ }
4194
+ if (previousState !== this._signalingState) this._dispatchSignalingStateChange();
4195
+ await nextTask();
4196
+ if (this._suppressNextNativeSignalingState === "stable")
4197
+ this._suppressNextNativeSignalingState = null;
4198
+ }
4199
+
4200
+ _refreshCurrentOrPendingLocalDescription(description) {
4201
+ if (!description) return;
4202
+ this._localDescription = description;
4203
+ if (this._pendingLocalDescription?.type === description.type) {
4204
+ this._pendingLocalDescription = description;
4205
+ } else {
4206
+ this._currentLocalDescription = description;
4207
+ }
4208
+ }
4209
+
4210
+ _refreshCurrentOrPendingRemoteDescription(description) {
4211
+ if (!description) return;
4212
+ this._remoteDescription = description;
4213
+ if (this._pendingRemoteDescription?.type === description.type) {
4214
+ this._pendingRemoteDescription = description;
4215
+ } else {
4216
+ this._currentRemoteDescription = description;
4217
+ }
4218
+ }
4219
+
4220
+ _ensureIceRestartCredentials() {
4221
+ if (!this._pendingIceRestartCredentials) {
4222
+ this._pendingIceRestartCredentials = createIceRestartCredentials();
4223
+ }
4224
+ return this._pendingIceRestartCredentials;
4225
+ }
4226
+
4227
+ _setNonstandardLocalIceCredentials(credentials) {
4228
+ this._assertNotClosed();
4229
+ if (credentials === null || typeof credentials !== "object") {
4230
+ throw new TypeError("ICE credentials must be an object");
4231
+ }
4232
+ const iceUfrag = credentials.iceUfrag;
4233
+ const icePwd = credentials.icePwd;
4234
+ if (typeof iceUfrag !== "string" || iceUfrag.length < 4) {
4235
+ throw new TypeError("iceUfrag must contain at least 4 characters");
4236
+ }
4237
+ if (typeof icePwd !== "string" || icePwd.length < 22) {
4238
+ throw new TypeError("icePwd must contain at least 22 characters");
4239
+ }
4240
+ if (byteLength(iceUfrag) > 256 || byteLength(icePwd) > 256) {
4241
+ throw new TypeError("ICE credentials must not exceed 256 bytes");
4242
+ }
4243
+ if (!/^[A-Za-z0-9+/]+$/.test(iceUfrag) || !/^[A-Za-z0-9+/]+$/.test(icePwd)) {
4244
+ throw new TypeError("ICE credentials may contain only ASCII letters, digits, +, or /");
4245
+ }
4246
+ if (this._nonstandardPreparedLocalDescriptionType) {
4247
+ const current = this._nonstandardLocalIceCredentials;
4248
+ if (current?.iceUfrag === iceUfrag && current?.icePwd === icePwd) return;
4249
+ throw makeDOMException(
4250
+ "Local ICE credentials have already been applied",
4251
+ "InvalidStateError",
4252
+ );
4253
+ }
4254
+ if (!this._canApplyNativeIceCredentials()) {
4255
+ throw makeDOMException(
4256
+ "Explicit local ICE credentials must be set before the first local description",
4257
+ "InvalidStateError",
4258
+ );
4259
+ }
4260
+ this._nonstandardLocalIceCredentials = { iceUfrag, icePwd };
4261
+ }
4262
+
4263
+ _prepareNonstandardLocalDescription(type) {
4264
+ if (!this._nonstandardLocalIceCredentials) return null;
4265
+ if (this._nonstandardPreparedLocalDescriptionType) {
4266
+ if (this._nonstandardPreparedLocalDescriptionType !== type) {
4267
+ throw makeDOMException(
4268
+ "Explicit local ICE credentials were applied to another description type",
4269
+ "InvalidStateError",
4270
+ );
4271
+ }
4272
+ return this._preparedLocalDescription?.toJSON() ?? null;
4273
+ }
4274
+
4275
+ this._nonstandardPreparedLocalDescriptionType = type;
4276
+ const nativeSignalingState = type === "offer" ? "have-local-offer" : "stable";
4277
+ this._suppressNextNativeSignalingState = nativeSignalingState;
4278
+ try {
4279
+ const nativePeerConnection = this._ensureNativePeerConnection();
4280
+ nativePeerConnection.setLocalDescription(type, this._nonstandardLocalIceCredentials);
4281
+ const description = nativePeerConnection.localDescription();
4282
+ if (!description) {
4283
+ throw new Error("libdatachannel did not generate a local description");
4284
+ }
4285
+ this._preparedLocalDescription = new RTCSessionDescription(description);
4286
+ return this._preparedLocalDescription.toJSON();
4287
+ } catch (error) {
4288
+ this._nonstandardPreparedLocalDescriptionType = null;
4289
+ this._preparedLocalDescription = null;
4290
+ if (this._suppressNextNativeSignalingState === nativeSignalingState) {
4291
+ this._suppressNextNativeSignalingState = null;
4292
+ }
4293
+ throw error;
4294
+ }
4295
+ }
4296
+
4297
+ _localOfferInit(type) {
4298
+ if (type !== "offer" || !this._iceRestartPending || !this._canApplyNativeIceCredentials()) {
4299
+ return undefined;
4300
+ }
4301
+ return this._ensureIceRestartCredentials();
4302
+ }
4303
+
4304
+ _canApplyNativeIceCredentials() {
4305
+ return (
4306
+ this._iceGatheringState === "new" &&
4307
+ !this._localDescription &&
4308
+ !this._currentLocalDescription &&
4309
+ !this._pendingLocalDescription
4310
+ );
4311
+ }
4312
+
4313
+ _isJsOnlyIceRestartRemoteOffer(description, explicitMarker) {
4314
+ if (explicitMarker) return true;
4315
+ if (description.type !== "offer" || !this._currentRemoteDescription) return false;
4316
+ if (!hasDataMediaSection(description) || !hasDataMediaSection(this._currentRemoteDescription)) {
4317
+ return false;
4318
+ }
4319
+ return hasDifferentIceCredentials(description, this._currentRemoteDescription);
4320
+ }
4321
+
4322
+ _shouldApplyDataOnlyLocalOffer(description) {
4323
+ return (
4324
+ !this._iceRestartPending &&
4325
+ this._signalingState === "stable" &&
4326
+ this._currentLocalDescription?.type === "offer" &&
4327
+ this._currentRemoteDescription?.type === "answer" &&
4328
+ hasDataMediaSection(this._currentLocalDescription) &&
4329
+ hasDataMediaSection(this._currentRemoteDescription) &&
4330
+ (!description ||
4331
+ (hasDataMediaSection(description) &&
4332
+ !hasDifferentIceCredentials(description, this._currentLocalDescription)))
4333
+ );
4334
+ }
4335
+
4336
+ _shouldApplyDataOnlyLocalAnswer(description) {
4337
+ return (
4338
+ this._pendingRemoteDescription?.type === "offer" &&
4339
+ this._currentRemoteDescription?.type === "offer" &&
4340
+ this._currentLocalDescription?.type === "answer" &&
4341
+ hasDataMediaSection(this._pendingRemoteDescription) &&
4342
+ hasDataMediaSection(this._currentRemoteDescription) &&
4343
+ hasDataMediaSection(this._currentLocalDescription) &&
4344
+ !hasDifferentIceCredentials(this._pendingRemoteDescription, this._currentRemoteDescription) &&
4345
+ (!description ||
4346
+ (hasDataMediaSection(description) &&
4347
+ !hasDifferentIceCredentials(description, this._currentLocalDescription)))
4348
+ );
4349
+ }
4350
+
4351
+ _shouldApplyDataOnlyRemoteOffer(description) {
4352
+ return (
4353
+ this._signalingState === "stable" &&
4354
+ this._currentRemoteDescription?.type === "offer" &&
4355
+ this._currentLocalDescription?.type === "answer" &&
4356
+ hasDataMediaSection(description) &&
4357
+ hasDataMediaSection(this._currentRemoteDescription) &&
4358
+ hasDataMediaSection(this._currentLocalDescription) &&
4359
+ !hasDifferentIceCredentials(description, this._currentRemoteDescription)
4360
+ );
4361
+ }
4362
+
4363
+ _shouldApplyDataOnlyRemoteAnswer(description) {
4364
+ return (
4365
+ this._pendingLocalDescription?.type === "offer" &&
4366
+ this._currentLocalDescription?.type === "offer" &&
4367
+ this._currentRemoteDescription?.type === "answer" &&
4368
+ hasDataMediaSection(description) &&
4369
+ hasDataMediaSection(this._pendingLocalDescription) &&
4370
+ hasDataMediaSection(this._currentLocalDescription) &&
4371
+ hasDataMediaSection(this._currentRemoteDescription) &&
4372
+ !hasDifferentIceCredentials(this._pendingLocalDescription, this._currentLocalDescription) &&
4373
+ !hasDifferentIceCredentials(description, this._currentRemoteDescription)
4374
+ );
4375
+ }
4376
+
4377
+ _clearIceRestartRequest() {
4378
+ this._iceRestartPending = false;
4379
+ this._pendingIceRestartCredentials = null;
4380
+ }
4381
+
4382
+ _assertNotClosed() {
4383
+ if (this._closed) throw makeDOMException("RTCPeerConnection is closed", "InvalidStateError");
4384
+ }
4385
+
4386
+ async _ensureLocalAnswerApplied() {
4387
+ if (this._localDescription?.type === "answer" && !this._pendingRemoteDescription)
4388
+ return this._localDescription;
4389
+ if (this._jsOnlyIceRestartRemoteOffer) {
4390
+ const answer =
4391
+ this._lastCreatedAnswer ||
4392
+ markJsOnlyIceRestart(
4393
+ new RTCSessionDescription(this._ensureNativePeerConnection().createAnswer()),
4394
+ );
4395
+ await this._applyJsOnlyLocalAnswer(answer);
4396
+ return this._localDescription;
4397
+ }
4398
+ if (isNoMediaSdp(this.remoteDescription)) {
4399
+ const answer =
4400
+ this._lastCreatedAnswer ||
4401
+ new RTCSessionDescription({
4402
+ type: "answer",
4403
+ sdp: this.remoteDescription.sdp,
4404
+ });
4405
+ await this._applyNoMediaLocalDescription(answer);
4406
+ return this._localDescription;
4407
+ }
4408
+ this._ensureNativePeerConnection().setLocalDescription("answer");
4409
+ const nativeDescription = this._ensureNativePeerConnection().localDescription();
4410
+ this._localDescription = nativeDescription
4411
+ ? new RTCSessionDescription(nativeDescription)
4412
+ : null;
4413
+ this._syncStatesFromNative();
4414
+ this._commitRemoteDescription();
4415
+ this._commitLocalDescription(this._localDescription);
4416
+ this._syncSignalingStateFromDescriptions();
4417
+ this._scheduleNativeCandidateGathering();
4418
+ for (const candidate of this._pendingIce.splice(0)) await this.addIceCandidate(candidate);
4419
+ this._flushPendingRemoteCandidatesForNative();
4420
+ await nextTask();
4421
+ await this._refreshLocalDescriptionAfterGatheringWindow();
4422
+ this._registerLocalDescriptionForPairing();
4423
+ return this._localDescription;
4424
+ }
4425
+
4426
+ async _applyJsOnlyLocalAnswer(description) {
4427
+ const previousState = this._signalingState;
4428
+ const localDescription = markJsOnlyIceRestart(new RTCSessionDescription(description));
4429
+ this._commitRemoteDescription();
4430
+ this._commitLocalDescription(localDescription);
4431
+ this._registerLocalDescriptionForPairing();
4432
+ this._jsOnlyIceRestartRemoteOffer = false;
4433
+ this._clearNegotiationNeededIfDataMLineIsPresent();
4434
+ this._signalingState = "stable";
4435
+ this._refreshIceRole();
4436
+ this._updateSctpTransport();
4437
+ if (previousState !== this._signalingState) this._dispatchSignalingStateChange();
4438
+ await nextTask();
4439
+ }
4440
+
4441
+ async _applyDataOnlyLocalOffer(description) {
4442
+ const previousState = this._signalingState;
4443
+ const localDescription = new RTCSessionDescription(description);
4444
+ this._setPendingLocalDescription(localDescription);
4445
+ this._registerLocalDescriptionForPairing();
4446
+ this._syncSignalingStateFromDescriptions();
4447
+ this._refreshIceRole();
4448
+ this._updateSctpTransport();
4449
+ if (previousState !== this._signalingState) this._dispatchSignalingStateChange();
4450
+ await nextTask();
4451
+ }
4452
+
4453
+ async _applyDataOnlyLocalAnswer(description) {
4454
+ const previousState = this._signalingState;
4455
+ const localDescription = new RTCSessionDescription(description);
4456
+ this._commitRemoteDescription();
4457
+ this._commitLocalDescription(localDescription);
4458
+ this._registerLocalDescriptionForPairing();
4459
+ this._clearNegotiationNeededIfDataMLineIsPresent();
4460
+ this._syncSignalingStateFromDescriptions();
4461
+ this._refreshIceRole();
4462
+ this._updateSctpTransport();
4463
+ if (previousState !== this._signalingState) this._dispatchSignalingStateChange();
4464
+ await nextTask();
4465
+ }
4466
+
4467
+ async _applyNoMediaLocalDescription(description) {
4468
+ const localDescription = new RTCSessionDescription(description);
4469
+ if (localDescription.type === "offer") {
4470
+ this._setPendingLocalDescription(localDescription);
4471
+ } else if (localDescription.type === "answer") {
4472
+ this._commitRemoteDescription();
4473
+ this._commitLocalDescription(localDescription);
4474
+ } else {
4475
+ this._setPendingLocalDescription(localDescription);
4476
+ }
4477
+ this._registerLocalDescriptionForPairing();
4478
+ this._signalingState = description.type === "offer" ? "have-local-offer" : "stable";
4479
+ this._clearNegotiationNeededIfDataMLineIsPresent();
4480
+ this._refreshIceRole();
4481
+ this._updateSctpTransport();
4482
+ this._dispatchSignalingStateChange();
4483
+ await nextTask();
4484
+ }
4485
+
4486
+ _scheduleNativeCandidateGathering() {
4487
+ if (this._closed || !this._native || !hasDataMediaSection(this._localDescription)) return;
4488
+ if (this._nativeCandidateGatheringScheduled) return;
4489
+ this._nativeCandidateGatheringScheduled = true;
4490
+ setImmediate(() => {
4491
+ this._nativeCandidateGatheringScheduled = false;
4492
+ if (this._closed || !this._native || !hasDataMediaSection(this._localDescription)) return;
4493
+ try {
4494
+ this._native.gatherLocalCandidates();
4495
+ } catch {
4496
+ // Gathering may already be complete or the native transport may be closing.
4497
+ }
4498
+ });
4499
+ }
4500
+
4501
+ _refreshLocalDescriptionFromNative() {
4502
+ if (this._closed || !this._localDescription) return;
4503
+ if (!this._native) return;
4504
+ const nativeDescription = this._native.localDescription();
4505
+ if (nativeDescription) {
4506
+ this._refreshCurrentOrPendingLocalDescription(new RTCSessionDescription(nativeDescription));
4507
+ this._registerLocalDescriptionForPairing();
4508
+ }
4509
+ this._syncStatesFromNative();
4510
+ }
4511
+
4512
+ _refreshLocalDescriptionAfterGatheringWindow() {
4513
+ this._refreshLocalDescriptionFromNative();
4514
+ if (this._closed || !this._localDescription || this._iceGatheringState === "complete") return;
4515
+ if (this._localDescriptionRefreshScheduled) return;
4516
+ this._localDescriptionRefreshScheduled = true;
4517
+ setTimeout(() => {
4518
+ this._localDescriptionRefreshScheduled = false;
4519
+ this._refreshLocalDescriptionFromNative();
4520
+ }, 50);
4521
+ }
4522
+
4523
+ _syncStatesFromNative() {
4524
+ if (this._closed) return;
4525
+ if (!this._native) return;
4526
+ this._connectionState = this._native.connectionState;
4527
+ this._iceConnectionState = this._native.iceConnectionState;
4528
+ this._syncSignalingStateFromDescriptions();
4529
+ this._refreshIceRole();
4530
+ this._updateSctpTransport();
4531
+ }
4532
+
4533
+ _handleNativeEvent(event) {
4534
+ if (this._closed) {
4535
+ try {
4536
+ event.channel?.close?.();
4537
+ } catch {
4538
+ // Closed peers must ignore late native callbacks; channel close is best-effort.
4539
+ }
4540
+ return;
4541
+ }
4542
+ if (this._shouldDeferIceEvent(event)) {
4543
+ this._deferredIceEvents.push(event);
4544
+ return;
4545
+ }
4546
+
4547
+ if (event.target === "datachannel") {
4548
+ const channel = this._channels.get(event.channelId);
4549
+ if (channel) {
4550
+ channel._handleNativeEvent(event);
4551
+ } else if (event.channelId) {
4552
+ const events = this._pendingNativeDataChannelEvents.get(event.channelId) || [];
4553
+ events.push(event);
4554
+ this._pendingNativeDataChannelEvents.set(event.channelId, events);
4555
+ }
4556
+ return;
4557
+ }
4558
+
4559
+ switch (event.type) {
4560
+ case "datachannel": {
4561
+ const incomingId = event.channel?.id ?? null;
4562
+ let channel =
4563
+ incomingId == null ? null : this._syntheticIncomingDataChannelForId(incomingId);
4564
+ const adoptedSynthetic = Boolean(channel && channel.readyState !== "closed");
4565
+ if (adoptedSynthetic) {
4566
+ this._pendingSyntheticDataChannelAnnouncements.delete(incomingId);
4567
+ channel._adoptNativeChannel(event.channel, event.channelReadyState);
4568
+ } else {
4569
+ channel = RTCDataChannel._fromNative(this, event.channel, event.channelReadyState);
4570
+ }
4571
+ const id = channel.id;
4572
+ if (id != null) {
4573
+ if (adoptedSynthetic && this._remoteAnnouncedDataChannelIds.has(id)) {
4574
+ this._flushPendingNativeDataChannelEvents(channel, event.channel.bindingId);
4575
+ channel._flushQueuedNativeEventsAfterAnnouncement();
4576
+ if (!channel._announcementPending) channel._announceOpenAfterDataChannelEvent();
4577
+ break;
4578
+ }
4579
+ if (this._remoteAnnouncedDataChannelIds.has(id)) {
4580
+ channel.close();
4581
+ break;
4582
+ }
4583
+ this._remoteAnnouncedDataChannelIds.add(id);
4584
+ }
4585
+ channel._createdLocally = false;
4586
+ channel._openEventPending = channel.readyState === "open";
4587
+ channel._announcementPending = true;
4588
+ this._pendingDataChannelEvents.push(new RTCDataChannelEvent("datachannel", { channel }));
4589
+ this._flushPendingNativeDataChannelEvents(channel, event.channelId);
4590
+ this._scheduleDataChannelFlush();
4591
+ break;
4592
+ }
4593
+ case "localdescription": {
4594
+ const description = new RTCSessionDescription(event.description);
4595
+ if (this._nonstandardPreparedLocalDescriptionType === description.type) {
4596
+ this._preparedLocalDescription = description;
4597
+ break;
4598
+ }
4599
+ this._refreshCurrentOrPendingLocalDescription(description);
4600
+ this._registerLocalDescriptionForPairing();
4601
+ this._refreshIceRole();
4602
+ this._updateSctpTransport();
4603
+ break;
4604
+ }
4605
+ case "localcandidate": {
4606
+ const candidateInit = {
4607
+ candidate: event.candidate.candidate,
4608
+ sdpMid: event.candidate.sdpMid || "0",
4609
+ };
4610
+ const candidate = new RTCIceCandidate(candidateInit);
4611
+ Object.defineProperty(candidate, "_webrtcNodeLocalCandidate", {
4612
+ value: true,
4613
+ configurable: true,
4614
+ });
4615
+ this._rememberLocalIceCandidate(candidate);
4616
+ this._refreshCurrentOrPendingLocalDescription(
4617
+ appendRemoteCandidateToDescription(this._localDescription, candidate),
4618
+ );
4619
+ this.dispatchEvent(new RTCPeerConnectionIceEvent("icecandidate", { candidate }));
4620
+ break;
4621
+ }
4622
+ case "icegatheringstatechange":
4623
+ this._iceGatheringState = event.state;
4624
+ this.dispatchEvent(makeEvent("icegatheringstatechange"));
4625
+ this._iceTransport()?.dispatchEvent(makeEvent("gatheringstatechange"));
4626
+ if (event.state === "complete") {
4627
+ this.dispatchEvent(new RTCPeerConnectionIceEvent("icecandidate", { candidate: null }));
4628
+ }
4629
+ break;
4630
+ case "iceconnectionstatechange":
4631
+ this._iceConnectionState = event.state;
4632
+ this._updateSctpTransport();
4633
+ this.dispatchEvent(makeEvent("iceconnectionstatechange"));
4634
+ this._iceTransport()?._handlePeerIceConnectionState(event.state);
4635
+ this._closeChannelsOnPeerFailure();
4636
+ break;
4637
+ case "connectionstatechange":
4638
+ this._connectionState = event.state;
4639
+ this._updateSctpTransport();
4640
+ this.dispatchEvent(makeEvent("connectionstatechange"));
4641
+ this._closeChannelsOnPeerFailure();
4642
+ break;
4643
+ case "signalingstatechange":
4644
+ if (this._jsOnlyIceRestartOfferPending) {
4645
+ this._signalingState = "have-local-offer";
4646
+ break;
4647
+ }
4648
+ if (this._suppressNextNativeSignalingState === event.state) {
4649
+ this._suppressNextNativeSignalingState = null;
4650
+ break;
4651
+ }
4652
+ if (event.state !== this._descriptionSignalingState()) break;
4653
+ if (
4654
+ event.state === this._signalingState &&
4655
+ event.state === this._lastDispatchedSignalingState
4656
+ ) {
4657
+ break;
4658
+ }
4659
+ this._signalingState = event.state;
4660
+ this._dispatchSignalingStateChange();
4661
+ break;
4662
+ }
4663
+ }
4664
+
4665
+ _handleNativeEventBatch(events) {
4666
+ if (!events.length) return;
4667
+ const first = events[0];
4668
+ if (first?.target !== "datachannel" || first.type !== "message" || first.channelId == null) {
4669
+ for (const event of events) this._handleNativeEvent(event);
4670
+ return;
4671
+ }
4672
+
4673
+ const channelId = first.channelId;
4674
+ for (let index = 1; index < events.length; index += 1) {
4675
+ const event = events[index];
4676
+ if (
4677
+ event?.target !== "datachannel" ||
4678
+ event.type !== "message" ||
4679
+ event.channelId !== channelId
4680
+ ) {
4681
+ for (const item of events) this._handleNativeEvent(item);
4682
+ return;
4683
+ }
4684
+ }
4685
+
4686
+ const channel = this._channels.get(channelId);
4687
+ if (channel) {
4688
+ if (channel._announcementPending || channel._nativeEventDrainActive) {
4689
+ for (const event of events) channel._queuedNativeEvents.push(event);
4690
+ return;
4691
+ }
4692
+ if (channel._dispatchNativeMessageBatch(events)) return;
4693
+ channel._queueMessageEvents(events);
4694
+ return;
4695
+ }
4696
+
4697
+ const pending = this._pendingNativeDataChannelEvents.get(channelId) || [];
4698
+ for (const event of events) pending.push(event);
4699
+ this._pendingNativeDataChannelEvents.set(channelId, pending);
4700
+ }
4701
+
4702
+ _registerDataChannelId(channel, id = channel._effectiveId()) {
4703
+ if (id == null) return;
4704
+ if (channel._registeredDataChannelId === id) return;
4705
+ this._unregisterDataChannelId(channel);
4706
+ const existing = this._usedDataChannelIds.get(id);
4707
+ if (existing && existing !== channel && existing.readyState !== "closed") return;
4708
+ channel._registeredDataChannelId = id;
4709
+ this._usedDataChannelIds.set(id, channel);
4710
+ this._pairDataChannelById(channel, id);
4711
+ }
4712
+
4713
+ _flushPendingNativeDataChannelEvents(channel, channelId) {
4714
+ const events = this._pendingNativeDataChannelEvents.get(channelId);
4715
+ if (!events) return;
4716
+ this._pendingNativeDataChannelEvents.delete(channelId);
4717
+ for (const event of events) {
4718
+ if (channel._announcementPending || channel._nativeEventDrainActive) {
4719
+ channel._queuedNativeEvents.push(event);
4720
+ } else {
4721
+ channel._handleNativeEvent(event, true);
4722
+ }
4723
+ }
4724
+ }
4725
+
4726
+ _unregisterDataChannelId(channel) {
4727
+ const id = channel._registeredDataChannelId;
4728
+ if (id == null) return;
4729
+ if (this._usedDataChannelIds.get(id) === channel) {
4730
+ this._usedDataChannelIds.delete(id);
4731
+ }
4732
+ channel._registeredDataChannelId = null;
4733
+ }
4734
+
4735
+ _isDataChannelIdInUse(id) {
4736
+ let channel = this._usedDataChannelIds.get(id);
4737
+ if (channel && channel.readyState !== "closed") return true;
4738
+ if (!this._dataChannelIdRefreshNeeded) return false;
4739
+
4740
+ let refreshStillNeeded = false;
4741
+ for (const currentChannel of this._channels.values()) {
4742
+ if (currentChannel.readyState === "closed") continue;
4743
+ const effectiveId = currentChannel._effectiveId();
4744
+ if (effectiveId == null) {
4745
+ refreshStillNeeded = true;
4746
+ continue;
4747
+ }
4748
+ this._registerDataChannelId(currentChannel, effectiveId);
4749
+ }
4750
+ this._dataChannelIdRefreshNeeded = refreshStillNeeded;
4751
+ channel = this._usedDataChannelIds.get(id);
4752
+ return Boolean(channel && channel.readyState !== "closed");
4753
+ }
4754
+
4755
+ _dataChannelIdParityFromDtlsRole() {
4756
+ if (this._remoteDescription?.type !== "answer") return null;
4757
+ if (this._localDescription?.type !== "offer") return null;
4758
+ const setup = dtlsSetupFromDescription(this._remoteDescription);
4759
+ if (setup === "passive") return 0;
4760
+ if (setup === "active") return 1;
4761
+ return null;
4762
+ }
4763
+
4764
+ _nextAvailableDataChannelId(parity) {
4765
+ for (let id = parity; id <= 65534; id += 2) {
4766
+ if (!this._isDataChannelIdInUse(id)) return id;
4767
+ }
4768
+ return null;
4769
+ }
4770
+
4771
+ _assignDataChannelIdsFromDtlsRole() {
4772
+ const parity = this._dataChannelIdParityFromDtlsRole();
4773
+ if (parity === null) return;
4774
+ for (const channel of this._channels.values()) {
4775
+ if (channel.negotiated || channel._effectiveId() != null || channel.readyState === "closed")
4776
+ continue;
4777
+ const id = this._nextAvailableDataChannelId(parity);
4778
+ if (id === null) {
4779
+ channel._handlePeerConnectionFailure();
4780
+ continue;
4781
+ }
4782
+ channel._assignId(id);
4783
+ }
4784
+ }
4785
+
4786
+ _closeChannelsOnPeerFailure({ includeDisconnected = false } = {}) {
4787
+ if (this._closed) return;
4788
+ const failed =
4789
+ this._connectionState === "closed" ||
4790
+ this._connectionState === "failed" ||
4791
+ this._iceConnectionState === "closed" ||
4792
+ this._iceConnectionState === "failed" ||
4793
+ (includeDisconnected &&
4794
+ (this._connectionState === "disconnected" || this._iceConnectionState === "disconnected"));
4795
+ if (!failed) return;
4796
+ for (const channel of this._channels.values()) {
4797
+ channel._handlePeerConnectionFailure();
4798
+ }
4799
+ }
4800
+
4801
+ _markNegotiationNeeded() {
4802
+ if (this._closed || this._signalingState !== "stable" || this._negotiationNeeded) return;
4803
+ this._negotiationNeeded = true;
4804
+ if (this._negotiationNeededScheduled) return;
4805
+ this._negotiationNeededScheduled = true;
4806
+ setTimeout(() => {
4807
+ this._negotiationNeededScheduled = false;
4808
+ if (this._closed || this._signalingState !== "stable" || !this._negotiationNeeded) return;
4809
+ this.dispatchEvent(makeEvent("negotiationneeded"));
4810
+ }, 0);
4811
+ }
4812
+
4813
+ _clearNegotiationNeededIfDataMLineIsPresent() {
4814
+ const sdp = this._localDescription?.sdp || this._remoteDescription?.sdp || "";
4815
+ if (/\r?\nm=application\b/i.test(sdp)) {
4816
+ this._negotiationNeeded = false;
4817
+ }
4818
+ }
4819
+
4820
+ _eventListenerAdded(type) {
4821
+ if (type === "datachannel") {
4822
+ this._scheduleDataChannelFlush();
4823
+ this._scheduleDataChannelAnnouncementRepair();
4824
+ this._pairedPeer?._scheduleDataChannelAnnouncementRepair();
4825
+ }
4826
+ }
4827
+
4828
+ _scheduleDataChannelFlush() {
4829
+ if (this._dataChannelFlushScheduled || !this._pendingDataChannelEvents.length) return;
4830
+ this._dataChannelFlushScheduled = true;
4831
+ setTimeout(() => {
4832
+ this._dataChannelFlushScheduled = false;
4833
+ if (this._closed || !this._hasEventConsumer("datachannel")) return;
4834
+ const events = this._pendingDataChannelEvents.splice(0);
4835
+ for (const event of events) {
4836
+ if (this._closed) return;
4837
+ event.channel._gateMessageEventsUntilConsumer();
4838
+ this.dispatchEvent(event);
4839
+ event.channel._announcementPending = false;
4840
+ event.channel._announceOpenAfterDataChannelEvent();
4841
+ event.channel._gateMessageEventsAfterAnnouncement();
4842
+ event.channel._gateMessageEventsUntilConsumer();
4843
+ event.channel._flushQueuedNativeEventsAfterAnnouncement();
4844
+ }
4845
+ if (this._pendingDataChannelEvents.length) this._scheduleDataChannelFlush();
4846
+ }, 0);
4847
+ }
4848
+ }
4849
+
4850
+ function normalizeDataChannelInit(init) {
4851
+ const options = {
4852
+ ordered: init.ordered !== undefined ? Boolean(init.ordered) : true,
4853
+ maxPacketLifeTime: init.maxPacketLifeTime,
4854
+ maxRetransmits: init.maxRetransmits,
4855
+ protocol: init.protocol === undefined ? "" : String(init.protocol),
4856
+ negotiated: init.negotiated !== undefined ? Boolean(init.negotiated) : false,
4857
+ id: init.id,
4858
+ };
4859
+
4860
+ if (options.maxPacketLifeTime != null) {
4861
+ options.maxPacketLifeTime = enforceRange(options.maxPacketLifeTime, "maxPacketLifeTime");
4862
+ }
4863
+ if (options.maxRetransmits != null) {
4864
+ options.maxRetransmits = enforceRange(options.maxRetransmits, "maxRetransmits");
4865
+ }
4866
+ if (options.maxPacketLifeTime != null && options.maxRetransmits != null) {
4867
+ throw new TypeError("maxPacketLifeTime and maxRetransmits are mutually exclusive");
4868
+ }
4869
+ if (options.id != null) {
4870
+ options.id = enforceRange(options.id, "id", 65535);
4871
+ }
4872
+ if (options.negotiated && options.id == null) {
4873
+ throw new TypeError("negotiated RTCDataChannel requires an id");
4874
+ }
4875
+ if (options.negotiated && options.id > 65534) {
4876
+ throw new TypeError("id must be an integer between 0 and 65534");
4877
+ }
4878
+ if (!options.negotiated) {
4879
+ options.id = undefined;
4880
+ }
4881
+ return options;
4882
+ }
4883
+
4884
+ module.exports = {
4885
+ RTCPeerConnection,
4886
+ RTCDataChannel,
4887
+ RTCSessionDescription,
4888
+ RTCIceCandidate,
4889
+ RTCIceCandidatePair,
4890
+ RTCCertificate,
4891
+ RTCDataChannelEvent,
4892
+ RTCPeerConnectionIceEvent,
4893
+ RTCPeerConnectionIceErrorEvent,
4894
+ RTCError,
4895
+ RTCErrorEvent,
4896
+ RTCIceTransport,
4897
+ RTCSctpTransport,
4898
+ RTCDtlsTransport,
4899
+ EventTarget: SimpleEventTarget,
4900
+ Event: SimpleEvent,
4901
+ MessageEvent: SimpleMessageEvent,
4902
+ nonstandard: {
4903
+ IceUdpMuxListener,
4904
+ configurePeerConnection,
4905
+ setLocalIceCredentials,
4906
+ getRemoteFingerprint,
4907
+ importCertificate,
4908
+ native,
4909
+ },
4910
+ };