rwebtransport 0.2.2 → 0.2.5

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 (99) hide show
  1. package/Cargo.lock +523 -140
  2. package/Cargo.toml +5 -5
  3. package/README.md +8 -4
  4. package/crates/echo-server/src/bin/gen-test-cert.rs +1 -1
  5. package/crates/native/Cargo.toml +2 -0
  6. package/crates/native/src/config.rs +69 -8
  7. package/crates/native/src/driver.rs +253 -90
  8. package/crates/native/src/lib.rs +80 -57
  9. package/crates/native/src/parser_memory.rs +203 -0
  10. package/crates/native/src/server.rs +215 -183
  11. package/crates/native/src/session.rs +1341 -243
  12. package/crates/native/src/test_support.rs +119 -0
  13. package/crates/wtcore/Cargo.toml +1 -0
  14. package/crates/wtcore/src/h3.rs +250 -46
  15. package/dist/index.js +218 -75
  16. package/dist/index.js.map +7 -1
  17. package/dist/index.mjs +214 -69
  18. package/dist/index.mjs.map +7 -1
  19. package/dist/native.d.ts +10 -4
  20. package/dist/server.d.ts +1 -0
  21. package/package.json +84 -78
  22. package/prebuilds/darwin-arm64/rwebtransport.node +0 -0
  23. package/prebuilds/linux-arm64/rwebtransport.node +0 -0
  24. package/prebuilds/linux-x64/rwebtransport.node +0 -0
  25. package/prebuilds/win32-x64/rwebtransport.node +0 -0
  26. package/scripts/build-linux-prebuilt.sh +46 -0
  27. package/scripts/build-ts.js +41 -0
  28. package/scripts/build.js +10 -3
  29. package/vendor/quiche/AGENTS.md +10 -0
  30. package/vendor/quiche/Cargo.lock +239 -248
  31. package/vendor/quiche/Cargo.toml +23 -10
  32. package/vendor/quiche/examples/Makefile +4 -4
  33. package/vendor/quiche/examples/client.rs +10 -28
  34. package/vendor/quiche/examples/http3-client.rs +20 -34
  35. package/vendor/quiche/examples/http3-server.rs +47 -78
  36. package/vendor/quiche/examples/server.rs +19 -49
  37. package/vendor/quiche/include/quiche.h +35 -4
  38. package/vendor/quiche/src/build.rs +17 -0
  39. package/vendor/quiche/src/cid.rs +129 -61
  40. package/vendor/quiche/src/crypto/boringssl.rs +98 -86
  41. package/vendor/quiche/src/crypto/mod.rs +64 -77
  42. package/vendor/quiche/src/dgram.rs +2 -3
  43. package/vendor/quiche/src/error.rs +22 -20
  44. package/vendor/quiche/src/ffi.rs +558 -280
  45. package/vendor/quiche/src/flowcontrol.rs +0 -7
  46. package/vendor/quiche/src/frame.rs +134 -135
  47. package/vendor/quiche/src/h3/ffi.rs +73 -60
  48. package/vendor/quiche/src/h3/frame.rs +70 -90
  49. package/vendor/quiche/src/h3/mod.rs +1024 -593
  50. package/vendor/quiche/src/h3/qpack/decoder.rs +248 -34
  51. package/vendor/quiche/src/h3/qpack/dynamic_table.rs +859 -0
  52. package/vendor/quiche/src/h3/qpack/encoder.rs +14 -17
  53. package/vendor/quiche/src/h3/qpack/mod.rs +48 -0
  54. package/vendor/quiche/src/h3/qpack/static_table.rs +86 -73
  55. package/vendor/quiche/src/h3/stream.rs +1009 -194
  56. package/vendor/quiche/src/lib.rs +1361 -1195
  57. package/vendor/quiche/src/minmax.rs +2 -6
  58. package/vendor/quiche/src/packet.rs +420 -552
  59. package/vendor/quiche/src/path.rs +202 -72
  60. package/vendor/quiche/src/pmtud.rs +18 -16
  61. package/vendor/quiche/src/ranges.rs +184 -82
  62. package/vendor/quiche/src/recovery/AGENTS.md +5 -2
  63. package/vendor/quiche/src/recovery/bandwidth.rs +59 -40
  64. package/vendor/quiche/src/recovery/bytes_in_flight.rs +2 -2
  65. package/vendor/quiche/src/recovery/congestion/cubic.rs +38 -47
  66. package/vendor/quiche/src/recovery/congestion/delivery_rate.rs +54 -60
  67. package/vendor/quiche/src/recovery/congestion/hystart.rs +6 -10
  68. package/vendor/quiche/src/recovery/congestion/mod.rs +110 -42
  69. package/vendor/quiche/src/recovery/congestion/prr.rs +4 -1
  70. package/vendor/quiche/src/recovery/congestion/recovery.rs +91 -95
  71. package/vendor/quiche/src/recovery/congestion/reno.rs +17 -12
  72. package/vendor/quiche/src/recovery/congestion/test_sender.rs +8 -27
  73. package/vendor/quiche/src/recovery/gcongestion/bbr/bandwidth_sampler.rs +159 -247
  74. package/vendor/quiche/src/recovery/gcongestion/bbr/windowed_filter.rs +9 -14
  75. package/vendor/quiche/src/recovery/gcongestion/bbr2/drain.rs +18 -15
  76. package/vendor/quiche/src/recovery/gcongestion/bbr2/mode.rs +43 -28
  77. package/vendor/quiche/src/recovery/gcongestion/bbr2/network_model.rs +349 -76
  78. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_bw.rs +147 -195
  79. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_rtt.rs +29 -27
  80. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/global_min.rs +180 -0
  81. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/global_min_tests.rs +221 -0
  82. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/hmm.rs +395 -0
  83. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/hmm_tests.rs +473 -0
  84. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/mod.rs +175 -0
  85. package/vendor/quiche/src/recovery/gcongestion/bbr2/startup.rs +33 -26
  86. package/vendor/quiche/src/recovery/gcongestion/bbr2.rs +107 -60
  87. package/vendor/quiche/src/recovery/gcongestion/mod.rs +64 -11
  88. package/vendor/quiche/src/recovery/gcongestion/pacer.rs +34 -25
  89. package/vendor/quiche/src/recovery/gcongestion/recovery.rs +81 -86
  90. package/vendor/quiche/src/recovery/mod.rs +414 -173
  91. package/vendor/quiche/src/recovery/rtt.rs +8 -5
  92. package/vendor/quiche/src/stream/mod.rs +864 -133
  93. package/vendor/quiche/src/stream/recv_buf.rs +476 -172
  94. package/vendor/quiche/src/stream/send_buf.rs +343 -81
  95. package/vendor/quiche/src/test_utils.rs +78 -64
  96. package/vendor/quiche/src/tests.rs +2559 -1335
  97. package/vendor/quiche/src/tls/boringssl.rs +60 -63
  98. package/vendor/quiche/src/tls/mod.rs +146 -193
  99. package/vendor/quiche/src/transport_params.rs +87 -103
