@ac-kit/net-webrtc 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +28 -0
  3. package/README.md +99 -2
  4. package/dist/_ice-servers.d.ts +15 -0
  5. package/dist/_ice-servers.d.ts.map +1 -0
  6. package/dist/_ice-servers.js +33 -0
  7. package/dist/_ice-servers.js.map +1 -0
  8. package/dist/_mdns.d.ts +53 -0
  9. package/dist/_mdns.d.ts.map +1 -0
  10. package/dist/_mdns.js +239 -0
  11. package/dist/_mdns.js.map +1 -0
  12. package/dist/_native.d.ts +82 -0
  13. package/dist/_native.d.ts.map +1 -0
  14. package/dist/_native.js +51 -0
  15. package/dist/_native.js.map +1 -0
  16. package/dist/_peer-connection-driver.d.ts +95 -0
  17. package/dist/_peer-connection-driver.d.ts.map +1 -0
  18. package/dist/_peer-connection-driver.js +500 -0
  19. package/dist/_peer-connection-driver.js.map +1 -0
  20. package/dist/_stun.d.ts +28 -0
  21. package/dist/_stun.d.ts.map +1 -0
  22. package/dist/_stun.js +115 -0
  23. package/dist/_stun.js.map +1 -0
  24. package/dist/dtls-fingerprint.d.ts +18 -0
  25. package/dist/dtls-fingerprint.d.ts.map +1 -0
  26. package/dist/dtls-fingerprint.js +25 -0
  27. package/dist/dtls-fingerprint.js.map +1 -0
  28. package/dist/errors.d.ts +27 -0
  29. package/dist/errors.d.ts.map +1 -0
  30. package/dist/errors.js +42 -0
  31. package/dist/errors.js.map +1 -0
  32. package/dist/index.d.ts +5 -0
  33. package/dist/index.d.ts.map +1 -0
  34. package/dist/index.js +5 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/webrtc-data-channel.d.ts +80 -0
  37. package/dist/webrtc-data-channel.d.ts.map +1 -0
  38. package/dist/webrtc-data-channel.js +138 -0
  39. package/dist/webrtc-data-channel.js.map +1 -0
  40. package/dist/webrtc-peer-connection.d.ts +205 -0
  41. package/dist/webrtc-peer-connection.d.ts.map +1 -0
  42. package/dist/webrtc-peer-connection.js +324 -0
  43. package/dist/webrtc-peer-connection.js.map +1 -0
  44. package/package.json +75 -3
