@browsercore/quic 0.1.3 → 0.1.4

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 (49) hide show
  1. package/README.md +122 -0
  2. package/dist/connection.d.ts +13 -13
  3. package/dist/connection.d.ts.map +1 -1
  4. package/dist/connection.js +119 -73
  5. package/dist/connection.js.map +1 -1
  6. package/dist/errors.d.ts.map +1 -1
  7. package/dist/errors.js.map +1 -1
  8. package/dist/frame/frame.d.ts +1 -2
  9. package/dist/frame/frame.d.ts.map +1 -1
  10. package/dist/frame/frame.js +19 -8
  11. package/dist/frame/frame.js.map +1 -1
  12. package/dist/frame/varint.d.ts +10 -0
  13. package/dist/frame/varint.d.ts.map +1 -1
  14. package/dist/frame/varint.js +38 -14
  15. package/dist/frame/varint.js.map +1 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/packet/packet.d.ts +1 -2
  21. package/dist/packet/packet.d.ts.map +1 -1
  22. package/dist/packet/packet.js +19 -4
  23. package/dist/packet/packet.js.map +1 -1
  24. package/dist/stream/stream.d.ts +1 -1
  25. package/dist/stream/stream.d.ts.map +1 -1
  26. package/dist/stream/stream.js +124 -84
  27. package/dist/stream/stream.js.map +1 -1
  28. package/dist/types.d.ts.map +1 -1
  29. package/dist/utils.d.ts.map +1 -1
  30. package/dist/utils.js +2 -1
  31. package/dist/utils.js.map +1 -1
  32. package/package.json +22 -9
  33. package/.github/workflows/ci.yml +0 -17
  34. package/.github/workflows/publish.yml +0 -49
  35. package/CODING_STANDARDS.md +0 -205
  36. package/src/connection.ts +0 -374
  37. package/src/errors.ts +0 -153
  38. package/src/frame/frame.ts +0 -423
  39. package/src/frame/varint.ts +0 -124
  40. package/src/index.ts +0 -70
  41. package/src/packet/packet.ts +0 -210
  42. package/src/stream/stream.ts +0 -746
  43. package/src/types.ts +0 -441
  44. package/src/utils.ts +0 -38
  45. package/tests/connection.test.ts +0 -106
  46. package/tests/fake-transport.ts +0 -107
  47. package/tests/stream.test.ts +0 -152
  48. package/tests/wire.test.ts +0 -342
  49. package/tsconfig.json +0 -30
