@webtransport-bun/webtransport 0.1.0 → 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/dist/index.js CHANGED
@@ -5,25 +5,51 @@
5
5
  * Production-ready WebTransport for Bun, backed by napi-rs + wtransport (Rust).
6
6
  * Supports in-process server, client (Node API and W3C-style facade), datagrams, and streams.
7
7
  */
8
- if (typeof globalThis.Bun === "undefined") {
9
- throw new Error("@webtransport-bun/webtransport requires Bun (>=1.3.9). See https://bun.sh");
10
- }
11
8
  // Re-export stream symbols and helpers
12
9
  export { WT_RESET, WT_STOP_SENDING } from "./streams.js";
13
- import { BidiStream, SendStream, RecvStream } from "./streams.js";
10
+ import { BidiStream, RecvStream, SendStream, WT_RESET, WT_STOP_SENDING, } from "./streams.js";
14
11
  /**
15
12
  * Stable error codes. Use with {@link WebTransportError.code} for programmatic handling.
16
13
  * @see WebTransportError
17
14
  */
18
15
  export { E_TLS, E_HANDSHAKE_TIMEOUT, E_SESSION_CLOSED, E_SESSION_IDLE_TIMEOUT, E_STREAM_RESET, E_STOP_SENDING, E_QUEUE_FULL, E_BACKPRESSURE_TIMEOUT, E_LIMIT_EXCEEDED, E_RATE_LIMITED, E_INTERNAL, WebTransportError, } from "./errors.js";
19
16
  import { E_INTERNAL, E_HANDSHAKE_TIMEOUT, E_SESSION_CLOSED, WebTransportError, } from "./errors.js";
