@floegence/flowersec-core 7.0.0 → 7.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.
Files changed (65) hide show
  1. package/README.md +6 -5
  2. package/THIRD_PARTY_NOTICES.md +8 -8
  3. package/dist/node/acceptorV3.js +9 -4
  4. package/dist/node/connectSessionV3.d.ts +2 -2
  5. package/dist/node/connectSessionV3.js +9 -3
  6. package/dist/node/connectionPath.js +49 -37
  7. package/dist/node/listenerIngress.d.ts +7 -0
  8. package/dist/node/listenerIngress.js +21 -0
  9. package/dist/node/nativeTransportAddon.d.ts +1 -5
  10. package/dist/node/nativeTransportAddon.js +3 -5
  11. package/dist/node/proxyServer.d.ts +1 -0
  12. package/dist/node/proxyServer.js +173 -78
  13. package/dist/node/proxyTarget.d.ts +1 -0
  14. package/dist/node/proxyTarget.js +13 -0
  15. package/dist/node/rawQuicAdapterV3.js +2 -2
  16. package/dist/node/rawQuicServerV3.d.ts +3 -1
  17. package/dist/node/rawQuicServerV3.js +18 -3
  18. package/dist/node/tunnelRuntimeV3.js +42 -8
  19. package/dist/node/webSocketServerV3.js +27 -2
  20. package/dist/proxy/bodyIntake.d.ts +13 -0
  21. package/dist/proxy/bodyIntake.js +55 -0
  22. package/dist/proxy/controllerGuard.d.ts +4 -0
  23. package/dist/proxy/controllerGuard.js +79 -37
  24. package/dist/proxy/fetch.d.ts +2 -1
  25. package/dist/proxy/fetch.js +55 -27
  26. package/dist/proxy/integration.d.ts +1 -1
  27. package/dist/proxy/integration.js +25 -5
  28. package/dist/proxy/registerServiceWorker.d.ts +5 -0
  29. package/dist/proxy/registerServiceWorker.js +30 -21
  30. package/dist/proxy/runtime.d.ts +7 -1
  31. package/dist/proxy/runtime.js +129 -39
  32. package/dist/proxy/scope.js +1 -1
  33. package/dist/proxy/serviceWorker.js +286 -43
  34. package/dist/proxy/serviceWorkerRuntime.d.ts +5 -2
  35. package/dist/proxy/serviceWorkerRuntime.js +58 -3
  36. package/dist/proxy/stream.d.ts +1 -0
  37. package/dist/proxy/stream.js +6 -3
  38. package/dist/proxy/types.d.ts +1 -1
  39. package/dist/proxy/windowBridge.d.ts +3 -1
  40. package/dist/proxy/windowBridge.js +64 -19
  41. package/dist/proxy/wsPatch.js +70 -52
  42. package/dist/public/sessionHandlers.js +3 -2
  43. package/dist/utils/abort.d.ts +1 -0
  44. package/dist/utils/abort.js +13 -0
  45. package/dist/v3/artifactLease.d.ts +6 -0
  46. package/dist/v3/artifactLease.js +6 -0
  47. package/dist/v3/contract.d.ts +1 -0
  48. package/dist/v3/nodeRuntime.js +10 -25
  49. package/dist/v3/publicSession.d.ts +2 -1
  50. package/dist/v3/publicSession.js +11 -15
  51. package/dist/v3/session.d.ts +7 -1
  52. package/dist/v3/session.js +110 -25
  53. package/dist/v3/unreliableMessage.d.ts +1 -0
  54. package/dist/v3/unreliableMessage.js +5 -1
  55. package/dist/v3/webSocketCarrier.js +24 -11
  56. package/dist/v3/webTransportCarrier.js +6 -0
  57. package/dist/vendor/tr46.js +17 -23
  58. package/dist/ws-client/binaryTransport.d.ts +2 -0
  59. package/dist/ws-client/binaryTransport.js +8 -2
  60. package/dist/yamux/byteReader.js +1 -0
  61. package/dist/yamux/session.d.ts +2 -0
  62. package/dist/yamux/session.js +4 -1
  63. package/package.json +12 -12
  64. package/sbom/cyclonedx.json +43 -43
  65. package/sbom/spdx.json +49 -49