@@ -1,17 +0,0 @@
1
- name: CI
2
- on:
3
- push:
4
- branches: [main]
5
- pull_request:
6
- branches: [main]
7
- jobs:
8
- build-and-test:
9
- runs-on: ubuntu-latest
10
- steps:
11
- - uses: actions/checkout@v4
12
- - uses: actions/setup-node@v4
13
- with:
14
- node-version: 24
15
- - run: npm install
16
- - run: npm test
17
- - run: npm run build
@@ -1,49 +0,0 @@
1
- name: Publish
2
- on:
3
- push:
4
- branches: [main]
5
- jobs:
6
- publish:
7
- runs-on: ubuntu-latest
8
- permissions:
9
- contents: write
10
- id-token: write
11
- steps:
12
- - uses: actions/checkout@v4
13
- with:
14
- fetch-depth: 0
15
- fetch-tags: true
16
- token: ${{ secrets.GITHUB_TOKEN }}
17
- - uses: actions/setup-node@v4
18
- with:
19
- node-version: 24
20
- registry-url: https://registry.npmjs.org
21
- - run: npm install
22
- - run: npm run build
23
- - run: npm test
24
- - name: Publish to npm if version is new
25
- run: |
26
- VERSION=$(node -p "require('./package.json').version")
27
- NAME=$(node -p "require('./package.json').name")
28
- if npm view "$NAME@$VERSION" version >/dev/null 2>&1; then
29
- echo "$NAME@$VERSION already on npm — skipping publish"
30
- else
31
- npm publish --access public
32
- fi
33
- env:
34
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
35
- - name: Create git tag and GitHub Release
36
- env:
37
- GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
38
- run: |
39
- VERSION=$(node -p "require('./package.json').version")
40
- TAG="v$VERSION"
41
- if git rev-parse "$TAG" >/dev/null 2>&1; then
42
- echo "tag $TAG already exists — skipping release"
43
- exit 0
44
- fi
45
- git config user.name "github-actions[bot]"
46
- git config user.email "github-actions[bot]@users.noreply.github.com"
47
- git tag "$TAG"
48
- git push origin "$TAG"
49
- gh release create "$TAG" --title "$TAG" --generate-notes
@@ -1,205 +0,0 @@
1
- # TypeScript Coding Standards
2
-
3
- These rules are the standard for this codebase and **every** sub-package. Every PR,
4
- every AI-generated snippet, and every hand-written file follows them. They exist so
5
- the intended behavior lives in the types — never in tribal knowledge or hidden assumptions.
6
-
7
- > Design for AI modification: before committing, ask *"Could another developer or an
8
- > LLM understand the intended behavior without asking me?"* If not — add types, split
9
- > functions, clarify states, rename.
10
-
11
- ---
12
-
13
- ## 1. Strict compiler — never relax it
14
-
15
- Every `tsconfig.json` inherits `tsconfig.base.json`, which carries:
16
-
17
- ```json
18
- {
19
- "strict": true,
20
- "noUncheckedIndexedAccess": true,
21
- "exactOptionalPropertyTypes": true
22
- }
23
- ```
24
-
25
- - `noUncheckedIndexedAccess` → `arr[i]` is `T | undefined`.
26
- - `exactOptionalPropertyTypes` → `?` means absent-or-present, not present-and-undefined.
27
-
28
- Ambiguity creates bugs and forces LLMs to guess. **Never** override these to `false`
29
- in a sub-package to dodge an error. Fix the error instead.
30
-
31
- ## 2. Every important data structure has a type
32
-
33
- If data crosses a module boundary, it has an explicit type. No anonymous object
34
- literals escaping a function.
35
-
36
- ```ts
37
- // Bad
38
- const frame = { type: 0x1, streamId: 3, data: buf };
39
-
40
- // Good
41
- interface HeadersFrame {
42
- readonly type: FrameType.HEADERS;
43
- readonly streamId: StreamId;
44
- readonly data: Uint8Array;
45
- }
46
- ```
47
-
48
- ## 3. Never `any`
49
-
50
- Unknown external data is `unknown`, then validated. `any` is a build failure.
51
-
52
- ```ts
53
- function parseFrame(raw: Uint8Array): Frame {
54
- const unknown = decodeUnknown(raw); // unknown
55
- return FrameSchema.parse(unknown); // validated → typed
56
- }
57
- ```
58
-
59
- ## 4. Interfaces for domain objects, type aliases for states/constraints
60
-
61
- - Interfaces for real entities (`TlsConnection`, `Http2Stream`, `Cookie`).
62
- - Type aliases for states/constraints (`RunStatus`, `CipherSuite`).
63
- - If values come from a known set, encode the set — never bare `string`.
64
-
65
- ## 5. Model states explicitly — make invalid states unrepresentable
66
-
67
- No "state via nullable-field combos." Use discriminated unions.
68
-
69
- ```ts
70
- // Bad — allows { state: "open", error: "failed" }
71
- interface Connection {
72
- state: string;
73
- stream?: Stream;
74
- error?: string;
75
- }
76
-
77
- // Good
78
- type ConnectionState =
79
- | { readonly state: "connecting" }
80
- | { readonly state: "open"; readonly stream: Stream }
81
- | { readonly state: "closed"; readonly reason: CloseReason };
82
- ```
83
-
84
- ## 6. Discriminated unions for every workflow/state
85
-
86
- The compiler + LLM reason about every case.
87
-
88
- ## 7. Functions declare input AND output types
89
-
90
- Public functions always define both sides — no inference-only signatures on exported APIs.
91
-
92
- ## 8. One function = one decision
93
-
94
- No `processHandshake()` that validates + persists + schedules + notifies. Split:
95
- `validate…`, `decodeStep`, `actuate`, `recordStep`.
96
-
97
- ## 9. No hidden behavior
98
-
99
- A function named `updateSettings` does not also flush a log. Every side effect is its
100
- own named call.
101
-
102
- ## 10. Name things explicitly
103
-
104
- `cipherSuite`, `observedRank`, `clientHello` — never `data`, `result`, `obj`.
105
- The name is the documentation.
106
-
107
- ## 11. Prefer immutable data + `readonly`
108
-
109
- ```ts
110
- const next = { ...prev, cipherSuite } as const;
111
- interface Connection { readonly id: ConnectionId; }
112
- ```
113
-
114
- No in-place mutation of shared state. `const` over `let`.
115
-
116
- ## 12. Validate external data immediately
117
-
118
- Everything from outside the boundary is `unknown`: sockets, files, captures, configs.
119
- Use **Zod** at every boundary:
120
-
121
- ```ts
122
- const frame = FrameSchema.parse(raw); // never `raw as Frame`
123
- ```
124
-
125
- ## 13. Types are contracts, not documentation
126
-
127
- ```ts
128
- // Bad // user id
129
- // id: string;
130
- // Good
131
- type UserId = string & { __brand: "UserId" };
132
- ```
133
-
134
- ## 14. Branded/opaque ID types — load-bearing
135
-
136
- Don't use bare `number`/`string` for IDs. This kills the "pass an X where a Y belongs"
137
- class of bug. The project uses these brands (defined per-package, see `types.ts`):
138
-
139
- ```ts
140
- type ConnectionId = string & { __brand: "ConnectionId" };
141
- type StreamId = number & { __brand: "StreamId" };
142
- type SessionId = string & { __brand: "SessionId" };
143
- ```
144
-
145
- ## 15. Exhaustive switches
146
-
147
- Every `switch` over a union hits `default: assertNever(x)`. Adding a state forces every
148
- handler to compile-error until handled.
149
-
150
- ```ts
151
- function assertNever(x: never): never {
152
- throw new Error(`Unexpected value: ${JSON.stringify(x)}`);
153
- }
154
- ```
155
-
156
- ## 16. Explicit, typed errors
157
-
158
- ```ts
159
- // Bad
160
- throw new Error("handshake failed");
161
- // Good
162
- throw new TlsHandshakeError("server_hello_parse", cause);
163
- ```
164
-
165
- Errors are part of the API. Define them in each package's `errors.ts`.
166
-
167
- ## 17. No magic strings
168
-
169
- `if (event === Event.COLD_START)` or a string-literal union — never bare `"cold_start"`.
170
-
171
- ## 18. Clear dependency boundaries
172
-
173
- Domain (pure protocol logic) knows nothing of AWS / HTTP / DDB / sockets. Infrastructure
174
- adapts. The protocol state machines stay I/O-free so they're unit-testable.
175
-
176
- **Within this repo**, the dependency graph flows upward only — never sideways or downward:
177
-
178
- ```
179
- @browsercore/fetch
180
- └─ @browsercore/http2 @browsercore/http1 @browsercore/cookies @browsercore/profiles
181
- └─ @browsercore/tls
182
- └─ @browsercore/crypto @browsercore/transport
183
- └─ node:net / node:crypto
184
- ```
185
-
186
- A package may only import from packages *below* it in this graph.
187
-
188
- ## 19. Documentation: why, not what
189
-
190
- Comments explain *why* ("crawl past our position so the competitor snapshot covers the
191
- neighborhood"), never *what* the code obviously does. Priority: Types > Names > Structure >
192
- Comments.
193
-
194
- ## 20. API contracts in one place
195
-
196
- Domain types live in each package's `types.ts`; wire schemas in `schemas.ts`. One source
197
- of truth, never duplicated shapes.
198
-
199
- ---
200
-
201
- ## The Golden Rule
202
-
203
- Every piece of important information exists as one of: **a type, a function signature,
204
- an explicit state model, a schema validation, or clear naming.** Never rely on tribal
205
- knowledge or hidden assumptions.
package/src/connection.ts DELETED
@@ -1,374 +0,0 @@
1
- /**
2
- * QUIC connection lifecycle + datagram read loop (RFC 9000 §5, §12).
3
- *
4
- * Wires packet header parsing/serialization, the frame layer, and the stream
5
- * manager over an injected {@link DatagramTransport} (UDP). The connection owns
6
- * the read loop: it turns inbound datagrams into frames, dispatches each to the
7
- * stream manager, and drains pending stream sends back into outbound packets.
8
- *
9
- * Honest limitations:
10
- * - The TLS 1.3 handshake and packet protection (header protection + AEAD
11
- * payload encryption) are out of scope. `connectQuic()` returns a connection
12
- * that moves *unprotected* frames over the transport directly — enough to
13
- * drive the data plane and to be tested with a fake datagram transport. A
14
- * production build layers protection + the handshake on top of this.
15
- * - No congestion controller, no connection migration, no PATH_CHALLENGE /
16
- * PATH_RESPONSE beyond frame relay, and no liveness PING.
17
- *
18
- * Concurrency model: the read loop is a single async task pulling datagrams from
19
- * the transport. Outbound frames are produced synchronously by the stream
20
- * manager and packed into packets; writes resolve once bytes are buffered.
21
- */
22
-
23
- import type { EventEmitter } from "node:events";
24
- import type {
25
- ConnectionId,
26
- QuicConnection,
27
- QuicFrame,
28
- QuicOptions,
29
- QuicStream,
30
- QuicTransportParameters,
31
- UdpAddress,
32
- } from "./types.js";
33
- import { QuicFrameType } from "./types.js";
34
- import { parsePacketHeader, serializeShortHeader } from "./packet/packet.js";
35
- import type { PacketHeader } from "./packet/packet.js";
36
- import { readFrames, serializeFrame } from "./frame/frame.js";
37
- import { ConnectionClosedError } from "./errors.js";
38
- import { createStreamManager, type StreamManager } from "./stream/stream.js";
39
- import { concatAll } from "./utils.js";
40
-
41
- /** Byte type alias matching the `Uint8Array<ArrayBufferLike>` wire signatures. */
42
- type Bytes = Uint8Array<ArrayBufferLike>;
43
-
44
- /** Largest UDP payload we will pack into a single datagram (RFC 9000 §14). */
45
- const MAX_DATAGRAM_PAYLOAD = 1200;
46
-
47
- /**
48
- * Concrete QUIC connection. The public surface matches the fixed
49
- * `QuicConnection` interface; internal state is kept on the instance.
50
- */
51
- export class QuicConnectionImpl implements QuicConnection {
52
- public readonly id: string;
53
-
54
- /** The underlying datagram (UDP) transport. */
55
- private readonly transport: QuicOptions["transport"];
56
- /** The peer's UDP address. */
57
- private readonly peer: UdpAddress;
58
- /** Stream manager (also an EventEmitter for connection-level signals). */
59
- private readonly manager: StreamManager & EventEmitter;
60
- /** Our current destination connection id (the one we put on outbound packets). */
61
- private readonly dcid: ConnectionId;
62
-
63
- /** Set once the connection begins graceful shutdown. */
64
- private closing = false;
65
- /** Set once the connection is fully torn down. */
66
- private closed = false;
67
- /** Buffered outbound frames waiting to be packed into the next packet. */
68
- private readonly outboundFrames: QuicFrame[] = [];
69
-
70
- public constructor(
71
- id: string,
72
- options: QuicOptions,
73
- manager: StreamManager & EventEmitter,
74
- dcid: ConnectionId,
75
- ) {
76
- this.id = id;
77
- this.transport = options.transport;
78
- this.peer = options.peer;
79
- this.manager = manager;
80
- this.dcid = dcid;
81
- }
82
-
83
- // --- public QuicConnection surface ------------------------------------------
84
-
85
- public async openBidirectionalStream(): Promise<QuicStream> {
86
- this._ensureOpen();
87
- return this.manager.openStream(true);
88
- }
89
-
90
- public async acceptBidirectionalStream(): Promise<QuicStream> {
91
- this._ensureOpen();
92
- return this.manager.acceptStream(true);
93
- }
94
-
95
- public async openUnidirectionalStream(): Promise<QuicStream> {
96
- this._ensureOpen();
97
- return this.manager.openStream(false);
98
- }
99
-
100
- public async acceptUnidirectionalStream(): Promise<QuicStream> {
101
- this._ensureOpen();
102
- return this.manager.acceptStream(false);
103
- }
104
-
105
- public async close(errorCode: bigint, reason: string): Promise<void> {
106
- if (this.closed) return;
107
- this.closing = true;
108
- this.manager.close(errorCode, reason);
109
- // Pack + flush the CONNECTION_CLOSE frame, then tear down.
110
- await this._flush();
111
- await this._teardown({ kind: "client_close" });
112
- }
113
-
114
- // --- frame I/O -------------------------------------------------------------
115
-
116
- /**
117
- * Enqueue a frame for the next outbound packet. Control frames from the
118
- * stream manager flow through here so they are serialized + sent by the
119
- * connection's packetizer.
120
- */
121
- public sendFrame(frame: QuicFrame): void {
122
- this.outboundFrames.push(frame);
123
- }
124
-
125
- /**
126
- * Pack all buffered outbound frames into a short-header packet and send it.
127
- * Splits into multiple datagrams if the payload exceeds MAX_DATAGRAM_PAYLOAD.
128
- */
129
- private async _flush(): Promise<void> {
130
- if (this.outboundFrames.length === 0) return;
131
- const frames = this.outboundFrames.splice(0, this.outboundFrames.length);
132
- const payload = this._packFrames(frames);
133
- let offset = 0;
134
- while (offset < payload.length) {
135
- const slice = payload.subarray(offset, offset + MAX_DATAGRAM_PAYLOAD) as Bytes;
136
- const packet = this._wrapPacket(slice);
137
- await this.transport.send(packet, this.peer);
138
- offset += MAX_DATAGRAM_PAYLOAD;
139
- }
140
- }
141
-
142
- /** Serialize frames into a single byte buffer (no packet header). */
143
- private _packFrames(frames: QuicFrame[]): Bytes {
144
- return concatAll(frames.map((f) => serializeFrame(f)));
145
- }
146
-
147
- /** Wrap a serialized payload in a short (1-RTT) header + packet number. */
148
- private _wrapPacket(payload: Bytes): Bytes {
149
- const header = serializeShortHeader(this.dcid, 1, false, false);
150
- // 1-byte packet number (relative offset 0) — placeholder for the
151
- // protection layer, which assigns real packet numbers.
152
- const packetNumber = new Uint8Array([0]);
153
- return concatAll([header, packetNumber, payload]);
154
- }
155
-
156
- // --- read loop -------------------------------------------------------------
157
-
158
- /**
159
- * Start the datagram read loop. Must be called once after construction.
160
- * Runs until the transport closes or the connection tears down.
161
- */
162
- public startReadLoop(): void {
163
- // React to connection-level signals from the stream manager.
164
- this.manager.on("connectionClose", ({ errorCode, reason }: { errorCode: bigint; reason: string }) => {
165
- void errorCode;
166
- void reason;
167
- void this._onPeerClose(errorCode, reason);
168
- });
169
-
170
- void this._readLoop();
171
- }
172
-
173
- private async _onPeerClose(errorCode: bigint, reason: string): Promise<void> {
174
- if (this.closed) return;
175
- this.closing = true;
176
- this.manager.abortAll(new ConnectionClosedError(errorCode, reason));
177
- await this._teardown({ kind: "remote_close" });
178
- }
179
-
180
- /** Parse a single datagram into frames and dispatch them. */
181
- private async _dispatchDatagram(data: Bytes): Promise<void> {
182
- if (data.length === 0) return;
183
- try {
184
- const header = parsePacketHeader(data);
185
- this._applyHeader(header);
186
- // Skip the header + packet number to reach the frame payload. The
187
- // protection layer would decrypt first in a full implementation.
188
- const pnLength = header.packetNumberLength;
189
- // Short headers carry a variable-length DCID after the first byte;
190
- // its length is not on the wire, so the connection supplies it from
191
- // the handshake state we already know (this.dcid).
192
- const dcidLength = header.form === 0 ? this.dcid.length : 0;
193
- const payloadStart = header.headerLength + dcidLength + pnLength;
194
- const payload = data.subarray(payloadStart);
195
- if (payload.length === 0) return;
196
-
197
- const read = this._byteStreamReader(payload);
198
- for await (const frame of readFrames(read)) {
199
- this._handleFrame(frame);
200
- }
201
- } catch (err) {
202
- // A parse error on one datagram is not necessarily fatal for the
203
- // connection, but without a protection layer to frame it we close.
204
- this._handleFatal(err instanceof Error ? err : new Error(String(err)));
205
- }
206
- }
207
-
208
- /** Pull the DCID / version from a parsed header into connection state. */
209
- private _applyHeader(header: PacketHeader): void {
210
- if (header.form === 1) {
211
- // Long header: could carry a version negotiation. We ignore for now.
212
- return;
213
- }
214
- // Short header: the DCID on the wire is the route to the peer.
215
- void header.dcid;
216
- }
217
-
218
- /**
219
- * Build a pull-based byte reader over a fixed buffer. `readFrames` consumes
220
- * bytes incrementally; this yields slices until the buffer is exhausted.
221
- */
222
- private _byteStreamReader(buf: Bytes): () => Promise<Uint8Array | null> {
223
- let offset = 0;
224
- return async (): Promise<Uint8Array | null> => {
225
- if (offset >= buf.length) return null;
226
- const chunk = buf.subarray(offset);
227
- offset = buf.length;
228
- return chunk;
229
- };
230
- }
231
-
232
- /** Route a decoded frame: data-plane frames to the manager, the rest here. */
233
- private _handleFrame(frame: QuicFrame): void {
234
- switch (frame.type) {
235
- case QuicFrameType.PADDING:
236
- case QuicFrameType.PING:
237
- return;
238
- case QuicFrameType.ACK:
239
- case QuicFrameType.ACK_ECN:
240
- case QuicFrameType.CRYPTO:
241
- case QuicFrameType.NEW_TOKEN:
242
- case QuicFrameType.NEW_CONNECTION_ID:
243
- case QuicFrameType.RETIRE_CONNECTION_ID:
244
- case QuicFrameType.PATH_CHALLENGE:
245
- case QuicFrameType.PATH_RESPONSE:
246
- case QuicFrameType.HANDSHAKE_DONE:
247
- // Connection / handshake layer concerns — relay only.
248
- return;
249
- default:
250
- // Data-plane frame: dispatch to the stream manager, which may
251
- // emit outbound control frames (MAX_DATA, MAX_STREAM_DATA, ...).
252
- this._withOutbound(() => this.manager.dispatch(frame));
253
- return;
254
- }
255
- }
256
-
257
- /** Run `fn`, then flush any outbound frames it produced to the peer. */
258
- private _withOutbound(fn: () => void): void {
259
- const before = this.outboundFrames.length;
260
- fn();
261
- if (this.outboundFrames.length > before) {
262
- void this._flush();
263
- }
264
- }
265
-
266
- /** Main read loop: pull datagrams, dispatch, drain sends. */
267
- private async _readLoop(): Promise<void> {
268
- try {
269
- while (!this.closed) {
270
- const { data } = await this.transport.recv();
271
- await this._dispatchDatagram(data as Bytes);
272
- // Drain any pending stream sends after handling each datagram.
273
- this._drainSends();
274
- }
275
- } catch (err) {
276
- if (!this.closed) {
277
- this._handleFatal(err instanceof Error ? err : new Error(String(err)));
278
- }
279
- }
280
- }
281
-
282
- /** Emit STREAM frames for streams with queued data, then flush. */
283
- private _drainSends(): void {
284
- if (!this.manager.hasPendingSends) return;
285
- this.manager.flushSends(MAX_DATAGRAM_PAYLOAD, (frame) => this.sendFrame(frame));
286
- void this._flush();
287
- }
288
-
289
- /** Tear down the connection on a fatal transport / parse error. */
290
- private _handleFatal(err: Error): void {
291
- if (this.closed) return;
292
- this.closing = true;
293
- this.manager.abortAll(err);
294
- this._teardown({ kind: "error", error: err });
295
- }
296
-
297
- /** Mark closed and release the transport. */
298
- private async _teardown(reason: { readonly kind: "client_close" } | { readonly kind: "remote_close" } | { readonly kind: "error"; readonly error: Error }): Promise<void> {
299
- if (this.closed) return;
300
- this.closed = true;
301
- this.closing = true;
302
- try {
303
- await this.transport.close(reason);
304
- } catch {
305
- // best-effort
306
- }
307
- }
308
-
309
- private _ensureOpen(): void {
310
- if (this.closing || this.closed) {
311
- throw new Error("connection is closing");
312
- }
313
- }
314
- }
315
-
316
- // ---------------------------------------------------------------------------
317
- // helpers
318
- // ---------------------------------------------------------------------------
319
-
320
- /** Resolve the local transport parameters, filling in defaults. */
321
- function resolveLocalParameters(options: QuicOptions): QuicTransportParameters {
322
- const src = options.transportParameters;
323
- const out: Partial<Record<keyof QuicTransportParameters, bigint | number>> = {};
324
- if (src?.initialMaxData !== undefined) out.initialMaxData = src.initialMaxData;
325
- if (src?.initialMaxStreamDataBidiLocal !== undefined) {
326
- out.initialMaxStreamDataBidiLocal = src.initialMaxStreamDataBidiLocal;
327
- }
328
- if (src?.initialMaxStreamDataBidiRemote !== undefined) {
329
- out.initialMaxStreamDataBidiRemote = src.initialMaxStreamDataBidiRemote;
330
- }
331
- if (src?.initialMaxStreamDataUni !== undefined) out.initialMaxStreamDataUni = src.initialMaxStreamDataUni;
332
- if (src?.initialMaxStreamsBidi !== undefined) out.initialMaxStreamsBidi = src.initialMaxStreamsBidi;
333
- if (src?.initialMaxStreamsUni !== undefined) out.initialMaxStreamsUni = src.initialMaxStreamsUni;
334
- if (src?.maxIdleTimeoutMs !== undefined) out.maxIdleTimeoutMs = src.maxIdleTimeoutMs;
335
- if (src?.maxUdpPayloadSize !== undefined) out.maxUdpPayloadSize = src.maxUdpPayloadSize;
336
- if (src?.activeConnectionIdLimit !== undefined) out.activeConnectionIdLimit = src.activeConnectionIdLimit;
337
- return out as QuicTransportParameters;
338
- }
339
-
340
- // ---------------------------------------------------------------------------
341
- // connectQuic
342
- // ---------------------------------------------------------------------------
343
-
344
- /**
345
- * Establish a QUIC connection over an existing datagram transport.
346
- *
347
- * Creates the stream manager and the read loop. Because the TLS handshake and
348
- * packet protection are out of scope, this returns a connection that moves
349
- * unprotected frames — the data plane is fully functional and testable with a
350
- * fake datagram transport.
351
- */
352
- export async function connectQuic(options: QuicOptions): Promise<QuicConnection> {
353
- const id = `quic_${Date.now().toString(36)}`;
354
-
355
- // The stream manager is constructed before the connection, but its frames
356
- // must reach the connection's packetizer. We bridge the two with a mutable
357
- // router that we point at the connection once it exists.
358
- const frameRouter: { send: (frame: QuicFrame) => void } = { send: () => {} };
359
-
360
- const manager = createStreamManager({
361
- sendFrame: (frame) => frameRouter.send(frame),
362
- localParameters: resolveLocalParameters(options),
363
- peerParameters: options.transportParameters ?? {},
364
- });
365
-
366
- const conn = new QuicConnectionImpl(id, options, manager, options.initialDcid);
367
- frameRouter.send = (frame) => conn.sendFrame(frame);
368
-
369
- // A larger send window may have queued stream data — the read loop drains it.
370
- manager.on("maxData", () => { /* sends drain in the read loop */ });
371
-
372
- conn.startReadLoop();
373
- return conn;
374
- }