rwebtransport 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/Cargo.lock +666 -0
  2. package/Cargo.toml +31 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +41 -0
  5. package/README.md +550 -0
  6. package/crates/echo-server/Cargo.toml +20 -0
  7. package/crates/echo-server/src/main.rs +666 -0
  8. package/crates/native/Cargo.toml +23 -0
  9. package/crates/native/src/config.rs +129 -0
  10. package/crates/native/src/driver.rs +463 -0
  11. package/crates/native/src/lib.rs +821 -0
  12. package/crates/native/src/server.rs +718 -0
  13. package/crates/native/src/session.rs +1191 -0
  14. package/crates/native/src/tls.rs +96 -0
  15. package/crates/wtcore/Cargo.toml +15 -0
  16. package/crates/wtcore/src/h3.rs +226 -0
  17. package/crates/wtcore/src/lib.rs +9 -0
  18. package/dist/datagrams.d.ts +16 -0
  19. package/dist/errors.d.ts +10 -0
  20. package/dist/index.d.ts +7 -0
  21. package/dist/index.js +1512 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/index.mjs +1473 -0
  24. package/dist/index.mjs.map +1 -0
  25. package/dist/loader.d.ts +2 -0
  26. package/dist/native.d.ts +226 -0
  27. package/dist/server.d.ts +44 -0
  28. package/dist/streams.d.ts +14 -0
  29. package/dist/types.d.ts +24 -0
  30. package/dist/webtransport.d.ts +20 -0
  31. package/package.json +79 -0
  32. package/prebuilds/win32-x64/rwebtransport.node +0 -0
  33. package/scripts/bench.mjs +180 -0
  34. package/scripts/build.js +67 -0
  35. package/scripts/postinstall.js +67 -0
  36. package/scripts/setup-unix.sh +129 -0
  37. package/scripts/setup-windows.ps1 +229 -0
  38. package/vendor/quiche/AGENTS.md +75 -0
  39. package/vendor/quiche/COPYING +23 -0
  40. package/vendor/quiche/Cargo.lock +1212 -0
  41. package/vendor/quiche/Cargo.toml +215 -0
  42. package/vendor/quiche/README.md +466 -0
  43. package/vendor/quiche/examples/Makefile +46 -0
  44. package/vendor/quiche/examples/README.md +20 -0
  45. package/vendor/quiche/examples/cert-big.crt +90 -0
  46. package/vendor/quiche/examples/cert.crt +18 -0
  47. package/vendor/quiche/examples/cert.key +28 -0
  48. package/vendor/quiche/examples/client.c +343 -0
  49. package/vendor/quiche/examples/client.rs +281 -0
  50. package/vendor/quiche/examples/gen-certs.sh +15 -0
  51. package/vendor/quiche/examples/http3-client.c +473 -0
  52. package/vendor/quiche/examples/http3-client.rs +349 -0
  53. package/vendor/quiche/examples/http3-server.c +614 -0
  54. package/vendor/quiche/examples/http3-server.rs +680 -0
  55. package/vendor/quiche/examples/qpack-decode.rs +87 -0
  56. package/vendor/quiche/examples/qpack-encode.rs +88 -0
  57. package/vendor/quiche/examples/rootca.crt +21 -0
  58. package/vendor/quiche/examples/server.c +529 -0
  59. package/vendor/quiche/examples/server.rs +529 -0
  60. package/vendor/quiche/include/quiche.h +1282 -0
  61. package/vendor/quiche/quiche.svg +1 -0
  62. package/vendor/quiche/src/buffers.rs +105 -0
  63. package/vendor/quiche/src/build.rs +66 -0
  64. package/vendor/quiche/src/cid.rs +1079 -0
  65. package/vendor/quiche/src/crypto/boringssl.rs +373 -0
  66. package/vendor/quiche/src/crypto/mod.rs +671 -0
  67. package/vendor/quiche/src/dgram.rs +118 -0
  68. package/vendor/quiche/src/error.rs +263 -0
  69. package/vendor/quiche/src/ffi.rs +2290 -0
  70. package/vendor/quiche/src/flowcontrol.rs +246 -0
  71. package/vendor/quiche/src/frame.rs +2172 -0
  72. package/vendor/quiche/src/h3/AGENTS.md +54 -0
  73. package/vendor/quiche/src/h3/ffi.rs +442 -0
  74. package/vendor/quiche/src/h3/frame.rs +1404 -0
  75. package/vendor/quiche/src/h3/mod.rs +8223 -0
  76. package/vendor/quiche/src/h3/qpack/decoder.rs +288 -0
  77. package/vendor/quiche/src/h3/qpack/encoder.rs +235 -0
  78. package/vendor/quiche/src/h3/qpack/mod.rs +202 -0
  79. package/vendor/quiche/src/h3/qpack/static_table.rs +323 -0
  80. package/vendor/quiche/src/h3/stream.rs +1595 -0
  81. package/vendor/quiche/src/lib.rs +9556 -0
  82. package/vendor/quiche/src/minmax.rs +446 -0
  83. package/vendor/quiche/src/packet.rs +2334 -0
  84. package/vendor/quiche/src/path.rs +1374 -0
  85. package/vendor/quiche/src/pmtud.rs +652 -0
  86. package/vendor/quiche/src/rand.rs +64 -0
  87. package/vendor/quiche/src/range_buf.rs +186 -0
  88. package/vendor/quiche/src/ranges.rs +755 -0
  89. package/vendor/quiche/src/recovery/AGENTS.md +80 -0
  90. package/vendor/quiche/src/recovery/bandwidth.rs +565 -0
  91. package/vendor/quiche/src/recovery/bytes_in_flight.rs +179 -0
  92. package/vendor/quiche/src/recovery/congestion/cubic.rs +1038 -0
  93. package/vendor/quiche/src/recovery/congestion/delivery_rate.rs +514 -0
  94. package/vendor/quiche/src/recovery/congestion/hystart.rs +241 -0
  95. package/vendor/quiche/src/recovery/congestion/mod.rs +361 -0
  96. package/vendor/quiche/src/recovery/congestion/prr.rs +238 -0
  97. package/vendor/quiche/src/recovery/congestion/recovery.rs +1170 -0
  98. package/vendor/quiche/src/recovery/congestion/reno.rs +291 -0
  99. package/vendor/quiche/src/recovery/congestion/test_sender.rs +201 -0
  100. package/vendor/quiche/src/recovery/gcongestion/bbr/bandwidth_sampler.rs +1947 -0
  101. package/vendor/quiche/src/recovery/gcongestion/bbr/windowed_filter.rs +158 -0
  102. package/vendor/quiche/src/recovery/gcongestion/bbr.rs +37 -0
  103. package/vendor/quiche/src/recovery/gcongestion/bbr2/drain.rs +120 -0
  104. package/vendor/quiche/src/recovery/gcongestion/bbr2/mode.rs +318 -0
  105. package/vendor/quiche/src/recovery/gcongestion/bbr2/network_model.rs +784 -0
  106. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_bw.rs +729 -0
  107. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_rtt.rs +175 -0
  108. package/vendor/quiche/src/recovery/gcongestion/bbr2/startup.rs +190 -0
  109. package/vendor/quiche/src/recovery/gcongestion/bbr2.rs +855 -0
  110. package/vendor/quiche/src/recovery/gcongestion/mod.rs +275 -0
  111. package/vendor/quiche/src/recovery/gcongestion/pacer.rs +294 -0
  112. package/vendor/quiche/src/recovery/gcongestion/recovery.rs +1384 -0
  113. package/vendor/quiche/src/recovery/mod.rs +3086 -0
  114. package/vendor/quiche/src/recovery/rtt.rs +152 -0
  115. package/vendor/quiche/src/stream/mod.rs +2210 -0
  116. package/vendor/quiche/src/stream/recv_buf.rs +1236 -0
  117. package/vendor/quiche/src/stream/send_buf.rs +849 -0
  118. package/vendor/quiche/src/test_utils.rs +681 -0
  119. package/vendor/quiche/src/tests.rs +12922 -0
  120. package/vendor/quiche/src/tls/boringssl.rs +375 -0
  121. package/vendor/quiche/src/tls/mod.rs +1245 -0
  122. package/vendor/quiche/src/transport_params.rs +628 -0
