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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/loader.ts","../src/errors.ts","../src/native.ts","../src/datagrams.ts","../src/streams.ts","../src/webtransport.ts","../src/server.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n//! Locates and loads the rwebtransport native addon.\n//!\n//! Resolution order:\n//! 1. A prebuilt binary at `prebuilds/<platform>-<arch>/rwebtransport.node`.\n//! 2. If none is found, compile the Rust crate on the fly via `scripts/build.js`\n//! (requires a Rust toolchain + cmake + C/C++ compiler) and load the result.\n//!\n//! Only Node 24 and Node 26 are supported.\n\nimport { createRequire } from 'node:module';\nimport { execFileSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { NativeAddon } from './native.js';\n\n/**\n * A CommonJS-style `require` synthesized from this ES module's URL. Native\n * addons (`.node` files) are loaded through `require`, which understands the\n * platform binary format, rather than the ESM `import` machinery.\n *\n * @internal\n */\nconst require = createRequire(import.meta.url);\n\n/**\n * Absolute path of the directory containing this compiled module, resolved from\n * `import.meta.url`. Used as the anchor for locating package resources.\n *\n * @internal\n */\nconst moduleDir = dirname(fileURLToPath(import.meta.url));\n\n/**\n * The package root (one level up from the bundled `dist/` directory). All\n * runtime asset lookups (prebuilt binaries, the build script) are resolved\n * relative to this directory.\n *\n * @internal\n */\nconst PACKAGE_ROOT = join(moduleDir, '..');\n\n/**\n * Guard that aborts loading on an unsupported Node.js runtime. Only Node 24 and\n * Node 26 major versions are supported; anything else means the native ABI may\n * not match.\n *\n * @throws {Error} If the running Node major version is neither 24 nor 26.\n * @internal\n */\nfunction assertSupportedRuntime(): void {\n const major = Number(process.versions.node.split('.')[0]);\n if (major !== 24 && major !== 26) {\n throw new Error(\n `rwebtransport supports Node 24 and Node 26 only; this is Node ${process.versions.node}.`,\n );\n }\n}\n\n/**\n * Compute the expected location of the prebuilt native addon for the current\n * platform and architecture, namely\n * `prebuilds/<process.platform>-<process.arch>/rwebtransport.node` under the\n * package root.\n *\n * @returns The absolute path to the platform-specific prebuilt `.node` file.\n * The file is not guaranteed to exist; callers check separately.\n * @internal\n */\nfunction prebuiltPath(): string {\n return join(\n PACKAGE_ROOT,\n 'prebuilds',\n `${process.platform}-${process.arch}`,\n 'rwebtransport.node',\n );\n}\n\n/**\n * Memoized addon instance. Populated on the first successful {@link loadNative}\n * call and returned directly by all subsequent calls; `undefined` until then.\n *\n * @internal\n */\nlet cached: NativeAddon | undefined;\n\n/**\n * Locate, load, and cache the rwebtransport native addon.\n *\n * @remarks\n * On the first call the resolution proceeds as follows:\n * 1. Return early if a previous call already cached the addon.\n * 2. Assert the runtime is Node 24 or 26 (see {@link assertSupportedRuntime}).\n * 3. If a prebuilt binary exists for this platform and architecture, `require`\n * it, cache it, and return it.\n * 4. Otherwise fall back to compiling from source: run `scripts/build.js` with\n * the current Node executable (working directory set to the package root\n * and stdio inherited, so the compile output is streamed to the caller's\n * console), then `require` and cache the freshly produced binary. A notice\n * is written to `process.stderr` before the (one-time) build begins.\n *\n * Every later call short-circuits on the cached instance without re-checking the\n * runtime or the filesystem.\n *\n * @returns The loaded {@link NativeAddon}: the raw function surface exported by\n * `rwebtransport.node`.\n * @throws {Error} If the runtime is an unsupported Node.js version.\n * @throws {Error} If no prebuilt binary exists and `scripts/build.js` is absent,\n * so no binary can be compiled.\n * @throws {Error} If the on-the-fly build runs but does not produce the expected\n * binary. `execFileSync` additionally propagates if the build\n * process itself exits non-zero, and `require` propagates if the\n * resulting binary cannot be loaded.\n * @see {@link NativeAddon} for the shape of the returned object.\n * @internal\n */\nexport function loadNative(): NativeAddon {\n if (cached) return cached;\n assertSupportedRuntime();\n\n const prebuilt = prebuiltPath();\n if (existsSync(prebuilt)) {\n cached = require(prebuilt) as NativeAddon;\n return cached;\n }\n\n // Fallback: compile from source.\n const builder = join(PACKAGE_ROOT, 'scripts', 'build.js');\n if (!existsSync(builder)) {\n throw new Error(\n `rwebtransport: no prebuilt binary at ${prebuilt} and no build script to compile one. ` +\n `Reinstall the package or build it manually (npm run build:rust).`,\n );\n }\n process.stderr.write(\n 'rwebtransport: no prebuilt binary for this platform; compiling the native addon (this happens once)...\\n',\n );\n execFileSync(process.execPath, [builder], { cwd: PACKAGE_ROOT, stdio: 'inherit' });\n\n if (!existsSync(prebuilt)) {\n throw new Error(`rwebtransport: build completed but ${prebuilt} was not produced.`);\n }\n cached = require(prebuilt) as NativeAddon;\n return cached;\n}\n","// SPDX-License-Identifier: Apache-2.0\n//! The `WebTransportError` type, matching the W3C interface.\n\n/**\n * Identifies which part of the transport a {@link WebTransportError} came from.\n *\n * @remarks\n * Mirrors the `source` attribute of the W3C `WebTransportError` interface.\n * `'stream'` means the failure was raised by an individual send or receive\n * stream (for example a stream reset), while `'session'` means it applies to\n * the whole WebTransport session (for example the connection closing).\n *\n * @see {@link WebTransportError.source}\n */\nexport type WebTransportErrorSource = 'stream' | 'session';\n\n/**\n * Optional settings passed to the {@link WebTransportError} constructor.\n *\n * @remarks\n * Both fields are optional; the constructor applies defaults when they are\n * omitted. Corresponds to the `WebTransportErrorOptions` dictionary in the\n * W3C WebTransport specification.\n */\nexport interface WebTransportErrorOptions {\n /**\n * Which part of the transport the error originated from.\n *\n * @defaultValue `'session'` (applied by the constructor when omitted)\n * @see {@link WebTransportErrorSource}\n */\n source?: WebTransportErrorSource;\n /**\n * The application-supplied error code carried by a stream reset, or `null`\n * when the error is not associated with a specific stream error code.\n *\n * @defaultValue `null` (applied by the constructor when omitted)\n */\n streamErrorCode?: number | null;\n}\n\n/**\n * Error thrown / rejected for WebTransport failures, mirroring the browser\n * `WebTransportError`.\n *\n * @remarks\n * Extends the built-in {@link Error}. Instances are surfaced when a session or\n * stream fails, for example as the rejection reason of a pending promise or as\n * the error a {@link ReadableStream} / {@link WritableStream} is aborted with.\n * The constructor re-applies the prototype via {@link Object.setPrototypeOf}\n * so that `instanceof WebTransportError` works even when the class is\n * transpiled down to an ES5-style constructor function.\n *\n * @example\n * ```ts\n * throw new WebTransportError('stream reset', {\n * source: 'stream',\n * streamErrorCode: 42,\n * });\n * ```\n *\n * @see {@link WebTransportErrorOptions}\n */\nexport class WebTransportError extends Error {\n /** Whether the error originated from a stream or the session as a whole. */\n public readonly source: WebTransportErrorSource;\n /** The application error code, if the error came from a stream reset. */\n public readonly streamErrorCode: number | null;\n\n /**\n * Creates a new {@link WebTransportError}.\n *\n * @param message - Human-readable description of the failure. When omitted,\n * the message defaults to the string `'WebTransport error'`.\n * @param options - Optional {@link WebTransportErrorOptions}; defaults to an\n * empty object so that both fields fall back to their own defaults.\n *\n * @remarks\n * Sets {@link Error.name} to `'WebTransportError'`, resolves\n * {@link WebTransportError.source} (defaulting to `'session'`) and\n * {@link WebTransportError.streamErrorCode} (defaulting to `null`), then\n * restores the prototype chain with {@link Object.setPrototypeOf} so\n * `instanceof` checks succeed under downlevel compilation.\n */\n public constructor(message?: string, options: WebTransportErrorOptions = {}) {\n super(message ?? 'WebTransport error');\n this.name = 'WebTransportError';\n this.source = options.source ?? 'session';\n this.streamErrorCode = options.streamErrorCode ?? null;\n Object.setPrototypeOf(this, WebTransportError.prototype);\n }\n}\n","// SPDX-License-Identifier: Apache-2.0\n//! Typed view of the native addon and the event dispatcher that turns its\n//! low-level, callback-based ABI into promises and per-stream sinks.\n\nimport { loadNative } from './loader.js';\nimport { WebTransportError } from './errors.js';\nimport type { WebTransportCloseInfo } from './types.js';\n\n/**\n * Opaque handle to a native client session (a neon `JsBox`).\n *\n * @remarks\n * Returned by {@link NativeAddon.connect} and passed back into every\n * per-session native call so the addon can find the session's driver thread.\n * The `__brand` field is a compile-time nominal marker only: there is no such\n * property at runtime, and its purpose is to keep a client handle from being\n * confused with a {@link NativeServerHandle} or a plain object.\n * @internal\n */\nexport type NativeHandle = { readonly __brand: 'rwt-session' };\n\n/**\n * Opaque handle to a native server (a neon `JsBox`).\n *\n * @remarks\n * Returned by {@link NativeAddon.serverListen} and passed back into every\n * `server*` native call, together with a numeric session id, to target one of\n * the server's active sessions. Like {@link NativeHandle}, `__brand` is a\n * compile-time-only nominal marker.\n * @internal\n */\nexport type NativeServerHandle = { readonly __brand: 'rwt-server' };\n\n/**\n * The `type` discriminant shared by every {@link NativeEvent} and\n * {@link ServerNativeEvent}.\n *\n * @remarks\n * The string values are the exact wire contract emitted by the native addon, so\n * they must not be changed. Using an enum (rather than bare string literals)\n * gives the TypeScript layer a single, referenceable source of truth for the\n * event kinds.\n * @internal\n */\nexport enum NativeEventType {\n /** A client session's Extended CONNECT completed and it is established. */\n Ready = 'ready',\n /** A server session was established (a valid CONNECT arrived, answered 200). */\n ServerReady = 'serverReady',\n /** The session ended. */\n Closed = 'closed',\n /** The session failed with an error message. */\n Error = 'error',\n /** An inbound datagram payload arrived. */\n Datagram = 'datagram',\n /** The peer opened a stream. */\n Stream = 'stream',\n /** Inbound application bytes arrived on an existing stream. */\n StreamData = 'streamData',\n /** The peer finished (FIN) its side of a stream. */\n StreamFin = 'streamFin',\n /** The peer reset a stream. */\n StreamReset = 'streamReset',\n /** The peer sent STOP_SENDING for a stream. */\n StreamStopSending = 'streamStopSending',\n /** Acknowledges a locally requested {@link NativeAddon.openStream}. */\n StreamOpened = 'streamOpened',\n /** Acknowledges a {@link NativeAddon.writeStream} (the backpressure signal). */\n WriteAck = 'writeAck',\n /** Acknowledges a {@link NativeAddon.sendDatagram}. */\n DatagramAck = 'datagramAck',\n /** Server level: the listener is bound (carries the port). */\n Listening = 'listening',\n /** Server level: a fatal server failure. */\n ServerError = 'serverError',\n /** Server level: the server stopped. */\n ServerClosed = 'serverClosed',\n}\n\n/**\n * The client session's Extended CONNECT completed and the session is established.\n * @internal\n */\nexport interface NativeReadyEvent {\n /** Discriminant. */\n type: NativeEventType.Ready;\n}\n\n/**\n * A server session was established. Carries the client's CONNECT request\n * metadata and the client's remote address at establishment.\n * @internal\n */\nexport interface NativeServerReadyEvent {\n /** Discriminant. */\n type: NativeEventType.ServerReady;\n /** The `:authority` pseudo-header of the client's CONNECT request. */\n authority: string;\n /** The `:path` pseudo-header of the client's CONNECT request. */\n path: string;\n /** The `origin` header value, or `null` if the client sent none. */\n origin: string | null;\n /** Any additional (non-pseudo) request headers, keyed by header name. */\n headers: Record<string, string>;\n /** The client's remote IP address at session establishment. */\n remoteAddress: string;\n /** The client's remote UDP port at session establishment. */\n remotePort: number;\n}\n\n/**\n * The session ended. `code`/`reason` are the WebTransport close code and UTF-8\n * encoded reason; `remote` is true when the peer initiated the close.\n * @internal\n */\nexport interface NativeClosedEvent {\n /** Discriminant. */\n type: NativeEventType.Closed;\n /** The WebTransport close code. */\n code: number;\n /** The UTF-8 encoded close reason. */\n reason: Uint8Array;\n /** True when the peer initiated the close. */\n remote: boolean;\n}\n\n/**\n * The session failed with the given message.\n * @internal\n */\nexport interface NativeErrorEvent {\n /** Discriminant. */\n type: NativeEventType.Error;\n /** Human-readable failure message. */\n message: string;\n}\n\n/**\n * An inbound datagram payload.\n * @internal\n */\nexport interface NativeDatagramEvent {\n /** Discriminant. */\n type: NativeEventType.Datagram;\n /** The received datagram bytes. */\n data: Uint8Array;\n}\n\n/**\n * The peer opened a stream.\n * @internal\n */\nexport interface NativeStreamEvent {\n /** Discriminant. */\n type: NativeEventType.Stream;\n /** The id of the newly opened stream. */\n streamId: number;\n /** True for a bidirectional stream, false for a unidirectional one. */\n bidi: boolean;\n}\n\n/**\n * Inbound application bytes on an existing stream.\n * @internal\n */\nexport interface NativeStreamDataEvent {\n /** Discriminant. */\n type: NativeEventType.StreamData;\n /** The stream the bytes arrived on. */\n streamId: number;\n /** The received bytes. */\n data: Uint8Array;\n}\n\n/**\n * The peer finished (FIN) its side of a stream.\n * @internal\n */\nexport interface NativeStreamFinEvent {\n /** Discriminant. */\n type: NativeEventType.StreamFin;\n /** The stream that was finished. */\n streamId: number;\n}\n\n/**\n * The peer reset a stream.\n * @internal\n */\nexport interface NativeStreamResetEvent {\n /** Discriminant. */\n type: NativeEventType.StreamReset;\n /** The stream that was reset. */\n streamId: number;\n /** The application error code the peer sent. */\n code: number;\n}\n\n/**\n * The peer sent STOP_SENDING for a stream.\n * @internal\n */\nexport interface NativeStreamStopSendingEvent {\n /** Discriminant. */\n type: NativeEventType.StreamStopSending;\n /** The stream the peer asked us to stop sending on. */\n streamId: number;\n /** The application error code the peer sent. */\n code: number;\n}\n\n/**\n * Acknowledges a locally requested {@link NativeAddon.openStream}, pairing the\n * JS-generated `requestId` with the assigned stream id.\n * @internal\n */\nexport interface NativeStreamOpenedEvent {\n /** Discriminant. */\n type: NativeEventType.StreamOpened;\n /** The request id passed to {@link NativeAddon.openStream}. */\n requestId: number;\n /** The stream id the native side assigned. */\n streamId: number;\n}\n\n/**\n * Acknowledges a {@link NativeAddon.writeStream}: the bytes have been flushed\n * into quiche. This is the write backpressure signal.\n * @internal\n */\nexport interface NativeWriteAckEvent {\n /** Discriminant. */\n type: NativeEventType.WriteAck;\n /** The request id passed to {@link NativeAddon.writeStream}. */\n requestId: number;\n}\n\n/**\n * Acknowledges a {@link NativeAddon.sendDatagram}.\n * @internal\n */\nexport interface NativeDatagramAckEvent {\n /** Discriminant. */\n type: NativeEventType.DatagramAck;\n /** The request id passed to {@link NativeAddon.sendDatagram}. */\n requestId: number;\n /**\n * False when the datagram was dropped instead of sent (for example the\n * session was not ready or the payload exceeded the current flight size).\n */\n sent: boolean;\n}\n\n/**\n * Events delivered by the native addon to a client session's, or one server\n * session's, `onEvent` callback.\n *\n * @remarks\n * A discriminated union keyed on {@link NativeEventType}. Each session receives\n * its own stream of these, dispatched by {@link SessionCore.dispatch}.\n * @internal\n */\nexport type NativeEvent =\n | NativeReadyEvent\n | NativeServerReadyEvent\n | NativeClosedEvent\n | NativeErrorEvent\n | NativeDatagramEvent\n | NativeStreamEvent\n | NativeStreamDataEvent\n | NativeStreamFinEvent\n | NativeStreamResetEvent\n | NativeStreamStopSendingEvent\n | NativeStreamOpenedEvent\n | NativeWriteAckEvent\n | NativeDatagramAckEvent;\n\n/**\n * The raw function surface exported by `rwebtransport.node`.\n *\n * @remarks\n * This interface is the TypeScript view of the neon addon and is implemented by\n * native code, not by any TS class. Client-facing calls take a\n * {@link NativeHandle}; server-facing calls (prefixed `server`) take a\n * {@link NativeServerHandle} plus a numeric session id. Asynchronous results are\n * not returned directly: they arrive later as {@link NativeEvent}s on the\n * `onEvent` callback, correlated to the originating call by a JS-generated\n * `requestId`.\n * @see The native ABI notes for the exact wire contract.\n * @internal\n */\nexport interface NativeAddon {\n /**\n * Open a client session by performing a QUIC handshake and WebTransport\n * Extended CONNECT to `url`, spawning a background driver thread.\n *\n * @param url - The `https://host:port/path` session URL.\n * @param hashes - SHA-256 certificate pins as 32-byte arrays; when non-empty,\n * a matching certificate is accepted and normal CA/hostname validation is\n * bypassed.\n * @param insecure - Disable all certificate verification (development only).\n * @param origin - Value for the `origin` request header, or null to omit it.\n * @param headerNames - Additional request header names (parallel to `headerValues`).\n * @param headerValues - Additional request header values (parallel to `headerNames`).\n * @param onEvent - Callback invoked for every subsequent session event.\n * @returns An opaque handle to the new session.\n * @throws Synchronously on setup failures such as a malformed URL, DNS\n * resolution failure, socket bind failure, or invalid configuration.\n */\n connect(\n url: string,\n hashes: Uint8Array[],\n insecure: boolean,\n origin: string | null,\n headerNames: string[],\n headerValues: string[],\n onEvent: (ev: NativeEvent) => void,\n ): NativeHandle;\n /**\n * Request a new outbound stream. The result arrives asynchronously as a\n * `streamOpened` event carrying the same `requestId` and the assigned stream id.\n *\n * @param handle - The session handle.\n * @param bidi - True for a bidirectional stream, false for send-only unidirectional.\n * @param requestId - JS-generated id used to correlate the `streamOpened` event.\n */\n openStream(handle: NativeHandle, bidi: boolean, requestId: number): void;\n /**\n * Queue `bytes` for sending on `streamId`. A `writeAck` event with the same\n * `requestId` fires once the bytes are flushed into quiche's send buffer,\n * which is the backpressure signal used to resolve the write promise.\n *\n * @param handle - The session handle.\n * @param streamId - The target stream id.\n * @param bytes - The payload to send.\n * @param requestId - JS-generated id used to correlate the `writeAck` event.\n */\n writeStream(handle: NativeHandle, streamId: number, bytes: Uint8Array, requestId: number): void;\n /**\n * Finish (half-close) the send side of `streamId`, sending a QUIC FIN.\n *\n * @param handle - The session handle.\n * @param streamId - The stream to finish.\n */\n finStream(handle: NativeHandle, streamId: number): void;\n /**\n * Abruptly reset the send side of `streamId` with the given application error code.\n *\n * @param handle - The session handle.\n * @param streamId - The stream to reset.\n * @param code - The application error code (unsigned 32-bit).\n */\n resetStream(handle: NativeHandle, streamId: number, code: number): void;\n /**\n * Ask the peer to stop sending on `streamId` (QUIC STOP_SENDING) with the\n * given application error code.\n *\n * @param handle - The session handle.\n * @param streamId - The stream whose inbound half should be stopped.\n * @param code - The application error code (unsigned 32-bit).\n */\n stopSending(handle: NativeHandle, streamId: number, code: number): void;\n /**\n * Toggle read backpressure on `streamId`. When paused, the native side stops\n * draining quiche's receive buffer, which flow-controls the peer.\n *\n * @param handle - The session handle.\n * @param streamId - The receive stream to pause or resume.\n * @param paused - True to pause draining, false to resume.\n */\n setPaused(handle: NativeHandle, streamId: number, paused: boolean): void;\n /**\n * Send a datagram. A `datagramAck` event with the same `requestId` reports\n * whether it was actually sent.\n *\n * @param handle - The session handle.\n * @param bytes - The datagram payload.\n * @param requestId - JS-generated id used to correlate the `datagramAck` event.\n */\n sendDatagram(handle: NativeHandle, bytes: Uint8Array, requestId: number): void;\n /**\n * @param handle - The session handle.\n * @returns The maximum datagram payload size currently permitted, in bytes\n * (0 when datagrams cannot be sent).\n */\n maxDatagramSize(handle: NativeHandle): number;\n /**\n * @param handle - The session handle.\n * @returns Whether the session has been established (synchronous, via shared atomics).\n */\n isReady(handle: NativeHandle): boolean;\n /**\n * @param handle - The session handle.\n * @returns Whether the session has closed (synchronous, via shared atomics).\n */\n isClosed(handle: NativeHandle): boolean;\n /**\n * Gracefully close the session: send a CLOSE_WEBTRANSPORT_SESSION capsule and\n * FIN the CONNECT stream, then close the QUIC connection.\n *\n * @param handle - The session handle.\n * @param code - The WebTransport close code (unsigned 32-bit).\n * @param reason - The UTF-8 encoded close reason.\n */\n closeSession(handle: NativeHandle, code: number, reason: Uint8Array): void;\n /**\n * Tear down the session's driver thread. Called on close; the native\n * finalizer also invokes it as a safety net.\n *\n * @param handle - The session handle.\n */\n shutdown(handle: NativeHandle): void;\n\n /**\n * Start a WebTransport server: bind a UDP socket and begin accepting sessions.\n *\n * @param certPath - Path to the PEM certificate chain file.\n * @param keyPath - Path to the PEM private-key file.\n * @param host - Interface address to bind.\n * @param port - UDP port to bind (0 lets the OS choose; read it back from the\n * `listening` event).\n * @param reusePort - Bind with `SO_REUSEPORT` (Unix only) to share a port\n * across processes.\n * @param onEvent - Callback invoked for server-level and session-scoped events.\n * @returns An opaque handle to the server.\n */\n serverListen(\n certPath: string,\n keyPath: string,\n host: string,\n port: number,\n reusePort: boolean,\n onEvent: (ev: ServerNativeEvent) => void,\n ): NativeServerHandle;\n /**\n * Server-side {@link openStream}: request a new outbound stream on the given\n * session.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param bidi - True for bidirectional, false for send-only unidirectional.\n * @param requestId - JS-generated id used to correlate the `streamOpened` event.\n */\n serverOpenStream(\n handle: NativeServerHandle,\n session: number,\n bidi: boolean,\n requestId: number,\n ): void;\n /**\n * Server-side {@link writeStream}: queue bytes on a session's stream.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param streamId - The target stream id.\n * @param bytes - The payload to send.\n * @param requestId - JS-generated id used to correlate the `writeAck` event.\n */\n serverWrite(\n handle: NativeServerHandle,\n session: number,\n streamId: number,\n bytes: Uint8Array,\n requestId: number,\n ): void;\n /**\n * Server-side {@link finStream}: finish the send side of a session's stream.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param streamId - The stream to finish.\n */\n serverFin(handle: NativeServerHandle, session: number, streamId: number): void;\n /**\n * Server-side {@link resetStream}: reset the send side of a session's stream.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param streamId - The stream to reset.\n * @param code - The application error code (unsigned 32-bit).\n */\n serverReset(handle: NativeServerHandle, session: number, streamId: number, code: number): void;\n /**\n * Server-side {@link stopSending}: ask the peer to stop sending on a session's stream.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param streamId - The stream whose inbound half should be stopped.\n * @param code - The application error code (unsigned 32-bit).\n */\n serverStopSending(\n handle: NativeServerHandle,\n session: number,\n streamId: number,\n code: number,\n ): void;\n /**\n * Server-side {@link setPaused}: toggle read backpressure on a session's stream.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param streamId - The receive stream to pause or resume.\n * @param paused - True to pause draining, false to resume.\n */\n serverSetPaused(\n handle: NativeServerHandle,\n session: number,\n streamId: number,\n paused: boolean,\n ): void;\n /**\n * Server-side {@link sendDatagram}: send a datagram on a session.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param bytes - The datagram payload.\n * @param requestId - JS-generated id used to correlate the `datagramAck` event.\n */\n serverSendDatagram(\n handle: NativeServerHandle,\n session: number,\n bytes: Uint8Array,\n requestId: number,\n ): void;\n /**\n * Server-side {@link maxDatagramSize}.\n *\n * @param handle - The server handle.\n * @returns The maximum datagram payload size currently permitted, in bytes.\n */\n serverMaxDatagramSize(handle: NativeServerHandle): number;\n /**\n * Server-side {@link closeSession}: gracefully close one session.\n *\n * @param handle - The server handle.\n * @param session - The session id to close.\n * @param code - The WebTransport close code (unsigned 32-bit).\n * @param reason - The UTF-8 encoded close reason.\n */\n serverCloseSession(\n handle: NativeServerHandle,\n session: number,\n code: number,\n reason: Uint8Array,\n ): void;\n /**\n * Stop the server, closing all its sessions and freeing the listening socket.\n *\n * @param handle - The server handle.\n */\n serverShutdown(handle: NativeServerHandle): void;\n}\n\n/**\n * Server level: the listener is bound and accepting packets.\n * @internal\n */\nexport interface NativeListeningEvent {\n /** Discriminant. */\n type: NativeEventType.Listening;\n /** The UDP port the server actually bound. */\n port: number;\n}\n\n/**\n * Server level: a fatal server failure (for example a bind or certificate error).\n * @internal\n */\nexport interface NativeServerErrorEvent {\n /** Discriminant. */\n type: NativeEventType.ServerError;\n /** Human-readable failure message. */\n message: string;\n}\n\n/**\n * Server level: the server stopped.\n * @internal\n */\nexport interface NativeServerClosedEvent {\n /** Discriminant. */\n type: NativeEventType.ServerClosed;\n}\n\n/**\n * Server-level events, plus every {@link NativeEvent} widened with a numeric\n * `session` id.\n *\n * @remarks\n * The `session` field identifies which of the server's sessions a session-scoped\n * event belongs to, so the server can demultiplex a single `onEvent` stream\n * across all its active sessions.\n * @internal\n */\nexport type ServerNativeEvent =\n | NativeListeningEvent\n | NativeServerErrorEvent\n | NativeServerClosedEvent\n | (NativeEvent & { session: number });\n\n/**\n * Normalized inputs for opening a session.\n *\n * @remarks\n * Produced by the client `WebTransport` layer from user-facing options and\n * passed straight through to {@link NativeAddon.connect} by\n * {@link createClientSession}. The header arrays are parallel (`headerNames[i]`\n * pairs with `headerValues[i]`).\n * @internal\n */\nexport interface ConnectConfig {\n /** The `https://host:port/path` session URL. */\n url: string;\n /** SHA-256 certificate pins as 32-byte arrays; empty when none are pinned. */\n hashes: Uint8Array[];\n /** Disable all certificate verification (development only). */\n insecure: boolean;\n /** Value for the `origin` request header, or null to omit it. */\n origin: string | null;\n /** Additional request header names, parallel to {@link ConnectConfig.headerValues}. */\n headerNames: string[];\n /** Additional request header values, parallel to {@link ConnectConfig.headerNames}. */\n headerValues: string[];\n}\n\n/**\n * Consumer of a receive stream's inbound events.\n *\n * @remarks\n * Registered per stream via {@link SessionCore.registerReceive}. The stream\n * layer implements this to feed a WHATWG `ReadableStream` controller.\n * @internal\n */\nexport interface ReceiveSink {\n /**\n * A chunk of stream data arrived.\n *\n * @param chunk - The received bytes.\n */\n onData(chunk: Uint8Array): void;\n /** The peer finished (FIN) the stream; no more data will arrive. */\n onFin(): void;\n /**\n * The peer reset the stream.\n *\n * @param code - The application error code from the reset.\n */\n onReset(code: number): void;\n}\n\n/**\n * Consumer of a send stream's control events.\n *\n * @remarks\n * Registered per stream via {@link SessionCore.registerSend}. The stream layer\n * implements this to error its WHATWG `WritableStream` controller.\n * @internal\n */\nexport interface SendSink {\n /**\n * The peer asked to stop receiving (QUIC STOP_SENDING).\n *\n * @param code - The application error code the peer supplied.\n */\n onStopSending(code: number): void;\n}\n\n/**\n * Consumer of peer-initiated streams.\n *\n * @remarks\n * A single handler per session, set via {@link SessionCore.setIncomingHandler};\n * invoked when the peer opens a new stream.\n * @internal\n */\nexport interface IncomingHandler {\n /**\n * The peer opened a bidirectional stream.\n *\n * @param streamId - The new stream's id.\n */\n onBidi(streamId: number): void;\n /**\n * The peer opened a unidirectional (receive-only) stream.\n *\n * @param streamId - The new stream's id.\n */\n onUni(streamId: number): void;\n}\n\n/**\n * Consumer of inbound datagrams.\n *\n * @remarks\n * A single sink per session, set via {@link SessionCore.setDatagramSink};\n * invoked with each datagram payload as it arrives.\n * @param data - The datagram payload.\n * @internal\n */\nexport type DatagramSink = (data: Uint8Array) => void;\n\n/**\n * A promise bundled with its own `resolve`/`reject` functions.\n *\n * @typeParam T - The value the promise resolves to.\n * @remarks\n * Used to correlate a native acknowledgement event (which arrives later) with\n * the caller awaiting it.\n * @internal\n */\ninterface Deferred<T> {\n /** The pending promise handed to the awaiter. */\n promise: Promise<T>;\n /** Settles {@link Deferred.promise} with a value. */\n resolve: (value: T) => void;\n /** Rejects {@link Deferred.promise} with a reason. */\n reject: (reason: unknown) => void;\n}\n\n/**\n * Create a {@link Deferred}: a promise together with externally callable\n * `resolve` and `reject`.\n *\n * @typeParam T - The value the promise resolves to.\n * @returns The bundled promise and its settle functions.\n * @internal\n */\nfunction deferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n\n/**\n * The low-level per-session command surface. Implemented by a client transport\n * (native session handle) or a server transport (server handle + session id), so\n * the same {@link SessionCore} drives both roles.\n *\n * @remarks\n * These methods are fire-and-forget: their outcomes come back later as\n * {@link NativeEvent}s that {@link SessionCore.dispatch} routes to the awaiting\n * promises and sinks.\n * @internal\n */\nexport interface SessionTransport {\n /**\n * Request a new outbound stream.\n *\n * @param bidi - True for bidirectional, false for send-only unidirectional.\n * @param requestId - Id correlating the eventual `streamOpened` event.\n */\n openStream(bidi: boolean, requestId: number): void;\n /**\n * Queue bytes for sending on a stream.\n *\n * @param streamId - The target stream id.\n * @param bytes - The payload.\n * @param requestId - Id correlating the eventual `writeAck` event.\n */\n write(streamId: number, bytes: Uint8Array, requestId: number): void;\n /**\n * Finish (half-close) the send side of a stream.\n *\n * @param streamId - The stream to finish.\n */\n fin(streamId: number): void;\n /**\n * Reset the send side of a stream.\n *\n * @param streamId - The stream to reset.\n * @param code - The application error code.\n */\n reset(streamId: number, code: number): void;\n /**\n * Ask the peer to stop sending on a stream.\n *\n * @param streamId - The stream whose inbound half should be stopped.\n * @param code - The application error code.\n */\n stopSending(streamId: number, code: number): void;\n /**\n * Toggle read backpressure on a stream.\n *\n * @param streamId - The receive stream.\n * @param paused - True to pause draining, false to resume.\n */\n setPaused(streamId: number, paused: boolean): void;\n /**\n * Send a datagram.\n *\n * @param bytes - The datagram payload.\n * @param requestId - Id correlating the eventual `datagramAck` event.\n */\n sendDatagram(bytes: Uint8Array, requestId: number): void;\n /** @returns The maximum datagram payload size, in bytes. */\n maxDatagramSize(): number;\n /**\n * Gracefully close the session.\n *\n * @param code - The WebTransport close code.\n * @param reason - The UTF-8 encoded close reason.\n */\n closeSession(code: number, reason: Uint8Array): void;\n /** Tear down the session's native resources. */\n shutdown(): void;\n}\n\n/**\n * Dispatches native events to promises / sinks and issues commands through an\n * injected {@link SessionTransport}. Exactly one `SessionCore` backs one\n * WebTransport session (client or server side).\n *\n * @remarks\n * The higher layers ({@link WebTransportReceiveStream | streams} and\n * {@link WebTransportDatagramDuplexStream | datagrams}) never touch the native\n * addon directly: they call this core, which owns the request-id bookkeeping and\n * the lifecycle promises.\n * @internal\n */\nexport class SessionCore {\n /**\n * The command transport, undefined until {@link SessionCore.attach} runs.\n * While undefined, outbound commands are dropped or rejected.\n */\n private transport: SessionTransport | undefined;\n\n /** Monotonic source of request ids handed to the transport. */\n private nextRequestId = 1;\n /** Pending {@link SessionCore.openStream} requests, keyed by request id. */\n private readonly opens = new Map<number, Deferred<number>>();\n /** Pending {@link SessionCore.write} requests, keyed by request id. */\n private readonly writes = new Map<number, Deferred<void>>();\n /** Pending {@link SessionCore.sendDatagram} requests, keyed by request id. */\n private readonly datagramAcks = new Map<number, Deferred<boolean>>();\n /** Active receive sinks, keyed by stream id. */\n private readonly receives = new Map<number, ReceiveSink>();\n /** Active send sinks, keyed by stream id. */\n private readonly sends = new Map<number, SendSink>();\n\n /** Handler for peer-initiated streams, if one has been set. */\n private incoming: IncomingHandler | undefined;\n /** Sink for inbound datagrams, if one has been set. */\n private datagramSink: DatagramSink | undefined;\n\n /** True once the session has reached its terminal (closed) state. */\n private closedState = false;\n /** True once the session has been established (`ready`/`serverReady`). */\n private readyState = false;\n\n /**\n * Resolves when the session is established, rejects if it fails before then.\n * Backs the public `WebTransport.ready` promise.\n */\n public readonly ready = deferred<void>();\n /**\n * Resolves with close info on a clean shutdown, rejects on an error or on a\n * close that happens before the session is ready. Backs `WebTransport.closed`.\n */\n public readonly closed = deferred<WebTransportCloseInfo>();\n\n /**\n * Attach no-op catch handlers to {@link SessionCore.ready} and\n * {@link SessionCore.closed} so that a session whose promises the user never\n * observes does not trigger Node's unhandled-rejection warning.\n */\n public constructor() {\n // Swallow default unhandled-rejection warnings; the user observes these.\n void this.closed.promise.catch(() => {});\n void this.ready.promise.catch(() => {});\n }\n\n /**\n * Attach the transport once the underlying native handle exists.\n *\n * @param transport - The command sink for this session (client or server side).\n */\n public attach(transport: SessionTransport): void {\n this.transport = transport;\n }\n\n /**\n * Fail a session that could not be set up at all (e.g. client connect threw).\n *\n * @param message - Human-readable description of the setup failure.\n * @remarks\n * The failure is delivered on a microtask so the caller has a chance to\n * attach `.ready`/`.closed` handlers before they reject.\n */\n public failSetup(message: string): void {\n // Defer so the caller can attach `.ready`/`.closed` handlers first.\n queueMicrotask(() =>\n this.finish(null, new WebTransportError(message, { source: 'session' })),\n );\n }\n\n /**\n * @returns The next request id, post-incrementing the internal counter.\n */\n private nextId(): number {\n return this.nextRequestId++;\n }\n\n /**\n * Open an outbound stream and await its assigned id.\n *\n * @param bidi - True for a bidirectional stream, false for unidirectional.\n * @returns A promise for the new stream's id.\n * @remarks\n * Rejects immediately (without touching the transport) if the session is not\n * usable (unattached or closed).\n */\n public openStream(bidi: boolean): Promise<number> {\n if (!this.usable()) return Promise.reject(this.deadError());\n const requestId = this.nextId();\n const d = deferred<number>();\n this.opens.set(requestId, d);\n this.transport!.openStream(bidi, requestId);\n return d.promise;\n }\n\n /**\n * Write a chunk to a stream; resolves once the bytes are flushed into quiche\n * (the write backpressure signal).\n *\n * @param streamId - The target stream id.\n * @param chunk - The bytes to send.\n * @returns A promise that resolves when the write is acknowledged.\n * @remarks\n * Rejects immediately if the session is not usable.\n */\n public write(streamId: number, chunk: Uint8Array): Promise<void> {\n if (!this.usable()) return Promise.reject(this.deadError());\n const requestId = this.nextId();\n const d = deferred<void>();\n this.writes.set(requestId, d);\n this.transport!.write(streamId, chunk, requestId);\n return d.promise;\n }\n\n /**\n * Finish (half-close) the send side of a stream. No-op if not attached.\n *\n * @param streamId - The stream to finish.\n */\n public finStream(streamId: number): void {\n this.transport?.fin(streamId);\n }\n\n /**\n * Reset the send side of a stream. No-op if not attached.\n *\n * @param streamId - The stream to reset.\n * @param code - The application error code; coerced to an unsigned 32-bit value.\n */\n public resetStream(streamId: number, code: number): void {\n this.transport?.reset(streamId, code >>> 0);\n }\n\n /**\n * Ask the peer to stop sending on a stream. No-op if not attached.\n *\n * @param streamId - The stream whose inbound half should be stopped.\n * @param code - The application error code; coerced to an unsigned 32-bit value.\n */\n public stopSending(streamId: number, code: number): void {\n this.transport?.stopSending(streamId, code >>> 0);\n }\n\n /**\n * Toggle read backpressure on a stream. No-op if not attached.\n *\n * @param streamId - The receive stream.\n * @param paused - True to pause native draining (flow-control the peer), false to resume.\n */\n public setPaused(streamId: number, paused: boolean): void {\n this.transport?.setPaused(streamId, paused);\n }\n\n /**\n * Send a datagram.\n *\n * @param chunk - The datagram payload.\n * @returns A promise resolving to whether the datagram was actually sent;\n * resolves to false (rather than rejecting) when the session is not usable.\n */\n public sendDatagram(chunk: Uint8Array): Promise<boolean> {\n if (!this.usable()) return Promise.resolve(false);\n const requestId = this.nextId();\n const d = deferred<boolean>();\n this.datagramAcks.set(requestId, d);\n this.transport!.sendDatagram(chunk, requestId);\n return d.promise;\n }\n\n /**\n * @returns The maximum datagram payload size in bytes, or 0 if not attached.\n */\n public maxDatagramSize(): number {\n return this.transport ? this.transport.maxDatagramSize() : 0;\n }\n\n /**\n * Gracefully close the session. No-op if already closed or not attached.\n *\n * @param code - The WebTransport close code; coerced to an unsigned 32-bit value.\n * @param reason - The close reason, UTF-8 encoded before it is sent.\n */\n public close(code: number, reason: string): void {\n if (this.closedState || !this.transport) return;\n this.transport.closeSession(code >>> 0, new TextEncoder().encode(reason));\n }\n\n /** Tear down the native resources for this session. No-op if not attached. */\n public shutdown(): void {\n this.transport?.shutdown();\n }\n\n /**\n * Whether outbound operations can still be issued (attached, not closed).\n *\n * @returns True when a transport is attached and the session is not closed.\n */\n private usable(): boolean {\n return this.transport !== undefined && !this.closedState;\n }\n\n /**\n * @returns The error used to reject operations attempted on a dead session.\n */\n private deadError(): WebTransportError {\n return new WebTransportError('session is closed', { source: 'session' });\n }\n\n /**\n * Register a sink to receive a stream's inbound data/fin/reset events.\n *\n * @param streamId - The stream to observe.\n * @param sink - The receiver of that stream's inbound events.\n */\n public registerReceive(streamId: number, sink: ReceiveSink): void {\n this.receives.set(streamId, sink);\n }\n /**\n * Stop delivering inbound events for a stream.\n *\n * @param streamId - The stream to forget.\n */\n public unregisterReceive(streamId: number): void {\n this.receives.delete(streamId);\n }\n /**\n * Register a sink to receive a stream's STOP_SENDING notifications.\n *\n * @param streamId - The stream to observe.\n * @param sink - The receiver of that stream's send-side control events.\n */\n public registerSend(streamId: number, sink: SendSink): void {\n this.sends.set(streamId, sink);\n }\n /**\n * Stop delivering send-side control events for a stream.\n *\n * @param streamId - The stream to forget.\n */\n public unregisterSend(streamId: number): void {\n this.sends.delete(streamId);\n }\n /**\n * Set the handler invoked when the peer opens a stream. Replaces any prior handler.\n *\n * @param handler - The consumer of peer-initiated streams.\n */\n public setIncomingHandler(handler: IncomingHandler): void {\n this.incoming = handler;\n }\n /**\n * Set the sink invoked for each inbound datagram. Replaces any prior sink.\n *\n * @param sink - The consumer of inbound datagram payloads.\n */\n public setDatagramSink(sink: DatagramSink): void {\n this.datagramSink = sink;\n }\n\n /**\n * Route one native event to the appropriate promise, sink, or handler.\n *\n * @param ev - The event delivered by the native addon.\n * @remarks\n * This is the single entry point the native `onEvent` callback funnels into.\n * `ready`/`serverReady` mark the session established and resolve `ready`;\n * `closed`/`error` drive {@link SessionCore.finish}; the `stream*` events look\n * up the matching sink (silently ignored if none is registered); and the\n * `*Ack`/`streamOpened` events settle and then remove the pending deferred\n * for their `requestId`.\n */\n public dispatch(ev: NativeEvent): void {\n switch (ev.type) {\n case NativeEventType.Ready:\n case NativeEventType.ServerReady: {\n this.readyState = true;\n this.ready.resolve();\n break;\n }\n case NativeEventType.Closed: {\n const reason = new TextDecoder().decode(ev.reason);\n this.finish({ closeCode: ev.code, reason }, undefined);\n break;\n }\n case NativeEventType.Error: {\n const err = new WebTransportError(ev.message, { source: 'session' });\n this.finish(null, err);\n break;\n }\n case NativeEventType.Datagram: {\n this.datagramSink?.(ev.data);\n break;\n }\n case NativeEventType.Stream: {\n if (ev.bidi) this.incoming?.onBidi(ev.streamId);\n else this.incoming?.onUni(ev.streamId);\n break;\n }\n case NativeEventType.StreamData: {\n this.receives.get(ev.streamId)?.onData(ev.data);\n break;\n }\n case NativeEventType.StreamFin: {\n this.receives.get(ev.streamId)?.onFin();\n break;\n }\n case NativeEventType.StreamReset: {\n this.receives.get(ev.streamId)?.onReset(ev.code);\n break;\n }\n case NativeEventType.StreamStopSending: {\n this.sends.get(ev.streamId)?.onStopSending(ev.code);\n break;\n }\n case NativeEventType.StreamOpened: {\n this.opens.get(ev.requestId)?.resolve(ev.streamId);\n this.opens.delete(ev.requestId);\n break;\n }\n case NativeEventType.WriteAck: {\n this.writes.get(ev.requestId)?.resolve();\n this.writes.delete(ev.requestId);\n break;\n }\n case NativeEventType.DatagramAck: {\n this.datagramAcks.get(ev.requestId)?.resolve(ev.sent);\n this.datagramAcks.delete(ev.requestId);\n break;\n }\n }\n }\n\n /**\n * Terminal transition: resolve/reject everything and tear down.\n *\n * @param info - Close info for a clean close, or null when closing on error.\n * @param error - The error that ended the session, or undefined for a clean close.\n * @remarks\n * Idempotent: returns immediately if the session already closed. Settles the\n * lifecycle promises according to state: if the session never became ready,\n * both `ready` and `closed` reject (a pre-ready close is a failed connect); if\n * it was ready and `error` is set, only `closed` rejects; otherwise `closed`\n * resolves with `info` (defaulting to code 0 / empty reason). It then rejects\n * every pending open and write, resolves every pending datagram ack to false,\n * signals a reset (code 0) to all receive sinks and STOP_SENDING (code 0) to\n * all send sinks, clears the bookkeeping maps, and finally shuts down the\n * transport.\n */\n private finish(info: WebTransportCloseInfo | null, error: WebTransportError | undefined): void {\n if (this.closedState) return;\n this.closedState = true;\n\n if (!this.readyState) {\n // The session never established: both `ready` and `closed` reject\n // (a session that closes before it is ready has failed to connect).\n const err =\n error ??\n new WebTransportError('session closed before it was established', {\n source: 'session',\n });\n this.ready.reject(err);\n this.closed.reject(err);\n } else if (error) {\n // Established, then terminated abnormally.\n this.closed.reject(error);\n } else {\n // Established, then closed cleanly.\n this.closed.resolve(info ?? { closeCode: 0, reason: '' });\n }\n\n const err = error ?? new WebTransportError('session closed', { source: 'session' });\n for (const d of this.opens.values()) d.reject(err);\n for (const d of this.writes.values()) d.reject(err);\n for (const d of this.datagramAcks.values()) d.resolve(false);\n for (const sink of this.receives.values()) sink.onReset(0);\n for (const sink of this.sends.values()) sink.onStopSending(0);\n this.opens.clear();\n this.writes.clear();\n this.datagramAcks.clear();\n this.receives.clear();\n this.sends.clear();\n\n this.transport?.shutdown();\n }\n\n /** @returns Whether the session has reached its terminal closed state. */\n public get isClosed(): boolean {\n return this.closedState;\n }\n}\n\n/**\n * Routes session commands through a native client session handle.\n *\n * @remarks\n * The client-side {@link SessionTransport}: each method forwards to the matching\n * {@link NativeAddon} function with the captured {@link NativeHandle}.\n * @internal\n */\nclass ClientTransport implements SessionTransport {\n /**\n * @param native - The loaded native addon.\n * @param handle - The client session handle these commands target.\n */\n public constructor(\n private readonly native: NativeAddon,\n private readonly handle: NativeHandle,\n ) {}\n /**\n * @param bidi - True for bidirectional, false for unidirectional.\n * @param requestId - Id correlating the eventual `streamOpened` event.\n */\n public openStream(bidi: boolean, requestId: number): void {\n this.native.openStream(this.handle, bidi, requestId);\n }\n /**\n * @param streamId - The target stream id.\n * @param bytes - The payload.\n * @param requestId - Id correlating the eventual `writeAck` event.\n */\n public write(streamId: number, bytes: Uint8Array, requestId: number): void {\n this.native.writeStream(this.handle, streamId, bytes, requestId);\n }\n /** @param streamId - The stream to finish. */\n public fin(streamId: number): void {\n this.native.finStream(this.handle, streamId);\n }\n /**\n * @param streamId - The stream to reset.\n * @param code - The application error code.\n */\n public reset(streamId: number, code: number): void {\n this.native.resetStream(this.handle, streamId, code);\n }\n /**\n * @param streamId - The stream whose inbound half should be stopped.\n * @param code - The application error code.\n */\n public stopSending(streamId: number, code: number): void {\n this.native.stopSending(this.handle, streamId, code);\n }\n /**\n * @param streamId - The receive stream.\n * @param paused - True to pause draining, false to resume.\n */\n public setPaused(streamId: number, paused: boolean): void {\n this.native.setPaused(this.handle, streamId, paused);\n }\n /**\n * @param bytes - The datagram payload.\n * @param requestId - Id correlating the eventual `datagramAck` event.\n */\n public sendDatagram(bytes: Uint8Array, requestId: number): void {\n this.native.sendDatagram(this.handle, bytes, requestId);\n }\n /** @returns The maximum datagram payload size, in bytes. */\n public maxDatagramSize(): number {\n return this.native.maxDatagramSize(this.handle);\n }\n /**\n * @param code - The WebTransport close code.\n * @param reason - The UTF-8 encoded close reason.\n */\n public closeSession(code: number, reason: Uint8Array): void {\n this.native.closeSession(this.handle, code, reason);\n }\n /** Tear down the session's native driver thread. */\n public shutdown(): void {\n this.native.shutdown(this.handle);\n }\n}\n\n/**\n * Create and connect a client-role session.\n *\n * @param config - The normalized connect parameters.\n * @returns A {@link SessionCore} wired to a fresh native client session; if the\n * native `connect` throws during setup, the returned core is failed\n * asynchronously via {@link SessionCore.failSetup} rather than throwing here.\n * @remarks\n * Loads the native addon, constructs the core, calls {@link NativeAddon.connect}\n * with an `onEvent` callback bound to {@link SessionCore.dispatch}, and attaches\n * a {@link ClientTransport} around the returned handle.\n * @internal\n */\nexport function createClientSession(config: ConnectConfig): SessionCore {\n const native = loadNative();\n const core = new SessionCore();\n try {\n const handle = native.connect(\n config.url,\n config.hashes,\n config.insecure,\n config.origin,\n config.headerNames,\n config.headerValues,\n (ev) => core.dispatch(ev),\n );\n core.attach(new ClientTransport(native, handle));\n } catch (e) {\n core.failSetup(e instanceof Error ? e.message : String(e));\n }\n return core;\n}\n\n/**\n * Routes session commands through a native server handle + session id.\n *\n * @remarks\n * The server-side {@link SessionTransport}: each method forwards to the matching\n * `server*` {@link NativeAddon} function with the captured\n * {@link NativeServerHandle} and numeric session id.\n * @internal\n */\nexport class ServerTransport implements SessionTransport {\n /**\n * @param native - The loaded native addon.\n * @param handle - The server handle these commands target.\n * @param session - The id of the session these commands act on.\n */\n public constructor(\n private readonly native: NativeAddon,\n private readonly handle: NativeServerHandle,\n private readonly session: number,\n ) {}\n /**\n * @param bidi - True for bidirectional, false for unidirectional.\n * @param requestId - Id correlating the eventual `streamOpened` event.\n */\n public openStream(bidi: boolean, requestId: number): void {\n this.native.serverOpenStream(this.handle, this.session, bidi, requestId);\n }\n /**\n * @param streamId - The target stream id.\n * @param bytes - The payload.\n * @param requestId - Id correlating the eventual `writeAck` event.\n */\n public write(streamId: number, bytes: Uint8Array, requestId: number): void {\n this.native.serverWrite(this.handle, this.session, streamId, bytes, requestId);\n }\n /** @param streamId - The stream to finish. */\n public fin(streamId: number): void {\n this.native.serverFin(this.handle, this.session, streamId);\n }\n /**\n * @param streamId - The stream to reset.\n * @param code - The application error code.\n */\n public reset(streamId: number, code: number): void {\n this.native.serverReset(this.handle, this.session, streamId, code);\n }\n /**\n * @param streamId - The stream whose inbound half should be stopped.\n * @param code - The application error code.\n */\n public stopSending(streamId: number, code: number): void {\n this.native.serverStopSending(this.handle, this.session, streamId, code);\n }\n /**\n * @param streamId - The receive stream.\n * @param paused - True to pause draining, false to resume.\n */\n public setPaused(streamId: number, paused: boolean): void {\n this.native.serverSetPaused(this.handle, this.session, streamId, paused);\n }\n /**\n * @param bytes - The datagram payload.\n * @param requestId - Id correlating the eventual `datagramAck` event.\n */\n public sendDatagram(bytes: Uint8Array, requestId: number): void {\n this.native.serverSendDatagram(this.handle, this.session, bytes, requestId);\n }\n /** @returns The maximum datagram payload size, in bytes. */\n public maxDatagramSize(): number {\n return this.native.serverMaxDatagramSize(this.handle);\n }\n /**\n * @param code - The WebTransport close code.\n * @param reason - The UTF-8 encoded close reason.\n */\n public closeSession(code: number, reason: Uint8Array): void {\n this.native.serverCloseSession(this.handle, this.session, code, reason);\n }\n /**\n * No-op: the server driver owns the session lifecycle, so there is nothing to\n * tear down per session on the JS side.\n */\n public shutdown(): void {\n // The server driver owns the session lifecycle; nothing to tear down here.\n }\n}\n","// SPDX-License-Identifier: Apache-2.0\n//! `WebTransportDatagramDuplexStream`: unreliable, unordered datagrams.\n\nimport type { SessionCore } from './native.js';\n\n/**\n * The datagram transport for a session. `readable` yields inbound datagrams and\n * `writable` sends them; both are lossy by design (datagrams that don't fit the\n * queue are dropped rather than buffered indefinitely).\n *\n * @remarks\n * This mirrors the WHATWG `WebTransportDatagramDuplexStream` interface. One\n * instance is created per {@link SessionCore} and exposed as the `datagrams`\n * member of a session. Loss happens in two places: inbound datagrams that\n * arrive while the `readable` queue is already full are discarded (see the\n * datagram sink installed in the constructor), and outbound datagrams are\n * subject to the queue backpressure of `writable` plus whatever the native\n * QUIC layer chooses to drop when a packet cannot carry them.\n *\n * @see WebTransport for how a session exposes this stream.\n */\nexport class WebTransportDatagramDuplexStream {\n /**\n * The underlying session used to send datagrams, register the inbound sink,\n * query the maximum datagram size, and observe session closure.\n *\n * @internal\n */\n private readonly session: SessionCore;\n /**\n * Stream of inbound datagrams. Each chunk is one received datagram payload.\n * Backed by a {@link CountQueuingStrategy} whose high water mark is the\n * value of {@link incomingHighWaterMark} captured when this instance was\n * constructed. The stream is closed automatically when the session ends.\n */\n public readonly readable: ReadableStream<Uint8Array>;\n /**\n * Stream for sending outbound datagrams. Writing a chunk forwards it to\n * {@link SessionCore.sendDatagram}, whose boolean result (whether the\n * datagram was actually transmitted rather than dropped) is discarded, so\n * that `write()` resolves once the native transport reports back on the\n * send attempt. Backed by a {@link CountQueuingStrategy} whose high water\n * mark is the value of {@link outgoingHighWaterMark} captured when this\n * instance was constructed.\n */\n public readonly writable: WritableStream<Uint8Array>;\n\n /**\n * High water mark (in datagrams) for the inbound `readable` queue. Read\n * back through {@link incomingHighWaterMark}. Only the value present at\n * construction time is applied to the actual {@link readable} strategy;\n * later changes update the reported number but do not resize the live\n * queue.\n *\n * @defaultValue 64\n * @internal\n */\n private incomingHwm = 64;\n /**\n * High water mark (in datagrams) for the outbound `writable` queue. Read\n * back through {@link outgoingHighWaterMark}. Only the value present at\n * construction time is applied to the actual {@link writable} strategy;\n * later changes update the reported number but do not resize the live\n * queue.\n *\n * @defaultValue 64\n * @internal\n */\n private outgoingHwm = 64;\n\n /**\n * Max age (ms) an inbound datagram is retained before being dropped, or\n * `null` for no limit.\n *\n * @remarks\n * Present to match the WHATWG interface. This class stores the value but\n * does not currently enforce it: inbound loss here is driven only by the\n * `readable` queue being full, not by datagram age.\n *\n * @defaultValue null\n */\n public incomingMaxAge: number | null = null;\n /**\n * Max age (ms) an outbound datagram waits to be sent before being dropped,\n * or `null` for no limit.\n *\n * @remarks\n * Present to match the WHATWG interface. This class stores the value but\n * does not currently enforce it; outbound loss is governed by the\n * `writable` queue backpressure and the native QUIC layer.\n *\n * @defaultValue null\n */\n public outgoingMaxAge: number | null = null;\n\n /**\n * Build the datagram duplex stream over a session.\n *\n * @param session - The session that carries the datagrams. Its\n * {@link SessionCore.setDatagramSink} is used to receive inbound datagrams,\n * {@link SessionCore.sendDatagram} to send them, and its\n * {@link SessionCore.closed} promise to know when to close the inbound\n * stream.\n *\n * @remarks\n * Wiring performed here, in order:\n *\n * 1. Creates {@link readable} and captures its controller from `start`.\n * 2. Installs a datagram sink that enqueues each received datagram only\n * while the controller's `desiredSize` is positive (treating an unknown\n * `desiredSize` of `null` as `1`, i.e. room available); datagrams that\n * arrive when the queue is full are dropped.\n * 3. Subscribes to the session's `closed` promise so the inbound stream is\n * closed on both clean close and error, preventing a pending `read()`\n * from hanging forever. A double-close is swallowed.\n * 4. Creates {@link writable} whose `write` forwards each chunk to\n * `session.sendDatagram` and maps the boolean ack to `undefined`.\n */\n public constructor(session: SessionCore) {\n this.session = session;\n\n let rController!: ReadableStreamDefaultController<Uint8Array>;\n this.readable = new ReadableStream<Uint8Array>(\n {\n start(c) {\n rController = c;\n },\n },\n new CountQueuingStrategy({ highWaterMark: this.incomingHwm }),\n );\n\n session.setDatagramSink((data) => {\n // Unreliable: drop when the inbound queue is already full.\n if ((rController.desiredSize ?? 1) > 0) {\n rController.enqueue(data);\n }\n });\n\n // Close the inbound datagram stream when the session ends, otherwise a\n // reader awaiting read() would hang forever after close.\n void session.closed.promise.then(\n () => {\n try {\n rController.close();\n } catch {\n // already closed\n }\n },\n () => {\n try {\n rController.close();\n } catch {\n // already closed\n }\n },\n );\n\n this.writable = new WritableStream<Uint8Array>(\n {\n write: (chunk) => session.sendDatagram(chunk).then(() => undefined),\n },\n new CountQueuingStrategy({ highWaterMark: this.outgoingHwm }),\n );\n }\n\n /**\n * The largest datagram payload that currently fits in a single packet.\n *\n * @returns The maximum datagram payload size in bytes as reported by the\n * native transport, or `0` when the session has no transport attached yet.\n * The value can change over the life of the session as the path MTU is\n * discovered.\n */\n public get maxDatagramSize(): number {\n return this.session.maxDatagramSize();\n }\n\n /**\n * The high water mark (in datagrams) reported for the inbound `readable`\n * queue.\n *\n * @returns The most recently set incoming high water mark.\n */\n public get incomingHighWaterMark(): number {\n return this.incomingHwm;\n }\n /**\n * Set the reported inbound high water mark.\n *\n * @param value - Desired high water mark; coerced to an integer with\n * `value | 0` and clamped to a minimum of `1`.\n *\n * @remarks\n * This updates only the number returned by {@link incomingHighWaterMark}.\n * The live {@link readable} queue keeps the strategy fixed at construction\n * time, so changing this after construction does not resize it.\n */\n public set incomingHighWaterMark(value: number) {\n this.incomingHwm = Math.max(1, value | 0);\n }\n\n /**\n * The high water mark (in datagrams) reported for the outbound `writable`\n * queue.\n *\n * @returns The most recently set outgoing high water mark.\n */\n public get outgoingHighWaterMark(): number {\n return this.outgoingHwm;\n }\n /**\n * Set the reported outbound high water mark.\n *\n * @param value - Desired high water mark; coerced to an integer with\n * `value | 0` and clamped to a minimum of `1`.\n *\n * @remarks\n * This updates only the number returned by {@link outgoingHighWaterMark}.\n * The live {@link writable} queue keeps the strategy fixed at construction\n * time, so changing this after construction does not resize it.\n */\n public set outgoingHighWaterMark(value: number) {\n this.outgoingHwm = Math.max(1, value | 0);\n }\n}\n","// SPDX-License-Identifier: Apache-2.0\n//! WebTransport stream classes, implemented as WHATWG Readable/Writable streams\n//! with end-to-end backpressure onto the native QUIC flow-control window.\n\nimport { WebTransportError } from './errors.js';\nimport type { SessionCore } from './native.js';\n\n/**\n * Derive a QUIC/WebTransport application error code from an abort or cancel reason.\n *\n * @param reason - The value handed to a stream `cancel(reason)` or `abort(reason)`.\n * @returns The stream's application error code as an unsigned 32-bit integer: it is\n * {@link WebTransportError.streamErrorCode} (coerced with `>>> 0`) when `reason` is\n * a {@link WebTransportError} carrying a non-null code, and `0` for every other\n * value, including plain errors and `undefined`.\n * @remarks Translates a JS-level abort or cancel into the numeric code carried by the\n * QUIC `STOP_SENDING` and `RESET_STREAM` frames sent to the peer.\n * @internal\n */\nfunction errorCode(reason: unknown): number {\n if (reason instanceof WebTransportError && reason.streamErrorCode != null) {\n return reason.streamErrorCode >>> 0;\n }\n return 0;\n}\n\n/**\n * The readable half of a WebTransport stream. A `ReadableStream<Uint8Array>`\n * whose queue high-water mark drives native read backpressure: when the JS queue\n * fills, the native side stops draining quiche, flow-controlling the peer.\n *\n * @remarks Subclasses the WHATWG `ReadableStream`, so all standard reader APIs\n * (`getReader`, async iteration, `pipeTo`, `cancel`, and so on) work as usual.\n * Inbound bytes arrive as native `streamData` events routed through the session's\n * {@link ReceiveSink}; a peer FIN closes the stream and a peer reset errors it with\n * a {@link WebTransportError}.\n */\nexport class WebTransportReceiveStream extends ReadableStream<Uint8Array> {\n /**\n * The QUIC stream id of the underlying stream. Stable for the lifetime of the\n * stream and shared with the paired {@link WebTransportSendStream} when this is\n * one half of a {@link WebTransportBidirectionalStream}.\n */\n public readonly streamId: number;\n\n /**\n * Wire a `ReadableStream` up to a native receive stream.\n *\n * @param session - The session core that dispatches native events and issues\n * flow-control and teardown commands for this stream.\n * @param streamId - The QUIC stream id to receive from.\n * @remarks Installs the `ReadableStream` underlying source and registers a\n * {@link ReceiveSink} on `session` for `streamId`:\n *\n * - `pull` unpauses the native stream via `setPaused(streamId, false)`, so\n * quiche resumes draining inbound bytes when the consumer wants more.\n * - `cancel(reason)` sends `STOP_SENDING` to the peer with the code from\n * {@link errorCode} and then unregisters the receive sink.\n * - The sink's `onData` enqueues each chunk and, once the controller's\n * `desiredSize` falls to zero or below (a nullish `desiredSize` is treated as\n * `1`, so it does not pause), pauses the native stream to flow-control the\n * peer.\n * - The sink's `onFin` closes the controller (swallowing the error if it was\n * already closed or errored) and unregisters.\n * - The sink's `onReset(code)` errors the controller with a `'stream'`-sourced\n * {@link WebTransportError} ('stream reset by peer') carrying the peer's code,\n * then unregisters.\n *\n * A {@link CountQueuingStrategy} with a high-water mark of 32 chunks bounds the\n * JS-side queue and thereby the pause threshold.\n */\n public constructor(session: SessionCore, streamId: number) {\n let controller!: ReadableStreamDefaultController<Uint8Array>;\n super(\n {\n start(c) {\n controller = c;\n },\n pull() {\n session.setPaused(streamId, false);\n },\n cancel(reason) {\n session.stopSending(streamId, errorCode(reason));\n session.unregisterReceive(streamId);\n },\n },\n new CountQueuingStrategy({ highWaterMark: 32 }),\n );\n\n session.registerReceive(streamId, {\n onData(chunk) {\n controller.enqueue(chunk);\n if ((controller.desiredSize ?? 1) <= 0) {\n session.setPaused(streamId, true);\n }\n },\n onFin() {\n try {\n controller.close();\n } catch {\n // already closed/errored\n }\n session.unregisterReceive(streamId);\n },\n onReset(code) {\n controller.error(\n new WebTransportError('stream reset by peer', {\n source: 'stream',\n streamErrorCode: code,\n }),\n );\n session.unregisterReceive(streamId);\n },\n });\n\n this.streamId = streamId;\n }\n}\n\n/**\n * The writable half of a WebTransport stream. Each `write()` resolves only once\n * the bytes have been accepted into quiche's send buffer, giving natural\n * backpressure gated by the peer's flow-control window.\n *\n * @remarks Subclasses the WHATWG `WritableStream`, so all standard writer APIs\n * (`getWriter`, `write`, `close`, `abort`, `pipeTo` targets, and so on) work as\n * usual. A peer `STOP_SENDING` errors the stream through the session's\n * {@link SendSink}.\n */\nexport class WebTransportSendStream extends WritableStream<Uint8Array> {\n /**\n * The QUIC stream id of the underlying stream. Stable for the lifetime of the\n * stream and shared with the paired {@link WebTransportReceiveStream} when this is\n * one half of a {@link WebTransportBidirectionalStream}.\n */\n public readonly streamId: number;\n\n /**\n * Wire a `WritableStream` up to a native send stream.\n *\n * @param session - The session core that dispatches native events and issues\n * write, FIN, reset, and teardown commands for this stream.\n * @param streamId - The QUIC stream id to send on.\n * @remarks Installs the `WritableStream` underlying sink and registers a\n * {@link SendSink} on `session` for `streamId`:\n *\n * - `write(chunk)` forwards to `session.write` and returns its promise, which\n * settles only once the bytes are accepted into quiche's send buffer; awaiting\n * that promise is what applies end-to-end backpressure.\n * - `close` sends a FIN via `finStream` and unregisters the send sink.\n * - `abort(reason)` resets the stream via `resetStream` with the code from\n * {@link errorCode} and unregisters the send sink.\n * - The sink's `onStopSending(code)` errors the controller with a\n * `'stream'`-sourced {@link WebTransportError} ('peer sent STOP_SENDING')\n * carrying the peer's code (swallowing the error if the stream was already\n * errored or closed) and unregisters.\n *\n * A {@link ByteLengthQueuingStrategy} with a high-water mark of 1 MiB\n * (`1024 * 1024` bytes) bounds the JS-side write queue.\n */\n public constructor(session: SessionCore, streamId: number) {\n let controller!: WritableStreamDefaultController;\n super(\n {\n start(c) {\n controller = c;\n },\n write(chunk) {\n return session.write(streamId, chunk);\n },\n close() {\n session.finStream(streamId);\n session.unregisterSend(streamId);\n },\n abort(reason) {\n session.resetStream(streamId, errorCode(reason));\n session.unregisterSend(streamId);\n },\n },\n new ByteLengthQueuingStrategy({ highWaterMark: 1024 * 1024 }),\n );\n\n session.registerSend(streamId, {\n onStopSending(code) {\n try {\n controller.error(\n new WebTransportError('peer sent STOP_SENDING', {\n source: 'stream',\n streamErrorCode: code,\n }),\n );\n } catch {\n // already errored/closed\n }\n session.unregisterSend(streamId);\n },\n });\n\n this.streamId = streamId;\n }\n}\n\n/**\n * A bidirectional WebTransport stream: a {@link WebTransportReceiveStream} and a\n * {@link WebTransportSendStream} over a single QUIC stream id, exposed as `readable`\n * and `writable` halves. Mirrors the shape of the browser\n * `WebTransportBidirectionalStream`.\n */\nexport class WebTransportBidirectionalStream {\n /** The readable half, delivering bytes the peer sends on this stream. */\n public readonly readable: WebTransportReceiveStream;\n /** The writable half, sending bytes to the peer on this stream. */\n public readonly writable: WebTransportSendStream;\n\n /**\n * Construct both halves over the same QUIC stream.\n *\n * @param session - The session core backing both halves.\n * @param streamId - The QUIC stream id shared by the readable and writable halves.\n */\n public constructor(session: SessionCore, streamId: number) {\n this.readable = new WebTransportReceiveStream(session, streamId);\n this.writable = new WebTransportSendStream(session, streamId);\n }\n}\n","// SPDX-License-Identifier: Apache-2.0\n//! The `WebTransport` class: the W3C entry point.\n\nimport { SessionCore, createClientSession, type ConnectConfig } from './native.js';\nimport { WebTransportError } from './errors.js';\nimport { WebTransportDatagramDuplexStream } from './datagrams.js';\nimport {\n WebTransportBidirectionalStream,\n WebTransportReceiveStream,\n WebTransportSendStream,\n} from './streams.js';\nimport type {\n BinarySource,\n WebTransportCloseInfo,\n WebTransportCloseOptions,\n WebTransportOptions,\n} from './types.js';\n\n/**\n * Normalize a {@link BinarySource} into a `Uint8Array` view over the same\n * memory, without copying.\n *\n * @param src - A typed array or `DataView`, or a raw `ArrayBuffer`.\n * @returns A `Uint8Array`: the whole buffer when `src` is an `ArrayBuffer`,\n * otherwise a view restricted to the source view's own `byteOffset` and\n * `byteLength` so a subview does not expose bytes outside its window.\n * @internal\n */\nfunction toBytes(src: BinarySource): Uint8Array {\n if (src instanceof ArrayBuffer) return new Uint8Array(src);\n return new Uint8Array(src.buffer, src.byteOffset, src.byteLength);\n}\n\n/**\n * Validate a URL and {@link WebTransportOptions} and flatten them into the\n * {@link ConnectConfig} the native `connect` function expects.\n *\n * @param url - The session URL. Must be a `string` beginning with `https://`.\n * @param options - Caller-supplied session options.\n * @returns The normalized connect configuration (URL, SHA-256 hash pins,\n * insecure flag, origin, and parallel header name/value arrays).\n * @throws WebTransportError with `source: 'session'` if `url` is not an\n * `https://` string, if a certificate hash uses an algorithm other than\n * `sha-256`, or if a `sha-256` hash value is not exactly 32 bytes.\n * @remarks Each entry of `options.serverCertificateHashes` is checked: the\n * algorithm is compared case-insensitively against `sha-256` and the value is\n * converted with {@link toBytes} and required to be 32 bytes long.\n * `options.headers` is split into parallel `headerNames` and `headerValues`\n * arrays. Missing optional fields default to `insecure: false` and\n * `origin: null`.\n * @internal\n */\nfunction buildConfig(url: string, options: WebTransportOptions): ConnectConfig {\n if (typeof url !== 'string' || !url.startsWith('https://')) {\n throw new WebTransportError(`invalid WebTransport URL: ${url}`, { source: 'session' });\n }\n\n const hashes: Uint8Array[] = [];\n for (const hash of options.serverCertificateHashes ?? []) {\n const algorithm = hash.algorithm.toLowerCase();\n if (algorithm !== 'sha-256') {\n throw new WebTransportError(\n `unsupported certificate hash algorithm: ${hash.algorithm} (only sha-256)`,\n { source: 'session' },\n );\n }\n const bytes = toBytes(hash.value);\n if (bytes.byteLength !== 32) {\n throw new WebTransportError('sha-256 certificate hash must be 32 bytes', {\n source: 'session',\n });\n }\n hashes.push(bytes);\n }\n\n const headerNames: string[] = [];\n const headerValues: string[] = [];\n for (const [name, value] of Object.entries(options.headers ?? {})) {\n headerNames.push(name);\n headerValues.push(value);\n }\n\n return {\n url,\n hashes,\n insecure: options.insecure ?? false,\n origin: options.origin ?? null,\n headerNames,\n headerValues,\n };\n}\n\n/**\n * The symmetric surface of an established WebTransport session (streams and\n * datagrams), shared by the client {@link WebTransport} and the server-side\n * session (`WebTransportServerSession` in `src/server.ts`).\n *\n * @remarks Wraps a {@link SessionCore}, which turns the callback-based native\n * ABI into promises and per-stream sinks. Peer-initiated streams surface on\n * {@link WebTransportSession.incomingBidirectionalStreams} and\n * {@link WebTransportSession.incomingUnidirectionalStreams}; datagrams are\n * exposed through {@link WebTransportSession.datagrams}.\n * @see {@link WebTransport} for the client entry point.\n */\nexport class WebTransportSession {\n /**\n * The event dispatcher and command surface backing this session. Shared with\n * the datagram and stream wrappers so they can issue native commands and\n * register their inbound sinks. Protected so the server-side subclass can\n * reach it while it stays hidden from public API consumers.\n * @internal\n */\n protected readonly core: SessionCore;\n /**\n * The session's datagram transport: a {@link WebTransportDatagramDuplexStream}\n * whose `readable` yields inbound datagrams and `writable` sends them.\n * Datagrams are unreliable and unordered; ones that do not fit the queue are\n * dropped rather than buffered.\n */\n public readonly datagrams: WebTransportDatagramDuplexStream;\n /**\n * A `ReadableStream` that yields a {@link WebTransportBidirectionalStream} for\n * every bidirectional stream the peer opens. Fed by the core's incoming\n * handler; it closes when the session closes cleanly and errors if the\n * session terminates abnormally.\n */\n public readonly incomingBidirectionalStreams: ReadableStream<WebTransportBidirectionalStream>;\n /**\n * A `ReadableStream` that yields a receive-only\n * {@link WebTransportReceiveStream} for every unidirectional stream the peer\n * opens. Fed by the core's incoming handler; it closes on clean session close\n * and errors on abnormal termination.\n */\n public readonly incomingUnidirectionalStreams: ReadableStream<WebTransportReceiveStream>;\n /**\n * Guards {@link WebTransportSession.close} so that repeated calls are no-ops\n * and the native close is issued at most once.\n * @internal\n */\n private closeCalled = false;\n\n /**\n * Wire up the session surface around an existing {@link SessionCore}.\n *\n * @param core - The event dispatcher and command core for this session. For\n * the client this is a freshly connected client session; for the server it is\n * a session-scoped core created by the server driver.\n * @remarks Creates the {@link WebTransportSession.datagrams} duplex, then\n * constructs the two incoming-stream `ReadableStream`s and captures their\n * controllers via the `start` callback. Registers an incoming handler on\n * `core` so each peer-opened bidi/uni stream is wrapped and enqueued;\n * `enqueue` is wrapped in try/catch because it throws once the consumer has\n * cancelled the reader, and that error must not escape native event dispatch.\n * Finally it observes `core.closed`: on clean close both controllers are\n * closed via {@link safeClose}, and on rejection both are errored with the\n * failure reason via {@link safeError}.\n */\n public constructor(core: SessionCore) {\n this.core = core;\n this.datagrams = new WebTransportDatagramDuplexStream(core);\n\n let bidiController!: ReadableStreamDefaultController<WebTransportBidirectionalStream>;\n let uniController!: ReadableStreamDefaultController<WebTransportReceiveStream>;\n this.incomingBidirectionalStreams = new ReadableStream<WebTransportBidirectionalStream>({\n start: (c) => {\n bidiController = c;\n },\n });\n this.incomingUnidirectionalStreams = new ReadableStream<WebTransportReceiveStream>({\n start: (c) => {\n uniController = c;\n },\n });\n\n core.setIncomingHandler({\n onBidi: (id) => {\n // Guard: enqueue throws if the consumer already cancelled the\n // reader, and that must not escape the native event dispatch.\n try {\n bidiController.enqueue(new WebTransportBidirectionalStream(core, id));\n } catch {\n // consumer no longer reading incoming bidi streams\n }\n },\n onUni: (id) => {\n try {\n uniController.enqueue(new WebTransportReceiveStream(core, id));\n } catch {\n // consumer no longer reading incoming uni streams\n }\n },\n });\n\n core.closed.promise.then(\n () => {\n safeClose(bidiController);\n safeClose(uniController);\n },\n (err: unknown) => {\n safeError(bidiController, err);\n safeError(uniController, err);\n },\n );\n }\n\n /**\n * A promise that resolves once the session handshake completes and the\n * session is established, and rejects if the session fails or closes before\n * it becomes ready.\n * @returns The core's `ready` promise.\n */\n public get ready(): Promise<void> {\n return this.core.ready.promise;\n }\n\n /**\n * A promise that resolves with the {@link WebTransportCloseInfo} (close code\n * and reason) when the session ends cleanly, and rejects with a\n * {@link WebTransportError} on abnormal termination or if the session never\n * became ready.\n * @returns The core's `closed` promise.\n */\n public get closed(): Promise<WebTransportCloseInfo> {\n return this.core.closed.promise;\n }\n\n /**\n * Open a new outbound bidirectional stream.\n *\n * @returns A promise resolving to a {@link WebTransportBidirectionalStream}\n * (paired readable and writable halves) once the native side reports the new\n * stream id.\n * @throws WebTransportError (the returned promise rejects) if the session is\n * already closed or was never attached.\n */\n public async createBidirectionalStream(): Promise<WebTransportBidirectionalStream> {\n const id = await this.core.openStream(true);\n return new WebTransportBidirectionalStream(this.core, id);\n }\n\n /**\n * Open a new outbound unidirectional (send-only) stream.\n *\n * @returns A promise resolving to a {@link WebTransportSendStream} once the\n * native side reports the new stream id.\n * @throws WebTransportError (the returned promise rejects) if the session is\n * already closed or was never attached.\n */\n public async createUnidirectionalStream(): Promise<WebTransportSendStream> {\n const id = await this.core.openStream(false);\n return new WebTransportSendStream(this.core, id);\n }\n\n /**\n * Close the session gracefully, notifying the peer with an application code\n * and reason.\n *\n * @param closeInfo - Close options. `closeInfo.closeCode` defaults to `0` and\n * `closeInfo.reason` defaults to `''`; both are forwarded to the native\n * close.\n * @defaultValue `closeInfo` defaults to `{}` (close code `0`, empty reason).\n * @remarks Idempotent: guarded by {@link WebTransportSession.closeCalled} so\n * only the first call takes effect and later calls are no-ops. Delegates to\n * the core, which issues the native `closeSession` (a graceful\n * CLOSE_WEBTRANSPORT_SESSION capsule plus FIN, then QUIC close) only while the\n * session is still attached and not already closed.\n */\n public close(closeInfo: WebTransportCloseOptions = {}): void {\n if (this.closeCalled) return;\n this.closeCalled = true;\n this.core.close(closeInfo.closeCode ?? 0, closeInfo.reason ?? '');\n }\n}\n\n/**\n * A WebTransport client session, matching the\n * [W3C WebTransport](https://w3c.github.io/webtransport/) interface.\n *\n * @remarks Constructs and begins connecting a native client session\n * immediately; setup (DNS, socket bind, TLS/QUIC handshake) runs asynchronously\n * on the driver thread. Await {@link WebTransportSession.ready | ready} before\n * use, and observe {@link WebTransportSession.closed | closed} for termination.\n * @example\n * ```ts\n * const wt = new WebTransport('https://example.com:4433/wt');\n * await wt.ready;\n * const stream = await wt.createBidirectionalStream();\n * ```\n */\nexport class WebTransport extends WebTransportSession {\n /**\n * Create and begin connecting a WebTransport client session.\n *\n * @param url - The session URL; must be an `https://` URL.\n * @param options - Session options: certificate pinning, extra headers,\n * origin, and the Node-specific `insecure` flag.\n * @defaultValue `options` defaults to `{}`.\n * @throws WebTransportError synchronously if {@link buildConfig} rejects the\n * URL or a certificate hash. Asynchronous setup failures (DNS, bind,\n * handshake) instead reject {@link WebTransportSession.ready | ready} and\n * {@link WebTransportSession.closed | closed}.\n * @remarks Validates and normalizes inputs via {@link buildConfig}, then\n * calls {@link createClientSession} to spawn the native driver thread and\n * passes the resulting {@link SessionCore} to the base constructor.\n */\n public constructor(url: string, options: WebTransportOptions = {}) {\n super(createClientSession(buildConfig(url, options)));\n }\n}\n\n/**\n * Call a controller's `close()`, swallowing the error it throws when the\n * controller is already closed or errored.\n *\n * @param controller - Any object exposing a `close()` method (a readable stream\n * default controller).\n * @internal\n */\nfunction safeClose(controller: { close(): void }): void {\n try {\n controller.close();\n } catch {\n // already closed\n }\n}\n\n/**\n * Call a controller's `error()` with a reason, swallowing the error it throws\n * when the controller is already closed or errored.\n *\n * @param controller - Any object exposing an `error()` method (a readable stream\n * default controller).\n * @param reason - The failure reason to surface to the stream's consumer.\n * @internal\n */\nfunction safeError(controller: { error(reason?: unknown): void }, reason: unknown): void {\n try {\n controller.error(reason);\n } catch {\n // already closed/errored\n }\n}\n","// SPDX-License-Identifier: Apache-2.0\n//! The `WebTransportServer` accepts WebTransport sessions from clients. Each\n//! established session is a {@link WebTransportServerSession}, which shares the\n//! full stream/datagram surface with the client `WebTransport`.\n\nimport { WebTransportError } from './errors.js';\nimport { loadNative } from './loader.js';\nimport {\n NativeEventType,\n SessionCore,\n ServerTransport,\n type NativeAddon,\n type NativeServerHandle,\n type ServerNativeEvent,\n} from './native.js';\nimport { WebTransportSession } from './webtransport.js';\n\n/**\n * A promise paired with its externally callable `resolve` and `reject`, so a\n * value can be settled from outside the executor (for example from a native\n * event callback).\n *\n * @typeParam T - The type the promise resolves to.\n * @internal Private helper, not part of the published package API.\n */\ninterface Deferred<T> {\n /** The promise controlled by this deferred. */\n promise: Promise<T>;\n /** Fulfills {@link Deferred.promise} with the given value. */\n resolve: (value: T) => void;\n /** Rejects {@link Deferred.promise} with the given reason. */\n reject: (reason: unknown) => void;\n}\n\n/**\n * Create a {@link Deferred}: a fresh promise together with its `resolve` and\n * `reject` functions captured from the executor.\n *\n * @typeParam T - The type the promise resolves to.\n * @returns A deferred whose `resolve`/`reject` settle its `promise`.\n * @internal Private helper, not part of the published package API.\n */\nfunction deferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n\n/** Options for {@link WebTransportServer}. */\nexport interface WebTransportServerOptions {\n /** UDP port to listen on. Use `0` to let the OS pick (read it back via `port`). */\n port: number;\n /**\n * Interface (IP address) to bind.\n *\n * @defaultValue `'0.0.0.0'` (all IPv4 interfaces).\n */\n host?: string;\n /** Path to the PEM certificate chain file. */\n cert: string;\n /** Path to the PEM private-key file. */\n key: string;\n /**\n * Bind with `SO_REUSEPORT` (Unix only) so multiple processes, for example\n * Node `cluster` workers, can share one listening port and let the kernel\n * load-balance connections across them. Ignored on Windows, where the flag\n * does not exist.\n *\n * @defaultValue `false`\n */\n reusePort?: boolean;\n}\n\n/**\n * Metadata about the Extended CONNECT that opened a server session, extracted\n * from the client's HTTP/3 CONNECT request pseudo-headers and headers.\n */\nexport interface WebTransportSessionRequest {\n /** The `:authority` pseudo-header of the client's CONNECT request. */\n authority: string;\n /** The `:path` pseudo-header of the client's CONNECT request. */\n path: string;\n /** The `origin` header value, or `null` if the client did not send one. */\n origin: string | null;\n /** Any additional (non-pseudo) request headers, keyed by header name. */\n headers: Record<string, string>;\n /** The client's remote IP address at session establishment. */\n remoteAddress: string;\n /** The client's remote UDP port at session establishment. */\n remotePort: number;\n}\n\n/**\n * A server-side WebTransport session. Symmetric with the client `WebTransport`\n * (streams + datagrams inherited from {@link WebTransportSession}), plus the\n * request metadata carried on the client's CONNECT.\n */\nexport class WebTransportServerSession extends WebTransportSession {\n /** The `:authority` of the client's CONNECT request. */\n public readonly authority: string;\n /** The `:path` of the client's CONNECT request. */\n public readonly path: string;\n /** The `origin` header, if the client sent one, otherwise `null`. */\n public readonly origin: string | null;\n /** Any additional (non-pseudo) request headers, keyed by header name. */\n public readonly headers: Record<string, string>;\n /**\n * The client's remote IP address, as reported by the transport when the\n * session was established. The same for every stream and datagram on this\n * session, since they all share the one QUIC connection.\n */\n public readonly remoteAddress: string;\n /** The client's remote UDP port at session establishment. */\n public readonly remotePort: number;\n\n /**\n * Wrap an established session core together with the CONNECT metadata that\n * opened it. Called by {@link WebTransportServer} when a new session becomes\n * ready; not intended for direct construction by users.\n *\n * @param core - The dispatcher/command core backing this session, already\n * attached to a {@link ServerTransport}.\n * @param request - The CONNECT metadata (authority, path, origin, headers)\n * plus the client's remote address, copied onto this session's public fields.\n */\n public constructor(core: SessionCore, request: WebTransportSessionRequest) {\n super(core);\n this.authority = request.authority;\n this.path = request.path;\n this.origin = request.origin;\n this.headers = request.headers;\n this.remoteAddress = request.remoteAddress;\n this.remotePort = request.remotePort;\n }\n}\n\n/**\n * A WebTransport server. Bind a port with a certificate, then consume\n * {@link incomingSessions}.\n *\n * @example\n * ```ts\n * const server = new WebTransportServer({ port: 4433, cert, key });\n * await server.ready;\n * for await (const session of readable(server.incomingSessions)) {\n * // handle the session\n * }\n * ```\n *\n * @see {@link WebTransportServerSession} for the per-session surface.\n */\nexport class WebTransportServer {\n /** The loaded native addon, source of the `server*` command functions. */\n private readonly native: NativeAddon;\n /** Opaque native server handle returned by `serverListen`. */\n private readonly handle: NativeServerHandle;\n /** Live sessions keyed by their native session id, for event routing. */\n private readonly sessions = new Map<number, SessionCore>();\n /** Settled when the native side reports `listening`; backs {@link ready}. */\n private readonly readyD = deferred<void>();\n /**\n * Settled when the server stops (`serverClosed`) or fatally fails\n * (`serverError`); backs {@link closed}.\n */\n private readonly closedD = deferred<void>();\n /** Controller for {@link incomingSessions}; captured in its `start`. */\n private incomingController!: ReadableStreamDefaultController<WebTransportServerSession>;\n /** The UDP port actually bound, learned from the `listening` event. */\n private boundPort = 0;\n /** Guards {@link close} so shutdown is issued at most once. */\n private closeCalled = false;\n\n /**\n * The sessions clients open, delivered as they are established. Each pull\n * yields a {@link WebTransportServerSession}. The stream is closed when the\n * server stops or errors.\n */\n public readonly incomingSessions: ReadableStream<WebTransportServerSession>;\n\n /**\n * Load the native addon and start listening immediately.\n *\n * Sets up {@link incomingSessions} (capturing its controller), attaches\n * no-op catch handlers to the internal ready/closed promises so they never\n * surface as unhandled rejections, then calls the native `serverListen` with\n * the given certificate, key, host, port and reuse-port flag, wiring every\n * native event to {@link onEvent}.\n *\n * @param options - Bind address, port, certificate/key paths and reuse-port\n * flag. `host` defaults to `'0.0.0.0'` and `reusePort` defaults to `false`.\n * @see {@link ready} to await binding and {@link WebTransportServerOptions}.\n */\n public constructor(options: WebTransportServerOptions) {\n this.native = loadNative();\n void this.readyD.promise.catch(() => {});\n void this.closedD.promise.catch(() => {});\n\n this.incomingSessions = new ReadableStream<WebTransportServerSession>({\n start: (c) => {\n this.incomingController = c;\n },\n });\n\n this.handle = this.native.serverListen(\n options.cert,\n options.key,\n options.host ?? '0.0.0.0',\n options.port,\n options.reusePort ?? false,\n (ev) => this.onEvent(ev),\n );\n }\n\n /**\n * Resolves once the server is listening (the native `listening` event has\n * arrived); rejects if the server fails before it binds.\n */\n public get ready(): Promise<void> {\n return this.readyD.promise;\n }\n\n /**\n * Resolves when the server has stopped cleanly (`serverClosed`), rejects on\n * a fatal server error (`serverError`).\n */\n public get closed(): Promise<void> {\n return this.closedD.promise;\n }\n\n /** The UDP port the server is bound to (valid after {@link ready}). */\n public get port(): number {\n return this.boundPort;\n }\n\n /**\n * Stop the server and all its sessions. Idempotent: repeated calls after the\n * first are ignored. Triggers the native `serverShutdown`, which eventually\n * drives a `serverClosed` event that settles {@link closed} and finishes any\n * remaining sessions.\n */\n public close(): void {\n if (this.closeCalled) return;\n this.closeCalled = true;\n this.native.serverShutdown(this.handle);\n }\n\n /**\n * Handle one native server event. Server-level events (`listening`,\n * `serverError`, `serverClosed`) settle the server's ready/closed promises\n * and, on stop or error, finish all sessions and close\n * {@link incomingSessions}. Session-scoped events carry a `session` id: a\n * `serverReady` creates and registers a new {@link SessionCore} (attached to\n * a {@link ServerTransport}), wraps it in a {@link WebTransportServerSession}\n * and enqueues it; every session-scoped event is then dispatched to the\n * matching core.\n *\n * @param ev - The event delivered by the native `serverListen` callback.\n * @remarks Enqueue into {@link incomingSessions} is guarded: if the consumer\n * has stopped reading, the thrown error is swallowed so it cannot escape\n * the native event dispatch. On `serverError`, the `WebTransportError` is\n * created with `source: 'session'`.\n */\n private onEvent(ev: ServerNativeEvent): void {\n switch (ev.type) {\n case NativeEventType.Listening: {\n this.boundPort = ev.port;\n this.readyD.resolve();\n return;\n }\n case NativeEventType.ServerError: {\n const err = new WebTransportError(ev.message, { source: 'session' });\n this.readyD.reject(err);\n this.closedD.reject(err);\n this.finishAllSessions();\n safeCloseController(this.incomingController);\n return;\n }\n case NativeEventType.ServerClosed: {\n this.closedD.resolve();\n this.finishAllSessions();\n safeCloseController(this.incomingController);\n return;\n }\n }\n\n // Session-scoped event.\n const sessionId = ev.session;\n if (ev.type === NativeEventType.ServerReady) {\n const core = new SessionCore();\n core.attach(new ServerTransport(this.native, this.handle, sessionId));\n this.sessions.set(sessionId, core);\n void core.closed.promise.finally(() => this.sessions.delete(sessionId));\n const session = new WebTransportServerSession(core, {\n authority: ev.authority,\n path: ev.path,\n origin: ev.origin,\n headers: ev.headers,\n remoteAddress: ev.remoteAddress,\n remotePort: ev.remotePort,\n });\n try {\n this.incomingController.enqueue(session);\n } catch {\n // consumer no longer reading incoming sessions\n }\n }\n\n this.sessions.get(sessionId)?.dispatch(ev);\n }\n\n /**\n * Settle every live session when the server stops, so their `ready`/`closed`\n * promises never hang and the session map does not leak.\n *\n * @remarks Dispatches a synthetic clean `closed` event (code `0`, empty\n * reason, `remote: false`) to each session core, then clears the map. The\n * per-core `closed.finally` handler registered in {@link onEvent} would\n * also remove entries, but the map is cleared here unconditionally.\n */\n private finishAllSessions(): void {\n for (const core of this.sessions.values()) {\n core.dispatch({\n type: NativeEventType.Closed,\n code: 0,\n reason: new Uint8Array(),\n remote: false,\n });\n }\n this.sessions.clear();\n }\n}\n\n/**\n * Close a ReadableStream controller, ignoring the error thrown if it is already\n * closed. Used when the server stops or errors so shutting the incoming-session\n * stream is safe regardless of its current state.\n *\n * @param controller - Any object exposing a `close()` method (the\n * {@link WebTransportServer.incomingSessions} controller).\n * @internal Private helper, not part of the published package API.\n */\nfunction safeCloseController(controller: { close(): void }): void {\n try {\n controller.close();\n } catch {\n // already closed\n }\n}\n"],"mappings":";AAUA,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;A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EAWQ,oBAA0B;AAC9B,eAAW,QAAQ,KAAK,SAAS,OAAO,GAAG;AACvC,WAAK,SAAS;AAAA,QACV;AAAA,QACA,MAAM;AAAA,QACN,QAAQ,IAAI,WAAW;AAAA,QACvB,QAAQ;AAAA,MACZ,CAAC;AAAA,IACL;AACA,SAAK,SAAS,MAAM;AAAA,EACxB;AACJ;AAWA,SAAS,oBAAoB,YAAqC;AAC9D,MAAI;AACA,eAAW,MAAM;AAAA,EACrB,QAAQ;AAAA,EAER;AACJ;","names":["require","err","deferred"]}
1
+ {"version":3,"sources":["../src/loader.ts","../src/errors.ts","../src/native.ts","../src/datagrams.ts","../src/streams.ts","../src/webtransport.ts","../src/server.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n//! Locates and loads the rwebtransport native addon.\n//!\n//! Resolution order:\n//! 1. A prebuilt binary at `prebuilds/<platform>-<arch>/rwebtransport.node`.\n//! 2. If none is found, compile the Rust crate on the fly via `scripts/build.js`\n//! (requires a Rust toolchain + cmake + C/C++ compiler) and load the result.\n//!\n//! Only Node 24 and Node 26 are supported.\n\nimport { createRequire } from 'node:module';\nimport { execFileSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { NativeAddon } from './native.js';\n\n/**\n * A CommonJS-style `require` synthesized from this ES module's URL. Native\n * addons (`.node` files) are loaded through `require`, which understands the\n * platform binary format, rather than the ESM `import` machinery.\n *\n * @internal\n */\nconst require = createRequire(import.meta.url);\n\n/**\n * Absolute path of the directory containing this compiled module, resolved from\n * `import.meta.url`. Used as the anchor for locating package resources.\n *\n * @internal\n */\nconst moduleDir = dirname(fileURLToPath(import.meta.url));\n\n/**\n * The package root (one level up from the bundled `dist/` directory). All\n * runtime asset lookups (prebuilt binaries, the build script) are resolved\n * relative to this directory.\n *\n * @internal\n */\nconst PACKAGE_ROOT = join(moduleDir, '..');\n\n/**\n * Guard that aborts loading on an unsupported Node.js runtime. Only Node 24 and\n * Node 26 major versions are supported; anything else means the native ABI may\n * not match.\n *\n * @throws {Error} If the running Node major version is neither 24 nor 26.\n * @internal\n */\nfunction assertSupportedRuntime(): void {\n const major = Number(process.versions.node.split('.')[0]);\n if (major !== 24 && major !== 26) {\n throw new Error(\n `rwebtransport supports Node 24 and Node 26 only; this is Node ${process.versions.node}.`,\n );\n }\n}\n\n/**\n * Compute the expected location of the prebuilt native addon for the current\n * platform and architecture, namely\n * `prebuilds/<process.platform>-<process.arch>/rwebtransport.node` under the\n * package root.\n *\n * @returns The absolute path to the platform-specific prebuilt `.node` file.\n * The file is not guaranteed to exist; callers check separately.\n * @internal\n */\nfunction prebuiltPath(): string {\n return join(\n PACKAGE_ROOT,\n 'prebuilds',\n `${process.platform}-${process.arch}`,\n 'rwebtransport.node',\n );\n}\n\n/**\n * Memoized addon instance. Populated on the first successful {@link loadNative}\n * call and returned directly by all subsequent calls; `undefined` until then.\n *\n * @internal\n */\nlet cached: NativeAddon | undefined;\n\n/**\n * Locate, load, and cache the rwebtransport native addon.\n *\n * @remarks\n * On the first call the resolution proceeds as follows:\n * 1. Return early if a previous call already cached the addon.\n * 2. Assert the runtime is Node 24 or 26 (see {@link assertSupportedRuntime}).\n * 3. If a prebuilt binary exists for this platform and architecture, `require`\n * it, cache it, and return it.\n * 4. Otherwise fall back to compiling from source: run `scripts/build.js` with\n * the current Node executable (working directory set to the package root\n * and stdio inherited, so the compile output is streamed to the caller's\n * console), then `require` and cache the freshly produced binary. A notice\n * is written to `process.stderr` before the (one-time) build begins.\n *\n * Every later call short-circuits on the cached instance without re-checking the\n * runtime or the filesystem.\n *\n * @returns The loaded {@link NativeAddon}: the raw function surface exported by\n * `rwebtransport.node`.\n * @throws {Error} If the runtime is an unsupported Node.js version.\n * @throws {Error} If no prebuilt binary exists and `scripts/build.js` is absent,\n * so no binary can be compiled.\n * @throws {Error} If the on-the-fly build runs but does not produce the expected\n * binary. `execFileSync` additionally propagates if the build\n * process itself exits non-zero, and `require` propagates if the\n * resulting binary cannot be loaded.\n * @see {@link NativeAddon} for the shape of the returned object.\n * @internal\n */\nexport function loadNative(): NativeAddon {\n if (cached) return cached;\n assertSupportedRuntime();\n\n const prebuilt = prebuiltPath();\n if (existsSync(prebuilt)) {\n cached = require(prebuilt) as NativeAddon;\n return cached;\n }\n\n // Fallback: compile from source.\n const builder = join(PACKAGE_ROOT, 'scripts', 'build.js');\n if (!existsSync(builder)) {\n throw new Error(\n `rwebtransport: no prebuilt binary at ${prebuilt} and no build script to compile one. ` +\n `Reinstall the package or build it manually (npm run build:rust).`,\n );\n }\n process.stderr.write(\n 'rwebtransport: no prebuilt binary for this platform; compiling the native addon (this happens once)...\\n',\n );\n execFileSync(process.execPath, [builder], { cwd: PACKAGE_ROOT, stdio: 'inherit' });\n\n if (!existsSync(prebuilt)) {\n throw new Error(`rwebtransport: build completed but ${prebuilt} was not produced.`);\n }\n cached = require(prebuilt) as NativeAddon;\n return cached;\n}\n","// SPDX-License-Identifier: Apache-2.0\n//! The `WebTransportError` type, matching the W3C interface.\n\n/**\n * Identifies which part of the transport a {@link WebTransportError} came from.\n *\n * @remarks\n * Mirrors the `source` attribute of the W3C `WebTransportError` interface.\n * `'stream'` means the failure was raised by an individual send or receive\n * stream (for example a stream reset), while `'session'` means it applies to\n * the whole WebTransport session (for example the connection closing).\n *\n * @see {@link WebTransportError.source}\n */\nexport type WebTransportErrorSource = 'stream' | 'session';\n\n/**\n * Optional settings passed to the {@link WebTransportError} constructor.\n *\n * @remarks\n * Both fields are optional; the constructor applies defaults when they are\n * omitted. Corresponds to the `WebTransportErrorOptions` dictionary in the\n * W3C WebTransport specification.\n */\nexport interface WebTransportErrorOptions {\n /**\n * Which part of the transport the error originated from.\n *\n * @defaultValue `'session'` (applied by the constructor when omitted)\n * @see {@link WebTransportErrorSource}\n */\n source?: WebTransportErrorSource;\n /**\n * The application-supplied error code carried by a stream reset, or `null`\n * when the error is not associated with a specific stream error code.\n *\n * @defaultValue `null` (applied by the constructor when omitted)\n */\n streamErrorCode?: number | null;\n}\n\n/**\n * Error thrown / rejected for WebTransport failures, mirroring the browser\n * `WebTransportError`.\n *\n * @remarks\n * Extends the built-in {@link Error}. Instances are surfaced when a session or\n * stream fails, for example as the rejection reason of a pending promise or as\n * the error a {@link ReadableStream} / {@link WritableStream} is aborted with.\n * The constructor re-applies the prototype via {@link Object.setPrototypeOf}\n * so that `instanceof WebTransportError` works even when the class is\n * transpiled down to an ES5-style constructor function.\n *\n * @example\n * ```ts\n * throw new WebTransportError('stream reset', {\n * source: 'stream',\n * streamErrorCode: 42,\n * });\n * ```\n *\n * @see {@link WebTransportErrorOptions}\n */\nexport class WebTransportError extends Error {\n /** Whether the error originated from a stream or the session as a whole. */\n public readonly source: WebTransportErrorSource;\n /** The application error code, if the error came from a stream reset. */\n public readonly streamErrorCode: number | null;\n\n /**\n * Creates a new {@link WebTransportError}.\n *\n * @param message - Human-readable description of the failure. When omitted,\n * the message defaults to the string `'WebTransport error'`.\n * @param options - Optional {@link WebTransportErrorOptions}; defaults to an\n * empty object so that both fields fall back to their own defaults.\n *\n * @remarks\n * Sets {@link Error.name} to `'WebTransportError'`, resolves\n * {@link WebTransportError.source} (defaulting to `'session'`) and\n * {@link WebTransportError.streamErrorCode} (defaulting to `null`), then\n * restores the prototype chain with {@link Object.setPrototypeOf} so\n * `instanceof` checks succeed under downlevel compilation.\n */\n public constructor(message?: string, options: WebTransportErrorOptions = {}) {\n super(message ?? 'WebTransport error');\n this.name = 'WebTransportError';\n this.source = options.source ?? 'session';\n this.streamErrorCode = options.streamErrorCode ?? null;\n Object.setPrototypeOf(this, WebTransportError.prototype);\n }\n}\n","// SPDX-License-Identifier: Apache-2.0\n//! Typed view of the native addon and the event dispatcher that turns its\n//! low-level, callback-based ABI into promises and per-stream sinks.\n\nimport { loadNative } from './loader.js';\nimport { WebTransportError } from './errors.js';\nimport type { WebTransportCloseInfo, WebTransportConnectionStats } from './types.js';\n\n/**\n * Opaque handle to a native client session (a neon `JsBox`).\n *\n * @remarks\n * Returned by {@link NativeAddon.connect} and passed back into every\n * per-session native call so the addon can find the session's driver thread.\n * The `__brand` field is a compile-time nominal marker only: there is no such\n * property at runtime, and its purpose is to keep a client handle from being\n * confused with a {@link NativeServerHandle} or a plain object.\n * @internal\n */\nexport type NativeHandle = { readonly __brand: 'rwt-session' };\n\n/**\n * Opaque handle to a native server (a neon `JsBox`).\n *\n * @remarks\n * Returned by {@link NativeAddon.serverListen} and passed back into every\n * `server*` native call, together with a numeric session id, to target one of\n * the server's active sessions. Like {@link NativeHandle}, `__brand` is a\n * compile-time-only nominal marker.\n * @internal\n */\nexport type NativeServerHandle = { readonly __brand: 'rwt-server' };\n\n/**\n * The `type` discriminant shared by every {@link NativeEvent} and\n * {@link ServerNativeEvent}.\n *\n * @remarks\n * The string values are the exact wire contract emitted by the native addon, so\n * they must not be changed. Using an enum (rather than bare string literals)\n * gives the TypeScript layer a single, referenceable source of truth for the\n * event kinds.\n * @internal\n */\nexport enum NativeEventType {\n /** A client session's Extended CONNECT completed and it is established. */\n Ready = 'ready',\n /** The peer sent DRAIN_WEBTRANSPORT_SESSION (going away soon, still usable). */\n Draining = 'draining',\n /** A server session was established (a valid CONNECT arrived, answered 200). */\n ServerReady = 'serverReady',\n /** The session ended. */\n Closed = 'closed',\n /** The session failed with an error message. */\n Error = 'error',\n /** An inbound datagram payload arrived. */\n Datagram = 'datagram',\n /** The peer opened a stream. */\n Stream = 'stream',\n /** Inbound application bytes arrived on an existing stream. */\n StreamData = 'streamData',\n /** The peer finished (FIN) its side of a stream. */\n StreamFin = 'streamFin',\n /** The peer reset a stream. */\n StreamReset = 'streamReset',\n /** The peer sent STOP_SENDING for a stream. */\n StreamStopSending = 'streamStopSending',\n /** Acknowledges a locally requested {@link NativeAddon.openStream}. */\n StreamOpened = 'streamOpened',\n /** Acknowledges a {@link NativeAddon.writeStream} (the backpressure signal). */\n WriteAck = 'writeAck',\n /** Acknowledges a {@link NativeAddon.sendDatagram}. */\n DatagramAck = 'datagramAck',\n /** Result of a {@link NativeAddon.getStats} request. */\n Stats = 'stats',\n /** Result of a {@link NativeAddon.exportKeyingMaterial} request. */\n KeyingMaterial = 'keyingMaterial',\n /** Server level: the listener is bound (carries the port). */\n Listening = 'listening',\n /** Server level: a fatal server failure. */\n ServerError = 'serverError',\n /** Server level: the server stopped. */\n ServerClosed = 'serverClosed',\n}\n\n/**\n * The client session's Extended CONNECT completed and the session is established.\n * @internal\n */\nexport interface NativeReadyEvent {\n /** Discriminant. */\n type: NativeEventType.Ready;\n /** The negotiated subprotocol (from `wt-protocol`), or `null` if none. */\n protocol: string | null;\n /** The CONNECT 2xx response headers, as ordered `[name, value]` pairs. */\n responseHeaders: [string, string][];\n}\n\n/**\n * The peer sent a DRAIN_WEBTRANSPORT_SESSION capsule.\n * @internal\n */\nexport interface NativeDrainingEvent {\n /** Discriminant. */\n type: NativeEventType.Draining;\n}\n\n/**\n * A server session was established. Carries the client's CONNECT request\n * metadata and the client's remote address at establishment.\n * @internal\n */\nexport interface NativeServerReadyEvent {\n /** Discriminant. */\n type: NativeEventType.ServerReady;\n /** The `:authority` pseudo-header of the client's CONNECT request. */\n authority: string;\n /** The `:path` pseudo-header of the client's CONNECT request. */\n path: string;\n /** The `origin` header value, or `null` if the client sent none. */\n origin: string | null;\n /** Any additional (non-pseudo) request headers, keyed by header name. */\n headers: Record<string, string>;\n /** The subprotocols the client offered (from `wt-available-protocols`). */\n requestedProtocols: string[];\n /** The subprotocol the server selected (echoed in `wt-protocol`), or `null`. */\n protocol: string | null;\n /** The client's remote IP address at session establishment. */\n remoteAddress: string;\n /** The client's remote UDP port at session establishment. */\n remotePort: number;\n}\n\n/**\n * The session ended. `code`/`reason` are the WebTransport close code and UTF-8\n * encoded reason; `remote` is true when the peer initiated the close.\n * @internal\n */\nexport interface NativeClosedEvent {\n /** Discriminant. */\n type: NativeEventType.Closed;\n /** The WebTransport close code. */\n code: number;\n /** The UTF-8 encoded close reason. */\n reason: Uint8Array;\n /** True when the peer initiated the close. */\n remote: boolean;\n}\n\n/**\n * The session failed with the given message.\n * @internal\n */\nexport interface NativeErrorEvent {\n /** Discriminant. */\n type: NativeEventType.Error;\n /** Human-readable failure message. */\n message: string;\n}\n\n/**\n * An inbound datagram payload.\n * @internal\n */\nexport interface NativeDatagramEvent {\n /** Discriminant. */\n type: NativeEventType.Datagram;\n /** The received datagram bytes. */\n data: Uint8Array;\n}\n\n/**\n * The peer opened a stream.\n * @internal\n */\nexport interface NativeStreamEvent {\n /** Discriminant. */\n type: NativeEventType.Stream;\n /** The id of the newly opened stream. */\n streamId: number;\n /** True for a bidirectional stream, false for a unidirectional one. */\n bidi: boolean;\n}\n\n/**\n * Inbound application bytes on an existing stream.\n * @internal\n */\nexport interface NativeStreamDataEvent {\n /** Discriminant. */\n type: NativeEventType.StreamData;\n /** The stream the bytes arrived on. */\n streamId: number;\n /** The received bytes. */\n data: Uint8Array;\n}\n\n/**\n * The peer finished (FIN) its side of a stream.\n * @internal\n */\nexport interface NativeStreamFinEvent {\n /** Discriminant. */\n type: NativeEventType.StreamFin;\n /** The stream that was finished. */\n streamId: number;\n}\n\n/**\n * The peer reset a stream.\n * @internal\n */\nexport interface NativeStreamResetEvent {\n /** Discriminant. */\n type: NativeEventType.StreamReset;\n /** The stream that was reset. */\n streamId: number;\n /** The application error code the peer sent. */\n code: number;\n}\n\n/**\n * The peer sent STOP_SENDING for a stream.\n * @internal\n */\nexport interface NativeStreamStopSendingEvent {\n /** Discriminant. */\n type: NativeEventType.StreamStopSending;\n /** The stream the peer asked us to stop sending on. */\n streamId: number;\n /** The application error code the peer sent. */\n code: number;\n}\n\n/**\n * Acknowledges a locally requested {@link NativeAddon.openStream}, pairing the\n * JS-generated `requestId` with the assigned stream id.\n * @internal\n */\nexport interface NativeStreamOpenedEvent {\n /** Discriminant. */\n type: NativeEventType.StreamOpened;\n /** The request id passed to {@link NativeAddon.openStream}. */\n requestId: number;\n /** The stream id the native side assigned. */\n streamId: number;\n}\n\n/**\n * Acknowledges a {@link NativeAddon.writeStream}: the bytes have been flushed\n * into quiche. This is the write backpressure signal.\n * @internal\n */\nexport interface NativeWriteAckEvent {\n /** Discriminant. */\n type: NativeEventType.WriteAck;\n /** The request id passed to {@link NativeAddon.writeStream}. */\n requestId: number;\n}\n\n/**\n * Acknowledges a {@link NativeAddon.sendDatagram}.\n * @internal\n */\nexport interface NativeDatagramAckEvent {\n /** Discriminant. */\n type: NativeEventType.DatagramAck;\n /** The request id passed to {@link NativeAddon.sendDatagram}. */\n requestId: number;\n /**\n * False when the datagram was dropped instead of sent (for example the\n * session was not ready or the payload exceeded the current flight size).\n */\n sent: boolean;\n}\n\n/**\n * The result of a {@link NativeAddon.getStats} request, keyed by `requestId`.\n * @internal\n */\nexport interface NativeStatsEvent {\n /** Discriminant. */\n type: NativeEventType.Stats;\n /** The request id passed to {@link NativeAddon.getStats}. */\n requestId: number;\n /** Total bytes sent. */\n bytesSent: number;\n /** Total bytes received. */\n bytesReceived: number;\n /** QUIC packets sent. */\n packetsSent: number;\n /** QUIC packets received. */\n packetsReceived: number;\n /** QUIC packets declared lost. */\n packetsLost: number;\n /** Smoothed RTT in milliseconds. */\n smoothedRtt: number;\n /** RTT variation in milliseconds. */\n rttVariation: number;\n /** Minimum observed RTT in milliseconds. */\n minRtt: number;\n}\n\n/**\n * The result of a {@link NativeAddon.exportKeyingMaterial} request, keyed by\n * `requestId`.\n * @internal\n */\nexport interface NativeKeyingMaterialEvent {\n /** Discriminant. */\n type: NativeEventType.KeyingMaterial;\n /** The request id passed to {@link NativeAddon.exportKeyingMaterial}. */\n requestId: number;\n /** True if the export succeeded; false if the TLS export failed. */\n ok: boolean;\n /** The exported keying material, present only when `ok` is true. */\n data?: Uint8Array;\n}\n\n/**\n * Events delivered by the native addon to a client session's, or one server\n * session's, `onEvent` callback.\n *\n * @remarks\n * A discriminated union keyed on {@link NativeEventType}. Each session receives\n * its own stream of these, dispatched by {@link SessionCore.dispatch}.\n * @internal\n */\nexport type NativeEvent =\n | NativeReadyEvent\n | NativeDrainingEvent\n | NativeServerReadyEvent\n | NativeClosedEvent\n | NativeErrorEvent\n | NativeDatagramEvent\n | NativeStreamEvent\n | NativeStreamDataEvent\n | NativeStreamFinEvent\n | NativeStreamResetEvent\n | NativeStreamStopSendingEvent\n | NativeStreamOpenedEvent\n | NativeWriteAckEvent\n | NativeDatagramAckEvent\n | NativeStatsEvent\n | NativeKeyingMaterialEvent;\n\n/**\n * The raw function surface exported by `rwebtransport.node`.\n *\n * @remarks\n * This interface is the TypeScript view of the neon addon and is implemented by\n * native code, not by any TS class. Client-facing calls take a\n * {@link NativeHandle}; server-facing calls (prefixed `server`) take a\n * {@link NativeServerHandle} plus a numeric session id. Asynchronous results are\n * not returned directly: they arrive later as {@link NativeEvent}s on the\n * `onEvent` callback, correlated to the originating call by a JS-generated\n * `requestId`.\n * @see The native ABI notes for the exact wire contract.\n * @internal\n */\nexport interface NativeAddon {\n /**\n * Open a client session by performing a QUIC handshake and WebTransport\n * Extended CONNECT to `url`, spawning a background driver thread.\n *\n * @param url - The `https://host:port/path` session URL.\n * @param hashes - SHA-256 certificate pins as 32-byte arrays; when non-empty,\n * a matching certificate is accepted and normal CA/hostname validation is\n * bypassed.\n * @param insecure - Disable all certificate verification (development only).\n * @param origin - Value for the `origin` request header, or null to omit it.\n * @param headerNames - Additional request header names (parallel to `headerValues`).\n * @param headerValues - Additional request header values (parallel to `headerNames`).\n * @param onEvent - Callback invoked for every subsequent session event.\n * @returns An opaque handle to the new session.\n * @throws Synchronously on setup failures such as a malformed URL, DNS\n * resolution failure, socket bind failure, or invalid configuration.\n */\n connect(\n url: string,\n hashes: Uint8Array[],\n insecure: boolean,\n origin: string | null,\n headerNames: string[],\n headerValues: string[],\n protocols: string[],\n onEvent: (ev: NativeEvent) => void,\n ): NativeHandle;\n /**\n * Request a new outbound stream. The result arrives asynchronously as a\n * `streamOpened` event carrying the same `requestId` and the assigned stream id.\n *\n * @param handle - The session handle.\n * @param bidi - True for a bidirectional stream, false for send-only unidirectional.\n * @param requestId - JS-generated id used to correlate the `streamOpened` event.\n */\n openStream(handle: NativeHandle, bidi: boolean, requestId: number): void;\n /**\n * Queue `bytes` for sending on `streamId`. A `writeAck` event with the same\n * `requestId` fires once the bytes are flushed into quiche's send buffer,\n * which is the backpressure signal used to resolve the write promise.\n *\n * @param handle - The session handle.\n * @param streamId - The target stream id.\n * @param bytes - The payload to send.\n * @param requestId - JS-generated id used to correlate the `writeAck` event.\n */\n writeStream(handle: NativeHandle, streamId: number, bytes: Uint8Array, requestId: number): void;\n /**\n * Finish (half-close) the send side of `streamId`, sending a QUIC FIN.\n *\n * @param handle - The session handle.\n * @param streamId - The stream to finish.\n */\n finStream(handle: NativeHandle, streamId: number): void;\n /**\n * Abruptly reset the send side of `streamId` with the given application error code.\n *\n * @param handle - The session handle.\n * @param streamId - The stream to reset.\n * @param code - The application error code (unsigned 32-bit).\n */\n resetStream(handle: NativeHandle, streamId: number, code: number): void;\n /**\n * Ask the peer to stop sending on `streamId` (QUIC STOP_SENDING) with the\n * given application error code.\n *\n * @param handle - The session handle.\n * @param streamId - The stream whose inbound half should be stopped.\n * @param code - The application error code (unsigned 32-bit).\n */\n stopSending(handle: NativeHandle, streamId: number, code: number): void;\n /**\n * Toggle read backpressure on `streamId`. When paused, the native side stops\n * draining quiche's receive buffer, which flow-controls the peer.\n *\n * @param handle - The session handle.\n * @param streamId - The receive stream to pause or resume.\n * @param paused - True to pause draining, false to resume.\n */\n setPaused(handle: NativeHandle, streamId: number, paused: boolean): void;\n /**\n * Send a datagram. A `datagramAck` event with the same `requestId` reports\n * whether it was actually sent.\n *\n * @param handle - The session handle.\n * @param bytes - The datagram payload.\n * @param requestId - JS-generated id used to correlate the `datagramAck` event.\n */\n sendDatagram(handle: NativeHandle, bytes: Uint8Array, requestId: number): void;\n /**\n * @param handle - The session handle.\n * @returns The maximum datagram payload size currently permitted, in bytes\n * (0 when datagrams cannot be sent).\n */\n maxDatagramSize(handle: NativeHandle): number;\n /**\n * @param handle - The session handle.\n * @returns Whether the session has been established (synchronous, via shared atomics).\n */\n isReady(handle: NativeHandle): boolean;\n /**\n * @param handle - The session handle.\n * @returns Whether the session has closed (synchronous, via shared atomics).\n */\n isClosed(handle: NativeHandle): boolean;\n /**\n * Gracefully close the session: send a CLOSE_WEBTRANSPORT_SESSION capsule and\n * FIN the CONNECT stream, then close the QUIC connection.\n *\n * @param handle - The session handle.\n * @param code - The WebTransport close code (unsigned 32-bit).\n * @param reason - The UTF-8 encoded close reason.\n */\n closeSession(handle: NativeHandle, code: number, reason: Uint8Array): void;\n /** Send a DRAIN_WEBTRANSPORT_SESSION capsule to the peer. */\n drain(handle: NativeHandle): void;\n /** Request connection stats; the result arrives as a `stats` event. */\n getStats(handle: NativeHandle, requestId: number): void;\n /**\n * Export TLS keying material (RFC 5705); the result arrives as a\n * `keyingMaterial` event.\n *\n * @param handle - The session handle.\n * @param requestId - Correlates the reply event.\n * @param label - The exporter label bytes.\n * @param context - The exporter context bytes (may be empty).\n * @param length - Number of bytes of keying material to produce.\n */\n exportKeyingMaterial(\n handle: NativeHandle,\n requestId: number,\n label: Uint8Array,\n context: Uint8Array,\n length: number,\n ): void;\n /**\n * Tear down the session's driver thread. Called on close; the native\n * finalizer also invokes it as a safety net.\n *\n * @param handle - The session handle.\n */\n shutdown(handle: NativeHandle): void;\n\n /**\n * Start a WebTransport server: bind a UDP socket and begin accepting sessions.\n *\n * @param certPath - Path to the PEM certificate chain file.\n * @param keyPath - Path to the PEM private-key file.\n * @param host - Interface address to bind.\n * @param port - UDP port to bind (0 lets the OS choose; read it back from the\n * `listening` event).\n * @param reusePort - Bind with `SO_REUSEPORT` (Unix only) to share a port\n * across processes.\n * @param onEvent - Callback invoked for server-level and session-scoped events.\n * @returns An opaque handle to the server.\n */\n serverListen(\n certPath: string,\n keyPath: string,\n host: string,\n port: number,\n reusePort: boolean,\n supportedProtocols: string[],\n allowedOrigins: string[] | null,\n responseHeaderNames: string[],\n responseHeaderValues: string[],\n onEvent: (ev: ServerNativeEvent) => void,\n ): NativeServerHandle;\n /**\n * Server-side {@link openStream}: request a new outbound stream on the given\n * session.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param bidi - True for bidirectional, false for send-only unidirectional.\n * @param requestId - JS-generated id used to correlate the `streamOpened` event.\n */\n serverOpenStream(\n handle: NativeServerHandle,\n session: number,\n bidi: boolean,\n requestId: number,\n ): void;\n /**\n * Server-side {@link writeStream}: queue bytes on a session's stream.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param streamId - The target stream id.\n * @param bytes - The payload to send.\n * @param requestId - JS-generated id used to correlate the `writeAck` event.\n */\n serverWrite(\n handle: NativeServerHandle,\n session: number,\n streamId: number,\n bytes: Uint8Array,\n requestId: number,\n ): void;\n /**\n * Server-side {@link finStream}: finish the send side of a session's stream.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param streamId - The stream to finish.\n */\n serverFin(handle: NativeServerHandle, session: number, streamId: number): void;\n /**\n * Server-side {@link resetStream}: reset the send side of a session's stream.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param streamId - The stream to reset.\n * @param code - The application error code (unsigned 32-bit).\n */\n serverReset(handle: NativeServerHandle, session: number, streamId: number, code: number): void;\n /**\n * Server-side {@link stopSending}: ask the peer to stop sending on a session's stream.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param streamId - The stream whose inbound half should be stopped.\n * @param code - The application error code (unsigned 32-bit).\n */\n serverStopSending(\n handle: NativeServerHandle,\n session: number,\n streamId: number,\n code: number,\n ): void;\n /**\n * Server-side {@link setPaused}: toggle read backpressure on a session's stream.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param streamId - The receive stream to pause or resume.\n * @param paused - True to pause draining, false to resume.\n */\n serverSetPaused(\n handle: NativeServerHandle,\n session: number,\n streamId: number,\n paused: boolean,\n ): void;\n /**\n * Server-side {@link sendDatagram}: send a datagram on a session.\n *\n * @param handle - The server handle.\n * @param session - The target session id.\n * @param bytes - The datagram payload.\n * @param requestId - JS-generated id used to correlate the `datagramAck` event.\n */\n serverSendDatagram(\n handle: NativeServerHandle,\n session: number,\n bytes: Uint8Array,\n requestId: number,\n ): void;\n /**\n * Server-side {@link maxDatagramSize}.\n *\n * @param handle - The server handle.\n * @returns The maximum datagram payload size currently permitted, in bytes.\n */\n serverMaxDatagramSize(handle: NativeServerHandle): number;\n /**\n * Server-side {@link closeSession}: gracefully close one session.\n *\n * @param handle - The server handle.\n * @param session - The session id to close.\n * @param code - The WebTransport close code (unsigned 32-bit).\n * @param reason - The UTF-8 encoded close reason.\n */\n serverCloseSession(\n handle: NativeServerHandle,\n session: number,\n code: number,\n reason: Uint8Array,\n ): void;\n /** Send a DRAIN_WEBTRANSPORT_SESSION capsule to one session's peer. */\n serverDrain(handle: NativeServerHandle, session: number): void;\n /** Request one session's connection stats; the result arrives as a `stats` event. */\n serverGetStats(handle: NativeServerHandle, session: number, requestId: number): void;\n /**\n * Export TLS keying material (RFC 5705) for one session; the result arrives\n * as a `keyingMaterial` event.\n */\n serverExportKeyingMaterial(\n handle: NativeServerHandle,\n session: number,\n requestId: number,\n label: Uint8Array,\n context: Uint8Array,\n length: number,\n ): void;\n /**\n * Stop the server, closing all its sessions and freeing the listening socket.\n *\n * @param handle - The server handle.\n */\n serverShutdown(handle: NativeServerHandle): void;\n}\n\n/**\n * Server level: the listener is bound and accepting packets.\n * @internal\n */\nexport interface NativeListeningEvent {\n /** Discriminant. */\n type: NativeEventType.Listening;\n /** The UDP port the server actually bound. */\n port: number;\n}\n\n/**\n * Server level: a fatal server failure (for example a bind or certificate error).\n * @internal\n */\nexport interface NativeServerErrorEvent {\n /** Discriminant. */\n type: NativeEventType.ServerError;\n /** Human-readable failure message. */\n message: string;\n}\n\n/**\n * Server level: the server stopped.\n * @internal\n */\nexport interface NativeServerClosedEvent {\n /** Discriminant. */\n type: NativeEventType.ServerClosed;\n}\n\n/**\n * Server-level events, plus every {@link NativeEvent} widened with a numeric\n * `session` id.\n *\n * @remarks\n * The `session` field identifies which of the server's sessions a session-scoped\n * event belongs to, so the server can demultiplex a single `onEvent` stream\n * across all its active sessions.\n * @internal\n */\nexport type ServerNativeEvent =\n | NativeListeningEvent\n | NativeServerErrorEvent\n | NativeServerClosedEvent\n | (NativeEvent & { session: number });\n\n/**\n * Normalized inputs for opening a session.\n *\n * @remarks\n * Produced by the client `WebTransport` layer from user-facing options and\n * passed straight through to {@link NativeAddon.connect} by\n * {@link createClientSession}. The header arrays are parallel (`headerNames[i]`\n * pairs with `headerValues[i]`).\n * @internal\n */\nexport interface ConnectConfig {\n /** The `https://host:port/path` session URL. */\n url: string;\n /** SHA-256 certificate pins as 32-byte arrays; empty when none are pinned. */\n hashes: Uint8Array[];\n /** Disable all certificate verification (development only). */\n insecure: boolean;\n /** Value for the `origin` request header, or null to omit it. */\n origin: string | null;\n /** Additional request header names, parallel to {@link ConnectConfig.headerValues}. */\n headerNames: string[];\n /** Additional request header values, parallel to {@link ConnectConfig.headerNames}. */\n headerValues: string[];\n /** WebTransport subprotocols to offer (preference order); empty for none. */\n protocols: string[];\n}\n\n/**\n * Consumer of a receive stream's inbound events.\n *\n * @remarks\n * Registered per stream via {@link SessionCore.registerReceive}. The stream\n * layer implements this to feed a WHATWG `ReadableStream` controller.\n * @internal\n */\nexport interface ReceiveSink {\n /**\n * A chunk of stream data arrived.\n *\n * @param chunk - The received bytes.\n */\n onData(chunk: Uint8Array): void;\n /** The peer finished (FIN) the stream; no more data will arrive. */\n onFin(): void;\n /**\n * The peer reset the stream.\n *\n * @param code - The application error code from the reset.\n */\n onReset(code: number): void;\n /**\n * The session terminated, taking this stream with it. Distinct from a peer\n * stream reset: the error is session-sourced, not a per-stream reset code.\n *\n * @param error - The session-terminal error to fail the stream with.\n */\n onSessionClose(error: WebTransportError): void;\n}\n\n/**\n * Consumer of a send stream's control events.\n *\n * @remarks\n * Registered per stream via {@link SessionCore.registerSend}. The stream layer\n * implements this to error its WHATWG `WritableStream` controller.\n * @internal\n */\nexport interface SendSink {\n /**\n * The peer asked to stop receiving (QUIC STOP_SENDING).\n *\n * @param code - The application error code the peer supplied.\n */\n onStopSending(code: number): void;\n /**\n * The session terminated, taking this stream with it. Distinct from a peer\n * STOP_SENDING: the error is session-sourced, not a per-stream code.\n *\n * @param error - The session-terminal error to fail the stream with.\n */\n onSessionClose(error: WebTransportError): void;\n}\n\n/**\n * Consumer of peer-initiated streams.\n *\n * @remarks\n * A single handler per session, set via {@link SessionCore.setIncomingHandler};\n * invoked when the peer opens a new stream.\n * @internal\n */\nexport interface IncomingHandler {\n /**\n * The peer opened a bidirectional stream.\n *\n * @param streamId - The new stream's id.\n */\n onBidi(streamId: number): void;\n /**\n * The peer opened a unidirectional (receive-only) stream.\n *\n * @param streamId - The new stream's id.\n */\n onUni(streamId: number): void;\n}\n\n/**\n * Consumer of inbound datagrams.\n *\n * @remarks\n * A single sink per session, set via {@link SessionCore.setDatagramSink};\n * invoked with each datagram payload as it arrives.\n * @param data - The datagram payload.\n * @internal\n */\nexport type DatagramSink = (data: Uint8Array) => void;\n\n/**\n * A promise bundled with its own `resolve`/`reject` functions.\n *\n * @typeParam T - The value the promise resolves to.\n * @remarks\n * Used to correlate a native acknowledgement event (which arrives later) with\n * the caller awaiting it.\n * @internal\n */\ninterface Deferred<T> {\n /** The pending promise handed to the awaiter. */\n promise: Promise<T>;\n /** Settles {@link Deferred.promise} with a value. */\n resolve: (value: T) => void;\n /** Rejects {@link Deferred.promise} with a reason. */\n reject: (reason: unknown) => void;\n}\n\n/**\n * Create a {@link Deferred}: a promise together with externally callable\n * `resolve` and `reject`.\n *\n * @typeParam T - The value the promise resolves to.\n * @returns The bundled promise and its settle functions.\n * @internal\n */\nfunction deferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n\n/**\n * The low-level per-session command surface. Implemented by a client transport\n * (native session handle) or a server transport (server handle + session id), so\n * the same {@link SessionCore} drives both roles.\n *\n * @remarks\n * These methods are fire-and-forget: their outcomes come back later as\n * {@link NativeEvent}s that {@link SessionCore.dispatch} routes to the awaiting\n * promises and sinks.\n * @internal\n */\nexport interface SessionTransport {\n /**\n * Request a new outbound stream.\n *\n * @param bidi - True for bidirectional, false for send-only unidirectional.\n * @param requestId - Id correlating the eventual `streamOpened` event.\n */\n openStream(bidi: boolean, requestId: number): void;\n /**\n * Queue bytes for sending on a stream.\n *\n * @param streamId - The target stream id.\n * @param bytes - The payload.\n * @param requestId - Id correlating the eventual `writeAck` event.\n */\n write(streamId: number, bytes: Uint8Array, requestId: number): void;\n /**\n * Finish (half-close) the send side of a stream.\n *\n * @param streamId - The stream to finish.\n */\n fin(streamId: number): void;\n /**\n * Reset the send side of a stream.\n *\n * @param streamId - The stream to reset.\n * @param code - The application error code.\n */\n reset(streamId: number, code: number): void;\n /**\n * Ask the peer to stop sending on a stream.\n *\n * @param streamId - The stream whose inbound half should be stopped.\n * @param code - The application error code.\n */\n stopSending(streamId: number, code: number): void;\n /**\n * Toggle read backpressure on a stream.\n *\n * @param streamId - The receive stream.\n * @param paused - True to pause draining, false to resume.\n */\n setPaused(streamId: number, paused: boolean): void;\n /**\n * Send a datagram.\n *\n * @param bytes - The datagram payload.\n * @param requestId - Id correlating the eventual `datagramAck` event.\n */\n sendDatagram(bytes: Uint8Array, requestId: number): void;\n /** @returns The maximum datagram payload size, in bytes. */\n maxDatagramSize(): number;\n /**\n * Gracefully close the session.\n *\n * @param code - The WebTransport close code.\n * @param reason - The UTF-8 encoded close reason.\n */\n closeSession(code: number, reason: Uint8Array): void;\n /** Send a DRAIN_WEBTRANSPORT_SESSION capsule to the peer. */\n drain(): void;\n /** Request connection stats; the result arrives as a `stats` event. */\n getStats(requestId: number): void;\n /**\n * Export TLS keying material (RFC 5705); the result arrives as a\n * `keyingMaterial` event.\n *\n * @param requestId - Id correlating the eventual `keyingMaterial` event.\n * @param label - The exporter label bytes.\n * @param context - The exporter context bytes (may be empty).\n * @param length - Number of bytes of keying material to produce.\n */\n exportKeyingMaterial(\n requestId: number,\n label: Uint8Array,\n context: Uint8Array,\n length: number,\n ): void;\n /** Tear down the session's native resources. */\n shutdown(): void;\n}\n\n/**\n * Dispatches native events to promises / sinks and issues commands through an\n * injected {@link SessionTransport}. Exactly one `SessionCore` backs one\n * WebTransport session (client or server side).\n *\n * @remarks\n * The higher layers ({@link WebTransportReceiveStream | streams} and\n * {@link WebTransportDatagramDuplexStream | datagrams}) never touch the native\n * addon directly: they call this core, which owns the request-id bookkeeping and\n * the lifecycle promises.\n * @internal\n */\nexport class SessionCore {\n /**\n * The command transport, undefined until {@link SessionCore.attach} runs.\n * While undefined, outbound commands are dropped or rejected.\n */\n private transport: SessionTransport | undefined;\n\n /** Monotonic source of request ids handed to the transport. */\n private nextRequestId = 1;\n /** Pending {@link SessionCore.openStream} requests, keyed by request id. */\n private readonly opens = new Map<number, Deferred<number>>();\n /** Pending {@link SessionCore.write} requests, keyed by request id. */\n private readonly writes = new Map<number, Deferred<void>>();\n /** Pending {@link SessionCore.sendDatagram} requests, keyed by request id. */\n private readonly datagramAcks = new Map<number, Deferred<boolean>>();\n /** Pending getStats() requests, keyed by request id. */\n private readonly statsRequests = new Map<number, Deferred<WebTransportConnectionStats>>();\n /** Pending exportKeyingMaterial() requests, keyed by request id. */\n private readonly keyingMaterialRequests = new Map<number, Deferred<Uint8Array>>();\n /** Active receive sinks, keyed by stream id. */\n private readonly receives = new Map<number, ReceiveSink>();\n /** Active send sinks, keyed by stream id. */\n private readonly sends = new Map<number, SendSink>();\n\n /** Handler for peer-initiated streams, if one has been set. */\n private incoming: IncomingHandler | undefined;\n /** Sink for inbound datagrams, if one has been set. */\n private datagramSink: DatagramSink | undefined;\n /** Count of inbound datagrams dropped because the readable queue was full. */\n private droppedIncomingDatagrams = 0;\n\n /** True once the session has reached its terminal (closed) state. */\n private closedState = false;\n /** True once the session has been established (`ready`/`serverReady`). */\n private readyState = false;\n /** True when the session reached its terminal state through an error. */\n private failedState = false;\n /** The most recent stats reported by the native layer, cached for {@link SessionCore.getStats}. */\n private lastStats: WebTransportConnectionStats | undefined;\n /** The negotiated subprotocol, cached from the ready event (`''` if none). */\n private cachedProtocol = '';\n /** The CONNECT response headers, cached from the client ready event. */\n private cachedResponseHeaders: [string, string][] = [];\n\n /**\n * Resolves when the session is established, rejects if it fails before then.\n * Backs the public `WebTransport.ready` promise.\n */\n public readonly ready = deferred<void>();\n /**\n * Resolves with close info on a clean shutdown, rejects on an error or on a\n * close that happens before the session is ready. Backs `WebTransport.closed`.\n */\n public readonly closed = deferred<WebTransportCloseInfo>();\n /**\n * Resolves when the peer sends a DRAIN_WEBTRANSPORT_SESSION capsule (it\n * intends to close soon but the session stays usable). Backs\n * `WebTransport.draining`. Never rejects.\n */\n public readonly draining = deferred<void>();\n\n /**\n * Attach no-op catch handlers to {@link SessionCore.ready} and\n * {@link SessionCore.closed} so that a session whose promises the user never\n * observes does not trigger Node's unhandled-rejection warning.\n */\n public constructor() {\n // Swallow default unhandled-rejection warnings; the user observes these.\n void this.closed.promise.catch(() => {});\n void this.ready.promise.catch(() => {});\n }\n\n /**\n * Attach the transport once the underlying native handle exists.\n *\n * @param transport - The command sink for this session (client or server side).\n */\n public attach(transport: SessionTransport): void {\n this.transport = transport;\n }\n\n /**\n * Fail a session that could not be set up at all (e.g. client connect threw).\n *\n * @param message - Human-readable description of the setup failure.\n * @remarks\n * The failure is delivered on a microtask so the caller has a chance to\n * attach `.ready`/`.closed` handlers before they reject.\n */\n public failSetup(message: string): void {\n // Defer so the caller can attach `.ready`/`.closed` handlers first.\n queueMicrotask(() =>\n this.finish(null, new WebTransportError(message, { source: 'session' })),\n );\n }\n\n /**\n * @returns The next request id, post-incrementing the internal counter.\n */\n private nextId(): number {\n return this.nextRequestId++;\n }\n\n /**\n * Open an outbound stream and await its assigned id.\n *\n * @param bidi - True for a bidirectional stream, false for unidirectional.\n * @returns A promise for the new stream's id.\n * @remarks\n * Rejects immediately (without touching the transport) if the session is not\n * usable (unattached or closed).\n */\n public openStream(bidi: boolean): Promise<number> {\n if (!this.usable()) return Promise.reject(this.deadError());\n const requestId = this.nextId();\n const d = deferred<number>();\n this.opens.set(requestId, d);\n this.transport!.openStream(bidi, requestId);\n return d.promise;\n }\n\n /**\n * Write a chunk to a stream; resolves once the bytes are flushed into quiche\n * (the write backpressure signal).\n *\n * @param streamId - The target stream id.\n * @param chunk - The bytes to send.\n * @returns A promise that resolves when the write is acknowledged.\n * @remarks\n * Rejects immediately if the session is not usable.\n */\n public write(streamId: number, chunk: Uint8Array): Promise<void> {\n if (!this.usable()) return Promise.reject(this.deadError());\n const requestId = this.nextId();\n const d = deferred<void>();\n this.writes.set(requestId, d);\n this.transport!.write(streamId, chunk, requestId);\n return d.promise;\n }\n\n /**\n * Finish (half-close) the send side of a stream. No-op if not attached.\n *\n * @param streamId - The stream to finish.\n */\n public finStream(streamId: number): void {\n this.transport?.fin(streamId);\n }\n\n /**\n * Reset the send side of a stream. No-op if not attached.\n *\n * @param streamId - The stream to reset.\n * @param code - The application error code; coerced to an unsigned 32-bit value.\n */\n public resetStream(streamId: number, code: number): void {\n this.transport?.reset(streamId, code >>> 0);\n }\n\n /**\n * Ask the peer to stop sending on a stream. No-op if not attached.\n *\n * @param streamId - The stream whose inbound half should be stopped.\n * @param code - The application error code; coerced to an unsigned 32-bit value.\n */\n public stopSending(streamId: number, code: number): void {\n this.transport?.stopSending(streamId, code >>> 0);\n }\n\n /**\n * Toggle read backpressure on a stream. No-op if not attached.\n *\n * @param streamId - The receive stream.\n * @param paused - True to pause native draining (flow-control the peer), false to resume.\n */\n public setPaused(streamId: number, paused: boolean): void {\n this.transport?.setPaused(streamId, paused);\n }\n\n /**\n * Send a datagram.\n *\n * @param chunk - The datagram payload.\n * @returns A promise resolving to whether the datagram was actually sent;\n * resolves to false (rather than rejecting) when the session is not usable.\n */\n public sendDatagram(chunk: Uint8Array): Promise<boolean> {\n if (!this.usable()) return Promise.resolve(false);\n const requestId = this.nextId();\n const d = deferred<boolean>();\n this.datagramAcks.set(requestId, d);\n this.transport!.sendDatagram(chunk, requestId);\n return d.promise;\n }\n\n /**\n * @returns The maximum datagram payload size in bytes, or 0 if not attached.\n */\n public maxDatagramSize(): number {\n return this.transport ? this.transport.maxDatagramSize() : 0;\n }\n\n /**\n * Gracefully close the session. No-op if already closed or not attached.\n *\n * @param code - The WebTransport close code; coerced to an unsigned 32-bit value.\n * @param reason - The close reason, UTF-8 encoded before it is sent.\n */\n public close(code: number, reason: string): void {\n if (this.closedState || !this.transport) return;\n this.transport.closeSession(code >>> 0, new TextEncoder().encode(reason));\n }\n\n /** Tell the peer this session is draining (send a DRAIN capsule). */\n public drain(): void {\n this.transport?.drain();\n }\n\n /**\n * Snapshot the connection's stats. Resolves with a\n * {@link WebTransportConnectionStats} once the driver reports back. After a\n * clean close it resolves with the last stats seen while live; it rejects\n * only when the session was never attached or terminated through an error.\n */\n public getStats(): Promise<WebTransportConnectionStats> {\n if (!this.usable()) {\n if (!this.failedState && this.lastStats !== undefined) {\n return Promise.resolve(this.lastStats);\n }\n return Promise.reject(this.deadError());\n }\n const requestId = this.nextId();\n const d = deferred<WebTransportConnectionStats>();\n this.statsRequests.set(requestId, d);\n this.transport!.getStats(requestId);\n return d.promise;\n }\n\n /**\n * Export TLS keying material (RFC 5705). Resolves with `length` bytes derived\n * from `label` and `context` once the driver reports back; rejects if the\n * session is not usable or the TLS export fails.\n */\n public exportKeyingMaterial(\n label: Uint8Array,\n context: Uint8Array,\n length: number,\n ): Promise<Uint8Array> {\n if (!this.usable()) return Promise.reject(this.deadError());\n const requestId = this.nextId();\n const d = deferred<Uint8Array>();\n this.keyingMaterialRequests.set(requestId, d);\n this.transport!.exportKeyingMaterial(requestId, label, context, length);\n return d.promise;\n }\n\n /** Tear down the native resources for this session. No-op if not attached. */\n public shutdown(): void {\n this.transport?.shutdown();\n }\n\n /**\n * Whether outbound operations can still be issued (attached, not closed).\n *\n * @returns True when a transport is attached and the session is not closed.\n */\n private usable(): boolean {\n return this.transport !== undefined && !this.closedState;\n }\n\n /**\n * @returns The error used to reject operations attempted on a dead session.\n */\n private deadError(): WebTransportError {\n return new WebTransportError('session is closed', { source: 'session' });\n }\n\n /**\n * Register a sink to receive a stream's inbound data/fin/reset events.\n *\n * @param streamId - The stream to observe.\n * @param sink - The receiver of that stream's inbound events.\n */\n public registerReceive(streamId: number, sink: ReceiveSink): void {\n this.receives.set(streamId, sink);\n }\n /**\n * Stop delivering inbound events for a stream.\n *\n * @param streamId - The stream to forget.\n */\n public unregisterReceive(streamId: number): void {\n this.receives.delete(streamId);\n }\n /**\n * Register a sink to receive a stream's STOP_SENDING notifications.\n *\n * @param streamId - The stream to observe.\n * @param sink - The receiver of that stream's send-side control events.\n */\n public registerSend(streamId: number, sink: SendSink): void {\n this.sends.set(streamId, sink);\n }\n /**\n * Stop delivering send-side control events for a stream.\n *\n * @param streamId - The stream to forget.\n */\n public unregisterSend(streamId: number): void {\n this.sends.delete(streamId);\n }\n /**\n * Set the handler invoked when the peer opens a stream. Replaces any prior handler.\n *\n * @param handler - The consumer of peer-initiated streams.\n */\n public setIncomingHandler(handler: IncomingHandler): void {\n this.incoming = handler;\n }\n /**\n * Set the sink invoked for each inbound datagram. Replaces any prior sink.\n *\n * @param sink - The consumer of inbound datagram payloads.\n */\n public setDatagramSink(sink: DatagramSink): void {\n this.datagramSink = sink;\n }\n\n /**\n * Record that one inbound datagram was dropped because the readable queue\n * was full. Surfaced through getStats() as `datagrams.droppedIncoming`.\n */\n public recordDroppedIncomingDatagram(): void {\n this.droppedIncomingDatagrams++;\n }\n\n /**\n * Route one native event to the appropriate promise, sink, or handler.\n *\n * @param ev - The event delivered by the native addon.\n * @remarks\n * This is the single entry point the native `onEvent` callback funnels into.\n * `ready`/`serverReady` mark the session established and resolve `ready`;\n * `closed`/`error` drive {@link SessionCore.finish}; the `stream*` events look\n * up the matching sink (silently ignored if none is registered); and the\n * `*Ack`/`streamOpened` events settle and then remove the pending deferred\n * for their `requestId`.\n */\n public dispatch(ev: NativeEvent): void {\n switch (ev.type) {\n case NativeEventType.Ready: {\n this.readyState = true;\n this.cachedProtocol = ev.protocol ?? '';\n this.cachedResponseHeaders = ev.responseHeaders;\n this.ready.resolve();\n break;\n }\n case NativeEventType.ServerReady: {\n this.readyState = true;\n this.cachedProtocol = ev.protocol ?? '';\n this.ready.resolve();\n break;\n }\n case NativeEventType.Draining: {\n this.draining.resolve();\n break;\n }\n case NativeEventType.Closed: {\n const reason = new TextDecoder().decode(ev.reason);\n this.finish({ closeCode: ev.code, reason }, undefined);\n break;\n }\n case NativeEventType.Error: {\n const err = new WebTransportError(ev.message, { source: 'session' });\n this.finish(null, err);\n break;\n }\n case NativeEventType.Datagram: {\n this.datagramSink?.(ev.data);\n break;\n }\n case NativeEventType.Stream: {\n if (ev.bidi) this.incoming?.onBidi(ev.streamId);\n else this.incoming?.onUni(ev.streamId);\n break;\n }\n case NativeEventType.StreamData: {\n this.receives.get(ev.streamId)?.onData(ev.data);\n break;\n }\n case NativeEventType.StreamFin: {\n this.receives.get(ev.streamId)?.onFin();\n break;\n }\n case NativeEventType.StreamReset: {\n this.receives.get(ev.streamId)?.onReset(ev.code);\n break;\n }\n case NativeEventType.StreamStopSending: {\n this.sends.get(ev.streamId)?.onStopSending(ev.code);\n break;\n }\n case NativeEventType.StreamOpened: {\n this.opens.get(ev.requestId)?.resolve(ev.streamId);\n this.opens.delete(ev.requestId);\n break;\n }\n case NativeEventType.WriteAck: {\n this.writes.get(ev.requestId)?.resolve();\n this.writes.delete(ev.requestId);\n break;\n }\n case NativeEventType.DatagramAck: {\n this.datagramAcks.get(ev.requestId)?.resolve(ev.sent);\n this.datagramAcks.delete(ev.requestId);\n break;\n }\n case NativeEventType.Stats: {\n const stats: WebTransportConnectionStats = {\n bytesSent: ev.bytesSent,\n bytesReceived: ev.bytesReceived,\n packetsSent: ev.packetsSent,\n packetsReceived: ev.packetsReceived,\n packetsLost: ev.packetsLost,\n smoothedRtt: ev.smoothedRtt,\n rttVariation: ev.rttVariation,\n minRtt: ev.minRtt,\n datagrams: {\n expiredOutgoing: 0,\n droppedIncoming: this.droppedIncomingDatagrams,\n lostOutgoing: 0,\n expiredIncoming: 0,\n },\n };\n this.lastStats = stats;\n this.statsRequests.get(ev.requestId)?.resolve(stats);\n this.statsRequests.delete(ev.requestId);\n break;\n }\n case NativeEventType.KeyingMaterial: {\n const d = this.keyingMaterialRequests.get(ev.requestId);\n if (d) {\n if (ev.ok && ev.data) {\n d.resolve(ev.data);\n } else {\n d.reject(\n new WebTransportError('keying material export failed', {\n source: 'session',\n }),\n );\n }\n this.keyingMaterialRequests.delete(ev.requestId);\n }\n break;\n }\n }\n }\n\n /**\n * Terminal transition: resolve/reject everything and tear down.\n *\n * @param info - Close info for a clean close, or null when closing on error.\n * @param error - The error that ended the session, or undefined for a clean close.\n * @remarks\n * Idempotent: returns immediately if the session already closed. Settles the\n * lifecycle promises according to state: if the session never became ready,\n * both `ready` and `closed` reject (a pre-ready close is a failed connect); if\n * it was ready and `error` is set, only `closed` rejects; otherwise `closed`\n * resolves with `info` (defaulting to code 0 / empty reason). It then rejects\n * every pending open and write, resolves every pending datagram ack to false,\n * signals a reset (code 0) to all receive sinks and STOP_SENDING (code 0) to\n * all send sinks, clears the bookkeeping maps, and finally shuts down the\n * transport.\n */\n private finish(info: WebTransportCloseInfo | null, error: WebTransportError | undefined): void {\n if (this.closedState) return;\n this.closedState = true;\n if (error) this.failedState = true;\n // A session that closes without a prior DRAIN never emitted `draining`;\n // settle it here so `await session.draining` cannot hang past close.\n this.draining.resolve();\n\n if (!this.readyState) {\n // The session never established: both `ready` and `closed` reject\n // (a session that closes before it is ready has failed to connect).\n const err =\n error ??\n new WebTransportError('session closed before it was established', {\n source: 'session',\n });\n this.ready.reject(err);\n this.closed.reject(err);\n } else if (error) {\n // Established, then terminated abnormally.\n this.closed.reject(error);\n } else {\n // Established, then closed cleanly.\n this.closed.resolve(info ?? { closeCode: 0, reason: '' });\n }\n\n const err = error ?? new WebTransportError('session closed', { source: 'session' });\n for (const d of this.opens.values()) d.reject(err);\n for (const d of this.writes.values()) d.reject(err);\n for (const d of this.datagramAcks.values()) d.resolve(false);\n for (const d of this.statsRequests.values()) d.reject(err);\n for (const d of this.keyingMaterialRequests.values()) d.reject(err);\n for (const sink of this.receives.values()) sink.onSessionClose(err);\n for (const sink of this.sends.values()) sink.onSessionClose(err);\n this.opens.clear();\n this.writes.clear();\n this.datagramAcks.clear();\n this.statsRequests.clear();\n this.keyingMaterialRequests.clear();\n this.receives.clear();\n this.sends.clear();\n\n this.transport?.shutdown();\n }\n\n /** @returns Whether the session has reached its terminal closed state. */\n public get isClosed(): boolean {\n return this.closedState;\n }\n\n /** @returns Whether the session has been established (ready). */\n public get isReady(): boolean {\n return this.readyState;\n }\n\n /** @returns The negotiated subprotocol, or `''` if none was negotiated. */\n public get protocol(): string {\n return this.cachedProtocol;\n }\n\n /** @returns The CONNECT response headers as ordered `[name, value]` pairs. */\n public get responseHeaders(): [string, string][] {\n return this.cachedResponseHeaders;\n }\n}\n\n/**\n * Routes session commands through a native client session handle.\n *\n * @remarks\n * The client-side {@link SessionTransport}: each method forwards to the matching\n * {@link NativeAddon} function with the captured {@link NativeHandle}.\n * @internal\n */\nclass ClientTransport implements SessionTransport {\n /**\n * @param native - The loaded native addon.\n * @param handle - The client session handle these commands target.\n */\n public constructor(\n private readonly native: NativeAddon,\n private readonly handle: NativeHandle,\n ) {}\n /**\n * @param bidi - True for bidirectional, false for unidirectional.\n * @param requestId - Id correlating the eventual `streamOpened` event.\n */\n public openStream(bidi: boolean, requestId: number): void {\n this.native.openStream(this.handle, bidi, requestId);\n }\n /**\n * @param streamId - The target stream id.\n * @param bytes - The payload.\n * @param requestId - Id correlating the eventual `writeAck` event.\n */\n public write(streamId: number, bytes: Uint8Array, requestId: number): void {\n this.native.writeStream(this.handle, streamId, bytes, requestId);\n }\n /** @param streamId - The stream to finish. */\n public fin(streamId: number): void {\n this.native.finStream(this.handle, streamId);\n }\n /**\n * @param streamId - The stream to reset.\n * @param code - The application error code.\n */\n public reset(streamId: number, code: number): void {\n this.native.resetStream(this.handle, streamId, code);\n }\n /**\n * @param streamId - The stream whose inbound half should be stopped.\n * @param code - The application error code.\n */\n public stopSending(streamId: number, code: number): void {\n this.native.stopSending(this.handle, streamId, code);\n }\n /**\n * @param streamId - The receive stream.\n * @param paused - True to pause draining, false to resume.\n */\n public setPaused(streamId: number, paused: boolean): void {\n this.native.setPaused(this.handle, streamId, paused);\n }\n /**\n * @param bytes - The datagram payload.\n * @param requestId - Id correlating the eventual `datagramAck` event.\n */\n public sendDatagram(bytes: Uint8Array, requestId: number): void {\n this.native.sendDatagram(this.handle, bytes, requestId);\n }\n /** @returns The maximum datagram payload size, in bytes. */\n public maxDatagramSize(): number {\n return this.native.maxDatagramSize(this.handle);\n }\n /**\n * @param code - The WebTransport close code.\n * @param reason - The UTF-8 encoded close reason.\n */\n public closeSession(code: number, reason: Uint8Array): void {\n this.native.closeSession(this.handle, code, reason);\n }\n /** Send a DRAIN_WEBTRANSPORT_SESSION capsule to the peer. */\n public drain(): void {\n this.native.drain(this.handle);\n }\n /** Request connection stats; the result arrives as a `stats` event. */\n public getStats(requestId: number): void {\n this.native.getStats(this.handle, requestId);\n }\n /** Export TLS keying material; the result arrives as a `keyingMaterial` event. */\n public exportKeyingMaterial(\n requestId: number,\n label: Uint8Array,\n context: Uint8Array,\n length: number,\n ): void {\n this.native.exportKeyingMaterial(this.handle, requestId, label, context, length);\n }\n /** Tear down the session's native driver thread. */\n public shutdown(): void {\n this.native.shutdown(this.handle);\n }\n}\n\n/**\n * Create and connect a client-role session.\n *\n * @param config - The normalized connect parameters.\n * @returns A {@link SessionCore} wired to a fresh native client session; if the\n * native `connect` throws during setup, the returned core is failed\n * asynchronously via {@link SessionCore.failSetup} rather than throwing here.\n * @remarks\n * Loads the native addon, constructs the core, calls {@link NativeAddon.connect}\n * with an `onEvent` callback bound to {@link SessionCore.dispatch}, and attaches\n * a {@link ClientTransport} around the returned handle.\n * @internal\n */\nexport function createClientSession(config: ConnectConfig): SessionCore {\n const native = loadNative();\n const core = new SessionCore();\n try {\n const handle = native.connect(\n config.url,\n config.hashes,\n config.insecure,\n config.origin,\n config.headerNames,\n config.headerValues,\n config.protocols,\n (ev) => core.dispatch(ev),\n );\n core.attach(new ClientTransport(native, handle));\n } catch (e) {\n core.failSetup(e instanceof Error ? e.message : String(e));\n }\n return core;\n}\n\n/**\n * Routes session commands through a native server handle + session id.\n *\n * @remarks\n * The server-side {@link SessionTransport}: each method forwards to the matching\n * `server*` {@link NativeAddon} function with the captured\n * {@link NativeServerHandle} and numeric session id.\n * @internal\n */\nexport class ServerTransport implements SessionTransport {\n /**\n * @param native - The loaded native addon.\n * @param handle - The server handle these commands target.\n * @param session - The id of the session these commands act on.\n */\n public constructor(\n private readonly native: NativeAddon,\n private readonly handle: NativeServerHandle,\n private readonly session: number,\n ) {}\n /**\n * @param bidi - True for bidirectional, false for unidirectional.\n * @param requestId - Id correlating the eventual `streamOpened` event.\n */\n public openStream(bidi: boolean, requestId: number): void {\n this.native.serverOpenStream(this.handle, this.session, bidi, requestId);\n }\n /**\n * @param streamId - The target stream id.\n * @param bytes - The payload.\n * @param requestId - Id correlating the eventual `writeAck` event.\n */\n public write(streamId: number, bytes: Uint8Array, requestId: number): void {\n this.native.serverWrite(this.handle, this.session, streamId, bytes, requestId);\n }\n /** @param streamId - The stream to finish. */\n public fin(streamId: number): void {\n this.native.serverFin(this.handle, this.session, streamId);\n }\n /**\n * @param streamId - The stream to reset.\n * @param code - The application error code.\n */\n public reset(streamId: number, code: number): void {\n this.native.serverReset(this.handle, this.session, streamId, code);\n }\n /**\n * @param streamId - The stream whose inbound half should be stopped.\n * @param code - The application error code.\n */\n public stopSending(streamId: number, code: number): void {\n this.native.serverStopSending(this.handle, this.session, streamId, code);\n }\n /**\n * @param streamId - The receive stream.\n * @param paused - True to pause draining, false to resume.\n */\n public setPaused(streamId: number, paused: boolean): void {\n this.native.serverSetPaused(this.handle, this.session, streamId, paused);\n }\n /**\n * @param bytes - The datagram payload.\n * @param requestId - Id correlating the eventual `datagramAck` event.\n */\n public sendDatagram(bytes: Uint8Array, requestId: number): void {\n this.native.serverSendDatagram(this.handle, this.session, bytes, requestId);\n }\n /** @returns The maximum datagram payload size, in bytes. */\n public maxDatagramSize(): number {\n return this.native.serverMaxDatagramSize(this.handle);\n }\n /**\n * @param code - The WebTransport close code.\n * @param reason - The UTF-8 encoded close reason.\n */\n public closeSession(code: number, reason: Uint8Array): void {\n this.native.serverCloseSession(this.handle, this.session, code, reason);\n }\n /** Send a DRAIN_WEBTRANSPORT_SESSION capsule to this session's peer. */\n public drain(): void {\n this.native.serverDrain(this.handle, this.session);\n }\n /** Request this session's connection stats; the result arrives as a `stats` event. */\n public getStats(requestId: number): void {\n this.native.serverGetStats(this.handle, this.session, requestId);\n }\n /** Export TLS keying material; the result arrives as a `keyingMaterial` event. */\n public exportKeyingMaterial(\n requestId: number,\n label: Uint8Array,\n context: Uint8Array,\n length: number,\n ): void {\n this.native.serverExportKeyingMaterial(\n this.handle,\n this.session,\n requestId,\n label,\n context,\n length,\n );\n }\n /**\n * No-op: the server driver owns the session lifecycle, so there is nothing to\n * tear down per session on the JS side.\n */\n public shutdown(): void {\n // The server driver owns the session lifecycle; nothing to tear down here.\n }\n}\n","// SPDX-License-Identifier: Apache-2.0\n//! `WebTransportDatagramDuplexStream`: unreliable, unordered datagrams.\n\nimport type { SessionCore } from './native.js';\n\n/**\n * The datagram transport for a session. `readable` yields inbound datagrams and\n * `writable` sends them; both are lossy by design (datagrams that don't fit the\n * queue are dropped rather than buffered indefinitely).\n *\n * @remarks\n * This mirrors the WHATWG `WebTransportDatagramDuplexStream` interface. One\n * instance is created per {@link SessionCore} and exposed as the `datagrams`\n * member of a session. Loss happens in two places: inbound datagrams that\n * arrive while the `readable` queue is already full are discarded (see the\n * datagram sink installed in the constructor), and outbound datagrams are\n * subject to the queue backpressure of `writable` plus whatever the native\n * QUIC layer chooses to drop when a packet cannot carry them.\n *\n * @see WebTransport for how a session exposes this stream.\n */\nexport class WebTransportDatagramDuplexStream {\n /**\n * The underlying session used to send datagrams, register the inbound sink,\n * query the maximum datagram size, and observe session closure.\n *\n * @internal\n */\n private readonly session: SessionCore;\n /**\n * Stream of inbound datagrams. Each chunk is one received datagram payload.\n * Backed by a {@link CountQueuingStrategy} whose high water mark is the\n * value of {@link incomingHighWaterMark} captured when this instance was\n * constructed. The stream is closed automatically when the session ends.\n */\n public readonly readable: ReadableStream<Uint8Array>;\n /**\n * Stream for sending outbound datagrams. Writing a chunk forwards it to\n * {@link SessionCore.sendDatagram}, whose boolean result (whether the\n * datagram was actually transmitted rather than dropped) is discarded, so\n * that `write()` resolves once the native transport reports back on the\n * send attempt. Backed by a {@link CountQueuingStrategy} whose high water\n * mark is the value of {@link outgoingHighWaterMark} captured when this\n * instance was constructed.\n */\n public readonly writable: WritableStream<Uint8Array>;\n\n /**\n * High water mark (in datagrams) for the inbound `readable` queue. Read\n * back through {@link incomingHighWaterMark}. Only the value present at\n * construction time is applied to the actual {@link readable} strategy;\n * later changes update the reported number but do not resize the live\n * queue.\n *\n * @defaultValue 64\n * @internal\n */\n private incomingHwm = 64;\n /**\n * High water mark (in datagrams) for the outbound `writable` queue. Read\n * back through {@link outgoingHighWaterMark}. Only the value present at\n * construction time is applied to the actual {@link writable} strategy;\n * later changes update the reported number but do not resize the live\n * queue.\n *\n * @defaultValue 64\n * @internal\n */\n private outgoingHwm = 64;\n\n /**\n * Max age (ms) an inbound datagram is retained before being dropped, or\n * `null` for no limit.\n *\n * @remarks\n * Present to match the WHATWG interface. This class stores the value but\n * does not currently enforce it: inbound loss here is driven only by the\n * `readable` queue being full, not by datagram age.\n *\n * @defaultValue null\n */\n public incomingMaxAge: number | null = null;\n /**\n * Max age (ms) an outbound datagram waits to be sent before being dropped,\n * or `null` for no limit.\n *\n * @remarks\n * Present to match the WHATWG interface. This class stores the value but\n * does not currently enforce it; outbound loss is governed by the\n * `writable` queue backpressure and the native QUIC layer.\n *\n * @defaultValue null\n */\n public outgoingMaxAge: number | null = null;\n\n /**\n * Build the datagram duplex stream over a session.\n *\n * @param session - The session that carries the datagrams. Its\n * {@link SessionCore.setDatagramSink} is used to receive inbound datagrams,\n * {@link SessionCore.sendDatagram} to send them, and its\n * {@link SessionCore.closed} promise to know when to close the inbound\n * stream.\n *\n * @remarks\n * Wiring performed here, in order:\n *\n * 1. Creates {@link readable} and captures its controller from `start`.\n * 2. Installs a datagram sink that enqueues each received datagram only\n * while the controller's `desiredSize` is positive (treating an unknown\n * `desiredSize` of `null` as `1`, i.e. room available); datagrams that\n * arrive when the queue is full are dropped.\n * 3. Subscribes to the session's `closed` promise so the inbound stream is\n * closed on both clean close and error, preventing a pending `read()`\n * from hanging forever. A double-close is swallowed.\n * 4. Creates {@link writable} whose `write` forwards each chunk to\n * `session.sendDatagram` and maps the boolean ack to `undefined`.\n */\n public constructor(session: SessionCore) {\n this.session = session;\n\n let rController!: ReadableStreamDefaultController<Uint8Array>;\n this.readable = new ReadableStream<Uint8Array>(\n {\n start(c) {\n rController = c;\n },\n },\n new CountQueuingStrategy({ highWaterMark: this.incomingHwm }),\n );\n\n session.setDatagramSink((data) => {\n // Unreliable: drop when the inbound queue is already full.\n if ((rController.desiredSize ?? 1) > 0) {\n rController.enqueue(data);\n } else {\n session.recordDroppedIncomingDatagram();\n }\n });\n\n // Close the inbound datagram stream when the session ends, otherwise a\n // reader awaiting read() would hang forever after close.\n void session.closed.promise.then(\n () => {\n try {\n rController.close();\n } catch {\n // already closed\n }\n },\n () => {\n try {\n rController.close();\n } catch {\n // already closed\n }\n },\n );\n\n this.writable = new WritableStream<Uint8Array>(\n {\n write: (chunk) => session.sendDatagram(chunk).then(() => undefined),\n },\n new CountQueuingStrategy({ highWaterMark: this.outgoingHwm }),\n );\n }\n\n /**\n * The largest datagram payload that currently fits in a single packet.\n *\n * @returns The maximum datagram payload size in bytes as reported by the\n * native transport, or `0` when the session has no transport attached yet.\n * The value can change over the life of the session as the path MTU is\n * discovered.\n */\n public get maxDatagramSize(): number {\n return this.session.maxDatagramSize();\n }\n\n /**\n * The high water mark (in datagrams) reported for the inbound `readable`\n * queue.\n *\n * @returns The most recently set incoming high water mark.\n */\n public get incomingHighWaterMark(): number {\n return this.incomingHwm;\n }\n /**\n * Set the reported inbound high water mark.\n *\n * @param value - Desired high water mark; coerced to an integer with\n * `value | 0` and clamped to a minimum of `1`.\n *\n * @remarks\n * This updates only the number returned by {@link incomingHighWaterMark}.\n * The live {@link readable} queue keeps the strategy fixed at construction\n * time, so changing this after construction does not resize it.\n */\n public set incomingHighWaterMark(value: number) {\n this.incomingHwm = Math.max(1, value | 0);\n }\n\n /**\n * The high water mark (in datagrams) reported for the outbound `writable`\n * queue.\n *\n * @returns The most recently set outgoing high water mark.\n */\n public get outgoingHighWaterMark(): number {\n return this.outgoingHwm;\n }\n /**\n * Set the reported outbound high water mark.\n *\n * @param value - Desired high water mark; coerced to an integer with\n * `value | 0` and clamped to a minimum of `1`.\n *\n * @remarks\n * This updates only the number returned by {@link outgoingHighWaterMark}.\n * The live {@link writable} queue keeps the strategy fixed at construction\n * time, so changing this after construction does not resize it.\n */\n public set outgoingHighWaterMark(value: number) {\n this.outgoingHwm = Math.max(1, value | 0);\n }\n}\n","// SPDX-License-Identifier: Apache-2.0\n//! WebTransport stream classes, implemented as WHATWG Readable/Writable streams\n//! with end-to-end backpressure onto the native QUIC flow-control window.\n\nimport { WebTransportError } from './errors.js';\nimport type { SessionCore } from './native.js';\n\n/**\n * Derive a QUIC/WebTransport application error code from an abort or cancel reason.\n *\n * @param reason - The value handed to a stream `cancel(reason)` or `abort(reason)`.\n * @returns The stream's application error code as an unsigned 32-bit integer: it is\n * {@link WebTransportError.streamErrorCode} (coerced with `>>> 0`) when `reason` is\n * a {@link WebTransportError} carrying a non-null code, and `0` for every other\n * value, including plain errors and `undefined`.\n * @remarks Translates a JS-level abort or cancel into the numeric code carried by the\n * QUIC `STOP_SENDING` and `RESET_STREAM` frames sent to the peer.\n * @internal\n */\nfunction errorCode(reason: unknown): number {\n if (reason instanceof WebTransportError && reason.streamErrorCode != null) {\n return reason.streamErrorCode >>> 0;\n }\n return 0;\n}\n\n/**\n * The readable half of a WebTransport stream. A `ReadableStream<Uint8Array>`\n * whose queue high-water mark drives native read backpressure: when the JS queue\n * fills, the native side stops draining quiche, flow-controlling the peer.\n *\n * @remarks Subclasses the WHATWG `ReadableStream`, so all standard reader APIs\n * (`getReader`, async iteration, `pipeTo`, `cancel`, and so on) work as usual.\n * Inbound bytes arrive as native `streamData` events routed through the session's\n * {@link ReceiveSink}; a peer FIN closes the stream and a peer reset errors it with\n * a {@link WebTransportError}.\n */\nexport class WebTransportReceiveStream extends ReadableStream<Uint8Array> {\n /**\n * The QUIC stream id of the underlying stream. Stable for the lifetime of the\n * stream and shared with the paired {@link WebTransportSendStream} when this is\n * one half of a {@link WebTransportBidirectionalStream}.\n */\n public readonly streamId: number;\n\n /**\n * Wire a `ReadableStream` up to a native receive stream.\n *\n * @param session - The session core that dispatches native events and issues\n * flow-control and teardown commands for this stream.\n * @param streamId - The QUIC stream id to receive from.\n * @remarks Installs the `ReadableStream` underlying source and registers a\n * {@link ReceiveSink} on `session` for `streamId`:\n *\n * - `pull` unpauses the native stream via `setPaused(streamId, false)`, so\n * quiche resumes draining inbound bytes when the consumer wants more.\n * - `cancel(reason)` sends `STOP_SENDING` to the peer with the code from\n * {@link errorCode} and then unregisters the receive sink.\n * - The sink's `onData` enqueues each chunk and, once the controller's\n * `desiredSize` falls to zero or below (a nullish `desiredSize` is treated as\n * `1`, so it does not pause), pauses the native stream to flow-control the\n * peer.\n * - The sink's `onFin` closes the controller (swallowing the error if it was\n * already closed or errored) and unregisters.\n * - The sink's `onReset(code)` errors the controller with a `'stream'`-sourced\n * {@link WebTransportError} ('stream reset by peer') carrying the peer's code,\n * then unregisters.\n *\n * A {@link CountQueuingStrategy} with a high-water mark of 32 chunks bounds the\n * JS-side queue and thereby the pause threshold.\n */\n public constructor(session: SessionCore, streamId: number) {\n let controller!: ReadableStreamDefaultController<Uint8Array>;\n super(\n {\n start(c) {\n controller = c;\n },\n pull() {\n session.setPaused(streamId, false);\n },\n cancel(reason) {\n session.stopSending(streamId, errorCode(reason));\n session.unregisterReceive(streamId);\n },\n },\n new CountQueuingStrategy({ highWaterMark: 32 }),\n );\n\n session.registerReceive(streamId, {\n onData(chunk) {\n controller.enqueue(chunk);\n if ((controller.desiredSize ?? 1) <= 0) {\n session.setPaused(streamId, true);\n }\n },\n onFin() {\n try {\n controller.close();\n } catch {\n // already closed/errored\n }\n session.unregisterReceive(streamId);\n },\n onReset(code) {\n controller.error(\n new WebTransportError('stream reset by peer', {\n source: 'stream',\n streamErrorCode: code,\n }),\n );\n session.unregisterReceive(streamId);\n },\n onSessionClose(error) {\n try {\n controller.error(error);\n } catch {\n // already closed/errored\n }\n session.unregisterReceive(streamId);\n },\n });\n\n this.streamId = streamId;\n }\n}\n\n/**\n * The writable half of a WebTransport stream. Each `write()` resolves only once\n * the bytes have been accepted into quiche's send buffer, giving natural\n * backpressure gated by the peer's flow-control window.\n *\n * @remarks Subclasses the WHATWG `WritableStream`, so all standard writer APIs\n * (`getWriter`, `write`, `close`, `abort`, `pipeTo` targets, and so on) work as\n * usual. A peer `STOP_SENDING` errors the stream through the session's\n * {@link SendSink}.\n */\n/**\n * An opaque handle for grouping streams so their sends can be scheduled relative\n * to one another via each stream's {@link WebTransportSendStream.sendOrder}.\n * Create one with `WebTransport.createSendGroup()`. Accepted for W3C API parity;\n * the grouping is a best-effort hint (quiche schedules by its own urgency).\n */\nexport class WebTransportSendGroup {}\n\n/** Options for creating a send stream (W3C `WebTransportSendStreamOptions`). */\nexport interface WebTransportSendStreamOptions {\n /** The {@link WebTransportSendGroup} to associate the new stream with. */\n sendGroup?: WebTransportSendGroup;\n /** Relative send priority; higher is nominally sent first. Defaults to `0`. */\n sendOrder?: number;\n /**\n * Wait for stream-creation credit instead of failing when it is exhausted.\n * Accepted for parity; stream creation here does not currently fail on credit.\n */\n waitUntilAvailable?: boolean;\n}\n\nexport class WebTransportSendStream extends WritableStream<Uint8Array> {\n /**\n * The QUIC stream id of the underlying stream. Stable for the lifetime of the\n * stream and shared with the paired {@link WebTransportReceiveStream} when this is\n * one half of a {@link WebTransportBidirectionalStream}.\n */\n public readonly streamId: number;\n /**\n * The {@link WebTransportSendGroup} this stream belongs to, or `null`.\n * Mutable per the W3C API; grouping is a best-effort scheduling hint.\n */\n public sendGroup: WebTransportSendGroup | null;\n /**\n * Relative send priority within the send group. Higher values are nominally\n * sent first. Mutable per the W3C API; the effect on the wire is best-effort.\n */\n public sendOrder: number;\n\n /**\n * Wire a `WritableStream` up to a native send stream.\n *\n * @param session - The session core that dispatches native events and issues\n * write, FIN, reset, and teardown commands for this stream.\n * @param streamId - The QUIC stream id to send on.\n * @remarks Installs the `WritableStream` underlying sink and registers a\n * {@link SendSink} on `session` for `streamId`:\n *\n * - `write(chunk)` forwards to `session.write` and returns its promise, which\n * settles only once the bytes are accepted into quiche's send buffer; awaiting\n * that promise is what applies end-to-end backpressure.\n * - `close` sends a FIN via `finStream` and unregisters the send sink.\n * - `abort(reason)` resets the stream via `resetStream` with the code from\n * {@link errorCode} and unregisters the send sink.\n * - The sink's `onStopSending(code)` errors the controller with a\n * `'stream'`-sourced {@link WebTransportError} ('peer sent STOP_SENDING')\n * carrying the peer's code (swallowing the error if the stream was already\n * errored or closed) and unregisters.\n *\n * A {@link ByteLengthQueuingStrategy} with a high-water mark of 1 MiB\n * (`1024 * 1024` bytes) bounds the JS-side write queue.\n */\n public constructor(\n session: SessionCore,\n streamId: number,\n options: WebTransportSendStreamOptions = {},\n ) {\n let controller!: WritableStreamDefaultController;\n super(\n {\n start(c) {\n controller = c;\n },\n write(chunk) {\n return session.write(streamId, chunk);\n },\n close() {\n session.finStream(streamId);\n session.unregisterSend(streamId);\n },\n abort(reason) {\n session.resetStream(streamId, errorCode(reason));\n session.unregisterSend(streamId);\n },\n },\n new ByteLengthQueuingStrategy({ highWaterMark: 1024 * 1024 }),\n );\n\n session.registerSend(streamId, {\n onStopSending(code) {\n try {\n controller.error(\n new WebTransportError('peer sent STOP_SENDING', {\n source: 'stream',\n streamErrorCode: code,\n }),\n );\n } catch {\n // already errored/closed\n }\n session.unregisterSend(streamId);\n },\n onSessionClose(error) {\n try {\n controller.error(error);\n } catch {\n // already errored/closed\n }\n session.unregisterSend(streamId);\n },\n });\n\n this.streamId = streamId;\n this.sendGroup = options.sendGroup ?? null;\n this.sendOrder = options.sendOrder ?? 0;\n }\n}\n\n/**\n * A bidirectional WebTransport stream: a {@link WebTransportReceiveStream} and a\n * {@link WebTransportSendStream} over a single QUIC stream id, exposed as `readable`\n * and `writable` halves. Mirrors the shape of the browser\n * `WebTransportBidirectionalStream`.\n */\nexport class WebTransportBidirectionalStream {\n /** The readable half, delivering bytes the peer sends on this stream. */\n public readonly readable: WebTransportReceiveStream;\n /** The writable half, sending bytes to the peer on this stream. */\n public readonly writable: WebTransportSendStream;\n\n /**\n * Construct both halves over the same QUIC stream.\n *\n * @param session - The session core backing both halves.\n * @param streamId - The QUIC stream id shared by the readable and writable halves.\n */\n public constructor(\n session: SessionCore,\n streamId: number,\n options: WebTransportSendStreamOptions = {},\n ) {\n this.readable = new WebTransportReceiveStream(session, streamId);\n this.writable = new WebTransportSendStream(session, streamId, options);\n }\n}\n","// SPDX-License-Identifier: Apache-2.0\n//! The `WebTransport` class: the W3C entry point.\n\nimport { SessionCore, createClientSession, type ConnectConfig } from './native.js';\nimport { WebTransportError } from './errors.js';\nimport { WebTransportDatagramDuplexStream } from './datagrams.js';\nimport {\n WebTransportBidirectionalStream,\n WebTransportReceiveStream,\n WebTransportSendStream,\n WebTransportSendGroup,\n type WebTransportSendStreamOptions,\n} from './streams.js';\nimport type {\n BinarySource,\n WebTransportCloseInfo,\n WebTransportCloseOptions,\n WebTransportOptions,\n WebTransportReliabilityMode,\n WebTransportConnectionStats,\n} from './types.js';\n\n/**\n * Normalize a {@link BinarySource} into a `Uint8Array` view over the same\n * memory, without copying.\n *\n * @param src - A typed array or `DataView`, or a raw `ArrayBuffer`.\n * @returns A `Uint8Array`: the whole buffer when `src` is an `ArrayBuffer`,\n * otherwise a view restricted to the source view's own `byteOffset` and\n * `byteLength` so a subview does not expose bytes outside its window.\n * @internal\n */\nfunction toBytes(src: BinarySource): Uint8Array {\n if (src instanceof ArrayBuffer) return new Uint8Array(src);\n return new Uint8Array(src.buffer, src.byteOffset, src.byteLength);\n}\n\n/**\n * Validate a URL and {@link WebTransportOptions} and flatten them into the\n * {@link ConnectConfig} the native `connect` function expects.\n *\n * @param url - The session URL. Must be a `string` beginning with `https://`.\n * @param options - Caller-supplied session options.\n * @returns The normalized connect configuration (URL, SHA-256 hash pins,\n * insecure flag, origin, and parallel header name/value arrays).\n * @throws WebTransportError with `source: 'session'` if `url` is not an\n * `https://` string, if a certificate hash uses an algorithm other than\n * `sha-256`, or if a `sha-256` hash value is not exactly 32 bytes.\n * @remarks Each entry of `options.serverCertificateHashes` is checked: the\n * algorithm is compared case-insensitively against `sha-256` and the value is\n * converted with {@link toBytes} and required to be 32 bytes long.\n * `options.headers` is split into parallel `headerNames` and `headerValues`\n * arrays. Missing optional fields default to `insecure: false` and\n * `origin: null`.\n * @internal\n */\nfunction buildConfig(url: string, options: WebTransportOptions): ConnectConfig {\n if (typeof url !== 'string' || !url.startsWith('https://')) {\n throw new WebTransportError(`invalid WebTransport URL: ${url}`, { source: 'session' });\n }\n\n const hashes: Uint8Array[] = [];\n for (const hash of options.serverCertificateHashes ?? []) {\n const algorithm = hash.algorithm.toLowerCase();\n if (algorithm !== 'sha-256') {\n throw new WebTransportError(\n `unsupported certificate hash algorithm: ${hash.algorithm} (only sha-256)`,\n { source: 'session' },\n );\n }\n const bytes = toBytes(hash.value);\n if (bytes.byteLength !== 32) {\n throw new WebTransportError('sha-256 certificate hash must be 32 bytes', {\n source: 'session',\n });\n }\n hashes.push(bytes);\n }\n\n const headerNames: string[] = [];\n const headerValues: string[] = [];\n for (const [name, value] of Object.entries(options.headers ?? {})) {\n headerNames.push(name);\n headerValues.push(value);\n }\n\n return {\n url,\n hashes,\n insecure: options.insecure ?? false,\n origin: options.origin ?? null,\n headerNames,\n headerValues,\n protocols: options.protocols ?? [],\n };\n}\n\n/**\n * The symmetric surface of an established WebTransport session (streams and\n * datagrams), shared by the client {@link WebTransport} and the server-side\n * session (`WebTransportServerSession` in `src/server.ts`).\n *\n * @remarks Wraps a {@link SessionCore}, which turns the callback-based native\n * ABI into promises and per-stream sinks. Peer-initiated streams surface on\n * {@link WebTransportSession.incomingBidirectionalStreams} and\n * {@link WebTransportSession.incomingUnidirectionalStreams}; datagrams are\n * exposed through {@link WebTransportSession.datagrams}.\n * @see {@link WebTransport} for the client entry point.\n */\nexport class WebTransportSession {\n /**\n * The event dispatcher and command surface backing this session. Shared with\n * the datagram and stream wrappers so they can issue native commands and\n * register their inbound sinks. Protected so the server-side subclass can\n * reach it while it stays hidden from public API consumers.\n * @internal\n */\n protected readonly core: SessionCore;\n /**\n * The session's datagram transport: a {@link WebTransportDatagramDuplexStream}\n * whose `readable` yields inbound datagrams and `writable` sends them.\n * Datagrams are unreliable and unordered; ones that do not fit the queue are\n * dropped rather than buffered.\n */\n public readonly datagrams: WebTransportDatagramDuplexStream;\n /**\n * A `ReadableStream` that yields a {@link WebTransportBidirectionalStream} for\n * every bidirectional stream the peer opens. Fed by the core's incoming\n * handler; it closes when the session closes cleanly and errors if the\n * session terminates abnormally.\n */\n public readonly incomingBidirectionalStreams: ReadableStream<WebTransportBidirectionalStream>;\n /**\n * A `ReadableStream` that yields a receive-only\n * {@link WebTransportReceiveStream} for every unidirectional stream the peer\n * opens. Fed by the core's incoming handler; it closes on clean session close\n * and errors on abnormal termination.\n */\n public readonly incomingUnidirectionalStreams: ReadableStream<WebTransportReceiveStream>;\n /**\n * Guards {@link WebTransportSession.close} so that repeated calls are no-ops\n * and the native close is issued at most once.\n * @internal\n */\n private closeCalled = false;\n\n /**\n * Wire up the session surface around an existing {@link SessionCore}.\n *\n * @param core - The event dispatcher and command core for this session. For\n * the client this is a freshly connected client session; for the server it is\n * a session-scoped core created by the server driver.\n * @remarks Creates the {@link WebTransportSession.datagrams} duplex, then\n * constructs the two incoming-stream `ReadableStream`s and captures their\n * controllers via the `start` callback. Registers an incoming handler on\n * `core` so each peer-opened bidi/uni stream is wrapped and enqueued;\n * `enqueue` is wrapped in try/catch because it throws once the consumer has\n * cancelled the reader, and that error must not escape native event dispatch.\n * Finally it observes `core.closed`: on clean close both controllers are\n * closed via {@link safeClose}, and on rejection both are errored with the\n * failure reason via {@link safeError}.\n */\n public constructor(core: SessionCore) {\n this.core = core;\n this.datagrams = new WebTransportDatagramDuplexStream(core);\n\n let bidiController!: ReadableStreamDefaultController<WebTransportBidirectionalStream>;\n let uniController!: ReadableStreamDefaultController<WebTransportReceiveStream>;\n this.incomingBidirectionalStreams = new ReadableStream<WebTransportBidirectionalStream>({\n start: (c) => {\n bidiController = c;\n },\n });\n this.incomingUnidirectionalStreams = new ReadableStream<WebTransportReceiveStream>({\n start: (c) => {\n uniController = c;\n },\n });\n\n core.setIncomingHandler({\n onBidi: (id) => {\n // Guard: enqueue throws if the consumer already cancelled the\n // reader, and that must not escape the native event dispatch.\n try {\n bidiController.enqueue(new WebTransportBidirectionalStream(core, id));\n } catch {\n // consumer no longer reading incoming bidi streams\n }\n },\n onUni: (id) => {\n try {\n uniController.enqueue(new WebTransportReceiveStream(core, id));\n } catch {\n // consumer no longer reading incoming uni streams\n }\n },\n });\n\n core.closed.promise.then(\n () => {\n safeClose(bidiController);\n safeClose(uniController);\n },\n (err: unknown) => {\n safeError(bidiController, err);\n safeError(uniController, err);\n },\n );\n }\n\n /**\n * A promise that resolves once the session handshake completes and the\n * session is established, and rejects if the session fails or closes before\n * it becomes ready.\n * @returns The core's `ready` promise.\n */\n public get ready(): Promise<void> {\n return this.core.ready.promise;\n }\n\n /**\n * A promise that resolves with the {@link WebTransportCloseInfo} (close code\n * and reason) when the session ends cleanly, and rejects with a\n * {@link WebTransportError} on abnormal termination or if the session never\n * became ready.\n * @returns The core's `closed` promise.\n */\n public get closed(): Promise<WebTransportCloseInfo> {\n return this.core.closed.promise;\n }\n\n /**\n * A promise that resolves when the peer signals it is draining the session\n * (a `DRAIN_WEBTRANSPORT_SESSION` capsule): it intends to close soon, so you\n * should stop opening new streams, but the session and its existing streams\n * stay usable until {@link closed}. Never rejects.\n * @returns The core's `draining` promise.\n */\n public get draining(): Promise<void> {\n return this.core.draining.promise;\n }\n\n /**\n * The reliability modes this session supports. `'pending'` until the session\n * is established, then `'supports-unreliable'` because this transport always\n * offers both reliable streams and unreliable datagrams.\n */\n public get reliability(): WebTransportReliabilityMode {\n return this.core.isReady ? 'supports-unreliable' : 'pending';\n }\n\n /**\n * The negotiated WebTransport subprotocol, or the empty string when none was\n * negotiated (or before the session is established). Matches the W3C\n * `WebTransport.protocol` attribute.\n */\n public get protocol(): string {\n return this.core.protocol;\n }\n\n /**\n * Open a new outbound bidirectional stream.\n *\n * @returns A promise resolving to a {@link WebTransportBidirectionalStream}\n * (paired readable and writable halves) once the native side reports the new\n * stream id.\n * @throws WebTransportError (the returned promise rejects) if the session is\n * already closed or was never attached.\n */\n public async createBidirectionalStream(\n options: WebTransportSendStreamOptions = {},\n ): Promise<WebTransportBidirectionalStream> {\n const id = await this.core.openStream(true);\n return new WebTransportBidirectionalStream(this.core, id, options);\n }\n\n /**\n * Open a new outbound unidirectional (send-only) stream.\n *\n * @returns A promise resolving to a {@link WebTransportSendStream} once the\n * native side reports the new stream id.\n * @throws WebTransportError (the returned promise rejects) if the session is\n * already closed or was never attached.\n */\n public async createUnidirectionalStream(\n options: WebTransportSendStreamOptions = {},\n ): Promise<WebTransportSendStream> {\n const id = await this.core.openStream(false);\n return new WebTransportSendStream(this.core, id, options);\n }\n\n /**\n * Create a {@link WebTransportSendGroup} for scheduling several streams'\n * sends relative to one another via each stream's `sendOrder`.\n */\n public createSendGroup(): WebTransportSendGroup {\n return new WebTransportSendGroup();\n }\n\n /**\n * Close the session gracefully, notifying the peer with an application code\n * and reason.\n *\n * @param closeInfo - Close options. `closeInfo.closeCode` defaults to `0` and\n * `closeInfo.reason` defaults to `''`; both are forwarded to the native\n * close.\n * @defaultValue `closeInfo` defaults to `{}` (close code `0`, empty reason).\n * @remarks Idempotent: guarded by {@link WebTransportSession.closeCalled} so\n * only the first call takes effect and later calls are no-ops. Delegates to\n * the core, which issues the native `closeSession` (a graceful\n * CLOSE_WEBTRANSPORT_SESSION capsule plus FIN, then QUIC close) only while the\n * session is still attached and not already closed.\n */\n public close(closeInfo: WebTransportCloseOptions = {}): void {\n if (this.closeCalled) return;\n this.closeCalled = true;\n this.core.close(closeInfo.closeCode ?? 0, closeInfo.reason ?? '');\n }\n\n /**\n * Tell the peer this session is draining by sending a\n * `DRAIN_WEBTRANSPORT_SESSION` capsule: a graceful signal that you intend to\n * stop using it soon, while the session and its streams stay open until\n * {@link close}. The peer observes this through its {@link draining} promise.\n * A Node extension beyond the W3C API, useful for a server shedding load.\n */\n public drain(): void {\n this.core.drain();\n }\n\n /**\n * Snapshot connection statistics (bytes and packets transferred, RTT, and\n * datagram counters).\n * @returns A promise resolving to {@link WebTransportConnectionStats}.\n * @throws WebTransportError (the promise rejects) if the session is closed.\n */\n public getStats(): Promise<WebTransportConnectionStats> {\n return this.core.getStats();\n }\n\n /**\n * Export keying material from the session's TLS connection (RFC 5705),\n * matching the W3C `exportKeyingMaterial`. Both endpoints derive identical\n * bytes for the same `label`, `context`, and `outputLength`, and nothing\n * outside the TLS session can reproduce them, which makes the result\n * suitable for channel binding.\n *\n * @param label - The exporter label, a {@link BinarySource}.\n * @param context - The exporter context, a {@link BinarySource}; pass an\n * empty buffer for no application context.\n * @param outputLength - Number of bytes of keying material to produce.\n * @returns A promise resolving to a `Uint8Array` of `outputLength` bytes.\n * @throws WebTransportError (the promise rejects) if the session is closed or\n * the TLS export fails (for example, before the handshake completes).\n */\n public exportKeyingMaterial(\n label: BinarySource,\n context: BinarySource,\n outputLength: number,\n ): Promise<Uint8Array> {\n return this.core.exportKeyingMaterial(toBytes(label), toBytes(context), outputLength);\n }\n}\n\n/**\n * A WebTransport client session, matching the\n * [W3C WebTransport](https://w3c.github.io/webtransport/) interface.\n *\n * @remarks Constructs and begins connecting a native client session\n * immediately; setup (DNS, socket bind, TLS/QUIC handshake) runs asynchronously\n * on the driver thread. Await {@link WebTransportSession.ready | ready} before\n * use, and observe {@link WebTransportSession.closed | closed} for termination.\n * @example\n * ```ts\n * const wt = new WebTransport('https://example.com:4433/wt');\n * await wt.ready;\n * const stream = await wt.createBidirectionalStream();\n * ```\n */\nexport class WebTransport extends WebTransportSession {\n /**\n * Create and begin connecting a WebTransport client session.\n *\n * @param url - The session URL; must be an `https://` URL.\n * @param options - Session options: certificate pinning, extra headers,\n * origin, and the Node-specific `insecure` flag.\n * @defaultValue `options` defaults to `{}`.\n * @throws WebTransportError synchronously if {@link buildConfig} rejects the\n * URL or a certificate hash. Asynchronous setup failures (DNS, bind,\n * handshake) instead reject {@link WebTransportSession.ready | ready} and\n * {@link WebTransportSession.closed | closed}.\n * @remarks Validates and normalizes inputs via {@link buildConfig}, then\n * calls {@link createClientSession} to spawn the native driver thread and\n * passes the resulting {@link SessionCore} to the base constructor.\n */\n public constructor(url: string, options: WebTransportOptions = {}) {\n super(createClientSession(buildConfig(url, options)));\n }\n\n /**\n * The headers from the server's Extended CONNECT `2xx` response, as a\n * `Headers` object (empty until the session is established). Matches the W3C\n * `WebTransport.responseHeaders` attribute.\n */\n public get responseHeaders(): Headers {\n return new Headers(this.core.responseHeaders);\n }\n}\n\n/**\n * Call a controller's `close()`, swallowing the error it throws when the\n * controller is already closed or errored.\n *\n * @param controller - Any object exposing a `close()` method (a readable stream\n * default controller).\n * @internal\n */\nfunction safeClose(controller: { close(): void }): void {\n try {\n controller.close();\n } catch {\n // already closed\n }\n}\n\n/**\n * Call a controller's `error()` with a reason, swallowing the error it throws\n * when the controller is already closed or errored.\n *\n * @param controller - Any object exposing an `error()` method (a readable stream\n * default controller).\n * @param reason - The failure reason to surface to the stream's consumer.\n * @internal\n */\nfunction safeError(controller: { error(reason?: unknown): void }, reason: unknown): void {\n try {\n controller.error(reason);\n } catch {\n // already closed/errored\n }\n}\n","// SPDX-License-Identifier: Apache-2.0\n//! The `WebTransportServer` accepts WebTransport sessions from clients. Each\n//! established session is a {@link WebTransportServerSession}, which shares the\n//! full stream/datagram surface with the client `WebTransport`.\n\nimport { WebTransportError } from './errors.js';\nimport { loadNative } from './loader.js';\nimport {\n NativeEventType,\n SessionCore,\n ServerTransport,\n type NativeAddon,\n type NativeServerHandle,\n type ServerNativeEvent,\n} from './native.js';\nimport { WebTransportSession } from './webtransport.js';\n\n/**\n * A promise paired with its externally callable `resolve` and `reject`, so a\n * value can be settled from outside the executor (for example from a native\n * event callback).\n *\n * @typeParam T - The type the promise resolves to.\n * @internal Private helper, not part of the published package API.\n */\ninterface Deferred<T> {\n /** The promise controlled by this deferred. */\n promise: Promise<T>;\n /** Fulfills {@link Deferred.promise} with the given value. */\n resolve: (value: T) => void;\n /** Rejects {@link Deferred.promise} with the given reason. */\n reject: (reason: unknown) => void;\n}\n\n/**\n * Create a {@link Deferred}: a fresh promise together with its `resolve` and\n * `reject` functions captured from the executor.\n *\n * @typeParam T - The type the promise resolves to.\n * @returns A deferred whose `resolve`/`reject` settle its `promise`.\n * @internal Private helper, not part of the published package API.\n */\nfunction deferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n\n/** Options for {@link WebTransportServer}. */\nexport interface WebTransportServerOptions {\n /** UDP port to listen on. Use `0` to let the OS pick (read it back via `port`). */\n port: number;\n /**\n * Interface (IP address) to bind.\n *\n * @defaultValue `'0.0.0.0'` (all IPv4 interfaces).\n */\n host?: string;\n /** Path to the PEM certificate chain file. */\n cert: string;\n /** Path to the PEM private-key file. */\n key: string;\n /**\n * Bind with `SO_REUSEPORT` (Unix only) so multiple processes, for example\n * Node `cluster` workers, can share one listening port and let the kernel\n * load-balance connections across them. Ignored on Windows, where the flag\n * does not exist.\n *\n * @defaultValue `false`\n */\n reusePort?: boolean;\n /**\n * WebTransport subprotocols this server supports, in preference order. For\n * each CONNECT, the first supported protocol that the client also offered is\n * selected and echoed back (exposed as {@link WebTransportServerSession.protocol}).\n */\n supportedProtocols?: string[];\n /**\n * If set, only Extended CONNECTs whose `origin` header is in this list are\n * accepted; all others are rejected with a `403`. When omitted, any origin is\n * accepted (the application can still inspect {@link WebTransportSessionRequest.origin}).\n */\n allowedOrigins?: string[];\n /**\n * Extra headers to include on every `200` CONNECT response, for example a\n * server version or capability token, exposed to the client as\n * {@link WebTransport.responseHeaders}.\n */\n responseHeaders?: Record<string, string>;\n}\n\n/**\n * Metadata about the Extended CONNECT that opened a server session, extracted\n * from the client's HTTP/3 CONNECT request pseudo-headers and headers.\n */\nexport interface WebTransportSessionRequest {\n /** The `:authority` pseudo-header of the client's CONNECT request. */\n authority: string;\n /** The `:path` pseudo-header of the client's CONNECT request. */\n path: string;\n /** The `origin` header value, or `null` if the client did not send one. */\n origin: string | null;\n /** Any additional (non-pseudo) request headers, keyed by header name. */\n headers: Record<string, string>;\n /** The subprotocols the client offered in `wt-available-protocols`. */\n requestedProtocols: string[];\n /** The subprotocol the server selected for this session, or `null` if none. */\n protocol: string | null;\n /** The client's remote IP address at session establishment. */\n remoteAddress: string;\n /** The client's remote UDP port at session establishment. */\n remotePort: number;\n}\n\n/**\n * A server-side WebTransport session. Symmetric with the client `WebTransport`\n * (streams + datagrams inherited from {@link WebTransportSession}), plus the\n * request metadata carried on the client's CONNECT.\n */\nexport class WebTransportServerSession extends WebTransportSession {\n /** The `:authority` of the client's CONNECT request. */\n public readonly authority: string;\n /** The `:path` of the client's CONNECT request. */\n public readonly path: string;\n /** The `origin` header, if the client sent one, otherwise `null`. */\n public readonly origin: string | null;\n /** Any additional (non-pseudo) request headers, keyed by header name. */\n public readonly headers: Record<string, string>;\n /** The subprotocols the client offered in `wt-available-protocols`. */\n public readonly requestedProtocols: string[];\n /**\n * The client's remote IP address, as reported by the transport when the\n * session was established. The same for every stream and datagram on this\n * session, since they all share the one QUIC connection.\n */\n public readonly remoteAddress: string;\n /** The client's remote UDP port at session establishment. */\n public readonly remotePort: number;\n\n /**\n * Wrap an established session core together with the CONNECT metadata that\n * opened it. Called by {@link WebTransportServer} when a new session becomes\n * ready; not intended for direct construction by users.\n *\n * @param core - The dispatcher/command core backing this session, already\n * attached to a {@link ServerTransport}.\n * @param request - The CONNECT metadata (authority, path, origin, headers)\n * plus the client's remote address, copied onto this session's public fields.\n */\n public constructor(core: SessionCore, request: WebTransportSessionRequest) {\n super(core);\n this.authority = request.authority;\n this.path = request.path;\n this.origin = request.origin;\n this.headers = request.headers;\n this.requestedProtocols = request.requestedProtocols;\n this.remoteAddress = request.remoteAddress;\n this.remotePort = request.remotePort;\n }\n}\n\n/**\n * A WebTransport server. Bind a port with a certificate, then consume\n * {@link incomingSessions}.\n *\n * @example\n * ```ts\n * const server = new WebTransportServer({ port: 4433, cert, key });\n * await server.ready;\n * for await (const session of readable(server.incomingSessions)) {\n * // handle the session\n * }\n * ```\n *\n * @see {@link WebTransportServerSession} for the per-session surface.\n */\nexport class WebTransportServer {\n /** The loaded native addon, source of the `server*` command functions. */\n private readonly native: NativeAddon;\n /** Opaque native server handle returned by `serverListen`. */\n private readonly handle: NativeServerHandle;\n /** Live sessions keyed by their native session id, for event routing. */\n private readonly sessions = new Map<number, SessionCore>();\n /** Settled when the native side reports `listening`; backs {@link ready}. */\n private readonly readyD = deferred<void>();\n /**\n * Settled when the server stops (`serverClosed`) or fatally fails\n * (`serverError`); backs {@link closed}.\n */\n private readonly closedD = deferred<void>();\n /** Controller for {@link incomingSessions}; captured in its `start`. */\n private incomingController!: ReadableStreamDefaultController<WebTransportServerSession>;\n /** The UDP port actually bound, learned from the `listening` event. */\n private boundPort = 0;\n /** Guards {@link close} so shutdown is issued at most once. */\n private closeCalled = false;\n\n /**\n * The sessions clients open, delivered as they are established. Each pull\n * yields a {@link WebTransportServerSession}. The stream is closed when the\n * server stops or errors.\n */\n public readonly incomingSessions: ReadableStream<WebTransportServerSession>;\n\n /**\n * Load the native addon and start listening immediately.\n *\n * Sets up {@link incomingSessions} (capturing its controller), attaches\n * no-op catch handlers to the internal ready/closed promises so they never\n * surface as unhandled rejections, then calls the native `serverListen` with\n * the given certificate, key, host, port and reuse-port flag, wiring every\n * native event to {@link onEvent}.\n *\n * @param options - Bind address, port, certificate/key paths and reuse-port\n * flag. `host` defaults to `'0.0.0.0'` and `reusePort` defaults to `false`.\n * @see {@link ready} to await binding and {@link WebTransportServerOptions}.\n */\n public constructor(options: WebTransportServerOptions) {\n this.native = loadNative();\n void this.readyD.promise.catch(() => {});\n void this.closedD.promise.catch(() => {});\n\n this.incomingSessions = new ReadableStream<WebTransportServerSession>({\n start: (c) => {\n this.incomingController = c;\n },\n });\n\n const responseHeaderNames: string[] = [];\n const responseHeaderValues: string[] = [];\n for (const [name, value] of Object.entries(options.responseHeaders ?? {})) {\n responseHeaderNames.push(name);\n responseHeaderValues.push(value);\n }\n\n this.handle = this.native.serverListen(\n options.cert,\n options.key,\n options.host ?? '0.0.0.0',\n options.port,\n options.reusePort ?? false,\n options.supportedProtocols ?? [],\n options.allowedOrigins ?? null,\n responseHeaderNames,\n responseHeaderValues,\n (ev) => this.onEvent(ev),\n );\n }\n\n /**\n * Resolves once the server is listening (the native `listening` event has\n * arrived); rejects if the server fails before it binds.\n */\n public get ready(): Promise<void> {\n return this.readyD.promise;\n }\n\n /**\n * Resolves when the server has stopped cleanly (`serverClosed`), rejects on\n * a fatal server error (`serverError`).\n */\n public get closed(): Promise<void> {\n return this.closedD.promise;\n }\n\n /** The UDP port the server is bound to (valid after {@link ready}). */\n public get port(): number {\n return this.boundPort;\n }\n\n /**\n * Stop the server and all its sessions. Idempotent: repeated calls after the\n * first are ignored. Triggers the native `serverShutdown`, which eventually\n * drives a `serverClosed` event that settles {@link closed} and finishes any\n * remaining sessions.\n */\n public close(): void {\n if (this.closeCalled) return;\n this.closeCalled = true;\n this.native.serverShutdown(this.handle);\n }\n\n /**\n * Handle one native server event. Server-level events (`listening`,\n * `serverError`, `serverClosed`) settle the server's ready/closed promises\n * and, on stop or error, finish all sessions and close\n * {@link incomingSessions}. Session-scoped events carry a `session` id: a\n * `serverReady` creates and registers a new {@link SessionCore} (attached to\n * a {@link ServerTransport}), wraps it in a {@link WebTransportServerSession}\n * and enqueues it; every session-scoped event is then dispatched to the\n * matching core.\n *\n * @param ev - The event delivered by the native `serverListen` callback.\n * @remarks Enqueue into {@link incomingSessions} is guarded: if the consumer\n * has stopped reading, the thrown error is swallowed so it cannot escape\n * the native event dispatch. On `serverError`, the `WebTransportError` is\n * created with `source: 'session'`.\n */\n private onEvent(ev: ServerNativeEvent): void {\n switch (ev.type) {\n case NativeEventType.Listening: {\n this.boundPort = ev.port;\n this.readyD.resolve();\n return;\n }\n case NativeEventType.ServerError: {\n const err = new WebTransportError(ev.message, { source: 'session' });\n this.readyD.reject(err);\n this.closedD.reject(err);\n this.finishAllSessions();\n safeCloseController(this.incomingController);\n return;\n }\n case NativeEventType.ServerClosed: {\n this.closedD.resolve();\n this.finishAllSessions();\n safeCloseController(this.incomingController);\n return;\n }\n }\n\n // Session-scoped event.\n const sessionId = ev.session;\n if (ev.type === NativeEventType.ServerReady) {\n const core = new SessionCore();\n core.attach(new ServerTransport(this.native, this.handle, sessionId));\n this.sessions.set(sessionId, core);\n void core.closed.promise.finally(() => this.sessions.delete(sessionId));\n const session = new WebTransportServerSession(core, {\n authority: ev.authority,\n path: ev.path,\n origin: ev.origin,\n headers: ev.headers,\n requestedProtocols: ev.requestedProtocols,\n protocol: ev.protocol,\n remoteAddress: ev.remoteAddress,\n remotePort: ev.remotePort,\n });\n try {\n this.incomingController.enqueue(session);\n } catch {\n // consumer no longer reading incoming sessions\n }\n }\n\n this.sessions.get(sessionId)?.dispatch(ev);\n }\n\n /**\n * Settle every live session when the server stops, so their `ready`/`closed`\n * promises never hang and the session map does not leak.\n *\n * @remarks Dispatches a synthetic clean `closed` event (code `0`, empty\n * reason, `remote: false`) to each session core, then clears the map. The\n * per-core `closed.finally` handler registered in {@link onEvent} would\n * also remove entries, but the map is cleared here unconditionally.\n */\n private finishAllSessions(): void {\n for (const core of this.sessions.values()) {\n core.dispatch({\n type: NativeEventType.Closed,\n code: 0,\n reason: new Uint8Array(),\n remote: false,\n });\n }\n this.sessions.clear();\n }\n}\n\n/**\n * Close a ReadableStream controller, ignoring the error thrown if it is already\n * closed. Used when the server stops or errors so shutting the incoming-session\n * stream is safe regardless of its current state.\n *\n * @param controller - Any object exposing a `close()` method (the\n * {@link WebTransportServer.incomingSessions} controller).\n * @internal Private helper, not part of the published package API.\n */\nfunction safeCloseController(controller: { close(): void }): void {\n try {\n controller.close();\n } catch {\n // already closed\n }\n}\n"],"mappings":";AAUA,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAW9B,IAAMA,WAAU,cAAc,YAAY,GAAG;AAQ7C,IAAM,YAAY,QAAQ,cAAc,YAAY,GAAG,CAAC;AASxD,IAAM,eAAe,KAAK,WAAW,IAAI;AAUzC,SAAS,yBAA+B;AACpC,QAAM,QAAQ,OAAO,QAAQ,SAAS,KAAK,MAAM,GAAG,EAAE,CAAC,CAAC;AACxD,MAAI,UAAU,MAAM,UAAU,IAAI;AAC9B,UAAM,IAAI;AAAA,MACN,iEAAiE,QAAQ,SAAS,IAAI;AAAA,IAC1F;AAAA,EACJ;AACJ;AAYA,SAAS,eAAuB;AAC5B,SAAO;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