@@ -0,0 +1,51 @@
1
+ import { createRequire } from "node:module";
2
+ import { UnsupportedError } from "@ac-kit/core";
3
+ let binding_ = null;
4
+ /**
5
+ * The native binding for this platform, loaded on first use so that importing
6
+ * the package never fails on a platform without one. Each platform's binary is
7
+ * its own package, `@ac-kit/net-webrtc-<platform>`, which the package manager
8
+ * installs as an optional dependency only where it runs.
9
+ *
10
+ * @throws {UnsupportedError} When no binary was installed for this platform.
11
+ */
12
+ export function nativeWebRtc_() {
13
+ if (binding_ === null) {
14
+ const name = `@ac-kit/net-webrtc-${nativePlatform_()}`;
15
+ const require = createRequire(import.meta.url);
16
+ try {
17
+ // A native addon's exports are untyped; their shape is fixed by
18
+ // `rust/rtc-node/src/lib.rs` and checked by the tests.
19
+ binding_ = require(name);
20
+ }
21
+ catch (error) {
22
+ throw new UnsupportedError(`No WebRTC native binding: ${name}`, {
23
+ cause: error,
24
+ });
25
+ }
26
+ }
27
+ return binding_;
28
+ }
29
+ /**
30
+ * The binary's platform suffix: `linux-x64-gnu`, `darwin-arm64`,
31
+ * `win32-x64-msvc`.
32
+ */
33
+ function nativePlatform_() {
34
+ const { platform, arch } = process;
35
+ if (platform === "linux") {
36
+ return `${platform}-${arch}-${isGlibc_() ? "gnu" : "musl"}`;
37
+ }
38
+ if (platform === "win32") {
39
+ return `${platform}-${arch}-msvc`;
40
+ }
41
+ return `${platform}-${arch}`;
42
+ }
43
+ function isGlibc_() {
44
+ const report = process.report.getReport();
45
+ // `header.glibcVersionRuntime` is set only on glibc; the report is typed as
46
+ // an open object.
47
+ const header = report
48
+ .header;
49
+ return header?.glibcVersionRuntime !== undefined;
50
+ }
51
+ //# sourceMappingURL=_native.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_native.js","sourceRoot":"","sources":["../src/_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ClB,MAAM,MAAM,GAAI,MAAwD;SACtE,MAAM,CAAC;IACT,OAAO,MAAM,EAAE,mBAAmB,KAAK,SAAS,CAAC;AAClD,CAAC"}
@@ -0,0 +1,95 @@
1
+ import type { Callable } from "@ac-kit/core";
2
+ import type { StunServer_ } from "./_ice-servers.js";
3
+ import { type NativeDataChannelInfo_, type NativeDataChannelOptions_, type NativeEvent_, type NativeSessionDescription_ } from "./_native.js";
4
+ /** What the driver needs to start. */
5
+ export type PeerConnectionDriverOptions_ = {
6
+ readonly stunServers: readonly StunServer_[];
7
+ readonly bindAddress: string | undefined;
8
+ readonly portRange: readonly [first: number, last: number] | undefined;
9
+ readonly maxMessageSize: number | undefined;
10
+ };
11
+ /**
12
+ * Drives webrtc-rs's sans-I/O `rtc` state machine, as `net-quic` drives quiche:
13
+ * this side owns the UDP sockets and the timer, feeds what arrives in, sends
14
+ * what the state machine produced, and re-arms the timer.
15
+ *
16
+ * Every input ends in {@link process}, which runs once per event-loop turn
17
+ * however many datagrams arrived or calls were made in it: a burst costs one
18
+ * crossing into the binding, not one per datagram.
19
+ *
20
+ * Gathering starts once a local description is set, as in a browser: host
21
+ * candidates at once, then a server-reflexive one per host socket and STUN
22
+ * server that answers. A remote candidate named by mDNS is added once its name
23
+ * resolves, or dropped.
24
+ */
25
+ export declare class PeerConnectionDriver_ {
26
+ private readonly options;
27
+ private readonly onEvent;
28
+ private readonly native;
29
+ private readonly sockets;
30
+ private readonly stunTransactions;
31
+ private readonly bound;
32
+ private readonly mdnsAbort;
33
+ /** Channels to close once what was sent on them is acknowledged. */
34
+ private readonly pendingCloses;
35
+ private gathering;
36
+ private closed;
37
+ private processScheduled;
38
+ private timer;
39
+ private timerDeadline;
40
+ private connected;
41
+ private lastLocal;
42
+ private lastRemote;
43
+ constructor(options: PeerConnectionDriverOptions_, onEvent: Callable<[event: NativeEvent_]>);
44
+ private bindSockets;
45
+ private receive;
46
+ /** Settles the STUN transaction `data` answers; `false` when it answers none. */
47
+ private receiveStun;
48
+ private startGathering;
49
+ private gather;
50
+ /**
51
+ * Asks a STUN server for `host`'s mapped address; `null` when it does not
52
+ * tell.
53
+ */
54
+ private queryStun;
55
+ /** Runs {@link process} once this turn's I/O and calls are in. */
56
+ private scheduleProcess;
57
+ /** Deliver the state machine's events, send its datagrams, re-arm the timer. */
58
+ private process;
59
+ private transmit;
60
+ /**
61
+ * Keeps a timer that fires no later than the state machine's deadline. One
62
+ * that fires early is harmless — `onTimeout` before the deadline does nothing
63
+ * — so it is replaced only when the deadline moves earlier.
64
+ */
65
+ private armTimer;
66
+ setLocalDescription(type: string | null): NativeSessionDescription_;
67
+ setRemoteDescription(description: NativeSessionDescription_): void;
68
+ localDescription(): NativeSessionDescription_ | null;
69
+ remoteDescription(): NativeSessionDescription_ | null;
70
+ /**
71
+ * Adds a remote candidate. One whose address is a `.local` name is added once
72
+ * mDNS resolves it, and dropped if it does not, as browsers do.
73
+ *
74
+ * @throws {Error} When no remote description is set, or the candidate is
75
+ * malformed.
76
+ */
77
+ addRemoteCandidate(candidate: string, mid: string | null): void;
78
+ selectedAddresses(): [local: string, remote: string] | null;
79
+ createDataChannel(label: string, options: NativeDataChannelOptions_): number;
80
+ dataChannelInfo(channel: number): NativeDataChannelInfo_;
81
+ sendBinary(channel: number, data: Uint8Array): void;
82
+ sendText(channel: number, text: string): void;
83
+ bufferedAmount(channel: number): number;
84
+ setBufferedAmountLowThreshold(channel: number, amount: number): void;
85
+ /**
86
+ * Closes a channel once SCTP has acknowledged everything sent on it: `rtc`
87
+ * resets the stream at once and drops what is still queued, where a browser
88
+ * sends it first.
89
+ */
90
+ closeDataChannel(channel: number): void;
91
+ private closeDrainedChannels;
92
+ /** Close everything; no event follows. Idempotent. */
93
+ close(): void;
94
+ }
95
+ //# sourceMappingURL=_peer-connection-driver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_peer-connection-driver.d.ts","sourceRoot":"","sources":["../src/_peer-connection-driver.ts"],"names":[],"mappings":"AAIA,OA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AAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAEnE;IAED;;;;OAIG;IACH,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAGtC;IAED,OAAO,CAAC,oBAAoB;IAS5B,sDAAsD;IACtD,KAAK,IAAI,IAAI,CA2BZ;CACD"}
@@ -0,0 +1,500 @@
1
+ import { lookup } from "node:dns/promises";
2
+ import { isIP } from "node:net";
3
+ import { networkInterfaces } from "node:os";
4
+ import { DgramSocket } from "@ac-kit/node";
5
+ import { resolveMdnsName_ } from "./_mdns.js";
6
+ import { nativeWebRtc_, } from "./_native.js";
7
+ import { decodeStunBindingResponse_, encodeStunBindingRequest_, isStunMessage_, } from "./_stun.js";
8
+ /** STUN Binding retransmissions (RFC 8489 §6.2.1, shortened): 3 tries. */
9
+ const STUN_RETRANSMIT_MS_ = [0, 500, 1500];
10
+ /** A STUN server that has not answered by then gives no candidate. */
11
+ const STUN_TIMEOUT_MS_ = 3000;
12
+ /** How long a `.local` candidate's name is asked for. */
13
+ const MDNS_TIMEOUT_MS_ = 3000;
14
+ const MDNS_RETRY_MS_ = 1000;
15
+ /**
16
+ * Socket buffers asked of the kernel, which caps them (`net.core.rmem_max`): a
17
+ * burst a receive buffer cannot hold is lost, and SCTP backs off for it.
18
+ */
19
+ const SOCKET_BUFFER_SIZE_ = 4 * 1024 * 1024;
20
+ /**
21
+ * Datagrams sent per turn of the event loop before reading the sockets again.
22
+ * SCTP's window can release thousands at once; a peer, or this process's own
23
+ * other connections, would drop most of them.
24
+ */
25
+ const MAX_DATAGRAMS_PER_POLL_ = 16;
26
+ /** Polls per {@link PeerConnectionDriver_.process} before yielding. */
27
+ const MAX_PROCESS_ROUNDS_ = 8;
28
+ /**
29
+ * Every address a host candidate is gathered on: `bindAddress` alone, or each
30
+ * non-internal interface address of its family, the loopback ones only when
31
+ * there is nothing else. One socket per address, since a wildcard socket cannot
32
+ * tell which local address a datagram arrived on, and ICE needs it.
33
+ */
34
+ function hostAddresses_(bindAddress) {
35
+ if (bindAddress !== undefined &&
36
+ bindAddress !== "0.0.0.0" &&
37
+ bindAddress !== "::") {
38
+ return [bindAddress];
39
+ }
40
+ const wanted = bindAddress === "::" ? "IPv6" : "IPv4";
41
+ const external = [];
42
+ const internal = [];
43
+ for (const addresses of Object.values(networkInterfaces())) {
44
+ for (const { address, family, internal: isInternal } of addresses ?? []) {
45
+ // A link-local IPv6 address needs a scope id a candidate cannot carry.
46
+ if (family !== wanted || address.startsWith("fe80:")) {
47
+ continue;
48
+ }
49
+ (isInternal ? internal : external).push(address);
50
+ }
51
+ }
52
+ return external.length > 0 ? external : internal;
53
+ }
54
+ async function bindHostSocket_(address, portRange) {
55
+ const [first, last] = portRange ?? [0, 0];
56
+ let lastError;
57
+ for (let port = first; port <= last; port++) {
58
+ const socket = DgramSocket.from({
59
+ type: isIP(address) === 6 ? "udp6" : "udp4",
60
+ recvBufferSize: SOCKET_BUFFER_SIZE_,
61
+ sendBufferSize: SOCKET_BUFFER_SIZE_,
62
+ });
63
+ try {
64
+ await socket.bind(port, address);
65
+ const bound = socket.address();
66
+ if (bound === null) {
67
+ throw new Error("UDP socket is not bound");
68
+ }
69
+ return { socket, address, port: bound.port };
70
+ }
71
+ catch (error) {
72
+ lastError = error;
73
+ await socket.close().catch(() => undefined);
74
+ }
75
+ }
76
+ throw lastError;
77
+ }
78
+ function transactionKey_(transactionId) {
79
+ return Buffer.from(transactionId.buffer, transactionId.byteOffset, 12).toString("hex");
80
+ }
81
+ /** The connection-address token of an SDP candidate attribute. */
82
+ function candidateAddress_(candidate) {
83
+ return candidate.replace(/^a=/, "").split(" ")[4];
84
+ }
85
+ /**
86
+ * Drives webrtc-rs's sans-I/O `rtc` state machine, as `net-quic` drives quiche:
87
+ * this side owns the UDP sockets and the timer, feeds what arrives in, sends
88
+ * what the state machine produced, and re-arms the timer.
89
+ *
90
+ * Every input ends in {@link process}, which runs once per event-loop turn
91
+ * however many datagrams arrived or calls were made in it: a burst costs one
92
+ * crossing into the binding, not one per datagram.
93
+ *
94
+ * Gathering starts once a local description is set, as in a browser: host
95
+ * candidates at once, then a server-reflexive one per host socket and STUN
96
+ * server that answers. A remote candidate named by mDNS is added once its name
97
+ * resolves, or dropped.
98
+ */
99
+ export class PeerConnectionDriver_ {
100
+ options;
101
+ onEvent;
102
+ native;
103
+ sockets = new Map();
104
+ stunTransactions = new Map();
105
+ bound;
106
+ mdnsAbort = new AbortController();
107
+ /** Channels to close once what was sent on them is acknowledged. */
108
+ pendingCloses = new Set();
109
+ gathering = false;
110
+ closed = false;
111
+ processScheduled = false;
112
+ timer = null;
113
+ timerDeadline = Number.POSITIVE_INFINITY;
114
+ connected = false;
115
+ lastLocal = null;
116
+ lastRemote = null;
117
+ constructor(options, onEvent) {
118
+ this.options = options;
119
+ this.onEvent = onEvent;
120
+ this.native = new (nativeWebRtc_().RtcPeerConnection)({
121
+ maxMessageSize: options.maxMessageSize,
122
+ });
123
+ this.bound = this.bindSockets();
124
+ // Reported when gathering starts.
125
+ this.bound.catch(() => undefined);
126
+ }
127
+ async bindSockets() {
128
+ // An address that cannot be bound (vanished, tentative, its port range
129
+ // taken) costs its candidate only, as in a browser.
130
+ const settled = await Promise.allSettled(hostAddresses_(this.options.bindAddress).map((address) => bindHostSocket_(address, this.options.portRange)));
131
+ const hosts = settled.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
132
+ if (hosts.length === 0) {
133
+ const failure = settled.find((result) => result.status === "rejected");
134
+ throw failure?.reason ?? new Error("No local address to bind");
135
+ }
136
+ for (const host of hosts) {
137
+ if (this.closed) {
138
+ await host.socket.close();
139
+ continue;
140
+ }
141
+ this.sockets.set(host.address, host);
142
+ host.socket.subscribe("message", (data, _size, from) => this.receive(host, data, from));
143
+ host.socket.subscribe("error", () => {
144
+ // A failed send or an ICMP error: that datagram is lost, as the
145
+ // network might have lost it, and ICE recovers.
146
+ });
147
+ }
148
+ }
149
+ receive(host, data, from) {
150
+ if (this.closed) {
151
+ return;
152
+ }
153
+ if (this.stunTransactions.size > 0 &&
154
+ isStunMessage_(data) &&
155
+ this.receiveStun(data, from)) {
156
+ return;
157
+ }
158
+ try {
159
+ this.native.handleRead(data, host.address, host.port, from.address, from.port);
160
+ }
161
+ catch {
162
+ // A datagram the state machine rejects is dropped, as the network might have.
163
+ }
164
+ this.scheduleProcess();
165
+ }
166
+ /** Settles the STUN transaction `data` answers; `false` when it answers none. */
167
+ receiveStun(data, from) {
168
+ const transaction = this.stunTransactions.get(transactionKey_(data.subarray(8, 20)));
169
+ if (transaction === undefined ||
170
+ transaction.port !== from.port ||
171
+ transaction.address !== from.address) {
172
+ return false;
173
+ }
174
+ const result = decodeStunBindingResponse_(data, transaction.transactionId);
175
+ if (result !== null) {
176
+ transaction.settle(result.kind === "mapped" ? result : null);
177
+ }
178
+ return true;
179
+ }
180
+ startGathering() {
181
+ if (this.gathering) {
182
+ return;
183
+ }
184
+ this.gathering = true;
185
+ void this.gather();
186
+ }
187
+ async gather() {
188
+ try {
189
+ await this.bound;
190
+ }
191
+ catch (error) {
192
+ // No socket could be bound: nothing can connect.
193
+ this.onEvent({ type: "state", state: "failed", message: String(error) });
194
+ return;
195
+ }
196
+ if (this.closed) {
197
+ return;
198
+ }
199
+ const hosts = [...this.sockets.values()];
200
+ for (const host of hosts) {
201
+ this.native.addLocalHostCandidate(host.address, host.port);
202
+ }
203
+ this.scheduleProcess();
204
+ const servers = await Promise.all(this.options.stunServers.map(async (server) => {
205
+ try {
206
+ return {
207
+ ...server,
208
+ addresses: await lookup(server.host, { all: true }),
209
+ };
210
+ }
211
+ catch {
212
+ return { ...server, addresses: [] };
213
+ }
214
+ }));
215
+ if (this.closed) {
216
+ return;
217
+ }
218
+ const seen = new Set(hosts.map((host) => `${host.address}:${host.port}`));
219
+ await Promise.all(hosts.flatMap((host) => servers.map(async (server) => {
220
+ const family = isIP(host.address);
221
+ const target = server.addresses.find((address) => address.family === family);
222
+ if (target === undefined) {
223
+ return;
224
+ }
225
+ const mapped = await this.queryStun(host, target.address, server.port);
226
+ const key = mapped === null ? null : `${mapped.address}:${mapped.port}`;
227
+ // A mapping equal to a host candidate or to an earlier one is
228
+ // redundant (RFC 8445 §5.1.3).
229
+ if (mapped === null || key === null || seen.has(key) || this.closed) {
230
+ return;
231
+ }
232
+ seen.add(key);
233
+ this.native.addLocalServerReflexiveCandidate(mapped.address, mapped.port, host.address, host.port);
234
+ this.scheduleProcess();
235
+ })));
236
+ if (!this.closed) {
237
+ this.native.endOfLocalCandidates();
238
+ this.scheduleProcess();
239
+ }
240
+ }
241
+ /**
242
+ * Asks a STUN server for `host`'s mapped address; `null` when it does not
243
+ * tell.
244
+ */
245
+ queryStun(host, address, port) {
246
+ if (this.closed) {
247
+ return Promise.resolve(null);
248
+ }
249
+ const { message, transactionId } = encodeStunBindingRequest_();
250
+ const key = transactionKey_(transactionId);
251
+ const settled = Promise.withResolvers();
252
+ const timers = STUN_RETRANSMIT_MS_.map((delay) => setTimeout(() => {
253
+ host.socket.send(port, address, message).catch(() => {
254
+ // Lost: the next retransmission or the timeout follows.
255
+ });
256
+ }, delay));
257
+ timers.push(setTimeout(() => settled.resolve(null), STUN_TIMEOUT_MS_));
258
+ this.stunTransactions.set(key, {
259
+ transactionId,
260
+ address,
261
+ port,
262
+ settle: settled.resolve,
263
+ });
264
+ return settled.promise.finally(() => {
265
+ for (const timer of timers) {
266
+ clearTimeout(timer);
267
+ }
268
+ this.stunTransactions.delete(key);
269
+ });
270
+ }
271
+ /** Runs {@link process} once this turn's I/O and calls are in. */
272
+ scheduleProcess() {
273
+ if (this.processScheduled || this.closed) {
274
+ return;
275
+ }
276
+ this.processScheduled = true;
277
+ setImmediate(() => this.process());
278
+ }
279
+ /** Deliver the state machine's events, send its datagrams, re-arm the timer. */
280
+ process() {
281
+ this.processScheduled = false;
282
+ // Event handlers may send or close: poll again until nothing more comes
283
+ // out, a bounded number of times before yielding to the event loop.
284
+ for (let round = 0; !this.closed; round++) {
285
+ if (round === MAX_PROCESS_ROUNDS_) {
286
+ this.scheduleProcess();
287
+ return;
288
+ }
289
+ this.closeDrainedChannels();
290
+ const { datagrams, events, timeoutMs } = this.native.poll(MAX_DATAGRAMS_PER_POLL_);
291
+ this.transmit(datagrams);
292
+ for (const event of events) {
293
+ if (event.type === "state") {
294
+ this.connected = event.state === "connected";
295
+ }
296
+ this.onEvent(event);
297
+ if (this.closed) {
298
+ return;
299
+ }
300
+ }
301
+ if (datagrams.length === MAX_DATAGRAMS_PER_POLL_) {
302
+ // More are waiting: send them on the next turn, after this one's
303
+ // sockets are read, rather than flood a receive buffer.
304
+ this.scheduleProcess();
305
+ return;
306
+ }
307
+ if (events.length === 0 && datagrams.length === 0) {
308
+ this.armTimer(timeoutMs);
309
+ return;
310
+ }
311
+ }
312
+ }
313
+ transmit(datagrams) {
314
+ for (const datagram of datagrams) {
315
+ const host = this.sockets.get(datagram.localAddress);
316
+ if (host === undefined) {
317
+ continue;
318
+ }
319
+ if (this.connected) {
320
+ this.lastLocal = `${host.address}:${host.port}`;
321
+ this.lastRemote = `${datagram.address}:${datagram.port}`;
322
+ }
323
+ host.socket
324
+ .send(datagram.port, datagram.address, datagram.data)
325
+ .catch(() => {
326
+ // Lost, as the network might have lost it.
327
+ });
328
+ }
329
+ }
330
+ /**
331
+ * Keeps a timer that fires no later than the state machine's deadline. One
332
+ * that fires early is harmless — `onTimeout` before the deadline does nothing
333
+ * — so it is replaced only when the deadline moves earlier.
334
+ */
335
+ armTimer(timeoutMs) {
336
+ if (timeoutMs === undefined) {
337
+ return;
338
+ }
339
+ const deadline = performance.now() + timeoutMs;
340
+ if (this.timer !== null && this.timerDeadline <= deadline) {
341
+ return;
342
+ }
343
+ if (this.timer !== null) {
344
+ clearTimeout(this.timer);
345
+ }
346
+ this.timerDeadline = deadline;
347
+ this.timer = setTimeout(() => {
348
+ this.timer = null;
349
+ this.timerDeadline = Number.POSITIVE_INFINITY;
350
+ if (this.closed) {
351
+ return;
352
+ }
353
+ try {
354
+ this.native.onTimeout();
355
+ }
356
+ catch (error) {
357
+ // The state machine cannot go on: report it as ICE would.
358
+ this.onEvent({
359
+ type: "state",
360
+ state: "failed",
361
+ message: String(error),
362
+ });
363
+ return;
364
+ }
365
+ this.process();
366
+ }, timeoutMs);
367
+ }
368
+ setLocalDescription(type) {
369
+ const description = this.native.setLocalDescription(type);
370
+ this.startGathering();
371
+ this.scheduleProcess();
372
+ return description;
373
+ }
374
+ setRemoteDescription(description) {
375
+ this.native.setRemoteDescription(description);
376
+ this.scheduleProcess();
377
+ }
378
+ localDescription() {
379
+ return this.native.localDescription();
380
+ }
381
+ remoteDescription() {
382
+ return this.native.remoteDescription();
383
+ }
384
+ /**
385
+ * Adds a remote candidate. One whose address is a `.local` name is added once
386
+ * mDNS resolves it, and dropped if it does not, as browsers do.
387
+ *
388
+ * @throws {Error} When no remote description is set, or the candidate is
389
+ * malformed.
390
+ */
391
+ addRemoteCandidate(candidate, mid) {
392
+ const address = candidateAddress_(candidate);
393
+ if (address === undefined || !address.toLowerCase().endsWith(".local")) {
394
+ this.native.addRemoteCandidate(candidate, mid);
395
+ this.scheduleProcess();
396
+ return;
397
+ }
398
+ if (this.native.remoteDescription() === null) {
399
+ // The same error an address candidate gets, at the same time.
400
+ this.native.addRemoteCandidate(candidate, mid);
401
+ }
402
+ resolveMdnsName_(address, {
403
+ timeoutMs: MDNS_TIMEOUT_MS_,
404
+ retryMs: MDNS_RETRY_MS_,
405
+ signal: this.mdnsAbort.signal,
406
+ })
407
+ .then((resolved) => {
408
+ if (resolved === null || this.closed) {
409
+ return;
410
+ }
411
+ const tokens = candidate.split(" ");
412
+ tokens[4] = resolved;
413
+ try {
414
+ this.native.addRemoteCandidate(tokens.join(" "), mid);
415
+ }
416
+ catch {
417
+ // Malformed past its address: dropped, like an unresolved one.
418
+ }
419
+ this.scheduleProcess();
420
+ })
421
+ .catch(() => {
422
+ // Unresolvable, as when nobody answers: dropped.
423
+ });
424
+ }
425
+ selectedAddresses() {
426
+ return this.connected && this.lastLocal !== null && this.lastRemote !== null
427
+ ? [this.lastLocal, this.lastRemote]
428
+ : null;
429
+ }
430
+ createDataChannel(label, options) {
431
+ const channel = this.native.createDataChannel(label, options);
432
+ this.scheduleProcess();
433
+ return channel;
434
+ }
435
+ dataChannelInfo(channel) {
436
+ return this.native.dataChannelInfo(channel);
437
+ }
438
+ sendBinary(channel, data) {
439
+ this.native.dataChannelSendBinary(channel, data);
440
+ this.scheduleProcess();
441
+ }
442
+ sendText(channel, text) {
443
+ this.native.dataChannelSendText(channel, text);
444
+ this.scheduleProcess();
445
+ }
446
+ bufferedAmount(channel) {
447
+ return this.native.dataChannelBufferedAmount(channel);
448
+ }
449
+ setBufferedAmountLowThreshold(channel, amount) {
450
+ this.native.dataChannelSetBufferedAmountLowThreshold(channel, amount);
451
+ }
452
+ /**
453
+ * Closes a channel once SCTP has acknowledged everything sent on it: `rtc`
454
+ * resets the stream at once and drops what is still queued, where a browser
455
+ * sends it first.
456
+ */
457
+ closeDataChannel(channel) {
458
+ this.pendingCloses.add(channel);
459
+ this.scheduleProcess();
460
+ }
461
+ closeDrainedChannels() {
462
+ for (const channel of this.pendingCloses) {
463
+ if (this.native.dataChannelBufferedAmount(channel) === 0) {
464
+ this.pendingCloses.delete(channel);
465
+ this.native.dataChannelClose(channel);
466
+ }
467
+ }
468
+ }
469
+ /** Close everything; no event follows. Idempotent. */
470
+ close() {
471
+ if (this.closed) {
472
+ return;
473
+ }
474
+ try {
475
+ this.native.close();
476
+ // The DTLS close_notify and SCTP abort it queued.
477
+ this.transmit(this.native.poll(4294967295).datagrams);
478
+ }
479
+ finally {
480
+ this.closed = true;
481
+ this.mdnsAbort.abort();
482
+ for (const transaction of this.stunTransactions.values()) {
483
+ transaction.settle(null);
484
+ }
485
+ if (this.timer !== null) {
486
+ clearTimeout(this.timer);
487
+ this.timer = null;
488
+ }
489
+ const sockets = [...this.sockets.values()];
490
+ this.sockets.clear();
491
+ // Closing a socket drops sends still pending: let this turn's leave first.
492
+ setImmediate(() => {
493
+ for (const { socket } of sockets) {
494
+ void socket.close().catch(() => undefined);
495
+ }
496
+ });
497
+ }
498
+ }
499
+ }
500
+ //# sourceMappingURL=_peer-connection-driver.js.map