@statewalker/webrun-http-browser 0.6.5 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +302 -52
  2. package/dist/core/data-calls.d.ts +17 -0
  3. package/dist/core/data-calls.d.ts.map +1 -1
  4. package/dist/core/service-worker-control.d.ts +3 -1
  5. package/dist/core/service-worker-control.d.ts.map +1 -1
  6. package/dist/index.d.ts +3 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +4218 -301
  9. package/dist/link/async-dispose.d.ts +10 -0
  10. package/dist/link/async-dispose.d.ts.map +1 -0
  11. package/dist/link/errors.d.ts +2 -0
  12. package/dist/link/errors.d.ts.map +1 -0
  13. package/dist/link/http-link.d.ts +72 -0
  14. package/dist/link/http-link.d.ts.map +1 -0
  15. package/dist/link/index.d.ts +4 -0
  16. package/dist/link/index.d.ts.map +1 -0
  17. package/dist/link/locks.d.ts +39 -0
  18. package/dist/link/locks.d.ts.map +1 -0
  19. package/dist/link/rendezvous.d.ts +21 -0
  20. package/dist/link/rendezvous.d.ts.map +1 -0
  21. package/dist/relay/index-sw.d.ts +12 -2
  22. package/dist/relay/index-sw.d.ts.map +1 -1
  23. package/dist/relay/index.d.ts +66 -8
  24. package/dist/relay/index.d.ts.map +1 -1
  25. package/dist/relay-sw.js +1328 -64
  26. package/dist/relay-worker.js +1329 -64
  27. package/dist/sw/handler-endpoint.d.ts +81 -0
  28. package/dist/sw/handler-endpoint.d.ts.map +1 -0
  29. package/dist/sw/handler-table.d.ts +53 -0
  30. package/dist/sw/handler-table.d.ts.map +1 -0
  31. package/dist/sw/http-sw-dispatcher.d.ts +162 -21
  32. package/dist/sw/http-sw-dispatcher.d.ts.map +1 -1
  33. package/dist/sw/index.d.ts +5 -0
  34. package/dist/sw/index.d.ts.map +1 -1
  35. package/dist/sw/protocol.d.ts +115 -0
  36. package/dist/sw/protocol.d.ts.map +1 -0
  37. package/dist/sw/sw-dispatcher.d.ts.map +1 -1
  38. package/dist/sw/sw-http-adapter.d.ts +199 -0
  39. package/dist/sw/sw-http-adapter.d.ts.map +1 -0
  40. package/dist/sw/sw-websocket.d.ts +16 -0
  41. package/dist/sw/sw-websocket.d.ts.map +1 -0
  42. package/dist/sw/worker-service.d.ts +45 -0
  43. package/dist/sw/worker-service.d.ts.map +1 -0
  44. package/dist/sw/worker-url.d.ts +9 -0
  45. package/dist/sw/worker-url.d.ts.map +1 -0
  46. package/dist/sw-worker.js +2403 -265
  47. package/dist/sw.d.ts +2 -0
  48. package/dist/sw.d.ts.map +1 -1
  49. package/dist/sw.js +4189 -546
  50. package/dist/worker.d.ts +10 -0
  51. package/dist/worker.d.ts.map +1 -0
  52. package/dist/worker.js +3780 -0
  53. package/dist/ws/client.d.ts +73 -0
  54. package/dist/ws/client.d.ts.map +1 -0
  55. package/dist/ws/frames.d.ts +68 -0
  56. package/dist/ws/frames.d.ts.map +1 -0
  57. package/dist/ws/index.d.ts +6 -0
  58. package/dist/ws/index.d.ts.map +1 -0
  59. package/dist/ws/server.d.ts +53 -0
  60. package/dist/ws/server.d.ts.map +1 -0
  61. package/dist/ws/socket-core.d.ts +91 -0
  62. package/dist/ws/socket-core.d.ts.map +1 -0
  63. package/dist/ws/upgrade.d.ts +93 -0
  64. package/dist/ws/upgrade.d.ts.map +1 -0
  65. package/package.json +10 -5
  66. package/src/core/data-calls.ts +52 -2
  67. package/src/core/service-worker-control.ts +7 -1
  68. package/src/index.ts +3 -0
  69. package/src/link/async-dispose.ts +22 -0
  70. package/src/link/errors.ts +3 -0
  71. package/src/link/http-link.ts +238 -0
  72. package/src/link/index.ts +3 -0
  73. package/src/link/locks.ts +97 -0
  74. package/src/link/rendezvous.ts +60 -0
  75. package/src/relay/index-sw.ts +84 -12
  76. package/src/relay/index.ts +203 -27
  77. package/src/sw/handler-endpoint.ts +278 -0
  78. package/src/sw/handler-table.ts +130 -0
  79. package/src/sw/http-sw-dispatcher.ts +649 -90
  80. package/src/sw/index.ts +5 -0
  81. package/src/sw/protocol.ts +103 -0
  82. package/src/sw/sw-dispatcher.ts +1 -20
  83. package/src/sw/sw-http-adapter.ts +613 -0
  84. package/src/sw/sw-websocket.ts +43 -0
  85. package/src/sw/worker-service.ts +133 -0
  86. package/src/sw/worker-url.ts +19 -0
  87. package/src/sw-worker.ts +8 -3
  88. package/src/sw.ts +2 -0
  89. package/src/worker.ts +9 -0
  90. package/src/ws/client.ts +346 -0
  91. package/src/ws/frames.ts +119 -0
  92. package/src/ws/index.ts +11 -0
  93. package/src/ws/server.ts +132 -0
  94. package/src/ws/socket-core.ts +251 -0
  95. package/src/ws/upgrade.ts +200 -0