@@ -93,6 +93,8 @@ export declare class SessionV3 implements SessionV3Contract {
93
93
  private controlReceiveKey;
94
94
  private controlWriteTail;
95
95
  private controlTerminalSealed;
96
+ private applicationWriteBytes;
97
+ private applicationWrites;
96
98
  private nextLogicalID;
97
99
  private receivedGoAway;
98
100
  private receivedGoAwayLastAccepted;
@@ -147,6 +149,7 @@ export declare class SessionV3 implements SessionV3Contract {
147
149
  private readonly rpcRouter;
148
150
  private readonly rpcServerOptions;
149
151
  constructor(carrier: CarrierSessionV3, control: CarrierStreamV3, controlReader: ExactReader, config: SessionConfigV3, material: HandshakeMaterial);
152
+ reserveWrite(bytes: number): () => void;
150
153
  private createRpcClient;
151
154
  openStream(kind: string, options?: InternalStreamOpenOptionsV3): Promise<ByteStreamV3>;
152
155
  acceptStream(options?: OperationOptionsV3): Promise<IncomingStreamV3>;
@@ -235,6 +238,8 @@ declare class EncryptedStreamV3 implements ByteStreamV3 {
235
238
  sendEpoch: number;
236
239
  receiveEpoch: number;
237
240
  private readonly permitRelease;
241
+ private resetController?;
242
+ get resetSignal(): AbortSignal;
238
243
  readonly reader: ExactReader;
239
244
  readonly opened: Readonly<{
240
245
  promise: Promise<void>;
@@ -250,7 +255,8 @@ declare class EncryptedStreamV3 implements ByteStreamV3 {
250
255
  epoch: number;
251
256
  sequence: bigint;
252
257
  }> | undefined;
253
- private sendTail;
258
+ private sendQueue;
259
+ private sending;
254
260
  private localFIN;
255
261
  private remoteFIN;
256
262
  private pumpStarted;
@@ -1,4 +1,5 @@
1
1
  import { RpcClient } from "../rpc/client.js";
2
+ import { SDK_DEFAULTS } from "../defaults.js";
2
3
  import { RpcRouter, RpcServer } from "../rpc/server.js";
3
4
  import { CarrierError } from "./carrier.js";
4
5
  import { FLOWERSEC_V3_PROFILE } from "./transportConstants.js";
@@ -9,6 +10,7 @@ import { UNRELIABLE_MESSAGES_FEATURE_V3, UNRELIABLE_MESSAGE_WIRE_BYTES_V3, creat
9
10
  const decoder = new TextDecoder();
10
11
  const MAX_DATA_BYTES = 16_384;
11
12
  const MAX_BUFFERED_STREAM_BYTES = 4 * 1024 * 1024;
13
+ const MAX_BUFFERED_STREAM_RECORDS = 4096;
12
14
  const RESERVED_RPC_KIND = "flowersec.rpc.v5";
13
15
  const DEFAULT_IDLE_TIMEOUT_MS = 60_000;
14
16
  const DEFAULT_CLOSE_TIMEOUT_MS = 2_000;
@@ -114,6 +116,8 @@ export class SessionV3 {
114
116
  controlReceiveKey;
115
117
  controlWriteTail = Promise.resolve();
116
118
  controlTerminalSealed = false;
119
+ applicationWriteBytes = 0;
120
+ applicationWrites = 0;
117
121
  nextLogicalID;
118
122
  receivedGoAway = false;
119
123
  receivedGoAwayLastAccepted = 0n;
@@ -203,6 +207,7 @@ export class SessionV3 {
203
207
  ? this.receiveRoots.get(epoch)?.epochSecret
204
208
  : undefined,
205
209
  onProtocolFailure: () => this.fail(protocolError("previous protocol unreliable frame")),
210
+ onActivity: () => this.markAuthenticatedActivity(),
206
211
  })
207
212
  : undefined;
208
213
  this.outboundPermits = new AsyncSemaphore(config.maxInboundStreams);
@@ -211,6 +216,14 @@ export class SessionV3 {
211
216
  this.rpcServerOptions = config.rpcServerOptions;
212
217
  this.rpc = new SessionRpcPeerV3(this.createRpcClient.bind(this), this.rpcRouter);
213
218
  }
219
+ reserveWrite(bytes) {
220
+ if (this.applicationWrites >= 256 || this.applicationWriteBytes + bytes > SDK_DEFAULTS.e2ee.maxOutboundBufferedBytes) {
221
+ throw new SessionV3Error("resource_exhausted", "session write budget exceeded");
222
+ }
223
+ this.applicationWrites++;
224
+ this.applicationWriteBytes += bytes;
225
+ return () => { this.applicationWrites--; this.applicationWriteBytes -= bytes; };
226
+ }
214
227
  createRpcClient() {
215
228
  let opened;
216
229
  let reader;
@@ -234,8 +247,9 @@ export class SessionV3 {
234
247
  this.pings.set(nonce, pending);
235
248
  const started = this.runtime.monotonicMilliseconds();
236
249
  try {
237
- await this.sendControl(InnerTypeV3.Ping, u64(nonce), options.signal);
238
- await raceAbort(pending.promise, options.signal);
250
+ await raceAbort(Promise.all([
251
+ this.sendControl(InnerTypeV3.Ping, u64(nonce), options.signal), pending.promise,
252
+ ]), options.signal);
239
253
  return Math.max(0, this.runtime.monotonicMilliseconds() - started);
240
254
  }
241
255
  finally {
@@ -369,6 +383,7 @@ export class SessionV3 {
369
383
  releaseStream(stream) {
370
384
  stream.wipeRecordMaterials();
371
385
  if (stream.terminalError !== undefined) {
386
+ this.incoming.remove(stream.id);
372
387
  this.releasedStreams.delete(stream.id);
373
388
  this.releasedStreamCleanup.unregister(stream);
374
389
  }
@@ -389,8 +404,11 @@ export class SessionV3 {
389
404
  const pending = deferred();
390
405
  this.pings.set(nonce, pending);
391
406
  try {
392
- await this.sendControl(InnerTypeV3.Ping, u64(nonce));
393
- return await resolveWithin(pending.promise, DEFAULT_CONTROL_CONFIRM_TIMEOUT_MS);
407
+ const [, confirmed] = await Promise.all([
408
+ this.sendControl(InnerTypeV3.Ping, u64(nonce)),
409
+ resolveWithin(pending.promise, DEFAULT_CONTROL_CONFIRM_TIMEOUT_MS),
410
+ ]);
411
+ return confirmed;
394
412
  }
395
413
  finally {
396
414
  this.pings.delete(nonce);
@@ -608,6 +626,8 @@ export class SessionV3 {
608
626
  }));
609
627
  return;
610
628
  }
629
+ if (stream.terminalError !== undefined)
630
+ return;
611
631
  this.incoming.push({
612
632
  id: stream.id,
613
633
  kind: stream.kind,
@@ -644,7 +664,14 @@ export class SessionV3 {
644
664
  const task = this.controlWriteTail.then(async () => {
645
665
  if (this.lifecycle === "closed")
646
666
  throw this.terminalError ?? new SessionV3Error("closed", "Flowersec v5 session closed");
647
- await this.writeControl(type, payload, signal);
667
+ throwIfAborted(signal);
668
+ try {
669
+ await this.writeControl(type, payload);
670
+ }
671
+ catch (error) {
672
+ this.fail(asError(error));
673
+ throw error;
674
+ }
648
675
  });
649
676
  this.controlWriteTail = task.catch(() => undefined);
650
677
  if (signal === undefined)
@@ -701,11 +728,11 @@ export class SessionV3 {
701
728
  this.controlWriteTail = task.catch(() => undefined);
702
729
  return task;
703
730
  }
704
- async writeControl(type, payload, signal) {
731
+ async writeControl(type, payload) {
705
732
  const material = this.controlSendKey ??= deriveControlRecordKey(this.rootForSend(this.controlSendEpoch), this.h3, this.sendDirection, this.controlSendEpoch);
706
733
  const wire = sealRecordWireV3Internal(this.suite, material, this.h3, 0n, this.sendDirection, this.controlSendEpoch, this.controlSendSequence, type, payload);
707
734
  this.controlSendSequence += 1n;
708
- await writeAll(this.control, wire, signal);
735
+ await writeAll(this.control, wire);
709
736
  this.markAuthenticatedActivity();
710
737
  }
711
738
  async readControl() {
@@ -766,6 +793,7 @@ export class SessionV3 {
766
793
  if (releasedStream !== undefined) {
767
794
  this.releasedStreamCleanup.unregister(releasedStream);
768
795
  releasedStream.markTerminal(new SessionV3Error("stream_reset", "logical stream reset by peer"));
796
+ this.incoming.remove(id);
769
797
  }
770
798
  }
771
799
  }
@@ -909,6 +937,10 @@ export class SessionV3 {
909
937
  // Do not consume a transition id until preparation has completed and
910
938
  // the caller has not cancelled the operation.
911
939
  throwIfAborted(prepareSignal.signal);
940
+ const active = [...this.streams.values()].filter((stream) => stream.canRekeySend());
941
+ if (active.some((stream) => stream.hasRemoteFIN())) {
942
+ throw new SessionV3Error("resource_exhausted", "stream acknowledgement direction has finished");
943
+ }
912
944
  prepareSignal.cancel();
913
945
  prepareDeadline.cancel();
914
946
  completionDeadline = createSessionDeadline(this.deadlines, "rekey_completion");
@@ -921,7 +953,6 @@ export class SessionV3 {
921
953
  const transition = this.nextTransition;
922
954
  this.nextTransition = transition === MAX_UINT64 ? 0n : transition + 1n;
923
955
  const payload = concat(u64(transition), u32(nextEpoch), u64(watermark));
924
- const active = [...this.streams.values()].filter((stream) => stream.canRekeySend());
925
956
  const updates = active.map((stream) => stream.startSendRekey(transition, nextEpoch));
926
957
  await Promise.all(updates.map(async (update) => await raceAbort(update.armed.promise, completionSignal.signal)));
927
958
  const pending = {
@@ -1329,6 +1360,13 @@ class EncryptedStreamV3 {
1329
1360
  sendEpoch;
1330
1361
  receiveEpoch;
1331
1362
  permitRelease;
1363
+ resetController;
1364
+ get resetSignal() {
1365
+ this.resetController ??= new AbortController();
1366
+ if (this.terminalError !== undefined)
1367
+ this.resetController.abort(this.terminalError);
1368
+ return this.resetController.signal;
1369
+ }
1332
1370
  reader;
1333
1371
  opened = deferred();
1334
1372
  data = new ByteQueue(MAX_BUFFERED_STREAM_BYTES);
@@ -1336,7 +1374,8 @@ class EncryptedStreamV3 {
1336
1374
  sendSequence = 0n;
1337
1375
  receiveSequence = 0n;
1338
1376
  priorACK;
1339
- sendTail = Promise.resolve();
1377
+ sendQueue;
1378
+ sending = false;
1340
1379
  localFIN = false;
1341
1380
  remoteFIN = false;
1342
1381
  pumpStarted = false;
@@ -1368,7 +1407,16 @@ class EncryptedStreamV3 {
1368
1407
  if (!(payload instanceof Uint8Array))
1369
1408
  throw new TypeError("stream write requires Uint8Array");
1370
1409
  throwIfAborted(options.signal);
1371
- return await this.writeBytes(new Uint8Array(payload), options.signal, false);
1410
+ if (this.terminalError !== undefined)
1411
+ throw this.terminalError;
1412
+ const size = Math.min(payload.length, SDK_DEFAULTS.e2ee.maxOutboundBufferedBytes);
1413
+ const release = this.session.reserveWrite(size);
1414
+ try {
1415
+ return await this.writeBytes(new Uint8Array(payload.subarray(0, size)), options.signal, false);
1416
+ }
1417
+ finally {
1418
+ release();
1419
+ }
1372
1420
  }
1373
1421
  /** The frame encoder owns these bytes until the sequenced write completes. */
1374
1422
  async writeRpcFrame(payload, signal) {
@@ -1400,7 +1448,7 @@ class EncryptedStreamV3 {
1400
1448
  void this.session.localReset(this, normalized);
1401
1449
  throw normalized;
1402
1450
  }
1403
- });
1451
+ }, signal, false);
1404
1452
  return payload.length;
1405
1453
  }
1406
1454
  async closeWrite() {
@@ -1432,6 +1480,8 @@ class EncryptedStreamV3 {
1432
1480
  await this.session.localReset(this, new SessionV3Error("stream_reset", "logical stream reset"));
1433
1481
  }
1434
1482
  async close() {
1483
+ if (this.localFIN && this.remoteFIN)
1484
+ return;
1435
1485
  await this.reset();
1436
1486
  }
1437
1487
  send(type, payload, signal) {
@@ -1498,6 +1548,7 @@ class EncryptedStreamV3 {
1498
1548
  if (this.terminalError !== undefined)
1499
1549
  return false;
1500
1550
  this.terminalError = error;
1551
+ this.resetController?.abort(error);
1501
1552
  this.pendingFIN?.abort(error);
1502
1553
  const pendingSendRekey = this.pendingSendRekey;
1503
1554
  this.pendingSendRekey = undefined;
@@ -1628,15 +1679,42 @@ class EncryptedStreamV3 {
1628
1679
  setOpenHash(value) {
1629
1680
  this.openHash = value.slice();
1630
1681
  }
1631
- enqueueSend(operation, signal) {
1632
- const queued = this.sendTail.then(async () => {
1633
- if (this.terminalError !== undefined)
1634
- throw this.terminalError;
1635
- await operation();
1682
+ enqueueSend(operation, signal, interruptActive = true) {
1683
+ if (signal?.aborted)
1684
+ return Promise.reject(abortReason(signal));
1685
+ return new Promise((resolve, reject) => {
1686
+ const queue = this.sendQueue ??= new Set();
1687
+ const abort = () => { if (queue.delete(run))
1688
+ reject(abortReason(signal)); };
1689
+ const run = async () => {
1690
+ signal?.removeEventListener("abort", abort);
1691
+ try {
1692
+ if (this.terminalError !== undefined)
1693
+ throw this.terminalError;
1694
+ if (signal && interruptActive)
1695
+ await raceAbort(operation(), signal);
1696
+ else
1697
+ await operation();
1698
+ resolve();
1699
+ }
1700
+ catch (error) {
1701
+ reject(error);
1702
+ }
1703
+ };
1704
+ queue.add(run);
1705
+ signal?.addEventListener("abort", abort, { once: true });
1706
+ if (this.sending)
1707
+ return;
1708
+ this.sending = true;
1709
+ void Promise.resolve().then(async () => {
1710
+ for (const next of queue) {
1711
+ queue.delete(next);
1712
+ await next();
1713
+ }
1714
+ this.sending = false;
1715
+ this.sendQueue = undefined;
1716
+ });
1636
1717
  });
1637
- const task = signal === undefined ? queued : raceAbort(queued, signal);
1638
- this.sendTail = task.catch(() => undefined);
1639
- return task;
1640
1718
  }
1641
1719
  async waitSendRekey(signal) {
1642
1720
  while (this.pendingSendRekey !== undefined) {
@@ -1894,7 +1972,7 @@ class ByteQueue {
1894
1972
  if (!Number.isInteger(required) || required < 0 || required > this.limit) {
1895
1973
  throw new RangeError("invalid stream receive capacity request");
1896
1974
  }
1897
- while (this.bytes + required > this.limit) {
1975
+ while (this.bytes + required > this.limit || this.chunks.length - this.head >= MAX_BUFFERED_STREAM_RECORDS) {
1898
1976
  if (this.error !== undefined)
1899
1977
  throw this.error;
1900
1978
  if (this.closed)
@@ -1911,6 +1989,7 @@ class ByteQueue {
1911
1989
  }
1912
1990
  async read(signal) {
1913
1991
  while (true) {
1992
+ throwIfAborted(signal);
1914
1993
  if (this.error !== undefined)
1915
1994
  throw this.error;
1916
1995
  if (this.head < this.chunks.length) {
@@ -2021,7 +2100,7 @@ class AsyncSemaphore {
2021
2100
  }
2022
2101
  }
2023
2102
  class AsyncQueue {
2024
- values = [];
2103
+ values = new Map();
2025
2104
  waiters = new Set();
2026
2105
  error;
2027
2106
  push(value) {
@@ -2029,14 +2108,20 @@ class AsyncQueue {
2029
2108
  return;
2030
2109
  const waiter = this.waiters.values().next().value;
2031
2110
  if (waiter === undefined || !waiter.deliver(value))
2032
- this.values.push(value);
2111
+ this.values.set(value.id, value);
2112
+ }
2113
+ remove(id) {
2114
+ this.values.delete(id);
2033
2115
  }
2034
2116
  async shift(signal) {
2117
+ throwIfAborted(signal);
2035
2118
  if (this.error !== undefined)
2036
2119
  throw this.error;
2037
- const value = this.values.shift();
2038
- if (value !== undefined)
2120
+ const value = this.values.values().next().value;
2121
+ if (value !== undefined) {
2122
+ this.values.delete(value.id);
2039
2123
  return value;
2124
+ }
2040
2125
  return await new Promise((resolve, reject) => {
2041
2126
  let settled = false;
2042
2127
  const cleanup = () => {
@@ -2069,7 +2154,7 @@ class AsyncQueue {
2069
2154
  }
2070
2155
  fail(error) {
2071
2156
  this.error = error;
2072
- this.values.length = 0;
2157
+ this.values.clear();
2073
2158
  for (const waiter of [...this.waiters])
2074
2159
  waiter.fail(error);
2075
2160
  }
@@ -16,6 +16,7 @@ export type InternalUnreliableMessageChannelV3Options = Readonly<{
16
16
  }>;
17
17
  receiveEpochSecret(epoch: number): Uint8Array | undefined;
18
18
  onProtocolFailure(): void;
19
+ onActivity?(): void;
19
20
  now?: () => number;
20
21
  }>;
21
22
  export type UnreliableMessageMaterialV3 = Readonly<{
@@ -70,10 +70,13 @@ class InternalUnreliableMessageChannelV3 {
70
70
  });
71
71
  this.pendingSends++;
72
72
  try {
73
- return await this.options.transport.send(sealed.wire, {
73
+ const result = await this.options.transport.send(sealed.wire, {
74
74
  ...(options.signal === undefined ? {} : { signal: options.signal }),
75
75
  expiresAt,
76
76
  });
77
+ if (result === "accepted")
78
+ this.options.onActivity?.();
79
+ return result;
77
80
  }
78
81
  catch (error) {
79
82
  if (isAbortError(error))
@@ -124,6 +127,7 @@ class InternalUnreliableMessageChannelV3 {
124
127
  window.mark(decoded.sequence);
125
128
  this.replay.set(decoded.epoch, window);
126
129
  pruneReplayEpochs(this.replay, decoded.epoch);
130
+ this.options.onActivity?.();
127
131
  return plaintext.slice();
128
132
  }
129
133
  }
@@ -143,7 +143,7 @@ class WebSocketYamuxCarrierSession {
143
143
  path;
144
144
  inboundBidirectionalStreamCapacity;
145
145
  unreliableDatagrams = undefined;
146
- incoming = new IncomingStreamQueue();
146
+ incoming;
147
147
  yamux;
148
148
  termination = deferred();
149
149
  terminalError;
@@ -159,6 +159,7 @@ class WebSocketYamuxCarrierSession {
159
159
  close: () => transport.close(),
160
160
  };
161
161
  const policy = options.resourcePolicy ?? {};
162
+ this.incoming = new IncomingStreamQueue(this.inboundBidirectionalStreamCapacity);
162
163
  this.yamux = new YamuxSession(duplex, {
163
164
  client: options.client,
164
165
  limits: {
@@ -170,7 +171,8 @@ class WebSocketYamuxCarrierSession {
170
171
  ...(policy.maxStreamReceiveBytes === undefined ? {} : { maxStreamReceiveBytes: policy.maxStreamReceiveBytes }),
171
172
  ...(policy.maxSessionReceiveBytes === undefined ? {} : { maxSessionReceiveBytes: policy.maxSessionReceiveBytes }),
172
173
  },
173
- onIncomingStream: (stream) => this.incoming.push(new YamuxCarrierStreamAdapter(stream)),
174
+ onIncomingStream: (stream) => this.incoming.push(stream.id, new YamuxCarrierStreamAdapter(stream)),
175
+ onIncomingStreamClosed: (id) => this.incoming.remove(id),
174
176
  onTerminal: (error) => {
175
177
  const failure = error instanceof CarrierError
176
178
  ? error
@@ -269,17 +271,26 @@ class YamuxCarrierStreamAdapter {
269
271
  }
270
272
  }
271
273
  class IncomingStreamQueue {
272
- values = [];
274
+ capacity;
275
+ values = new Map();
273
276
  waiters = new Set();
274
277
  terminalError;
275
- push(value) {
278
+ constructor(capacity) {
279
+ this.capacity = capacity;
280
+ }
281
+ remove(id) { this.values.delete(id); }
282
+ push(id, value) {
276
283
  if (this.terminalError !== undefined) {
277
284
  value.abort(this.terminalError);
278
285
  return;
279
286
  }
280
287
  const waiter = this.waiters.values().next().value;
281
- if (waiter === undefined)
282
- this.values.push(value);
288
+ if (waiter === undefined) {
289
+ if (this.values.size < this.capacity)
290
+ this.values.set(id, value);
291
+ else
292
+ void value.reset().catch(() => undefined);
293
+ }
283
294
  else {
284
295
  this.waiters.delete(waiter);
285
296
  waiter.deliver(value);
@@ -289,9 +300,11 @@ class IncomingStreamQueue {
289
300
  throwIfAborted(signal);
290
301
  if (this.terminalError !== undefined)
291
302
  return Promise.reject(this.terminalError);
292
- const value = this.values.shift();
293
- if (value !== undefined)
294
- return Promise.resolve(value);
303
+ const next = this.values.entries().next();
304
+ if (!next.done) {
305
+ this.values.delete(next.value[0]);
306
+ return Promise.resolve(next.value[1]);
307
+ }
295
308
  return new Promise((resolve, reject) => {
296
309
  let settled = false;
297
310
  const cleanup = () => {
@@ -325,9 +338,9 @@ class IncomingStreamQueue {
325
338
  if (this.terminalError !== undefined)
326
339
  return;
327
340
  this.terminalError = error;
328
- for (const stream of this.values)
341
+ for (const stream of this.values.values())
329
342
  stream.abort(error);
330
- this.values.length = 0;
343
+ this.values.clear();
331
344
  for (const waiter of this.waiters)
332
345
  waiter.fail(error);
333
346
  this.waiters.clear();
@@ -202,6 +202,12 @@ class WebTransportCarrierStreamAdapter {
202
202
  this.onRelease = onRelease;
203
203
  this.reader = stream.readable.getReader();
204
204
  this.writer = stream.writable.getWriter();
205
+ void this.reader.closed.then(() => {
206
+ if (this.readClosed)
207
+ return;
208
+ this.readClosed = true;
209
+ this.releaseIfComplete();
210
+ }, error => this.abort(new CarrierError("reset", "WebTransport stream read failed", error)));
205
211
  }
206
212
  async read(_options = {}) {
207
213
  this.assertReadable();