rwebtransport 0.1.2 → 0.2.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.
package/dist/index.mjs CHANGED
@@ -103,6 +103,10 @@ var SessionCore = class {
103
103
  writes = /* @__PURE__ */ new Map();
104
104
  /** Pending {@link SessionCore.sendDatagram} requests, keyed by request id. */
105
105
  datagramAcks = /* @__PURE__ */ new Map();
106
+ /** Pending getStats() requests, keyed by request id. */
107
+ statsRequests = /* @__PURE__ */ new Map();
108
+ /** Pending exportKeyingMaterial() requests, keyed by request id. */
109
+ keyingMaterialRequests = /* @__PURE__ */ new Map();
106
110
  /** Active receive sinks, keyed by stream id. */
107
111
  receives = /* @__PURE__ */ new Map();
108
112
  /** Active send sinks, keyed by stream id. */
@@ -111,10 +115,20 @@ var SessionCore = class {
111
115
  incoming;
112
116
  /** Sink for inbound datagrams, if one has been set. */
113
117
  datagramSink;
118
+ /** Count of inbound datagrams dropped because the readable queue was full. */
119
+ droppedIncomingDatagrams = 0;
114
120
  /** True once the session has reached its terminal (closed) state. */
115
121
  closedState = false;
116
122
  /** True once the session has been established (`ready`/`serverReady`). */
117
123
  readyState = false;
124
+ /** True when the session reached its terminal state through an error. */
125
+ failedState = false;
126
+ /** The most recent stats reported by the native layer, cached for {@link SessionCore.getStats}. */
127
+ lastStats;
128
+ /** The negotiated subprotocol, cached from the ready event (`''` if none). */
129
+ cachedProtocol = "";
130
+ /** The CONNECT response headers, cached from the client ready event. */
131
+ cachedResponseHeaders = [];
118
132
  /**
119
133
  * Resolves when the session is established, rejects if it fails before then.
120
134
  * Backs the public `WebTransport.ready` promise.
@@ -125,6 +139,12 @@ var SessionCore = class {
125
139
  * close that happens before the session is ready. Backs `WebTransport.closed`.
126
140
  */
127
141
  closed = deferred();
142
+ /**
143
+ * Resolves when the peer sends a DRAIN_WEBTRANSPORT_SESSION capsule (it
144
+ * intends to close soon but the session stays usable). Backs
145
+ * `WebTransport.draining`. Never rejects.
146
+ */
147
+ draining = deferred();
128
148
  /**
129
149
  * Attach no-op catch handlers to {@link SessionCore.ready} and
130
150
  * {@link SessionCore.closed} so that a session whose promises the user never
@@ -264,6 +284,42 @@ var SessionCore = class {
264
284
  if (this.closedState || !this.transport) return;
265
285
  this.transport.closeSession(code >>> 0, new TextEncoder().encode(reason));
266
286
  }
287
+ /** Tell the peer this session is draining (send a DRAIN capsule). */
288
+ drain() {
289
+ this.transport?.drain();
290
+ }
291
+ /**
292
+ * Snapshot the connection's stats. Resolves with a
293
+ * {@link WebTransportConnectionStats} once the driver reports back. After a
294
+ * clean close it resolves with the last stats seen while live; it rejects
295
+ * only when the session was never attached or terminated through an error.
296
+ */
297
+ getStats() {
298
+ if (!this.usable()) {
299
+ if (!this.failedState && this.lastStats !== void 0) {
300
+ return Promise.resolve(this.lastStats);
301
+ }
302
+ return Promise.reject(this.deadError());
303
+ }
304
+ const requestId = this.nextId();
305
+ const d = deferred();
306
+ this.statsRequests.set(requestId, d);
307
+ this.transport.getStats(requestId);
308
+ return d.promise;
309
+ }
310
+ /**
311
+ * Export TLS keying material (RFC 5705). Resolves with `length` bytes derived
312
+ * from `label` and `context` once the driver reports back; rejects if the
313
+ * session is not usable or the TLS export fails.
314
+ */
315
+ exportKeyingMaterial(label, context, length) {
316
+ if (!this.usable()) return Promise.reject(this.deadError());
317
+ const requestId = this.nextId();
318
+ const d = deferred();
319
+ this.keyingMaterialRequests.set(requestId, d);
320
+ this.transport.exportKeyingMaterial(requestId, label, context, length);
321
+ return d.promise;
322
+ }
267
323
  /** Tear down the native resources for this session. No-op if not attached. */
268
324
  shutdown() {
269
325
  this.transport?.shutdown();
@@ -332,6 +388,13 @@ var SessionCore = class {
332
388
  setDatagramSink(sink) {
333
389
  this.datagramSink = sink;
334
390
  }
391
+ /**
392
+ * Record that one inbound datagram was dropped because the readable queue
393
+ * was full. Surfaced through getStats() as `datagrams.droppedIncoming`.
394
+ */
395
+ recordDroppedIncomingDatagram() {
396
+ this.droppedIncomingDatagrams++;
397
+ }
335
398
  /**
336
399
  * Route one native event to the appropriate promise, sink, or handler.
337
400
  *
@@ -346,12 +409,23 @@ var SessionCore = class {
346
409
  */
347
410
  dispatch(ev) {
348
411
  switch (ev.type) {
349
- case "ready" /* Ready */:
412
+ case "ready" /* Ready */: {
413
+ this.readyState = true;
414
+ this.cachedProtocol = ev.protocol ?? "";
415
+ this.cachedResponseHeaders = ev.responseHeaders;
416
+ this.ready.resolve();
417
+ break;
418
+ }
350
419
  case "serverReady" /* ServerReady */: {
351
420
  this.readyState = true;
421
+ this.cachedProtocol = ev.protocol ?? "";
352
422
  this.ready.resolve();
353
423
  break;
354
424
  }
425
+ case "draining" /* Draining */: {
426
+ this.draining.resolve();
427
+ break;
428
+ }
355
429
  case "closed" /* Closed */: {
356
430
  const reason = new TextDecoder().decode(ev.reason);
357
431
  this.finish({ closeCode: ev.code, reason }, void 0);
@@ -402,6 +476,44 @@ var SessionCore = class {
402
476
  this.datagramAcks.delete(ev.requestId);
403
477
  break;
404
478
  }
479
+ case "stats" /* Stats */: {
480
+ const stats = {
481
+ bytesSent: ev.bytesSent,
482
+ bytesReceived: ev.bytesReceived,
483
+ packetsSent: ev.packetsSent,
484
+ packetsReceived: ev.packetsReceived,
485
+ packetsLost: ev.packetsLost,
486
+ smoothedRtt: ev.smoothedRtt,
487
+ rttVariation: ev.rttVariation,
488
+ minRtt: ev.minRtt,
489
+ datagrams: {
490
+ expiredOutgoing: 0,
491
+ droppedIncoming: this.droppedIncomingDatagrams,
492
+ lostOutgoing: 0,
493
+ expiredIncoming: 0
494
+ }
495
+ };
496
+ this.lastStats = stats;
497
+ this.statsRequests.get(ev.requestId)?.resolve(stats);
498
+ this.statsRequests.delete(ev.requestId);
499
+ break;
500
+ }
501
+ case "keyingMaterial" /* KeyingMaterial */: {
502
+ const d = this.keyingMaterialRequests.get(ev.requestId);
503
+ if (d) {
504
+ if (ev.ok && ev.data) {
505
+ d.resolve(ev.data);
506
+ } else {
507
+ d.reject(
508
+ new WebTransportError("keying material export failed", {
509
+ source: "session"
510
+ })
511
+ );
512
+ }
513
+ this.keyingMaterialRequests.delete(ev.requestId);
514
+ }
515
+ break;
516
+ }
405
517
  }
406
518
  }
407
519
  /**
@@ -423,6 +535,8 @@ var SessionCore = class {
423
535
  finish(info, error) {
424
536
  if (this.closedState) return;
425
537
  this.closedState = true;
538
+ if (error) this.failedState = true;
539
+ this.draining.resolve();
426
540
  if (!this.readyState) {
427
541
  const err2 = error ?? new WebTransportError("session closed before it was established", {
428
542
  source: "session"
@@ -438,11 +552,15 @@ var SessionCore = class {
438
552
  for (const d of this.opens.values()) d.reject(err);
439
553
  for (const d of this.writes.values()) d.reject(err);
440
554
  for (const d of this.datagramAcks.values()) d.resolve(false);
441
- for (const sink of this.receives.values()) sink.onReset(0);
442
- for (const sink of this.sends.values()) sink.onStopSending(0);
555
+ for (const d of this.statsRequests.values()) d.reject(err);
556
+ for (const d of this.keyingMaterialRequests.values()) d.reject(err);
557
+ for (const sink of this.receives.values()) sink.onSessionClose(err);
558
+ for (const sink of this.sends.values()) sink.onSessionClose(err);
443
559
  this.opens.clear();
444
560
  this.writes.clear();
445
561
  this.datagramAcks.clear();
562
+ this.statsRequests.clear();
563
+ this.keyingMaterialRequests.clear();
446
564
  this.receives.clear();
447
565
  this.sends.clear();
448
566
  this.transport?.shutdown();
@@ -451,6 +569,18 @@ var SessionCore = class {
451
569
  get isClosed() {
452
570
  return this.closedState;
453
571
  }
572
+ /** @returns Whether the session has been established (ready). */
573
+ get isReady() {
574
+ return this.readyState;
575
+ }
576
+ /** @returns The negotiated subprotocol, or `''` if none was negotiated. */
577
+ get protocol() {
578
+ return this.cachedProtocol;
579
+ }
580
+ /** @returns The CONNECT response headers as ordered `[name, value]` pairs. */
581
+ get responseHeaders() {
582
+ return this.cachedResponseHeaders;
583
+ }
454
584
  };
455
585
  var ClientTransport = class {
456
586
  /**
@@ -521,6 +651,18 @@ var ClientTransport = class {
521
651
  closeSession(code, reason) {
522
652
  this.native.closeSession(this.handle, code, reason);
523
653
  }
654
+ /** Send a DRAIN_WEBTRANSPORT_SESSION capsule to the peer. */
655
+ drain() {
656
+ this.native.drain(this.handle);
657
+ }
658
+ /** Request connection stats; the result arrives as a `stats` event. */
659
+ getStats(requestId) {
660
+ this.native.getStats(this.handle, requestId);
661
+ }
662
+ /** Export TLS keying material; the result arrives as a `keyingMaterial` event. */
663
+ exportKeyingMaterial(requestId, label, context, length) {
664
+ this.native.exportKeyingMaterial(this.handle, requestId, label, context, length);
665
+ }
524
666
  /** Tear down the session's native driver thread. */
525
667
  shutdown() {
526
668
  this.native.shutdown(this.handle);
@@ -537,6 +679,7 @@ function createClientSession(config) {
537
679
  config.origin,
538
680
  config.headerNames,
539
681
  config.headerValues,
682
+ config.protocols,
540
683
  (ev) => core.dispatch(ev)
541
684
  );
542
685
  core.attach(new ClientTransport(native, handle));
@@ -617,6 +760,25 @@ var ServerTransport = class {
617
760
  closeSession(code, reason) {
618
761
  this.native.serverCloseSession(this.handle, this.session, code, reason);
619
762
  }
763
+ /** Send a DRAIN_WEBTRANSPORT_SESSION capsule to this session's peer. */
764
+ drain() {
765
+ this.native.serverDrain(this.handle, this.session);
766
+ }
767
+ /** Request this session's connection stats; the result arrives as a `stats` event. */
768
+ getStats(requestId) {
769
+ this.native.serverGetStats(this.handle, this.session, requestId);
770
+ }
771
+ /** Export TLS keying material; the result arrives as a `keyingMaterial` event. */
772
+ exportKeyingMaterial(requestId, label, context, length) {
773
+ this.native.serverExportKeyingMaterial(
774
+ this.handle,
775
+ this.session,
776
+ requestId,
777
+ label,
778
+ context,
779
+ length
780
+ );
781
+ }
620
782
  /**
621
783
  * No-op: the server driver owns the session lifecycle, so there is nothing to
622
784
  * tear down per session on the JS side.
@@ -734,6 +896,8 @@ var WebTransportDatagramDuplexStream = class {
734
896
  session.setDatagramSink((data) => {
735
897
  if ((rController.desiredSize ?? 1) > 0) {
736
898
  rController.enqueue(data);
899
+ } else {
900
+ session.recordDroppedIncomingDatagram();
737
901
  }
738
902
  });
739
903
  void session.closed.promise.then(
@@ -895,11 +1059,20 @@ var WebTransportReceiveStream = class extends ReadableStream {
895
1059
  })
896
1060
  );
897
1061
  session.unregisterReceive(streamId);
1062
+ },
1063
+ onSessionClose(error) {
1064
+ try {
1065
+ controller.error(error);
1066
+ } catch {
1067
+ }
1068
+ session.unregisterReceive(streamId);
898
1069
  }
899
1070
  });
900
1071
  this.streamId = streamId;
901
1072
  }
902
1073
  };
1074
+ var WebTransportSendGroup = class {
1075
+ };
903
1076
  var WebTransportSendStream = class extends WritableStream {
904
1077
  /**
905
1078
  * The QUIC stream id of the underlying stream. Stable for the lifetime of the
@@ -907,6 +1080,16 @@ var WebTransportSendStream = class extends WritableStream {
907
1080
  * one half of a {@link WebTransportBidirectionalStream}.
908
1081
  */
909
1082
  streamId;
1083
+ /**
1084
+ * The {@link WebTransportSendGroup} this stream belongs to, or `null`.
1085
+ * Mutable per the W3C API; grouping is a best-effort scheduling hint.
1086
+ */
1087
+ sendGroup;
1088
+ /**
1089
+ * Relative send priority within the send group. Higher values are nominally
1090
+ * sent first. Mutable per the W3C API; the effect on the wire is best-effort.
1091
+ */
1092
+ sendOrder;
910
1093
  /**
911
1094
  * Wire a `WritableStream` up to a native send stream.
912
1095
  *
@@ -930,7 +1113,7 @@ var WebTransportSendStream = class extends WritableStream {
930
1113
  * A {@link ByteLengthQueuingStrategy} with a high-water mark of 1 MiB
931
1114
  * (`1024 * 1024` bytes) bounds the JS-side write queue.
932
1115
  */
933
- constructor(session, streamId) {
1116
+ constructor(session, streamId, options = {}) {
934
1117
  let controller;
935
1118
  super(
936
1119
  {
@@ -963,9 +1146,18 @@ var WebTransportSendStream = class extends WritableStream {
963
1146
  } catch {
964
1147
  }
965
1148
  session.unregisterSend(streamId);
1149
+ },
1150
+ onSessionClose(error) {
1151
+ try {
1152
+ controller.error(error);
1153
+ } catch {
1154
+ }
1155
+ session.unregisterSend(streamId);
966
1156
  }
967
1157
  });
968
1158
  this.streamId = streamId;
1159
+ this.sendGroup = options.sendGroup ?? null;
1160
+ this.sendOrder = options.sendOrder ?? 0;
969
1161
  }
970
1162
  };
971
1163
  var WebTransportBidirectionalStream = class {
@@ -979,9 +1171,9 @@ var WebTransportBidirectionalStream = class {
979
1171
  * @param session - The session core backing both halves.
980
1172
  * @param streamId - The QUIC stream id shared by the readable and writable halves.
981
1173
  */
982
- constructor(session, streamId) {
1174
+ constructor(session, streamId, options = {}) {
983
1175
  this.readable = new WebTransportReceiveStream(session, streamId);
984
- this.writable = new WebTransportSendStream(session, streamId);
1176
+ this.writable = new WebTransportSendStream(session, streamId, options);
985
1177
  }
986
1178
  };
987
1179
 
@@ -1023,7 +1215,8 @@ function buildConfig(url, options) {
1023
1215
  insecure: options.insecure ?? false,
1024
1216
  origin: options.origin ?? null,
1025
1217
  headerNames,
1026
- headerValues
1218
+ headerValues,
1219
+ protocols: options.protocols ?? []
1027
1220
  };
1028
1221
  }
1029
1222
  var WebTransportSession = class {
@@ -1137,6 +1330,32 @@ var WebTransportSession = class {
1137
1330
  get closed() {
1138
1331
  return this.core.closed.promise;
1139
1332
  }
1333
+ /**
1334
+ * A promise that resolves when the peer signals it is draining the session
1335
+ * (a `DRAIN_WEBTRANSPORT_SESSION` capsule): it intends to close soon, so you
1336
+ * should stop opening new streams, but the session and its existing streams
1337
+ * stay usable until {@link closed}. Never rejects.
1338
+ * @returns The core's `draining` promise.
1339
+ */
1340
+ get draining() {
1341
+ return this.core.draining.promise;
1342
+ }
1343
+ /**
1344
+ * The reliability modes this session supports. `'pending'` until the session
1345
+ * is established, then `'supports-unreliable'` because this transport always
1346
+ * offers both reliable streams and unreliable datagrams.
1347
+ */
1348
+ get reliability() {
1349
+ return this.core.isReady ? "supports-unreliable" : "pending";
1350
+ }
1351
+ /**
1352
+ * The negotiated WebTransport subprotocol, or the empty string when none was
1353
+ * negotiated (or before the session is established). Matches the W3C
1354
+ * `WebTransport.protocol` attribute.
1355
+ */
1356
+ get protocol() {
1357
+ return this.core.protocol;
1358
+ }
1140
1359
  /**
1141
1360
  * Open a new outbound bidirectional stream.
1142
1361
  *
@@ -1146,9 +1365,9 @@ var WebTransportSession = class {
1146
1365
  * @throws WebTransportError (the returned promise rejects) if the session is
1147
1366
  * already closed or was never attached.
1148
1367
  */
1149
- async createBidirectionalStream() {
1368
+ async createBidirectionalStream(options = {}) {
1150
1369
  const id = await this.core.openStream(true);
1151
- return new WebTransportBidirectionalStream(this.core, id);
1370
+ return new WebTransportBidirectionalStream(this.core, id, options);
1152
1371
  }
1153
1372
  /**
1154
1373
  * Open a new outbound unidirectional (send-only) stream.
@@ -1158,9 +1377,16 @@ var WebTransportSession = class {
1158
1377
  * @throws WebTransportError (the returned promise rejects) if the session is
1159
1378
  * already closed or was never attached.
1160
1379
  */
1161
- async createUnidirectionalStream() {
1380
+ async createUnidirectionalStream(options = {}) {
1162
1381
  const id = await this.core.openStream(false);
1163
- return new WebTransportSendStream(this.core, id);
1382
+ return new WebTransportSendStream(this.core, id, options);
1383
+ }
1384
+ /**
1385
+ * Create a {@link WebTransportSendGroup} for scheduling several streams'
1386
+ * sends relative to one another via each stream's `sendOrder`.
1387
+ */
1388
+ createSendGroup() {
1389
+ return new WebTransportSendGroup();
1164
1390
  }
1165
1391
  /**
1166
1392
  * Close the session gracefully, notifying the peer with an application code
@@ -1181,6 +1407,43 @@ var WebTransportSession = class {
1181
1407
  this.closeCalled = true;
1182
1408
  this.core.close(closeInfo.closeCode ?? 0, closeInfo.reason ?? "");
1183
1409
  }
1410
+ /**
1411
+ * Tell the peer this session is draining by sending a
1412
+ * `DRAIN_WEBTRANSPORT_SESSION` capsule: a graceful signal that you intend to
1413
+ * stop using it soon, while the session and its streams stay open until
1414
+ * {@link close}. The peer observes this through its {@link draining} promise.
1415
+ * A Node extension beyond the W3C API, useful for a server shedding load.
1416
+ */
1417
+ drain() {
1418
+ this.core.drain();
1419
+ }
1420
+ /**
1421
+ * Snapshot connection statistics (bytes and packets transferred, RTT, and
1422
+ * datagram counters).
1423
+ * @returns A promise resolving to {@link WebTransportConnectionStats}.
1424
+ * @throws WebTransportError (the promise rejects) if the session is closed.
1425
+ */
1426
+ getStats() {
1427
+ return this.core.getStats();
1428
+ }
1429
+ /**
1430
+ * Export keying material from the session's TLS connection (RFC 5705),
1431
+ * matching the W3C `exportKeyingMaterial`. Both endpoints derive identical
1432
+ * bytes for the same `label`, `context`, and `outputLength`, and nothing
1433
+ * outside the TLS session can reproduce them, which makes the result
1434
+ * suitable for channel binding.
1435
+ *
1436
+ * @param label - The exporter label, a {@link BinarySource}.
1437
+ * @param context - The exporter context, a {@link BinarySource}; pass an
1438
+ * empty buffer for no application context.
1439
+ * @param outputLength - Number of bytes of keying material to produce.
1440
+ * @returns A promise resolving to a `Uint8Array` of `outputLength` bytes.
1441
+ * @throws WebTransportError (the promise rejects) if the session is closed or
1442
+ * the TLS export fails (for example, before the handshake completes).
1443
+ */
1444
+ exportKeyingMaterial(label, context, outputLength) {
1445
+ return this.core.exportKeyingMaterial(toBytes(label), toBytes(context), outputLength);
1446
+ }
1184
1447
  };
1185
1448
  var WebTransport = class extends WebTransportSession {
1186
1449
  /**
@@ -1201,6 +1464,14 @@ var WebTransport = class extends WebTransportSession {
1201
1464
  constructor(url, options = {}) {
1202
1465
  super(createClientSession(buildConfig(url, options)));
1203
1466
  }
1467
+ /**
1468
+ * The headers from the server's Extended CONNECT `2xx` response, as a
1469
+ * `Headers` object (empty until the session is established). Matches the W3C
1470
+ * `WebTransport.responseHeaders` attribute.
1471
+ */
1472
+ get responseHeaders() {
1473
+ return new Headers(this.core.responseHeaders);
1474
+ }
1204
1475
  };
1205
1476
  function safeClose(controller) {
1206
1477
  try {
@@ -1234,6 +1505,8 @@ var WebTransportServerSession = class extends WebTransportSession {
1234
1505
  origin;
1235
1506
  /** Any additional (non-pseudo) request headers, keyed by header name. */
1236
1507
  headers;
1508
+ /** The subprotocols the client offered in `wt-available-protocols`. */
1509
+ requestedProtocols;
1237
1510
  /**
1238
1511
  * The client's remote IP address, as reported by the transport when the
1239
1512
  * session was established. The same for every stream and datagram on this
@@ -1258,6 +1531,7 @@ var WebTransportServerSession = class extends WebTransportSession {
1258
1531
  this.path = request.path;
1259
1532
  this.origin = request.origin;
1260
1533
  this.headers = request.headers;
1534
+ this.requestedProtocols = request.requestedProtocols;
1261
1535
  this.remoteAddress = request.remoteAddress;
1262
1536
  this.remotePort = request.remotePort;
1263
1537
  }
@@ -1312,12 +1586,22 @@ var WebTransportServer = class {
1312
1586
  this.incomingController = c;
1313
1587
  }
1314
1588
  });
1589
+ const responseHeaderNames = [];
1590
+ const responseHeaderValues = [];
1591
+ for (const [name, value] of Object.entries(options.responseHeaders ?? {})) {
1592
+ responseHeaderNames.push(name);
1593
+ responseHeaderValues.push(value);
1594
+ }
1315
1595
  this.handle = this.native.serverListen(
1316
1596
  options.cert,
1317
1597
  options.key,
1318
1598
  options.host ?? "0.0.0.0",
1319
1599
  options.port,
1320
1600
  options.reusePort ?? false,
1601
+ options.supportedProtocols ?? [],
1602
+ options.allowedOrigins ?? null,
1603
+ responseHeaderNames,
1604
+ responseHeaderValues,
1321
1605
  (ev) => this.onEvent(ev)
1322
1606
  );
1323
1607
  }
@@ -1399,6 +1683,8 @@ var WebTransportServer = class {
1399
1683
  path: ev.path,
1400
1684
  origin: ev.origin,
1401
1685
  headers: ev.headers,
1686
+ requestedProtocols: ev.requestedProtocols,
1687
+ protocol: ev.protocol,
1402
1688
  remoteAddress: ev.remoteAddress,
1403
1689
  remotePort: ev.remotePort
1404
1690
  });
@@ -1442,6 +1728,7 @@ export {
1442
1728
  WebTransportDatagramDuplexStream,
1443
1729
  WebTransportError,
1444
1730
  WebTransportReceiveStream,
1731
+ WebTransportSendGroup,
1445
1732
  WebTransportSendStream,
1446
1733
  WebTransportServer,
1447
1734
  WebTransportServerSession,