@webtransport-bun/webtransport 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +54 -0
- package/dist/errors.d.ts +36 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +38 -0
- package/dist/index.d.ts +358 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +848 -0
- package/dist/streams.d.ts +72 -0
- package/dist/streams.d.ts.map +1 -0
- package/dist/streams.js +165 -0
- package/package.json +48 -0
- package/prebuilds/SHA256SUMS +1 -0
- package/prebuilds/webtransport-native.darwin-arm64.node +0 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,848 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
* @module @webtransport-bun/webtransport
|
|
4
|
+
*
|
|
5
|
+
* Production-ready WebTransport for Bun, backed by napi-rs + wtransport (Rust).
|
|
6
|
+
* Supports in-process server, client (Node API and W3C-style facade), datagrams, and streams.
|
|
7
|
+
*/
|
|
8
|
+
if (typeof globalThis.Bun === "undefined") {
|
|
9
|
+
throw new Error("@webtransport-bun/webtransport requires Bun (>=1.3.9). See https://bun.sh");
|
|
10
|
+
}
|
|
11
|
+
// Re-export stream symbols and helpers
|
|
12
|
+
export { WT_RESET, WT_STOP_SENDING } from "./streams.js";
|
|
13
|
+
import { BidiStream, SendStream, RecvStream } from "./streams.js";
|
|
14
|
+
/**
|
|
15
|
+
* Stable error codes. Use with {@link WebTransportError.code} for programmatic handling.
|
|
16
|
+
* @see WebTransportError
|
|
17
|
+
*/
|
|
18
|
+
export { E_TLS, E_HANDSHAKE_TIMEOUT, E_SESSION_CLOSED, E_SESSION_IDLE_TIMEOUT, E_STREAM_RESET, E_STOP_SENDING, E_QUEUE_FULL, E_BACKPRESSURE_TIMEOUT, E_LIMIT_EXCEEDED, E_RATE_LIMITED, E_INTERNAL, WebTransportError, } from "./errors.js";
|
|
19
|
+
import { E_INTERNAL, E_HANDSHAKE_TIMEOUT, E_SESSION_CLOSED, WebTransportError, } from "./errors.js";
|
|
20
|
+
const E_CODE_RE = /^E_[A-Z_]+/;
|
|
21
|
+
function toWebTransportError(err) {
|
|
22
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
23
|
+
const match = E_CODE_RE.exec(msg);
|
|
24
|
+
if (match)
|
|
25
|
+
return new WebTransportError(match[0], msg);
|
|
26
|
+
return new WebTransportError(E_INTERNAL, msg);
|
|
27
|
+
}
|
|
28
|
+
/** Default limit values from AGENTS.md */
|
|
29
|
+
export const DEFAULT_LIMITS = {
|
|
30
|
+
maxSessions: 2000,
|
|
31
|
+
maxHandshakesInFlight: 200,
|
|
32
|
+
maxStreamsPerSessionBidi: 200,
|
|
33
|
+
maxStreamsPerSessionUni: 200,
|
|
34
|
+
maxStreamsGlobal: 50_000,
|
|
35
|
+
maxDatagramSize: 1200,
|
|
36
|
+
maxQueuedBytesGlobal: 512 * 1024 * 1024, // 512 MiB
|
|
37
|
+
maxQueuedBytesPerSession: 2 * 1024 * 1024, // 2 MiB
|
|
38
|
+
maxQueuedBytesPerStream: 256 * 1024, // 256 KiB
|
|
39
|
+
backpressureTimeoutMs: 5000,
|
|
40
|
+
handshakeTimeoutMs: 10_000,
|
|
41
|
+
idleTimeoutMs: 60_000,
|
|
42
|
+
};
|
|
43
|
+
/** Default rate-limit values from AGENTS.md */
|
|
44
|
+
export const DEFAULT_RATE_LIMITS = {
|
|
45
|
+
handshakesPerSec: 20,
|
|
46
|
+
handshakesBurst: 40,
|
|
47
|
+
handshakesBurstPerPrefix: 100,
|
|
48
|
+
streamsPerSec: 200,
|
|
49
|
+
streamsBurst: 400,
|
|
50
|
+
datagramsPerSec: 2000,
|
|
51
|
+
datagramsBurst: 5000,
|
|
52
|
+
};
|
|
53
|
+
/** Prometheus metric name prefix. Override via env WEBTRANSPORT_METRICS_PREFIX. */
|
|
54
|
+
export const METRICS_PREFIX = process.env.WEBTRANSPORT_METRICS_PREFIX ?? "webtransport_";
|
|
55
|
+
function escapePromLabelValue(v) {
|
|
56
|
+
return String(v)
|
|
57
|
+
.replace(/\\/g, "\\\\")
|
|
58
|
+
.replace(/\n/g, "\\n")
|
|
59
|
+
.replace(/"/g, '\\"');
|
|
60
|
+
}
|
|
61
|
+
function sanitizePromLabelName(k) {
|
|
62
|
+
const safe = k.replace(/[^a-zA-Z0-9_]/g, "_");
|
|
63
|
+
return /^[a-zA-Z_]/.test(safe) ? safe : `_${safe}`;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Convert MetricsSnapshot to Prometheus exposition format (text).
|
|
67
|
+
* Gauges: sessions_active, handshakes_in_flight, streams_active, session_tasks_active, stream_tasks_active, queued_bytes_global.
|
|
68
|
+
* Counters: datagrams_in, datagrams_out, datagrams_dropped, backpressure_wait_total, backpressure_timeout_total, rate_limited_total, limit_exceeded_total.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```ts
|
|
72
|
+
* const snapshot = server.metricsSnapshot();
|
|
73
|
+
* const text = metricsToPrometheus(snapshot, { serverId: "main" });
|
|
74
|
+
* response.end(text); // Content-Type: text/plain; version=0.0.4
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
export function metricsToPrometheus(m, labels) {
|
|
78
|
+
const l = labels
|
|
79
|
+
? "," + Object.entries(labels)
|
|
80
|
+
.map(([k, v]) => `${sanitizePromLabelName(k)}="${escapePromLabelValue(v)}"`)
|
|
81
|
+
.join(",")
|
|
82
|
+
: "";
|
|
83
|
+
const p = METRICS_PREFIX;
|
|
84
|
+
const lines = [
|
|
85
|
+
`# HELP ${p}sessions_active Current open sessions`,
|
|
86
|
+
`# TYPE ${p}sessions_active gauge`,
|
|
87
|
+
`${p}sessions_active${l} ${m.sessionsActive}`,
|
|
88
|
+
`# HELP ${p}handshakes_in_flight Handshakes in progress`,
|
|
89
|
+
`# TYPE ${p}handshakes_in_flight gauge`,
|
|
90
|
+
`${p}handshakes_in_flight${l} ${m.handshakesInFlight}`,
|
|
91
|
+
`# HELP ${p}streams_active Active streams`,
|
|
92
|
+
`# TYPE ${p}streams_active gauge`,
|
|
93
|
+
`${p}streams_active${l} ${m.streamsActive}`,
|
|
94
|
+
`# HELP ${p}session_tasks_active Internal session tasks`,
|
|
95
|
+
`# TYPE ${p}session_tasks_active gauge`,
|
|
96
|
+
`${p}session_tasks_active${l} ${m.sessionTasksActive}`,
|
|
97
|
+
`# HELP ${p}stream_tasks_active Internal stream tasks`,
|
|
98
|
+
`# TYPE ${p}stream_tasks_active gauge`,
|
|
99
|
+
`${p}stream_tasks_active${l} ${m.streamTasksActive}`,
|
|
100
|
+
`# HELP ${p}queued_bytes_global Bytes queued globally`,
|
|
101
|
+
`# TYPE ${p}queued_bytes_global gauge`,
|
|
102
|
+
`${p}queued_bytes_global${l} ${m.queuedBytesGlobal}`,
|
|
103
|
+
`# HELP ${p}datagrams_in Datagrams received`,
|
|
104
|
+
`# TYPE ${p}datagrams_in counter`,
|
|
105
|
+
`${p}datagrams_in${l} ${m.datagramsIn}`,
|
|
106
|
+
`# HELP ${p}datagrams_out Datagrams sent`,
|
|
107
|
+
`# TYPE ${p}datagrams_out counter`,
|
|
108
|
+
`${p}datagrams_out${l} ${m.datagramsOut}`,
|
|
109
|
+
`# HELP ${p}datagrams_dropped Datagrams dropped`,
|
|
110
|
+
`# TYPE ${p}datagrams_dropped counter`,
|
|
111
|
+
`${p}datagrams_dropped${l} ${m.datagramsDropped}`,
|
|
112
|
+
`# HELP ${p}backpressure_wait_total Times senders waited on backpressure`,
|
|
113
|
+
`# TYPE ${p}backpressure_wait_total counter`,
|
|
114
|
+
`${p}backpressure_wait_total${l} ${m.backpressureWaitCount}`,
|
|
115
|
+
`# HELP ${p}backpressure_timeout_total Times backpressure timeout fired`,
|
|
116
|
+
`# TYPE ${p}backpressure_timeout_total counter`,
|
|
117
|
+
`${p}backpressure_timeout_total${l} ${m.backpressureTimeoutCount}`,
|
|
118
|
+
`# HELP ${p}rate_limited_total Sessions rejected by rate limit`,
|
|
119
|
+
`# TYPE ${p}rate_limited_total counter`,
|
|
120
|
+
`${p}rate_limited_total${l} ${m.rateLimitedCount}`,
|
|
121
|
+
`# HELP ${p}limit_exceeded_total Sessions rejected (limits)`,
|
|
122
|
+
`# TYPE ${p}limit_exceeded_total counter`,
|
|
123
|
+
`${p}limit_exceeded_total${l} ${m.limitExceededCount}`,
|
|
124
|
+
];
|
|
125
|
+
return lines.join("\n") + "\n";
|
|
126
|
+
}
|
|
127
|
+
// ---------------------------------------------------------------------------
|
|
128
|
+
// Native addon loader
|
|
129
|
+
// ---------------------------------------------------------------------------
|
|
130
|
+
import { createRequire } from "node:module";
|
|
131
|
+
const _require = createRequire(import.meta.url);
|
|
132
|
+
const PLATFORM = process.platform;
|
|
133
|
+
const ARCH = process.arch;
|
|
134
|
+
let native;
|
|
135
|
+
const binaryCandidates = [
|
|
136
|
+
`webtransport-native.${PLATFORM}-${ARCH}.node`,
|
|
137
|
+
`webtransport-native.${PLATFORM}-${ARCH}-gnu.node`,
|
|
138
|
+
`webtransport-native.${PLATFORM}-${ARCH}-musl.node`,
|
|
139
|
+
];
|
|
140
|
+
const basePaths = [
|
|
141
|
+
"../../../crates/native",
|
|
142
|
+
"../prebuilds",
|
|
143
|
+
];
|
|
144
|
+
for (const base of basePaths) {
|
|
145
|
+
for (const candidate of binaryCandidates) {
|
|
146
|
+
try {
|
|
147
|
+
native = _require(`${base}/${candidate}`);
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (native)
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
// ---------------------------------------------------------------------------
|
|
158
|
+
// Server session implementation
|
|
159
|
+
// ---------------------------------------------------------------------------
|
|
160
|
+
class NativeServerSession {
|
|
161
|
+
#nativeHandle;
|
|
162
|
+
#closedPromise;
|
|
163
|
+
#closed = false;
|
|
164
|
+
constructor(nativeHandle, closedPromise) {
|
|
165
|
+
this.#nativeHandle = nativeHandle;
|
|
166
|
+
this.#closedPromise = closedPromise;
|
|
167
|
+
this.#closedPromise.then(() => { this.#closed = true; });
|
|
168
|
+
}
|
|
169
|
+
get id() {
|
|
170
|
+
return this.#nativeHandle.id;
|
|
171
|
+
}
|
|
172
|
+
get peer() {
|
|
173
|
+
return {
|
|
174
|
+
ip: this.#nativeHandle.peerIp,
|
|
175
|
+
port: this.#nativeHandle.peerPort,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
get ready() {
|
|
179
|
+
// Server sessions are already handshake-complete when onSession fires
|
|
180
|
+
return Promise.resolve();
|
|
181
|
+
}
|
|
182
|
+
get closed() {
|
|
183
|
+
return this.#closedPromise;
|
|
184
|
+
}
|
|
185
|
+
close(info) {
|
|
186
|
+
if (!this.#closed) {
|
|
187
|
+
this.#closed = true;
|
|
188
|
+
this.#nativeHandle.close(info?.code ?? null, info?.reason ?? null);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
async sendDatagram(data) {
|
|
192
|
+
if (this.#closed)
|
|
193
|
+
throw new WebTransportError(E_SESSION_CLOSED);
|
|
194
|
+
try {
|
|
195
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
|
|
196
|
+
await this.#nativeHandle.sendDatagram(buf);
|
|
197
|
+
}
|
|
198
|
+
catch (err) {
|
|
199
|
+
throw toWebTransportError(err);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
async *incomingDatagrams() {
|
|
203
|
+
while (!this.#closed) {
|
|
204
|
+
try {
|
|
205
|
+
const datagram = await this.#nativeHandle.readDatagram();
|
|
206
|
+
if (!datagram)
|
|
207
|
+
break;
|
|
208
|
+
yield datagram;
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
async createBidirectionalStream() {
|
|
216
|
+
if (this.#closed)
|
|
217
|
+
throw new WebTransportError(E_SESSION_CLOSED);
|
|
218
|
+
try {
|
|
219
|
+
const nativeStream = await this.#nativeHandle.createBidiStream();
|
|
220
|
+
return new BidiStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
throw toWebTransportError(err);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
async *incomingBidirectionalStreams() {
|
|
227
|
+
while (!this.#closed) {
|
|
228
|
+
try {
|
|
229
|
+
const nativeStream = await this.#nativeHandle.acceptBidiStream();
|
|
230
|
+
if (!nativeStream)
|
|
231
|
+
break;
|
|
232
|
+
yield new BidiStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
break;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
async createUnidirectionalStream() {
|
|
240
|
+
if (this.#closed)
|
|
241
|
+
throw new WebTransportError(E_SESSION_CLOSED);
|
|
242
|
+
try {
|
|
243
|
+
const nativeStream = await this.#nativeHandle.createUniStream();
|
|
244
|
+
return new SendStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
|
|
245
|
+
}
|
|
246
|
+
catch (err) {
|
|
247
|
+
throw toWebTransportError(err);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
async *incomingUnidirectionalStreams() {
|
|
251
|
+
while (!this.#closed) {
|
|
252
|
+
try {
|
|
253
|
+
const nativeStream = await this.#nativeHandle.acceptUniStream();
|
|
254
|
+
if (!nativeStream)
|
|
255
|
+
break;
|
|
256
|
+
yield new RecvStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
metricsSnapshot() {
|
|
264
|
+
return this.#nativeHandle.metricsSnapshot();
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
// ---------------------------------------------------------------------------
|
|
268
|
+
// createServer
|
|
269
|
+
// ---------------------------------------------------------------------------
|
|
270
|
+
/**
|
|
271
|
+
* Create an in-process WebTransport server.
|
|
272
|
+
*
|
|
273
|
+
* @param opts - Server configuration. Requires `port`, `tls` (certPem, keyPem), and `onSession` callback.
|
|
274
|
+
* @returns WebTransportServer with `address`, `close()`, and `metricsSnapshot()`.
|
|
275
|
+
* @throws Error if native addon is not loaded.
|
|
276
|
+
*
|
|
277
|
+
* @example
|
|
278
|
+
* ```ts
|
|
279
|
+
* const server = createServer({
|
|
280
|
+
* port: 4433,
|
|
281
|
+
* tls: { certPem: "...", keyPem: "..." },
|
|
282
|
+
* onSession: async (session) => {
|
|
283
|
+
* for await (const d of session.incomingDatagrams()) {
|
|
284
|
+
* await session.sendDatagram(d);
|
|
285
|
+
* }
|
|
286
|
+
* },
|
|
287
|
+
* });
|
|
288
|
+
* // server.address.port
|
|
289
|
+
* await server.close();
|
|
290
|
+
* ```
|
|
291
|
+
*/
|
|
292
|
+
export function createServer(opts) {
|
|
293
|
+
if (!native) {
|
|
294
|
+
throw new Error("Native addon not loaded");
|
|
295
|
+
}
|
|
296
|
+
const certPem = typeof opts.tls.certPem === "string" ? opts.tls.certPem : new TextDecoder().decode(opts.tls.certPem);
|
|
297
|
+
const keyPem = typeof opts.tls.keyPem === "string" ? opts.tls.keyPem : new TextDecoder().decode(opts.tls.keyPem);
|
|
298
|
+
const caPem = typeof opts.tls.caPem === "string"
|
|
299
|
+
? opts.tls.caPem
|
|
300
|
+
: opts.tls.caPem != null
|
|
301
|
+
? new TextDecoder().decode(opts.tls.caPem)
|
|
302
|
+
: "";
|
|
303
|
+
const limitsJson = JSON.stringify({ ...DEFAULT_LIMITS, ...opts.limits });
|
|
304
|
+
const rateLimitsJson = JSON.stringify({ ...DEFAULT_RATE_LIMITS, ...opts.rateLimits });
|
|
305
|
+
const closedResolvers = new Map();
|
|
306
|
+
let activeOnSessionCallbacks = 0;
|
|
307
|
+
let onSessionDrainResolve = null;
|
|
308
|
+
const logCallback = (logEvents) => {
|
|
309
|
+
if (opts.log) {
|
|
310
|
+
for (const le of logEvents) {
|
|
311
|
+
opts.log({
|
|
312
|
+
level: le.level ?? "info",
|
|
313
|
+
msg: le.msg ?? "",
|
|
314
|
+
sessionId: le.sessionId,
|
|
315
|
+
peerIp: le.peerIp,
|
|
316
|
+
peerPort: le.peerPort,
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
const handle = new native.ServerHandle(opts.port, opts.host ?? "0.0.0.0", opts.debug === true, certPem, keyPem, caPem, limitsJson, rateLimitsJson, (events) => {
|
|
322
|
+
for (const evt of events) {
|
|
323
|
+
if (evt.name === "session" && evt.id != null && evt.peerIp != null && evt.peerPort != null) {
|
|
324
|
+
let closedResolve;
|
|
325
|
+
const closedPromise = new Promise((resolve) => { closedResolve = resolve; });
|
|
326
|
+
closedResolvers.set(evt.id, closedResolve);
|
|
327
|
+
const nativeSession = new native.SessionHandle(evt.id, evt.peerIp, evt.peerPort);
|
|
328
|
+
const session = new NativeServerSession(nativeSession, closedPromise);
|
|
329
|
+
activeOnSessionCallbacks++;
|
|
330
|
+
const maybePromise = opts.onSession(session);
|
|
331
|
+
if (maybePromise && typeof maybePromise.then === "function") {
|
|
332
|
+
maybePromise.then(onSessionCallbackDone, onSessionCallbackDone);
|
|
333
|
+
}
|
|
334
|
+
else {
|
|
335
|
+
onSessionCallbackDone();
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
else if (evt.name === "session_closed" && evt.id != null) {
|
|
339
|
+
const resolve = closedResolvers.get(evt.id);
|
|
340
|
+
closedResolvers.delete(evt.id);
|
|
341
|
+
if (resolve)
|
|
342
|
+
resolve({ code: evt.code, reason: evt.reason });
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}, logCallback);
|
|
346
|
+
function onSessionCallbackDone() {
|
|
347
|
+
activeOnSessionCallbacks--;
|
|
348
|
+
if (activeOnSessionCallbacks <= 0 && onSessionDrainResolve) {
|
|
349
|
+
onSessionDrainResolve();
|
|
350
|
+
onSessionDrainResolve = null;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
return {
|
|
354
|
+
address: { host: opts.host ?? "0.0.0.0", port: handle.port },
|
|
355
|
+
close: async () => {
|
|
356
|
+
await handle.close();
|
|
357
|
+
for (const [id, resolve] of closedResolvers) {
|
|
358
|
+
closedResolvers.delete(id);
|
|
359
|
+
resolve({ code: 0, reason: "server closed" });
|
|
360
|
+
}
|
|
361
|
+
if (activeOnSessionCallbacks > 0) {
|
|
362
|
+
await Promise.race([
|
|
363
|
+
new Promise((r) => { onSessionDrainResolve = r; }),
|
|
364
|
+
new Promise((r) => setTimeout(r, 5000)),
|
|
365
|
+
]);
|
|
366
|
+
}
|
|
367
|
+
},
|
|
368
|
+
metricsSnapshot: () => handle.metricsSnapshot(),
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
// ---------------------------------------------------------------------------
|
|
372
|
+
// Client session implementation
|
|
373
|
+
// ---------------------------------------------------------------------------
|
|
374
|
+
class NativeClientSession {
|
|
375
|
+
#nativeHandle;
|
|
376
|
+
#readyPromise;
|
|
377
|
+
#closedPromise;
|
|
378
|
+
#closed = false;
|
|
379
|
+
constructor(nativeHandle, readyPromise, closedPromise) {
|
|
380
|
+
this.#nativeHandle = nativeHandle;
|
|
381
|
+
this.#readyPromise = readyPromise;
|
|
382
|
+
this.#closedPromise = closedPromise;
|
|
383
|
+
this.#closedPromise.then(() => { this.#closed = true; });
|
|
384
|
+
}
|
|
385
|
+
get id() {
|
|
386
|
+
return this.#nativeHandle.id;
|
|
387
|
+
}
|
|
388
|
+
get peer() {
|
|
389
|
+
return {
|
|
390
|
+
ip: this.#nativeHandle.peerIp,
|
|
391
|
+
port: this.#nativeHandle.peerPort,
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
get ready() {
|
|
395
|
+
return this.#readyPromise;
|
|
396
|
+
}
|
|
397
|
+
get closed() {
|
|
398
|
+
return this.#closedPromise;
|
|
399
|
+
}
|
|
400
|
+
close(info) {
|
|
401
|
+
if (!this.#closed) {
|
|
402
|
+
this.#closed = true;
|
|
403
|
+
this.#nativeHandle.close(info?.code ?? null, info?.reason ?? null);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
async sendDatagram(data) {
|
|
407
|
+
if (this.#closed)
|
|
408
|
+
throw new WebTransportError(E_SESSION_CLOSED);
|
|
409
|
+
try {
|
|
410
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
|
|
411
|
+
await this.#nativeHandle.sendDatagram(buf);
|
|
412
|
+
}
|
|
413
|
+
catch (err) {
|
|
414
|
+
throw toWebTransportError(err);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
async *incomingDatagrams() {
|
|
418
|
+
while (!this.#closed) {
|
|
419
|
+
try {
|
|
420
|
+
const dgram = await this.#nativeHandle.readDatagram();
|
|
421
|
+
if (!dgram)
|
|
422
|
+
break;
|
|
423
|
+
yield dgram;
|
|
424
|
+
}
|
|
425
|
+
catch {
|
|
426
|
+
break;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
async createBidirectionalStream() {
|
|
431
|
+
if (this.#closed)
|
|
432
|
+
throw new WebTransportError(E_SESSION_CLOSED);
|
|
433
|
+
try {
|
|
434
|
+
const nativeStream = await this.#nativeHandle.createBidiStream();
|
|
435
|
+
return new BidiStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
|
|
436
|
+
}
|
|
437
|
+
catch (err) {
|
|
438
|
+
throw toWebTransportError(err);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
async *incomingBidirectionalStreams() {
|
|
442
|
+
while (!this.#closed) {
|
|
443
|
+
try {
|
|
444
|
+
const nativeStream = await this.#nativeHandle.acceptBidiStream();
|
|
445
|
+
if (!nativeStream)
|
|
446
|
+
break;
|
|
447
|
+
yield new BidiStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
|
|
448
|
+
}
|
|
449
|
+
catch {
|
|
450
|
+
break;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
async createUnidirectionalStream() {
|
|
455
|
+
if (this.#closed)
|
|
456
|
+
throw new WebTransportError(E_SESSION_CLOSED);
|
|
457
|
+
try {
|
|
458
|
+
const nativeStream = await this.#nativeHandle.createUniStream();
|
|
459
|
+
return new SendStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
|
|
460
|
+
}
|
|
461
|
+
catch (err) {
|
|
462
|
+
throw toWebTransportError(err);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
async *incomingUnidirectionalStreams() {
|
|
466
|
+
while (!this.#closed) {
|
|
467
|
+
try {
|
|
468
|
+
const nativeStream = await this.#nativeHandle.acceptUniStream();
|
|
469
|
+
if (!nativeStream)
|
|
470
|
+
break;
|
|
471
|
+
yield new RecvStream({ handleId: nativeStream?.id ?? 0, nativeHandle: nativeStream });
|
|
472
|
+
}
|
|
473
|
+
catch {
|
|
474
|
+
break;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
metricsSnapshot() {
|
|
479
|
+
return this.#nativeHandle.metricsSnapshot();
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
// ---------------------------------------------------------------------------
|
|
483
|
+
// connect
|
|
484
|
+
// ---------------------------------------------------------------------------
|
|
485
|
+
/**
|
|
486
|
+
* Connect to a WebTransport server (Node API).
|
|
487
|
+
*
|
|
488
|
+
* @param url - WebTransport URL (e.g. `https://host:port/path`).
|
|
489
|
+
* @param opts - Optional TLS, limits, and logging. Limits default per {@link DEFAULT_LIMITS}.
|
|
490
|
+
* Use `tls.insecureSkipVerify: true` only for dev; emits a warning.
|
|
491
|
+
* @returns Promise that resolves to ClientSession when handshake completes.
|
|
492
|
+
* @throws WebTransportError with code `E_HANDSHAKE_TIMEOUT` if handshake exceeds `limits.handshakeTimeoutMs` (default 10s).
|
|
493
|
+
* @throws WebTransportError with code `E_TLS` on TLS failure.
|
|
494
|
+
*
|
|
495
|
+
* @example
|
|
496
|
+
* ```ts
|
|
497
|
+
* const session = await connect("https://127.0.0.1:4433", {
|
|
498
|
+
* tls: { insecureSkipVerify: true },
|
|
499
|
+
* limits: { handshakeTimeoutMs: 5000 },
|
|
500
|
+
* });
|
|
501
|
+
* await session.ready;
|
|
502
|
+
* await session.sendDatagram(new Uint8Array([1, 2, 3]));
|
|
503
|
+
* session.close({ code: 1000, reason: "done" });
|
|
504
|
+
* ```
|
|
505
|
+
*/
|
|
506
|
+
export async function connect(url, opts) {
|
|
507
|
+
if (!native) {
|
|
508
|
+
throw new Error("Native addon not loaded");
|
|
509
|
+
}
|
|
510
|
+
if (opts?.tls?.insecureSkipVerify === true) {
|
|
511
|
+
const log = opts.log ?? ((e) => console.warn(`[webtransport] ${e.level}: ${e.msg}`));
|
|
512
|
+
log({ level: "warn", msg: "tls.insecureSkipVerify is enabled — dev only, never use in production" });
|
|
513
|
+
}
|
|
514
|
+
const mergedLimits = { ...DEFAULT_LIMITS, ...opts?.limits };
|
|
515
|
+
const tlsOpts = opts?.tls ? {
|
|
516
|
+
insecureSkipVerify: opts.tls.insecureSkipVerify ?? false,
|
|
517
|
+
caPem: opts.tls.caPem ? (typeof opts.tls.caPem === "string" ? opts.tls.caPem : new TextDecoder().decode(opts.tls.caPem)) : undefined,
|
|
518
|
+
serverName: opts.tls.serverName,
|
|
519
|
+
} : undefined;
|
|
520
|
+
const optsJson = JSON.stringify({
|
|
521
|
+
limits: mergedLimits,
|
|
522
|
+
tls: tlsOpts,
|
|
523
|
+
});
|
|
524
|
+
const handshakeTimeout = mergedLimits.handshakeTimeoutMs;
|
|
525
|
+
const connectPromise = new Promise((resolve, reject) => {
|
|
526
|
+
const closedResolvers = new Map();
|
|
527
|
+
const onClosed = (events) => {
|
|
528
|
+
for (const evt of events) {
|
|
529
|
+
if (evt.name === "session_closed" && evt.id != null) {
|
|
530
|
+
const resolveClosed = closedResolvers.get(evt.id);
|
|
531
|
+
closedResolvers.delete(evt.id);
|
|
532
|
+
if (resolveClosed)
|
|
533
|
+
resolveClosed({ code: evt.code, reason: evt.reason });
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
native.connect(url, optsJson, onClosed, (err, handleId) => {
|
|
538
|
+
if (err) {
|
|
539
|
+
reject(toWebTransportError(err));
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
if (handleId == null) {
|
|
543
|
+
reject(new Error("connect succeeded but no handle id"));
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
const handle = native.takeClientSession(handleId);
|
|
547
|
+
if (!handle) {
|
|
548
|
+
reject(new Error("connect: handle not found in registry"));
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
let closedResolve;
|
|
552
|
+
const closedPromise = new Promise((r) => { closedResolve = r; });
|
|
553
|
+
closedResolvers.set(handle.id, closedResolve);
|
|
554
|
+
const readyPromise = Promise.resolve();
|
|
555
|
+
resolve(new NativeClientSession(handle, readyPromise, closedPromise));
|
|
556
|
+
});
|
|
557
|
+
});
|
|
558
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
559
|
+
setTimeout(() => {
|
|
560
|
+
reject(new WebTransportError(E_HANDSHAKE_TIMEOUT, `E_HANDSHAKE_TIMEOUT: connect timed out after ${handshakeTimeout}ms`));
|
|
561
|
+
}, handshakeTimeout);
|
|
562
|
+
});
|
|
563
|
+
return Promise.race([connectPromise, timeoutPromise]);
|
|
564
|
+
}
|
|
565
|
+
// ---------------------------------------------------------------------------
|
|
566
|
+
// Browser-style WebTransport facade (Phase P1)
|
|
567
|
+
// ---------------------------------------------------------------------------
|
|
568
|
+
const UNSUPPORTED_CTOR_OPTIONS = ["allowPooling", "requireUnreliable"];
|
|
569
|
+
function rejectUnsupportedOption(optionName) {
|
|
570
|
+
throw new WebTransportError(E_INTERNAL, `E_INTERNAL: unsupported option '${optionName}'`);
|
|
571
|
+
}
|
|
572
|
+
function validateServerCertificateHashes(arr) {
|
|
573
|
+
for (const entry of arr) {
|
|
574
|
+
if (entry.algorithm !== "sha-256") {
|
|
575
|
+
throw new WebTransportError(E_INTERNAL, `E_INTERNAL: serverCertificateHashes only supports algorithm "sha-256", got "${entry.algorithm}"`);
|
|
576
|
+
}
|
|
577
|
+
if (entry.value == null || (typeof entry.value === "object" && "byteLength" in entry && entry.byteLength === 0)) {
|
|
578
|
+
throw new WebTransportError(E_INTERNAL, "E_INTERNAL: serverCertificateHashes entry value must be non-empty BufferSource");
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
function validateClientOptions(opts) {
|
|
583
|
+
if (!opts)
|
|
584
|
+
return;
|
|
585
|
+
for (const k of UNSUPPORTED_CTOR_OPTIONS) {
|
|
586
|
+
if (k in opts && opts[k] !== undefined) {
|
|
587
|
+
rejectUnsupportedOption(k);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
if (opts.serverCertificateHashes !== undefined) {
|
|
591
|
+
if (!Array.isArray(opts.serverCertificateHashes)) {
|
|
592
|
+
throw new WebTransportError(E_INTERNAL, "E_INTERNAL: serverCertificateHashes must be an array");
|
|
593
|
+
}
|
|
594
|
+
validateServerCertificateHashes(opts.serverCertificateHashes);
|
|
595
|
+
throw new WebTransportError(E_INTERNAL, "E_INTERNAL: serverCertificateHashes is not supported in this runtime");
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
function mapToClientOptions(opts) {
|
|
599
|
+
if (!opts)
|
|
600
|
+
return {};
|
|
601
|
+
validateClientOptions(opts);
|
|
602
|
+
return {
|
|
603
|
+
tls: opts.tls,
|
|
604
|
+
limits: opts.limits,
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
function toCloseInfo(info) {
|
|
608
|
+
return {
|
|
609
|
+
closeCode: info?.code,
|
|
610
|
+
reason: info?.reason,
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* Browser-style WebTransport client (W3C facade).
|
|
615
|
+
*
|
|
616
|
+
* Use `new WebTransport(url, options)` to connect, or `toWebTransport(session)` to wrap an existing
|
|
617
|
+
* {@link ClientSession}. Await {@link WebTransport.ready} before using datagrams/streams.
|
|
618
|
+
*
|
|
619
|
+
* Unsupported options (`allowPooling`, `requireUnreliable`, `sendOrder`, `sendGroup`,
|
|
620
|
+
* `serverCertificateHashes`) throw {@link WebTransportError} with code `E_INTERNAL`.
|
|
621
|
+
*
|
|
622
|
+
* @example
|
|
623
|
+
* ```ts
|
|
624
|
+
* const wt = new WebTransport("https://127.0.0.1:4433", { tls: { insecureSkipVerify: true } });
|
|
625
|
+
* await wt.ready;
|
|
626
|
+
* const { readable, writable } = await wt.createBidirectionalStream();
|
|
627
|
+
* writable.getWriter().write(new Uint8Array([1, 2, 3]));
|
|
628
|
+
* wt.close({ closeCode: 1000, reason: "done" });
|
|
629
|
+
* await wt.closed;
|
|
630
|
+
* ```
|
|
631
|
+
*/
|
|
632
|
+
export class WebTransport {
|
|
633
|
+
#sessionPromise;
|
|
634
|
+
#ready;
|
|
635
|
+
#closed;
|
|
636
|
+
#draining;
|
|
637
|
+
#session = null;
|
|
638
|
+
#state;
|
|
639
|
+
#datagramsCache = null;
|
|
640
|
+
#incomingBidiCache = null;
|
|
641
|
+
#incomingUniCache = null;
|
|
642
|
+
constructor(urlOrSession, options) {
|
|
643
|
+
if (typeof urlOrSession === "string") {
|
|
644
|
+
const clientOpts = mapToClientOptions(options);
|
|
645
|
+
this.#sessionPromise = connect(urlOrSession, clientOpts);
|
|
646
|
+
this.#state = "connecting";
|
|
647
|
+
this.#ready = this.#sessionPromise.then((s) => {
|
|
648
|
+
this.#session = s;
|
|
649
|
+
if (this.#state !== "draining")
|
|
650
|
+
this.#state = "connected";
|
|
651
|
+
}, (err) => {
|
|
652
|
+
this.#state = "failed";
|
|
653
|
+
throw err;
|
|
654
|
+
});
|
|
655
|
+
this.#closed = this.#sessionPromise.then((s) => s.closed.then((info) => {
|
|
656
|
+
this.#state = "closed";
|
|
657
|
+
return toCloseInfo(info);
|
|
658
|
+
}));
|
|
659
|
+
}
|
|
660
|
+
else {
|
|
661
|
+
const s = urlOrSession;
|
|
662
|
+
this.#sessionPromise = Promise.resolve(s);
|
|
663
|
+
this.#session = s;
|
|
664
|
+
this.#state = "connected";
|
|
665
|
+
this.#ready = s.ready;
|
|
666
|
+
this.#closed = s.closed.then((info) => {
|
|
667
|
+
this.#state = "closed";
|
|
668
|
+
return toCloseInfo(info);
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
// draining: spec says it resolves when session is asked to gracefully close.
|
|
672
|
+
// Native layer has no separate draining signal; we resolve when closed (documented as partial parity).
|
|
673
|
+
this.#draining = this.#closed.then(() => { });
|
|
674
|
+
}
|
|
675
|
+
/** Resolves when handshake completes. Rejects with WebTransportError on connect failure. */
|
|
676
|
+
get ready() {
|
|
677
|
+
return this.#ready;
|
|
678
|
+
}
|
|
679
|
+
/** Resolves with close info when session closes. Never rejects. */
|
|
680
|
+
get closed() {
|
|
681
|
+
return this.#closed;
|
|
682
|
+
}
|
|
683
|
+
/** Resolves when session is draining. Currently resolves with closed (partial parity). */
|
|
684
|
+
get draining() {
|
|
685
|
+
return this.#draining;
|
|
686
|
+
}
|
|
687
|
+
/** Datagram Web Streams (readable/writable). Throws E_SESSION_CLOSED after close. */
|
|
688
|
+
get datagrams() {
|
|
689
|
+
if (!this.#datagramsCache) {
|
|
690
|
+
this.#datagramsCache = createDatagramStreams(this);
|
|
691
|
+
}
|
|
692
|
+
return this.#datagramsCache;
|
|
693
|
+
}
|
|
694
|
+
/** Incoming bidirectional streams as ReadableStream of { readable, writable }. */
|
|
695
|
+
get incomingBidirectionalStreams() {
|
|
696
|
+
if (!this.#incomingBidiCache) {
|
|
697
|
+
this.#incomingBidiCache = createIncomingBidiStreams(this);
|
|
698
|
+
}
|
|
699
|
+
return this.#incomingBidiCache;
|
|
700
|
+
}
|
|
701
|
+
/** Incoming unidirectional streams as ReadableStream of ReadableStream. */
|
|
702
|
+
get incomingUnidirectionalStreams() {
|
|
703
|
+
if (!this.#incomingUniCache) {
|
|
704
|
+
this.#incomingUniCache = createIncomingUniStreams(this);
|
|
705
|
+
}
|
|
706
|
+
return this.#incomingUniCache;
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Create a bidirectional stream (Web Streams). Rejects sendOrder/sendGroup (unsupported).
|
|
710
|
+
* @throws WebTransportError E_SESSION_CLOSED if session is closed/draining/failed.
|
|
711
|
+
*/
|
|
712
|
+
async createBidirectionalStream(options) {
|
|
713
|
+
if (options?.sendOrder !== undefined)
|
|
714
|
+
rejectUnsupportedOption("sendOrder");
|
|
715
|
+
if (options?.sendGroup !== undefined)
|
|
716
|
+
rejectUnsupportedOption("sendGroup");
|
|
717
|
+
if (this.#state === "draining" || this.#state === "closed" || this.#state === "failed") {
|
|
718
|
+
throw new WebTransportError(E_SESSION_CLOSED);
|
|
719
|
+
}
|
|
720
|
+
const s = await this.#sessionPromise;
|
|
721
|
+
const duplex = await s.createBidirectionalStream();
|
|
722
|
+
return nodeDuplexToWebBidi(duplex);
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* Create a unidirectional send stream (WritableStream). Rejects sendOrder/sendGroup (unsupported).
|
|
726
|
+
* @throws WebTransportError E_SESSION_CLOSED if session is closed/draining/failed.
|
|
727
|
+
*/
|
|
728
|
+
async createUnidirectionalStream(options) {
|
|
729
|
+
if (options?.sendOrder !== undefined)
|
|
730
|
+
rejectUnsupportedOption("sendOrder");
|
|
731
|
+
if (options?.sendGroup !== undefined)
|
|
732
|
+
rejectUnsupportedOption("sendGroup");
|
|
733
|
+
if (this.#state === "draining" || this.#state === "closed" || this.#state === "failed") {
|
|
734
|
+
throw new WebTransportError(E_SESSION_CLOSED);
|
|
735
|
+
}
|
|
736
|
+
const s = await this.#sessionPromise;
|
|
737
|
+
const writable = await s.createUnidirectionalStream();
|
|
738
|
+
return nodeWritableToWebWritable(writable);
|
|
739
|
+
}
|
|
740
|
+
/** Initiate graceful close. Idempotent after first call. */
|
|
741
|
+
close(info) {
|
|
742
|
+
if (this.#state === "connected" || this.#state === "connecting") {
|
|
743
|
+
this.#state = "draining";
|
|
744
|
+
}
|
|
745
|
+
if (this.#session) {
|
|
746
|
+
this.#session.close({
|
|
747
|
+
code: info?.closeCode,
|
|
748
|
+
reason: info?.reason,
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
/** Internal: session for adapters (not part of spec) */
|
|
753
|
+
async _getSession() {
|
|
754
|
+
return this.#sessionPromise;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
// Stub implementations for P2/P3 — will be replaced in datagram/stream phases
|
|
758
|
+
function createDatagramStreams(wt) {
|
|
759
|
+
const readable = new ReadableStream({
|
|
760
|
+
async start(controller) {
|
|
761
|
+
const s = await wt._getSession();
|
|
762
|
+
for await (const d of s.incomingDatagrams()) {
|
|
763
|
+
controller.enqueue(new Uint8Array(d));
|
|
764
|
+
}
|
|
765
|
+
controller.close();
|
|
766
|
+
},
|
|
767
|
+
});
|
|
768
|
+
const writable = new WritableStream({
|
|
769
|
+
async write(chunk) {
|
|
770
|
+
const s = await wt._getSession();
|
|
771
|
+
await s.sendDatagram(chunk);
|
|
772
|
+
},
|
|
773
|
+
});
|
|
774
|
+
return { readable, writable };
|
|
775
|
+
}
|
|
776
|
+
function createIncomingBidiStreams(wt) {
|
|
777
|
+
return new ReadableStream({
|
|
778
|
+
async start(controller) {
|
|
779
|
+
const s = await wt._getSession();
|
|
780
|
+
for await (const duplex of s.incomingBidirectionalStreams()) {
|
|
781
|
+
controller.enqueue(await nodeDuplexToWebBidi(duplex));
|
|
782
|
+
}
|
|
783
|
+
controller.close();
|
|
784
|
+
},
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
function createIncomingUniStreams(wt) {
|
|
788
|
+
return new ReadableStream({
|
|
789
|
+
async start(controller) {
|
|
790
|
+
const s = await wt._getSession();
|
|
791
|
+
for await (const readable of s.incomingUnidirectionalStreams()) {
|
|
792
|
+
controller.enqueue(nodeReadableToWebReadable(readable));
|
|
793
|
+
}
|
|
794
|
+
controller.close();
|
|
795
|
+
},
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
function nodeDuplexToWebBidi(duplex) {
|
|
799
|
+
const readable = nodeReadableToWebReadable(duplex);
|
|
800
|
+
const writable = nodeWritableToWebWritable(duplex);
|
|
801
|
+
return Promise.resolve({ readable, writable });
|
|
802
|
+
}
|
|
803
|
+
function nodeReadableToWebReadable(r) {
|
|
804
|
+
return new ReadableStream({
|
|
805
|
+
async start(controller) {
|
|
806
|
+
for await (const chunk of r) {
|
|
807
|
+
controller.enqueue(chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk));
|
|
808
|
+
}
|
|
809
|
+
controller.close();
|
|
810
|
+
},
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
function nodeWritableToWebWritable(w) {
|
|
814
|
+
return new WritableStream({
|
|
815
|
+
async write(chunk) {
|
|
816
|
+
return new Promise((resolve, reject) => {
|
|
817
|
+
w.write(Buffer.from(chunk), (err) => (err ? reject(err) : resolve()));
|
|
818
|
+
});
|
|
819
|
+
},
|
|
820
|
+
close() {
|
|
821
|
+
return new Promise((resolve, reject) => {
|
|
822
|
+
w.end((err) => (err ? reject(err) : resolve()));
|
|
823
|
+
});
|
|
824
|
+
},
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* Wrap an existing {@link ClientSession} as a browser-style WebTransport.
|
|
829
|
+
*
|
|
830
|
+
* Use when you obtained a session via {@link connect} but want Web Streams and W3C-style API.
|
|
831
|
+
*
|
|
832
|
+
* @param session - Connected ClientSession from {@link connect}.
|
|
833
|
+
* @returns WebTransport with same lifecycle; `ready` resolves immediately if session is connected.
|
|
834
|
+
*
|
|
835
|
+
* @example
|
|
836
|
+
* ```ts
|
|
837
|
+
* const session = await connect("https://127.0.0.1:4433", { tls: { insecureSkipVerify: true } });
|
|
838
|
+
* const wt = toWebTransport(session);
|
|
839
|
+
* await wt.ready;
|
|
840
|
+
* const writer = wt.datagrams.writable.getWriter();
|
|
841
|
+
* await writer.write(new Uint8Array([1, 2, 3]));
|
|
842
|
+
* writer.releaseLock();
|
|
843
|
+
* session.close();
|
|
844
|
+
* ```
|
|
845
|
+
*/
|
|
846
|
+
export function toWebTransport(session) {
|
|
847
|
+
return new WebTransport(session);
|
|
848
|
+
}
|