package/dist/worker.js ADDED
@@ -0,0 +1,3780 @@
1
+ //#region ../webrun-streams/dist/index.js
2
+ function serializeError(error) {
3
+ if (error instanceof Error) {
4
+ const out = {
5
+ message: error.message,
6
+ stack: error.stack
7
+ };
8
+ const bag = error;
9
+ for (const key of Object.keys(bag)) out[key] = bag[key];
10
+ return out;
11
+ }
12
+ if (typeof error === "object" && error !== null) {
13
+ const bag = error;
14
+ return {
15
+ message: String(bag.message ?? error),
16
+ ...bag
17
+ };
18
+ }
19
+ return { message: String(error) };
20
+ }
21
+ function deserializeError(error) {
22
+ const payload = typeof error === "string" ? { message: error } : error;
23
+ return Object.assign(new Error(payload.message), payload);
24
+ }
25
+ /**
26
+ * The newAsyncGenerator function creates async generators from callback-based initialization
27
+ * functions, providing a bridge between imperative event handling and declarative async
28
+ * iteration patterns.
29
+ *
30
+ * The initialization function receives two callback functions that control the generator's
31
+ * behavior. The `next` function yields values to consumers, while the `done` function
32
+ * signals completion or error conditions. The initialization function can return a cleanup
33
+ * function that will be called when the generator is closed or an error occurs.
34
+ *
35
+ * The generator manages an internal queue of values and completion signals, ensuring that
36
+ * producers can yield values without overwhelming consumers. Proper backpressure is implemented
37
+ * by having the `next` and `done` functions return promises that resolve only after the
38
+ * consumer has processed the values. This prevents memory leaks and ensures that producers
39
+ * are aware of whether their values were successfully handled.
40
+ * The generator also handles cleanup by draining any remaining items in the queue and notifying
41
+ * producers that their values were not processed if the generator is closed early. This ensures
42
+ * that resources are properly managed and that no memory leaks occur.
43
+ *
44
+ * Example usage:
45
+ * ```typescript
46
+ * const asyncGen = newAsyncGenerator<number>((next, done) => {
47
+ * let count = 0;
48
+ * const interval = setInterval(() => {
49
+ * if (count < 5) {
50
+ * next(count++);
51
+ * } else {
52
+ * done();
53
+ * clearInterval(interval);
54
+ * }
55
+ * }, 1000);
56
+ * return () => clearInterval(interval); // Cleanup function
57
+ * });
58
+ * (async () => {
59
+ * for await (const num of asyncGen) {
60
+ * console.log(num); // Logs numbers 0 to 4 at 1 second intervals
61
+ * }
62
+ * console.log("Completed");
63
+ * })();
64
+ * ```
65
+ * @template T The type of values yielded by the generator
66
+ * @template E The type of errors that can be thrown; defaults to Error
67
+ * @param init Initialization function that sets up the generator behavior with next/done callbacks;
68
+ * The first parameter - `next` function - is used to yield values to consumers;
69
+ * It returns a Promise<boolean> indicating whether the value was successfully handled;
70
+ * The second parameter - `done` function - is used to signal completion or error;
71
+ * It returns a Promise<boolean> indicating whether the completion was successfully handled;
72
+ * The initialization function can optionally return a cleanup function that will be called
73
+ * when the generator is closed or an error occurs;
74
+ * @param skipValues If true, only the most recent value is kept in the queue,
75
+ * skipping intermediate values (not consumed values are considered skipped);
76
+ * This is useful for scenarios where only the latest value matters, such as UI updates.
77
+ * Defaults to false, meaning all values are queued and processed in order.
78
+ * @returns AsyncGenerator that properly manages backpressure and resource cleanup
79
+ */
80
+ async function* newAsyncGenerator(init, skipValues = false) {
81
+ let head;
82
+ let tail;
83
+ /** Flag to prevent new values from being queued after generator closes */
84
+ let closed = false;
85
+ /** Wake-up function to notify the generator loop of new items */
86
+ let wakeUp;
87
+ /**
88
+ * Drains the internal queue, notifying all pending producers that their values
89
+ * were not processed due to generator closure. This prevents memory leaks and
90
+ * ensures proper backpressure signaling.
91
+ */
92
+ const drainQueue = () => {
93
+ for (; head; head = head.next) {
94
+ closed = closed || head.done;
95
+ head.resolve(false);
96
+ }
97
+ tail = void 0;
98
+ };
99
+ /**
100
+ * Enqueues a value or completion signal with a promise that resolves when the item
101
+ * is processed. This enables backpressure by allowing producers to know when their
102
+ * values have been consumed.
103
+ */
104
+ const enqueue = (params) => {
105
+ if (skipValues) drainQueue();
106
+ return !closed ? new Promise((resolve) => {
107
+ const next = {
108
+ ...params,
109
+ next: void 0,
110
+ resolve
111
+ };
112
+ if (tail) tail.next = next;
113
+ tail = next;
114
+ if (!head) head = tail;
115
+ wakeUp?.();
116
+ }) : Promise.resolve(false);
117
+ };
118
+ /**
119
+ * Producer function to yield a value to consumers. Returns a promise that resolves
120
+ * to true if the value was successfully processed, false if the generator is closed
121
+ * or the value was skipped due to backpressure.
122
+ */
123
+ const next = (value) => enqueue({
124
+ done: false,
125
+ value
126
+ });
127
+ /**
128
+ * Producer function to signal completion or error. Optional error parameter will
129
+ * cause the generator to throw that error to consumers.
130
+ */
131
+ const done = (error) => enqueue({
132
+ done: true,
133
+ error
134
+ });
135
+ const unsubscribe = init(next, done);
136
+ try {
137
+ while (!closed) {
138
+ if (!head) {
139
+ await new Promise((resolve) => {
140
+ wakeUp = resolve;
141
+ }).then(() => {
142
+ wakeUp = void 0;
143
+ });
144
+ continue;
145
+ }
146
+ const slot = head;
147
+ head = head.next;
148
+ if (tail === slot) tail = head;
149
+ try {
150
+ if (slot.done) {
151
+ closed = true;
152
+ if (slot.error !== void 0) throw slot.error;
153
+ break;
154
+ }
155
+ yield slot.value;
156
+ } finally {
157
+ slot.resolve(true);
158
+ }
159
+ }
160
+ } finally {
161
+ /**
162
+ * Cleanup phase - ensures proper resource management and notification of any
163
+ * remaining producers. This runs whether the generator completes normally,
164
+ * encounters an error, or is closed early by the consumer.
165
+ */
166
+ closed = true;
167
+ wakeUp?.();
168
+ if (typeof unsubscribe === "function") await unsubscribe();
169
+ /**
170
+ * Drain any remaining items in the queue and notify their producers that
171
+ * the values were not processed. This prevents memory leaks and ensures
172
+ * proper backpressure signaling.
173
+ */
174
+ drainQueue();
175
+ }
176
+ }
177
+ /**
178
+ * Inverse of {@link sendIterator}: turns a sequence of `{done, value, error}`
179
+ * chunks (delivered to the supplied callback by `installer`) into an async
180
+ * generator.
181
+ *
182
+ * The `installer` is given a `deliver` function. It should call `deliver`
183
+ * once for each incoming chunk and may return a cleanup callback that
184
+ * runs when the consumer stops iterating.
185
+ */
186
+ function recieveIterator(installer) {
187
+ return newAsyncGenerator((next, done) => {
188
+ const cleanup = installer(async (chunk = { done: true }) => {
189
+ const { done: isDone = true, value, error } = chunk;
190
+ if (error) return await done(error);
191
+ if (isDone) return await done();
192
+ return await next(value);
193
+ });
194
+ if (cleanup) return async () => {
195
+ await cleanup();
196
+ };
197
+ });
198
+ }
199
+ /**
200
+ * Drain an async iterator into a sink that consumes one chunk at a time.
201
+ *
202
+ * Each yielded value becomes `{ done: false, value }`. Completion emits
203
+ * `{ done: true }`. If the iterator throws, the error is caught and the
204
+ * final `done` chunk carries it so the peer can rethrow on its side.
205
+ */
206
+ async function sendIterator(send, it) {
207
+ let error;
208
+ try {
209
+ for await (const value of it) await send({
210
+ done: false,
211
+ value
212
+ });
213
+ } catch (err) {
214
+ error = err;
215
+ } finally {
216
+ await send({
217
+ done: true,
218
+ error
219
+ });
220
+ }
221
+ }
222
+ const DEFAULT_CHUNK_SIZE = 16384;
223
+ /**
224
+ * Curried `Duplex`-shaped transformer that splits incoming `Uint8Array`s into
225
+ * chunks no larger than `size` bytes. Empty input chunks are skipped; small
226
+ * input chunks pass through unchanged (zero-copy `subarray` views are used
227
+ * when splitting, so no allocation per chunk).
228
+ *
229
+ * Use to respect transport MTUs before reaching `channel.send`. Reassembly on
230
+ * the receive side is not needed — consumers iterate a continuous byte stream.
231
+ */
232
+ function toChunks(size = DEFAULT_CHUNK_SIZE) {
233
+ if (!(Number.isInteger(size) && size > 0)) throw new RangeError(`toChunks: size must be a positive integer, got ${size}`);
234
+ return async function* (input) {
235
+ for await (const block of input) {
236
+ if (block.byteLength === 0) continue;
237
+ if (block.byteLength <= size) {
238
+ yield block;
239
+ continue;
240
+ }
241
+ let offset = 0;
242
+ while (offset < block.byteLength) {
243
+ const end = Math.min(offset + size, block.byteLength);
244
+ yield block.subarray(offset, end);
245
+ offset = end;
246
+ }
247
+ }
248
+ };
249
+ }
250
+ //#endregion
251
+ //#region ../webrun-http-streams/dist/index.js
252
+ const CR = 13;
253
+ const LF = 10;
254
+ const EMPTY = /* @__PURE__ */ new Uint8Array(0);
255
+ var ByteStreamError = class extends Error {
256
+ name = "ByteStreamError";
257
+ };
258
+ function toAsyncIterator(input) {
259
+ const asyncIter = input[Symbol.asyncIterator];
260
+ if (asyncIter) return asyncIter.call(input);
261
+ const syncIter = input[Symbol.iterator]();
262
+ return { next() {
263
+ return Promise.resolve(syncIter.next());
264
+ } };
265
+ }
266
+ /**
267
+ * Discard an iterable we are contractually forbidden from consuming — a body
268
+ * skipped for HEAD/204, or one abandoned because the peer reported an error.
269
+ *
270
+ * The `.next()` is not optional: `.return()` on a generator still in suspended
271
+ * start is a no-op, so the body never runs and its `try/finally` never unwinds.
272
+ * Without it a wrapped ReadableStream or socket is never cancelled.
273
+ */
274
+ async function discard(source) {
275
+ if (source === void 0) return;
276
+ const it = toAsyncIterator(source);
277
+ try {
278
+ await it.next();
279
+ await it.return?.();
280
+ } catch {}
281
+ }
282
+ function concatChunks(parts, totalLen) {
283
+ if (parts.length === 1) {
284
+ const only = parts[0];
285
+ if (only !== void 0) return only;
286
+ }
287
+ const out = new Uint8Array(totalLen);
288
+ let off = 0;
289
+ for (const p of parts) {
290
+ out.set(p, off);
291
+ off += p.byteLength;
292
+ }
293
+ return out;
294
+ }
295
+ /**
296
+ * Pull-based reader over a byte source. Holds at most one pending buffer, and
297
+ * hands out `subarray` views rather than copies — a body never passes through
298
+ * an allocation here.
299
+ */
300
+ var ByteReader = class {
301
+ #iter;
302
+ #buf = EMPTY;
303
+ #done = false;
304
+ constructor(input) {
305
+ this.#iter = toAsyncIterator(input);
306
+ }
307
+ /** Bytes already pulled from the source but not yet consumed. */
308
+ bufferedLength() {
309
+ return this.#buf.byteLength;
310
+ }
311
+ /** Pull one more non-empty chunk. Returns false at end of stream. */
312
+ async #pull() {
313
+ if (this.#done) return false;
314
+ while (true) {
315
+ const next = await this.#iter.next();
316
+ if (next.done) {
317
+ this.#done = true;
318
+ return false;
319
+ }
320
+ const chunk = next.value;
321
+ if (chunk.byteLength === 0) continue;
322
+ this.#buf = this.#buf.byteLength === 0 ? chunk : concatChunks([this.#buf, chunk], this.#buf.byteLength + chunk.byteLength);
323
+ return true;
324
+ }
325
+ }
326
+ async peekByte() {
327
+ while (this.#buf.byteLength === 0) if (!await this.#pull()) return void 0;
328
+ return this.#buf[0];
329
+ }
330
+ /** Up to `max` bytes. `undefined` means end of stream. */
331
+ async readSome(max) {
332
+ while (this.#buf.byteLength === 0) if (!await this.#pull()) return void 0;
333
+ const take = Math.min(max, this.#buf.byteLength);
334
+ const out = this.#buf.subarray(0, take);
335
+ this.#buf = this.#buf.subarray(take);
336
+ return out;
337
+ }
338
+ /**
339
+ * One CRLF-terminated line, without the CRLF. A bare LF is rejected: real
340
+ * peers always send CRLF, and tolerating a bare LF is precisely the lenience
341
+ * that lets request smuggling through a proxy pair.
342
+ *
343
+ * The `maxBytes` bound is best-effort: it only rejects a line if the check
344
+ * happens to run before the line is fully buffered. A line already sitting in
345
+ * the buffer bypasses the check. Callers needing a hard per-line limit or
346
+ * aggregate bounds must keep their own running total.
347
+ */
348
+ async readLine(maxBytes) {
349
+ let searched = 0;
350
+ while (true) {
351
+ const idx = this.#buf.indexOf(LF, searched);
352
+ if (idx !== -1) {
353
+ if (idx === 0 || this.#buf[idx - 1] !== CR) throw new ByteStreamError("bare LF line terminator; CRLF required");
354
+ const line = this.#buf.subarray(0, idx - 1);
355
+ this.#buf = this.#buf.subarray(idx + 1);
356
+ return line;
357
+ }
358
+ searched = this.#buf.byteLength;
359
+ if (searched > maxBytes) throw new ByteStreamError(`line exceeds ${maxBytes} bytes without CRLF`);
360
+ if (!await this.#pull()) throw new ByteStreamError(`stream ended after ${searched} bytes without CRLF`);
361
+ }
362
+ }
363
+ /** Everything not yet consumed, lazily. */
364
+ async *rest() {
365
+ while (true) {
366
+ if (this.#buf.byteLength > 0) {
367
+ const out = this.#buf;
368
+ this.#buf = EMPTY;
369
+ yield out;
370
+ continue;
371
+ }
372
+ if (!await this.#pull()) return;
373
+ }
374
+ }
375
+ };
376
+ /**
377
+ * Raised for any byte sequence this codec refuses to interpret. Every case is
378
+ * a refusal to guess: HTTP/1.1 parsers that guess are how request smuggling
379
+ * works.
380
+ */
381
+ var HttpParseError = class extends Error {
382
+ name = "HttpParseError";
383
+ };
384
+ const NEWLINE = 10;
385
+ /** Mirrors the HTTP/1.1 codec's default `maxHeaderBytes`. */
386
+ const MAX_ENVELOPE_BYTES = 65536;
387
+ const encoder$1 = /* @__PURE__ */ new TextEncoder();
388
+ const decoder = /* @__PURE__ */ new TextDecoder();
389
+ /**
390
+ * Encode an HTTP envelope plus optional body as one continuous byte stream:
391
+ *
392
+ * <JSON.stringify(envelope)>\n<body bytes...>
393
+ *
394
+ * `JSON.stringify` with default whitespace never emits a literal `\n`, so the
395
+ * first `0x0a` byte unambiguously terminates the envelope.
396
+ *
397
+ * This is the same wire shape used by the legacy `webrun-http-port` package.
398
+ */
399
+ async function* encodeMessage(envelope, body) {
400
+ yield encoder$1.encode(`${JSON.stringify(envelope)}\n`);
401
+ if (!body) return;
402
+ for await (const chunk of body) if (chunk.byteLength > 0) yield chunk;
403
+ }
404
+ /**
405
+ * Consume an envelope-then-body byte stream. Returns the parsed envelope and
406
+ * an async iterable over the remaining body bytes.
407
+ */
408
+ async function decodeMessage(input) {
409
+ const iter = toAsyncIterator(input);
410
+ const accum = [];
411
+ let accumLen = 0;
412
+ let before;
413
+ let tail;
414
+ while (true) {
415
+ const next = await iter.next();
416
+ if (next.done) throw new HttpParseError(`decodeMessage: stream ended after ${accumLen} bytes without delimiter (\\n)`);
417
+ const chunk = next.value;
418
+ if (chunk.byteLength === 0) continue;
419
+ const nl = chunk.indexOf(NEWLINE);
420
+ if (nl === -1) {
421
+ accum.push(chunk);
422
+ accumLen += chunk.byteLength;
423
+ if (accumLen > MAX_ENVELOPE_BYTES) throw new HttpParseError(`decodeMessage: envelope exceeds ${MAX_ENVELOPE_BYTES} bytes without delimiter (\\n)`);
424
+ continue;
425
+ }
426
+ accum.push(chunk.subarray(0, nl));
427
+ accumLen += nl;
428
+ before = concatChunks(accum, accumLen);
429
+ tail = chunk.subarray(nl + 1);
430
+ break;
431
+ }
432
+ let envelope;
433
+ try {
434
+ envelope = JSON.parse(decoder.decode(before));
435
+ } catch (err) {
436
+ throw new HttpParseError(`decodeMessage: malformed envelope JSON at bytes 0..${before.byteLength}: ${err.message}`);
437
+ }
438
+ async function* body() {
439
+ if (tail.byteLength > 0) yield tail;
440
+ while (true) {
441
+ const next = await iter.next();
442
+ if (next.done) return;
443
+ if (next.value.byteLength > 0) yield next.value;
444
+ }
445
+ }
446
+ return {
447
+ envelope,
448
+ body: body()
449
+ };
450
+ }
451
+ const OPEN_BRACE = 123;
452
+ /**
453
+ * The original wire format — `<JSON.stringify(envelope)>\n<body bytes…>` —
454
+ * expressed as a `MessageCodec`. Direction-agnostic: requests and responses
455
+ * serialise identically.
456
+ *
457
+ * Retained so a peer pair can be upgraded in either order; see ADR-0006.
458
+ */
459
+ const jsonEnvelopeCodec = {
460
+ name: "json-envelope",
461
+ sniff: (byte) => byte === OPEN_BRACE,
462
+ encodeRequest: (env, body) => encodeMessage(env, body),
463
+ encodeResponse: (env, body) => encodeMessage(env, body),
464
+ decodeRequest: (input) => decodeMessage(input),
465
+ decodeResponse: (input) => decodeMessage(input)
466
+ };
467
+ const TCHAR = /* @__PURE__ */ new Set("!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
468
+ const SP = 32;
469
+ const HTAB = 9;
470
+ function isTokenChar(byte) {
471
+ return byte > SP && byte < 127 && TCHAR.has(String.fromCharCode(byte));
472
+ }
473
+ function isToken(value) {
474
+ if (value.length === 0) return false;
475
+ for (const ch of value) if (!TCHAR.has(ch)) return false;
476
+ return true;
477
+ }
478
+ /**
479
+ * Header bytes are latin-1: byte-preserving, matching Node, and lossless
480
+ * across a decode/encode round-trip. Control characters are rejected
481
+ * separately by `assertValidHeaderValue`.
482
+ */
483
+ function decodeLatin1(bytes) {
484
+ let out = "";
485
+ for (const byte of bytes) out += String.fromCharCode(byte);
486
+ return out;
487
+ }
488
+ function encodeLatin1(text) {
489
+ const out = new Uint8Array(text.length);
490
+ for (let i = 0; i < text.length; i++) {
491
+ const code = text.charCodeAt(i);
492
+ if (code > 255) throw new HttpParseError(`not latin-1 encodable: ${JSON.stringify(text)}`);
493
+ out[i] = code;
494
+ }
495
+ return out;
496
+ }
497
+ const HOST_IP_LITERAL = /^\[[0-9A-Fa-f:.]+\](:\d{1,5})?$/;
498
+ const HOST_REG_NAME = /^[A-Za-z0-9._~-]+(:\d{1,5})?$/;
499
+ /**
500
+ * Validates a value that is about to become (or was read as) a `Host`
501
+ * header: untrusted input either way, so an unrecognised shape is a refusal,
502
+ * not a guess. Rejects a present-but-empty value, one carrying userinfo
503
+ * (`evil.com@good.com`), and — the reason this also runs on encode — one
504
+ * smuggling a CRLF-terminated line into the authority of a caller-supplied
505
+ * url. Never applied to trusted configuration (a codec's `opts.host`).
506
+ */
507
+ function assertValidHost(host) {
508
+ if (!HOST_IP_LITERAL.test(host) && !HOST_REG_NAME.test(host)) throw new HttpParseError(`invalid Host header: ${JSON.stringify(host)}`);
509
+ }
510
+ /**
511
+ * A request-target must be entirely visible ASCII (RFC 9110 VCHAR) — nothing
512
+ * `<= 0x20` (space and every control character, CR/LF included) and nothing
513
+ * `>= 0x7F` (DEL and beyond). Applied on encode (`splitTarget`, so a
514
+ * caller-supplied url can never inject a second request line) and on decode
515
+ * (so a relay that decodes then re-encodes can never put an embedded control
516
+ * character back on the wire).
517
+ */
518
+ function assertValidTarget(target) {
519
+ for (let i = 0; i < target.length; i++) {
520
+ const code = target.charCodeAt(i);
521
+ if (code <= SP || code >= 127) throw new HttpParseError(`invalid request-target: ${JSON.stringify(target)}`);
522
+ }
523
+ }
524
+ /**
525
+ * Shared control-character check behind both `assertValidHeaderValue` and
526
+ * `assertValidStatusText` — the two were previously checked by different,
527
+ * looser rules (statusText only rejected CR/LF), which is exactly the
528
+ * asymmetry class C1 and M5 are both instances of. `label` is prepended
529
+ * verbatim to each message, so callers keep their own wording.
530
+ */
531
+ function assertNoControlChars(label, value) {
532
+ for (let i = 0; i < value.length; i++) {
533
+ const code = value.charCodeAt(i);
534
+ if (code === 13 || code === 10) throw new HttpParseError(`${label} contains CR or LF`);
535
+ if (code < SP && code !== HTAB || code === 127) throw new HttpParseError(`${label} contains a control character`);
536
+ if (code > 255) throw new HttpParseError(`${label} is not latin-1 encodable`);
537
+ }
538
+ }
539
+ function assertValidHeaderValue(name, value) {
540
+ assertNoControlChars(`header "${name}" value`, value);
541
+ }
542
+ /** Same character class as a header value (M5) — CR/LF, every C0 control, and DEL. */
543
+ function assertValidStatusText(value) {
544
+ assertNoControlChars("statusText", value);
545
+ }
546
+ function encodeHeaderLines(headers) {
547
+ let out = "";
548
+ for (const [name, value] of headers) {
549
+ if (!isToken(name)) throw new HttpParseError(`invalid header name: ${JSON.stringify(name)}`);
550
+ assertValidHeaderValue(name, value);
551
+ out += `${name}: ${value}\r\n`;
552
+ }
553
+ return out;
554
+ }
555
+ /**
556
+ * Read to the blank line. `alreadyUsed` is the byte count of the start line,
557
+ * so the bound covers the whole head section rather than the headers alone.
558
+ */
559
+ async function readHeaderSection(reader, maxHeaderBytes, alreadyUsed) {
560
+ const headers = [];
561
+ let used = alreadyUsed;
562
+ while (true) {
563
+ const remaining = maxHeaderBytes - used;
564
+ if (remaining <= 0) throw new HttpParseError(`head section exceeds ${maxHeaderBytes} bytes`);
565
+ const lineBytes = await reader.readLine(remaining);
566
+ used += lineBytes.byteLength + 2;
567
+ if (used > maxHeaderBytes) throw new HttpParseError(`head section exceeds ${maxHeaderBytes} bytes`);
568
+ if (lineBytes.byteLength === 0) return headers;
569
+ if (lineBytes[0] === SP || lineBytes[0] === HTAB) throw new HttpParseError("obs-fold header continuation is not accepted");
570
+ const line = decodeLatin1(lineBytes);
571
+ const colon = line.indexOf(":");
572
+ if (colon <= 0) throw new HttpParseError(`malformed header line: ${JSON.stringify(line)}`);
573
+ const name = line.slice(0, colon);
574
+ if (!isToken(name)) throw new HttpParseError(`invalid header name: ${JSON.stringify(name)}`);
575
+ const value = line.slice(colon + 1).replace(/^[ \t]+/, "").replace(/[ \t]+$/, "");
576
+ assertValidHeaderValue(name, value);
577
+ headers.push([name, value]);
578
+ }
579
+ }
580
+ function getAll(headers, name) {
581
+ const lower = name.toLowerCase();
582
+ return headers.filter(([k]) => k.toLowerCase() === lower).map(([, v]) => v);
583
+ }
584
+ function withoutHeaders(headers, names) {
585
+ const drop = new Set(names.map((n) => n.toLowerCase()));
586
+ return headers.filter(([k]) => !drop.has(k.toLowerCase()));
587
+ }
588
+ /**
589
+ * Parse a `Content-Length` field into a single validated value.
590
+ *
591
+ * RFC 9110 §8.6 permits the value to be a comma-separated list of identical
592
+ * numbers (a relay may have appended one), so the list is folded; differing
593
+ * values are a refusal, not a choice. Shared by `resolveFraming` on decode and
594
+ * by the encoder's declared-length check, which previously carried its own
595
+ * copy that did NOT split on commas — so decode accepted `5, 5` while encode
596
+ * rejected it, and a relay that decoded then re-encoded threw.
597
+ *
598
+ * Returns undefined when the field is absent.
599
+ */
600
+ function parseContentLength(values) {
601
+ if (values.length === 0) return void 0;
602
+ const unique = new Set(values.flatMap((v) => v.split(",").map((s) => s.trim())));
603
+ if (unique.size !== 1) throw new HttpParseError(`conflicting Content-Length values: ${[...unique].join(", ")}`);
604
+ const raw = [...unique][0];
605
+ if (!/^\d{1,15}$/.test(raw)) throw new HttpParseError(`invalid Content-Length: ${JSON.stringify(raw)}`);
606
+ return Number(raw);
607
+ }
608
+ /**
609
+ * Statuses that carry no body whatever the headers say (RFC 9110 §8.6): 1xx,
610
+ * 204 and 304. Defined once because the encoder must not frame a body for
611
+ * them and the decoder must not try to read one — two lists that agreed today
612
+ * and were free to drift tomorrow.
613
+ *
614
+ * A response to HEAD is also bodyless, but that depends on the request rather
615
+ * than the status, so callers test it separately.
616
+ */
617
+ function isBodylessStatus(status) {
618
+ return status < 200 || status === 204 || status === 304;
619
+ }
620
+ /**
621
+ * RFC 9112 §6.3, with every ambiguity turned into a refusal. In particular a
622
+ * message declaring both Content-Length and Transfer-Encoding is rejected
623
+ * rather than resolved — disagreeing on which one wins is request smuggling.
624
+ */
625
+ function resolveFraming(headers, version) {
626
+ const te = getAll(headers, "transfer-encoding");
627
+ const cl = getAll(headers, "content-length");
628
+ if (te.length > 0 && cl.length > 0) throw new HttpParseError("message declares both Content-Length and Transfer-Encoding; refusing (request smuggling)");
629
+ if (te.length > 0) {
630
+ const encodings = te.join(",").split(",").map((s) => s.trim().toLowerCase()).filter((s) => s !== "");
631
+ if (encodings.length !== 1 || encodings[0] !== "chunked") throw new HttpParseError(`unsupported Transfer-Encoding: ${JSON.stringify(te.join(", "))}`);
632
+ if (version === "HTTP/1.0") throw new HttpParseError("Transfer-Encoding is not valid in HTTP/1.0");
633
+ return { kind: "chunked" };
634
+ }
635
+ const length = parseContentLength(cl);
636
+ if (length !== void 0) return {
637
+ kind: "length",
638
+ length
639
+ };
640
+ return { kind: "none" };
641
+ }
642
+ const CRLF = /* @__PURE__ */ new Uint8Array([13, 10]);
643
+ const LAST_CHUNK = /* @__PURE__ */ new Uint8Array([
644
+ 48,
645
+ 13,
646
+ 10,
647
+ 13,
648
+ 10
649
+ ]);
650
+ const encoder = /* @__PURE__ */ new TextEncoder();
651
+ /**
652
+ * Chunk sizes are written in HEXADECIMAL — a 21-byte chunk is `15`. Writing
653
+ * them in decimal is the defect note 15 found in @libp2p/http, and it is the
654
+ * one that cannot be caught downstream: decimal digits are also valid hex, so
655
+ * a conforming parser silently reads the wrong length.
656
+ *
657
+ * Zero-length source chunks are skipped; a zero-sized chunk on the wire is the
658
+ * body terminator.
659
+ */
660
+ async function* encodeChunked(body) {
661
+ for await (const chunk of body) {
662
+ if (chunk.byteLength === 0) continue;
663
+ yield encoder.encode(`${chunk.byteLength.toString(16)}\r\n`);
664
+ yield chunk;
665
+ yield CRLF;
666
+ }
667
+ yield LAST_CHUNK;
668
+ }
669
+ /**
670
+ * Decode a chunked body, yielding data chunks as they arrive. Nothing is
671
+ * accumulated: a chunk larger than the transport's frame is yielded in pieces.
672
+ */
673
+ async function* decodeChunked(reader, maxLineBytes) {
674
+ while (true) {
675
+ const sizeLine = decodeLatin1(await reader.readLine(maxLineBytes));
676
+ const semicolon = sizeLine.indexOf(";");
677
+ const sizeText = semicolon === -1 ? sizeLine : sizeLine.slice(0, semicolon);
678
+ if (!/^[0-9a-fA-F]{1,32}$/.test(sizeText)) throw new HttpParseError(`invalid chunk size: ${JSON.stringify(sizeLine)}`);
679
+ const size = Number.parseInt(sizeText, 16);
680
+ if (!Number.isSafeInteger(size)) throw new HttpParseError(`chunk size is too large: ${JSON.stringify(sizeLine)}`);
681
+ if (size === 0) {
682
+ let used = 0;
683
+ while (true) {
684
+ const remaining = maxLineBytes - used;
685
+ if (remaining <= 0) throw new HttpParseError(`trailer section exceeds ${maxLineBytes} bytes`);
686
+ const lineBytes = await reader.readLine(remaining);
687
+ used += lineBytes.byteLength + 2;
688
+ if (used > maxLineBytes) throw new HttpParseError(`trailer section exceeds ${maxLineBytes} bytes`);
689
+ if (lineBytes.byteLength === 0) break;
690
+ }
691
+ return;
692
+ }
693
+ let remaining = size;
694
+ while (remaining > 0) {
695
+ const part = await reader.readSome(remaining);
696
+ if (part === void 0) throw new HttpParseError(`chunk truncated: ${remaining} of ${size} bytes missing`);
697
+ remaining -= part.byteLength;
698
+ yield part;
699
+ }
700
+ try {
701
+ if ((await reader.readLine(2)).byteLength !== 0) throw new HttpParseError("chunk data not terminated by CRLF");
702
+ } catch (err) {
703
+ if (err instanceof ByteStreamError) throw new HttpParseError("chunk data not terminated by CRLF");
704
+ throw err;
705
+ }
706
+ }
707
+ }
708
+ const VERSIONS = /* @__PURE__ */ new Set(["HTTP/1.1", "HTTP/1.0"]);
709
+ const ABSOLUTE_FORM = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;
710
+ /**
711
+ * One message per Duplex call (ADR-0006), so bytes after a complete message
712
+ * are an error. Checked against what is ALREADY BUFFERED rather than by
713
+ * awaiting end-of-stream: a live socket from a keep-alive peer never reaches
714
+ * EOF, so awaiting one would hang instead of failing.
715
+ */
716
+ function assertNoBufferedBytes(reader) {
717
+ const extra = reader.bufferedLength();
718
+ if (extra > 0) throw new HttpParseError(`${extra} trailing bytes after a complete message`);
719
+ }
720
+ /**
721
+ * The public error contract (I2): everything leaving `decodeRequest` /
722
+ * `decodeResponse` is an `HttpParseError`, whether the refusal happened
723
+ * synchronously (a malformed start line or header) or lazily while the body
724
+ * is later drained. `ByteStreamError` — the `ByteReader`'s own class, never
725
+ * exported — is the one thing converted here, message and all preserved via
726
+ * `cause`. Anything else is a genuine failure of the underlying source (a
727
+ * dropped socket, say) and must reach the caller unchanged: blanket-catching
728
+ * would hide that distinction.
729
+ */
730
+ function toHttpParseError(err) {
731
+ if (err instanceof ByteStreamError) throw new HttpParseError(err.message, { cause: err });
732
+ throw err;
733
+ }
734
+ /** Applies `toHttpParseError` across the whole lifetime of a body generator. */
735
+ async function* convertBodyErrors(source) {
736
+ try {
737
+ yield* source;
738
+ } catch (err) {
739
+ toHttpParseError(err);
740
+ }
741
+ }
742
+ async function* readBody(reader, framing, opts, noneMeansEof) {
743
+ if (framing.kind === "chunked") {
744
+ yield* decodeChunked(reader, opts.maxHeaderBytes);
745
+ assertNoBufferedBytes(reader);
746
+ return;
747
+ }
748
+ if (framing.kind === "length") {
749
+ let remaining = framing.length;
750
+ while (remaining > 0) {
751
+ const part = await reader.readSome(remaining);
752
+ if (part === void 0) throw new HttpParseError(`body truncated: ${remaining} of ${framing.length} bytes missing`);
753
+ remaining -= part.byteLength;
754
+ yield part;
755
+ }
756
+ assertNoBufferedBytes(reader);
757
+ return;
758
+ }
759
+ if (noneMeansEof) {
760
+ yield* reader.rest();
761
+ return;
762
+ }
763
+ assertNoBufferedBytes(reader);
764
+ }
765
+ /**
766
+ * `readLine`'s bound is best-effort — it is skipped when the line is already
767
+ * buffered — so a very long start line can reach these messages intact. Since
768
+ * a refusal is now echoed back to the sender in a 400 body, quote only enough
769
+ * to diagnose rather than reflecting the whole thing.
770
+ */
771
+ function quoteLine(line) {
772
+ const MAX = 120;
773
+ return line.length <= MAX ? JSON.stringify(line) : `${JSON.stringify(line.slice(0, MAX))} (truncated from ${line.length} chars)`;
774
+ }
775
+ async function decodeRequest(input, opts) {
776
+ const reader = new ByteReader(input);
777
+ try {
778
+ const startBytes = await reader.readLine(opts.maxHeaderBytes);
779
+ const startLine = decodeLatin1(startBytes);
780
+ const parts = startLine.split(" ");
781
+ if (parts.length !== 3) throw new HttpParseError(`malformed request line: ${quoteLine(startLine)}`);
782
+ const [method, target, version] = parts;
783
+ if (!isToken(method)) throw new HttpParseError(`invalid method: ${JSON.stringify(method)}`);
784
+ if (!VERSIONS.has(version)) throw new HttpParseError(`unsupported HTTP version: ${JSON.stringify(version)}`);
785
+ if (target === "*") throw new HttpParseError("asterisk-form request target is not supported");
786
+ assertValidTarget(target);
787
+ const headers = await readHeaderSection(reader, opts.maxHeaderBytes, startBytes.byteLength + 2);
788
+ const hosts = getAll(headers, "host");
789
+ if (hosts.length > 1) throw new HttpParseError("multiple Host headers");
790
+ const host = hosts[0];
791
+ let url;
792
+ if (target.startsWith("/")) {
793
+ if (version === "HTTP/1.1" && host === void 0) throw new HttpParseError("HTTP/1.1 request has no Host header");
794
+ if (host !== void 0) assertValidHost(host);
795
+ url = `${opts.scheme}://${host ?? opts.host}${target}`;
796
+ } else if (ABSOLUTE_FORM.test(target)) url = target;
797
+ else throw new HttpParseError(`unsupported request target: ${JSON.stringify(target)}`);
798
+ try {
799
+ new URL(url);
800
+ } catch {
801
+ throw new HttpParseError(`decoded url is not a valid URL: ${JSON.stringify(url)}`);
802
+ }
803
+ return {
804
+ envelope: {
805
+ url,
806
+ method,
807
+ headers
808
+ },
809
+ body: convertBodyErrors(readBody(reader, resolveFraming(headers, version), opts, false))
810
+ };
811
+ } catch (err) {
812
+ toHttpParseError(err);
813
+ }
814
+ }
815
+ async function decodeResponse(input, opts, method) {
816
+ const reader = new ByteReader(input);
817
+ try {
818
+ const startBytes = await reader.readLine(opts.maxHeaderBytes);
819
+ const startLine = decodeLatin1(startBytes);
820
+ const firstSp = startLine.indexOf(" ");
821
+ if (firstSp === -1) throw new HttpParseError(`malformed status line: ${quoteLine(startLine)}`);
822
+ const version = startLine.slice(0, firstSp);
823
+ if (!VERSIONS.has(version)) throw new HttpParseError(`unsupported HTTP version: ${JSON.stringify(version)}`);
824
+ const afterVersion = startLine.slice(firstSp + 1);
825
+ const secondSp = afterVersion.indexOf(" ");
826
+ const codeText = secondSp === -1 ? afterVersion : afterVersion.slice(0, secondSp);
827
+ if (!/^\d{3}$/.test(codeText)) throw new HttpParseError(`invalid status code: ${JSON.stringify(codeText)}`);
828
+ const status = Number(codeText);
829
+ const statusText = secondSp === -1 ? "" : afterVersion.slice(secondSp + 1);
830
+ const headers = await readHeaderSection(reader, opts.maxHeaderBytes, startBytes.byteLength + 2);
831
+ const bodyless = isBodylessStatus(status) || method.toUpperCase() === "HEAD";
832
+ const framing = bodyless ? { kind: "none" } : resolveFraming(headers, version);
833
+ return {
834
+ envelope: {
835
+ status,
836
+ statusText,
837
+ headers
838
+ },
839
+ body: convertBodyErrors(readBody(reader, framing, opts, !bodyless))
840
+ };
841
+ } catch (err) {
842
+ toHttpParseError(err);
843
+ }
844
+ }
845
+ /** Headers the codec owns: a caller-supplied copy is dropped and re-derived. */
846
+ const REQUEST_OWNED = [
847
+ "host",
848
+ "connection",
849
+ "transfer-encoding"
850
+ ];
851
+ const RESPONSE_OWNED = ["connection", "transfer-encoding"];
852
+ /**
853
+ * Split a URL into an origin-form request target and an authority *without*
854
+ * going through `new URL()`. `URL` normalises percent-encoding and would
855
+ * re-serialise the target — which is the exact class of defect note 15 found
856
+ * in @libp2p/http, where rebuilding the request line silently dropped
857
+ * `url.search`. Here the target is a verbatim slice of the caller's string.
858
+ */
859
+ function splitTarget(url, opts) {
860
+ if (url.startsWith("/")) {
861
+ assertValidTarget(url);
862
+ return {
863
+ target: url,
864
+ authority: opts.host
865
+ };
866
+ }
867
+ const match = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/([^/?#]*)([^#]*)/.exec(url);
868
+ if (!match) throw new HttpParseError(`cannot derive a request target from url: ${JSON.stringify(url)}`);
869
+ const rawAuthority = match[1];
870
+ if (rawAuthority === "") throw new HttpParseError(`url has no authority: ${JSON.stringify(url)}`);
871
+ const at = rawAuthority.lastIndexOf("@");
872
+ const authority = at === -1 ? rawAuthority : rawAuthority.slice(at + 1);
873
+ assertValidHost(authority);
874
+ const rawTarget = match[2];
875
+ const target = rawTarget === "" ? "/" : rawTarget.startsWith("/") ? rawTarget : `/${rawTarget}`;
876
+ assertValidTarget(target);
877
+ return {
878
+ target,
879
+ authority
880
+ };
881
+ }
882
+ async function* emitBody(body, declared) {
883
+ if (declared === void 0) {
884
+ yield* encodeChunked(body);
885
+ return;
886
+ }
887
+ let sent = 0;
888
+ for await (const chunk of body) {
889
+ if (chunk.byteLength === 0) continue;
890
+ sent += chunk.byteLength;
891
+ if (sent > declared) throw new HttpParseError(`body exceeds declared Content-Length ${declared} (${sent} bytes so far)`);
892
+ yield chunk;
893
+ }
894
+ if (sent !== declared) throw new HttpParseError(`body is ${sent} bytes but Content-Length declares ${declared}`);
895
+ }
896
+ async function* encodeRequest(env, body, opts) {
897
+ if (!isToken(env.method)) throw new HttpParseError(`invalid method: ${JSON.stringify(env.method)}`);
898
+ const { target, authority } = splitTarget(env.url, opts);
899
+ if (authority === "") throw new HttpParseError("no Host available: url has no authority and no host is configured");
900
+ const carried = withoutHeaders(env.headers, REQUEST_OWNED);
901
+ const declared = parseContentLength(getAll(carried, "content-length"));
902
+ let head = `${env.method} ${target} HTTP/1.1\r\n`;
903
+ head += `Host: ${authority}\r\n`;
904
+ head += encodeHeaderLines(carried);
905
+ head += "Connection: close\r\n";
906
+ if (body !== void 0 && declared === void 0) head += "Transfer-Encoding: chunked\r\n";
907
+ head += "\r\n";
908
+ yield encodeLatin1(head);
909
+ if (body === void 0) {
910
+ if (declared !== void 0 && declared !== 0) throw new HttpParseError(`body is 0 bytes but Content-Length declares ${declared}`);
911
+ return;
912
+ }
913
+ yield* emitBody(body, declared);
914
+ }
915
+ async function* encodeResponse(env, body, _opts, requestMethod) {
916
+ if (!Number.isInteger(env.status) || env.status < 100 || env.status > 599) throw new HttpParseError(`invalid status: ${env.status}`);
917
+ const reason = env.statusText ?? "";
918
+ assertValidStatusText(reason);
919
+ const bodylessStatus = isBodylessStatus(env.status);
920
+ const bodyless = bodylessStatus || requestMethod?.toUpperCase() === "HEAD";
921
+ const owned = bodylessStatus ? [...RESPONSE_OWNED, "content-length"] : RESPONSE_OWNED;
922
+ const carried = withoutHeaders(env.headers, owned);
923
+ const declared = parseContentLength(getAll(carried, "content-length"));
924
+ let head = `HTTP/1.1 ${env.status} ${reason}\r\n`;
925
+ head += encodeHeaderLines(carried);
926
+ head += "Connection: close\r\n";
927
+ if (!bodyless && body !== void 0 && declared === void 0) head += "Transfer-Encoding: chunked\r\n";
928
+ head += "\r\n";
929
+ yield encodeLatin1(head);
930
+ if (bodyless) {
931
+ await discard(body);
932
+ return;
933
+ }
934
+ if (body === void 0) {
935
+ if (declared !== void 0 && declared !== 0) throw new HttpParseError(`body is 0 bytes but Content-Length declares ${declared}`);
936
+ return;
937
+ }
938
+ yield* emitBody(body, declared);
939
+ }
940
+ function newHttpCodec(options = {}) {
941
+ const opts = {
942
+ scheme: options.scheme ?? "http",
943
+ host: options.host ?? "localhost",
944
+ maxHeaderBytes: options.maxHeaderBytes ?? 65536
945
+ };
946
+ return {
947
+ name: "http/1.1",
948
+ sniff: (byte) => isTokenChar(byte),
949
+ encodeRequest: (env, body) => encodeRequest(env, body, opts),
950
+ encodeResponse: (env, body, o) => encodeResponse(env, body, opts, o?.method),
951
+ decodeRequest: (input) => decodeRequest(input, opts),
952
+ decodeResponse: (input, o) => decodeResponse(input, opts, o.method)
953
+ };
954
+ }
955
+ const httpCodec = /* @__PURE__ */ newHttpCodec();
956
+ /**
957
+ * Dispatches on byte 0. The formats are self-identifying — a JSON envelope
958
+ * always begins `{`, which is not a token character and so can never begin an
959
+ * HTTP start-line — so no negotiation handshake, magic prefix, or version byte
960
+ * is needed.
961
+ *
962
+ * This is what makes a mixed-version peer pair safe: readers accept either
963
+ * format, so the two ends can be upgraded in any order.
964
+ */
965
+ function newSniffingCodec(options) {
966
+ const { write, accept } = options;
967
+ async function pick(input) {
968
+ const reader = new ByteReader(input);
969
+ const first = await reader.peekByte();
970
+ if (first === void 0) throw new HttpParseError("sniff: stream ended before any bytes arrived");
971
+ const codec = accept.find((c) => c.sniff(first));
972
+ if (!codec) throw new HttpParseError(`sniff: no accepted codec recognises a message starting with byte 0x${first.toString(16).padStart(2, "0")}`);
973
+ return {
974
+ codec,
975
+ input: reader.rest()
976
+ };
977
+ }
978
+ return {
979
+ name: `sniff(write=${write.name}; accept=${accept.map((c) => c.name).join(",")})`,
980
+ sniff: (byte) => accept.some((c) => c.sniff(byte)),
981
+ encodeRequest: (env, body) => write.encodeRequest(env, body),
982
+ encodeResponse: (env, body, o) => write.encodeResponse(env, body, o),
983
+ decodeRequest: async (input) => {
984
+ const picked = await pick(input);
985
+ try {
986
+ return {
987
+ ...await picked.codec.decodeRequest(picked.input),
988
+ codec: picked.codec
989
+ };
990
+ } catch (error) {
991
+ if (error !== null && typeof error === "object") error.codec = picked.codec;
992
+ throw error;
993
+ }
994
+ },
995
+ decodeResponse: async (input, o) => {
996
+ const picked = await pick(input);
997
+ return picked.codec.decodeResponse(picked.input, o);
998
+ }
999
+ };
1000
+ }
1001
+ /**
1002
+ * Writes HTTP/1.1; accepts HTTP/1.1 or the legacy JSON envelope. Used whenever
1003
+ * no `codec` option is supplied.
1004
+ */
1005
+ const defaultCodec = /* @__PURE__ */ newSniffingCodec({
1006
+ write: httpCodec,
1007
+ accept: [httpCodec, jsonEnvelopeCodec]
1008
+ });
1009
+ /**
1010
+ * Makes `target` disposable with `await using`: installs `dispose` as its
1011
+ * `[Symbol.asyncDispose]`, where the runtime defines the symbol. Hand-written
1012
+ * iterators lose what a native generator gets from `AsyncIteratorPrototype`;
1013
+ * this gives it back. A no-op where the symbol is missing. Kept off the
1014
+ * declared types, which would require consumers to compile with the
1015
+ * `esnext.disposable` lib.
1016
+ */
1017
+ function asyncDisposable$2(target, dispose) {
1018
+ const asyncDispose = Symbol.asyncDispose;
1019
+ if (asyncDispose && !(asyncDispose in target)) Object.defineProperty(target, asyncDispose, {
1020
+ value: async () => {
1021
+ await dispose();
1022
+ },
1023
+ configurable: true,
1024
+ writable: true
1025
+ });
1026
+ return target;
1027
+ }
1028
+ /** Carries the serialized JS error between two webrun peers. */
1029
+ const PEER_ERROR_HEADER = "x-webrun-error";
1030
+ /** Hard cap on the peer-error header (M3): see `encodeErrorResponse`. */
1031
+ const MAX_DETAIL_CHARS = 4096;
1032
+ /**
1033
+ * JSON with every non-printable-ASCII character escaped, so the result is a
1034
+ * legal latin-1 header value whatever the error message contained.
1035
+ */
1036
+ function asciiJson(value) {
1037
+ return JSON.stringify(value).replace(/[^\x20-\x7E]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
1038
+ }
1039
+ /**
1040
+ * Decision 13: a real HTTP peer cannot receive a JavaScript exception, only a
1041
+ * response. So an uncaught handler error becomes a conforming 500 whose body
1042
+ * carries the message, with the serialized error in a namespaced header that
1043
+ * another webrun peer re-throws from.
1044
+ */
1045
+ function encodeErrorResponse(codec, error, method, status = 500, statusText = "Internal Server Error") {
1046
+ const serialized = serializeError(error);
1047
+ let detail = asciiJson(serialized);
1048
+ if (detail.length > MAX_DETAIL_CHARS) detail = asciiJson({ message: serialized.message });
1049
+ if (detail.length > MAX_DETAIL_CHARS) detail = detail.slice(0, MAX_DETAIL_CHARS);
1050
+ const message = serialized.message ?? statusText;
1051
+ return codec.encodeResponse({
1052
+ status,
1053
+ statusText,
1054
+ headers: [["Content-Type", "text/plain; charset=utf-8"], [PEER_ERROR_HEADER, detail]]
1055
+ }, [new TextEncoder().encode(message)], { method });
1056
+ }
1057
+ /**
1058
+ * `output` is the `Duplex` call's own generator — one logical call, per the
1059
+ * `Duplex` contract in `@statewalker/webrun-streams`: "Consumer `.return()`
1060
+ * on the output → producer's `finally` runs." On a mux transport
1061
+ * (`emulateMux`), that `finally` is what frees the stream-table slot; skip it
1062
+ * and every peer-error response leaks one slot, unboundedly, until the mux
1063
+ * itself is exhausted (`maxStreams` reached, every further call rejected).
1064
+ *
1065
+ * Cancelling `output` here — not inside the codec's own decode logic — is
1066
+ * deliberate. `codec.decodeResponse` already pulled from `output` to read the
1067
+ * head before this function runs, so unlike the body case above there's no
1068
+ * suspended-start no-op to worry about. And it's safe specifically *because*
1069
+ * this is the client's own response-only generator: the request was already
1070
+ * fully sent before we got here, so there is nothing left to write on it.
1071
+ * The equivalent is NOT safe inside `src/http1/decode.ts`'s `ByteReader` —
1072
+ * that code also runs when a caller wires `codec.decodeRequest`/
1073
+ * `decodeResponse` directly onto a raw bidirectional socket (see
1074
+ * `tests/http1-node-interop.test.ts`), where the *same* object is read from
1075
+ * and then written back to (a server reads the request, then replies on the
1076
+ * same socket); cancelling the read side there tears down the whole
1077
+ * connection out from under the pending write. That was tried and reverted —
1078
+ * see the Task 11 report for the "socket hang up" failure it caused.
1079
+ */
1080
+ async function throwIfPeerError(result, output) {
1081
+ const found = result.envelope.headers.find(([k]) => k.toLowerCase() === PEER_ERROR_HEADER);
1082
+ if (!found) return;
1083
+ await discard(result.body);
1084
+ try {
1085
+ await output.return?.(void 0);
1086
+ } catch {}
1087
+ let payload;
1088
+ try {
1089
+ payload = JSON.parse(found[1]);
1090
+ } catch {
1091
+ payload = { message: found[1] };
1092
+ }
1093
+ throw deserializeError(payload);
1094
+ }
1095
+ /**
1096
+ * Initiate an HTTP call over a `Duplex`. The caller's `call: Duplex` is
1097
+ * obtained from any `webrun-streams-*` adapter's `connect`. Returns the
1098
+ * response envelope and an async iterable over the response body bytes.
1099
+ *
1100
+ * The call is one logical Duplex invocation; multiplexing of concurrent
1101
+ * calls is the adapter's concern (native or `emulateMux`).
1102
+ */
1103
+ async function httpFetch(call, env, body, options = {}) {
1104
+ const codec = options.codec ?? defaultCodec;
1105
+ const { signal } = options;
1106
+ if (signal?.aborted) throw abortReason$1(signal);
1107
+ const output = call(codec.encodeRequest(env, body));
1108
+ let released;
1109
+ const release = () => {
1110
+ released ??= (async () => {
1111
+ try {
1112
+ await output.return?.(void 0);
1113
+ } catch {}
1114
+ })();
1115
+ return released;
1116
+ };
1117
+ let finished = false;
1118
+ const finish = () => {
1119
+ if (finished || released) return;
1120
+ finished = true;
1121
+ if (signal?.aborted) {
1122
+ release();
1123
+ return;
1124
+ }
1125
+ const onAbort = () => void release();
1126
+ signal?.addEventListener("abort", onAbort, { once: true });
1127
+ drain(output).finally(() => signal?.removeEventListener("abort", onAbort));
1128
+ };
1129
+ let decoded;
1130
+ try {
1131
+ decoded = await untilAborted(codec.decodeResponse(output, { method: env.method }), signal);
1132
+ } catch (error) {
1133
+ if (signal?.aborted) release();
1134
+ else await release();
1135
+ throw error;
1136
+ }
1137
+ const result = {
1138
+ envelope: decoded.envelope,
1139
+ body: releasingOnExit(decoded.body, finish, release),
1140
+ release,
1141
+ finish
1142
+ };
1143
+ await throwIfPeerError(result, output);
1144
+ return result;
1145
+ }
1146
+ /** `promise`, rejected with the signal's reason if it aborts first. */
1147
+ function untilAborted(promise, signal) {
1148
+ if (!signal) return promise;
1149
+ return new Promise((resolve, reject) => {
1150
+ const onAbort = () => reject(abortReason$1(signal));
1151
+ if (signal.aborted) return onAbort();
1152
+ signal.addEventListener("abort", onAbort, { once: true });
1153
+ promise.then((value) => {
1154
+ signal.removeEventListener("abort", onAbort);
1155
+ resolve(value);
1156
+ }, (error) => {
1157
+ signal.removeEventListener("abort", onAbort);
1158
+ reject(error);
1159
+ });
1160
+ });
1161
+ }
1162
+ /** The signal's reason as an `Error` (`AbortError` when it gave none). */
1163
+ function abortReason$1(signal) {
1164
+ const reason = signal.reason;
1165
+ if (reason instanceof Error) return reason;
1166
+ const err = new Error(reason === void 0 ? "Aborted" : String(reason));
1167
+ err.name = "AbortError";
1168
+ return err;
1169
+ }
1170
+ /**
1171
+ * `body`, ending the call however it is left: read to its end, or left early.
1172
+ *
1173
+ * The body the codec hands back is a generator of its own over a `ByteReader`,
1174
+ * and its ending never reaches the call's `output` (see `throwIfPeerError` for
1175
+ * why the codec must not do that itself). A caller that stopped reading — an
1176
+ * aborted `fetch`, a cancelled response stream — left the peer's producer
1177
+ * parked forever; and one that read the body to its end left the call itself
1178
+ * open, which on a multiplexed transport is one port per exchange until the
1179
+ * multiplexer refuses to open more (`maxPorts`).
1180
+ *
1181
+ * Left early, the call is abandoned (`.return()`): the peer's producer is
1182
+ * released. Read to its end, the call is not cut short but read to ITS end, in
1183
+ * the background: the peer ends it once its side of the exchange is over,
1184
+ * which may be later than the response — a handler that answered before it
1185
+ * read the request body is still receiving it (`HttpDataHandlerResult.settled`),
1186
+ * and abandoning the call would abort that upload.
1187
+ */
1188
+ async function* releasingOnExit(body, finish, release) {
1189
+ let completed = false;
1190
+ try {
1191
+ yield* body;
1192
+ completed = true;
1193
+ } finally {
1194
+ if (completed) finish();
1195
+ else await release();
1196
+ }
1197
+ }
1198
+ /** Reads `output` to its end, discarding what is left, ignoring a failure. */
1199
+ async function drain(output) {
1200
+ try {
1201
+ for (let r = await output.next(); !r.done; r = await output.next());
1202
+ } catch {}
1203
+ }
1204
+ /**
1205
+ * Wrap an HTTP handler as a `Duplex` so it can be registered with any
1206
+ * `webrun-streams-*` adapter's `serve`.
1207
+ */
1208
+ function httpServe(handler, options = {}) {
1209
+ const codec = options.codec ?? defaultCodec;
1210
+ return async function* httpHandlerDuplex(input) {
1211
+ let decoded;
1212
+ try {
1213
+ decoded = await codec.decodeRequest(input);
1214
+ } catch (error) {
1215
+ if (!(error instanceof HttpParseError)) throw error;
1216
+ yield* encodeErrorResponse(error.codec ?? codec, error, "GET", 400, "Bad Request");
1217
+ return;
1218
+ }
1219
+ const replyCodec = decoded.codec ?? codec;
1220
+ let result;
1221
+ try {
1222
+ result = await handler(decoded.envelope, decoded.body);
1223
+ } catch (error) {
1224
+ yield* encodeErrorResponse(replyCodec, error, decoded.envelope.method);
1225
+ return;
1226
+ }
1227
+ let completed = false;
1228
+ try {
1229
+ yield* replyCodec.encodeResponse(result.envelope, result.body, { method: decoded.envelope.method });
1230
+ completed = true;
1231
+ await result.settled?.();
1232
+ } finally {
1233
+ if (!completed) try {
1234
+ await result.release?.();
1235
+ } catch {}
1236
+ }
1237
+ };
1238
+ }
1239
+ /**
1240
+ * The one place that knows a runtime may not implement request body streams,
1241
+ * and the buffering both fallbacks need. `fetch.ts` and `http-stubs.ts` each
1242
+ * carry a client and a server direction that must agree on the answer, so the
1243
+ * predicate lives here rather than being written out four times.
1244
+ */
1245
+ /**
1246
+ * Whether `Request.prototype` exposes a `body` accessor. Two call sites read
1247
+ * that property, and two more depend on the constructor accepting a
1248
+ * `ReadableStream` as `init.body`; this predicate answers for all four.
1249
+ *
1250
+ * What was verified, and all that is claimed here: Firefox (146 at the time of
1251
+ * writing) has *neither*, and Chromium and Node have *both*. On Firefox it is
1252
+ * not that `body` is `undefined` on the instance —
1253
+ * `Object.getOwnPropertyDescriptor(Request.prototype, "body")` is `null`, the
1254
+ * accessor is genuinely absent — and because a `ReadableStream` is then not a
1255
+ * recognised `BodyInit`, the constructor falls through to the string branch and
1256
+ * stores the literal text `[object ReadableStream]`.
1257
+ *
1258
+ * The two halves are NOT guaranteed to ship together, so do not read this as a
1259
+ * test for "request streams" in general. Safari is the counterexample: it has
1260
+ * had `Request.body` since 11.1 but only accepts a stream as `init.body` from
1261
+ * Technology Preview 250, so a shipping Safari has the reader half without the
1262
+ * upload half and this returns `true` there. That looks benign — WebKit appears
1263
+ * to store the stream on the `Request` rather than stringify it, and its error
1264
+ * comes from `fetch()`, which this package never calls on the objects it builds
1265
+ * — but it is untested, and it is the case to look at first if a Safari report
1266
+ * arrives. The sharper probe, if one is ever needed, is whether
1267
+ * `new Request(url, {method:"POST", body:new ReadableStream(), duplex:"half"})`
1268
+ * has a `content-type` of `text/plain;charset=UTF-8` (stringified) or `null`
1269
+ * (stored); it is not used here because it costs a `Request` and a
1270
+ * `ReadableStream` per call and agrees with the descriptor check on every
1271
+ * runtime measured.
1272
+ *
1273
+ * A capability check, never a user-agent test: the question is what this
1274
+ * runtime does, and the answer flips on its own the day Firefox ships request
1275
+ * streams. Evaluated per call rather than cached at module load so that a test
1276
+ * can install a `Request` without the capability and exercise the real branch
1277
+ * under Node.
1278
+ */
1279
+ function supportsRequestStreams() {
1280
+ return typeof Request === "function" && Object.getOwnPropertyDescriptor(Request.prototype, "body") != null;
1281
+ }
1282
+ /**
1283
+ * Drain a body iterable into one contiguous buffer. Only the fallbacks need it.
1284
+ * Allocates its own buffer rather than reusing `bytes.ts`'s `concatChunks`,
1285
+ * which passes a single chunk straight through: that chunk is a view onto the
1286
+ * decoder's own read buffer, and the result here is handed to `new Request` and
1287
+ * outlives the decode. The allocation is also what makes it a
1288
+ * `Uint8Array<ArrayBuffer>`, which `BodyInit` accepts and the looser
1289
+ * `Uint8Array<ArrayBufferLike>` does not.
1290
+ */
1291
+ async function collectBytes(source) {
1292
+ const parts = [];
1293
+ let total = 0;
1294
+ for await (const chunk of source) {
1295
+ if (chunk.byteLength === 0) continue;
1296
+ parts.push(chunk);
1297
+ total += chunk.byteLength;
1298
+ }
1299
+ const out = new Uint8Array(total);
1300
+ let offset = 0;
1301
+ for (const part of parts) {
1302
+ out.set(part, offset);
1303
+ offset += part.byteLength;
1304
+ }
1305
+ return out;
1306
+ }
1307
+ const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
1308
+ 101,
1309
+ 103,
1310
+ 204,
1311
+ 205,
1312
+ 304
1313
+ ]);
1314
+ /**
1315
+ * Connection-scoped headers. The codec surfaces them verbatim (decision 12),
1316
+ * but they are meaningless to a `Request`/`Response`, and re-emitting them
1317
+ * from a relay would corrupt its framing.
1318
+ */
1319
+ const HOP_BY_HOP = /* @__PURE__ */ new Set([
1320
+ "connection",
1321
+ "host",
1322
+ "keep-alive",
1323
+ "proxy-authenticate",
1324
+ "proxy-authorization",
1325
+ "te",
1326
+ "trailer",
1327
+ "transfer-encoding",
1328
+ "upgrade"
1329
+ ]);
1330
+ function forwardableHeaders(headers) {
1331
+ return headers.filter(([name]) => !HOP_BY_HOP.has(name.toLowerCase()));
1332
+ }
1333
+ function headersToArray(headers) {
1334
+ const out = [];
1335
+ headers.forEach((value, key) => {
1336
+ out.push([key, value]);
1337
+ });
1338
+ return out;
1339
+ }
1340
+ async function* readableToAsyncIterable(stream) {
1341
+ if (!stream) return;
1342
+ const reader = stream.getReader();
1343
+ let consumed = false;
1344
+ try {
1345
+ while (true) {
1346
+ const { done, value } = await reader.read();
1347
+ if (done) {
1348
+ consumed = true;
1349
+ return;
1350
+ }
1351
+ if (value) yield value;
1352
+ }
1353
+ } finally {
1354
+ if (!consumed) try {
1355
+ await reader.cancel();
1356
+ } catch {}
1357
+ try {
1358
+ reader.releaseLock();
1359
+ } catch {}
1360
+ }
1361
+ }
1362
+ function asyncIterableToReadable(iter) {
1363
+ const it = iter[Symbol.asyncIterator]();
1364
+ return new ReadableStream({
1365
+ async pull(controller) {
1366
+ try {
1367
+ const { done, value } = await it.next();
1368
+ if (done) {
1369
+ controller.close();
1370
+ return;
1371
+ }
1372
+ controller.enqueue(value);
1373
+ } catch (err) {
1374
+ controller.error(err);
1375
+ }
1376
+ },
1377
+ async cancel() {
1378
+ await it.return?.();
1379
+ }
1380
+ });
1381
+ }
1382
+ /**
1383
+ * Run a `Request` through a `Duplex` call and reconstruct the `Response` on
1384
+ * the other side. The request's `signal` is plumbed into the body iteration —
1385
+ * abort terminates the underlying call.
1386
+ */
1387
+ async function fetchOverDuplex(call, request, options = {}) {
1388
+ if (request.signal?.aborted) throw abortReason$1(request.signal);
1389
+ const env = {
1390
+ url: request.url,
1391
+ method: request.method,
1392
+ headers: headersToArray(request.headers)
1393
+ };
1394
+ let body;
1395
+ if (request.body != null) body = readableToAsyncIterable(request.body);
1396
+ else if (!supportsRequestStreams()) {
1397
+ const buffered = new Uint8Array(await request.arrayBuffer());
1398
+ if (buffered.byteLength > 0) body = [buffered];
1399
+ }
1400
+ const { envelope, body: respBody, release, finish } = await httpFetch(call, env, body, {
1401
+ ...options,
1402
+ signal: request.signal ?? void 0
1403
+ });
1404
+ const responseInit = {
1405
+ status: envelope.status,
1406
+ statusText: envelope.statusText,
1407
+ headers: forwardableHeaders(envelope.headers)
1408
+ };
1409
+ if (request.method === "HEAD" || request.method === "OPTIONS" || NULL_BODY_STATUSES.has(envelope.status)) {
1410
+ if (finish) finish();
1411
+ else await release?.();
1412
+ return new Response(null, responseInit);
1413
+ }
1414
+ return new Response(asyncIterableToReadable(withAbort(respBody, request.signal)), responseInit);
1415
+ }
1416
+ /**
1417
+ * Wrap a `(Request) => Promise<Response>` handler as a `Duplex` so it can be
1418
+ * registered with any `webrun-streams-*` adapter's `serve`.
1419
+ */
1420
+ function serveFetchOverDuplex(handler, options = {}) {
1421
+ return httpServe(async (env, body) => {
1422
+ const reqInit = {
1423
+ method: env.method,
1424
+ headers: forwardableHeaders(env.headers)
1425
+ };
1426
+ let upload;
1427
+ if (env.method !== "GET" && env.method !== "HEAD") {
1428
+ if (supportsRequestStreams()) {
1429
+ upload = trackingEnd(body);
1430
+ reqInit.body = asyncIterableToReadable(upload.source);
1431
+ reqInit.duplex = "half";
1432
+ } else reqInit.body = await collectBytes(body);
1433
+ }
1434
+ const request = new Request(env.url, reqInit);
1435
+ const response = await handler(request);
1436
+ const settled = async () => {
1437
+ if (!upload) return;
1438
+ if (!request.bodyUsed && !request.body?.locked) request.body?.cancel().catch(() => {});
1439
+ await upload.settle(options.requestIdleMs ?? 3e4);
1440
+ };
1441
+ const respEnv = {
1442
+ status: response.status,
1443
+ statusText: response.statusText,
1444
+ headers: headersToArray(response.headers)
1445
+ };
1446
+ if (env.method === "HEAD" || env.method === "OPTIONS" || NULL_BODY_STATUSES.has(response.status)) {
1447
+ await response.body?.cancel();
1448
+ return {
1449
+ envelope: respEnv,
1450
+ body: void 0,
1451
+ settled
1452
+ };
1453
+ }
1454
+ return {
1455
+ envelope: respEnv,
1456
+ body: response.body ? readableToAsyncIterable(response.body) : void 0,
1457
+ release: () => response.body?.cancel(),
1458
+ settled
1459
+ };
1460
+ }, options);
1461
+ }
1462
+ /**
1463
+ * `source`, and `settle(idleMs)`: resolves once it is done — read to its end,
1464
+ * failed, or abandoned (`return()` included before the first `next()`, which a
1465
+ * generator's `finally` would not see) — or once nobody has asked it for a
1466
+ * chunk for `idleMs`, in which case it is abandoned: later reads fail.
1467
+ *
1468
+ * Idle counts only while no `next()` is pending: a reader waiting for a slow
1469
+ * sender is still reading.
1470
+ */
1471
+ function trackingEnd(source) {
1472
+ let end = () => {};
1473
+ let isEnded = false;
1474
+ const ended = new Promise((resolve) => {
1475
+ end = () => {
1476
+ isEnded = true;
1477
+ resolve();
1478
+ };
1479
+ });
1480
+ let abandoned;
1481
+ let pending = 0;
1482
+ let idleSince = Date.now();
1483
+ const it = source[Symbol.asyncIterator]();
1484
+ const abandon = (reason) => {
1485
+ abandoned ??= reason;
1486
+ end();
1487
+ Promise.resolve(it.return?.(void 0)).catch(() => {});
1488
+ };
1489
+ const tracked = {
1490
+ [Symbol.asyncIterator]() {
1491
+ return tracked;
1492
+ },
1493
+ async next() {
1494
+ if (abandoned) throw abandoned;
1495
+ pending++;
1496
+ try {
1497
+ const r = await it.next();
1498
+ if (r.done) end();
1499
+ return r;
1500
+ } catch (error) {
1501
+ end();
1502
+ throw error;
1503
+ } finally {
1504
+ if (--pending === 0) idleSince = Date.now();
1505
+ }
1506
+ },
1507
+ async return(value) {
1508
+ end();
1509
+ try {
1510
+ await it.return?.(value);
1511
+ } catch {}
1512
+ return {
1513
+ done: true,
1514
+ value: void 0
1515
+ };
1516
+ }
1517
+ };
1518
+ asyncDisposable$2(tracked, () => tracked.return?.() ?? Promise.resolve());
1519
+ const settle = (idleMs) => {
1520
+ if (isEnded || !Number.isFinite(idleMs)) return ended;
1521
+ return new Promise((resolve) => {
1522
+ let timer;
1523
+ const check = () => {
1524
+ if (isEnded) return resolve();
1525
+ const idle = pending === 0 ? Date.now() - idleSince : 0;
1526
+ if (idle >= idleMs) {
1527
+ abandon(/* @__PURE__ */ new Error(`webrun-http-streams: the request body was left unread for ${idleMs} ms after the response; abandoned`));
1528
+ return resolve();
1529
+ }
1530
+ timer = setTimeout(check, Math.max(1, Math.min(idleMs - idle, 1e3)));
1531
+ timer.unref?.();
1532
+ };
1533
+ ended.then(() => {
1534
+ clearTimeout(timer);
1535
+ resolve();
1536
+ });
1537
+ check();
1538
+ });
1539
+ };
1540
+ return {
1541
+ source: tracked,
1542
+ settle
1543
+ };
1544
+ }
1545
+ async function* withAbort(iter, signal) {
1546
+ if (!signal) {
1547
+ yield* iter;
1548
+ return;
1549
+ }
1550
+ for await (const chunk of iter) {
1551
+ if (signal.aborted) throw abortReason$1(signal);
1552
+ yield chunk;
1553
+ }
1554
+ }
1555
+ //#endregion
1556
+ //#region ../webrun-rpc/dist/index.js
1557
+ const closeSignals = /* @__PURE__ */ new WeakMap();
1558
+ /**
1559
+ * Internal: register a port's close signal. Called once by `bindBytesToPort`.
1560
+ *
1561
+ * @internal
1562
+ */
1563
+ function setPortCloseSignal(port, signal) {
1564
+ closeSignals.set(port, signal);
1565
+ }
1566
+ /**
1567
+ * Return the AbortSignal that fires when `port`'s transport closes, or
1568
+ * `undefined` if `port` is not transport-backed (e.g., a raw
1569
+ * `MessageChannel().port1`).
1570
+ */
1571
+ function getPortCloseSignal(port) {
1572
+ return closeSignals.get(port);
1573
+ }
1574
+ /**
1575
+ * Pass as `timeout` to install no deadline at all. Used by the stream tier,
1576
+ * where the deadline belongs to the stream rather than to one chunk (spec D8):
1577
+ * a slow consumer is throttled, never failed.
1578
+ */
1579
+ const NO_TIMEOUT = Number.POSITIVE_INFINITY;
1580
+ /**
1581
+ * Asynchronous request/response over any `MessageTarget`.
1582
+ *
1583
+ * Sends `params` to the peer listening with `listenPort`, waits up to
1584
+ * `timeout` ms for a matching reply, and either resolves with the result or
1585
+ * rejects with the deserialised error.
1586
+ */
1587
+ function callPort(port, params, { timeout = 1e3, channelName = "", log = () => {}, newCallId = () => `call-${Date.now()}-${String(Math.random()).substring(2)}`, signal } = {}) {
1588
+ const callId = newCallId();
1589
+ log("[callPort]", {
1590
+ channelName,
1591
+ callId,
1592
+ params
1593
+ });
1594
+ const combinedSignal = combineSignals(signal, getPortCloseSignal(port));
1595
+ let timerId;
1596
+ let onMessage;
1597
+ let onAbort;
1598
+ const promise = new Promise((resolve, reject) => {
1599
+ if (combinedSignal?.aborted) {
1600
+ reject(abortReason(combinedSignal));
1601
+ return;
1602
+ }
1603
+ if (Number.isFinite(timeout) && timeout > 0) timerId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Call timeout. CallId: "${callId}".`)), timeout);
1604
+ onMessage = (event) => {
1605
+ const data = event.data;
1606
+ if (!data) return;
1607
+ if (data.channelName !== channelName) return;
1608
+ if (data.callId !== callId) return;
1609
+ if (data.type === "response:error") reject(deserializeError(data.error));
1610
+ else if (data.type === "response:result") resolve(data.result);
1611
+ };
1612
+ port.addEventListener("message", onMessage);
1613
+ if (combinedSignal) {
1614
+ onAbort = () => reject(abortReason(combinedSignal));
1615
+ combinedSignal.addEventListener("abort", onAbort, { once: true });
1616
+ }
1617
+ });
1618
+ promise.catch(() => {}).finally(() => {
1619
+ if (timerId !== void 0) clearTimeout(timerId);
1620
+ if (onMessage) port.removeEventListener("message", onMessage);
1621
+ if (onAbort && combinedSignal) combinedSignal.removeEventListener("abort", onAbort);
1622
+ });
1623
+ port.postMessage({
1624
+ type: "request",
1625
+ channelName,
1626
+ callId,
1627
+ params
1628
+ });
1629
+ return promise;
1630
+ }
1631
+ function abortReason(signal) {
1632
+ const reason = signal.reason;
1633
+ if (reason instanceof Error) return reason;
1634
+ const err = new Error(reason === void 0 ? "Aborted" : String(reason));
1635
+ err.name = "AbortError";
1636
+ return err;
1637
+ }
1638
+ function combineSignals(...signals) {
1639
+ const live = signals.filter((s) => s !== void 0);
1640
+ if (live.length === 0) return void 0;
1641
+ if (live.length === 1) return live[0];
1642
+ return AbortSignal.any(live);
1643
+ }
1644
+ /**
1645
+ * Installs `handler` as the server side of a `callPort` / `listenPort`
1646
+ * request/response pair on `port`.
1647
+ *
1648
+ * Returns a cleanup function that removes the listener.
1649
+ */
1650
+ function listenPort(port, handler, { channelName = "", log = () => {} } = {}) {
1651
+ const onMessage = async (event) => {
1652
+ const data = event.data;
1653
+ if (!data || data.channelName !== channelName || data.type !== "request") return;
1654
+ const { callId, params } = data;
1655
+ log("[listenPort]", {
1656
+ channelName,
1657
+ callId,
1658
+ params
1659
+ });
1660
+ let result;
1661
+ let error;
1662
+ let type;
1663
+ try {
1664
+ result = await handler(params);
1665
+ type = "response:result";
1666
+ } catch (e) {
1667
+ error = serializeError(e);
1668
+ type = "response:error";
1669
+ }
1670
+ port.postMessage({
1671
+ callId,
1672
+ channelName,
1673
+ type,
1674
+ result,
1675
+ error
1676
+ });
1677
+ };
1678
+ port.addEventListener("message", onMessage);
1679
+ return () => port.removeEventListener("message", onMessage);
1680
+ }
1681
+ /**
1682
+ * Wraps an async iterable so that an `AbortSignal` firing causes the wrapper
1683
+ * to return cleanly, forwarding `return()` to the underlying iterator so the
1684
+ * producer (e.g., a user-supplied generator) sees its own `finally` blocks
1685
+ * run immediately rather than waiting for the next yield.
1686
+ */
1687
+ async function* throughAbort(input, signal) {
1688
+ const iter = input[Symbol.asyncIterator] ? input[Symbol.asyncIterator]() : input[Symbol.iterator]();
1689
+ const onAbort = () => {
1690
+ iter.return?.(void 0);
1691
+ };
1692
+ if (signal.aborted) {
1693
+ iter.return?.(void 0);
1694
+ return;
1695
+ }
1696
+ signal.addEventListener("abort", onAbort, { once: true });
1697
+ try {
1698
+ while (true) {
1699
+ const r = await iter.next();
1700
+ if (r.done) return;
1701
+ if (signal.aborted) return;
1702
+ yield r.value;
1703
+ }
1704
+ } finally {
1705
+ signal.removeEventListener("abort", onAbort);
1706
+ }
1707
+ }
1708
+ /**
1709
+ * Makes `target` disposable with `await using`: installs `dispose` as its
1710
+ * `[Symbol.asyncDispose]`, where the runtime defines the symbol. Hand-written
1711
+ * iterators lose what a native generator gets from `AsyncIteratorPrototype`;
1712
+ * this gives it back. A no-op where the symbol is missing. Kept off the
1713
+ * declared types, which would require consumers to compile with the
1714
+ * `esnext.disposable` lib.
1715
+ */
1716
+ function asyncDisposable$1(target, dispose) {
1717
+ const asyncDispose = Symbol.asyncDispose;
1718
+ if (asyncDispose && !(asyncDispose in target)) Object.defineProperty(target, asyncDispose, {
1719
+ value: async () => {
1720
+ await dispose();
1721
+ },
1722
+ configurable: true,
1723
+ writable: true
1724
+ });
1725
+ return target;
1726
+ }
1727
+ /**
1728
+ * `gen`, except that `return()` and `throw()` take effect at once.
1729
+ *
1730
+ * On an async generator both are queued behind a `next()` that is still
1731
+ * pending: a consumer that gives up on a stream while it waits for the peer's
1732
+ * next chunk — an aborted fetch whose response head has not come, say — cannot
1733
+ * end it until that chunk arrives, which for a peer that never answers is
1734
+ * never. The stream's `finally` (which closes its port and tells the peer)
1735
+ * then never runs, and on a multiplexer the port is kept for good.
1736
+ *
1737
+ * So `abandon` runs first, synchronously: it must make the pending `next()`
1738
+ * settle (abort the stream), which then resolves done, after which the
1739
+ * generator's own `return()` / `throw()` proceeds as usual. On a generator
1740
+ * suspended at a `yield` it is the same ending, a step earlier. `abandon` runs once, whichever comes first.
1741
+ */
1742
+ function returningAtOnce(gen, abandon) {
1743
+ let abandoned = false;
1744
+ const giveUp = (reason) => {
1745
+ if (abandoned) return;
1746
+ abandoned = true;
1747
+ abandon(reason);
1748
+ };
1749
+ const wrapped = {
1750
+ next: (...args) => gen.next(...args).catch((error) => {
1751
+ if (abandoned) return {
1752
+ done: true,
1753
+ value: void 0
1754
+ };
1755
+ throw error;
1756
+ }),
1757
+ return(value) {
1758
+ giveUp();
1759
+ return gen.return(value);
1760
+ },
1761
+ throw(error) {
1762
+ giveUp(error);
1763
+ return gen.throw(error);
1764
+ },
1765
+ [Symbol.asyncIterator]() {
1766
+ return wrapped;
1767
+ }
1768
+ };
1769
+ return asyncDisposable$1(wrapped, () => wrapped.return(void 0));
1770
+ }
1771
+ /**
1772
+ * The `type` of the out-of-band notice a side posts when it abandons a stream.
1773
+ *
1774
+ * Layer 1's `close` is not observable to layer 2 — a closed virtual port drops
1775
+ * its listeners silently and is indistinguishable from a working port nobody
1776
+ * is answering — so the peer would otherwise wait forever. Exported because
1777
+ * tests and adapters assert on it.
1778
+ */
1779
+ const STREAM_ABORT = "webrun-rpc:stream-abort";
1780
+ /** Caller's input travels on this channel; the handler listens on it. */
1781
+ const CHANNEL_IN = "in";
1782
+ /** The handler's output travels on this channel; the caller listens on it. */
1783
+ const CHANNEL_OUT = "out";
1784
+ /**
1785
+ * One port in, one `Duplex` out (spec D9).
1786
+ *
1787
+ * The returned `Duplex` runs a single stream on `port`: the caller's `input`
1788
+ * is sent chunk by chunk with `callPort`, and the handler's output arrives the
1789
+ * same way on the other channel. Within each direction the next chunk is never
1790
+ * sent until the previous one has been delivered *and* pulled past by the
1791
+ * consumer (spec D11) — the reply to a chunk call *is* the confirmation, and
1792
+ * `listenPort` withholds it until then.
1793
+ *
1794
+ * A stream port carries exactly one invocation. To make several calls, open
1795
+ * several ports: `mux.openPort({ kind: "stream" })` per call.
1796
+ */
1797
+ function duplexOverPort(port, options = {}) {
1798
+ return (input) => runCallerSide(port, input, options);
1799
+ }
1800
+ /**
1801
+ * Installs `handler` as the serving side of one stream on `port`. Returns an
1802
+ * idempotent teardown that abandons the stream and notifies the peer.
1803
+ */
1804
+ function serveDuplexOverPort(port, handler, options = {}) {
1805
+ const controller = new AbortController();
1806
+ const notice = installAbortNotice(port, controller);
1807
+ abortOnPortClose(port, controller);
1808
+ const clock = installStreamTimeout(controller, options.timeout);
1809
+ const inbound = receiveChunks(port, CHANNEL_IN, controller, clock.touch);
1810
+ let output;
1811
+ try {
1812
+ output = handler(inbound.stream);
1813
+ } catch (err) {
1814
+ const pump = sendChunks(port, CHANNEL_OUT, failing(err), options, controller.signal, clock.touch);
1815
+ pump.catch(() => {});
1816
+ disarmClockWhenBothSidesSettle(clock, pump, inbound.ended);
1817
+ return teardownOnce(controller, notice, clock, inbound, void 0);
1818
+ }
1819
+ const pump = sendChunks(port, CHANNEL_OUT, output, options, controller.signal, clock.touch);
1820
+ pump.catch(() => {});
1821
+ disarmClockWhenBothSidesSettle(clock, pump, inbound.ended);
1822
+ return teardownOnce(controller, notice, clock, inbound, output);
1823
+ }
1824
+ /**
1825
+ * A stream that completes normally has nobody left to call the returned
1826
+ * teardown — the caller only knows the stream ended, not that it must also
1827
+ * dispose the serve-side handle. Without this, the last `touch()`'s timer
1828
+ * stays armed for up to `timeout` ms after real completion, doing nothing
1829
+ * but holding the event loop open.
1830
+ *
1831
+ * Only disarms once BOTH `pump` (our output) and `inboundEnded` (the peer's
1832
+ * declared end of input, or an abort) have settled. Disarming on `pump`
1833
+ * alone is not safe: under half-close the handler can finish producing
1834
+ * output while the caller is still sending input, and a clock stopped then
1835
+ * would leave that still-open half with no deadline at all — worse than the
1836
+ * leak this fixes.
1837
+ */
1838
+ function disarmClockWhenBothSidesSettle(clock, pump, inboundEnded) {
1839
+ Promise.allSettled([pump, inboundEnded]).then(() => {
1840
+ clock.stop();
1841
+ });
1842
+ }
1843
+ async function* failing(err) {
1844
+ throw err;
1845
+ }
1846
+ function teardownOnce(controller, notice, clock, inbound, output) {
1847
+ let torn = false;
1848
+ return () => {
1849
+ if (torn) return;
1850
+ torn = true;
1851
+ if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: stream torn down"));
1852
+ notice.post();
1853
+ notice.stop();
1854
+ clock.stop();
1855
+ inbound.stop();
1856
+ output?.return(void 0).catch(() => {});
1857
+ };
1858
+ }
1859
+ function runCallerSide(port, input, options) {
1860
+ const controller = new AbortController();
1861
+ const notice = installAbortNotice(port, controller);
1862
+ abortOnPortClose(port, controller);
1863
+ const clock = installStreamTimeout(controller, options.timeout);
1864
+ const inbound = receiveChunks(port, CHANNEL_OUT, controller, clock.touch);
1865
+ const pump = sendChunks(port, CHANNEL_IN, input, options, controller.signal, clock.touch);
1866
+ pump.catch(() => {});
1867
+ return returningAtOnce((async function* () {
1868
+ try {
1869
+ yield* inbound.stream;
1870
+ } finally {
1871
+ if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the caller abandoned the stream"));
1872
+ notice.post();
1873
+ notice.stop();
1874
+ clock.stop();
1875
+ inbound.stop();
1876
+ await pump.catch(() => {});
1877
+ try {
1878
+ await port.close?.();
1879
+ } catch {}
1880
+ }
1881
+ })(), () => {
1882
+ if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the caller abandoned the stream"));
1883
+ });
1884
+ }
1885
+ /**
1886
+ * Listens for the peer's abort notice, and can post our own. The notice is a
1887
+ * plain message with no `channelName` and a `type` that is not `"request"`,
1888
+ * so neither `callPort` nor `listenPort` reacts to it, and it carries no
1889
+ * numeric `id`, so `structuredCodec` never mistakes it for a layer 1 envelope.
1890
+ */
1891
+ function installAbortNotice(port, controller) {
1892
+ const onMessage = (event) => {
1893
+ const data = event.data;
1894
+ if (!data || data.type !== "webrun-rpc:stream-abort") return;
1895
+ if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the peer abandoned the stream"));
1896
+ };
1897
+ port.addEventListener("message", onMessage);
1898
+ let posted = false;
1899
+ return {
1900
+ post() {
1901
+ if (posted) return;
1902
+ posted = true;
1903
+ try {
1904
+ port.postMessage({ type: STREAM_ABORT });
1905
+ } catch {}
1906
+ },
1907
+ stop() {
1908
+ port.removeEventListener("message", onMessage);
1909
+ }
1910
+ };
1911
+ }
1912
+ /**
1913
+ * Aborts the stream when its port closes underneath it — the multiplexer was
1914
+ * closed, or the peer closed the port — for ports that report it (see
1915
+ * `getPortCloseSignal`). Without this a stream waiting for the peer's next
1916
+ * chunk would wait forever on a port that can no longer deliver one: the
1917
+ * outbound half's `callPort` already fails on the close signal, but nothing
1918
+ * failed the inbound half.
1919
+ */
1920
+ function abortOnPortClose(port, controller) {
1921
+ const closed = getPortCloseSignal(port);
1922
+ if (!closed) return;
1923
+ const onClose = () => {
1924
+ if (!controller.signal.aborted) controller.abort(closed.reason);
1925
+ };
1926
+ if (closed.aborted) {
1927
+ onClose();
1928
+ return;
1929
+ }
1930
+ closed.addEventListener("abort", onClose, { once: true });
1931
+ controller.signal.addEventListener("abort", () => closed.removeEventListener("abort", onClose), { once: true });
1932
+ }
1933
+ /**
1934
+ * The per-stream inactivity timeout (spec D8). Reset by any chunk in either
1935
+ * direction; elapsing aborts the stream. Unset, zero or non-finite installs no
1936
+ * timer at all, which is the default: a slow consumer is throttled, not failed.
1937
+ */
1938
+ function installStreamTimeout(controller, timeout) {
1939
+ if (timeout === void 0 || !Number.isFinite(timeout) || timeout <= 0) return {
1940
+ touch() {},
1941
+ stop() {}
1942
+ };
1943
+ let timer;
1944
+ let stopped = false;
1945
+ const arm = () => {
1946
+ timer = setTimeout(() => {
1947
+ if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error(`webrun-rpc: stream idle for ${timeout} ms`));
1948
+ }, timeout);
1949
+ };
1950
+ arm();
1951
+ return {
1952
+ touch() {
1953
+ if (stopped) return;
1954
+ if (timer !== void 0) clearTimeout(timer);
1955
+ arm();
1956
+ },
1957
+ stop() {
1958
+ stopped = true;
1959
+ if (timer !== void 0) clearTimeout(timer);
1960
+ timer = void 0;
1961
+ }
1962
+ };
1963
+ }
1964
+ /**
1965
+ * The receiving half of one direction.
1966
+ *
1967
+ * The `listenPort` listener is installed **eagerly**, not lazily inside
1968
+ * `recieveIterator`'s installer, because a handler that never drains its input
1969
+ * would otherwise leave the peer's chunk calls with nobody to answer them. If
1970
+ * the local consumer has not started iterating, an inbound chunk waits for it —
1971
+ * which is the correct backpressure, and different from having no listener.
1972
+ */
1973
+ function receiveChunks(port, channelName, controller, touch) {
1974
+ let deliver;
1975
+ const waiting = [];
1976
+ let finished = false;
1977
+ let outstanding = false;
1978
+ let poison;
1979
+ let resolveEnded = () => {};
1980
+ const ended = new Promise((resolve) => {
1981
+ resolveEnded = resolve;
1982
+ });
1983
+ let aborted = false;
1984
+ let abortReason;
1985
+ const ready = () => deliver || finished ? Promise.resolve() : new Promise((r) => waiting.push(r));
1986
+ const wake = () => {
1987
+ for (const r of waiting.splice(0)) r();
1988
+ };
1989
+ const off = listenPort(port, async ({ done, value, error }) => {
1990
+ touch();
1991
+ if (poison) throw poison;
1992
+ if (outstanding) {
1993
+ poison = /* @__PURE__ */ new Error("webrun-rpc: peer sent a second unconfirmed chunk; the stream port is closed");
1994
+ controller.abort(poison);
1995
+ setTimeout(() => {
1996
+ try {
1997
+ port.close?.();
1998
+ } catch {}
1999
+ }, 0);
2000
+ throw poison;
2001
+ }
2002
+ outstanding = true;
2003
+ try {
2004
+ await ready();
2005
+ if (finished) throw poison ?? /* @__PURE__ */ new Error("webrun-rpc: the stream is closed");
2006
+ await deliver?.({
2007
+ done,
2008
+ value,
2009
+ error: error ? deserializeError(error) : void 0
2010
+ });
2011
+ } finally {
2012
+ outstanding = false;
2013
+ }
2014
+ if (done) resolveEnded();
2015
+ }, { channelName });
2016
+ const detach = () => {
2017
+ finished = true;
2018
+ wake();
2019
+ off();
2020
+ controller.signal.removeEventListener("abort", onAbort);
2021
+ resolveEnded();
2022
+ };
2023
+ const onAbort = () => {
2024
+ aborted = true;
2025
+ abortReason = controller.signal.reason;
2026
+ finished = true;
2027
+ wake();
2028
+ deliver?.({
2029
+ done: true,
2030
+ error: abortReason
2031
+ });
2032
+ resolveEnded();
2033
+ };
2034
+ controller.signal.addEventListener("abort", onAbort, { once: true });
2035
+ return {
2036
+ stream: recieveIterator((d) => {
2037
+ if (aborted) {
2038
+ d({
2039
+ done: true,
2040
+ error: abortReason
2041
+ });
2042
+ return detach;
2043
+ }
2044
+ deliver = d;
2045
+ wake();
2046
+ return detach;
2047
+ }),
2048
+ stop: detach,
2049
+ ended
2050
+ };
2051
+ }
2052
+ /**
2053
+ * The sending half of one direction: one `callPort` per chunk, one call
2054
+ * outstanding at a time (spec D11/D12), with no per-chunk deadline (spec D8).
2055
+ */
2056
+ async function sendChunks(port, channelName, output, { maxMessageSize, log }, signal, touch) {
2057
+ const stream = throughAbort(maxMessageSize ? toChunks(maxMessageSize)(output) : output, signal);
2058
+ try {
2059
+ await sendIterator(async ({ done, value, error }) => {
2060
+ if (signal.aborted) return;
2061
+ const chunk = {
2062
+ done,
2063
+ value,
2064
+ error: error === void 0 ? void 0 : serializeError(error)
2065
+ };
2066
+ log?.("[duplexOverPort] send", {
2067
+ channelName,
2068
+ done,
2069
+ size: value?.byteLength
2070
+ });
2071
+ await callPort(port, chunk, {
2072
+ channelName,
2073
+ timeout: NO_TIMEOUT,
2074
+ signal
2075
+ });
2076
+ touch();
2077
+ }, stream);
2078
+ } catch (err) {
2079
+ if (signal.aborted) return;
2080
+ throw err;
2081
+ }
2082
+ }
2083
+ /**
2084
+ * One virtual port.
2085
+ *
2086
+ * `deliver` and `markClosed` are deliberately not on `port`: the consumer holds
2087
+ * only a `MessageTarget`, so it cannot forge inbound traffic or close the port
2088
+ * out from under the multiplexer's bookkeeping.
2089
+ */
2090
+ function newVirtualPort(send, requestClose) {
2091
+ const listeners = /* @__PURE__ */ new Set();
2092
+ let closed = false;
2093
+ const closing = new AbortController();
2094
+ const abort = (reason) => {
2095
+ if (closing.signal.aborted) return;
2096
+ closing.abort(reason ?? /* @__PURE__ */ new Error("webrun-rpc: the port was closed"));
2097
+ };
2098
+ const port = {
2099
+ addEventListener(_type, listener) {
2100
+ listeners.add(listener);
2101
+ },
2102
+ removeEventListener(_type, listener) {
2103
+ listeners.delete(listener);
2104
+ },
2105
+ postMessage(message, transfer) {
2106
+ if (closed) return;
2107
+ send(message, transfer);
2108
+ },
2109
+ close() {
2110
+ if (closed) return;
2111
+ closed = true;
2112
+ const notify = requestClose;
2113
+ listeners.clear();
2114
+ notify();
2115
+ abort();
2116
+ }
2117
+ };
2118
+ setPortCloseSignal(port, closing.signal);
2119
+ return {
2120
+ port,
2121
+ deliver(payload) {
2122
+ if (closed) return;
2123
+ const event = new MessageEvent("message", { data: payload });
2124
+ for (const listener of [...listeners]) try {
2125
+ listener(event);
2126
+ } catch {}
2127
+ },
2128
+ markClosed(reason) {
2129
+ closed = true;
2130
+ listeners.clear();
2131
+ abort(reason);
2132
+ },
2133
+ isClosed() {
2134
+ return closed;
2135
+ }
2136
+ };
2137
+ }
2138
+ /**
2139
+ * The message of the error that fails the calls still in flight on a
2140
+ * multiplexer when it is closed (`PortMux.close()`).
2141
+ */
2142
+ const MUX_CLOSED_MESSAGE = "webrun-rpc: the multiplexer was closed";
2143
+ /** Ceiling on concurrently open virtual ports. Bounds the id table only. */
2144
+ const DEFAULT_MAX_PORTS = 1024;
2145
+ /**
2146
+ * The default `PortMux`: emulates multiplexing over a single port.
2147
+ *
2148
+ * A transport that already multiplexes natively supplies its own `PortMux`
2149
+ * instead — this implementation is for transports that offer one pipe.
2150
+ */
2151
+ function multiplexPort(port, options) {
2152
+ const { codec, onPort, side = "initiator", maxPorts = DEFAULT_MAX_PORTS, maxMessageSize } = options;
2153
+ const open = /* @__PURE__ */ new Map();
2154
+ let nextId = side === "initiator" ? 0 : 1;
2155
+ let muxClosed = false;
2156
+ const post = (envelope, transfer) => {
2157
+ if (muxClosed) return;
2158
+ try {
2159
+ codec.post(port, envelope, transfer);
2160
+ } catch {}
2161
+ };
2162
+ const attach = (id) => {
2163
+ let self;
2164
+ self = newVirtualPort((payload, transfer) => post({
2165
+ type: "message",
2166
+ id,
2167
+ payload
2168
+ }, transfer), (reason) => {
2169
+ post({
2170
+ type: "close",
2171
+ id,
2172
+ reason
2173
+ });
2174
+ open.delete(id);
2175
+ self.markClosed();
2176
+ });
2177
+ open.set(id, self);
2178
+ return self;
2179
+ };
2180
+ const handleEnvelope = (envelope) => {
2181
+ if (muxClosed) return;
2182
+ if (envelope.type === "open") {
2183
+ if (open.has(envelope.id)) return;
2184
+ if (open.size >= maxPorts) {
2185
+ post({
2186
+ type: "close",
2187
+ id: envelope.id,
2188
+ reason: "max-ports"
2189
+ });
2190
+ return;
2191
+ }
2192
+ const handle = attach(envelope.id);
2193
+ let accepted = false;
2194
+ if (onPort) try {
2195
+ accepted = onPort(handle.port, envelope.meta) !== false;
2196
+ } catch {
2197
+ accepted = false;
2198
+ }
2199
+ if (!accepted) {
2200
+ open.delete(envelope.id);
2201
+ handle.markClosed(/* @__PURE__ */ new Error("webrun-rpc: the port was rejected"));
2202
+ post({
2203
+ type: "close",
2204
+ id: envelope.id,
2205
+ reason: "rejected"
2206
+ });
2207
+ }
2208
+ return;
2209
+ }
2210
+ const handle = open.get(envelope.id);
2211
+ if (envelope.type === "message") {
2212
+ if (!handle) return;
2213
+ handle.deliver(envelope.payload);
2214
+ return;
2215
+ }
2216
+ if (!handle) return;
2217
+ open.delete(envelope.id);
2218
+ handle.markClosed(/* @__PURE__ */ new Error("webrun-rpc: the peer closed the port"));
2219
+ };
2220
+ const listener = (event) => {
2221
+ const envelope = codec.read(event);
2222
+ if (envelope) handleEnvelope(envelope);
2223
+ };
2224
+ port.addEventListener("message", listener);
2225
+ port.start?.();
2226
+ return {
2227
+ maxMessageSize,
2228
+ async openPort(meta) {
2229
+ if (muxClosed) throw new Error("webrun-rpc: the multiplexer is closed");
2230
+ if (open.size >= maxPorts) throw new RangeError(`webrun-rpc: maxPorts (${maxPorts}) reached`);
2231
+ while (open.has(nextId)) nextId += 2;
2232
+ const id = nextId;
2233
+ nextId += 2;
2234
+ const handle = attach(id);
2235
+ post({
2236
+ type: "open",
2237
+ id,
2238
+ meta
2239
+ });
2240
+ return handle.port;
2241
+ },
2242
+ async close() {
2243
+ if (muxClosed) return;
2244
+ for (const [id, handle] of [...open]) {
2245
+ post({
2246
+ type: "close",
2247
+ id
2248
+ });
2249
+ open.delete(id);
2250
+ handle.markClosed(/* @__PURE__ */ new Error(MUX_CLOSED_MESSAGE));
2251
+ }
2252
+ muxClosed = true;
2253
+ port.removeEventListener("message", listener);
2254
+ await port.close?.();
2255
+ }
2256
+ };
2257
+ }
2258
+ /**
2259
+ * Announced with every port this pair opens. Layer 1 never reads `meta` — it is
2260
+ * here so a peer running something else over the same multiplexer can tell a
2261
+ * stream port from whatever else it hands out, and so a packet capture says
2262
+ * what the port is for.
2263
+ */
2264
+ const STREAM_META = { kind: "stream" };
2265
+ /**
2266
+ * One port source in, one caller `Duplex` out.
2267
+ *
2268
+ * A call is a port: the mux allocates one, `duplexOverPort` runs the single
2269
+ * invocation on it, and closing the stream closes the port. No stream ids, no
2270
+ * framing and no credit accounting live here — the mux owns the first, and
2271
+ * `duplexOverPort` owns the one-chunk window that makes memory bounded.
2272
+ */
2273
+ const connect = async ({ mux: factory, timeout }) => {
2274
+ const mux = await factory();
2275
+ const streamOptions = {
2276
+ maxMessageSize: mux.maxMessageSize,
2277
+ timeout
2278
+ };
2279
+ const call = (input) => {
2280
+ let stream;
2281
+ let abandoned = false;
2282
+ return returningAtOnce((async function* () {
2283
+ const port = await mux.openPort(STREAM_META);
2284
+ if (abandoned) {
2285
+ await port.close?.();
2286
+ return;
2287
+ }
2288
+ stream = duplexOverPort(port, streamOptions)(input);
2289
+ yield* stream;
2290
+ })(), () => {
2291
+ abandoned = true;
2292
+ stream?.return(void 0).catch(() => {});
2293
+ });
2294
+ };
2295
+ return {
2296
+ call,
2297
+ async close() {
2298
+ await mux.close();
2299
+ }
2300
+ };
2301
+ };
2302
+ /**
2303
+ * One port source in, `handler` serving every call that arrives on it.
2304
+ *
2305
+ * Each inbound port is one invocation, so the factory's `onPort` is the accept
2306
+ * loop: it installs `handler` on the new port and nothing else. The returned
2307
+ * teardown abandons the streams still running *before* dropping the mux, so
2308
+ * the peer's callers reject with "the peer abandoned the stream" instead of
2309
+ * parking forever on a port that has silently gone inert — layer 1's close is
2310
+ * not observable to layer 2, which is why the notice has to be posted
2311
+ * deliberately.
2312
+ */
2313
+ const serve = async ({ mux: factory, timeout }, handler) => {
2314
+ const live = /* @__PURE__ */ new Set();
2315
+ let streamOptions = { timeout };
2316
+ const mux = await factory((port) => {
2317
+ let off;
2318
+ let finished = false;
2319
+ const tracked = (input) => (async function* () {
2320
+ try {
2321
+ yield* handler(input);
2322
+ } finally {
2323
+ finished = true;
2324
+ if (off) live.delete(off);
2325
+ }
2326
+ })();
2327
+ off = serveDuplexOverPort(port, tracked, streamOptions);
2328
+ if (!finished) live.add(off);
2329
+ });
2330
+ streamOptions = {
2331
+ maxMessageSize: mux.maxMessageSize,
2332
+ timeout
2333
+ };
2334
+ let torn = false;
2335
+ return async () => {
2336
+ if (torn) return;
2337
+ torn = true;
2338
+ for (const off of [...live]) {
2339
+ live.delete(off);
2340
+ try {
2341
+ off();
2342
+ } catch {}
2343
+ }
2344
+ await mux.close();
2345
+ };
2346
+ };
2347
+ /**
2348
+ * Ports over ONE PIPE OF BYTES — a `MessagePort`, a worker, a WebSocket.
2349
+ *
2350
+ * There is no second port to be had, so `multiplexPort`'s id table invents
2351
+ * them. Use this when the transport gives you exactly one channel.
2352
+ */
2353
+ function overPipe(pipe, options) {
2354
+ return (onPort) => multiplexPort(pipe, {
2355
+ ...options,
2356
+ onPort
2357
+ });
2358
+ }
2359
+ function isEnvelope(value) {
2360
+ if (typeof value !== "object" || value === null) return false;
2361
+ const candidate = value;
2362
+ if (typeof candidate.id !== "number") return false;
2363
+ if (!Number.isInteger(candidate.id) || candidate.id < 0) return false;
2364
+ return candidate.type === "open" || candidate.type === "message" || candidate.type === "close";
2365
+ }
2366
+ /**
2367
+ * For ports whose messages are structured values — a real `MessagePort`, a
2368
+ * worker, an iframe.
2369
+ *
2370
+ * Envelopes are posted as-is, so nothing is encoded, `ArrayBuffer`s move
2371
+ * zero-copy through the transfer list, and structured clone does the work the
2372
+ * platform already does well. This is a performance choice only: layer 2 may
2373
+ * not send anything a byte codec could not also carry.
2374
+ */
2375
+ const structuredCodec = {
2376
+ post(port, envelope, transfer) {
2377
+ if (transfer && transfer.length > 0) port.postMessage(envelope, transfer);
2378
+ else port.postMessage(envelope);
2379
+ },
2380
+ read(event) {
2381
+ return isEnvelope(event.data) ? event.data : void 0;
2382
+ }
2383
+ };
2384
+ //#endregion
2385
+ //#region src/link/async-dispose.ts
2386
+ /**
2387
+ * Makes `target` disposable with `await using`: installs `dispose` as its
2388
+ * `[Symbol.asyncDispose]`, where the runtime defines the symbol. Hand-written
2389
+ * iterators lose what a native generator gets from `AsyncIteratorPrototype`;
2390
+ * this gives it back. A no-op where the symbol is missing. Kept off the
2391
+ * declared types, which would require consumers to compile with the
2392
+ * `esnext.disposable` lib.
2393
+ */
2394
+ function asyncDisposable(target, dispose) {
2395
+ const asyncDispose = Symbol.asyncDispose;
2396
+ if (asyncDispose && !(asyncDispose in target)) Object.defineProperty(target, asyncDispose, {
2397
+ value: async () => {
2398
+ await dispose();
2399
+ },
2400
+ configurable: true,
2401
+ writable: true
2402
+ });
2403
+ return target;
2404
+ }
2405
+ //#endregion
2406
+ //#region src/link/http-link.ts
2407
+ /**
2408
+ * The version of the HTTP-over-`MessagePort` protocol this package speaks,
2409
+ * sent in every hand-shake that sets up a link. Version 1 was this package's
2410
+ * own `handleStreams` / `sendStream` (no backpressure); version 2 is
2411
+ * webrun-rpc's `connect` / `serve` over `overPipe` with webrun-http-streams'
2412
+ * `fetchOverDuplex` / `serveFetchOverDuplex`: one port per link, calls
2413
+ * multiplexed on it, each call a stream with a one-chunk window in both
2414
+ * directions, and cancellation that reaches the handler.
2415
+ */
2416
+ const HTTP_LINK_PROTOCOL = "webrun-http-link/2";
2417
+ /**
2418
+ * Why a request failed when its link went away under it: the far side (the
2419
+ * handler, or the ServiceWorker) was lost. The request may or may not have
2420
+ * been applied.
2421
+ */
2422
+ var LinkLostError = class extends Error {
2423
+ constructor(message = "The link was lost while this request was in flight") {
2424
+ super(`${message}; it may or may not have been applied.`);
2425
+ this.name = "LinkLostError";
2426
+ }
2427
+ };
2428
+ /**
2429
+ * Posted on a link's port by the calling end when it closes the link, so the
2430
+ * answering end can release it: a `MessagePort` never reports that its other
2431
+ * end is gone.
2432
+ */
2433
+ const LINK_CLOSE = "webrun-http:link-close";
2434
+ /** Opens the calling end of a link on `port` (one port per link). */
2435
+ async function connectHttpLink(port, { streamTimeout, maxPorts } = {}) {
2436
+ const { call, close } = await connect({
2437
+ mux: overPipe(port, {
2438
+ codec: structuredCodec,
2439
+ side: "initiator",
2440
+ maxPorts
2441
+ }),
2442
+ timeout: streamTimeout
2443
+ });
2444
+ return trackedLink((request) => fetchOverDuplex(call, request), async () => {
2445
+ try {
2446
+ port.postMessage({ type: LINK_CLOSE });
2447
+ } catch {}
2448
+ await close();
2449
+ });
2450
+ }
2451
+ /**
2452
+ * Serves `handler` on the answering end of a link. Resolves with a teardown
2453
+ * that abandons the requests still running (their handlers see the
2454
+ * cancellation) and releases the port.
2455
+ */
2456
+ async function serveHttpLink(port, handler, { streamTimeout, maxPorts, requestIdleMs } = {}) {
2457
+ const teardown = await serve({
2458
+ mux: overPipe(port, {
2459
+ codec: structuredCodec,
2460
+ side: "responder",
2461
+ maxPorts
2462
+ }),
2463
+ timeout: streamTimeout
2464
+ }, serveFetchOverDuplex(async (request) => await handler(request), { requestIdleMs }));
2465
+ const onClose = (event) => {
2466
+ if (event.data?.type === LINK_CLOSE) close();
2467
+ };
2468
+ const close = async () => {
2469
+ port.removeEventListener("message", onClose);
2470
+ await teardown();
2471
+ };
2472
+ port.addEventListener("message", onClose);
2473
+ return close;
2474
+ }
2475
+ /**
2476
+ * Wraps a `send` so the link knows its requests in flight (for draining and
2477
+ * load-based routing) and can fail them all at once when it is closed.
2478
+ */
2479
+ function trackedLink(send, release) {
2480
+ let inflight = 0;
2481
+ let closed = false;
2482
+ let lostReason;
2483
+ const failers = /* @__PURE__ */ new Set();
2484
+ const idleWaiters = [];
2485
+ const done = () => {
2486
+ inflight--;
2487
+ if (inflight === 0) for (const resolve of idleWaiters.splice(0)) resolve();
2488
+ };
2489
+ const link = {
2490
+ get inflight() {
2491
+ return inflight;
2492
+ },
2493
+ get closed() {
2494
+ return closed;
2495
+ },
2496
+ whenIdle() {
2497
+ return inflight === 0 ? Promise.resolve() : new Promise((r) => idleWaiters.push(r));
2498
+ },
2499
+ async send(request) {
2500
+ if (closed) throw lostReason ?? new LinkLostError("The link is closed");
2501
+ inflight++;
2502
+ let finished = false;
2503
+ const finish = () => {
2504
+ if (finished) return;
2505
+ finished = true;
2506
+ failers.delete(fail);
2507
+ done();
2508
+ };
2509
+ let fail = () => {};
2510
+ const lost = new Promise((_, reject) => {
2511
+ fail = reject;
2512
+ });
2513
+ failers.add(fail);
2514
+ lost.catch(() => {});
2515
+ let response;
2516
+ try {
2517
+ response = await Promise.race([send(request), lost]);
2518
+ } catch (error) {
2519
+ finish();
2520
+ throw lostReason ?? error;
2521
+ }
2522
+ if (!response.body) {
2523
+ finish();
2524
+ return response;
2525
+ }
2526
+ return new Response(guardBody(response.body, lost, () => lostReason, finish), {
2527
+ status: response.status,
2528
+ statusText: response.statusText,
2529
+ headers: response.headers
2530
+ });
2531
+ },
2532
+ async close(reason) {
2533
+ if (closed) return;
2534
+ closed = true;
2535
+ lostReason = reason ?? new LinkLostError("The link was closed");
2536
+ for (const fail of [...failers]) fail(lostReason);
2537
+ try {
2538
+ await release();
2539
+ } catch {}
2540
+ }
2541
+ };
2542
+ return asyncDisposable(link, () => link.close());
2543
+ }
2544
+ /**
2545
+ * A response body that reports its end (done, cancelled or failed) and fails
2546
+ * with the link's reason when the link is lost mid-stream.
2547
+ */
2548
+ function guardBody(body, lost, reason, finish) {
2549
+ const reader = body.getReader();
2550
+ return new ReadableStream({
2551
+ async pull(controller) {
2552
+ try {
2553
+ const { done, value } = await Promise.race([reader.read(), lost]);
2554
+ if (done) {
2555
+ finish();
2556
+ controller.close();
2557
+ return;
2558
+ }
2559
+ controller.enqueue(value);
2560
+ } catch (error) {
2561
+ finish();
2562
+ reader.cancel().catch(() => {});
2563
+ controller.error(reason() ?? error);
2564
+ }
2565
+ },
2566
+ async cancel(why) {
2567
+ finish();
2568
+ await reader.cancel(why).catch(() => {});
2569
+ }
2570
+ });
2571
+ }
2572
+ //#endregion
2573
+ //#region src/link/locks.ts
2574
+ function lockManager() {
2575
+ return globalThis.navigator?.locks;
2576
+ }
2577
+ function locksAvailable() {
2578
+ return lockManager() !== void 0;
2579
+ }
2580
+ /** A fresh lock name: `<prefix>:<uuid>`. */
2581
+ function newLockName(prefix) {
2582
+ return `${prefix}:${crypto.randomUUID()}`;
2583
+ }
2584
+ /**
2585
+ * Takes the lock `name` and holds it until the returned release is called or
2586
+ * this context dies. Resolves once the lock is held; with no Web Locks,
2587
+ * resolves at once.
2588
+ */
2589
+ async function holdLock(name) {
2590
+ const locks = lockManager();
2591
+ if (!locks) return () => {};
2592
+ let release = () => {};
2593
+ const released = new Promise((resolve) => {
2594
+ release = resolve;
2595
+ });
2596
+ await new Promise((held) => {
2597
+ locks.request(name, {}, () => {
2598
+ held();
2599
+ return released;
2600
+ }).catch(() => held());
2601
+ });
2602
+ return release;
2603
+ }
2604
+ /**
2605
+ * Calls `onLost` once the lock `name` is granted to this context — that is,
2606
+ * once whoever holds it is gone — and releases it at once. Returns a function
2607
+ * that stops watching. With no Web Locks, never calls `onLost`.
2608
+ */
2609
+ function watchLock(name, onLost) {
2610
+ const locks = lockManager();
2611
+ if (!locks) return () => {};
2612
+ const controller = new AbortController();
2613
+ locks.request(name, { signal: controller.signal }, () => {
2614
+ if (!controller.signal.aborted) onLost();
2615
+ }).catch(() => {});
2616
+ return () => controller.abort();
2617
+ }
2618
+ //#endregion
2619
+ //#region src/ws/frames.ts
2620
+ /**
2621
+ * The wire protocol of a WebSocket carried over a `MessagePort`.
2622
+ *
2623
+ * A `MessagePort` is a natural carrier for a WebSocket: messages arrive in
2624
+ * order, and strings and transferable `ArrayBuffer`s cross it as they are. The
2625
+ * protocol on top is these frames, the same in both directions:
2626
+ *
2627
+ * - `m` — one message. An `ArrayBuffer` is transferred, never copied.
2628
+ * - `c` — close. The side that closes first sends it; the other answers with
2629
+ * its own `c` (the echo), and both are then closed cleanly.
2630
+ * - `p` — ping, client to server, carrying the client's heartbeat period.
2631
+ * - `q` — pong, server to client.
2632
+ * - `a` — ack: the receiver consumed `n` more bytes of messages. This is the
2633
+ * flow control: what a side has sent and not yet seen acknowledged is its
2634
+ * `bufferedAmount`, and the server end can wait for it to fall
2635
+ * (`whenDrained`). Added in version 2; version 1 had no backpressure.
2636
+ *
2637
+ * HEARTBEAT. A `MessagePort` never reports that the other side died, so the
2638
+ * client pings every `hb` ms and closes with 1006 when pongs stop for `2·hb`;
2639
+ * the server closes with 1006 when pings stop for `3·hb`. That is how a socket
2640
+ * notices a closed tab or a terminated worker.
2641
+ *
2642
+ * Unknown frames are ignored, so a later version can add frames a peer of
2643
+ * this version skips.
2644
+ */
2645
+ /** The version of this frame protocol. Sent in the upgrade hand-shake. */
2646
+ const WS_PORT_PROTOCOL_VERSION = 2;
2647
+ /** Default heartbeat period of the client, in ms. */
2648
+ const DEFAULT_HEARTBEAT_MS = 1e4;
2649
+ /** How long a side waits for the echo of its close frame, in ms. */
2650
+ const DEFAULT_CLOSE_TIMEOUT_MS = 5e3;
2651
+ const defaultTimers = {
2652
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
2653
+ clearTimeout: (id) => clearTimeout(id),
2654
+ setInterval: (fn, ms) => setInterval(fn, ms),
2655
+ clearInterval: (id) => clearInterval(id)
2656
+ };
2657
+ /** Recovers a frame from a message's data, or `undefined` for anything else. */
2658
+ function readFrame(data) {
2659
+ if (typeof data !== "object" || data === null) return void 0;
2660
+ const frame = data;
2661
+ switch (frame.t) {
2662
+ case "m": return typeof frame.d === "string" || frame.d instanceof ArrayBuffer ? frame : void 0;
2663
+ case "c": return {
2664
+ t: "c",
2665
+ code: typeof frame.code === "number" ? frame.code : 1005,
2666
+ reason: typeof frame.reason === "string" ? frame.reason : ""
2667
+ };
2668
+ case "p": {
2669
+ const hb = frame.hb;
2670
+ return {
2671
+ t: "p",
2672
+ hb: typeof hb === "number" && hb > 0 ? hb : DEFAULT_HEARTBEAT_MS
2673
+ };
2674
+ }
2675
+ case "q": return { t: "q" };
2676
+ case "a": {
2677
+ const n = frame.n;
2678
+ return typeof n === "number" && n >= 0 ? {
2679
+ t: "a",
2680
+ n
2681
+ } : void 0;
2682
+ }
2683
+ default: return;
2684
+ }
2685
+ }
2686
+ /** Posts `frame`, transferring a message's `ArrayBuffer`. */
2687
+ function postFrame(port, frame) {
2688
+ if (frame.t === "m" && frame.d instanceof ArrayBuffer) port.postMessage(frame, [frame.d]);
2689
+ else port.postMessage(frame);
2690
+ }
2691
+ /** The size a message counts for in `bufferedAmount`: UTF-8 bytes, or the buffer's length. */
2692
+ function messageSize(data) {
2693
+ return typeof data === "string" ? utf8Length(data) : data.byteLength;
2694
+ }
2695
+ /** The UTF-8 length of `text`, without encoding it. */
2696
+ function utf8Length(text) {
2697
+ let length = 0;
2698
+ for (let i = 0; i < text.length; i++) {
2699
+ const code = text.charCodeAt(i);
2700
+ if (code < 128) length += 1;
2701
+ else if (code < 2048) length += 2;
2702
+ else if (code >= 55296 && code <= 56319 && i + 1 < text.length) {
2703
+ const next = text.charCodeAt(i + 1);
2704
+ if (next >= 56320 && next <= 57343) {
2705
+ length += 4;
2706
+ i++;
2707
+ } else length += 3;
2708
+ } else length += 3;
2709
+ }
2710
+ return length;
2711
+ }
2712
+ /**
2713
+ * A `CloseEvent` for runtimes that have none: Node 22 has `Event` and
2714
+ * `MessageEvent` as globals, but not `CloseEvent`.
2715
+ */
2716
+ var WsCloseEvent = class extends Event {
2717
+ code;
2718
+ reason;
2719
+ wasClean;
2720
+ constructor(type, init = {}) {
2721
+ super(type, init);
2722
+ this.code = init.code ?? 0;
2723
+ this.reason = init.reason ?? "";
2724
+ this.wasClean = init.wasClean ?? false;
2725
+ }
2726
+ };
2727
+ /** A `close` event: the platform's `CloseEvent` where there is one. */
2728
+ function newCloseEvent(init) {
2729
+ const Native = globalThis.CloseEvent;
2730
+ return Native ? new Native("close", init) : new WsCloseEvent("close", init);
2731
+ }
2732
+ /**
2733
+ * What both ends of a socket over a `MessagePort` share: the frames, the close
2734
+ * handshake, and the byte accounting behind `bufferedAmount`.
2735
+ *
2736
+ * Not exported from the package: the two ends are `createWebSocketClass`'s
2737
+ * class and `ServerWebSocket`.
2738
+ */
2739
+ var PortSocketCore = class extends EventTarget {
2740
+ _port;
2741
+ _state = 0;
2742
+ _timers;
2743
+ _closeTimeoutMs;
2744
+ /** Bytes sent and not yet acknowledged by the peer, plus those still being prepared. */
2745
+ _inFlight = 0;
2746
+ /** Bytes of messages "sent" after the socket started closing: counted, never sent. */
2747
+ _discarded = 0;
2748
+ _toAck = 0;
2749
+ _ackScheduled = false;
2750
+ _closeTimer;
2751
+ _drainWaiters = [];
2752
+ constructor(options = {}) {
2753
+ super();
2754
+ this._timers = options.timers ?? defaultTimers;
2755
+ this._closeTimeoutMs = options.closeTimeoutMs ?? 5e3;
2756
+ }
2757
+ get readyState() {
2758
+ return this._state;
2759
+ }
2760
+ /**
2761
+ * Bytes queued by `send()` that the peer has not consumed yet. A peer
2762
+ * acknowledges what it has dispatched, so this falls as the other side reads.
2763
+ */
2764
+ get bufferedAmount() {
2765
+ return this._inFlight + this._discarded;
2766
+ }
2767
+ /**
2768
+ * Resolves once `bufferedAmount` is at most `limit` (default 0), or the
2769
+ * socket is closed. The backpressure a producer applies:
2770
+ * `if (socket.bufferedAmount > HIGH) await socket.whenDrained(LOW)`.
2771
+ */
2772
+ whenDrained(limit = 0) {
2773
+ if (this._state === 3 || this._inFlight <= limit) return Promise.resolve();
2774
+ return new Promise((resolve) => this._drainWaiters.push({
2775
+ limit,
2776
+ resolve
2777
+ }));
2778
+ }
2779
+ _attach(port) {
2780
+ this._port = port;
2781
+ port.onmessage = (event) => {
2782
+ const frame = readFrame(event.data);
2783
+ if (frame) this._onFrame(frame);
2784
+ };
2785
+ }
2786
+ _onFrame(frame) {
2787
+ switch (frame.t) {
2788
+ case "m":
2789
+ case "c":
2790
+ this._deliver(frame);
2791
+ return;
2792
+ case "a":
2793
+ this._inFlight = Math.max(0, this._inFlight - frame.n);
2794
+ this._wakeDrainWaiters();
2795
+ return;
2796
+ case "p":
2797
+ this._onPing(frame.hb);
2798
+ return;
2799
+ case "q":
2800
+ this._onPong();
2801
+ return;
2802
+ }
2803
+ }
2804
+ /** A message or close frame the socket is ready to act on. */
2805
+ _deliver(frame) {
2806
+ if (frame.t === "c") {
2807
+ this._onCloseFrame(frame.code, frame.reason);
2808
+ return;
2809
+ }
2810
+ if (this._state !== 1) return;
2811
+ this._dispatchMessage(frame.d);
2812
+ this._consumed(messageSize(frame.d));
2813
+ }
2814
+ _onPing(_hb) {}
2815
+ _onPong() {}
2816
+ _onClosed() {}
2817
+ /** Acknowledge consumed bytes, coalescing the acks of one turn into one frame. */
2818
+ _consumed(bytes) {
2819
+ this._toAck += bytes;
2820
+ if (this._ackScheduled) return;
2821
+ this._ackScheduled = true;
2822
+ queueMicrotask(() => {
2823
+ this._ackScheduled = false;
2824
+ const n = this._toAck;
2825
+ this._toAck = 0;
2826
+ if (n > 0 && this._state !== 3) this._post({
2827
+ t: "a",
2828
+ n
2829
+ });
2830
+ });
2831
+ }
2832
+ /** Reserves `bytes` in `bufferedAmount` for a message still being prepared (a Blob). */
2833
+ _reserve(bytes) {
2834
+ this._inFlight += bytes;
2835
+ }
2836
+ /** Sends one message whose bytes were reserved with `_reserve` (or `reserved = false`). */
2837
+ _sendData(data, reserved = false) {
2838
+ const size = messageSize(data);
2839
+ if (this._state !== 1) {
2840
+ if (reserved) this._inFlight = Math.max(0, this._inFlight - size);
2841
+ this._discarded += size;
2842
+ return;
2843
+ }
2844
+ if (!reserved) this._inFlight += size;
2845
+ this._post({
2846
+ t: "m",
2847
+ d: data
2848
+ });
2849
+ }
2850
+ _post(frame) {
2851
+ try {
2852
+ if (this._port) postFrame(this._port, frame);
2853
+ } catch {}
2854
+ }
2855
+ /** Starts the close handshake. */
2856
+ _startClose(code, reason) {
2857
+ if (this._state === 2 || this._state === 3) return;
2858
+ this._state = 2;
2859
+ this._post({
2860
+ t: "c",
2861
+ code,
2862
+ reason
2863
+ });
2864
+ this._closeTimer = this._timers.setTimeout(() => this._finish(1006, "", false), this._closeTimeoutMs);
2865
+ }
2866
+ _onCloseFrame(code, reason) {
2867
+ if (this._state === 3) return;
2868
+ if (this._state === 2) {
2869
+ this._finish(code, reason, true);
2870
+ return;
2871
+ }
2872
+ this._state = 2;
2873
+ this._post({
2874
+ t: "c",
2875
+ code,
2876
+ reason
2877
+ });
2878
+ this._finish(code, reason, true);
2879
+ }
2880
+ /** The socket is closed: release the port and tell the listeners. */
2881
+ _finish(code, reason, wasClean, error = false) {
2882
+ if (this._state === 3) return;
2883
+ this._state = 3;
2884
+ if (this._closeTimer !== void 0) this._timers.clearTimeout(this._closeTimer);
2885
+ this._closeTimer = void 0;
2886
+ this._onClosed();
2887
+ if (this._port) {
2888
+ this._port.onmessage = null;
2889
+ try {
2890
+ this._port.close();
2891
+ } catch {}
2892
+ }
2893
+ this._wakeDrainWaiters();
2894
+ if (error) this.dispatchEvent(new Event("error"));
2895
+ this.dispatchEvent(newCloseEvent({
2896
+ code,
2897
+ reason,
2898
+ wasClean
2899
+ }));
2900
+ }
2901
+ _wakeDrainWaiters() {
2902
+ if (this._drainWaiters.length === 0) return;
2903
+ const closed = this._state === 3;
2904
+ this._drainWaiters = this._drainWaiters.filter(({ limit, resolve }) => {
2905
+ if (!closed && this._inFlight > limit) return true;
2906
+ resolve();
2907
+ return false;
2908
+ });
2909
+ }
2910
+ };
2911
+ /** Copies `data` into a fresh `ArrayBuffer`: `send()` must never detach the caller's buffer. */
2912
+ function toArrayBuffer(data) {
2913
+ if (data instanceof ArrayBuffer) return data.slice(0);
2914
+ const copy = new Uint8Array(data.byteLength);
2915
+ copy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
2916
+ return copy.buffer;
2917
+ }
2918
+ function isBinary(data) {
2919
+ return data instanceof ArrayBuffer || ArrayBuffer.isView(data);
2920
+ }
2921
+ function isBlob(data) {
2922
+ return typeof Blob !== "undefined" && data instanceof Blob;
2923
+ }
2924
+ /** Valid close codes for an application to send: 1000, or 3000–4999. */
2925
+ function isApplicationCloseCode(code) {
2926
+ return code === 1e3 || code >= 3e3 && code <= 4999;
2927
+ }
2928
+ //#endregion
2929
+ //#region src/ws/client.ts
2930
+ /** RFC 7230 `token`: what a subprotocol name may be. */
2931
+ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
2932
+ /**
2933
+ * A WHATWG-compatible `WebSocket` class whose transport is a `MessagePort`
2934
+ * from `connect`. Code written against the browser's `WebSocket` runs on it
2935
+ * unchanged:
2936
+ *
2937
+ * ```ts
2938
+ * const WS = createWebSocketClass(adapter.connectWebSocket);
2939
+ * const ws = new WS(`${baseUrl}chat`, ["v1"]);
2940
+ * ws.onmessage = (event) => console.log(event.data);
2941
+ * ```
2942
+ *
2943
+ * It validates as the standard does (url, scheme, fragment, subprotocol
2944
+ * tokens and duplicates, close codes and reasons), has `binaryType`, the `on*`
2945
+ * handlers next to `addEventListener`, and the close handshake.
2946
+ * `bufferedAmount` is real: the server acknowledges what it consumed.
2947
+ *
2948
+ * The real `globalThis.WebSocket` is left alone; install the class where you
2949
+ * want it.
2950
+ */
2951
+ function createWebSocketClass(connect, options = {}) {
2952
+ const heartbeatMs = options.heartbeatMs ?? 1e4;
2953
+ class WebSocketOverPort extends PortSocketCore {
2954
+ static CONNECTING = 0;
2955
+ static OPEN = 1;
2956
+ static CLOSING = 2;
2957
+ static CLOSED = 3;
2958
+ CONNECTING = 0;
2959
+ OPEN = 1;
2960
+ CLOSING = 2;
2961
+ CLOSED = 3;
2962
+ url;
2963
+ extensions = "";
2964
+ _protocol = "";
2965
+ _binaryType = "blob";
2966
+ _handlers = {};
2967
+ _heartbeat;
2968
+ /** When the oldest ping still waiting for its pong was sent. */
2969
+ _unansweredSince;
2970
+ _onVisibility;
2971
+ /** Sends waiting for a Blob ahead of them to be read, so order is kept. */
2972
+ _chain;
2973
+ constructor(url, protocols = []) {
2974
+ super({
2975
+ timers: options.timers,
2976
+ closeTimeoutMs: options.closeTimeoutMs
2977
+ });
2978
+ this.url = parseUrl(url);
2979
+ const list = typeof protocols === "string" ? [protocols] : [...protocols];
2980
+ validateProtocols(list);
2981
+ for (const type of [
2982
+ "open",
2983
+ "message",
2984
+ "error",
2985
+ "close"
2986
+ ]) this.addEventListener(type, (event) => this._handlers[type]?.call(this, event));
2987
+ Promise.resolve().then(() => connect(this.url, list)).then((connection) => {
2988
+ try {
2989
+ this._opened(connection, list);
2990
+ } catch {
2991
+ this._failed();
2992
+ }
2993
+ }, () => this._failed());
2994
+ }
2995
+ get protocol() {
2996
+ return this._protocol;
2997
+ }
2998
+ get binaryType() {
2999
+ return this._binaryType;
3000
+ }
3001
+ set binaryType(value) {
3002
+ if (value === "blob" || value === "arraybuffer") this._binaryType = value;
3003
+ }
3004
+ get onopen() {
3005
+ return this._handlers.open ?? null;
3006
+ }
3007
+ set onopen(fn) {
3008
+ this._handlers.open = typeof fn === "function" ? fn : null;
3009
+ }
3010
+ get onmessage() {
3011
+ return this._handlers.message ?? null;
3012
+ }
3013
+ set onmessage(fn) {
3014
+ this._handlers.message = typeof fn === "function" ? fn : null;
3015
+ }
3016
+ get onerror() {
3017
+ return this._handlers.error ?? null;
3018
+ }
3019
+ set onerror(fn) {
3020
+ this._handlers.error = typeof fn === "function" ? fn : null;
3021
+ }
3022
+ get onclose() {
3023
+ return this._handlers.close ?? null;
3024
+ }
3025
+ set onclose(fn) {
3026
+ this._handlers.close = typeof fn === "function" ? fn : null;
3027
+ }
3028
+ send(data) {
3029
+ if (this._state === 0) throw new DOMException("Still in CONNECTING state.", "InvalidStateError");
3030
+ if (isBlob(data)) {
3031
+ const size = data.size;
3032
+ if (this._state !== 1) {
3033
+ this._sendData(new ArrayBuffer(size));
3034
+ return;
3035
+ }
3036
+ this._reserve(size);
3037
+ this._enqueue(async () => this._sendData(await data.arrayBuffer(), true));
3038
+ return;
3039
+ }
3040
+ const payload = isBinary(data) ? toArrayBuffer(data) : String(data);
3041
+ if (this._chain) this._enqueue(async () => this._sendData(payload));
3042
+ else this._sendData(payload);
3043
+ }
3044
+ close(code, reason) {
3045
+ if (code !== void 0 && !isApplicationCloseCode(code)) throw new DOMException(`The close code must be 1000 or in 3000-4999; ${code} is neither.`, "InvalidAccessError");
3046
+ const text = reason ?? "";
3047
+ if (utf8Length(text) > 123) throw new DOMException("The close reason is longer than 123 bytes.", "SyntaxError");
3048
+ if (this._state === 2 || this._state === 3) return;
3049
+ if (this._state === 0) {
3050
+ this._state = 2;
3051
+ return;
3052
+ }
3053
+ this._startClose(code ?? 1005, text);
3054
+ }
3055
+ _dispatchMessage(data) {
3056
+ const value = typeof data === "string" || this._binaryType === "arraybuffer" ? data : new Blob([data]);
3057
+ this.dispatchEvent(new MessageEvent("message", {
3058
+ data: value,
3059
+ origin: new URL(this.url).origin
3060
+ }));
3061
+ }
3062
+ _onPong() {
3063
+ this._unansweredSince = void 0;
3064
+ }
3065
+ _onClosed() {
3066
+ if (this._heartbeat !== void 0) this._timers.clearInterval(this._heartbeat);
3067
+ this._heartbeat = void 0;
3068
+ if (this._onVisibility) globalThis.document?.removeEventListener("visibilitychange", this._onVisibility);
3069
+ }
3070
+ _ping(hb = heartbeatMs) {
3071
+ this._unansweredSince ??= Date.now();
3072
+ this._post({
3073
+ t: "p",
3074
+ hb
3075
+ });
3076
+ }
3077
+ _opened(connection, requested) {
3078
+ const { port, protocol = "" } = connection ?? {};
3079
+ if (!port || typeof port.postMessage !== "function") {
3080
+ this._failed();
3081
+ return;
3082
+ }
3083
+ if (this._state !== 0) {
3084
+ try {
3085
+ port.postMessage({
3086
+ t: "c",
3087
+ code: 1006,
3088
+ reason: ""
3089
+ });
3090
+ port.close();
3091
+ } catch {}
3092
+ this._finish(1006, "", false, true);
3093
+ return;
3094
+ }
3095
+ if (protocol !== "" && !requested.includes(protocol)) {
3096
+ port.close();
3097
+ this._failed();
3098
+ return;
3099
+ }
3100
+ this._protocol = protocol;
3101
+ this._attach(port);
3102
+ this._state = 1;
3103
+ this._ping();
3104
+ this._heartbeat = this._timers.setInterval(() => {
3105
+ const since = this._unansweredSince;
3106
+ if (since !== void 0 && Date.now() - since > 2 * heartbeatMs) {
3107
+ this._finish(1006, "", false, true);
3108
+ return;
3109
+ }
3110
+ this._ping();
3111
+ }, heartbeatMs);
3112
+ const doc = globalThis.document;
3113
+ if (doc) {
3114
+ this._onVisibility = () => this._ping(doc.visibilityState === "hidden" ? Math.max(heartbeatMs, 7e4) : heartbeatMs);
3115
+ doc.addEventListener("visibilitychange", this._onVisibility);
3116
+ if (doc.visibilityState === "hidden") this._onVisibility();
3117
+ }
3118
+ this.dispatchEvent(new Event("open"));
3119
+ }
3120
+ _failed() {
3121
+ this._state = 2;
3122
+ this._finish(1006, "", false, true);
3123
+ }
3124
+ _enqueue(task) {
3125
+ const run = (this._chain ?? Promise.resolve()).then(task).catch(() => {});
3126
+ this._chain = run;
3127
+ run.then(() => {
3128
+ if (this._chain === run) this._chain = void 0;
3129
+ });
3130
+ }
3131
+ }
3132
+ return WebSocketOverPort;
3133
+ }
3134
+ function parseUrl(input) {
3135
+ let url;
3136
+ try {
3137
+ url = new URL(`${input}`, globalThis.location?.href);
3138
+ } catch {
3139
+ throw new DOMException(`The URL '${input}' is invalid.`, "SyntaxError");
3140
+ }
3141
+ if (url.protocol === "http:") url.protocol = "ws:";
3142
+ else if (url.protocol === "https:") url.protocol = "wss:";
3143
+ if (url.protocol !== "ws:" && url.protocol !== "wss:") throw new DOMException(`The URL's scheme must be 'ws', 'wss', 'http' or 'https'; '${url.protocol.slice(0, -1)}' is not allowed.`, "SyntaxError");
3144
+ if (url.hash !== "" || `${input}`.includes("#")) throw new DOMException(`The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`, "SyntaxError");
3145
+ return url.href;
3146
+ }
3147
+ function validateProtocols(protocols) {
3148
+ const seen = /* @__PURE__ */ new Set();
3149
+ for (const protocol of protocols) {
3150
+ if (!TOKEN.test(protocol)) throw new DOMException(`The subprotocol '${protocol}' is invalid.`, "SyntaxError");
3151
+ if (seen.has(protocol)) throw new DOMException(`The subprotocol '${protocol}' is duplicated.`, "SyntaxError");
3152
+ seen.add(protocol);
3153
+ }
3154
+ }
3155
+ //#endregion
3156
+ //#region src/link/errors.ts
3157
+ function errorMessage(error) {
3158
+ return error instanceof Error ? error.message : String(error);
3159
+ }
3160
+ //#endregion
3161
+ //#region src/link/rendezvous.ts
3162
+ /**
3163
+ * Matches replies to requests by id, for the control messages that hand
3164
+ * WebSocket ports across: each waiting request has a deadline, and all of a
3165
+ * peer's waiting requests can be failed at once when the peer is lost.
3166
+ */
3167
+ var PortRendezvous = class {
3168
+ _prefix;
3169
+ _waiting = /* @__PURE__ */ new Map();
3170
+ _counter = 0;
3171
+ constructor(_prefix = "r") {
3172
+ this._prefix = _prefix;
3173
+ }
3174
+ /** A fresh id for a request. */
3175
+ newId() {
3176
+ return `${this._prefix}:${++this._counter}`;
3177
+ }
3178
+ get size() {
3179
+ return this._waiting.size;
3180
+ }
3181
+ /** Waits for the reply to `id`, failing after `timeoutMs`. */
3182
+ wait(id, timeoutMs, describe = "the reply") {
3183
+ return new Promise((resolve, reject) => {
3184
+ const timer = setTimeout(() => {
3185
+ this._waiting.delete(id);
3186
+ reject(/* @__PURE__ */ new Error(`No answer to ${describe} within ${timeoutMs} ms`));
3187
+ }, timeoutMs);
3188
+ this._waiting.set(id, {
3189
+ resolve,
3190
+ reject,
3191
+ timer
3192
+ });
3193
+ });
3194
+ }
3195
+ /** Delivers the reply to `id`. `false` when nobody waits for it (it timed out). */
3196
+ settle(id, value) {
3197
+ const waiting = this._waiting.get(id);
3198
+ if (!waiting) return false;
3199
+ this._waiting.delete(id);
3200
+ clearTimeout(waiting.timer);
3201
+ waiting.resolve(value);
3202
+ return true;
3203
+ }
3204
+ fail(id, error) {
3205
+ const waiting = this._waiting.get(id);
3206
+ if (!waiting) return;
3207
+ this._waiting.delete(id);
3208
+ clearTimeout(waiting.timer);
3209
+ waiting.reject(error);
3210
+ }
3211
+ failAll(error) {
3212
+ for (const id of [...this._waiting.keys()]) this.fail(id, error);
3213
+ }
3214
+ };
3215
+ //#endregion
3216
+ //#region src/ws/server.ts
3217
+ /**
3218
+ * The server end of a socket over a `MessagePort`: what a handler gets from
3219
+ * `upgradeWebSocket` and talks to.
3220
+ *
3221
+ * - Events are delivered only after `accept()`; frames that arrive earlier are
3222
+ * queued. Pings are answered even before `accept()`, so a slow handler does
3223
+ * not look like a dead one.
3224
+ * - Messages arrive as strings or `ArrayBuffer`s.
3225
+ * - `bufferedAmount` counts what the client has not consumed yet, and
3226
+ * `whenDrained(limit)` waits for it to fall: the backpressure a producer
3227
+ * applies.
3228
+ * - When the client's pings stop for three heartbeat periods (a closed tab, a
3229
+ * terminated worker), the socket closes with 1006.
3230
+ */
3231
+ var ServerWebSocket = class extends PortSocketCore {
3232
+ static CONNECTING = 0;
3233
+ static OPEN = 1;
3234
+ static CLOSING = 2;
3235
+ static CLOSED = 3;
3236
+ url;
3237
+ protocol;
3238
+ _accepted = false;
3239
+ _queue = [];
3240
+ _heartbeatMs = DEFAULT_HEARTBEAT_MS;
3241
+ _lastPing = Date.now();
3242
+ _watch;
3243
+ constructor(port, options = {}) {
3244
+ super({
3245
+ timers: options.timers,
3246
+ closeTimeoutMs: options.closeTimeoutMs
3247
+ });
3248
+ this.url = options.url ?? "";
3249
+ this.protocol = options.protocol ?? "";
3250
+ this._attach(port);
3251
+ this._state = 1;
3252
+ this._watchHeartbeat();
3253
+ }
3254
+ /** Whether `accept()` was called. */
3255
+ get accepted() {
3256
+ return this._accepted;
3257
+ }
3258
+ /** Starts delivering events, the queued ones first. */
3259
+ accept() {
3260
+ if (this._accepted) return;
3261
+ this._accepted = true;
3262
+ for (const frame of this._queue.splice(0)) super._deliver(frame);
3263
+ }
3264
+ send(data) {
3265
+ if (!this._accepted) throw new DOMException("accept() the socket before sending on it.", "InvalidStateError");
3266
+ this._sendData(isBinary(data) ? toArrayBuffer(data) : String(data));
3267
+ }
3268
+ close(code = 1e3, reason = "") {
3269
+ if (!isSendableCloseCode(code)) throw new DOMException(`${code} is not a close code an endpoint may send.`, "InvalidAccessError");
3270
+ if (utf8Length(reason) > 123) throw new DOMException("The close reason is longer than 123 bytes.", "SyntaxError");
3271
+ this._startClose(code, reason);
3272
+ }
3273
+ _deliver(frame) {
3274
+ if (!this._accepted) {
3275
+ this._queue.push(frame);
3276
+ return;
3277
+ }
3278
+ super._deliver(frame);
3279
+ }
3280
+ _dispatchMessage(data) {
3281
+ this.dispatchEvent(new MessageEvent("message", { data }));
3282
+ }
3283
+ _onPing(hb) {
3284
+ this._post({ t: "q" });
3285
+ this._lastPing = Date.now();
3286
+ if (hb !== this._heartbeatMs) {
3287
+ this._heartbeatMs = hb;
3288
+ this._watchHeartbeat();
3289
+ }
3290
+ }
3291
+ _onClosed() {
3292
+ if (this._watch !== void 0) this._timers.clearInterval(this._watch);
3293
+ this._watch = void 0;
3294
+ }
3295
+ _watchHeartbeat() {
3296
+ if (this._watch !== void 0) this._timers.clearInterval(this._watch);
3297
+ this._watch = this._timers.setInterval(() => {
3298
+ if (Date.now() - this._lastPing > 3 * this._heartbeatMs) this._finish(1006, "", false, true);
3299
+ }, this._heartbeatMs);
3300
+ }
3301
+ };
3302
+ /** Codes an endpoint may put in a close frame (RFC 6455 §7.4). */
3303
+ function isSendableCloseCode(code) {
3304
+ if (!Number.isInteger(code)) return false;
3305
+ if (code >= 3e3 && code <= 4999) return true;
3306
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006;
3307
+ }
3308
+ //#endregion
3309
+ //#region src/ws/upgrade.ts
3310
+ /**
3311
+ * The upgrade, as an HTTP exchange: a `GET` with `Upgrade: websocket` goes to
3312
+ * an ordinary `(Request) => Response` handler, and a `101` answer carrying a
3313
+ * server socket means accepted. Anything else is a refusal, with its status.
3314
+ *
3315
+ * FORBIDDEN HEADERS. A browser drops `Upgrade`, `Connection` and every
3316
+ * `Sec-*` header from a `new Request()`. The upgrade request therefore carries
3317
+ * its headers as an own `headers` property, a standalone `Headers` that keeps
3318
+ * them, so handler code reads `request.headers.get("upgrade")` as usual.
3319
+ *
3320
+ * NO 101 IN A `Response`. The constructor refuses statuses below 200, so the
3321
+ * response `upgradeWebSocket` returns reports 101 through an own `status`
3322
+ * property; the port that goes back to the caller is found with `takePort`.
3323
+ */
3324
+ /** The request header carrying the client's version of the frame protocol. */
3325
+ const WS_VERSION_HEADER = "x-webrun-ws-version";
3326
+ /**
3327
+ * The `GET` a handler sees for `new WebSocket(url, protocols)`. A `ws:` or
3328
+ * `wss:` url is given as `http:` or `https:`, as a server sees it.
3329
+ */
3330
+ function newWebSocketUpgradeRequest(url, { protocols = [], headers } = {}) {
3331
+ const httpUrl = new URL(`${url}`);
3332
+ if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
3333
+ else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
3334
+ const all = new Headers(headers);
3335
+ all.set("upgrade", "websocket");
3336
+ all.set("connection", "Upgrade");
3337
+ all.set("sec-websocket-version", "13");
3338
+ if (!all.has("sec-websocket-key")) all.set("sec-websocket-key", randomKey());
3339
+ if (protocols.length > 0) all.set("sec-websocket-protocol", protocols.join(", "));
3340
+ if (!all.has("x-webrun-ws-version")) all.set(WS_VERSION_HEADER, `2`);
3341
+ return withHeaders(new Request(httpUrl, {
3342
+ method: "GET",
3343
+ headers: all
3344
+ }), all);
3345
+ }
3346
+ /**
3347
+ * Re-attaches `headers` to `request` as its own `headers` property, keeping
3348
+ * the forbidden ones a browser dropped. Returns `request`.
3349
+ */
3350
+ function withHeaders(request, headers) {
3351
+ Object.defineProperty(request, "headers", {
3352
+ value: headers,
3353
+ configurable: true
3354
+ });
3355
+ return request;
3356
+ }
3357
+ /** Whether `request` asks for a WebSocket. */
3358
+ function isWebSocketUpgrade(request) {
3359
+ return request.headers.get("upgrade")?.toLowerCase() === "websocket";
3360
+ }
3361
+ /** The subprotocols `request` asks for, in order of preference. */
3362
+ function requestedProtocols(request) {
3363
+ const header = request.headers.get("sec-websocket-protocol");
3364
+ if (!header) return [];
3365
+ return header.split(",").map((protocol) => protocol.trim()).filter((protocol) => protocol !== "");
3366
+ }
3367
+ /**
3368
+ * Where a response from `upgradeWebSocket` keeps its port. A registered
3369
+ * symbol, not a module-level `WeakMap`: the handler and the host that takes
3370
+ * the port often run different bundles of this package (a page's adapter from
3371
+ * `dist/sw.js`, its handler code importing `dist/worker.js`), and each bundle
3372
+ * has its own copy of every module.
3373
+ */
3374
+ const UPGRADE = Symbol.for("webrun-http-browser:websocket-upgrade");
3375
+ /**
3376
+ * Accepts a WebSocket upgrade in a handler:
3377
+ *
3378
+ * ```ts
3379
+ * if (isWebSocketUpgrade(request)) {
3380
+ * const { socket, response } = upgradeWebSocket(request, { protocol: "v1" });
3381
+ * socket.accept();
3382
+ * socket.addEventListener("message", (event) => socket.send(event.data));
3383
+ * return response;
3384
+ * }
3385
+ * ```
3386
+ *
3387
+ * The host takes the client's port from the response with `takePort` and
3388
+ * hands it to the caller.
3389
+ */
3390
+ function upgradeWebSocket(request, options = {}) {
3391
+ const protocol = options.protocol ?? "";
3392
+ const channel = new MessageChannel();
3393
+ const socket = new ServerWebSocket(channel.port1, {
3394
+ ...options,
3395
+ url: request.url,
3396
+ protocol
3397
+ });
3398
+ const response = new Response(null, {
3399
+ status: 200,
3400
+ headers: protocol ? { "sec-websocket-protocol": protocol } : {}
3401
+ });
3402
+ Object.defineProperties(response, {
3403
+ status: {
3404
+ value: 101,
3405
+ configurable: true
3406
+ },
3407
+ statusText: {
3408
+ value: "Switching Protocols",
3409
+ configurable: true
3410
+ },
3411
+ webSocket: {
3412
+ value: socket,
3413
+ configurable: true
3414
+ },
3415
+ [UPGRADE]: {
3416
+ value: {
3417
+ port: channel.port2,
3418
+ protocol
3419
+ },
3420
+ configurable: true,
3421
+ writable: true
3422
+ }
3423
+ });
3424
+ return {
3425
+ socket,
3426
+ response
3427
+ };
3428
+ }
3429
+ /**
3430
+ * The port to hand to the caller, for a response from `upgradeWebSocket`.
3431
+ * Taken once: a second call returns `undefined`.
3432
+ */
3433
+ function takePort(response) {
3434
+ return takeUpgrade(response)?.port;
3435
+ }
3436
+ /** `takePort`, with the subprotocol the server picked. */
3437
+ function takeUpgrade(response) {
3438
+ const holder = response;
3439
+ const upgrade = holder[UPGRADE];
3440
+ if (upgrade) holder[UPGRADE] = void 0;
3441
+ return upgrade;
3442
+ }
3443
+ /**
3444
+ * Runs an upgrade through `handler`, as a host does when a caller asks for a
3445
+ * socket: builds the upgrade request, calls the handler, and either takes the
3446
+ * port of a `101` or reports the refusal. A subprotocol the caller did not ask
3447
+ * for is a refusal, as in the standard.
3448
+ */
3449
+ async function serveWebSocketUpgrade(handler, { url, protocols = [], headers }) {
3450
+ let response;
3451
+ try {
3452
+ response = await handler(newWebSocketUpgradeRequest(url, {
3453
+ protocols,
3454
+ headers
3455
+ }));
3456
+ } catch (error) {
3457
+ return {
3458
+ ok: false,
3459
+ status: 500,
3460
+ message: errorMessage(error)
3461
+ };
3462
+ }
3463
+ const upgrade = takeUpgrade(response);
3464
+ if (!upgrade || response.status !== 101) {
3465
+ upgrade?.port.close();
3466
+ try {
3467
+ await response.body?.cancel();
3468
+ } catch {}
3469
+ return {
3470
+ ok: false,
3471
+ status: response.status,
3472
+ message: `The server refused the upgrade: ${response.status} ${response.statusText}`.trim()
3473
+ };
3474
+ }
3475
+ if (upgrade.protocol !== "" && !protocols.includes(upgrade.protocol)) {
3476
+ upgrade.port.close();
3477
+ return {
3478
+ ok: false,
3479
+ status: 400,
3480
+ message: `The server picked the subprotocol '${upgrade.protocol}', which was not requested.`
3481
+ };
3482
+ }
3483
+ return {
3484
+ ok: true,
3485
+ port: upgrade.port,
3486
+ protocol: upgrade.protocol
3487
+ };
3488
+ }
3489
+ function randomKey() {
3490
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
3491
+ crypto.getRandomValues(bytes);
3492
+ return btoa(String.fromCharCode(...bytes));
3493
+ }
3494
+ //#endregion
3495
+ //#region src/sw/handler-endpoint.ts
3496
+ /** The message calls through a lost ServiceWorker fail with. */
3497
+ const ROUTER_LOST_MESSAGE = "The ServiceWorker was lost while this call was in flight";
3498
+ /**
3499
+ * The handler's end of its links to the ServiceWorker, the same in a page and
3500
+ * in a Dedicated Worker.
3501
+ *
3502
+ * - Serves `handler` on each link's `down` port, and answers WebSocket
3503
+ * upgrades arriving on its `ctl` port by running them through `handler`.
3504
+ * - Sends requests through the router on `up` (`fetch`) and opens sockets to
3505
+ * other handlers over `ctl` (`connectWebSocket`).
3506
+ * - Watches the ServiceWorker's router lock. When the ServiceWorker dies, the
3507
+ * links made for it are dropped: calls in flight on them fail with
3508
+ * `LinkLostError` ("may or may not have been applied") instead of hanging,
3509
+ * and new calls wait for a link, asking for one (`requestRelink`) every
3510
+ * `relinkRetryMs` until it comes.
3511
+ * - While calls are in flight, calls `keepAlive` every `keepAliveMs`: port
3512
+ * messages are not events, so without it the browser may stop the
3513
+ * ServiceWorker in the middle of a long call.
3514
+ */
3515
+ var HandlerEndpoint = class {
3516
+ handler;
3517
+ options;
3518
+ _links = /* @__PURE__ */ new Set();
3519
+ _waiters = [];
3520
+ _sockets = new PortRendezvous("o");
3521
+ _keepAliveTimer;
3522
+ _closed = false;
3523
+ constructor(handler, options = {}) {
3524
+ this.handler = handler;
3525
+ this.options = options;
3526
+ }
3527
+ /** Whether any link is live. */
3528
+ get linked() {
3529
+ return this._links.size > 0;
3530
+ }
3531
+ /** Installs a fresh link made for the router holding `routerLock`. */
3532
+ async link(key, ports, routerLock) {
3533
+ if (this._closed) {
3534
+ for (const port of Object.values(ports)) port?.close();
3535
+ return;
3536
+ }
3537
+ const closeDown = await serveHttpLink(ports.down, this.handler, this.options);
3538
+ const up = ports.up ? await connectHttpLink(ports.up, this.options) : void 0;
3539
+ const link = {
3540
+ key,
3541
+ routerLock,
3542
+ ctl: ports.ctl,
3543
+ up,
3544
+ closeDown,
3545
+ stopWatch: () => {}
3546
+ };
3547
+ if (ports.ctl) ports.ctl.onmessage = (event) => this._onControl(link, event.data);
3548
+ if (routerLock) link.stopWatch = watchLock(routerLock, () => this._routerLost(routerLock));
3549
+ for (const old of [...this._links]) {
3550
+ if (old.key !== key) continue;
3551
+ if (old.routerLock !== routerLock) this._drop(old, new LinkLostError(ROUTER_LOST_MESSAGE));
3552
+ else if (!old.superseded) {
3553
+ old.superseded = true;
3554
+ setTimeout(() => void this._drop(old), this.options.supersededLinkMs ?? 3e4);
3555
+ }
3556
+ }
3557
+ this._links.add(link);
3558
+ for (const wake of this._waiters.splice(0)) wake();
3559
+ }
3560
+ /** Drops the links attached under `key` (all of them without a key). */
3561
+ async unlink(key, reason) {
3562
+ const dropped = [...this._links].filter((link) => key === void 0 || link.key === key);
3563
+ await Promise.all(dropped.map((link) => this._drop(link, reason)));
3564
+ }
3565
+ /** The routers this endpoint has live links for. */
3566
+ routerLocks() {
3567
+ return new Set([...this._links].map((link) => link.routerLock));
3568
+ }
3569
+ /**
3570
+ * Sends `request` through the ServiceWorker's router, as if the browser had
3571
+ * fetched it: it reaches the handler its url routes to.
3572
+ */
3573
+ async fetch(request) {
3574
+ const link = await this._linkWith("up");
3575
+ this._startKeepAlive();
3576
+ return await link.up.send(request);
3577
+ }
3578
+ /** Opens a socket to the handler `url` routes to, through the ServiceWorker. */
3579
+ async connectWebSocket(url, protocols = []) {
3580
+ const link = await this._linkWith("ctl");
3581
+ const id = this._sockets.newId();
3582
+ const answer = this._sockets.wait(id, this.options.wsConnectTimeoutMs ?? 15e3, `the socket request for ${url}`);
3583
+ link.ctl?.postMessage({
3584
+ t: "ws-open",
3585
+ id,
3586
+ url,
3587
+ protocols
3588
+ });
3589
+ return await answer;
3590
+ }
3591
+ async close() {
3592
+ this._closed = true;
3593
+ if (this._keepAliveTimer) clearInterval(this._keepAliveTimer);
3594
+ await this.unlink(void 0, new LinkLostError("The handler was closed"));
3595
+ for (const wake of this._waiters.splice(0)) wake();
3596
+ }
3597
+ async _drop(link, reason) {
3598
+ if (!this._links.delete(link)) return;
3599
+ link.stopWatch();
3600
+ await link.up?.close(reason);
3601
+ try {
3602
+ await link.closeDown();
3603
+ } catch {}
3604
+ if (link.ctl) {
3605
+ link.ctl.onmessage = null;
3606
+ link.ctl.close();
3607
+ }
3608
+ }
3609
+ _routerLost(routerLock) {
3610
+ const reason = new LinkLostError(ROUTER_LOST_MESSAGE);
3611
+ for (const link of [...this._links]) if (link.routerLock === routerLock) this._drop(link, reason);
3612
+ this._sockets.failAll(reason);
3613
+ }
3614
+ /** A live link with `port`, waiting (and asking) for one when there is none. */
3615
+ async _linkWith(port) {
3616
+ const find = () => [...this._links].filter((link) => !link.superseded).reverse().find((link) => port === "up" ? link.up && !link.up.closed : link.ctl);
3617
+ const found = find();
3618
+ if (found) return found;
3619
+ const retryMs = this.options.relinkRetryMs ?? 2e3;
3620
+ const deadline = Date.now() + (this.options.relinkTimeoutMs ?? 3e4);
3621
+ while (!this._closed) {
3622
+ this.options.requestRelink?.();
3623
+ await new Promise((resolve) => {
3624
+ const timer = setTimeout(resolve, Math.max(0, Math.min(retryMs, deadline - Date.now())));
3625
+ this._waiters.push(() => {
3626
+ clearTimeout(timer);
3627
+ resolve();
3628
+ });
3629
+ });
3630
+ const link = find();
3631
+ if (link) return link;
3632
+ if (Date.now() >= deadline) break;
3633
+ }
3634
+ throw new LinkLostError("No link to the ServiceWorker could be made for this call");
3635
+ }
3636
+ _startKeepAlive() {
3637
+ if (this._keepAliveTimer || !this.options.keepAlive) return;
3638
+ this._keepAliveTimer = setInterval(() => {
3639
+ if ([...this._links].reduce((sum, link) => sum + (link.up?.inflight ?? 0), 0) === 0) {
3640
+ clearInterval(this._keepAliveTimer);
3641
+ this._keepAliveTimer = void 0;
3642
+ return;
3643
+ }
3644
+ this.options.keepAlive?.();
3645
+ }, this.options.keepAliveMs ?? 2e4);
3646
+ }
3647
+ _onControl(link, message) {
3648
+ if (!message || typeof message !== "object") return;
3649
+ switch (message.t) {
3650
+ case "ws-connect":
3651
+ this._acceptSocket(link, message);
3652
+ return;
3653
+ case "ws-opened":
3654
+ if (!this._sockets.settle(message.id, {
3655
+ port: message.port,
3656
+ protocol: message.protocol
3657
+ })) message.port.close();
3658
+ return;
3659
+ case "ws-failed":
3660
+ this._sockets.fail(message.id, new Error(message.message));
3661
+ return;
3662
+ }
3663
+ }
3664
+ async _acceptSocket(link, { id, url, protocols, headers }) {
3665
+ const ctl = link.ctl;
3666
+ if (!ctl) return;
3667
+ try {
3668
+ const result = await serveWebSocketUpgrade(this.handler, {
3669
+ url,
3670
+ protocols,
3671
+ headers
3672
+ });
3673
+ if (result.ok) ctl.postMessage({
3674
+ t: "ws-accept",
3675
+ id,
3676
+ protocol: result.protocol,
3677
+ port: result.port
3678
+ }, [result.port]);
3679
+ else ctl.postMessage({
3680
+ t: "ws-refuse",
3681
+ id,
3682
+ status: result.status,
3683
+ message: result.message
3684
+ });
3685
+ } catch (error) {
3686
+ ctl.postMessage({
3687
+ t: "ws-refuse",
3688
+ id,
3689
+ status: 500,
3690
+ message: errorMessage(error)
3691
+ });
3692
+ }
3693
+ }
3694
+ };
3695
+ //#endregion
3696
+ //#region src/sw/worker-service.ts
3697
+ /**
3698
+ * Serves `handler` from a Dedicated Worker, on the links the page attaches
3699
+ * with `adapter.attachWorker(worker)`:
3700
+ *
3701
+ * ```ts
3702
+ * // worker.ts
3703
+ * const service = serveHttpInWorker(async (request) => new Response("hi"));
3704
+ * ```
3705
+ *
3706
+ * The worker holds an owner lock while it lives, so the ServiceWorker notices
3707
+ * at once when it is terminated. It watches the ServiceWorker's router lock,
3708
+ * and asks its page to attach it again when its links died and a call waits.
3709
+ * While calls through the router are in flight it asks its page every 20 s to
3710
+ * keep the ServiceWorker awake — only a message to the ServiceWorker object
3711
+ * counts as an event, and a worker cannot post one.
3712
+ */
3713
+ function serveHttpInWorker(handler, options = {}) {
3714
+ const scope = options.scope ?? globalThis;
3715
+ const ownerLock = newLockName("webrun-http-owner");
3716
+ const held = holdLock(ownerLock);
3717
+ const controls = /* @__PURE__ */ new Set();
3718
+ const tellPages = (message) => {
3719
+ for (const control of controls) control.postMessage(message);
3720
+ };
3721
+ const endpoint = new HandlerEndpoint(handler, {
3722
+ ...options,
3723
+ requestRelink: () => tellPages({ type: "relink" }),
3724
+ keepAlive: () => tellPages({ type: "keepalive" })
3725
+ });
3726
+ const onMessage = (event) => {
3727
+ const { data, ports } = event;
3728
+ if (data?.type !== "webrun-http:worker-hello") return;
3729
+ const control = ports?.[0];
3730
+ if (!control) return;
3731
+ controls.add(control);
3732
+ control.onmessage = (message) => {
3733
+ const msg = message.data;
3734
+ if (msg?.type === "link") {
3735
+ const [down, ctl, up] = message.ports;
3736
+ if (down) endpoint.link(msg.key, {
3737
+ down,
3738
+ ctl,
3739
+ up
3740
+ }, msg.routerLock);
3741
+ } else if (msg?.type === "unlink") endpoint.unlink(msg.key);
3742
+ };
3743
+ held.then(() => control.postMessage({
3744
+ type: "ready",
3745
+ ownerLock: locksAvailable() ? ownerLock : void 0
3746
+ }));
3747
+ };
3748
+ scope.addEventListener("message", onMessage);
3749
+ const baseUrl = () => globalThis.location?.href;
3750
+ const connectWebSocket = (url, protocols = []) => {
3751
+ const httpUrl = new URL(`${url}`, baseUrl());
3752
+ if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
3753
+ else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
3754
+ return endpoint.connectWebSocket(`${httpUrl}`, protocols);
3755
+ };
3756
+ let WebSocketClass;
3757
+ return {
3758
+ fetch(input, init) {
3759
+ const request = input instanceof Request && init === void 0 ? input : new Request(input instanceof Request ? input : new URL(`${input}`, baseUrl()), init);
3760
+ return endpoint.fetch(request);
3761
+ },
3762
+ connectWebSocket,
3763
+ get WebSocket() {
3764
+ WebSocketClass ??= createWebSocketClass(connectWebSocket, options.webSocket);
3765
+ return WebSocketClass;
3766
+ },
3767
+ get linked() {
3768
+ return endpoint.linked;
3769
+ },
3770
+ async close() {
3771
+ scope.removeEventListener("message", onMessage);
3772
+ await endpoint.close();
3773
+ for (const control of controls) control.close();
3774
+ controls.clear();
3775
+ (await held)();
3776
+ }
3777
+ };
3778
+ }
3779
+ //#endregion
3780
+ export { DEFAULT_CLOSE_TIMEOUT_MS, DEFAULT_HEARTBEAT_MS, HTTP_LINK_PROTOCOL, LinkLostError, ServerWebSocket, WS_PORT_PROTOCOL_VERSION, WS_VERSION_HEADER, WsCloseEvent, connectHttpLink, createWebSocketClass, isWebSocketUpgrade, newWebSocketUpgradeRequest, requestedProtocols, serveHttpInWorker, serveHttpLink, serveWebSocketUpgrade, takePort, takeUpgrade, trackedLink, upgradeWebSocket, withHeaders };