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.js CHANGED
@@ -1,3 +1,5 @@
1
+ 'use strict';
2
+ const __rwebtransportImportMetaUrl = require('node:url').pathToFileURL(__filename).href;
1
3
  "use strict";
2
4
  var __defProp = Object.defineProperty;
3
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -33,18 +35,14 @@ __export(index_exports, {
33
35
  });
34
36
  module.exports = __toCommonJS(index_exports);
35
37
 
36
- // node_modules/tsup/assets/cjs_shims.js
37
- var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
38
- var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
39
-
40
38
  // src/loader.ts
41
- var import_node_module = require("module");
42
- var import_node_child_process = require("child_process");
43
- var import_node_fs = require("fs");
44
- var import_node_path = require("path");
45
- var import_node_url = require("url");
46
- var require2 = (0, import_node_module.createRequire)(importMetaUrl);
47
- var moduleDir = (0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(importMetaUrl));
39
+ var import_node_module = require("node:module");
40
+ var import_node_child_process = require("node:child_process");
41
+ var import_node_fs = require("node:fs");
42
+ var import_node_path = require("node:path");
43
+ var import_node_url = require("node:url");
44
+ var require2 = (0, import_node_module.createRequire)(__rwebtransportImportMetaUrl);
45
+ var moduleDir = (0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(__rwebtransportImportMetaUrl));
48
46
  var PACKAGE_ROOT = (0, import_node_path.join)(moduleDir, "..");
49
47
  function assertSupportedRuntime() {
50
48
  const major = Number(process.versions.node.split(".")[0]);
@@ -54,37 +52,58 @@ function assertSupportedRuntime() {
54
52
  );
55
53
  }
56
54
  }
