@webrtc-node/webrtc 0.2.1 → 0.2.3

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 CHANGED
@@ -1,9 +1,27 @@
1
1
  "use strict";
2
2
 
3
3
  const crypto = require("node:crypto");
4
+ const { types } = require("node:util");
4
5
  const native = require("./load-native");
5
6
 
6
7
  const kHandlers = new WeakMap();
8
+ const dispatchingEvents = new WeakSet();
9
+ const arrayBufferByteLength = Object.getOwnPropertyDescriptor(
10
+ ArrayBuffer.prototype,
11
+ "byteLength",
12
+ ).get;
13
+ const arrayBufferResizable = Object.getOwnPropertyDescriptor(
14
+ ArrayBuffer.prototype,
15
+ "resizable",
16
+ )?.get;
17
+ const arrayBufferDetached = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "detached")?.get;
18
+ const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
19
+ const typedArrayBuffer = Object.getOwnPropertyDescriptor(typedArrayPrototype, "buffer").get;
20
+ const typedArrayByteOffset = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteOffset").get;
21
+ const typedArrayByteLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength").get;
22
+ const dataViewBuffer = Object.getOwnPropertyDescriptor(DataView.prototype, "buffer").get;
23
+ const dataViewByteOffset = Object.getOwnPropertyDescriptor(DataView.prototype, "byteOffset").get;
24
+ const dataViewByteLength = Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get;
7
25
  const certificateMaterial = new WeakMap();
8
26
  const localDescriptionOwners = new Map();