package/dist/index.js ADDED
@@ -0,0 +1,1512 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ WebTransport: () => WebTransport,
24
+ WebTransportBidirectionalStream: () => WebTransportBidirectionalStream,
25
+ WebTransportDatagramDuplexStream: () => WebTransportDatagramDuplexStream,
26
+ WebTransportError: () => WebTransportError,
27
+ WebTransportReceiveStream: () => WebTransportReceiveStream,
28
+ WebTransportSendStream: () => WebTransportSendStream,
29
+ WebTransportServer: () => WebTransportServer,
30
+ WebTransportServerSession: () => WebTransportServerSession,
31
+ WebTransportSession: () => WebTransportSession
32
+ });
33
+ module.exports = __toCommonJS(index_exports);
34
+
35
+ // node_modules/tsup/assets/cjs_shims.js
36
+ 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;
37
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
38
+
39
+ // src/loader.ts
40
+ var import_node_module = require("module");
41
+ var import_node_child_process = require("child_process");
42
+ var import_node_fs = require("fs");
43
+ var import_node_path = require("path");
44
+ var import_node_url = require("url");
45
+ var require2 = (0, import_node_module.createRequire)(importMetaUrl);
46
+ var moduleDir = (0, import_node_path.dirname)((0, import_node_url.fileURLToPath)(importMetaUrl));
47
+ var PACKAGE_ROOT = (0, import_node_path.join)(moduleDir, "..");
48
+ function assertSupportedRuntime() {
49
+ const major = Number(process.versions.node.split(".")[0]);
50
+ if (major !== 24 && major !== 26) {
51
+ throw new Error(
52
+ `rwebtransport supports Node 24 and Node 26 only; this is Node ${process.versions.node}.`
53
+ );
54
+ }
55
+ }
56
+ function prebuiltPath() {
57
+ return (0, import_node_path.join)(
58
+ PACKAGE_ROOT,
59
+ "prebuilds",
60
+ `${process.platform}-${process.arch}`,
61
+ "rwebtransport.node"
62
+ );
63
+ }
64
+ var cached;
65
+ function loadNative() {
66
+ if (cached) return cached;
67
+ assertSupportedRuntime();
68
+ const prebuilt = prebuiltPath();
69
+ if ((0, import_node_fs.existsSync)(prebuilt)) {
70
+ cached = require2(prebuilt);
71
+ return cached;
72
+ }
73
+ const builder = (0, import_node_path.join)(PACKAGE_ROOT, "scripts", "build.js");
74
+ if (!(0, import_node_fs.existsSync)(builder)) {
75
+ throw new Error(
76
+ `rwebtransport: no prebuilt binary at ${prebuilt} and no build script to compile one. Reinstall the package or build it manually (npm run build:rust).`
77
+ );
78
+ }
79
+ process.stderr.write(
80
+ "rwebtransport: no prebuilt binary for this platform; compiling the native addon (this happens once)...\n"
81
+ );
82
+ (0, import_node_child_process.execFileSync)(process.execPath, [builder], { cwd: PACKAGE_ROOT, stdio: "inherit" });
83
+ if (!(0, import_node_fs.existsSync)(prebuilt)) {
84
+ throw new Error(`rwebtransport: build completed but ${prebuilt} was not produced.`);
85
+ }
86
+ cached = require2(prebuilt);
87
+ return cached;
88
+ }
89
+
90
+ // src/errors.ts
91
+ var WebTransportError = class _WebTransportError extends Error {
92
+ /** Whether the error originated from a stream or the session as a whole. */
93
+ source;
94
+ /** The application error code, if the error came from a stream reset. */
95
+ streamErrorCode;
96
+ /**
97
+ * Creates a new {@link WebTransportError}.
98
+ *
99
+ * @param message - Human-readable description of the failure. When omitted,
100
+ * the message defaults to the string `'WebTransport error'`.
101
+ * @param options - Optional {@link WebTransportErrorOptions}; defaults to an
102
+ * empty object so that both fields fall back to their own defaults.
103
+ *
104
+ * @remarks
105
+ * Sets {@link Error.name} to `'WebTransportError'`, resolves
106
+ * {@link WebTransportError.source} (defaulting to `'session'`) and
107
+ * {@link WebTransportError.streamErrorCode} (defaulting to `null`), then
108
+ * restores the prototype chain with {@link Object.setPrototypeOf} so
109
+ * `instanceof` checks succeed under downlevel compilation.
110
+ */
111
+ constructor(message, options = {}) {
112
+ super(message ?? "WebTransport error");
113
+ this.name = "WebTransportError";
114
+ this.source = options.source ?? "session";
115
+ this.streamErrorCode = options.streamErrorCode ?? null;
116
+ Object.setPrototypeOf(this, _WebTransportError.prototype);
117
+ }
118
+ };
119
+
120
+ // src/native.ts
121
+ function deferred() {
122
+ let resolve;
123
+ let reject;
124
+ const promise = new Promise((res, rej) => {
125
+ resolve = res;
126
+ reject = rej;
127
+ });
128
+ return { promise, resolve, reject };
129
+ }
130
+ var SessionCore = class {
131
+ /**
132
+ * The command transport, undefined until {@link SessionCore.attach} runs.
133
+ * While undefined, outbound commands are dropped or rejected.
134
+ */
135
+ transport;
136
+ /** Monotonic source of request ids handed to the transport. */
137
+ nextRequestId = 1;
138
+ /** Pending {@link SessionCore.openStream} requests, keyed by request id. */
139
+ opens = /* @__PURE__ */ new Map();
140
+ /** Pending {@link SessionCore.write} requests, keyed by request id. */
141
+ writes = /* @__PURE__ */ new Map();
142
+ /** Pending {@link SessionCore.sendDatagram} requests, keyed by request id. */
143
+ datagramAcks = /* @__PURE__ */ new Map();
144
+ /** Active receive sinks, keyed by stream id. */
145
+ receives = /* @__PURE__ */ new Map();
146
+ /** Active send sinks, keyed by stream id. */
147
+ sends = /* @__PURE__ */ new Map();
148
+ /** Handler for peer-initiated streams, if one has been set. */
149
+ incoming;
150
+ /** Sink for inbound datagrams, if one has been set. */
151
+ datagramSink;
152
+ /** True once the session has reached its terminal (closed) state. */
153
+ closedState = false;
154
+ /** True once the session has been established (`ready`/`serverReady`). */
155
+ readyState = false;
156
+ /**
157
+ * Resolves when the session is established, rejects if it fails before then.
158
+ * Backs the public `WebTransport.ready` promise.
159
+ */
160
+ ready = deferred();
161
+ /**
162
+ * Resolves with close info on a clean shutdown, rejects on an error or on a
163
+ * close that happens before the session is ready. Backs `WebTransport.closed`.
164
+ */
165
+ closed = deferred();
166
+ /**
167
+ * Attach no-op catch handlers to {@link SessionCore.ready} and
168
+ * {@link SessionCore.closed} so that a session whose promises the user never
169
+ * observes does not trigger Node's unhandled-rejection warning.
170
+ */
171
+ constructor() {
172
+ void this.closed.promise.catch(() => {
173
+ });
174
+ void this.ready.promise.catch(() => {
175
+ });
176
+ }
177
+ /**
178
+ * Attach the transport once the underlying native handle exists.
179
+ *
180
+ * @param transport - The command sink for this session (client or server side).
181
+ */
182
+ attach(transport) {
183
+ this.transport = transport;
184
+ }
185
+ /**
186
+ * Fail a session that could not be set up at all (e.g. client connect threw).
187
+ *
188
+ * @param message - Human-readable description of the setup failure.
189
+ * @remarks
190
+ * The failure is delivered on a microtask so the caller has a chance to
191
+ * attach `.ready`/`.closed` handlers before they reject.
192
+ */
193
+ failSetup(message) {
194
+ queueMicrotask(
195
+ () => this.finish(null, new WebTransportError(message, { source: "session" }))
196
+ );
197
+ }
198
+ /**
199
+ * @returns The next request id, post-incrementing the internal counter.
200
+ */
201
+ nextId() {
202
+ return this.nextRequestId++;
203
+ }
204
+ /**
205
+ * Open an outbound stream and await its assigned id.
206
+ *
207
+ * @param bidi - True for a bidirectional stream, false for unidirectional.
208
+ * @returns A promise for the new stream's id.
209
+ * @remarks
210
+ * Rejects immediately (without touching the transport) if the session is not
211
+ * usable (unattached or closed).
212
+ */
213
+ openStream(bidi) {
214
+ if (!this.usable()) return Promise.reject(this.deadError());
215
+ const requestId = this.nextId();
216
+ const d = deferred();
217
+ this.opens.set(requestId, d);
218
+ this.transport.openStream(bidi, requestId);
219
+ return d.promise;
220
+ }
221
+ /**
222
+ * Write a chunk to a stream; resolves once the bytes are flushed into quiche
223
+ * (the write backpressure signal).
224
+ *
225
+ * @param streamId - The target stream id.
226
+ * @param chunk - The bytes to send.
227
+ * @returns A promise that resolves when the write is acknowledged.
228
+ * @remarks
229
+ * Rejects immediately if the session is not usable.
230
+ */
231
+ write(streamId, chunk) {
232
+ if (!this.usable()) return Promise.reject(this.deadError());
233
+ const requestId = this.nextId();
234
+ const d = deferred();
235
+ this.writes.set(requestId, d);
236
+ this.transport.write(streamId, chunk, requestId);
237
+ return d.promise;
238
+ }
239
+ /**
240
+ * Finish (half-close) the send side of a stream. No-op if not attached.
241
+ *
242
+ * @param streamId - The stream to finish.
243
+ */
244
+ finStream(streamId) {
245
+ this.transport?.fin(streamId);
246
+ }
247
+ /**
248
+ * Reset the send side of a stream. No-op if not attached.
249
+ *
250
+ * @param streamId - The stream to reset.
251
+ * @param code - The application error code; coerced to an unsigned 32-bit value.
252
+ */
253
+ resetStream(streamId, code) {
254
+ this.transport?.reset(streamId, code >>> 0);
255
+ }
256
+ /**
257
+ * Ask the peer to stop sending on a stream. No-op if not attached.
258
+ *
259
+ * @param streamId - The stream whose inbound half should be stopped.
260
+ * @param code - The application error code; coerced to an unsigned 32-bit value.
261
+ */
262
+ stopSending(streamId, code) {
263
+ this.transport?.stopSending(streamId, code >>> 0);
264
+ }
265
+ /**
266
+ * Toggle read backpressure on a stream. No-op if not attached.
267
+ *
268
+ * @param streamId - The receive stream.
269
+ * @param paused - True to pause native draining (flow-control the peer), false to resume.
270
+ */
271
+ setPaused(streamId, paused) {
272
+ this.transport?.setPaused(streamId, paused);
273
+ }
274
+ /**
275
+ * Send a datagram.
276
+ *
277
+ * @param chunk - The datagram payload.
278
+ * @returns A promise resolving to whether the datagram was actually sent;
279
+ * resolves to false (rather than rejecting) when the session is not usable.
280
+ */
281
+ sendDatagram(chunk) {
282
+ if (!this.usable()) return Promise.resolve(false);
283
+ const requestId = this.nextId();
284
+ const d = deferred();
285
+ this.datagramAcks.set(requestId, d);
286
+ this.transport.sendDatagram(chunk, requestId);
287
+ return d.promise;
288
+ }
289
+ /**
290
+ * @returns The maximum datagram payload size in bytes, or 0 if not attached.
291
+ */
292
+ maxDatagramSize() {
293
+ return this.transport ? this.transport.maxDatagramSize() : 0;
294
+ }
295
+ /**
296
+ * Gracefully close the session. No-op if already closed or not attached.
297
+ *
298
+ * @param code - The WebTransport close code; coerced to an unsigned 32-bit value.
299
+ * @param reason - The close reason, UTF-8 encoded before it is sent.
300
+ */
301
+ close(code, reason) {
302
+ if (this.closedState || !this.transport) return;
303
+ this.transport.closeSession(code >>> 0, new TextEncoder().encode(reason));
304
+ }
305
+ /** Tear down the native resources for this session. No-op if not attached. */
306
+ shutdown() {
307
+ this.transport?.shutdown();
308
+ }
309
+ /**
310
+ * Whether outbound operations can still be issued (attached, not closed).
311
+ *
312
+ * @returns True when a transport is attached and the session is not closed.
313
+ */
314
+ usable() {
315
+ return this.transport !== void 0 && !this.closedState;
316
+ }
317
+ /**
318
+ * @returns The error used to reject operations attempted on a dead session.
319
+ */
320
+ deadError() {
321
+ return new WebTransportError("session is closed", { source: "session" });
322
+ }
323
+ /**
324
+ * Register a sink to receive a stream's inbound data/fin/reset events.
325
+ *
326
+ * @param streamId - The stream to observe.
327
+ * @param sink - The receiver of that stream's inbound events.
328
+ */
329
+ registerReceive(streamId, sink) {
330
+ this.receives.set(streamId, sink);
331
+ }
332
+ /**
333
+ * Stop delivering inbound events for a stream.
334
+ *
335
+ * @param streamId - The stream to forget.
336
+ */
337
+ unregisterReceive(streamId) {
338
+ this.receives.delete(streamId);
339
+ }
340
+ /**
341
+ * Register a sink to receive a stream's STOP_SENDING notifications.
342
+ *
343
+ * @param streamId - The stream to observe.
344
+ * @param sink - The receiver of that stream's send-side control events.
345
+ */
346
+ registerSend(streamId, sink) {
347
+ this.sends.set(streamId, sink);
348
+ }
349
+ /**
350
+ * Stop delivering send-side control events for a stream.
351
+ *
352
+ * @param streamId - The stream to forget.
353
+ */
354
+ unregisterSend(streamId) {
355
+ this.sends.delete(streamId);
356
+ }
357
+ /**
358
+ * Set the handler invoked when the peer opens a stream. Replaces any prior handler.
359
+ *
360
+ * @param handler - The consumer of peer-initiated streams.
361
+ */
362
+ setIncomingHandler(handler) {
363
+ this.incoming = handler;
364
+ }
365
+ /**
366
+ * Set the sink invoked for each inbound datagram. Replaces any prior sink.
367
+ *
368
+ * @param sink - The consumer of inbound datagram payloads.
369
+ */
370
+ setDatagramSink(sink) {
371
+ this.datagramSink = sink;
372
+ }
373
+ /**
374
+ * Route one native event to the appropriate promise, sink, or handler.
375
+ *
376
+ * @param ev - The event delivered by the native addon.
377
+ * @remarks
378
+ * This is the single entry point the native `onEvent` callback funnels into.
379
+ * `ready`/`serverReady` mark the session established and resolve `ready`;
380
+ * `closed`/`error` drive {@link SessionCore.finish}; the `stream*` events look
381
+ * up the matching sink (silently ignored if none is registered); and the
382
+ * `*Ack`/`streamOpened` events settle and then remove the pending deferred
383
+ * for their `requestId`.
384
+ */
385
+ dispatch(ev) {
386
+ switch (ev.type) {
387
+ case "ready" /* Ready */:
388
+ case "serverReady" /* ServerReady */: {
389
+ this.readyState = true;
390
+ this.ready.resolve();
391
+ break;
392
+ }
393
+ case "closed" /* Closed */: {
394
+ const reason = new TextDecoder().decode(ev.reason);
395
+ this.finish({ closeCode: ev.code, reason }, void 0);
396
+ break;
397
+ }
398
+ case "error" /* Error */: {
399
+ const err = new WebTransportError(ev.message, { source: "session" });
400
+ this.finish(null, err);
401
+ break;
402
+ }
403
+ case "datagram" /* Datagram */: {
404
+ this.datagramSink?.(ev.data);
405
+ break;
406
+ }
407
+ case "stream" /* Stream */: {
408
+ if (ev.bidi) this.incoming?.onBidi(ev.streamId);
409
+ else this.incoming?.onUni(ev.streamId);
410
+ break;
411
+ }
412
+ case "streamData" /* StreamData */: {
413
+ this.receives.get(ev.streamId)?.onData(ev.data);
414
+ break;
415
+ }
416
+ case "streamFin" /* StreamFin */: {
417
+ this.receives.get(ev.streamId)?.onFin();
418
+ break;
419
+ }
420
+ case "streamReset" /* StreamReset */: {
421
+ this.receives.get(ev.streamId)?.onReset(ev.code);
422
+ break;
423
+ }
424
+ case "streamStopSending" /* StreamStopSending */: {
425
+ this.sends.get(ev.streamId)?.onStopSending(ev.code);
426
+ break;
427
+ }
428
+ case "streamOpened" /* StreamOpened */: {
429
+ this.opens.get(ev.requestId)?.resolve(ev.streamId);
430
+ this.opens.delete(ev.requestId);
431
+ break;
432
+ }
433
+ case "writeAck" /* WriteAck */: {
434
+ this.writes.get(ev.requestId)?.resolve();
435
+ this.writes.delete(ev.requestId);
436
+ break;
437
+ }
438
+ case "datagramAck" /* DatagramAck */: {
439
+ this.datagramAcks.get(ev.requestId)?.resolve(ev.sent);
440
+ this.datagramAcks.delete(ev.requestId);
441
+ break;
442
+ }
443
+ }
444
+ }
445
+ /**
446
+ * Terminal transition: resolve/reject everything and tear down.
447
+ *
448
+ * @param info - Close info for a clean close, or null when closing on error.
449
+ * @param error - The error that ended the session, or undefined for a clean close.
450
+ * @remarks
451
+ * Idempotent: returns immediately if the session already closed. Settles the
452
+ * lifecycle promises according to state: if the session never became ready,
453
+ * both `ready` and `closed` reject (a pre-ready close is a failed connect); if
454
+ * it was ready and `error` is set, only `closed` rejects; otherwise `closed`
455
+ * resolves with `info` (defaulting to code 0 / empty reason). It then rejects
456
+ * every pending open and write, resolves every pending datagram ack to false,
457
+ * signals a reset (code 0) to all receive sinks and STOP_SENDING (code 0) to
458
+ * all send sinks, clears the bookkeeping maps, and finally shuts down the
459
+ * transport.
460
+ */
461
+ finish(info, error) {
462
+ if (this.closedState) return;
463
+ this.closedState = true;
464
+ if (!this.readyState) {
465
+ const err2 = error ?? new WebTransportError("session closed before it was established", {
466
+ source: "session"
467
+ });
468
+ this.ready.reject(err2);
469
+ this.closed.reject(err2);
470
+ } else if (error) {
471
+ this.closed.reject(error);
472
+ } else {
473
+ this.closed.resolve(info ?? { closeCode: 0, reason: "" });
474
+ }
475
+ const err = error ?? new WebTransportError("session closed", { source: "session" });
476
+ for (const d of this.opens.values()) d.reject(err);
477
+ for (const d of this.writes.values()) d.reject(err);
478
+ for (const d of this.datagramAcks.values()) d.resolve(false);
479
+ for (const sink of this.receives.values()) sink.onReset(0);
480
+ for (const sink of this.sends.values()) sink.onStopSending(0);
481
+ this.opens.clear();
482
+ this.writes.clear();
483
+ this.datagramAcks.clear();
484
+ this.receives.clear();
485
+ this.sends.clear();
486
+ this.transport?.shutdown();
487
+ }
488
+ /** @returns Whether the session has reached its terminal closed state. */
489
+ get isClosed() {
490
+ return this.closedState;
491
+ }
492
+ };
493
+ var ClientTransport = class {
494
+ /**
495
+ * @param native - The loaded native addon.
496
+ * @param handle - The client session handle these commands target.
497
+ */
498
+ constructor(native, handle) {
499
+ this.native = native;
500
+ this.handle = handle;
501
+ }
502
+ native;
503
+ handle;
504
+ /**
505
+ * @param bidi - True for bidirectional, false for unidirectional.
506
+ * @param requestId - Id correlating the eventual `streamOpened` event.
507
+ */
508
+ openStream(bidi, requestId) {
509
+ this.native.openStream(this.handle, bidi, requestId);
510
+ }
511
+ /**
512
+ * @param streamId - The target stream id.
513
+ * @param bytes - The payload.
514
+ * @param requestId - Id correlating the eventual `writeAck` event.
515
+ */
516
+ write(streamId, bytes, requestId) {
517
+ this.native.writeStream(this.handle, streamId, bytes, requestId);
518
+ }
519
+ /** @param streamId - The stream to finish. */
520
+ fin(streamId) {
521
+ this.native.finStream(this.handle, streamId);
522
+ }
523
+ /**
524
+ * @param streamId - The stream to reset.
525
+ * @param code - The application error code.
526
+ */
527
+ reset(streamId, code) {
528
+ this.native.resetStream(this.handle, streamId, code);
529
+ }
530
+ /**
531
+ * @param streamId - The stream whose inbound half should be stopped.
532
+ * @param code - The application error code.
533
+ */
534
+ stopSending(streamId, code) {
535
+ this.native.stopSending(this.handle, streamId, code);
536
+ }
537
+ /**
538
+ * @param streamId - The receive stream.
539
+ * @param paused - True to pause draining, false to resume.
540
+ */
541
+ setPaused(streamId, paused) {
542
+ this.native.setPaused(this.handle, streamId, paused);
543
+ }
544
+ /**
545
+ * @param bytes - The datagram payload.
546
+ * @param requestId - Id correlating the eventual `datagramAck` event.
547
+ */
548
+ sendDatagram(bytes, requestId) {
549
+ this.native.sendDatagram(this.handle, bytes, requestId);
550
+ }
551
+ /** @returns The maximum datagram payload size, in bytes. */
552
+ maxDatagramSize() {
553
+ return this.native.maxDatagramSize(this.handle);
554
+ }
555
+ /**
556
+ * @param code - The WebTransport close code.
557
+ * @param reason - The UTF-8 encoded close reason.
558
+ */
559
+ closeSession(code, reason) {
560
+ this.native.closeSession(this.handle, code, reason);
561
+ }
562
+ /** Tear down the session's native driver thread. */
563
+ shutdown() {
564
+ this.native.shutdown(this.handle);
565
+ }
566
+ };
567
+ function createClientSession(config) {
568
+ const native = loadNative();
569
+ const core = new SessionCore();
570
+ try {
571
+ const handle = native.connect(
572
+ config.url,
573
+ config.hashes,
574
+ config.insecure,
575
+ config.origin,
576
+ config.headerNames,
577
+ config.headerValues,
578
+ (ev) => core.dispatch(ev)
579
+ );
580
+ core.attach(new ClientTransport(native, handle));
581
+ } catch (e) {
582
+ core.failSetup(e instanceof Error ? e.message : String(e));
583
+ }
584
+ return core;
585
+ }
586
+ var ServerTransport = class {
587
+ /**
588
+ * @param native - The loaded native addon.
589
+ * @param handle - The server handle these commands target.
590
+ * @param session - The id of the session these commands act on.
591
+ */
592
+ constructor(native, handle, session) {
593
+ this.native = native;
594
+ this.handle = handle;
595
+ this.session = session;
596
+ }
597
+ native;
598
+ handle;
599
+ session;
600
+ /**
601
+ * @param bidi - True for bidirectional, false for unidirectional.
602
+ * @param requestId - Id correlating the eventual `streamOpened` event.
603
+ */
604
+ openStream(bidi, requestId) {
605
+ this.native.serverOpenStream(this.handle, this.session, bidi, requestId);
606
+ }
607
+ /**
608
+ * @param streamId - The target stream id.
609
+ * @param bytes - The payload.
610
+ * @param requestId - Id correlating the eventual `writeAck` event.
611
+ */
612
+ write(streamId, bytes, requestId) {
613
+ this.native.serverWrite(this.handle, this.session, streamId, bytes, requestId);
614
+ }
615
+ /** @param streamId - The stream to finish. */
616
+ fin(streamId) {
617
+ this.native.serverFin(this.handle, this.session, streamId);
618
+ }
619
+ /**
620
+ * @param streamId - The stream to reset.
621
+ * @param code - The application error code.
622
+ */
623
+ reset(streamId, code) {
624
+ this.native.serverReset(this.handle, this.session, streamId, code);
625
+ }
626
+ /**
627
+ * @param streamId - The stream whose inbound half should be stopped.
628
+ * @param code - The application error code.
629
+ */
630
+ stopSending(streamId, code) {
631
+ this.native.serverStopSending(this.handle, this.session, streamId, code);
632
+ }
633
+ /**
634
+ * @param streamId - The receive stream.
635
+ * @param paused - True to pause draining, false to resume.
636
+ */
637
+ setPaused(streamId, paused) {
638
+ this.native.serverSetPaused(this.handle, this.session, streamId, paused);
639
+ }
640
+ /**
641
+ * @param bytes - The datagram payload.
642
+ * @param requestId - Id correlating the eventual `datagramAck` event.
643
+ */
644
+ sendDatagram(bytes, requestId) {
645
+ this.native.serverSendDatagram(this.handle, this.session, bytes, requestId);
646
+ }
647
+ /** @returns The maximum datagram payload size, in bytes. */
648
+ maxDatagramSize() {
649
+ return this.native.serverMaxDatagramSize(this.handle);
650
+ }
651
+ /**
652
+ * @param code - The WebTransport close code.
653
+ * @param reason - The UTF-8 encoded close reason.
654
+ */
655
+ closeSession(code, reason) {
656
+ this.native.serverCloseSession(this.handle, this.session, code, reason);
657
+ }
658
+ /**
659
+ * No-op: the server driver owns the session lifecycle, so there is nothing to
660
+ * tear down per session on the JS side.
661
+ */
662
+ shutdown() {
663
+ }
664
+ };
665
+
666
+ // src/datagrams.ts
667
+ var WebTransportDatagramDuplexStream = class {
668
+ /**
669
+ * The underlying session used to send datagrams, register the inbound sink,
670
+ * query the maximum datagram size, and observe session closure.
671
+ *
672
+ * @internal
673
+ */
674
+ session;
675
+ /**
676
+ * Stream of inbound datagrams. Each chunk is one received datagram payload.
677
+ * Backed by a {@link CountQueuingStrategy} whose high water mark is the
678
+ * value of {@link incomingHighWaterMark} captured when this instance was
679
+ * constructed. The stream is closed automatically when the session ends.
680
+ */
681
+ readable;
682
+ /**
683
+ * Stream for sending outbound datagrams. Writing a chunk forwards it to
684
+ * {@link SessionCore.sendDatagram}, whose boolean result (whether the
685
+ * datagram was actually transmitted rather than dropped) is discarded, so
686
+ * that `write()` resolves once the native transport reports back on the
687
+ * send attempt. Backed by a {@link CountQueuingStrategy} whose high water
688
+ * mark is the value of {@link outgoingHighWaterMark} captured when this
689
+ * instance was constructed.
690
+ */
691
+ writable;
692
+ /**
693
+ * High water mark (in datagrams) for the inbound `readable` queue. Read
694
+ * back through {@link incomingHighWaterMark}. Only the value present at
695
+ * construction time is applied to the actual {@link readable} strategy;
696
+ * later changes update the reported number but do not resize the live
697
+ * queue.
698
+ *
699
+ * @defaultValue 64
700
+ * @internal
701
+ */
702
+ incomingHwm = 64;
703
+ /**
704
+ * High water mark (in datagrams) for the outbound `writable` queue. Read
705
+ * back through {@link outgoingHighWaterMark}. Only the value present at
706
+ * construction time is applied to the actual {@link writable} strategy;
707
+ * later changes update the reported number but do not resize the live
708
+ * queue.
709
+ *
710
+ * @defaultValue 64
711
+ * @internal
712
+ */
713
+ outgoingHwm = 64;
714
+ /**
715
+ * Max age (ms) an inbound datagram is retained before being dropped, or
716
+ * `null` for no limit.
717
+ *
718
+ * @remarks
719
+ * Present to match the WHATWG interface. This class stores the value but
720
+ * does not currently enforce it: inbound loss here is driven only by the
721
+ * `readable` queue being full, not by datagram age.
722
+ *
723
+ * @defaultValue null
724
+ */
725
+ incomingMaxAge = null;
726
+ /**
727
+ * Max age (ms) an outbound datagram waits to be sent before being dropped,
728
+ * or `null` for no limit.
729
+ *
730
+ * @remarks
731
+ * Present to match the WHATWG interface. This class stores the value but
732
+ * does not currently enforce it; outbound loss is governed by the
733
+ * `writable` queue backpressure and the native QUIC layer.
734
+ *
735
+ * @defaultValue null
736
+ */
737
+ outgoingMaxAge = null;
738
+ /**
739
+ * Build the datagram duplex stream over a session.
740
+ *
741
+ * @param session - The session that carries the datagrams. Its
742
+ * {@link SessionCore.setDatagramSink} is used to receive inbound datagrams,
743
+ * {@link SessionCore.sendDatagram} to send them, and its
744
+ * {@link SessionCore.closed} promise to know when to close the inbound
745
+ * stream.
746
+ *
747
+ * @remarks
748
+ * Wiring performed here, in order:
749
+ *
750
+ * 1. Creates {@link readable} and captures its controller from `start`.
751
+ * 2. Installs a datagram sink that enqueues each received datagram only
752
+ * while the controller's `desiredSize` is positive (treating an unknown
753
+ * `desiredSize` of `null` as `1`, i.e. room available); datagrams that
754
+ * arrive when the queue is full are dropped.
755
+ * 3. Subscribes to the session's `closed` promise so the inbound stream is
756
+ * closed on both clean close and error, preventing a pending `read()`
757
+ * from hanging forever. A double-close is swallowed.
758
+ * 4. Creates {@link writable} whose `write` forwards each chunk to
759
+ * `session.sendDatagram` and maps the boolean ack to `undefined`.
760
+ */
761
+ constructor(session) {
762
+ this.session = session;
763
+ let rController;
764
+ this.readable = new ReadableStream(
765
+ {
766
+ start(c) {
767
+ rController = c;
768
+ }
769
+ },
770
+ new CountQueuingStrategy({ highWaterMark: this.incomingHwm })
771
+ );
772
+ session.setDatagramSink((data) => {
773
+ if ((rController.desiredSize ?? 1) > 0) {
774
+ rController.enqueue(data);
775
+ }
776
+ });
777
+ void session.closed.promise.then(
778
+ () => {
779
+ try {
780
+ rController.close();
781
+ } catch {
782
+ }
783
+ },
784
+ () => {
785
+ try {
786
+ rController.close();
787
+ } catch {
788
+ }
789
+ }
790
+ );
791
+ this.writable = new WritableStream(
792
+ {
793
+ write: (chunk) => session.sendDatagram(chunk).then(() => void 0)
794
+ },
795
+ new CountQueuingStrategy({ highWaterMark: this.outgoingHwm })
796
+ );
797
+ }
798
+ /**
799
+ * The largest datagram payload that currently fits in a single packet.
800
+ *
801
+ * @returns The maximum datagram payload size in bytes as reported by the
802
+ * native transport, or `0` when the session has no transport attached yet.
803
+ * The value can change over the life of the session as the path MTU is
804
+ * discovered.
805
+ */
806
+ get maxDatagramSize() {
807
+ return this.session.maxDatagramSize();
808
+ }
809
+ /**
810
+ * The high water mark (in datagrams) reported for the inbound `readable`
811
+ * queue.
812
+ *
813
+ * @returns The most recently set incoming high water mark.
814
+ */
815
+ get incomingHighWaterMark() {
816
+ return this.incomingHwm;
817
+ }
818
+ /**
819
+ * Set the reported inbound high water mark.
820
+ *
821
+ * @param value - Desired high water mark; coerced to an integer with
822
+ * `value | 0` and clamped to a minimum of `1`.
823
+ *
824
+ * @remarks
825
+ * This updates only the number returned by {@link incomingHighWaterMark}.
826
+ * The live {@link readable} queue keeps the strategy fixed at construction
827
+ * time, so changing this after construction does not resize it.
828
+ */
829
+ set incomingHighWaterMark(value) {
830
+ this.incomingHwm = Math.max(1, value | 0);
831
+ }
832
+ /**
833
+ * The high water mark (in datagrams) reported for the outbound `writable`
834
+ * queue.
835
+ *
836
+ * @returns The most recently set outgoing high water mark.
837
+ */
838
+ get outgoingHighWaterMark() {
839
+ return this.outgoingHwm;
840
+ }
841
+ /**
842
+ * Set the reported outbound high water mark.
843
+ *
844
+ * @param value - Desired high water mark; coerced to an integer with
845
+ * `value | 0` and clamped to a minimum of `1`.
846
+ *
847
+ * @remarks
848
+ * This updates only the number returned by {@link outgoingHighWaterMark}.
849
+ * The live {@link writable} queue keeps the strategy fixed at construction
850
+ * time, so changing this after construction does not resize it.
851
+ */
852
+ set outgoingHighWaterMark(value) {
853
+ this.outgoingHwm = Math.max(1, value | 0);
854
+ }
855
+ };
856
+
857
+ // src/streams.ts
858
+ function errorCode(reason) {
859
+ if (reason instanceof WebTransportError && reason.streamErrorCode != null) {
860
+ return reason.streamErrorCode >>> 0;
861
+ }
862
+ return 0;
863
+ }
864
+ var WebTransportReceiveStream = class extends ReadableStream {
865
+ /**
866
+ * The QUIC stream id of the underlying stream. Stable for the lifetime of the
867
+ * stream and shared with the paired {@link WebTransportSendStream} when this is
868
+ * one half of a {@link WebTransportBidirectionalStream}.
869
+ */
870
+ streamId;
871
+ /**
872
+ * Wire a `ReadableStream` up to a native receive stream.
873
+ *
874
+ * @param session - The session core that dispatches native events and issues
875
+ * flow-control and teardown commands for this stream.
876
+ * @param streamId - The QUIC stream id to receive from.
877
+ * @remarks Installs the `ReadableStream` underlying source and registers a
878
+ * {@link ReceiveSink} on `session` for `streamId`:
879
+ *
880
+ * - `pull` unpauses the native stream via `setPaused(streamId, false)`, so
881
+ * quiche resumes draining inbound bytes when the consumer wants more.
882
+ * - `cancel(reason)` sends `STOP_SENDING` to the peer with the code from
883
+ * {@link errorCode} and then unregisters the receive sink.
884
+ * - The sink's `onData` enqueues each chunk and, once the controller's
885
+ * `desiredSize` falls to zero or below (a nullish `desiredSize` is treated as
886
+ * `1`, so it does not pause), pauses the native stream to flow-control the
887
+ * peer.
888
+ * - The sink's `onFin` closes the controller (swallowing the error if it was
889
+ * already closed or errored) and unregisters.
890
+ * - The sink's `onReset(code)` errors the controller with a `'stream'`-sourced
891
+ * {@link WebTransportError} ('stream reset by peer') carrying the peer's code,
892
+ * then unregisters.
893
+ *
894
+ * A {@link CountQueuingStrategy} with a high-water mark of 32 chunks bounds the
895
+ * JS-side queue and thereby the pause threshold.
896
+ */
897
+ constructor(session, streamId) {
898
+ let controller;
899
+ super(
900
+ {
901
+ start(c) {
902
+ controller = c;
903
+ },
904
+ pull() {
905
+ session.setPaused(streamId, false);
906
+ },
907
+ cancel(reason) {
908
+ session.stopSending(streamId, errorCode(reason));
909
+ session.unregisterReceive(streamId);
910
+ }
911
+ },
912
+ new CountQueuingStrategy({ highWaterMark: 32 })
913
+ );
914
+ session.registerReceive(streamId, {
915
+ onData(chunk) {
916
+ controller.enqueue(chunk);
917
+ if ((controller.desiredSize ?? 1) <= 0) {
918
+ session.setPaused(streamId, true);
919
+ }
920
+ },
921
+ onFin() {
922
+ try {
923
+ controller.close();
924
+ } catch {
925
+ }
926
+ session.unregisterReceive(streamId);
927
+ },
928
+ onReset(code) {
929
+ controller.error(
930
+ new WebTransportError("stream reset by peer", {
931
+ source: "stream",
932
+ streamErrorCode: code
933
+ })
934
+ );
935
+ session.unregisterReceive(streamId);
936
+ }
937
+ });
938
+ this.streamId = streamId;
939
+ }
940
+ };
941
+ var WebTransportSendStream = class extends WritableStream {
942
+ /**
943
+ * The QUIC stream id of the underlying stream. Stable for the lifetime of the
944
+ * stream and shared with the paired {@link WebTransportReceiveStream} when this is
945
+ * one half of a {@link WebTransportBidirectionalStream}.
946
+ */
947
+ streamId;
948
+ /**
949
+ * Wire a `WritableStream` up to a native send stream.
950
+ *
951
+ * @param session - The session core that dispatches native events and issues
952
+ * write, FIN, reset, and teardown commands for this stream.
953
+ * @param streamId - The QUIC stream id to send on.
954
+ * @remarks Installs the `WritableStream` underlying sink and registers a
955
+ * {@link SendSink} on `session` for `streamId`:
956
+ *
957
+ * - `write(chunk)` forwards to `session.write` and returns its promise, which
958
+ * settles only once the bytes are accepted into quiche's send buffer; awaiting
959
+ * that promise is what applies end-to-end backpressure.
960
+ * - `close` sends a FIN via `finStream` and unregisters the send sink.
961
+ * - `abort(reason)` resets the stream via `resetStream` with the code from
962
+ * {@link errorCode} and unregisters the send sink.
963
+ * - The sink's `onStopSending(code)` errors the controller with a
964
+ * `'stream'`-sourced {@link WebTransportError} ('peer sent STOP_SENDING')
965
+ * carrying the peer's code (swallowing the error if the stream was already
966
+ * errored or closed) and unregisters.
967
+ *
968
+ * A {@link ByteLengthQueuingStrategy} with a high-water mark of 1 MiB
969
+ * (`1024 * 1024` bytes) bounds the JS-side write queue.
970
+ */
971
+ constructor(session, streamId) {
972
+ let controller;
973
+ super(
974
+ {
975
+ start(c) {
976
+ controller = c;
977
+ },
978
+ write(chunk) {
979
+ return session.write(streamId, chunk);
980
+ },
981
+ close() {
982
+ session.finStream(streamId);
983
+ session.unregisterSend(streamId);
984
+ },
985
+ abort(reason) {
986
+ session.resetStream(streamId, errorCode(reason));
987
+ session.unregisterSend(streamId);
988
+ }
989
+ },
990
+ new ByteLengthQueuingStrategy({ highWaterMark: 1024 * 1024 })
991
+ );
992
+ session.registerSend(streamId, {
993
+ onStopSending(code) {
994
+ try {
995
+ controller.error(
996
+ new WebTransportError("peer sent STOP_SENDING", {
997
+ source: "stream",
998
+ streamErrorCode: code
999
+ })
1000
+ );
1001
+ } catch {
1002
+ }
1003
+ session.unregisterSend(streamId);
1004
+ }
1005
+ });
1006
+ this.streamId = streamId;
1007
+ }
1008
+ };
1009
+ var WebTransportBidirectionalStream = class {
1010
+ /** The readable half, delivering bytes the peer sends on this stream. */
1011
+ readable;
1012
+ /** The writable half, sending bytes to the peer on this stream. */
1013
+ writable;
1014
+ /**
1015
+ * Construct both halves over the same QUIC stream.
1016
+ *
1017
+ * @param session - The session core backing both halves.
1018
+ * @param streamId - The QUIC stream id shared by the readable and writable halves.
1019
+ */
1020
+ constructor(session, streamId) {
1021
+ this.readable = new WebTransportReceiveStream(session, streamId);
1022
+ this.writable = new WebTransportSendStream(session, streamId);
1023
+ }
1024
+ };
1025
+
1026
+ // src/webtransport.ts
1027
+ function toBytes(src) {
1028
+ if (src instanceof ArrayBuffer) return new Uint8Array(src);
1029
+ return new Uint8Array(src.buffer, src.byteOffset, src.byteLength);
1030
+ }
1031
+ function buildConfig(url, options) {
1032
+ if (typeof url !== "string" || !url.startsWith("https://")) {
1033
+ throw new WebTransportError(`invalid WebTransport URL: ${url}`, { source: "session" });
1034
+ }
1035
+ const hashes = [];
1036
+ for (const hash of options.serverCertificateHashes ?? []) {
1037
+ const algorithm = hash.algorithm.toLowerCase();
1038
+ if (algorithm !== "sha-256") {
1039
+ throw new WebTransportError(
1040
+ `unsupported certificate hash algorithm: ${hash.algorithm} (only sha-256)`,
1041
+ { source: "session" }
1042
+ );
1043
+ }
1044
+ const bytes = toBytes(hash.value);
1045
+ if (bytes.byteLength !== 32) {
1046
+ throw new WebTransportError("sha-256 certificate hash must be 32 bytes", {
1047
+ source: "session"
1048
+ });
1049
+ }
1050
+ hashes.push(bytes);
1051
+ }
1052
+ const headerNames = [];
1053
+ const headerValues = [];
1054
+ for (const [name, value] of Object.entries(options.headers ?? {})) {
1055
+ headerNames.push(name);
1056
+ headerValues.push(value);
1057
+ }
1058
+ return {
1059
+ url,
1060
+ hashes,
1061
+ insecure: options.insecure ?? false,
1062
+ origin: options.origin ?? null,
1063
+ headerNames,
1064
+ headerValues
1065
+ };
1066
+ }
1067
+ var WebTransportSession = class {
1068
+ /**
1069
+ * The event dispatcher and command surface backing this session. Shared with
1070
+ * the datagram and stream wrappers so they can issue native commands and
1071
+ * register their inbound sinks. Protected so the server-side subclass can
1072
+ * reach it while it stays hidden from public API consumers.
1073
+ * @internal
1074
+ */
1075
+ core;
1076
+ /**
1077
+ * The session's datagram transport: a {@link WebTransportDatagramDuplexStream}
1078
+ * whose `readable` yields inbound datagrams and `writable` sends them.
1079
+ * Datagrams are unreliable and unordered; ones that do not fit the queue are
1080
+ * dropped rather than buffered.
1081
+ */
1082
+ datagrams;
1083
+ /**
1084
+ * A `ReadableStream` that yields a {@link WebTransportBidirectionalStream} for
1085
+ * every bidirectional stream the peer opens. Fed by the core's incoming
1086
+ * handler; it closes when the session closes cleanly and errors if the
1087
+ * session terminates abnormally.
1088
+ */
1089
+ incomingBidirectionalStreams;
1090
+ /**
1091
+ * A `ReadableStream` that yields a receive-only
1092
+ * {@link WebTransportReceiveStream} for every unidirectional stream the peer
1093
+ * opens. Fed by the core's incoming handler; it closes on clean session close
1094
+ * and errors on abnormal termination.
1095
+ */
1096
+ incomingUnidirectionalStreams;
1097
+ /**
1098
+ * Guards {@link WebTransportSession.close} so that repeated calls are no-ops
1099
+ * and the native close is issued at most once.
1100
+ * @internal
1101
+ */
1102
+ closeCalled = false;
1103
+ /**
1104
+ * Wire up the session surface around an existing {@link SessionCore}.
1105
+ *
1106
+ * @param core - The event dispatcher and command core for this session. For
1107
+ * the client this is a freshly connected client session; for the server it is
1108
+ * a session-scoped core created by the server driver.
1109
+ * @remarks Creates the {@link WebTransportSession.datagrams} duplex, then
1110
+ * constructs the two incoming-stream `ReadableStream`s and captures their
1111
+ * controllers via the `start` callback. Registers an incoming handler on
1112
+ * `core` so each peer-opened bidi/uni stream is wrapped and enqueued;
1113
+ * `enqueue` is wrapped in try/catch because it throws once the consumer has
1114
+ * cancelled the reader, and that error must not escape native event dispatch.
1115
+ * Finally it observes `core.closed`: on clean close both controllers are
1116
+ * closed via {@link safeClose}, and on rejection both are errored with the
1117
+ * failure reason via {@link safeError}.
1118
+ */
1119
+ constructor(core) {
1120
+ this.core = core;
1121
+ this.datagrams = new WebTransportDatagramDuplexStream(core);
1122
+ let bidiController;
1123
+ let uniController;
1124
+ this.incomingBidirectionalStreams = new ReadableStream({
1125
+ start: (c) => {
1126
+ bidiController = c;
1127
+ }
1128
+ });
1129
+ this.incomingUnidirectionalStreams = new ReadableStream({
1130
+ start: (c) => {
1131
+ uniController = c;
1132
+ }
1133
+ });
1134
+ core.setIncomingHandler({
1135
+ onBidi: (id) => {
1136
+ try {
1137
+ bidiController.enqueue(new WebTransportBidirectionalStream(core, id));
1138
+ } catch {
1139
+ }
1140
+ },
1141
+ onUni: (id) => {
1142
+ try {
1143
+ uniController.enqueue(new WebTransportReceiveStream(core, id));
1144
+ } catch {
1145
+ }
1146
+ }
1147
+ });
1148
+ core.closed.promise.then(
1149
+ () => {
1150
+ safeClose(bidiController);
1151
+ safeClose(uniController);
1152
+ },
1153
+ (err) => {
1154
+ safeError(bidiController, err);
1155
+ safeError(uniController, err);
1156
+ }
1157
+ );
1158
+ }
1159
+ /**
1160
+ * A promise that resolves once the session handshake completes and the
1161
+ * session is established, and rejects if the session fails or closes before
1162
+ * it becomes ready.
1163
+ * @returns The core's `ready` promise.
1164
+ */
1165
+ get ready() {
1166
+ return this.core.ready.promise;
1167
+ }
1168
+ /**
1169
+ * A promise that resolves with the {@link WebTransportCloseInfo} (close code
1170
+ * and reason) when the session ends cleanly, and rejects with a
1171
+ * {@link WebTransportError} on abnormal termination or if the session never
1172
+ * became ready.
1173
+ * @returns The core's `closed` promise.
1174
+ */
1175
+ get closed() {
1176
+ return this.core.closed.promise;
1177
+ }
1178
+ /**
1179
+ * Open a new outbound bidirectional stream.
1180
+ *
1181
+ * @returns A promise resolving to a {@link WebTransportBidirectionalStream}
1182
+ * (paired readable and writable halves) once the native side reports the new
1183
+ * stream id.
1184
+ * @throws WebTransportError (the returned promise rejects) if the session is
1185
+ * already closed or was never attached.
1186
+ */
1187
+ async createBidirectionalStream() {
1188
+ const id = await this.core.openStream(true);
1189
+ return new WebTransportBidirectionalStream(this.core, id);
1190
+ }
1191
+ /**
1192
+ * Open a new outbound unidirectional (send-only) stream.
1193
+ *
1194
+ * @returns A promise resolving to a {@link WebTransportSendStream} once the
1195
+ * native side reports the new stream id.
1196
+ * @throws WebTransportError (the returned promise rejects) if the session is
1197
+ * already closed or was never attached.
1198
+ */
1199
+ async createUnidirectionalStream() {
1200
+ const id = await this.core.openStream(false);
1201
+ return new WebTransportSendStream(this.core, id);
1202
+ }
1203
+ /**
1204
+ * Close the session gracefully, notifying the peer with an application code
1205
+ * and reason.
1206
+ *
1207
+ * @param closeInfo - Close options. `closeInfo.closeCode` defaults to `0` and
1208
+ * `closeInfo.reason` defaults to `''`; both are forwarded to the native
1209
+ * close.
1210
+ * @defaultValue `closeInfo` defaults to `{}` (close code `0`, empty reason).
1211
+ * @remarks Idempotent: guarded by {@link WebTransportSession.closeCalled} so
1212
+ * only the first call takes effect and later calls are no-ops. Delegates to
1213
+ * the core, which issues the native `closeSession` (a graceful
1214
+ * CLOSE_WEBTRANSPORT_SESSION capsule plus FIN, then QUIC close) only while the
1215
+ * session is still attached and not already closed.
1216
+ */
1217
+ close(closeInfo = {}) {
1218
+ if (this.closeCalled) return;
1219
+ this.closeCalled = true;
1220
+ this.core.close(closeInfo.closeCode ?? 0, closeInfo.reason ?? "");
1221
+ }
1222
+ };
1223
+ var WebTransport = class extends WebTransportSession {
1224
+ /**
1225
+ * Create and begin connecting a WebTransport client session.
1226
+ *
1227
+ * @param url - The session URL; must be an `https://` URL.
1228
+ * @param options - Session options: certificate pinning, extra headers,
1229
+ * origin, and the Node-specific `insecure` flag.
1230
+ * @defaultValue `options` defaults to `{}`.
1231
+ * @throws WebTransportError synchronously if {@link buildConfig} rejects the
1232
+ * URL or a certificate hash. Asynchronous setup failures (DNS, bind,
1233
+ * handshake) instead reject {@link WebTransportSession.ready | ready} and
1234
+ * {@link WebTransportSession.closed | closed}.
1235
+ * @remarks Validates and normalizes inputs via {@link buildConfig}, then
1236
+ * calls {@link createClientSession} to spawn the native driver thread and
1237
+ * passes the resulting {@link SessionCore} to the base constructor.
1238
+ */
1239
+ constructor(url, options = {}) {
1240
+ super(createClientSession(buildConfig(url, options)));
1241
+ }
1242
+ };
1243
+ function safeClose(controller) {
1244
+ try {
1245
+ controller.close();
1246
+ } catch {
1247
+ }
1248
+ }
1249
+ function safeError(controller, reason) {
1250
+ try {
1251
+ controller.error(reason);
1252
+ } catch {
1253
+ }
1254
+ }
1255
+
1256
+ // src/server.ts
1257
+ function deferred2() {
1258
+ let resolve;
1259
+ let reject;
1260
+ const promise = new Promise((res, rej) => {
1261
+ resolve = res;
1262
+ reject = rej;
1263
+ });
1264
+ return { promise, resolve, reject };
1265
+ }
1266
+ var WebTransportServerSession = class extends WebTransportSession {
1267
+ /** The `:authority` of the client's CONNECT request. */
1268
+ authority;
1269
+ /** The `:path` of the client's CONNECT request. */
1270
+ path;
1271
+ /** The `origin` header, if the client sent one, otherwise `null`. */
1272
+ origin;
1273
+ /** Any additional (non-pseudo) request headers, keyed by header name. */
1274
+ headers;
1275
+ /**
1276
+ * The client's remote IP address, as reported by the transport when the
1277
+ * session was established. The same for every stream and datagram on this
1278
+ * session, since they all share the one QUIC connection.
1279
+ */
1280
+ remoteAddress;
1281
+ /** The client's remote UDP port at session establishment. */
1282
+ remotePort;
1283
+ /**
1284
+ * Wrap an established session core together with the CONNECT metadata that
1285
+ * opened it. Called by {@link WebTransportServer} when a new session becomes
1286
+ * ready; not intended for direct construction by users.
1287
+ *
1288
+ * @param core - The dispatcher/command core backing this session, already
1289
+ * attached to a {@link ServerTransport}.
1290
+ * @param request - The CONNECT metadata (authority, path, origin, headers)
1291
+ * plus the client's remote address, copied onto this session's public fields.
1292
+ */
1293
+ constructor(core, request) {
1294
+ super(core);
1295
+ this.authority = request.authority;
1296
+ this.path = request.path;
1297
+ this.origin = request.origin;
1298
+ this.headers = request.headers;
1299
+ this.remoteAddress = request.remoteAddress;
1300
+ this.remotePort = request.remotePort;
1301
+ }
1302
+ };
1303
+ var WebTransportServer = class {
1304
+ /** The loaded native addon, source of the `server*` command functions. */
1305
+ native;
1306
+ /** Opaque native server handle returned by `serverListen`. */
1307
+ handle;
1308
+ /** Live sessions keyed by their native session id, for event routing. */
1309
+ sessions = /* @__PURE__ */ new Map();
1310
+ /** Settled when the native side reports `listening`; backs {@link ready}. */
1311
+ readyD = deferred2();
1312
+ /**
1313
+ * Settled when the server stops (`serverClosed`) or fatally fails
1314
+ * (`serverError`); backs {@link closed}.
1315
+ */
1316
+ closedD = deferred2();
1317
+ /** Controller for {@link incomingSessions}; captured in its `start`. */
1318
+ incomingController;
1319
+ /** The UDP port actually bound, learned from the `listening` event. */
1320
+ boundPort = 0;
1321
+ /** Guards {@link close} so shutdown is issued at most once. */
1322
+ closeCalled = false;
1323
+ /**
1324
+ * The sessions clients open, delivered as they are established. Each pull
1325
+ * yields a {@link WebTransportServerSession}. The stream is closed when the
1326
+ * server stops or errors.
1327
+ */
1328
+ incomingSessions;
1329
+ /**
1330
+ * Load the native addon and start listening immediately.
1331
+ *
1332
+ * Sets up {@link incomingSessions} (capturing its controller), attaches
1333
+ * no-op catch handlers to the internal ready/closed promises so they never
1334
+ * surface as unhandled rejections, then calls the native `serverListen` with
1335
+ * the given certificate, key, host, port and reuse-port flag, wiring every
1336
+ * native event to {@link onEvent}.
1337
+ *
1338
+ * @param options - Bind address, port, certificate/key paths and reuse-port
1339
+ * flag. `host` defaults to `'0.0.0.0'` and `reusePort` defaults to `false`.
1340
+ * @see {@link ready} to await binding and {@link WebTransportServerOptions}.
1341
+ */
1342
+ constructor(options) {
1343
+ this.native = loadNative();
1344
+ void this.readyD.promise.catch(() => {
1345
+ });
1346
+ void this.closedD.promise.catch(() => {
1347
+ });
1348
+ this.incomingSessions = new ReadableStream({
1349
+ start: (c) => {
1350
+ this.incomingController = c;
1351
+ }
1352
+ });
1353
+ this.handle = this.native.serverListen(
1354
+ options.cert,
1355
+ options.key,
1356
+ options.host ?? "0.0.0.0",
1357
+ options.port,
1358
+ options.reusePort ?? false,
1359
+ (ev) => this.onEvent(ev)
1360
+ );
1361
+ }
1362
+ /**
1363
+ * Resolves once the server is listening (the native `listening` event has
1364
+ * arrived); rejects if the server fails before it binds.
1365
+ */
1366
+ get ready() {
1367
+ return this.readyD.promise;
1368
+ }
1369
+ /**
1370
+ * Resolves when the server has stopped cleanly (`serverClosed`), rejects on
1371
+ * a fatal server error (`serverError`).
1372
+ */
1373
+ get closed() {
1374
+ return this.closedD.promise;
1375
+ }
1376
+ /** The UDP port the server is bound to (valid after {@link ready}). */
1377
+ get port() {
1378
+ return this.boundPort;
1379
+ }
1380
+ /**
1381
+ * Stop the server and all its sessions. Idempotent: repeated calls after the
1382
+ * first are ignored. Triggers the native `serverShutdown`, which eventually
1383
+ * drives a `serverClosed` event that settles {@link closed} and finishes any
1384
+ * remaining sessions.
1385
+ */
1386
+ close() {
1387
+ if (this.closeCalled) return;
1388
+ this.closeCalled = true;
1389
+ this.native.serverShutdown(this.handle);
1390
+ }
1391
+ /**
1392
+ * Handle one native server event. Server-level events (`listening`,
1393
+ * `serverError`, `serverClosed`) settle the server's ready/closed promises
1394
+ * and, on stop or error, finish all sessions and close
1395
+ * {@link incomingSessions}. Session-scoped events carry a `session` id: a
1396
+ * `serverReady` creates and registers a new {@link SessionCore} (attached to
1397
+ * a {@link ServerTransport}), wraps it in a {@link WebTransportServerSession}
1398
+ * and enqueues it; every session-scoped event is then dispatched to the
1399
+ * matching core.
1400
+ *
1401
+ * @param ev - The event delivered by the native `serverListen` callback.
1402
+ * @remarks Enqueue into {@link incomingSessions} is guarded: if the consumer
1403
+ * has stopped reading, the thrown error is swallowed so it cannot escape
1404
+ * the native event dispatch. On `serverError`, the `WebTransportError` is
1405
+ * created with `source: 'session'`.
1406
+ */
1407
+ onEvent(ev) {
1408
+ switch (ev.type) {
1409
+ case "listening" /* Listening */: {
1410
+ this.boundPort = ev.port;
1411
+ this.readyD.resolve();
1412
+ return;
1413
+ }
1414
+ case "serverError" /* ServerError */: {
1415
+ const err = new WebTransportError(ev.message, { source: "session" });
1416
+ this.readyD.reject(err);
1417
+ this.closedD.reject(err);
1418
+ this.finishAllSessions();
1419
+ safeCloseController(this.incomingController);
1420
+ return;
1421
+ }
1422
+ case "serverClosed" /* ServerClosed */: {
1423
+ this.closedD.resolve();
1424
+ this.finishAllSessions();
1425
+ safeCloseController(this.incomingController);
1426
+ return;
1427
+ }
1428
+ }
1429
+ const sessionId = ev.session;
1430
+ if (ev.type === "serverReady" /* ServerReady */) {
1431
+ const core = new SessionCore();
1432
+ core.attach(new ServerTransport(this.native, this.handle, sessionId));
1433
+ this.sessions.set(sessionId, core);
1434
+ void core.closed.promise.finally(() => this.sessions.delete(sessionId));
1435
+ const session = new WebTransportServerSession(core, {
1436
+ authority: ev.authority,
1437
+ path: ev.path,
1438
+ origin: ev.origin,
1439
+ headers: ev.headers,
1440
+ remoteAddress: ev.remoteAddress,
1441
+ remotePort: ev.remotePort
1442
+ });
1443
+ try {
1444
+ this.incomingController.enqueue(session);
1445
+ } catch {
1446
+ }
1447
+ }
1448
+ this.sessions.get(sessionId)?.dispatch(ev);
1449
+ }
1450
+ /**
1451
+ * Settle every live session when the server stops, so their `ready`/`closed`
1452
+ * promises never hang and the session map does not leak.
1453
+ *
1454
+ * @remarks Dispatches a synthetic clean `closed` event (code `0`, empty
1455
+ * reason, `remote: false`) to each session core, then clears the map. The
1456
+ * per-core `closed.finally` handler registered in {@link onEvent} would
1457
+ * also remove entries, but the map is cleared here unconditionally.
1458
+ */
1459
+ finishAllSessions() {
1460
+ for (const core of this.sessions.values()) {
1461
+ core.dispatch({
1462
+ type: "closed" /* Closed */,
1463
+ code: 0,
1464
+ reason: new Uint8Array(),
1465
+ remote: false
1466
+ });
1467
+ }
1468
+ this.sessions.clear();
1469
+ }
1470
+ };
1471
+ function safeCloseController(controller) {
1472
+ try {
1473
+ controller.close();
1474
+ } catch {
1475
+ }
1476
+ }
1477
+ // Annotate the CommonJS export names for ESM import in node:
1478
+ 0 && (module.exports = {
1479
+ WebTransport,
1480
+ WebTransportBidirectionalStream,
1481
+ WebTransportDatagramDuplexStream,
1482
+ WebTransportError,
1483
+ WebTransportReceiveStream,
1484
+ WebTransportSendStream,
1485
+ WebTransportServer,
1486
+ WebTransportServerSession,
1487
+ WebTransportSession
1488
+ });
1489
+ //! Locates and loads the rwebtransport native addon.
1490
+ //!
1491
+ //! Resolution order:
1492
+ //! 1. A prebuilt binary at `prebuilds/<platform>-<arch>/rwebtransport.node`.
1493
+ //! 2. If none is found, compile the Rust crate on the fly via `scripts/build.js`
1494
+ //! (requires a Rust toolchain + cmake + C/C++ compiler) and load the result.
1495
+ //! Only Node 24 and Node 26 are supported.
1496
+ //! The `WebTransportError` type, matching the W3C interface.
1497
+ //! Typed view of the native addon and the event dispatcher that turns its
1498
+ //! low-level, callback-based ABI into promises and per-stream sinks.
1499
+ //! `WebTransportDatagramDuplexStream`: unreliable, unordered datagrams.
1500
+ //! WebTransport stream classes, implemented as WHATWG Readable/Writable streams
1501
+ //! with end-to-end backpressure onto the native QUIC flow-control window.
1502
+ //! The `WebTransport` class: the W3C entry point.
1503
+ //! The `WebTransportServer` accepts WebTransport sessions from clients. Each
1504
+ //! established session is a {@link WebTransportServerSession}, which shares the
1505
+ //! full stream/datagram surface with the client `WebTransport`.
1506
+ //! rwebtransport: a fully-compatible WebTransport client and server for Node.js.
1507
+ //! ```ts
1508
+ //! import { WebTransport } from 'rwebtransport';
1509
+ //! const wt = new WebTransport('https://example.com:4433/echo');
1510
+ //! await wt.ready;
1511
+ //! ```
1512
+ //# sourceMappingURL=index.js.map