20
- const E_CODE_RE = /^E_[A-Z_]+/;
21
- function toWebTransportError(err) {
17
+ const E_CODE_RE = /E_[A-Z_]+/g;
18
+ /**
19
+ * Maps known validation/connect failures to browser-style DOMException names.
20
+ * Returns undefined for unknown cases; E_* code is always preserved.
21
+ * No broad catch-all: unknown errors remain explicit.
22
+ */
23
+ function normalizeToBrowserName(code, message) {
24
+ if (message.includes("serverCertificateHashes cannot be used with allowPooling=true")) {
25
+ return "NotSupportedError";
26
+ }
27
+ if (message.includes("serverCertificateHashes must be an array")) {
28
+ return "TypeError";
29
+ }
30
+ if (message.includes("allowPooling must be a boolean") ||
31
+ message.includes("requireUnreliable must be a boolean")) {
32
+ return "TypeError";
33
+ }
34
+ if (message.includes("congestionControl must be") ||
35
+ message.includes("datagramsReadableType must be")) {
36
+ return "TypeError";
37
+ }
38
+ if (message.includes("E_HANDSHAKE_TIMEOUT")) {
39
+ return "TimeoutError";
40
+ }
41
+ if (message.includes("E_SESSION_CLOSED") ||
42
+ message.includes("E_SESSION_IDLE_TIMEOUT")) {
43
+ return "InvalidStateError";
44
+ }
45
+ return undefined;
46
+ }
47
+ function toWebTransportError(err, strictW3CErrors) {
22
48
  const msg = err instanceof Error ? err.message : String(err);
23
- const match = E_CODE_RE.exec(msg);
24
- if (match)
25
- return new WebTransportError(match[0], msg);
26
- return new WebTransportError(E_INTERNAL, msg);
49
+ const match = msg.match(E_CODE_RE);
50
+ const code = match ? match[0] : E_INTERNAL;
51
+ const browserName = strictW3CErrors === true ? normalizeToBrowserName(code, msg) : undefined;
52
+ return new WebTransportError(code, msg, browserName ? { browserName } : undefined);
27
53
  }
28
54
  /** Default limit values from AGENTS.md */
29
55
  export const DEFAULT_LIMITS = {
@@ -50,8 +76,30 @@ export const DEFAULT_RATE_LIMITS = {
50
76
  datagramsPerSec: 2000,
51
77
  datagramsBurst: 5000,
52
78
  };
79
+ /** W3C-style send group object used by sendOrder/sendGroup options. */
80
+ export class WebTransportSendGroup {
81
+ #transport;
82
+ #id;
83
+ constructor(transport, id) {
84
+ this.#transport = transport;
85
+ this.#id = id;
86
+ }
87
+ _getTransport() {
88
+ return this.#transport;
89
+ }
90
+ _getId() {
91
+ return this.#id;
92
+ }
93
+ async getStats() {
94
+ return this.#transport._getSendGroupStats(this.#id);
95
+ }
96
+ }
53
97
  /** Prometheus metric name prefix. Override via env WEBTRANSPORT_METRICS_PREFIX. */
54
98
  export const METRICS_PREFIX = process.env.WEBTRANSPORT_METRICS_PREFIX ?? "webtransport_";
99
+ function shouldSuppressInsecureSkipVerifyWarning() {
100
+ const v = process.env.WEBTRANSPORT_SUPPRESS_INSECURE_SKIP_VERIFY_WARN;
101
+ return v === "1" || v === "true" || v === "yes";
102
+ }
55
103
  function escapePromLabelValue(v) {
56
104
  return String(v)
57
105
  .replace(/\\/g, "\\\\")
@@ -75,53 +123,86 @@ function sanitizePromLabelName(k) {
75
123
  * ```
76
124
  */
77
125
  export function metricsToPrometheus(m, labels) {
78
- const l = labels
79
- ? "," + Object.entries(labels)
126
+ const baseLabels = labels
127
+ ? Object.entries(labels)
80
128
  .map(([k, v]) => `${sanitizePromLabelName(k)}="${escapePromLabelValue(v)}"`)
81
129
  .join(",")
82
130
  : "";
131
+ const metricLabels = baseLabels ? `{${baseLabels}}` : "";
83
132
  const p = METRICS_PREFIX;
84
133
  const lines = [
85
134
  `# HELP ${p}sessions_active Current open sessions`,
86
135
  `# TYPE ${p}sessions_active gauge`,
87
- `${p}sessions_active${l} ${m.sessionsActive}`,
136
+ `${p}sessions_active${metricLabels} ${m.sessionsActive}`,
88
137
  `# HELP ${p}handshakes_in_flight Handshakes in progress`,
89
138
  `# TYPE ${p}handshakes_in_flight gauge`,
90
- `${p}handshakes_in_flight${l} ${m.handshakesInFlight}`,
139
+ `${p}handshakes_in_flight${metricLabels} ${m.handshakesInFlight}`,
91
140
  `# HELP ${p}streams_active Active streams`,
92
141
  `# TYPE ${p}streams_active gauge`,
93
- `${p}streams_active${l} ${m.streamsActive}`,
142
+ `${p}streams_active${metricLabels} ${m.streamsActive}`,
94
143
  `# HELP ${p}session_tasks_active Internal session tasks`,
95
144
  `# TYPE ${p}session_tasks_active gauge`,
96
- `${p}session_tasks_active${l} ${m.sessionTasksActive}`,
145
+ `${p}session_tasks_active${metricLabels} ${m.sessionTasksActive}`,
97
146
  `# HELP ${p}stream_tasks_active Internal stream tasks`,
98
147
  `# TYPE ${p}stream_tasks_active gauge`,
99
- `${p}stream_tasks_active${l} ${m.streamTasksActive}`,
148
+ `${p}stream_tasks_active${metricLabels} ${m.streamTasksActive}`,
100
149
  `# HELP ${p}queued_bytes_global Bytes queued globally`,
101
150
  `# TYPE ${p}queued_bytes_global gauge`,
102
- `${p}queued_bytes_global${l} ${m.queuedBytesGlobal}`,
151
+ `${p}queued_bytes_global${metricLabels} ${m.queuedBytesGlobal}`,
103
152
  `# HELP ${p}datagrams_in Datagrams received`,
104
153
  `# TYPE ${p}datagrams_in counter`,
105
- `${p}datagrams_in${l} ${m.datagramsIn}`,
154
+ `${p}datagrams_in${metricLabels} ${m.datagramsIn}`,
106
155
  `# HELP ${p}datagrams_out Datagrams sent`,
107
156
  `# TYPE ${p}datagrams_out counter`,
108
- `${p}datagrams_out${l} ${m.datagramsOut}`,
157
+ `${p}datagrams_out${metricLabels} ${m.datagramsOut}`,
109
158
  `# HELP ${p}datagrams_dropped Datagrams dropped`,
110
159
  `# TYPE ${p}datagrams_dropped counter`,
111
- `${p}datagrams_dropped${l} ${m.datagramsDropped}`,
160
+ `${p}datagrams_dropped${metricLabels} ${m.datagramsDropped}`,
112
161
  `# HELP ${p}backpressure_wait_total Times senders waited on backpressure`,
113
162
  `# TYPE ${p}backpressure_wait_total counter`,
114
- `${p}backpressure_wait_total${l} ${m.backpressureWaitCount}`,
163
+ `${p}backpressure_wait_total${metricLabels} ${m.backpressureWaitCount}`,
115
164
  `# HELP ${p}backpressure_timeout_total Times backpressure timeout fired`,
116
165
  `# TYPE ${p}backpressure_timeout_total counter`,
117
- `${p}backpressure_timeout_total${l} ${m.backpressureTimeoutCount}`,
166
+ `${p}backpressure_timeout_total${metricLabels} ${m.backpressureTimeoutCount}`,
118
167
  `# HELP ${p}rate_limited_total Sessions rejected by rate limit`,
119
168
  `# TYPE ${p}rate_limited_total counter`,
120
- `${p}rate_limited_total${l} ${m.rateLimitedCount}`,
169
+ `${p}rate_limited_total${metricLabels} ${m.rateLimitedCount}`,
121
170
  `# HELP ${p}limit_exceeded_total Sessions rejected (limits)`,
122
171
  `# TYPE ${p}limit_exceeded_total counter`,
123
- `${p}limit_exceeded_total${l} ${m.limitExceededCount}`,
172
+ `${p}limit_exceeded_total${metricLabels} ${m.limitExceededCount}`,
124
173
  ];
174
+ function emitHistogram(name, h) {
175
+ if (!h)
176
+ return;
177
+ const raw = h;
178
+ const le = (raw.le ?? []);
179
+ const cumulativeCount = (raw.cumulativeCount ??
180
+ raw.cumulative_count ??
181
+ []);
182
+ const count = (raw.count ?? 0);
183
+ const sumSecs = (raw.sumSecs ?? raw.sum_secs ?? 0);
184
+ const bn = `${p}${name}`;
185
+ lines.push(`# HELP ${bn}_seconds Latency histogram (seconds)`);
186
+ lines.push(`# TYPE ${bn}_seconds histogram`);
187
+ for (let i = 0; i < le.length; i++) {
188
+ const v = le[i];
189
+ const leVal = v === Infinity || v === undefined || v >= 1e308 ? "+Inf" : String(v);
190
+ const bucketLabels = baseLabels
191
+ ? `{le="${leVal}",${baseLabels}}`
192
+ : `{le="${leVal}"}`;
193
+ lines.push(`${bn}_seconds_bucket${bucketLabels} ${Math.round(cumulativeCount[i] ?? 0)}`);
194
+ }
195
+ const infBucketLabels = baseLabels
196
+ ? `{le="+Inf",${baseLabels}}`
197
+ : `{le="+Inf"}`;
198
+ lines.push(`${bn}_seconds_bucket${infBucketLabels} ${Math.round(count)}`);
199
+ lines.push(`${bn}_seconds_count${metricLabels} ${Math.round(count)}`);
200
+ lines.push(`${bn}_seconds_sum${metricLabels} ${sumSecs}`);
201
+ }
202
+ const mAny = m;
203
+ emitHistogram("handshake_latency", (mAny.handshakeLatency ?? mAny.handshake_latency));
204
+ emitHistogram("datagram_enqueue_latency", (mAny.datagramEnqueueLatency ?? mAny.datagram_enqueue_latency));
205
+ emitHistogram("stream_open_latency", (mAny.streamOpenLatency ?? mAny.stream_open_latency));
125
206
  return lines.join("\n") + "\n";
126
207
  }
127
208
  // ---------------------------------------------------------------------------
@@ -137,10 +218,7 @@ const binaryCandidates = [
137
218
  `webtransport-native.${PLATFORM}-${ARCH}-gnu.node`,
138
219
  `webtransport-native.${PLATFORM}-${ARCH}-musl.node`,
139
220
  ];
140
- const basePaths = [
141
- "../../../crates/native",
142
- "../prebuilds",
143
- ];
221
+ const basePaths = ["../../../crates/native", "../prebuilds"];
144
222
  for (const base of basePaths) {
145
223
  for (const candidate of binaryCandidates) {
146
224
  try {
@@ -161,10 +239,14 @@ class NativeServerSession {
161
239
  #nativeHandle;
162
240
  #closedPromise;
163
241
  #closed = false;
242
+ #incomingBidiCache = null;
243
+ #incomingUniCache = null;
164
244
  constructor(nativeHandle, closedPromise) {
165
245
  this.#nativeHandle = nativeHandle;
166
246
  this.#closedPromise = closedPromise;
167
- this.#closedPromise.then(() => { this.#closed = true; });
247
+ this.#closedPromise.then(() => {
248
+ this.#closed = true;
249
+ });
168
250
  }
169
251
  get id() {
170
252
  return this.#nativeHandle.id;
@@ -217,48 +299,40 @@ class NativeServerSession {
217
299
  throw new WebTransportError(E_SESSION_CLOSED);
218
300
  try {
219
301
  const nativeStream = await this.#nativeHandle.createBidiStream();
220
- return new BidiStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
302
+ return new BidiStream({
303
+ handleId: nativeStream?.id ?? 0,
304
+ nativeHandle: nativeStream,
305
+ });
221
306
  }
222
307
  catch (err) {
223
308
  throw toWebTransportError(err);
224
309
  }
225
310
  }
226
- async *incomingBidirectionalStreams() {
227
- while (!this.#closed) {
228
- try {
229
- const nativeStream = await this.#nativeHandle.acceptBidiStream();
230
- if (!nativeStream)
231
- break;
232
- yield new BidiStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
233
- }
234
- catch {
235
- break;
236
- }
311
+ get incomingBidirectionalStreams() {
312
+ if (!this.#incomingBidiCache) {
313
+ this.#incomingBidiCache = createServerIncomingBidiStreams(this.#nativeHandle, () => this.#closed);
237
314
  }
315
+ return this.#incomingBidiCache;
238
316
  }
239
317
  async createUnidirectionalStream() {
240
318
  if (this.#closed)
241
319
  throw new WebTransportError(E_SESSION_CLOSED);
242
320
  try {
243
321
  const nativeStream = await this.#nativeHandle.createUniStream();
244
- return new SendStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
322
+ return new SendStream({
323
+ handleId: nativeStream?.id ?? 0,
324
+ nativeHandle: nativeStream,
325
+ });
245
326
  }
246
327
  catch (err) {
247
328
  throw toWebTransportError(err);
248
329
  }
249
330
  }
250
- async *incomingUnidirectionalStreams() {
251
- while (!this.#closed) {
252
- try {
253
- const nativeStream = await this.#nativeHandle.acceptUniStream();
254
- if (!nativeStream)
255
- break;
256
- yield new RecvStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
257
- }
258
- catch {
259
- break;
260
- }
331
+ get incomingUnidirectionalStreams() {
332
+ if (!this.#incomingUniCache) {
333
+ this.#incomingUniCache = createServerIncomingUniStreams(this.#nativeHandle, () => this.#closed);
261
334
  }
335
+ return this.#incomingUniCache;
262
336
  }
263
337
  metricsSnapshot() {
264
338
  return this.#nativeHandle.metricsSnapshot();
@@ -293,15 +367,22 @@ export function createServer(opts) {
293
367
  if (!native) {
294
368
  throw new Error("Native addon not loaded");
295
369
  }
296
- const certPem = typeof opts.tls.certPem === "string" ? opts.tls.certPem : new TextDecoder().decode(opts.tls.certPem);
297
- const keyPem = typeof opts.tls.keyPem === "string" ? opts.tls.keyPem : new TextDecoder().decode(opts.tls.keyPem);
370
+ const certPem = typeof opts.tls.certPem === "string"
371
+ ? opts.tls.certPem
372
+ : new TextDecoder().decode(opts.tls.certPem);
373
+ const keyPem = typeof opts.tls.keyPem === "string"
374
+ ? opts.tls.keyPem
375
+ : new TextDecoder().decode(opts.tls.keyPem);
298
376
  const caPem = typeof opts.tls.caPem === "string"
299
377
  ? opts.tls.caPem
300
378
  : opts.tls.caPem != null
301
379
  ? new TextDecoder().decode(opts.tls.caPem)
302
380
  : "";
303
381
  const limitsJson = JSON.stringify({ ...DEFAULT_LIMITS, ...opts.limits });
304
- const rateLimitsJson = JSON.stringify({ ...DEFAULT_RATE_LIMITS, ...opts.rateLimits });
382
+ const rateLimitsJson = JSON.stringify({
383
+ ...DEFAULT_RATE_LIMITS,
384
+ ...opts.rateLimits,
385
+ });
305
386
  const closedResolvers = new Map();
306
387
  let activeOnSessionCallbacks = 0;
307
388
  let onSessionDrainResolve = null;
@@ -320,9 +401,14 @@ export function createServer(opts) {
320
401
  };
321
402
  const handle = new native.ServerHandle(opts.port, opts.host ?? "0.0.0.0", opts.debug === true, certPem, keyPem, caPem, limitsJson, rateLimitsJson, (events) => {
322
403
  for (const evt of events) {
323
- if (evt.name === "session" && evt.id != null && evt.peerIp != null && evt.peerPort != null) {
404
+ if (evt.name === "session" &&
405
+ evt.id != null &&
406
+ evt.peerIp != null &&
407
+ evt.peerPort != null) {
324
408
  let closedResolve;
325
- const closedPromise = new Promise((resolve) => { closedResolve = resolve; });
409
+ const closedPromise = new Promise((resolve) => {
410
+ closedResolve = resolve;
411
+ });
326
412
  closedResolvers.set(evt.id, closedResolve);
327
413
  const nativeSession = new native.SessionHandle(evt.id, evt.peerIp, evt.peerPort);
328
414
  const session = new NativeServerSession(nativeSession, closedPromise);
@@ -360,7 +446,9 @@ export function createServer(opts) {
360
446
  }
361
447
  if (activeOnSessionCallbacks > 0) {
362
448
  await Promise.race([
363
- new Promise((r) => { onSessionDrainResolve = r; }),
449
+ new Promise((r) => {
450
+ onSessionDrainResolve = r;
451
+ }),
364
452
  new Promise((r) => setTimeout(r, 5000)),
365
453
  ]);
366
454
  }
@@ -376,11 +464,15 @@ class NativeClientSession {
376
464
  #readyPromise;
377
465
  #closedPromise;
378
466
  #closed = false;
379
- constructor(nativeHandle, readyPromise, closedPromise) {
467
+ #strictW3CErrors;
468
+ constructor(nativeHandle, readyPromise, closedPromise, strictW3CErrors = false) {
380
469
  this.#nativeHandle = nativeHandle;
381
470
  this.#readyPromise = readyPromise;
382
471
  this.#closedPromise = closedPromise;
383
- this.#closedPromise.then(() => { this.#closed = true; });
472
+ this.#strictW3CErrors = strictW3CErrors;
473
+ this.#closedPromise.then(() => {
474
+ this.#closed = true;
475
+ });
384
476
  }
385
477
  get id() {
386
478
  return this.#nativeHandle.id;
@@ -411,7 +503,7 @@ class NativeClientSession {
411
503
  await this.#nativeHandle.sendDatagram(buf);
412
504
  }
413
505
  catch (err) {
414
- throw toWebTransportError(err);
506
+ throw toWebTransportError(err, this.#strictW3CErrors);
415
507
  }
416
508
  }
417
509
  async *incomingDatagrams() {
@@ -432,10 +524,13 @@ class NativeClientSession {
432
524
  throw new WebTransportError(E_SESSION_CLOSED);
433
525
  try {
434
526
  const nativeStream = await this.#nativeHandle.createBidiStream();
435
- return new BidiStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
527
+ return new BidiStream({
528
+ handleId: nativeStream?.id ?? 0,
529
+ nativeHandle: nativeStream,
530
+ });
436
531
  }
437
532
  catch (err) {
438
- throw toWebTransportError(err);
533
+ throw toWebTransportError(err, this.#strictW3CErrors);
439
534
  }
440
535
  }
441
536
  async *incomingBidirectionalStreams() {
@@ -444,7 +539,10 @@ class NativeClientSession {
444
539
  const nativeStream = await this.#nativeHandle.acceptBidiStream();
445
540
  if (!nativeStream)
446
541
  break;
447
- yield new BidiStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
542
+ yield new BidiStream({
543
+ handleId: nativeStream?.id ?? 0,
544
+ nativeHandle: nativeStream,
545
+ });
448
546
  }
449
547
  catch {
450
548
  break;
@@ -456,10 +554,13 @@ class NativeClientSession {
456
554
  throw new WebTransportError(E_SESSION_CLOSED);
457
555
  try {
458
556
  const nativeStream = await this.#nativeHandle.createUniStream();
459
- return new SendStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
557
+ return new SendStream({
558
+ handleId: nativeStream?.id ?? 0,
559
+ nativeHandle: nativeStream,
560
+ });
460
561
  }
461
562
  catch (err) {
462
- throw toWebTransportError(err);
563
+ throw toWebTransportError(err, this.#strictW3CErrors);
463
564
  }
464
565
  }
465
566
  async *incomingUnidirectionalStreams() {
@@ -468,7 +569,10 @@ class NativeClientSession {
468
569
  const nativeStream = await this.#nativeHandle.acceptUniStream();
469
570
  if (!nativeStream)
470
571
  break;
471
- yield new RecvStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
572
+ yield new RecvStream({
573
+ handleId: nativeStream?.id ?? 0,
574
+ nativeHandle: nativeStream,
575
+ });
472
576
  }
473
577
  catch {
474
578
  break;
@@ -507,19 +611,34 @@ export async function connect(url, opts) {
507
611
  if (!native) {
508
612
  throw new Error("Native addon not loaded");
509
613
  }
510
- if (opts?.tls?.insecureSkipVerify === true) {
511
- const log = opts.log ?? ((e) => console.warn(`[webtransport] ${e.level}: ${e.msg}`));
512
- log({ level: "warn", msg: "tls.insecureSkipVerify is enabled — dev only, never use in production" });
614
+ if (opts?.tls?.insecureSkipVerify === true &&
615
+ (opts.log !== undefined || !shouldSuppressInsecureSkipVerifyWarning())) {
616
+ const log = opts.log ??
617
+ ((e) => console.warn(`[webtransport] ${e.level}: ${e.msg}`));
618
+ log({
619
+ level: "warn",
620
+ msg: "tls.insecureSkipVerify is enabled — dev only, never use in production",
621
+ });
513
622
  }
514
623
  const mergedLimits = { ...DEFAULT_LIMITS, ...opts?.limits };
515
- const tlsOpts = opts?.tls ? {
516
- insecureSkipVerify: opts.tls.insecureSkipVerify ?? false,
517
- caPem: opts.tls.caPem ? (typeof opts.tls.caPem === "string" ? opts.tls.caPem : new TextDecoder().decode(opts.tls.caPem)) : undefined,
518
- serverName: opts.tls.serverName,
519
- } : undefined;
624
+ const tlsOpts = opts?.tls
625
+ ? {
626
+ insecureSkipVerify: opts.tls.insecureSkipVerify ?? false,
627
+ caPem: opts.tls.caPem
628
+ ? typeof opts.tls.caPem === "string"
629
+ ? opts.tls.caPem
630
+ : new TextDecoder().decode(opts.tls.caPem)
631
+ : undefined,
632
+ serverName: opts.tls.serverName,
633
+ }
634
+ : undefined;
520
635
  const optsJson = JSON.stringify({
521
636
  limits: mergedLimits,
522
637
  tls: tlsOpts,
638
+ congestionControl: opts?.congestionControl,
639
+ serverCertificateHashes: opts?.serverCertificateHashes,
640
+ allowPooling: opts?.allowPooling,
641
+ requireUnreliable: opts?.requireUnreliable,
523
642
  });
524
643
  const handshakeTimeout = mergedLimits.handshakeTimeoutMs;
525
644
  const connectPromise = new Promise((resolve, reject) => {
@@ -536,7 +655,7 @@ export async function connect(url, opts) {
536
655
  };
537
656
  native.connect(url, optsJson, onClosed, (err, handleId) => {
538
657
  if (err) {
539
- reject(toWebTransportError(err));
658
+ reject(toWebTransportError(err, opts?.strictW3CErrors));
540
659
  return;
541
660
  }
542
661
  if (handleId == null) {
@@ -549,50 +668,94 @@ export async function connect(url, opts) {
549
668
  return;
550
669
  }
551
670
  let closedResolve;
552
- const closedPromise = new Promise((r) => { closedResolve = r; });
671
+ const closedPromise = new Promise((r) => {
672
+ closedResolve = r;
673
+ });
553
674
  closedResolvers.set(handle.id, closedResolve);
554
675
  const readyPromise = Promise.resolve();
555
- resolve(new NativeClientSession(handle, readyPromise, closedPromise));
676
+ resolve(new NativeClientSession(handle, readyPromise, closedPromise, opts?.strictW3CErrors));
556
677
  });
557
678
  });
558
679
  const timeoutPromise = new Promise((_, reject) => {
559
680
  setTimeout(() => {
560
- reject(new WebTransportError(E_HANDSHAKE_TIMEOUT, `E_HANDSHAKE_TIMEOUT: connect timed out after ${handshakeTimeout}ms`));
681
+ const msg = `E_HANDSHAKE_TIMEOUT: connect timed out after ${handshakeTimeout}ms`;
682
+ const browserName = opts?.strictW3CErrors === true
683
+ ? (normalizeToBrowserName(E_HANDSHAKE_TIMEOUT, msg) ??
684
+ undefined)
685
+ : undefined;
686
+ reject(new WebTransportError(E_HANDSHAKE_TIMEOUT, msg, browserName ? { browserName } : undefined));
561
687
  }, handshakeTimeout);
562
688
  });
563
689
  return Promise.race([connectPromise, timeoutPromise]);
564
690
  }
691
+ /** Client pool metrics (hits, misses, evictions). For tests when allowPooling is used. */
692
+ export function clientPoolMetricsSnapshot() {
693
+ if (!native)
694
+ throw new Error("Native addon not loaded");
695
+ const s = native.clientPoolMetricsSnapshot();
696
+ return {
697
+ hits: s.hits,
698
+ misses: s.misses,
699
+ evictIdle: s.evictIdle ?? s.evict_idle ?? 0,
700
+ evictBroken: s.evictBroken ?? s.evict_broken ?? 0,
701
+ };
702
+ }
565
703
  // ---------------------------------------------------------------------------
566
704
  // Browser-style WebTransport facade (Phase P1)
567
705
  // ---------------------------------------------------------------------------
568
- const UNSUPPORTED_CTOR_OPTIONS = ["allowPooling", "requireUnreliable"];
569
- function rejectUnsupportedOption(optionName) {
570
- throw new WebTransportError(E_INTERNAL, `E_INTERNAL: unsupported option '${optionName}'`);
571
- }
572
706
  function validateServerCertificateHashes(arr) {
573
707
  for (const entry of arr) {
574
708
  if (entry.algorithm !== "sha-256") {
575
709
  throw new WebTransportError(E_INTERNAL, `E_INTERNAL: serverCertificateHashes only supports algorithm "sha-256", got "${entry.algorithm}"`);
576
710
  }
577
- if (entry.value == null || (typeof entry.value === "object" && "byteLength" in entry && entry.byteLength === 0)) {
711
+ if (entry.value == null ||
712
+ (typeof entry.value === "object" &&
713
+ "byteLength" in entry &&
714
+ entry.byteLength === 0)) {
578
715
  throw new WebTransportError(E_INTERNAL, "E_INTERNAL: serverCertificateHashes entry value must be non-empty BufferSource");
579
716
  }
580
717
  }
581
718
  }
719
+ function bufferSourceToUint8(value) {
720
+ if (value instanceof ArrayBuffer)
721
+ return new Uint8Array(value);
722
+ if (ArrayBuffer.isView(value)) {
723
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
724
+ }
725
+ throw new WebTransportError(E_INTERNAL, "E_INTERNAL: serverCertificateHashes entry value must be BufferSource");
726
+ }
727
+ function bufferSourceToBase64(value) {
728
+ return Buffer.from(bufferSourceToUint8(value)).toString("base64");
729
+ }
730
+ const VALID_CONGESTION = new Set(["default", "throughput", "low-latency"]);
731
+ const VALID_DATAGRAMS_READABLE_TYPE = new Set(["bytes", "default"]);
582
732
  function validateClientOptions(opts) {
583
733
  if (!opts)
584
734
  return;
585
- for (const k of UNSUPPORTED_CTOR_OPTIONS) {
586
- if (k in opts && opts[k] !== undefined) {
587
- rejectUnsupportedOption(k);
588
- }
735
+ if (opts.allowPooling !== undefined &&
736
+ typeof opts.allowPooling !== "boolean") {
737
+ throw new WebTransportError(E_INTERNAL, "E_INTERNAL: allowPooling must be a boolean");
738
+ }
739
+ if (opts.requireUnreliable !== undefined &&
740
+ typeof opts.requireUnreliable !== "boolean") {
741
+ throw new WebTransportError(E_INTERNAL, "E_INTERNAL: requireUnreliable must be a boolean");
742
+ }
743
+ if (opts.congestionControl !== undefined &&
744
+ !VALID_CONGESTION.has(opts.congestionControl)) {
745
+ throw new WebTransportError(E_INTERNAL, `E_INTERNAL: congestionControl must be "default", "throughput", or "low-latency", got "${opts.congestionControl}"`);
746
+ }
747
+ if (opts.datagramsReadableType !== undefined &&
748
+ !VALID_DATAGRAMS_READABLE_TYPE.has(opts.datagramsReadableType)) {
749
+ throw new WebTransportError(E_INTERNAL, `E_INTERNAL: datagramsReadableType must be "bytes" or "default", got "${opts.datagramsReadableType}"`);
589
750
  }
590
751
  if (opts.serverCertificateHashes !== undefined) {
591
752
  if (!Array.isArray(opts.serverCertificateHashes)) {
592
753
  throw new WebTransportError(E_INTERNAL, "E_INTERNAL: serverCertificateHashes must be an array");
593
754
  }
755
+ if (opts.allowPooling === true) {
756
+ throw new WebTransportError(E_INTERNAL, "E_INTERNAL: serverCertificateHashes cannot be used with allowPooling=true", { browserName: "NotSupportedError" });
757
+ }
594
758
  validateServerCertificateHashes(opts.serverCertificateHashes);
595
- throw new WebTransportError(E_INTERNAL, "E_INTERNAL: serverCertificateHashes is not supported in this runtime");
596
759
  }
597
760
  }
598
761
  function mapToClientOptions(opts) {
@@ -602,6 +765,14 @@ function mapToClientOptions(opts) {
602
765
  return {
603
766
  tls: opts.tls,
604
767
  limits: opts.limits,
768
+ congestionControl: opts.congestionControl,
769
+ strictW3CErrors: opts.strictW3CErrors,
770
+ serverCertificateHashes: opts.serverCertificateHashes?.map((entry) => ({
771
+ algorithm: entry.algorithm,
772
+ valueBase64: bufferSourceToBase64(entry.value),
773
+ })),
774
+ allowPooling: opts.allowPooling,
775
+ requireUnreliable: opts.requireUnreliable,
605
776
  };
606
777
  }
607
778
  function toCloseInfo(info) {
@@ -610,14 +781,91 @@ function toCloseInfo(info) {
610
781
  reason: info?.reason,
611
782
  };
612
783
  }
784
+ class SendScheduler {
785
+ #queues = new Map();
786
+ #groupOrder = [];
787
+ #rrIdx = 0;
788
+ #running = false;
789
+ #seq = 0;
790
+ enqueue(policy, run) {
791
+ return new Promise((resolve, reject) => {
792
+ const task = {
793
+ groupId: policy.groupId,
794
+ sendOrder: policy.sendOrder,
795
+ seq: this.#seq++,
796
+ run,
797
+ resolve,
798
+ reject,
799
+ };
800
+ const q = this.#queues.get(policy.groupId) ?? [];
801
+ q.push(task);
802
+ q.sort((a, b) => a.sendOrder - b.sendOrder || a.seq - b.seq);
803
+ this.#queues.set(policy.groupId, q);
804
+ if (!this.#groupOrder.includes(policy.groupId)) {
805
+ this.#groupOrder.push(policy.groupId);
806
+ }
807
+ void this.#drain();
808
+ });
809
+ }
810
+ async #drain() {
811
+ if (this.#running)
812
+ return;
813
+ this.#running = true;
814
+ try {
815
+ while (this.#groupOrder.length > 0) {
816
+ const groupId = this.#nextGroup();
817
+ if (groupId == null)
818
+ break;
819
+ const q = this.#queues.get(groupId);
820
+ if (!q || q.length === 0) {
821
+ this.#removeGroup(groupId);
822
+ continue;
823
+ }
824
+ const task = q.shift();
825
+ if (q.length === 0)
826
+ this.#removeGroup(groupId);
827
+ try {
828
+ await task.run();
829
+ task.resolve();
830
+ }
831
+ catch (err) {
832
+ task.reject(err);
833
+ }
834
+ }
835
+ }
836
+ finally {
837
+ this.#running = false;
838
+ }
839
+ }
840
+ #nextGroup() {
841
+ if (this.#groupOrder.length === 0)
842
+ return null;
843
+ if (this.#rrIdx >= this.#groupOrder.length)
844
+ this.#rrIdx = 0;
845
+ const groupId = this.#groupOrder[this.#rrIdx];
846
+ this.#rrIdx = (this.#rrIdx + 1) % Math.max(1, this.#groupOrder.length);
847
+ return groupId ?? null;
848
+ }
849
+ #removeGroup(groupId) {
850
+ this.#queues.delete(groupId);
851
+ const idx = this.#groupOrder.indexOf(groupId);
852
+ if (idx >= 0)
853
+ this.#groupOrder.splice(idx, 1);
854
+ if (this.#rrIdx > idx && idx >= 0)
855
+ this.#rrIdx--;
856
+ if (this.#rrIdx < 0)
857
+ this.#rrIdx = 0;
858
+ }
859
+ }
613
860
  /**
614
861
  * Browser-style WebTransport client (W3C facade).
615
862
  *
616
863
  * Use `new WebTransport(url, options)` to connect, or `toWebTransport(session)` to wrap an existing
617
864
  * {@link ClientSession}. Await {@link WebTransport.ready} before using datagrams/streams.
618
865
  *
619
- * Unsupported options (`allowPooling`, `requireUnreliable`, `sendOrder`, `sendGroup`,
620
- * `serverCertificateHashes`) throw {@link WebTransportError} with code `E_INTERNAL`.
866
+ * Option semantics:
867
+ * - `allowPooling`: when true, endpoint-level pooling; when false, dedicated sessions.
868
+ * - `requireUnreliable` is accepted; runtime transport always supports unreliable delivery.
621
869
  *
622
870
  * @example
623
871
  * ```ts
@@ -630,17 +878,36 @@ function toCloseInfo(info) {
630
878
  * ```
631
879
  */
632
880
  export class WebTransport {
881
+ /** Static: true if runtime supports sessions over exclusively reliable (TCP) connections. Ours uses QUIC (supports unreliable). */
882
+ static supportsReliableOnly = false;
633
883
  #sessionPromise;
634
884
  #ready;
635
885
  #closed;
636
886
  #draining;
887
+ #drainingResolve;
637
888
  #session = null;
638
889
  #state;
639
890
  #datagramsCache = null;
891
+ #datagramsReadableType;
640
892
  #incomingBidiCache = null;
641
893
  #incomingUniCache = null;
894
+ #sendScheduler = new SendScheduler();
895
+ #nextSendGroupId = 1;
896
+ #sendGroupBytesSent = new Map();
897
+ #connStats = {
898
+ bytesSent: 0,
899
+ bytesReceived: 0,
900
+ datagramsOut: 0,
901
+ datagramsIn: 0,
902
+ };
903
+ #congestionControl;
642
904
  constructor(urlOrSession, options) {
643
905
  if (typeof urlOrSession === "string") {
906
+ this.#datagramsReadableType = options?.datagramsReadableType ?? "default";
907
+ const requestedCongestion = options?.congestionControl ?? "default";
908
+ // Runtime currently supports default algorithm; explicit preference falls back to default.
909
+ this.#congestionControl =
910
+ requestedCongestion === "default" ? "default" : "default";
644
911
  const clientOpts = mapToClientOptions(options);
645
912
  this.#sessionPromise = connect(urlOrSession, clientOpts);
646
913
  this.#state = "connecting";
@@ -655,9 +922,15 @@ export class WebTransport {
655
922
  this.#closed = this.#sessionPromise.then((s) => s.closed.then((info) => {
656
923
  this.#state = "closed";
657
924
  return toCloseInfo(info);
658
- }));
925
+ }), () => {
926
+ // Connect failed: closed never rejects (PARITY_MATRIX).
927
+ this.#state = "closed";
928
+ return toCloseInfo({ code: 0, reason: "" });
929
+ });
659
930
  }
660
931
  else {
932
+ this.#datagramsReadableType = "default";
933
+ this.#congestionControl = "default";
661
934
  const s = urlOrSession;
662
935
  this.#sessionPromise = Promise.resolve(s);
663
936
  this.#session = s;
@@ -668,9 +941,10 @@ export class WebTransport {
668
941
  return toCloseInfo(info);
669
942
  });
670
943
  }
671
- // draining: spec says it resolves when session is asked to gracefully close.
672
- // Native layer has no separate draining signal; we resolve when closed (documented as partial parity).
673
- this.#draining = this.#closed.then(() => { });
944
+ // draining: spec says it resolves when close() is called and closing process has started.
945
+ this.#draining = new Promise((r) => {
946
+ this.#drainingResolve = r;
947
+ });
674
948
  }
675
949
  /** Resolves when handshake completes. Rejects with WebTransportError on connect failure. */
676
950
  get ready() {
@@ -680,14 +954,22 @@ export class WebTransport {
680
954
  get closed() {
681
955
  return this.#closed;
682
956
  }
683
- /** Resolves when session is draining. Currently resolves with closed (partial parity). */
957
+ /** Resolves when close() has been called and closing process has started. */
684
958
  get draining() {
685
959
  return this.#draining;
686
960
  }
687
- /** Datagram Web Streams (readable/writable). Throws E_SESSION_CLOSED after close. */
961
+ /** Effective congestion control mode applied by this runtime. */
962
+ get congestionControl() {
963
+ return this.#congestionControl;
964
+ }
965
+ /** Create a send group used by sendOrder/sendGroup options. */
966
+ createSendGroup() {
967
+ return new WebTransportSendGroup(this, this.#nextSendGroupId++);
968
+ }
969
+ /** Datagram duplex stream (W3C WebTransportDatagramDuplexStream). Throws E_SESSION_CLOSED after close. */
688
970
  get datagrams() {
689
971
  if (!this.#datagramsCache) {
690
- this.#datagramsCache = createDatagramStreams(this);
972
+ this.#datagramsCache = createDatagramStreams(this, this.#datagramsReadableType);
691
973
  }
692
974
  return this.#datagramsCache;
693
975
  }
@@ -706,39 +988,70 @@ export class WebTransport {
706
988
  return this.#incomingUniCache;
707
989
  }
708
990
  /**
709
- * Create a bidirectional stream (Web Streams). Rejects sendOrder/sendGroup (unsupported).
991
+ * Create a bidirectional stream (Web Streams).
710
992
  * @throws WebTransportError E_SESSION_CLOSED if session is closed/draining/failed.
711
993
  */
712
994
  async createBidirectionalStream(options) {
713
- if (options?.sendOrder !== undefined)
714
- rejectUnsupportedOption("sendOrder");
715
- if (options?.sendGroup !== undefined)
716
- rejectUnsupportedOption("sendGroup");
717
- if (this.#state === "draining" || this.#state === "closed" || this.#state === "failed") {
995
+ const policy = this._resolveSendPolicy(options);
996
+ if (this.#state === "draining" ||
997
+ this.#state === "closed" ||
998
+ this.#state === "failed") {
718
999
  throw new WebTransportError(E_SESSION_CLOSED);
719
1000
  }
720
1001
  const s = await this.#sessionPromise;
721
1002
  const duplex = await s.createBidirectionalStream();
722
- return nodeDuplexToWebBidi(duplex);
1003
+ return nodeDuplexToWebBidi(duplex, this.#sendScheduler, policy, (bytes) => {
1004
+ this.#connStats.bytesSent += bytes;
1005
+ this._recordSendGroupBytes(policy.groupId, bytes);
1006
+ }, (bytes) => {
1007
+ this.#connStats.bytesReceived += bytes;
1008
+ });
723
1009
  }
724
1010
  /**
725
- * Create a unidirectional send stream (WritableStream). Rejects sendOrder/sendGroup (unsupported).
1011
+ * Create a unidirectional send stream (WritableStream).
726
1012
  * @throws WebTransportError E_SESSION_CLOSED if session is closed/draining/failed.
727
1013
  */
728
1014
  async createUnidirectionalStream(options) {
729
- if (options?.sendOrder !== undefined)
730
- rejectUnsupportedOption("sendOrder");
731
- if (options?.sendGroup !== undefined)
732
- rejectUnsupportedOption("sendGroup");
733
- if (this.#state === "draining" || this.#state === "closed" || this.#state === "failed") {
1015
+ const policy = this._resolveSendPolicy(options);
1016
+ if (this.#state === "draining" ||
1017
+ this.#state === "closed" ||
1018
+ this.#state === "failed") {
734
1019
  throw new WebTransportError(E_SESSION_CLOSED);
735
1020
  }
736
1021
  const s = await this.#sessionPromise;
737
1022
  const writable = await s.createUnidirectionalStream();
738
- return nodeWritableToWebWritable(writable);
1023
+ return nodeWritableToWebWritable(writable, this.#sendScheduler, policy, (bytes) => {
1024
+ this.#connStats.bytesSent += bytes;
1025
+ this._recordSendGroupBytes(policy.groupId, bytes);
1026
+ });
1027
+ }
1028
+ /**
1029
+ * Get connection stats (W3C WebTransportConnectionStats).
1030
+ * Maps from session.metricsSnapshot(). Native exposes limited fields; unavailable stats are omitted.
1031
+ * @throws DOMException InvalidStateError if state is "failed"
1032
+ */
1033
+ async getStats() {
1034
+ if (this.#state === "failed") {
1035
+ throw new DOMException("Transport has failed", "InvalidStateError");
1036
+ }
1037
+ await this.#sessionPromise; // Ensure session resolved (throws if failed)
1038
+ return {
1039
+ datagrams: {
1040
+ droppedIncoming: 0,
1041
+ expiredIncoming: 0,
1042
+ expiredOutgoing: 0,
1043
+ lostOutgoing: 0,
1044
+ },
1045
+ bytesSent: this.#connStats.bytesSent,
1046
+ bytesReceived: this.#connStats.bytesReceived,
1047
+ packetsSent: this.#connStats.datagramsOut,
1048
+ packetsReceived: this.#connStats.datagramsIn,
1049
+ estimatedSendRate: null,
1050
+ };
739
1051
  }
740
1052
  /** Initiate graceful close. Idempotent after first call. */
741
1053
  close(info) {
1054
+ this.#drainingResolve(); // Resolves draining as soon as close() is called
742
1055
  if (this.#state === "connected" || this.#state === "connecting") {
743
1056
  this.#state = "draining";
744
1057
  }
@@ -748,37 +1061,193 @@ export class WebTransport {
748
1061
  reason: info?.reason,
749
1062
  });
750
1063
  }
1064
+ else {
1065
+ // Still connecting: absorb eventual connect failure to prevent unhandled rejection (S4).
1066
+ this.#ready.catch(() => { });
1067
+ }
751
1068
  }
752
1069
  /** Internal: session for adapters (not part of spec) */
753
1070
  async _getSession() {
754
1071
  return this.#sessionPromise;
755
1072
  }
1073
+ /** Internal: state for createWritable guard (not part of spec) */
1074
+ _getState() {
1075
+ return this.#state;
1076
+ }
1077
+ _resolveSendPolicy(options) {
1078
+ const sendOrder = options?.sendOrder ?? 0;
1079
+ if (!Number.isInteger(sendOrder)) {
1080
+ throw new TypeError("sendOrder must be an integer");
1081
+ }
1082
+ let groupId = 0;
1083
+ if (options?.sendGroup != null) {
1084
+ if (!(options.sendGroup instanceof WebTransportSendGroup)) {
1085
+ throw new DOMException("sendGroup belongs to another transport", "InvalidStateError");
1086
+ }
1087
+ if (options.sendGroup._getTransport() !== this) {
1088
+ throw new DOMException("sendGroup belongs to another transport", "InvalidStateError");
1089
+ }
1090
+ groupId = options.sendGroup._getId();
1091
+ }
1092
+ return { groupId, sendOrder };
1093
+ }
1094
+ _recordSendGroupBytes(groupId, bytes) {
1095
+ this.#sendGroupBytesSent.set(groupId, (this.#sendGroupBytesSent.get(groupId) ?? 0) + bytes);
1096
+ }
1097
+ async _getSendGroupStats(groupId) {
1098
+ return {
1099
+ bytesSent: this.#sendGroupBytesSent.get(groupId) ?? 0,
1100
+ };
1101
+ }
1102
+ async _sendDatagramWithPolicy(chunk, policy) {
1103
+ await this.#sendScheduler.enqueue(policy, async () => {
1104
+ const s = await this.#sessionPromise;
1105
+ await s.sendDatagram(chunk);
1106
+ this.#connStats.bytesSent += chunk.byteLength;
1107
+ this.#connStats.datagramsOut += 1;
1108
+ this._recordSendGroupBytes(policy.groupId, chunk.byteLength);
1109
+ });
1110
+ }
1111
+ _recordIncomingDatagram(chunk) {
1112
+ this.#connStats.bytesReceived += chunk.byteLength;
1113
+ this.#connStats.datagramsIn += 1;
1114
+ }
1115
+ _recordIncomingStreamBytes(bytes) {
1116
+ this.#connStats.bytesReceived += bytes;
1117
+ }
756
1118
  }
757
- // Stub implementations for P2/P3 — will be replaced in datagram/stream phases
758
- function createDatagramStreams(wt) {
759
- const readable = new ReadableStream({
760
- async start(controller) {
1119
+ function createDatagramWritable(wt, policy) {
1120
+ return new WritableStream({
1121
+ async write(chunk) {
1122
+ await wt._sendDatagramWithPolicy(chunk, policy);
1123
+ },
1124
+ });
1125
+ }
1126
+ function createDatagramStreams(wt, readableType) {
1127
+ let iter = null;
1128
+ const getNext = async () => {
1129
+ if (!iter) {
761
1130
  const s = await wt._getSession();
762
- for await (const d of s.incomingDatagrams()) {
763
- controller.enqueue(new Uint8Array(d));
1131
+ iter = s.incomingDatagrams()[Symbol.asyncIterator]();
1132
+ }
1133
+ return iter.next();
1134
+ };
1135
+ const pull = async (controller) => {
1136
+ const { done, value } = await getNext();
1137
+ if (done) {
1138
+ controller.close();
1139
+ return;
1140
+ }
1141
+ const chunk = new Uint8Array(value);
1142
+ wt._recordIncomingDatagram(chunk);
1143
+ const byteController = controller;
1144
+ if (readableType === "bytes" &&
1145
+ byteController.byobRequest &&
1146
+ byteController.byobRequest.view) {
1147
+ const view = byteController.byobRequest.view;
1148
+ if (view.byteLength < chunk.length) {
1149
+ throw new RangeError("BYOB buffer smaller than datagram size");
1150
+ }
1151
+ view.set(chunk.subarray(0, chunk.length));
1152
+ byteController.byobRequest.respond(chunk.length);
1153
+ return;
1154
+ }
1155
+ controller.enqueue(chunk);
1156
+ };
1157
+ const readable = readableType === "bytes"
1158
+ ? new ReadableStream({
1159
+ type: "bytes",
1160
+ pull,
1161
+ }, { highWaterMark: 0 })
1162
+ : new ReadableStream({ pull }, { highWaterMark: 0 });
1163
+ const writable = createDatagramWritable(wt, { groupId: 0, sendOrder: 0 });
1164
+ return {
1165
+ readable,
1166
+ writable,
1167
+ createWritable(options) {
1168
+ const state = wt._getState();
1169
+ if (state === "closed" || state === "failed") {
1170
+ throw new DOMException("Transport is closed or failed", "InvalidStateError");
1171
+ }
1172
+ return createDatagramWritable(wt, wt._resolveSendPolicy(options));
1173
+ },
1174
+ get maxDatagramSize() {
1175
+ return DEFAULT_LIMITS.maxDatagramSize;
1176
+ },
1177
+ };
1178
+ }
1179
+ function attachServerBidiControls(duplex, stream) {
1180
+ const withControls = stream;
1181
+ const reset = duplex[WT_RESET];
1182
+ if (typeof reset === "function") {
1183
+ withControls[WT_RESET] = (code) => reset.call(duplex, code);
1184
+ }
1185
+ const stopSending = duplex[WT_STOP_SENDING];
1186
+ if (typeof stopSending === "function") {
1187
+ withControls[WT_STOP_SENDING] = (code) => stopSending.call(duplex, code);
1188
+ }
1189
+ return withControls;
1190
+ }
1191
+ function attachServerRecvControls(readable, stream) {
1192
+ const withControls = stream;
1193
+ const stopSending = readable[WT_STOP_SENDING];
1194
+ if (typeof stopSending === "function") {
1195
+ withControls[WT_STOP_SENDING] = (code) => stopSending.call(readable, code);
1196
+ }
1197
+ return withControls;
1198
+ }
1199
+ function createServerIncomingBidiStreams(nativeHandle, isClosed) {
1200
+ return new ReadableStream({
1201
+ async start(controller) {
1202
+ while (!isClosed()) {
1203
+ try {
1204
+ const nativeStream = await nativeHandle.acceptBidiStream();
1205
+ if (!nativeStream)
1206
+ break;
1207
+ const duplex = new BidiStream({
1208
+ handleId: nativeStream?.id ?? 0,
1209
+ nativeHandle: nativeStream,
1210
+ });
1211
+ controller.enqueue(attachServerBidiControls(duplex, await nodeDuplexToWebBidi(duplex)));
1212
+ }
1213
+ catch {
1214
+ break;
1215
+ }
764
1216
  }
765
1217
  controller.close();
766
1218
  },
767
1219
  });
768
- const writable = new WritableStream({
769
- async write(chunk) {
770
- const s = await wt._getSession();
771
- await s.sendDatagram(chunk);
1220
+ }
1221
+ function createServerIncomingUniStreams(nativeHandle, isClosed) {
1222
+ return new ReadableStream({
1223
+ async start(controller) {
1224
+ while (!isClosed()) {
1225
+ try {
1226
+ const nativeStream = await nativeHandle.acceptUniStream();
1227
+ if (!nativeStream)
1228
+ break;
1229
+ const readable = new RecvStream({
1230
+ handleId: nativeStream?.id ?? 0,
1231
+ nativeHandle: nativeStream,
1232
+ });
1233
+ controller.enqueue(attachServerRecvControls(readable, nodeReadableToWebReadable(readable)));
1234
+ }
1235
+ catch {
1236
+ break;
1237
+ }
1238
+ }
1239
+ controller.close();
772
1240
  },
773
1241
  });
774
- return { readable, writable };
775
1242
  }
776
1243
  function createIncomingBidiStreams(wt) {
777
1244
  return new ReadableStream({
778
1245
  async start(controller) {
779
1246
  const s = await wt._getSession();
780
1247
  for await (const duplex of s.incomingBidirectionalStreams()) {
781
- controller.enqueue(await nodeDuplexToWebBidi(duplex));
1248
+ controller.enqueue(await nodeDuplexToWebBidi(duplex, undefined, undefined, undefined, (bytes) => {
1249
+ wt._recordIncomingStreamBytes(bytes);
1250
+ }));
782
1251
  }
783
1252
  controller.close();
784
1253
  },
@@ -789,39 +1258,78 @@ function createIncomingUniStreams(wt) {
789
1258
  async start(controller) {
790
1259
  const s = await wt._getSession();
791
1260
  for await (const readable of s.incomingUnidirectionalStreams()) {
792
- controller.enqueue(nodeReadableToWebReadable(readable));
1261
+ controller.enqueue(nodeReadableToWebReadable(readable, (bytes) => {
1262
+ wt._recordIncomingStreamBytes(bytes);
1263
+ }));
793
1264
  }
794
1265
  controller.close();
795
1266
  },
796
1267
  });
797
1268
  }
798
- function nodeDuplexToWebBidi(duplex) {
799
- const readable = nodeReadableToWebReadable(duplex);
800
- const writable = nodeWritableToWebWritable(duplex);
1269
+ function nodeDuplexToWebBidi(duplex, scheduler, policy, onWriteBytes, onReadBytes) {
1270
+ const readable = nodeReadableToWebReadable(duplex, onReadBytes);
1271
+ const writable = nodeWritableToWebWritable(duplex, scheduler, policy, onWriteBytes);
801
1272
  return Promise.resolve({ readable, writable });
802
1273
  }
803
- function nodeReadableToWebReadable(r) {
1274
+ /** Extract QUIC application error code from abort/cancel reason. */
1275
+ function extractStreamErrorCode(reason) {
1276
+ if (typeof reason === "number" && Number.isInteger(reason))
1277
+ return reason;
1278
+ const o = reason && typeof reason === "object"
1279
+ ? reason
1280
+ : null;
1281
+ if (o) {
1282
+ const c = (o.streamErrorCode ?? o.code);
1283
+ if (typeof c === "number" && Number.isInteger(c))
1284
+ return c;
1285
+ }
1286
+ return 0;
1287
+ }
1288
+ function nodeReadableToWebReadable(r, onReadBytes) {
1289
+ const stopSendable = r;
804
1290
  return new ReadableStream({
805
1291
  async start(controller) {
806
1292
  for await (const chunk of r) {
807
- controller.enqueue(chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk));
1293
+ const bytes = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
1294
+ if (onReadBytes)
1295
+ onReadBytes(bytes.byteLength);
1296
+ controller.enqueue(bytes);
808
1297
  }
809
1298
  controller.close();
810
1299
  },
1300
+ cancel(reason) {
1301
+ const fn = stopSendable[WT_STOP_SENDING];
1302
+ if (typeof fn === "function")
1303
+ fn.call(r, extractStreamErrorCode(reason));
1304
+ },
811
1305
  });
812
1306
  }
813
- function nodeWritableToWebWritable(w) {
1307
+ function nodeWritableToWebWritable(w, scheduler, policy, onWriteBytes) {
1308
+ const resettable = w;
814
1309
  return new WritableStream({
815
1310
  async write(chunk) {
816
- return new Promise((resolve, reject) => {
817
- w.write(Buffer.from(chunk), (err) => (err ? reject(err) : resolve()));
1311
+ const run = () => new Promise((resolve, reject) => {
1312
+ w.write(Buffer.from(chunk), (err) => err ? reject(err) : resolve());
818
1313
  });
1314
+ if (scheduler && policy) {
1315
+ await scheduler.enqueue(policy, run);
1316
+ }
1317
+ else {
1318
+ await run();
1319
+ }
1320
+ if (onWriteBytes)
1321
+ onWriteBytes(chunk.byteLength);
819
1322
  },
820
1323
  close() {
821
1324
  return new Promise((resolve, reject) => {
822
- w.end((err) => (err ? reject(err) : resolve()));
1325
+ w.end((err) => err ? reject(err) : resolve());
823
1326
  });
824
1327
  },
1328
+ abort(reason) {
1329
+ const fn = resettable[WT_RESET];
1330
+ if (typeof fn === "function")
1331
+ fn.call(w, extractStreamErrorCode(reason));
1332
+ },
825
1333
  });
826
1334
  }
827
1335
  /**