9
27
  const localDescriptionOwnerFinalizer = new FinalizationRegistry((key) => {
@@ -48,6 +66,9 @@ class SimpleMessageEvent extends SimpleEvent {
48
66
  class SimpleEventTarget {
49
67
  addEventListener(type, callback, options = undefined) {
50
68
  if (callback == null) return;
69
+ if (typeof callback !== "function" && typeof callback !== "object") {
70
+ throw new TypeError("Event listener must be a function or an object");
71
+ }
51
72
  let map = kHandlers.get(this);
52
73
  if (!map) {
53
74
  map = new Map();
@@ -60,20 +81,27 @@ class SimpleEventTarget {
60
81
  map.set(key, listeners);
61
82
  }
62
83
  const once = typeof options === "object" && options !== null && Boolean(options.once);
84
+ const capture = listenerCapture(options);
63
85
  let added = false;
64
- if (!listeners.some((listener) => listener.callback === callback)) {
65
- listeners.push({ callback, once });
86
+ if (
87
+ !listeners.some((listener) => listener.callback === callback && listener.capture === capture)
88
+ ) {
89
+ listeners.push({ callback, once, capture, removed: false });
66
90
  added = true;
67
91
  }
68
92
  if (added && typeof this._eventListenerAdded === "function") this._eventListenerAdded(key);
69
93
  }
70
94
 
71
- removeEventListener(type, callback) {
95
+ removeEventListener(type, callback, options = undefined) {
72
96
  const key = String(type);
73
97
  const listeners = kHandlers.get(this)?.get(key);
74
98
  if (!listeners) return;
75
- const index = listeners.findIndex((listener) => listener.callback === callback);
99
+ const capture = listenerCapture(options);
100
+ const index = listeners.findIndex(
101
+ (listener) => listener.callback === callback && listener.capture === capture,
102
+ );
76
103
  if (index !== -1) {
104
+ listeners[index].removed = true;
77
105
  listeners.splice(index, 1);
78
106
  if (typeof this._eventListenerRemoved === "function") this._eventListenerRemoved(key);
79
107
  }
@@ -83,19 +111,24 @@ class SimpleEventTarget {
83
111
  if (!event || typeof event.type !== "string") {
84
112
  throw new TypeError("dispatchEvent requires an Event object");
85
113
  }
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);
114
+ beginEventDispatch(this, event);
115
+ try {
116
+ const registeredListeners = kHandlers.get(this)?.get(event.type);
117
+ const listeners = registeredListeners?.length ? Array.from(registeredListeners) : null;
118
+ const handler = this[`on${event.type}`];
119
+ if (listeners) {
120
+ for (const listener of listeners) {
121
+ if (listener.removed) continue;
122
+ if (listener.once)
123
+ this.removeEventListener(event.type, listener.callback, listener.capture);
124
+ callListener(listener.callback, this, event);
125
+ }
95
126
  }
127
+ if (typeof handler === "function") callListener(handler, this, event);
128
+ return !event.defaultPrevented;
129
+ } finally {
130
+ endEventDispatch(event);
96
131
  }
97
- if (typeof handler === "function") callListener(handler, this, event);
98
- return !event.defaultPrevented;
99
132
  }
100
133
 
101
134
  _hasEventConsumer(type) {
@@ -104,11 +137,47 @@ class SimpleEventTarget {
104
137
  }
105
138
  }
106
139
 
140
+ function listenerCapture(options) {
141
+ return typeof options === "object" && options !== null
142
+ ? Boolean(options.capture)
143
+ : Boolean(options);
144
+ }
145
+
146
+ function beginEventDispatch(target, event) {
147
+ if (dispatchingEvents.has(event)) {
148
+ throw makeDOMException("Event is already being dispatched", "InvalidStateError");
149
+ }
150
+ event.target = target;
151
+ event.currentTarget = target;
152
+ dispatchingEvents.add(event);
153
+ }
154
+
155
+ function endEventDispatch(event) {
156
+ event.currentTarget = null;
157
+ dispatchingEvents.delete(event);
158
+ }
159
+
160
+ function dispatchDirectEvent(target, event, handler) {
161
+ beginEventDispatch(target, event);
162
+ try {
163
+ callListener(handler, target, event);
164
+ } finally {
165
+ endEventDispatch(event);
166
+ }
167
+ }
168
+
107
169
  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);
170
+ try {
171
+ if (typeof listener === "function") {
172
+ listener.call(target, event);
173
+ } else {
174
+ listener.handleEvent(event);
175
+ }
176
+ } catch (error) {
177
+ // Report through Node without interrupting event delivery or native cleanup.
178
+ process.nextTick(() => {
179
+ throw error;
180
+ });
112
181
  }
113
182
  }
114
183
 
@@ -139,11 +208,11 @@ function byteLength(value) {
139
208
  }
140
209
 
141
210
  function enforceRange(value, name, max = 65535) {
142
- const number = Number(value);
143
- if (!Number.isInteger(number) || number < 0 || number > max) {
211
+ const number = Math.trunc(+value);
212
+ if (!Number.isFinite(number) || number < 0 || number > max) {
144
213
  throw new TypeError(`${name} must be an integer between 0 and ${max}`);
145
214
  }
146
- return number;
215
+ return number === 0 ? 0 : number;
147
216
  }
148
217
 
149
218
  function toUnsignedLong(value) {
@@ -205,10 +274,31 @@ function getCertificateMaterial(certificate) {
205
274
 
206
275
  function normalizeEnum(value, name, allowed, defaultValue) {
207
276
  if (value === undefined) return defaultValue;
208
- if (value === null || !allowed.includes(value)) {
277
+ const string = toDOMString(value);
278
+ if (!allowed.includes(string)) {
209
279
  throw new TypeError(`${name} must be one of: ${allowed.join(", ")}`);
210
280
  }
211
- return value;
281
+ return string;
282
+ }
283
+
284
+ function isObject(value) {
285
+ return value !== null && (typeof value === "object" || typeof value === "function");
286
+ }
287
+
288
+ function toDOMString(value) {
289
+ if (typeof value === "symbol") throw new TypeError("Cannot convert a Symbol to a string");
290
+ return String(value);
291
+ }
292
+
293
+ function sequenceFromIterator(value, iterator, convert) {
294
+ return Array.from({ [Symbol.iterator]: () => Reflect.apply(iterator, value, []) }, convert);
295
+ }
296
+
297
+ function normalizeSequence(value, convert, name) {
298
+ if (!isObject(value)) throw new TypeError(`${name} must be iterable`);
299
+ const iterator = value[Symbol.iterator];
300
+ if (typeof iterator !== "function") throw new TypeError(`${name} must be iterable`);
301
+ return sequenceFromIterator(value, iterator, convert);
212
302
  }
213
303
 
214
304
  function validateIceServerUrl(url) {
@@ -225,18 +315,24 @@ function validateIceServerUrl(url) {
225
315
  }
226
316
 
227
317
  const [hostPort, query = ""] = rest.split("?");
318
+ const hasQuery = rest.includes("?");
228
319
  if (rest.split("?").length > 2 || !hostPort) {
229
320
  throw makeDOMException("Invalid ICE server URL", "SyntaxError");
230
321
  }
231
- if ((scheme === "stun" || scheme === "stuns") && query) {
322
+ if ((scheme === "stun" || scheme === "stuns") && hasQuery) {
232
323
  throw makeDOMException("STUN URL must not contain a query", "SyntaxError");
233
324
  }
234
- if ((scheme === "turn" || scheme === "turns") && query && !/^transport=(udp|tcp)$/i.test(query)) {
325
+ if (
326
+ (scheme === "turn" || scheme === "turns") &&
327
+ hasQuery &&
328
+ !/^transport=(udp|tcp)$/i.test(query)
329
+ ) {
235
330
  throw makeDOMException("Invalid TURN transport", "SyntaxError");
236
331
  }
237
332
 
238
333
  let host = hostPort;
239
334
  let port = "";
335
+ let hasPort = false;
240
336
  if (hostPort.startsWith("[")) {
241
337
  const end = hostPort.indexOf("]");
242
338
  if (end <= 1) throw makeDOMException("Invalid ICE server host", "SyntaxError");
@@ -244,19 +340,21 @@ function validateIceServerUrl(url) {
244
340
  const suffix = hostPort.slice(end + 1);
245
341
  if (suffix) {
246
342
  if (!suffix.startsWith(":")) throw makeDOMException("Invalid ICE server port", "SyntaxError");
343
+ hasPort = true;
247
344
  port = suffix.slice(1);
248
345
  }
249
346
  } else {
250
347
  const colonCount = (hostPort.match(/:/g) || []).length;
251
348
  if (colonCount > 1) throw makeDOMException("Invalid ICE server host", "SyntaxError");
252
349
  if (colonCount === 1) {
350
+ hasPort = true;
253
351
  const index = hostPort.lastIndexOf(":");
254
352
  host = hostPort.slice(0, index);
255
353
  port = hostPort.slice(index + 1);
256
354
  }
257
355
  }
258
- if (!host) throw makeDOMException("Invalid ICE server host", "SyntaxError");
259
- if (port !== "") {
356
+ if (!host || /\s/.test(host)) throw makeDOMException("Invalid ICE server host", "SyntaxError");
357
+ if (hasPort) {
260
358
  const number = Number(port);
261
359
  if (!/^\d+$/.test(port) || !Number.isInteger(number) || number < 0 || number > 65535) {
262
360
  throw makeDOMException("Invalid ICE server port", "SyntaxError");
@@ -266,78 +364,108 @@ function validateIceServerUrl(url) {
266
364
 
267
365
  function normalizeIceServers(iceServers) {
268
366
  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
- );
367
+ return normalizeSequence(
368
+ iceServers,
369
+ (server) => {
370
+ if (!isObject(server)) throw new TypeError("RTCIceServer must be an object");
371
+ const credentialValue = server.credential;
372
+ const credential = credentialValue === undefined ? undefined : toDOMString(credentialValue);
373
+ const urlsValue = server.urls;
374
+ if (urlsValue === undefined) {
375
+ throw new TypeError("RTCIceServer.urls is required");
290
376
  }
291
- if (byteLength(username) > 509) {
292
- throw makeDOMException("TURN username exceeds 509 bytes", "InvalidAccessError");
377
+ let urls;
378
+ const iterator = isObject(urlsValue) ? urlsValue[Symbol.iterator] : undefined;
379
+ if (iterator != null) {
380
+ if (typeof iterator !== "function")
381
+ throw new TypeError("RTCIceServer.urls iterator must be callable");
382
+ urls = sequenceFromIterator(urlsValue, iterator, toDOMString);
383
+ } else {
384
+ urls = [toDOMString(urlsValue)];
385
+ }
386
+ const usernameValue = server.username;
387
+ const username = usernameValue === undefined ? undefined : toDOMString(usernameValue);
388
+ if (urls.length === 0)
389
+ throw makeDOMException("RTCIceServer.urls must not be empty", "SyntaxError");
390
+ for (const url of urls) validateIceServerUrl(url);
391
+
392
+ const requiresCredentials = urls.some((url) => /^turns?:/i.test(url));
393
+ if (requiresCredentials) {
394
+ if (username === undefined || credential === undefined || credential === "") {
395
+ throw makeDOMException(
396
+ "TURN servers require username and credential",
397
+ "InvalidAccessError",
398
+ );
399
+ }
400
+ if (byteLength(username) > 509) {
401
+ throw makeDOMException("TURN username exceeds 509 bytes", "InvalidAccessError");
402
+ }
293
403
  }
294
- }
295
404
 
296
- const normalized = { urls };
297
- if (username !== undefined) normalized.username = username;
298
- if (credential !== undefined) normalized.credential = credential;
299
- return normalized;
300
- });
405
+ const normalized = { urls };
406
+ if (username !== undefined) normalized.username = username;
407
+ if (credential !== undefined) normalized.credential = credential;
408
+ return normalized;
409
+ },
410
+ "iceServers",
411
+ );
301
412
  }
302
413
 
303
- function normalizePeerConnectionConfiguration(configuration) {
414
+ function normalizePeerConnectionConfiguration(configuration, previous = null) {
304
415
  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
- }
416
+ if (!isObject(configuration)) throw new TypeError("RTCConfiguration must be an object");
417
+ const bundlePolicy = normalizeEnum(
418
+ configuration.bundlePolicy,
419
+ "bundlePolicy",
420
+ ["balanced", "max-compat", "max-bundle"],
421
+ "balanced",
422
+ );
423
+ const certificatesValue = configuration.certificates;
309
424
  const certificates =
310
- configuration.certificates === undefined ? [] : Array.from(configuration.certificates);
425
+ certificatesValue === undefined
426
+ ? previous?.certificates || []
427
+ : normalizeSequence(
428
+ certificatesValue,
429
+ (certificate) => {
430
+ if (!certificateMaterial.has(certificate)) {
431
+ throw new TypeError(
432
+ "certificates must contain generated or imported RTCCertificate objects",
433
+ );
434
+ }
435
+ return certificate;
436
+ },
437
+ "certificates",
438
+ );
439
+ const poolSizeValue = configuration.iceCandidatePoolSize;
440
+ const iceCandidatePoolSize =
441
+ poolSizeValue === undefined ? 0 : enforceRange(poolSizeValue, "iceCandidatePoolSize", 255);
442
+ const iceServers = normalizeIceServers(configuration.iceServers);
443
+ const iceTransportPolicy = normalizeEnum(
444
+ configuration.iceTransportPolicy,
445
+ "iceTransportPolicy",
446
+ ["all", "relay"],
447
+ "all",
448
+ );
449
+ const rtcpMuxPolicy = normalizeEnum(
450
+ configuration.rtcpMuxPolicy,
451
+ "rtcpMuxPolicy",
452
+ ["require"],
453
+ "require",
454
+ );
311
455
  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()) {
456
+ if (
457
+ (certificatesValue !== undefined || previous === null) &&
458
+ certificate.expires <= Date.now()
459
+ ) {
314
460
  throw makeDOMException("RTCCertificate has expired", "InvalidAccessError");
315
461
  }
316
462
  }
317
463
  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),
464
+ iceServers,
465
+ iceTransportPolicy,
466
+ bundlePolicy,
467
+ rtcpMuxPolicy,
468
+ iceCandidatePoolSize,
341
469
  certificates,
342
470
  };
343
471
  }
@@ -580,7 +708,6 @@ function getRemoteFingerprint(peerConnection) {
580
708
  }
581
709
 
582
710
  function normalizeDescription(init) {
583
- if (init instanceof RTCSessionDescription) return init;
584
711
  return new RTCSessionDescription(init);
585
712
  }
586
713
 
@@ -661,10 +788,6 @@ const DEFAULT_SCTP_MAX_MESSAGE_SIZE = 262144;
661
788
  const LIBDATACHANNEL_SCTP_MAX_CHANNELS = 1024;
662
789
  let nextUnsupportedDataChannelBindingId = -1;
663
790
 
664
- async function delayInvalidStateIfOperationPending(peer) {
665
- if (peer._operationsPending > 0) await nextTask();
666
- }
667
-
668
791
  const ICE_CREDENTIAL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
669
792
 
670
793
  function randomIceCredential(length) {
@@ -806,7 +929,6 @@ function parseCandidate(candidate) {
806
929
  }
807
930
 
808
931
  function normalizeAddIceCandidateInput(init) {
809
- if (init instanceof RTCIceCandidate) return init;
810
932
  if (init == null) {
811
933
  return {
812
934
  candidate: "",
@@ -888,7 +1010,12 @@ function serializeSdp(sessionLines, mediaSections) {
888
1010
 
889
1011
  function validateCandidateSyntax(candidate) {
890
1012
  if (candidate === "") return true;
891
- if (typeof candidate !== "string" || !candidate.startsWith("candidate:")) return false;
1013
+ if (
1014
+ typeof candidate !== "string" ||
1015
+ !candidate.startsWith("candidate:") ||
1016
+ /[^\x20-\x7e]/.test(candidate)
1017
+ )
1018
+ return false;
892
1019
  const parts = candidate.slice("candidate:".length).trim().split(/\s+/);
893
1020
  const typIndex = parts.indexOf("typ");
894
1021
  return parts.length >= 8 && typIndex >= 6 && Boolean(parts[typIndex + 1]);
@@ -941,14 +1068,24 @@ function selectCandidateSections(description, candidate) {
941
1068
 
942
1069
  function appendRemoteCandidateToDescription(description, candidate) {
943
1070
  if (!description?.sdp || isNoMediaSdp(description)) return description;
944
- if (!validateCandidateSyntax(candidate.candidate)) {
1071
+ const rawCandidate = candidate.candidate;
1072
+ let end = rawCandidate.length;
1073
+ if (rawCandidate.charCodeAt(end - 1) === 10) {
1074
+ end--;
1075
+ if (rawCandidate.charCodeAt(end - 1) === 13) end--;
1076
+ } else if (rawCandidate.charCodeAt(end - 1) === 13) {
1077
+ end--;
1078
+ }
1079
+ while (end > 0 && rawCandidate.charCodeAt(end - 1) === 32) end--;
1080
+ const candidateLine = rawCandidate.slice(0, end);
1081
+ if ((rawCandidate !== "" && candidateLine === "") || !validateCandidateSyntax(candidateLine)) {
945
1082
  throw makeDOMException("Invalid ICE candidate syntax", "OperationError");
946
1083
  }
947
1084
 
948
1085
  const { parsed, targets } = selectCandidateSections(description, candidate);
949
1086
  if (targets.length === 0) return description;
950
1087
 
951
- const line = candidate.candidate === "" ? "a=end-of-candidates" : `a=${candidate.candidate}`;
1088
+ const line = candidateLine === "" ? "a=end-of-candidates" : `a=${candidateLine}`;
952
1089
  for (const section of targets) {
953
1090
  if (!section.lines.includes(line)) section.lines.push(line);
954
1091
  }
@@ -1600,7 +1737,7 @@ class RTCDataChannel extends SimpleEventTarget {
1600
1737
  return;
1601
1738
  }
1602
1739
 
1603
- const view = data instanceof Uint8Array ? data : toUint8Array(data);
1740
+ const view = toUint8Array(data);
1604
1741
  const size = view.byteLength;
1605
1742
  this._assertWithinMaxMessageSize(size);
1606
1743
  if (this._hasPendingSends() || !this._nativeReadyForSend()) {
@@ -1813,7 +1950,7 @@ class RTCDataChannel extends SimpleEventTarget {
1813
1950
  _sendNativeBinary(data) {
1814
1951
  if (this._usesSyntheticPairDelivery()) {
1815
1952
  const view = toUint8Array(data);
1816
- const copy = view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength);
1953
+ const copy = new Uint8Array(view).buffer;
1817
1954
  this._trackPendingPairedDelivery(copy.byteLength);
1818
1955
  this._deliverSyntheticMessage({ binary: true, data: copy });
1819
1956
  return true;
@@ -1854,12 +1991,14 @@ class RTCDataChannel extends SimpleEventTarget {
1854
1991
  }
1855
1992
 
1856
1993
  _markPairedDeliveryReceived(event) {
1994
+ if (event._pairedDeliveryReceived) return false;
1857
1995
  const sender = this._pairedChannel;
1858
- if (!sender || sender.readyState === "closed") return;
1996
+ if (!sender || sender.readyState === "closed") return false;
1859
1997
  const size = event.binary ? event.data?.byteLength || 0 : byteLength(event.data || "");
1860
- if (size <= 0) return;
1998
+ if (size <= 0) return false;
1999
+ event._pairedDeliveryReceived = true;
1861
2000
  sender._pendingPairedDeliveryBytes = Math.max(0, sender._pendingPairedDeliveryBytes - size);
1862
- sender._decreaseBufferedAmountForPairedDelivery(size);
2001
+ return sender._decreaseBufferedAmountForPairedDelivery(size);
1863
2002
  }
1864
2003
 
1865
2004
  _decreaseBufferedAmountForPairedDelivery(size) {
@@ -1867,7 +2006,7 @@ class RTCDataChannel extends SimpleEventTarget {
1867
2006
  if (pending > 0) {
1868
2007
  this._pendingBufferedAmountDecrease -= pending;
1869
2008
  }
1870
- this._decreaseBufferedAmount(size);
2009
+ return this._decreaseBufferedAmount(size);
1871
2010
  }
1872
2011
 
1873
2012
  _decreaseBufferedAmount(size) {
@@ -1877,8 +2016,11 @@ class RTCDataChannel extends SimpleEventTarget {
1877
2016
  previous > this._bufferedAmountLowThreshold &&
1878
2017
  this._bufferedAmount <= this._bufferedAmountLowThreshold
1879
2018
  ) {
2019
+ const hasConsumer = this._hasEventConsumer("bufferedamountlow");
1880
2020
  this.dispatchEvent(makeEvent("bufferedamountlow"));
2021
+ return hasConsumer;
1881
2022
  }
2023
+ return false;
1882
2024
  }
1883
2025
 
1884
2026
  _closeNativeAfterBufferedSends(close) {
@@ -2229,9 +2371,7 @@ class RTCDataChannel extends SimpleEventTarget {
2229
2371
  _dispatchMessageEvent(event, directHandler) {
2230
2372
  const messageEvent = makeMessageEvent("message", { data: this._convertMessage(event) });
2231
2373
  if (directHandler) {
2232
- messageEvent.target = this;
2233
- messageEvent.currentTarget = this;
2234
- callListener(directHandler, this, messageEvent);
2374
+ dispatchDirectEvent(this, messageEvent, directHandler);
2235
2375
  } else {
2236
2376
  this.dispatchEvent(messageEvent);
2237
2377
  }
@@ -2275,7 +2415,12 @@ class RTCDataChannel extends SimpleEventTarget {
2275
2415
  )
2276
2416
  ? handler
2277
2417
  : null;
2278
- this._markPairedDeliveryReceived(event);
2418
+ if (this._markPairedDeliveryReceived(event)) {
2419
+ // Let bufferedamountlow promise continuations attach their message handlers.
2420
+ this._queuedMessageEventIndex--;
2421
+ this._scheduleMessageEventContinuation();
2422
+ return;
2423
+ }
2279
2424
  this._dispatchMessageEvent(event, directHandler);
2280
2425
 
2281
2426
  if (this._queuedMessageEventIndex >= this._queuedMessageEvents.length) {
@@ -2322,13 +2467,14 @@ class RTCDataChannel extends SimpleEventTarget {
2322
2467
  const shouldCreateBlob = this._binaryType === "blob" && typeof Blob !== "undefined";
2323
2468
  for (let index = 0; index < events.length; index += 1) {
2324
2469
  const event = events[index];
2325
- this._markPairedDeliveryReceived(event);
2470
+ if (this._markPairedDeliveryReceived(event)) {
2471
+ this._queueMessageEvents(events.slice(index));
2472
+ return true;
2473
+ }
2326
2474
  const messageEvent = makeMessageEvent("message", {
2327
2475
  data: event.binary && shouldCreateBlob ? new Blob([event.data]) : event.data,
2328
2476
  });
2329
- messageEvent.target = this;
2330
- messageEvent.currentTarget = this;
2331
- directHandler.call(this, messageEvent);
2477
+ dispatchDirectEvent(this, messageEvent, directHandler);
2332
2478
  if (this._readyState === "closed") return true;
2333
2479
  if (
2334
2480
  index + 1 < events.length &&
@@ -2389,13 +2535,40 @@ class RTCDataChannel extends SimpleEventTarget {
2389
2535
  }
2390
2536
 
2391
2537
  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);
2538
+ const isBuffer = types.isArrayBuffer(data);
2539
+ const isDataView = types.isDataView(data);
2540
+ let buffer;
2541
+ if (isBuffer) {
2542
+ buffer = data;
2543
+ } else if (ArrayBuffer.isView(data)) {
2544
+ buffer = (isDataView ? dataViewBuffer : typedArrayBuffer).call(data);
2545
+ } else {
2546
+ throw new TypeError(
2547
+ "RTCDataChannel.send expects a string, Blob, ArrayBuffer, or ArrayBufferView",
2548
+ );
2549
+ }
2550
+ if (types.isSharedArrayBuffer(buffer)) {
2551
+ throw new TypeError("RTCDataChannel.send buffer must not be shared");
2552
+ }
2553
+ if (arrayBufferResizable?.call(buffer)) {
2554
+ throw new TypeError("RTCDataChannel.send buffer must not be resizable");
2555
+ }
2556
+ const size = arrayBufferByteLength.call(buffer);
2557
+ if (arrayBufferDetached) {
2558
+ if (arrayBufferDetached.call(buffer)) return new Uint8Array();
2559
+ } else if (size === 0) {
2560
+ // Node 20 lacks ArrayBuffer.prototype.detached. Constructing a view checks it.
2561
+ try {
2562
+ new Uint8Array(buffer);
2563
+ } catch {
2564
+ return new Uint8Array();
2565
+ }
2396
2566
  }
2397
- throw new TypeError(
2398
- "RTCDataChannel.send expects a string, Blob, ArrayBuffer, or ArrayBufferView",
2567
+ if (isBuffer) return new Uint8Array(buffer);
2568
+ return new Uint8Array(
2569
+ buffer,
2570
+ (isDataView ? dataViewByteOffset : typedArrayByteOffset).call(data),
2571
+ (isDataView ? dataViewByteLength : typedArrayByteLength).call(data),
2399
2572
  );
2400
2573
  }
2401
2574
 
@@ -2450,6 +2623,7 @@ class RTCPeerConnection extends SimpleEventTarget {
2450
2623
  this._jsOnlyIceRestartOfferPending = false;
2451
2624
  this._jsOnlyIceRestartRemoteOffer = false;
2452
2625
  this._operationsPending = 0;
2626
+ this._operationQueue = [];
2453
2627
  this._operationIdleCallbacks = [];
2454
2628
  this._explicitIceCandidateExchange = false;
2455
2629
  this._sameProcessIceCandidateExchange = false;
@@ -2495,6 +2669,7 @@ class RTCPeerConnection extends SimpleEventTarget {
2495
2669
  }
2496
2670
 
2497
2671
  _ensureNativePeerConnection() {
2672
+ this._assertNotClosed();
2498
2673
  if (this._native) return this._native;
2499
2674
  const nativeConfiguration = {
2500
2675
  iceServers: this._configuration.iceServers.map((server) => ({
@@ -2527,12 +2702,11 @@ class RTCPeerConnection extends SimpleEventTarget {
2527
2702
 
2528
2703
  setConfiguration(configuration = {}) {
2529
2704
  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;
2705
+ const normalizedConfiguration = normalizePeerConnectionConfiguration(
2706
+ configuration,
2707
+ this._configuration,
2708
+ );
2709
+ this._assertNotClosed();
2536
2710
  if (normalizedConfiguration.bundlePolicy !== this._configuration.bundlePolicy) {
2537
2711
  throw makeDOMException("bundlePolicy cannot be changed", "InvalidModificationError");
2538
2712
  }
@@ -2544,6 +2718,15 @@ class RTCPeerConnection extends SimpleEventTarget {
2544
2718
  ) {
2545
2719
  throw makeDOMException("certificates cannot be changed", "InvalidModificationError");
2546
2720
  }
2721
+ if (
2722
+ this.localDescription &&
2723
+ normalizedConfiguration.iceCandidatePoolSize !== this._configuration.iceCandidatePoolSize
2724
+ ) {
2725
+ throw makeDOMException(
2726
+ "iceCandidatePoolSize cannot change with an applied local description",
2727
+ "InvalidModificationError",
2728
+ );
2729
+ }
2547
2730
  this._configuration = normalizedConfiguration;
2548
2731
  }
2549
2732
 
@@ -2645,13 +2828,16 @@ class RTCPeerConnection extends SimpleEventTarget {
2645
2828
  this._assertNotClosed();
2646
2829
  const optionsObject = options !== null && typeof options === "object" ? options : {};
2647
2830
  const iceRestartRequested = optionsObject.iceRestart === true;
2831
+ return this._chainOperation(() => this._createOffer(iceRestartRequested));
2832
+ }
2833
+
2834
+ async _createOffer(iceRestartRequested) {
2648
2835
  if (this._signalingState !== "stable" && this._signalingState !== "have-local-offer") {
2649
- await delayInvalidStateIfOperationPending(this);
2650
2836
  throw makeDOMException("Cannot create offer in current signaling state", "InvalidStateError");
2651
2837
  }
2652
- this._operationsPending += 1;
2653
2838
  try {
2654
2839
  await nextTask();
2840
+ if (this._closed) return new Promise(() => {});
2655
2841
  if (iceRestartRequested && !this._nonstandardLocalIceCredentials) {
2656
2842
  this._iceRestartPending = true;
2657
2843
  this._armDataChannelNativeCloseSuppression();
@@ -2671,8 +2857,6 @@ class RTCPeerConnection extends SimpleEventTarget {
2671
2857
  return offer;
2672
2858
  } catch (error) {
2673
2859
  throw mapNativeError(error, "InvalidStateError");
2674
- } finally {
2675
- this._finishPendingOperation();
2676
2860
  }
2677
2861
  }
2678
2862
 
@@ -2694,13 +2878,22 @@ class RTCPeerConnection extends SimpleEventTarget {
2694
2878
 
2695
2879
  async createAnswer() {
2696
2880
  this._assertNotClosed();
2697
- if (!this.remoteDescription) {
2698
- await delayInvalidStateIfOperationPending(this);
2699
- throw makeDOMException("Remote description is not set", "InvalidStateError");
2881
+ return this._chainOperation(() => this._createAnswer());
2882
+ }
2883
+
2884
+ async _createAnswer() {
2885
+ if (
2886
+ this._signalingState !== "have-remote-offer" &&
2887
+ this._signalingState !== "have-local-pranswer"
2888
+ ) {
2889
+ throw makeDOMException(
2890
+ "Cannot create answer in current signaling state",
2891
+ "InvalidStateError",
2892
+ );
2700
2893
  }
2701
- this._operationsPending += 1;
2702
2894
  try {
2703
2895
  await nextTask();
2896
+ if (this._closed) return new Promise(() => {});
2704
2897
  if (this._jsOnlyIceRestartRemoteOffer) {
2705
2898
  const answer = markJsOnlyIceRestart(
2706
2899
  new RTCSessionDescription(this._ensureNativePeerConnection().createAnswer()),
@@ -2731,27 +2924,26 @@ class RTCPeerConnection extends SimpleEventTarget {
2731
2924
  return answer;
2732
2925
  } catch (error) {
2733
2926
  throw mapNativeError(error, "InvalidStateError");
2734
- } finally {
2735
- this._finishPendingOperation();
2736
2927
  }
2737
2928
  }
2738
2929
 
2739
2930
  async setLocalDescription(description = undefined) {
2740
2931
  this._assertNotClosed();
2741
2932
  const jsOnlyIceRestartDescription = Boolean(description?._webrtcNodeJsOnlyIceRestart);
2742
- let normalized = description === undefined ? null : normalizeDescription(description);
2933
+ const normalized = description === undefined ? null : normalizeDescription(description);
2934
+ return this._chainOperation(() =>
2935
+ this._setLocalDescription(description, normalized, jsOnlyIceRestartDescription),
2936
+ );
2937
+ }
2938
+
2939
+ async _setLocalDescription(description, normalized, jsOnlyIceRestartDescription) {
2743
2940
  const type = normalized ? normalized.type : this._implicitLocalDescriptionType();
2744
- if (
2745
- normalized?.type === "rollback" &&
2746
- this._signalingState !== "have-local-offer" &&
2747
- this._operationsPending === 0
2748
- ) {
2941
+ if (normalized?.type === "rollback" && this._signalingState !== "have-local-offer") {
2749
2942
  throw makeDOMException(
2750
2943
  "Cannot roll back a local description in current signaling state",
2751
2944
  "InvalidStateError",
2752
2945
  );
2753
2946
  }
2754
- this._operationsPending += 1;
2755
2947
  try {
2756
2948
  await nextTask();
2757
2949
  if (this._closed) return new Promise(() => {});
@@ -2861,7 +3053,8 @@ class RTCPeerConnection extends SimpleEventTarget {
2861
3053
  this._localDescriptionSetByApi = hasDataMediaSection(this._localDescription);
2862
3054
  this._syncStatesFromNative();
2863
3055
  this._refreshIceRole();
2864
- for (const candidate of this._pendingIce.splice(0)) await this.addIceCandidate(candidate);
3056
+ for (const candidate of this._pendingIce.splice(0))
3057
+ await this._addExchangedLocalCandidate(candidate);
2865
3058
  this._flushPendingRemoteCandidatesForNative();
2866
3059
  return;
2867
3060
  }
@@ -2966,7 +3159,8 @@ class RTCPeerConnection extends SimpleEventTarget {
2966
3159
  this._commitRemoteDescription();
2967
3160
  this._commitLocalDescription(this._localDescription);
2968
3161
  this._syncSignalingStateFromDescriptions();
2969
- for (const candidate of this._pendingIce.splice(0)) await this.addIceCandidate(candidate);
3162
+ for (const candidate of this._pendingIce.splice(0))
3163
+ await this._addExchangedLocalCandidate(candidate);
2970
3164
  this._flushPendingRemoteCandidatesForNative();
2971
3165
  }
2972
3166
  this._localDescriptionSetByApi = hasDataMediaSection(this._localDescription);
@@ -2987,8 +3181,6 @@ class RTCPeerConnection extends SimpleEventTarget {
2987
3181
  }
2988
3182
  } catch (error) {
2989
3183
  throw mapNativeError(error, "InvalidStateError");
2990
- } finally {
2991
- this._finishPendingOperation();
2992
3184
  }
2993
3185
  }
2994
3186
 
@@ -2996,12 +3188,17 @@ class RTCPeerConnection extends SimpleEventTarget {
2996
3188
  this._assertNotClosed();
2997
3189
  const jsOnlyIceRestartDescription = Boolean(description?._webrtcNodeJsOnlyIceRestart);
2998
3190
  const normalized = normalizeDescription(description);
3191
+ return this._chainOperation(() =>
3192
+ this._setRemoteDescription(description, normalized, jsOnlyIceRestartDescription),
3193
+ );
3194
+ }
3195
+
3196
+ async _setRemoteDescription(description, normalized, jsOnlyIceRestartDescription) {
2999
3197
  if (
3000
3198
  normalized.type === "answer" &&
3001
3199
  this._signalingState !== "have-local-offer" &&
3002
3200
  this._signalingState !== "have-remote-pranswer" &&
3003
- !this._jsOnlyIceRestartOfferPending &&
3004
- this._operationsPending === 0
3201
+ !this._jsOnlyIceRestartOfferPending
3005
3202
  ) {
3006
3203
  throw makeDOMException(
3007
3204
  "Cannot set a remote answer in current signaling state",
@@ -3011,25 +3208,19 @@ class RTCPeerConnection extends SimpleEventTarget {
3011
3208
  if (
3012
3209
  normalized.type === "pranswer" &&
3013
3210
  this._signalingState !== "have-local-offer" &&
3014
- this._signalingState !== "have-remote-pranswer" &&
3015
- this._operationsPending === 0
3211
+ this._signalingState !== "have-remote-pranswer"
3016
3212
  ) {
3017
3213
  throw makeDOMException(
3018
3214
  "Cannot set a remote pranswer in current signaling state",
3019
3215
  "InvalidStateError",
3020
3216
  );
3021
3217
  }
3022
- if (
3023
- normalized.type === "rollback" &&
3024
- this._signalingState !== "have-remote-offer" &&
3025
- this._operationsPending === 0
3026
- ) {
3218
+ if (normalized.type === "rollback" && this._signalingState !== "have-remote-offer") {
3027
3219
  throw makeDOMException(
3028
3220
  "Cannot roll back a remote description in current signaling state",
3029
3221
  "InvalidStateError",
3030
3222
  );
3031
3223
  }
3032
- this._operationsPending += 1;
3033
3224
  try {
3034
3225
  await nextTask();
3035
3226
  if (this._closed) return new Promise(() => {});
@@ -3247,7 +3438,8 @@ class RTCPeerConnection extends SimpleEventTarget {
3247
3438
  this._dispatchSignalingStateChange();
3248
3439
  }
3249
3440
  if (normalized.type !== "offer") {
3250
- for (const candidate of this._pendingIce.splice(0)) await this.addIceCandidate(candidate);
3441
+ for (const candidate of this._pendingIce.splice(0))
3442
+ await this._addExchangedLocalCandidate(candidate);
3251
3443
  this._flushPendingRemoteCandidatesForNative();
3252
3444
  }
3253
3445
  await nextTask();
@@ -3259,32 +3451,26 @@ class RTCPeerConnection extends SimpleEventTarget {
3259
3451
  }
3260
3452
  } catch (error) {
3261
3453
  throw mapNativeError(error, "InvalidStateError");
3262
- } finally {
3263
- this._finishPendingOperation();
3264
3454
  }
3265
3455
  }
3266
3456
 
3267
3457
  async addIceCandidate(candidate = null) {
3268
3458
  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
3459
  if (candidate instanceof RTCIceCandidate && candidate._webrtcNodeLocalCandidate) {
3275
- await this._addExchangedLocalCandidate(candidate);
3276
- return;
3460
+ const snapshot = new RTCIceCandidate(candidate);
3461
+ return this._chainOperation(() => this._addExchangedLocalCandidate(snapshot));
3277
3462
  }
3278
3463
  const normalized = normalizeAddIceCandidateInput(candidate);
3464
+ return this._chainOperation(() => this._addIceCandidate(normalized));
3465
+ }
3466
+
3467
+ async _addIceCandidate(normalized) {
3279
3468
  if (!this.remoteDescription) {
3280
- await delayInvalidStateIfOperationPending(this);
3281
- if (!this.remoteDescription) {
3282
- throw makeDOMException("Remote description is not set", "InvalidStateError");
3283
- }
3469
+ throw makeDOMException("Remote description is not set", "InvalidStateError");
3284
3470
  }
3285
- this._operationsPending += 1;
3286
3471
  try {
3287
3472
  await nextTask();
3473
+ if (this._closed) return new Promise(() => {});
3288
3474
  const remoteDescription = appendRemoteCandidateToDescription(
3289
3475
  this._remoteDescription,
3290
3476
  normalized,
@@ -3317,8 +3503,6 @@ class RTCPeerConnection extends SimpleEventTarget {
3317
3503
  this._refreshCurrentOrPendingRemoteDescription(remoteDescription);
3318
3504
  } catch (error) {
3319
3505
  throw mapNativeError(error, "OperationError");
3320
- } finally {
3321
- this._finishPendingOperation();
3322
3506
  }
3323
3507
  }
3324
3508
 
@@ -3328,7 +3512,7 @@ class RTCPeerConnection extends SimpleEventTarget {
3328
3512
  if (this._pairedPeer) this._pairedPeer._sameProcessIceCandidateExchange = true;
3329
3513
  this._rememberRemoteIceCandidate(candidate);
3330
3514
  this._markExplicitIceCandidateExchange();
3331
- if (!this.remoteDescription || this._shouldDeferRemoteCandidateUntilLocalAnswer()) {
3515
+ if (!this.remoteDescription) {
3332
3516
  if (!this._pendingIce.some((entry) => sameCandidate(entry, candidate))) {
3333
3517
  this._pendingIce.push(candidate);
3334
3518
  }
@@ -3341,10 +3525,16 @@ class RTCPeerConnection extends SimpleEventTarget {
3341
3525
  nativeCandidate.sdpMid = resolveCandidateMid(this._remoteDescription, candidate);
3342
3526
  }
3343
3527
  try {
3344
- this._ensureNativePeerConnection().addRemoteCandidate(nativeCandidate);
3345
- this._refreshCurrentOrPendingRemoteDescription(
3346
- appendRemoteCandidateToDescription(this._remoteDescription, candidate),
3528
+ const remoteDescription = appendRemoteCandidateToDescription(
3529
+ this._remoteDescription,
3530
+ candidate,
3347
3531
  );
3532
+ if (this._shouldDeferRemoteCandidateUntilLocalAnswer()) {
3533
+ this._queuePendingRemoteCandidatesForNative([candidate]);
3534
+ } else {
3535
+ this._ensureNativePeerConnection().addRemoteCandidate(nativeCandidate);
3536
+ }
3537
+ this._refreshCurrentOrPendingRemoteDescription(remoteDescription);
3348
3538
  } catch {
3349
3539
  // Exchanged local candidates are delivered from event handlers that do
3350
3540
  // not await addIceCandidate(); keep them best-effort like browser ICE.
@@ -3354,6 +3544,10 @@ class RTCPeerConnection extends SimpleEventTarget {
3354
3544
  close() {
3355
3545
  if (this._closed) return;
3356
3546
  this._closed = true;
3547
+ this._operationQueue.length = 0;
3548
+ this._operationsPending = 0;
3549
+ const operationIdleCallbacks = this._operationIdleCallbacks.splice(0);
3550
+ for (const callback of operationIdleCallbacks) setImmediate(callback);
3357
3551
  const pairedPeer = this._pairedPeer;
3358
3552
  this._unregisterLocalDescriptionsForPairing();
3359
3553
  const nativePeer = this._native;
@@ -3385,6 +3579,7 @@ class RTCPeerConnection extends SimpleEventTarget {
3385
3579
  }
3386
3580
 
3387
3581
  _registerLocalDescriptionForPairing() {
3582
+ if (this._closed) return;
3388
3583
  const key = descriptionPairingKey(this._localDescription);
3389
3584
  if (!key) return;
3390
3585
  localDescriptionOwners.set(key, new WeakRef(this));
@@ -3542,7 +3737,10 @@ class RTCPeerConnection extends SimpleEventTarget {
3542
3737
  this._pairedPeer._iceConnectionState === "connected" ||
3543
3738
  this._pairedPeer._iceConnectionState === "completed");
3544
3739
  const nativeConnected =
3545
- nativeTransportConnected && dataTransportNegotiated && !this._selfRemoteDescription;
3740
+ nativeTransportConnected &&
3741
+ dataTransportNegotiated &&
3742
+ (!this._pairedPeer || pairedDataTransportNegotiated) &&
3743
+ !this._selfRemoteDescription;
3546
3744
  const sameProcessConnected =
3547
3745
  this._sameProcessIceCandidateExchange &&
3548
3746
  dataTransportNegotiated &&
@@ -3687,6 +3885,30 @@ class RTCPeerConnection extends SimpleEventTarget {
3687
3885
  }
3688
3886
  }
3689
3887
 
3888
+ _chainOperation(operation) {
3889
+ this._assertNotClosed();
3890
+ return new Promise((resolve, reject) => {
3891
+ const settle = (value, failed) => {
3892
+ // Closing a peer leaves active and queued operation promises pending.
3893
+ if (this._closed) return;
3894
+ if (failed) reject(value);
3895
+ else resolve(value);
3896
+ this._operationQueue.shift();
3897
+ this._finishPendingOperation();
3898
+ this._operationQueue[0]?.();
3899
+ };
3900
+ const run = () => {
3901
+ operation().then(
3902
+ (value) => settle(value, false),
3903
+ (error) => settle(error, true),
3904
+ );
3905
+ };
3906
+ this._operationsPending += 1;
3907
+ this._operationQueue.push(run);
3908
+ if (this._operationQueue.length === 1) run();
3909
+ });
3910
+ }
3911
+
3690
3912
  _finishPendingOperation() {
3691
3913
  this._operationsPending = Math.max(0, this._operationsPending - 1);
3692
3914
  if (this._operationsPending === 0) {
@@ -4106,7 +4328,10 @@ class RTCPeerConnection extends SimpleEventTarget {
4106
4328
  }
4107
4329
 
4108
4330
  _implicitLocalDescriptionType() {
4109
- return this._signalingState === "have-remote-offer" ? "answer" : "offer";
4331
+ return this._signalingState === "have-remote-offer" ||
4332
+ this._signalingState === "have-local-pranswer"
4333
+ ? "answer"
4334
+ : "offer";
4110
4335
  }
4111
4336
 
4112
4337
  _descriptionSignalingState() {
@@ -4415,7 +4640,8 @@ class RTCPeerConnection extends SimpleEventTarget {
4415
4640
  this._commitLocalDescription(this._localDescription);
4416
4641
  this._syncSignalingStateFromDescriptions();
4417
4642
  this._scheduleNativeCandidateGathering();
4418
- for (const candidate of this._pendingIce.splice(0)) await this.addIceCandidate(candidate);
4643
+ for (const candidate of this._pendingIce.splice(0))
4644
+ await this._addExchangedLocalCandidate(candidate);
4419
4645
  this._flushPendingRemoteCandidatesForNative();
4420
4646
  await nextTask();
4421
4647
  await this._refreshLocalDescriptionAfterGatheringWindow();