57
- function prebuiltPath() {
58
- return (0, import_node_path.join)(
59
- PACKAGE_ROOT,
60
- "prebuilds",
61
- `${process.platform}-${process.arch}`,
62
- "rwebtransport.node"
63
- );
55
+ function prebuiltPath(name = "rwebtransport.node") {
56
+ return (0, import_node_path.join)(PACKAGE_ROOT, "prebuilds", `${process.platform}-${process.arch}`, name);
64
57
  }
65
58
  var cached;
66
59
  function loadNative() {
67
60
  if (cached) return cached;
68
61
  assertSupportedRuntime();
69
62
  const prebuilt = prebuiltPath();
63
+ let prebuildError;
64
+ let output = prebuilt;
70
65
  if ((0, import_node_fs.existsSync)(prebuilt)) {
71
- cached = require2(prebuilt);
72
- return cached;
66
+ try {
67
+ cached = require2(prebuilt);
68
+ return cached;
69
+ } catch (error) {
70
+ if (!(error instanceof Error) || error.code !== "ERR_DLOPEN_FAILED") {
71
+ throw error;
72
+ }
73
+ prebuildError = error;
74
+ output = prebuiltPath("rwebtransport-local.node");
75
+ }
76
+ }
77
+ if (output !== prebuilt && (0, import_node_fs.existsSync)(output)) {
78
+ try {
79
+ cached = require2(output);
80
+ return cached;
81
+ } catch (error) {
82
+ if (!(error instanceof Error) || error.code !== "ERR_DLOPEN_FAILED") {
83
+ throw error;
84
+ }
85
+ }
73
86
  }
74
87
  const builder = (0, import_node_path.join)(PACKAGE_ROOT, "scripts", "build.js");
75
88
  if (!(0, import_node_fs.existsSync)(builder)) {
76
89
  throw new Error(
77
- `rwebtransport: no prebuilt binary at ${prebuilt} and no build script to compile one. Reinstall the package or build it manually (npm run build:rust).`
90
+ `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).`,
91
+ { cause: prebuildError }
78
92
  );
79
93
  }
80
94
  process.stderr.write(
81
- "rwebtransport: no prebuilt binary for this platform; compiling the native addon (this happens once)...\n"
95
+ "rwebtransport: no usable native binary for this platform; compiling the native addon...\n"
82
96
  );
83
- (0, import_node_child_process.execFileSync)(process.execPath, [builder], { cwd: PACKAGE_ROOT, stdio: "inherit" });
84
- if (!(0, import_node_fs.existsSync)(prebuilt)) {
85
- throw new Error(`rwebtransport: build completed but ${prebuilt} was not produced.`);
97
+ const args = output === prebuilt ? [builder] : [builder, "--fallback"];
98
+ try {
99
+ (0, import_node_child_process.execFileSync)(process.execPath, args, { cwd: PACKAGE_ROOT, stdio: "inherit" });
100
+ } catch (error) {
101
+ const detail = prebuildError instanceof Error ? ` (${prebuildError.message})` : "";
102
+ throw new Error(`rwebtransport: unable to build a native addon for this system${detail}`, {
103
+ cause: error
104
+ });
86
105
  }
87
- cached = require2(prebuilt);
106
+ cached = require2(output);
88
107
  return cached;
89
108
  }
90
109
 
@@ -168,6 +187,7 @@ var SessionCore = class {
168
187
  cachedProtocol = "";
169
188
  /** The CONNECT response headers, cached from the client ready event. */
170
189
  cachedResponseHeaders = [];
190
+ advertisedDatagramSize;
171
191
  /**
172
192
  * Resolves when the session is established, rejects if it fails before then.
173
193
  * Backs the public `WebTransport.ready` promise.
@@ -253,7 +273,7 @@ var SessionCore = class {
253
273
  if (!this.usable()) return Promise.reject(this.deadError());
254
274
  const requestId = this.nextId();
255
275
  const d = deferred();
256
- this.writes.set(requestId, d);
276
+ this.writes.set(requestId, { streamId, deferred: d });
257
277
  this.transport.write(streamId, chunk, requestId);
258
278
  return d.promise;
259
279
  }
@@ -273,6 +293,21 @@ var SessionCore = class {
273
293
  */
274
294
  resetStream(streamId, code) {
275
295
  this.transport?.reset(streamId, code >>> 0);
296
+ this.rejectStreamWrites(
297
+ streamId,
298
+ new WebTransportError("stream aborted", {
299
+ source: "stream",
300
+ streamErrorCode: code >>> 0
301
+ })
302
+ );
303
+ }
304
+ rejectStreamWrites(streamId, error) {
305
+ for (const [requestId, write] of this.writes) {
306
+ if (write.streamId === streamId) {
307
+ write.deferred.reject(error);
308
+ this.writes.delete(requestId);
309
+ }
310
+ }
276
311
  }
277
312
  /**
278
313
  * Ask the peer to stop sending on a stream. No-op if not attached.
@@ -311,7 +346,8 @@ var SessionCore = class {
311
346
  * @returns The maximum datagram payload size in bytes, or 0 if not attached.
312
347
  */
313
348
  maxDatagramSize() {
314
- return this.transport ? this.transport.maxDatagramSize() : 0;
349
+ if (this.closedState) return 0;
350
+ return this.advertisedDatagramSize ?? this.transport?.maxDatagramSize?.() ?? 0;
315
351
  }
316
352
  /**
317
353
  * Gracefully close the session. No-op if already closed or not attached.
@@ -323,6 +359,12 @@ var SessionCore = class {
323
359
  if (this.closedState || !this.transport) return;
324
360
  this.transport.closeSession(code >>> 0, new TextEncoder().encode(reason));
325
361
  }
362
+ /** End a session that exceeded a local resource limit, releasing its sinks. */
363
+ abort(message) {
364
+ if (this.closedState) return;
365
+ this.close(0, message);
366
+ this.finish(null, new WebTransportError(message, { source: "session" }));
367
+ }
326
368
  /** Tell the peer this session is draining (send a DRAIN capsule). */
327
369
  drain() {
328
370
  this.transport?.drain();
@@ -352,6 +394,11 @@ var SessionCore = class {
352
394
  * session is not usable or the TLS export fails.
353
395
  */
354
396
  exportKeyingMaterial(label, context, length) {
397
+ if (!Number.isInteger(length) || length < 1 || length > 4096) {
398
+ return Promise.reject(
399
+ new RangeError("outputLength must be an integer between 1 and 4096")
400
+ );
401
+ }
355
402
  if (!this.usable()) return Promise.reject(this.deadError());
356
403
  const requestId = this.nextId();
357
404
  const d = deferred();
@@ -447,6 +494,7 @@ var SessionCore = class {
447
494
  * for their `requestId`.
448
495
  */
449
496
  dispatch(ev) {
497
+ if (this.closedState) return;
450
498
  switch (ev.type) {
451
499
  case "ready" /* Ready */: {
452
500
  this.readyState = true;
@@ -479,6 +527,10 @@ var SessionCore = class {
479
527
  this.datagramSink?.(ev.data);
480
528
  break;
481
529
  }
530
+ case "datagramSize" /* DatagramSize */: {
531
+ this.advertisedDatagramSize = ev.size;
532
+ break;
533
+ }
482
534
  case "stream" /* Stream */: {
483
535
  if (ev.bidi) this.incoming?.onBidi(ev.streamId);
484
536
  else this.incoming?.onUni(ev.streamId);
@@ -497,6 +549,13 @@ var SessionCore = class {
497
549
  break;
498
550
  }
499
551
  case "streamStopSending" /* StreamStopSending */: {
552
+ this.rejectStreamWrites(
553
+ ev.streamId,
554
+ new WebTransportError("peer sent STOP_SENDING", {
555
+ source: "stream",
556
+ streamErrorCode: ev.code
557
+ })
558
+ );
500
559
  this.sends.get(ev.streamId)?.onStopSending(ev.code);
501
560
  break;
502
561
  }
@@ -506,8 +565,13 @@ var SessionCore = class {
506
565
  break;
507
566
  }
508
567
  case "writeAck" /* WriteAck */: {
509
- this.writes.get(ev.requestId)?.resolve();
568
+ const write = this.writes.get(ev.requestId);
510
569
  this.writes.delete(ev.requestId);
570
+ if (ev.accepted) write?.deferred.resolve();
571
+ else
572
+ write?.deferred.reject(
573
+ new WebTransportError("stream is closed", { source: "stream" })
574
+ );
511
575
  break;
512
576
  }
513
577
  case "datagramAck" /* DatagramAck */: {
@@ -589,7 +653,7 @@ var SessionCore = class {
589
653
  }
590
654
  const err = error ?? new WebTransportError("session closed", { source: "session" });
591
655
  for (const d of this.opens.values()) d.reject(err);
592
- for (const d of this.writes.values()) d.reject(err);
656
+ for (const write of this.writes.values()) write.deferred.reject(err);
593
657
  for (const d of this.datagramAcks.values()) d.resolve(false);
594
658
  for (const d of this.statsRequests.values()) d.reject(err);
595
659
  for (const d of this.keyingMaterialRequests.values()) d.reject(err);
@@ -788,10 +852,6 @@ var ServerTransport = class {
788
852
  sendDatagram(bytes, requestId) {
789
853
  this.native.serverSendDatagram(this.handle, this.session, bytes, requestId);
790
854
  }
791
- /** @returns The maximum datagram payload size, in bytes. */
792
- maxDatagramSize() {
793
- return this.native.serverMaxDatagramSize(this.handle);
794
- }
795
855
  /**
796
856
  * @param code - The WebTransport close code.
797
857
  * @param reason - The UTF-8 encoded close reason.
@@ -912,9 +972,8 @@ var WebTransportDatagramDuplexStream = class {
912
972
  *
913
973
  * 1. Creates {@link readable} and captures its controller from `start`.
914
974
  * 2. Installs a datagram sink that enqueues each received datagram only
915
- * while the controller's `desiredSize` is positive (treating an unknown
916
- * `desiredSize` of `null` as `1`, i.e. room available); datagrams that
917
- * arrive when the queue is full are dropped.
975
+ * while the controller's `desiredSize` is positive. Datagrams that
976
+ * arrive after cancellation or when the queue is full are dropped.
918
977
  * 3. Subscribes to the session's `closed` promise so the inbound stream is
919
978
  * closed on both clean close and error, preventing a pending `read()`
920
979
  * from hanging forever. A double-close is swallowed.
@@ -924,16 +983,20 @@ var WebTransportDatagramDuplexStream = class {
924
983
  constructor(session) {
925
984
  this.session = session;
926
985
  let rController;
986
+ let receiving = true;
927
987
  this.readable = new ReadableStream(
928
988
  {
929
989
  start(c) {
930
990
  rController = c;
991
+ },
992
+ cancel() {
993
+ receiving = false;
931
994
  }
932
995
  },
933
996
  new CountQueuingStrategy({ highWaterMark: this.incomingHwm })
934
997
  );
935
998
  session.setDatagramSink((data) => {
936
- if ((rController.desiredSize ?? 1) > 0) {
999
+ if (receiving && (rController.desiredSize ?? 0) > 0) {
937
1000
  rController.enqueue(data);
938
1001
  } else {
939
1002
  session.recordDroppedIncomingDatagram();
@@ -1042,46 +1105,48 @@ var WebTransportReceiveStream = class extends ReadableStream {
1042
1105
  * @remarks Installs the `ReadableStream` underlying source and registers a
1043
1106
  * {@link ReceiveSink} on `session` for `streamId`:
1044
1107
  *
1045
- * - `pull` unpauses the native stream via `setPaused(streamId, false)`, so
1046
- * quiche resumes draining inbound bytes when the consumer wants more.
1108
+ * - `pull` grants the native stream credit for one inbound chunk.
1047
1109
  * - `cancel(reason)` sends `STOP_SENDING` to the peer with the code from
1048
1110
  * {@link errorCode} and then unregisters the receive sink.
1049
- * - The sink's `onData` enqueues each chunk and, once the controller's
1050
- * `desiredSize` falls to zero or below (a nullish `desiredSize` is treated as
1051
- * `1`, so it does not pause), pauses the native stream to flow-control the
1052
- * peer.
1053
1111
  * - The sink's `onFin` closes the controller (swallowing the error if it was
1054
1112
  * already closed or errored) and unregisters.
1055
1113
  * - The sink's `onReset(code)` errors the controller with a `'stream'`-sourced
1056
1114
  * {@link WebTransportError} ('stream reset by peer') carrying the peer's code,
1057
1115
  * then unregisters.
1058
1116
  *
1059
- * A {@link CountQueuingStrategy} with a high-water mark of 32 chunks bounds the
1060
- * JS-side queue and thereby the pause threshold.
1117
+ * A zero high-water mark leaves unread payload in native flow control.
1061
1118
  */
1062
1119
  constructor(session, streamId) {
1063
1120
  let controller;
1121
+ let resolvePull;
1122
+ const finishPull = () => {
1123
+ const resolve = resolvePull;
1124
+ resolvePull = void 0;
1125
+ resolve?.();
1126
+ };
1064
1127
  super(
1065
1128
  {
1066
1129
  start(c) {
1067
1130
  controller = c;
1068
1131
  },
1069
1132
  pull() {
1133
+ const { promise, resolve } = Promise.withResolvers();
1134
+ resolvePull = resolve;
1070
1135
  session.setPaused(streamId, false);
1136
+ return promise;
1071
1137
  },
1072
1138
  cancel(reason) {
1073
1139
  session.stopSending(streamId, errorCode(reason));
1074
1140
  session.unregisterReceive(streamId);
1141
+ finishPull();
1075
1142
  }
1076
1143
  },
1077
- new CountQueuingStrategy({ highWaterMark: 32 })
1144
+ { highWaterMark: 0 }
1078
1145
  );
1079
1146
  session.registerReceive(streamId, {
1080
1147
  onData(chunk) {
1081
1148
  controller.enqueue(chunk);
1082
- if ((controller.desiredSize ?? 1) <= 0) {
1083
- session.setPaused(streamId, true);
1084
- }
1149
+ finishPull();
1085
1150
  },
1086
1151
  onFin() {
1087
1152
  try {
@@ -1089,6 +1154,7 @@ var WebTransportReceiveStream = class extends ReadableStream {
1089
1154
  } catch {
1090
1155
  }
1091
1156
  session.unregisterReceive(streamId);
1157
+ finishPull();
1092
1158
  },
1093
1159
  onReset(code) {
1094
1160
  controller.error(
@@ -1098,6 +1164,7 @@ var WebTransportReceiveStream = class extends ReadableStream {
1098
1164
  })
1099
1165
  );
1100
1166
  session.unregisterReceive(streamId);
1167
+ finishPull();
1101
1168
  },
1102
1169
  onSessionClose(error) {
1103
1170
  try {
@@ -1105,6 +1172,7 @@ var WebTransportReceiveStream = class extends ReadableStream {
1105
1172
  } catch {
1106
1173
  }
1107
1174
  session.unregisterReceive(streamId);
1175
+ finishPull();
1108
1176
  }
1109
1177
  });
1110
1178
  this.streamId = streamId;
@@ -1154,10 +1222,20 @@ var WebTransportSendStream = class extends WritableStream {
1154
1222
  */
1155
1223
  constructor(session, streamId, options = {}) {
1156
1224
  let controller;
1225
+ let reset = false;
1226
+ const abortNative = (reason) => {
1227
+ if (reset) return;
1228
+ reset = true;
1229
+ session.resetStream(streamId, errorCode(reason));
1230
+ session.unregisterSend(streamId);
1231
+ };
1157
1232
  super(
1158
1233
  {
1159
1234
  start(c) {
1160
1235
  controller = c;
1236
+ c.signal.addEventListener("abort", () => abortNative(c.signal.reason), {
1237
+ once: true
1238
+ });
1161
1239
  },
1162
1240
  write(chunk) {
1163
1241
  return session.write(streamId, chunk);
@@ -1167,8 +1245,7 @@ var WebTransportSendStream = class extends WritableStream {
1167
1245
  session.unregisterSend(streamId);
1168
1246
  },
1169
1247
  abort(reason) {
1170
- session.resetStream(streamId, errorCode(reason));
1171
- session.unregisterSend(streamId);
1248
+ abortNative(reason);
1172
1249
  }
1173
1250
  },
1174
1251
  new ByteLengthQueuingStrategy({ highWaterMark: 1024 * 1024 })
@@ -1217,14 +1294,27 @@ var WebTransportBidirectionalStream = class {
1217
1294
  };
1218
1295
 
1219
1296
  // src/webtransport.ts
1297
+ var MAX_PENDING_INCOMING_STREAMS = 128;
1220
1298
  function toBytes(src) {
1221
1299
  if (src instanceof ArrayBuffer) return new Uint8Array(src);
1222
1300
  return new Uint8Array(src.buffer, src.byteOffset, src.byteLength);
1223
1301
  }
1224
1302
  function buildConfig(url, options) {
1225
- if (typeof url !== "string" || !url.startsWith("https://")) {
1303
+ let parsed;
1304
+ try {
1305
+ parsed = new URL(url);
1306
+ } catch {
1226
1307
  throw new WebTransportError(`invalid WebTransport URL: ${url}`, { source: "session" });
1227
1308
  }
1309
+ if (typeof url !== "string" || parsed.protocol !== "https:" || parsed.hash || url.includes("#") || parsed.username || parsed.password) {
1310
+ throw new WebTransportError(`invalid WebTransport URL: ${url}`, { source: "session" });
1311
+ }
1312
+ const protocols = options.protocols ?? [];
1313
+ if (new Set(protocols).size !== protocols.length || protocols.some((protocol) => !/^[\x20-\x7e]{1,512}$/.test(protocol))) {
1314
+ throw new WebTransportError("protocols must be distinct ASCII strings of 1 to 512 bytes", {
1315
+ source: "session"
1316
+ });
1317
+ }
1228
1318
  const hashes = [];
1229
1319
  for (const hash of options.serverCertificateHashes ?? []) {
1230
1320
  const algorithm = hash.algorithm.toLowerCase();
@@ -1245,17 +1335,17 @@ function buildConfig(url, options) {
1245
1335
  const headerNames = [];
1246
1336
  const headerValues = [];
1247
1337
  for (const [name, value] of Object.entries(options.headers ?? {})) {
1248
- headerNames.push(name);
1338
+ headerNames.push(name.toLowerCase());
1249
1339
  headerValues.push(value);
1250
1340
  }
1251
1341
  return {
1252
- url,
1342
+ url: parsed.href,
1253
1343
  hashes,
1254
1344
  insecure: options.insecure ?? false,
1255
1345
  origin: options.origin ?? null,
1256
1346
  headerNames,
1257
1347
  headerValues,
1258
- protocols: options.protocols ?? []
1348
+ protocols
1259
1349
  };
1260
1350
  }
1261
1351
  var WebTransportSession = class {
@@ -1304,6 +1394,8 @@ var WebTransportSession = class {
1304
1394
  * constructs the two incoming-stream `ReadableStream`s and captures their
1305
1395
  * controllers via the `start` callback. Registers an incoming handler on
1306
1396
  * `core` so each peer-opened bidi/uni stream is wrapped and enqueued;
1397
+ * checks the 128-stream queue limit before allocating each wrapper and
1398
+ * aborts the session on overflow. Cancelled directions stop new peer streams.
1307
1399
  * `enqueue` is wrapped in try/catch because it throws once the consumer has
1308
1400
  * cancelled the reader, and that error must not escape native event dispatch.
1309
1401
  * Finally it observes `core.closed`: on clean close both controllers are
@@ -1315,24 +1407,55 @@ var WebTransportSession = class {
1315
1407
  this.datagrams = new WebTransportDatagramDuplexStream(core);
1316
1408
  let bidiController;
1317
1409
  let uniController;
1318
- this.incomingBidirectionalStreams = new ReadableStream({
1319
- start: (c) => {
1320
- bidiController = c;
1321
- }
1322
- });
1323
- this.incomingUnidirectionalStreams = new ReadableStream({
1324
- start: (c) => {
1325
- uniController = c;
1326
- }
1327
- });
1410
+ let bidiCancelled = false;
1411
+ let uniCancelled = false;
1412
+ this.incomingBidirectionalStreams = new ReadableStream(
1413
+ {
1414
+ start: (c) => {
1415
+ bidiController = c;
1416
+ },
1417
+ cancel: () => {
1418
+ bidiCancelled = true;
1419
+ }
1420
+ },
1421
+ new CountQueuingStrategy({ highWaterMark: MAX_PENDING_INCOMING_STREAMS })
1422
+ );
1423
+ this.incomingUnidirectionalStreams = new ReadableStream(
1424
+ {
1425
+ start: (c) => {
1426
+ uniController = c;
1427
+ },
1428
+ cancel: () => {
1429
+ uniCancelled = true;
1430
+ }
1431
+ },
1432
+ new CountQueuingStrategy({ highWaterMark: MAX_PENDING_INCOMING_STREAMS })
1433
+ );
1328
1434
  core.setIncomingHandler({
1329
1435
  onBidi: (id) => {
1436
+ if (bidiCancelled) {
1437
+ core.stopSending(id, 0);
1438
+ core.resetStream(id, 0);
1439
+ return;
1440
+ }
1441
+ if ((bidiController.desiredSize ?? 0) <= 0) {
1442
+ core.abort("incoming stream queue limit exceeded (bidirectional)");
1443
+ return;
1444
+ }
1330
1445
  try {
1331
1446
  bidiController.enqueue(new WebTransportBidirectionalStream(core, id));
1332
1447
  } catch {
1333
1448
  }
1334
1449
  },
1335
1450
  onUni: (id) => {
1451
+ if (uniCancelled) {
1452
+ core.stopSending(id, 0);
1453
+ return;
1454
+ }
1455
+ if ((uniController.desiredSize ?? 0) <= 0) {
1456
+ core.abort("incoming stream queue limit exceeded (unidirectional)");
1457
+ return;
1458
+ }
1336
1459
  try {
1337
1460
  uniController.enqueue(new WebTransportReceiveStream(core, id));
1338
1461
  } catch {
@@ -1526,6 +1649,7 @@ function safeError(controller, reason) {
1526
1649
  }
1527
1650
 
1528
1651
  // src/server.ts
1652
+ var MAX_PENDING_SESSIONS = 128;
1529
1653
  function deferred2() {
1530
1654
  let resolve;
1531
1655
  let reject;
@@ -1595,6 +1719,7 @@ var WebTransportServer = class {
1595
1719
  boundPort = 0;
1596
1720
  /** Guards {@link close} so shutdown is issued at most once. */
1597
1721
  closeCalled = false;
1722
+ incomingCancelled = false;
1598
1723
  /**
1599
1724
  * The sessions clients open, delivered as they are established. Each pull
1600
1725
  * yields a {@link WebTransportServerSession}. The stream is closed when the
@@ -1620,15 +1745,21 @@ var WebTransportServer = class {
1620
1745
  });
1621
1746
  void this.closedD.promise.catch(() => {
1622
1747
  });
1623
- this.incomingSessions = new ReadableStream({
1624
- start: (c) => {
1625
- this.incomingController = c;
1626
- }
1627
- });
1748
+ this.incomingSessions = new ReadableStream(
1749
+ {
1750
+ start: (c) => {
1751
+ this.incomingController = c;
1752
+ },
1753
+ cancel: () => {
1754
+ this.incomingCancelled = true;
1755
+ }
1756
+ },
1757
+ new CountQueuingStrategy({ highWaterMark: MAX_PENDING_SESSIONS })
1758
+ );
1628
1759
  const responseHeaderNames = [];
1629
1760
  const responseHeaderValues = [];
1630
1761
  for (const [name, value] of Object.entries(options.responseHeaders ?? {})) {
1631
- responseHeaderNames.push(name);
1762
+ responseHeaderNames.push(name.toLowerCase());
1632
1763
  responseHeaderValues.push(value);
1633
1764
  }
1634
1765
  this.handle = this.native.serverListen(
@@ -1713,10 +1844,22 @@ var WebTransportServer = class {
1713
1844
  }
1714
1845
  const sessionId = ev.session;
1715
1846
  if (ev.type === "serverReady" /* ServerReady */) {
1847
+ if (this.closeCalled || this.incomingCancelled || (this.incomingController.desiredSize ?? 0) <= 0) {
1848
+ this.native.serverCloseSession(
1849
+ this.handle,
1850
+ sessionId,
1851
+ 0,
1852
+ new TextEncoder().encode("incoming session queue limit exceeded")
1853
+ );
1854
+ return;
1855
+ }
1716
1856
  const core = new SessionCore();
1717
1857
  core.attach(new ServerTransport(this.native, this.handle, sessionId));
1718
1858
  this.sessions.set(sessionId, core);
1719
- void core.closed.promise.finally(() => this.sessions.delete(sessionId));
1859
+ const forget = () => {
1860
+ this.sessions.delete(sessionId);
1861
+ };
1862
+ void core.closed.promise.then(forget, forget);
1720
1863
  const session = new WebTransportServerSession(core, {
1721
1864
  authority: ev.authority,
1722
1865
  path: ev.path,
@@ -1740,7 +1883,7 @@ var WebTransportServer = class {
1740
1883
  *
1741
1884
  * @remarks Dispatches a synthetic clean `closed` event (code `0`, empty
1742
1885
  * reason, `remote: false`) to each session core, then clears the map. The
1743
- * per-core `closed.finally` handler registered in {@link onEvent} would
1886
+ * per-core `closed.then` handlers registered in {@link onEvent} would
1744
1887
  * also remove entries, but the map is cleared here unconditionally.
1745
1888
  */
1746
1889
  finishAllSessions() {
@@ -1797,4 +1940,4 @@ function safeCloseController(controller) {
1797
1940
  //! const wt = new WebTransport('https://example.com:4433/echo');
1798
1941
  //! await wt.ready;
1799
1942
  //! ```
1800
- //# sourceMappingURL=index.js.map
1943
+ //# sourceMappingURL=index.js.map