package/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  // src/loader.ts
2
- import { createRequire } from "module";
3
- import { execFileSync } from "child_process";
4
- import { existsSync } from "fs";
5
- import { dirname, join } from "path";
6
- import { fileURLToPath } from "url";
2
+ import { createRequire } from "node:module";
3
+ import { execFileSync } from "node:child_process";
4
+ import { existsSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
7
  var require2 = createRequire(import.meta.url);
8
8
  var moduleDir = dirname(fileURLToPath(import.meta.url));
9
9
  var PACKAGE_ROOT = join(moduleDir, "..");
@@ -15,37 +15,58 @@ function assertSupportedRuntime() {
15
15
  );
16
16
  }
17
17
  }
18
- function prebuiltPath() {
19
- return join(
20
- PACKAGE_ROOT,
21
- "prebuilds",
22
- `${process.platform}-${process.arch}`,
23
- "rwebtransport.node"
24
- );
18
+ function prebuiltPath(name = "rwebtransport.node") {
19
+ return join(PACKAGE_ROOT, "prebuilds", `${process.platform}-${process.arch}`, name);
25
20
  }
26
21
  var cached;
27
22
  function loadNative() {
28
23
  if (cached) return cached;
29
24
  assertSupportedRuntime();
30
25
  const prebuilt = prebuiltPath();
26
+ let prebuildError;
27
+ let output = prebuilt;
31
28
  if (existsSync(prebuilt)) {
32
- cached = require2(prebuilt);
33
- return cached;
29
+ try {
30
+ cached = require2(prebuilt);
31
+ return cached;
32
+ } catch (error) {
33
+ if (!(error instanceof Error) || error.code !== "ERR_DLOPEN_FAILED") {
34
+ throw error;
35
+ }
36
+ prebuildError = error;
37
+ output = prebuiltPath("rwebtransport-local.node");
38
+ }
39
+ }
40
+ if (output !== prebuilt && existsSync(output)) {
41
+ try {
42
+ cached = require2(output);
43
+ return cached;
44
+ } catch (error) {
45
+ if (!(error instanceof Error) || error.code !== "ERR_DLOPEN_FAILED") {
46
+ throw error;
47
+ }
48
+ }
34
49
  }
35
50
  const builder = join(PACKAGE_ROOT, "scripts", "build.js");
36
51
  if (!existsSync(builder)) {
37
52
  throw new Error(
38
- `rwebtransport: no prebuilt binary at ${prebuilt} and no build script to compile one. Reinstall the package or build it manually (npm run build:rust).`
53
+ `rwebtransport: no usable native binary at ${prebuilt} and no build script to compile one. Reinstall the package or build it manually (npm run build:rust).`,
54
+ { cause: prebuildError }
39
55
  );
40
56
  }
41
57
  process.stderr.write(
42
- "rwebtransport: no prebuilt binary for this platform; compiling the native addon (this happens once)...\n"
58
+ "rwebtransport: no usable native binary for this platform; compiling the native addon...\n"
43
59
  );
44
- execFileSync(process.execPath, [builder], { cwd: PACKAGE_ROOT, stdio: "inherit" });
45
- if (!existsSync(prebuilt)) {
46
- throw new Error(`rwebtransport: build completed but ${prebuilt} was not produced.`);
60
+ const args = output === prebuilt ? [builder] : [builder, "--fallback"];
61
+ try {
62
+ execFileSync(process.execPath, args, { cwd: PACKAGE_ROOT, stdio: "inherit" });
63
+ } catch (error) {
64
+ const detail = prebuildError instanceof Error ? ` (${prebuildError.message})` : "";
65
+ throw new Error(`rwebtransport: unable to build a native addon for this system${detail}`, {
66
+ cause: error
67
+ });
47
68
  }
48
- cached = require2(prebuilt);
69
+ cached = require2(output);
49
70
  return cached;
50
71
  }
51
72
 
@@ -129,6 +150,7 @@ var SessionCore = class {
129
150
  cachedProtocol = "";
130
151
  /** The CONNECT response headers, cached from the client ready event. */
131
152
  cachedResponseHeaders = [];
153
+ advertisedDatagramSize;
132
154
  /**
133
155
  * Resolves when the session is established, rejects if it fails before then.
134
156
  * Backs the public `WebTransport.ready` promise.
@@ -214,7 +236,7 @@ var SessionCore = class {
214
236
  if (!this.usable()) return Promise.reject(this.deadError());
215
237
  const requestId = this.nextId();
216
238
  const d = deferred();
217
- this.writes.set(requestId, d);
239
+ this.writes.set(requestId, { streamId, deferred: d });
218
240
  this.transport.write(streamId, chunk, requestId);
219
241
  return d.promise;
220
242
  }
@@ -234,6 +256,21 @@ var SessionCore = class {
234
256
  */
235
257
  resetStream(streamId, code) {
236
258
  this.transport?.reset(streamId, code >>> 0);
259
+ this.rejectStreamWrites(
260
+ streamId,
261
+ new WebTransportError("stream aborted", {
262
+ source: "stream",
263
+ streamErrorCode: code >>> 0
264
+ })
265
+ );
266
+ }
267
+ rejectStreamWrites(streamId, error) {
268
+ for (const [requestId, write] of this.writes) {
269
+ if (write.streamId === streamId) {
270
+ write.deferred.reject(error);
271
+ this.writes.delete(requestId);
272
+ }
273
+ }
237
274
  }
238
275
  /**
239
276
  * Ask the peer to stop sending on a stream. No-op if not attached.
@@ -272,7 +309,8 @@ var SessionCore = class {
272
309
  * @returns The maximum datagram payload size in bytes, or 0 if not attached.
273
310
  */
274
311
  maxDatagramSize() {
275
- return this.transport ? this.transport.maxDatagramSize() : 0;
312
+ if (this.closedState) return 0;
313
+ return this.advertisedDatagramSize ?? this.transport?.maxDatagramSize?.() ?? 0;
276
314
  }
277
315
  /**
278
316
  * Gracefully close the session. No-op if already closed or not attached.
@@ -284,6 +322,12 @@ var SessionCore = class {
284
322
  if (this.closedState || !this.transport) return;
285
323
  this.transport.closeSession(code >>> 0, new TextEncoder().encode(reason));
286
324
  }
325
+ /** End a session that exceeded a local resource limit, releasing its sinks. */
326
+ abort(message) {
327
+ if (this.closedState) return;
328
+ this.close(0, message);
329
+ this.finish(null, new WebTransportError(message, { source: "session" }));
330
+ }
287
331
  /** Tell the peer this session is draining (send a DRAIN capsule). */
288
332
  drain() {
289
333
  this.transport?.drain();
@@ -313,6 +357,11 @@ var SessionCore = class {
313
357
  * session is not usable or the TLS export fails.
314
358
  */
315
359
  exportKeyingMaterial(label, context, length) {
360
+ if (!Number.isInteger(length) || length < 1 || length > 4096) {
361
+ return Promise.reject(
362
+ new RangeError("outputLength must be an integer between 1 and 4096")
363
+ );
364
+ }
316
365
  if (!this.usable()) return Promise.reject(this.deadError());
317
366
  const requestId = this.nextId();
318
367
  const d = deferred();
@@ -408,6 +457,7 @@ var SessionCore = class {
408
457
  * for their `requestId`.
409
458
  */
410
459
  dispatch(ev) {
460
+ if (this.closedState) return;
411
461
  switch (ev.type) {
412
462
  case "ready" /* Ready */: {
413
463
  this.readyState = true;
@@ -440,6 +490,10 @@ var SessionCore = class {
440
490
  this.datagramSink?.(ev.data);
441
491
  break;
442
492
  }
493
+ case "datagramSize" /* DatagramSize */: {
494
+ this.advertisedDatagramSize = ev.size;
495
+ break;
496
+ }
443
497
  case "stream" /* Stream */: {
444
498
  if (ev.bidi) this.incoming?.onBidi(ev.streamId);
445
499
  else this.incoming?.onUni(ev.streamId);
@@ -458,6 +512,13 @@ var SessionCore = class {
458
512
  break;
459
513
  }
460
514
  case "streamStopSending" /* StreamStopSending */: {
515
+ this.rejectStreamWrites(
516
+ ev.streamId,
517
+ new WebTransportError("peer sent STOP_SENDING", {
518
+ source: "stream",
519
+ streamErrorCode: ev.code
520
+ })
521
+ );
461
522
  this.sends.get(ev.streamId)?.onStopSending(ev.code);
462
523
  break;
463
524
  }
@@ -467,8 +528,13 @@ var SessionCore = class {
467
528
  break;
468
529
  }
469
530
  case "writeAck" /* WriteAck */: {
470
- this.writes.get(ev.requestId)?.resolve();
531
+ const write = this.writes.get(ev.requestId);
471
532
  this.writes.delete(ev.requestId);
533
+ if (ev.accepted) write?.deferred.resolve();
534
+ else
535
+ write?.deferred.reject(
536
+ new WebTransportError("stream is closed", { source: "stream" })
537
+ );
472
538
  break;
473
539
  }
474
540
  case "datagramAck" /* DatagramAck */: {
@@ -550,7 +616,7 @@ var SessionCore = class {
550
616
  }
551
617
  const err = error ?? new WebTransportError("session closed", { source: "session" });
552
618
  for (const d of this.opens.values()) d.reject(err);
553
- for (const d of this.writes.values()) d.reject(err);
619
+ for (const write of this.writes.values()) write.deferred.reject(err);
554
620
  for (const d of this.datagramAcks.values()) d.resolve(false);
555
621
  for (const d of this.statsRequests.values()) d.reject(err);
556
622
  for (const d of this.keyingMaterialRequests.values()) d.reject(err);
@@ -749,10 +815,6 @@ var ServerTransport = class {
749
815
  sendDatagram(bytes, requestId) {
750
816
  this.native.serverSendDatagram(this.handle, this.session, bytes, requestId);
751
817
  }
752
- /** @returns The maximum datagram payload size, in bytes. */
753
- maxDatagramSize() {
754
- return this.native.serverMaxDatagramSize(this.handle);
755
- }
756
818
  /**
757
819
  * @param code - The WebTransport close code.
758
820
  * @param reason - The UTF-8 encoded close reason.
@@ -873,9 +935,8 @@ var WebTransportDatagramDuplexStream = class {
873
935
  *
874
936
  * 1. Creates {@link readable} and captures its controller from `start`.
875
937
  * 2. Installs a datagram sink that enqueues each received datagram only
876
- * while the controller's `desiredSize` is positive (treating an unknown
877
- * `desiredSize` of `null` as `1`, i.e. room available); datagrams that
878
- * arrive when the queue is full are dropped.
938
+ * while the controller's `desiredSize` is positive. Datagrams that
939
+ * arrive after cancellation or when the queue is full are dropped.
879
940
  * 3. Subscribes to the session's `closed` promise so the inbound stream is
880
941
  * closed on both clean close and error, preventing a pending `read()`
881
942
  * from hanging forever. A double-close is swallowed.
@@ -885,16 +946,20 @@ var WebTransportDatagramDuplexStream = class {
885
946
  constructor(session) {
886
947
  this.session = session;
887
948
  let rController;
949
+ let receiving = true;
888
950
  this.readable = new ReadableStream(
889
951
  {
890
952
  start(c) {
891
953
  rController = c;
954
+ },
955
+ cancel() {
956
+ receiving = false;
892
957
  }
893
958
  },
894
959
  new CountQueuingStrategy({ highWaterMark: this.incomingHwm })
895
960
  );
896
961
  session.setDatagramSink((data) => {
897
- if ((rController.desiredSize ?? 1) > 0) {
962
+ if (receiving && (rController.desiredSize ?? 0) > 0) {
898
963
  rController.enqueue(data);
899
964
  } else {
900
965
  session.recordDroppedIncomingDatagram();
@@ -1003,46 +1068,48 @@ var WebTransportReceiveStream = class extends ReadableStream {
1003
1068
  * @remarks Installs the `ReadableStream` underlying source and registers a
1004
1069
  * {@link ReceiveSink} on `session` for `streamId`:
1005
1070
  *
1006
- * - `pull` unpauses the native stream via `setPaused(streamId, false)`, so
1007
- * quiche resumes draining inbound bytes when the consumer wants more.
1071
+ * - `pull` grants the native stream credit for one inbound chunk.
1008
1072
  * - `cancel(reason)` sends `STOP_SENDING` to the peer with the code from
1009
1073
  * {@link errorCode} and then unregisters the receive sink.
1010
- * - The sink's `onData` enqueues each chunk and, once the controller's
1011
- * `desiredSize` falls to zero or below (a nullish `desiredSize` is treated as
1012
- * `1`, so it does not pause), pauses the native stream to flow-control the
1013
- * peer.
1014
1074
  * - The sink's `onFin` closes the controller (swallowing the error if it was
1015
1075
  * already closed or errored) and unregisters.
1016
1076
  * - The sink's `onReset(code)` errors the controller with a `'stream'`-sourced
1017
1077
  * {@link WebTransportError} ('stream reset by peer') carrying the peer's code,
1018
1078
  * then unregisters.
1019
1079
  *
1020
- * A {@link CountQueuingStrategy} with a high-water mark of 32 chunks bounds the
1021
- * JS-side queue and thereby the pause threshold.
1080
+ * A zero high-water mark leaves unread payload in native flow control.
1022
1081
  */
1023
1082
  constructor(session, streamId) {
1024
1083
  let controller;
1084
+ let resolvePull;
1085
+ const finishPull = () => {
1086
+ const resolve = resolvePull;
1087
+ resolvePull = void 0;
1088
+ resolve?.();
1089
+ };
1025
1090
  super(
1026
1091
  {
1027
1092
  start(c) {
1028
1093
  controller = c;
1029
1094
  },
1030
1095
  pull() {
1096
+ const { promise, resolve } = Promise.withResolvers();
1097
+ resolvePull = resolve;
1031
1098
  session.setPaused(streamId, false);
1099
+ return promise;
1032
1100
  },
1033
1101
  cancel(reason) {
1034
1102
  session.stopSending(streamId, errorCode(reason));
1035
1103
  session.unregisterReceive(streamId);
1104
+ finishPull();
1036
1105
  }
1037
1106
  },
1038
- new CountQueuingStrategy({ highWaterMark: 32 })
1107
+ { highWaterMark: 0 }
1039
1108
  );
1040
1109
  session.registerReceive(streamId, {
1041
1110
  onData(chunk) {
1042
1111
  controller.enqueue(chunk);
1043
- if ((controller.desiredSize ?? 1) <= 0) {
1044
- session.setPaused(streamId, true);
1045
- }
1112
+ finishPull();
1046
1113
  },
1047
1114
  onFin() {
1048
1115
  try {
@@ -1050,6 +1117,7 @@ var WebTransportReceiveStream = class extends ReadableStream {
1050
1117
  } catch {
1051
1118
  }
1052
1119
  session.unregisterReceive(streamId);
1120
+ finishPull();
1053
1121
  },
1054
1122
  onReset(code) {
1055
1123
  controller.error(
@@ -1059,6 +1127,7 @@ var WebTransportReceiveStream = class extends ReadableStream {
1059
1127
  })
1060
1128
  );
1061
1129
  session.unregisterReceive(streamId);
1130
+ finishPull();
1062
1131
  },
1063
1132
  onSessionClose(error) {
1064
1133
  try {
@@ -1066,6 +1135,7 @@ var WebTransportReceiveStream = class extends ReadableStream {
1066
1135
  } catch {
1067
1136
  }
1068
1137
  session.unregisterReceive(streamId);
1138
+ finishPull();
1069
1139
  }
1070
1140
  });
1071
1141
  this.streamId = streamId;
@@ -1115,10 +1185,20 @@ var WebTransportSendStream = class extends WritableStream {
1115
1185
  */
1116
1186
  constructor(session, streamId, options = {}) {
1117
1187
  let controller;
1188
+ let reset = false;
1189
+ const abortNative = (reason) => {
1190
+ if (reset) return;
1191
+ reset = true;
1192
+ session.resetStream(streamId, errorCode(reason));
1193
+ session.unregisterSend(streamId);
1194
+ };
1118
1195
  super(
1119
1196
  {
1120
1197
  start(c) {
1121
1198
  controller = c;
1199
+ c.signal.addEventListener("abort", () => abortNative(c.signal.reason), {
1200
+ once: true
1201
+ });
1122
1202
  },
1123
1203
  write(chunk) {
1124
1204
  return session.write(streamId, chunk);
@@ -1128,8 +1208,7 @@ var WebTransportSendStream = class extends WritableStream {
1128
1208
  session.unregisterSend(streamId);
1129
1209
  },
1130
1210
  abort(reason) {
1131
- session.resetStream(streamId, errorCode(reason));
1132
- session.unregisterSend(streamId);
1211
+ abortNative(reason);
1133
1212
  }
1134
1213
  },
1135
1214
  new ByteLengthQueuingStrategy({ highWaterMark: 1024 * 1024 })
@@ -1178,14 +1257,27 @@ var WebTransportBidirectionalStream = class {
1178
1257
  };
1179
1258
 
1180
1259
  // src/webtransport.ts
1260
+ var MAX_PENDING_INCOMING_STREAMS = 128;
1181
1261
  function toBytes(src) {
1182
1262
  if (src instanceof ArrayBuffer) return new Uint8Array(src);
1183
1263
  return new Uint8Array(src.buffer, src.byteOffset, src.byteLength);
1184
1264
  }
1185
1265
  function buildConfig(url, options) {
1186
- if (typeof url !== "string" || !url.startsWith("https://")) {
1266
+ let parsed;
1267
+ try {
1268
+ parsed = new URL(url);
1269
+ } catch {
1187
1270
  throw new WebTransportError(`invalid WebTransport URL: ${url}`, { source: "session" });
1188
1271
  }
1272
+ if (typeof url !== "string" || parsed.protocol !== "https:" || parsed.hash || url.includes("#") || parsed.username || parsed.password) {
1273
+ throw new WebTransportError(`invalid WebTransport URL: ${url}`, { source: "session" });
1274
+ }
1275
+ const protocols = options.protocols ?? [];
1276
+ if (new Set(protocols).size !== protocols.length || protocols.some((protocol) => !/^[\x20-\x7e]{1,512}$/.test(protocol))) {
1277
+ throw new WebTransportError("protocols must be distinct ASCII strings of 1 to 512 bytes", {
1278
+ source: "session"
1279
+ });
1280
+ }
1189
1281
  const hashes = [];
1190
1282
  for (const hash of options.serverCertificateHashes ?? []) {
1191
1283
  const algorithm = hash.algorithm.toLowerCase();
@@ -1206,17 +1298,17 @@ function buildConfig(url, options) {
1206
1298
  const headerNames = [];
1207
1299
  const headerValues = [];
1208
1300
  for (const [name, value] of Object.entries(options.headers ?? {})) {
1209
- headerNames.push(name);
1301
+ headerNames.push(name.toLowerCase());
1210
1302
  headerValues.push(value);
1211
1303
  }
1212
1304
  return {
1213
- url,
1305
+ url: parsed.href,
1214
1306
  hashes,
1215
1307
  insecure: options.insecure ?? false,
1216
1308
  origin: options.origin ?? null,
1217
1309
  headerNames,
1218
1310
  headerValues,
1219
- protocols: options.protocols ?? []
1311
+ protocols
1220
1312
  };
1221
1313
  }
1222
1314
  var WebTransportSession = class {
@@ -1265,6 +1357,8 @@ var WebTransportSession = class {
1265
1357
  * constructs the two incoming-stream `ReadableStream`s and captures their
1266
1358
  * controllers via the `start` callback. Registers an incoming handler on
1267
1359
  * `core` so each peer-opened bidi/uni stream is wrapped and enqueued;
1360
+ * checks the 128-stream queue limit before allocating each wrapper and
1361
+ * aborts the session on overflow. Cancelled directions stop new peer streams.
1268
1362
  * `enqueue` is wrapped in try/catch because it throws once the consumer has
1269
1363
  * cancelled the reader, and that error must not escape native event dispatch.
1270
1364
  * Finally it observes `core.closed`: on clean close both controllers are
@@ -1276,24 +1370,55 @@ var WebTransportSession = class {
1276
1370
  this.datagrams = new WebTransportDatagramDuplexStream(core);
1277
1371
  let bidiController;
1278
1372
  let uniController;
1279
- this.incomingBidirectionalStreams = new ReadableStream({
1280
- start: (c) => {
1281
- bidiController = c;
1282
- }
1283
- });
1284
- this.incomingUnidirectionalStreams = new ReadableStream({
1285
- start: (c) => {
1286
- uniController = c;
1287
- }
1288
- });
1373
+ let bidiCancelled = false;
1374
+ let uniCancelled = false;
1375
+ this.incomingBidirectionalStreams = new ReadableStream(
1376
+ {
1377
+ start: (c) => {
1378
+ bidiController = c;
1379
+ },
1380
+ cancel: () => {
1381
+ bidiCancelled = true;
1382
+ }
1383
+ },
1384
+ new CountQueuingStrategy({ highWaterMark: MAX_PENDING_INCOMING_STREAMS })
1385
+ );
1386
+ this.incomingUnidirectionalStreams = new ReadableStream(
1387
+ {
1388
+ start: (c) => {
1389
+ uniController = c;
1390
+ },
1391
+ cancel: () => {
1392
+ uniCancelled = true;
1393
+ }
1394
+ },
1395
+ new CountQueuingStrategy({ highWaterMark: MAX_PENDING_INCOMING_STREAMS })
1396
+ );
1289
1397
  core.setIncomingHandler({
1290
1398
  onBidi: (id) => {
1399
+ if (bidiCancelled) {
1400
+ core.stopSending(id, 0);
1401
+ core.resetStream(id, 0);
1402
+ return;
1403
+ }
1404
+ if ((bidiController.desiredSize ?? 0) <= 0) {
1405
+ core.abort("incoming stream queue limit exceeded (bidirectional)");
1406
+ return;
1407
+ }
1291
1408
  try {
1292
1409
  bidiController.enqueue(new WebTransportBidirectionalStream(core, id));
1293
1410
  } catch {
1294
1411
  }
1295
1412
  },
1296
1413
  onUni: (id) => {
1414
+ if (uniCancelled) {
1415
+ core.stopSending(id, 0);
1416
+ return;
1417
+ }
1418
+ if ((uniController.desiredSize ?? 0) <= 0) {
1419
+ core.abort("incoming stream queue limit exceeded (unidirectional)");
1420
+ return;
1421
+ }
1297
1422
  try {
1298
1423
  uniController.enqueue(new WebTransportReceiveStream(core, id));
1299
1424
  } catch {
@@ -1487,6 +1612,7 @@ function safeError(controller, reason) {
1487
1612
  }
1488
1613
 
1489
1614
  // src/server.ts
1615
+ var MAX_PENDING_SESSIONS = 128;
1490
1616
  function deferred2() {
1491
1617
  let resolve;
1492
1618
  let reject;
@@ -1556,6 +1682,7 @@ var WebTransportServer = class {
1556
1682
  boundPort = 0;
1557
1683
  /** Guards {@link close} so shutdown is issued at most once. */
1558
1684
  closeCalled = false;
1685
+ incomingCancelled = false;
1559
1686
  /**
1560
1687
  * The sessions clients open, delivered as they are established. Each pull
1561
1688
  * yields a {@link WebTransportServerSession}. The stream is closed when the
@@ -1581,15 +1708,21 @@ var WebTransportServer = class {
1581
1708
  });
1582
1709
  void this.closedD.promise.catch(() => {
1583
1710
  });
1584
- this.incomingSessions = new ReadableStream({
1585
- start: (c) => {
1586
- this.incomingController = c;
1587
- }
1588
- });
1711
+ this.incomingSessions = new ReadableStream(
1712
+ {
1713
+ start: (c) => {
1714
+ this.incomingController = c;
1715
+ },
1716
+ cancel: () => {
1717
+ this.incomingCancelled = true;
1718
+ }
1719
+ },
1720
+ new CountQueuingStrategy({ highWaterMark: MAX_PENDING_SESSIONS })
1721
+ );
1589
1722
  const responseHeaderNames = [];
1590
1723
  const responseHeaderValues = [];
1591
1724
  for (const [name, value] of Object.entries(options.responseHeaders ?? {})) {
1592
- responseHeaderNames.push(name);
1725
+ responseHeaderNames.push(name.toLowerCase());
1593
1726
  responseHeaderValues.push(value);
1594
1727
  }
1595
1728
  this.handle = this.native.serverListen(
@@ -1674,10 +1807,22 @@ var WebTransportServer = class {
1674
1807
  }
1675
1808
  const sessionId = ev.session;
1676
1809
  if (ev.type === "serverReady" /* ServerReady */) {
1810
+ if (this.closeCalled || this.incomingCancelled || (this.incomingController.desiredSize ?? 0) <= 0) {
1811
+ this.native.serverCloseSession(
1812
+ this.handle,
1813
+ sessionId,
1814
+ 0,
1815
+ new TextEncoder().encode("incoming session queue limit exceeded")
1816
+ );
1817
+ return;
1818
+ }
1677
1819
  const core = new SessionCore();
1678
1820
  core.attach(new ServerTransport(this.native, this.handle, sessionId));
1679
1821
  this.sessions.set(sessionId, core);
1680
- void core.closed.promise.finally(() => this.sessions.delete(sessionId));
1822
+ const forget = () => {
1823
+ this.sessions.delete(sessionId);
1824
+ };
1825
+ void core.closed.promise.then(forget, forget);
1681
1826
  const session = new WebTransportServerSession(core, {
1682
1827
  authority: ev.authority,
1683
1828
  path: ev.path,
@@ -1701,7 +1846,7 @@ var WebTransportServer = class {
1701
1846
  *
1702
1847
  * @remarks Dispatches a synthetic clean `closed` event (code `0`, empty
1703
1848
  * reason, `remote: false`) to each session core, then clears the map. The
1704
- * per-core `closed.finally` handler registered in {@link onEvent} would
1849
+ * per-core `closed.then` handlers registered in {@link onEvent} would
1705
1850
  * also remove entries, but the map is cleared here unconditionally.
1706
1851
  */
1707
1852
  finishAllSessions() {
@@ -1757,4 +1902,4 @@ export {
1757
1902
  //! const wt = new WebTransport('https://example.com:4433/echo');
1758
1903
  //! await wt.ready;
1759
1904
  //! ```
1760
- //# sourceMappingURL=index.mjs.map
1905
+ //# sourceMappingURL=index.mjs.map