@statewalker/webrun-http-browser 0.3.3 → 0.4.2

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 (93) hide show
  1. package/README.md +406 -51
  2. package/demo/demo-1.html +109 -194
  3. package/demo/demo-2.html +118 -299
  4. package/dist/core/data-calls.d.ts +5 -0
  5. package/dist/core/data-calls.d.ts.map +1 -0
  6. package/dist/core/data-channels.d.ts +17 -0
  7. package/dist/core/data-channels.d.ts.map +1 -0
  8. package/dist/core/index.d.ts +6 -0
  9. package/dist/core/index.d.ts.map +1 -0
  10. package/dist/core/message-target.d.ts +2 -0
  11. package/dist/core/message-target.d.ts.map +1 -0
  12. package/dist/core/registry.d.ts +18 -0
  13. package/dist/core/registry.d.ts.map +1 -0
  14. package/dist/http/http-send-recieve.d.ts +36 -0
  15. package/dist/http/http-send-recieve.d.ts.map +1 -0
  16. package/dist/http/index.d.ts +4 -0
  17. package/dist/http/index.d.ts.map +1 -0
  18. package/dist/index.d.ts +4 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +2670 -807
  21. package/dist/relay/index-sw.d.ts +7 -0
  22. package/dist/relay/index-sw.d.ts.map +1 -0
  23. package/dist/relay/index.d.ts +69 -0
  24. package/dist/relay/index.d.ts.map +1 -0
  25. package/dist/relay/split-service-url.d.ts +13 -0
  26. package/dist/relay/split-service-url.d.ts.map +1 -0
  27. package/dist/relay-sw.d.ts +2 -0
  28. package/dist/relay-sw.d.ts.map +1 -0
  29. package/dist/relay-sw.js +1660 -0
  30. package/dist/sw/http-sw-dispatcher.d.ts +28 -0
  31. package/dist/sw/http-sw-dispatcher.d.ts.map +1 -0
  32. package/dist/sw/index.d.ts +3 -0
  33. package/dist/sw/index.d.ts.map +1 -0
  34. package/dist/sw/sw-dispatcher.d.ts +74 -0
  35. package/dist/sw/sw-dispatcher.d.ts.map +1 -0
  36. package/dist/sw-worker.d.ts +2 -0
  37. package/dist/sw-worker.d.ts.map +1 -0
  38. package/dist/sw-worker.js +1597 -0
  39. package/dist/sw.d.ts +2 -0
  40. package/dist/sw.d.ts.map +1 -0
  41. package/dist/sw.js +1883 -0
  42. package/package.json +51 -37
  43. package/public/index.html +61 -97
  44. package/public/index.js +7 -4
  45. package/public/sw-worker.js +4 -0
  46. package/public-relay/heartbeat.js +4 -3
  47. package/public-relay/relay-sw.js +4 -6
  48. package/public-relay/relay.html +16 -11
  49. package/src/core/data-calls.ts +46 -0
  50. package/src/core/data-channels.ts +262 -0
  51. package/src/core/index.ts +9 -0
  52. package/src/core/message-target.ts +8 -0
  53. package/src/core/registry.ts +54 -0
  54. package/src/http/http-send-recieve.ts +94 -0
  55. package/src/http/index.ts +7 -0
  56. package/src/index.ts +3 -0
  57. package/src/relay/index-sw.ts +145 -0
  58. package/src/relay/index.ts +261 -0
  59. package/src/relay/split-service-url.ts +30 -0
  60. package/src/relay-sw.ts +7 -0
  61. package/src/sw/http-sw-dispatcher.ts +122 -0
  62. package/src/sw/index.ts +2 -0
  63. package/src/sw/sw-dispatcher.ts +332 -0
  64. package/src/sw-worker.ts +7 -0
  65. package/src/sw.ts +1 -0
  66. package/CHANGELOG.md +0 -1
  67. package/LICENSE +0 -21
  68. package/demo/demo-2 copy.html +0 -598
  69. package/demo/demo-3.html +0 -167
  70. package/dist/index-sw-umd.js +0 -798
  71. package/dist/index-sw-umd.min.js +0 -2
  72. package/dist/index-sw.js +0 -791
  73. package/dist/index-sw.min.js +0 -2
  74. package/dist/index-umd.js +0 -853
  75. package/dist/index-umd.min.js +0 -2
  76. package/dist/index.min.js +0 -2
  77. package/index.js +0 -1
  78. package/src/core/data-calls.js +0 -36
  79. package/src/core/data-channels.js +0 -192
  80. package/src/core/data-send-recieve.js +0 -28
  81. package/src/core/errors.js +0 -13
  82. package/src/core/index.js +0 -4
  83. package/src/http/HttpError.js +0 -59
  84. package/src/http/http-send-recieve.js +0 -40
  85. package/src/http/http-stubs.js +0 -135
  86. package/src/http/index.js +0 -3
  87. package/src/http/readable-streams.js +0 -33
  88. package/src/index.js +0 -7
  89. package/src/relay/index-sw.js +0 -216
  90. package/src/relay/index.js +0 -263
  91. package/src/relay/splitServiceUrl.js +0 -24
  92. package/src/sw/http-sw-dispatcher.js +0 -128
  93. package/src/sw/sw-dispatcher.js +0 -264
@@ -0,0 +1,1660 @@
1
+ (function() {
2
+ //#region ../webrun-streams/dist/index.js
3
+ function serializeError(error) {
4
+ if (error instanceof Error) {
5
+ const out = {
6
+ message: error.message,
7
+ stack: error.stack
8
+ };
9
+ const bag = error;
10
+ for (const key of Object.keys(bag)) out[key] = bag[key];
11
+ return out;
12
+ }
13
+ if (typeof error === "object" && error !== null) {
14
+ const bag = error;
15
+ return {
16
+ message: String(bag.message ?? error),
17
+ ...bag
18
+ };
19
+ }
20
+ return { message: String(error) };
21
+ }
22
+ function deserializeError(error) {
23
+ const payload = typeof error === "string" ? { message: error } : error;
24
+ return Object.assign(new Error(payload.message), payload);
25
+ }
26
+ new TextEncoder();
27
+ new TextDecoder();
28
+ /**
29
+ * The newAsyncGenerator function creates async generators from callback-based initialization
30
+ * functions, providing a bridge between imperative event handling and declarative async
31
+ * iteration patterns.
32
+ *
33
+ * The initialization function receives two callback functions that control the generator's
34
+ * behavior. The `next` function yields values to consumers, while the `done` function
35
+ * signals completion or error conditions. The initialization function can return a cleanup
36
+ * function that will be called when the generator is closed or an error occurs.
37
+ *
38
+ * The generator manages an internal queue of values and completion signals, ensuring that
39
+ * producers can yield values without overwhelming consumers. Proper backpressure is implemented
40
+ * by having the `next` and `done` functions return promises that resolve only after the
41
+ * consumer has processed the values. This prevents memory leaks and ensures that producers
42
+ * are aware of whether their values were successfully handled.
43
+ * The generator also handles cleanup by draining any remaining items in the queue and notifying
44
+ * producers that their values were not processed if the generator is closed early. This ensures
45
+ * that resources are properly managed and that no memory leaks occur.
46
+ *
47
+ * Example usage:
48
+ * ```typescript
49
+ * const asyncGen = newAsyncGenerator<number>((next, done) => {
50
+ * let count = 0;
51
+ * const interval = setInterval(() => {
52
+ * if (count < 5) {
53
+ * next(count++);
54
+ * } else {
55
+ * done();
56
+ * clearInterval(interval);
57
+ * }
58
+ * }, 1000);
59
+ * return () => clearInterval(interval); // Cleanup function
60
+ * });
61
+ * (async () => {
62
+ * for await (const num of asyncGen) {
63
+ * console.log(num); // Logs numbers 0 to 4 at 1 second intervals
64
+ * }
65
+ * console.log("Completed");
66
+ * })();
67
+ * ```
68
+ * @template T The type of values yielded by the generator
69
+ * @template E The type of errors that can be thrown; defaults to Error
70
+ * @param init Initialization function that sets up the generator behavior with next/done callbacks;
71
+ * The first parameter - `next` function - is used to yield values to consumers;
72
+ * It returns a Promise<boolean> indicating whether the value was successfully handled;
73
+ * The second parameter - `done` function - is used to signal completion or error;
74
+ * It returns a Promise<boolean> indicating whether the completion was successfully handled;
75
+ * The initialization function can optionally return a cleanup function that will be called
76
+ * when the generator is closed or an error occurs;
77
+ * @param skipValues If true, only the most recent value is kept in the queue,
78
+ * skipping intermediate values (not consumed values are considered skipped);
79
+ * This is useful for scenarios where only the latest value matters, such as UI updates.
80
+ * Defaults to false, meaning all values are queued and processed in order.
81
+ * @returns AsyncGenerator that properly manages backpressure and resource cleanup
82
+ */
83
+ async function* newAsyncGenerator(init, skipValues = false) {
84
+ let head;
85
+ let tail;
86
+ /** Flag to prevent new values from being queued after generator closes */
87
+ let closed = false;
88
+ /** Wake-up function to notify the generator loop of new items */
89
+ let wakeUp;
90
+ /**
91
+ * Drains the internal queue, notifying all pending producers that their values
92
+ * were not processed due to generator closure. This prevents memory leaks and
93
+ * ensures proper backpressure signaling.
94
+ */
95
+ const drainQueue = () => {
96
+ for (; head; head = head.next) {
97
+ closed = closed || head.done;
98
+ head.resolve(false);
99
+ }
100
+ tail = void 0;
101
+ };
102
+ /**
103
+ * Enqueues a value or completion signal with a promise that resolves when the item
104
+ * is processed. This enables backpressure by allowing producers to know when their
105
+ * values have been consumed.
106
+ */
107
+ const enqueue = (params) => {
108
+ if (skipValues) drainQueue();
109
+ return !closed ? new Promise((resolve) => {
110
+ const next = {
111
+ ...params,
112
+ next: void 0,
113
+ resolve
114
+ };
115
+ if (tail) tail.next = next;
116
+ tail = next;
117
+ if (!head) head = tail;
118
+ wakeUp?.();
119
+ }) : Promise.resolve(false);
120
+ };
121
+ /**
122
+ * Producer function to yield a value to consumers. Returns a promise that resolves
123
+ * to true if the value was successfully processed, false if the generator is closed
124
+ * or the value was skipped due to backpressure.
125
+ */
126
+ const next = (value) => enqueue({
127
+ done: false,
128
+ value
129
+ });
130
+ /**
131
+ * Producer function to signal completion or error. Optional error parameter will
132
+ * cause the generator to throw that error to consumers.
133
+ */
134
+ const done = (error) => enqueue({
135
+ done: true,
136
+ error
137
+ });
138
+ const unsubscribe = init(next, done);
139
+ try {
140
+ while (!closed) {
141
+ if (!head) {
142
+ await new Promise((resolve) => {
143
+ wakeUp = resolve;
144
+ }).then(() => {
145
+ wakeUp = void 0;
146
+ });
147
+ continue;
148
+ }
149
+ const slot = head;
150
+ head = head.next;
151
+ if (tail === slot) tail = head;
152
+ try {
153
+ if (slot.done) {
154
+ closed = true;
155
+ if (slot.error !== void 0) throw slot.error;
156
+ break;
157
+ }
158
+ yield slot.value;
159
+ } finally {
160
+ slot.resolve(true);
161
+ }
162
+ }
163
+ } finally {
164
+ /**
165
+ * Cleanup phase - ensures proper resource management and notification of any
166
+ * remaining producers. This runs whether the generator completes normally,
167
+ * encounters an error, or is closed early by the consumer.
168
+ */
169
+ closed = true;
170
+ wakeUp?.();
171
+ if (typeof unsubscribe === "function") await unsubscribe();
172
+ /**
173
+ * Drain any remaining items in the queue and notify their producers that
174
+ * the values were not processed. This prevents memory leaks and ensures
175
+ * proper backpressure signaling.
176
+ */
177
+ drainQueue();
178
+ }
179
+ }
180
+ new TextEncoder();
181
+ /**
182
+ * The iterator ↔ `ReadableStream` boundary.
183
+ *
184
+ * Both adapters must carry CANCELLATION, not just data: a response body leaves
185
+ * a handler as a `ReadableStream`, crosses a transport as an iterator, and
186
+ * becomes a `ReadableStream` again at the caller — so when the caller walks
187
+ * away, the only path back to the handler's producer runs through both of
188
+ * these functions. Teardown that stops at an adapter leaves a producer running
189
+ * for ever.
190
+ */
191
+ function toReadableStream(it) {
192
+ return new ReadableStream({
193
+ /**
194
+ * One chunk per pull. An earlier version drained the whole iterator inside
195
+ * a single `pull`, which defeated the stream's own backpressure (every
196
+ * chunk was enqueued as fast as the producer could make them, however slow
197
+ * the reader was) and left no point between chunks at which a cancellation
198
+ * could take effect.
199
+ */
200
+ async pull(controller) {
201
+ try {
202
+ const slot = await it.next();
203
+ if (!slot || slot.done) {
204
+ controller.close();
205
+ return;
206
+ }
207
+ controller.enqueue(await slot.value);
208
+ } catch (error) {
209
+ controller.error(error);
210
+ }
211
+ },
212
+ /**
213
+ * Release the source. NOT awaited: `.return()` on an async generator that
214
+ * is parked awaiting its own source is queued behind that pending
215
+ * `next()`, so awaiting it here would hang `reader.cancel()` on exactly
216
+ * the producers that most need cancelling.
217
+ */
218
+ cancel(reason) {
219
+ Promise.resolve(it.return?.(reason)).catch(() => {});
220
+ }
221
+ });
222
+ }
223
+ async function* fromReadableStream(stream) {
224
+ const reader = stream.getReader();
225
+ let drained = false;
226
+ try {
227
+ while (true) {
228
+ const { done, value } = await reader.read();
229
+ if (done) {
230
+ drained = true;
231
+ break;
232
+ }
233
+ if (value !== void 0) yield value;
234
+ }
235
+ } finally {
236
+ if (drained) reader.releaseLock();
237
+ else await reader.cancel().catch(() => {});
238
+ }
239
+ }
240
+ /**
241
+ * Inverse of {@link sendIterator}: turns a sequence of `{done, value, error}`
242
+ * chunks (delivered to the supplied callback by `installer`) into an async
243
+ * generator.
244
+ *
245
+ * The `installer` is given a `deliver` function. It should call `deliver`
246
+ * once for each incoming chunk and may return a cleanup callback that
247
+ * runs when the consumer stops iterating.
248
+ */
249
+ function recieveIterator(installer) {
250
+ return newAsyncGenerator((next, done) => {
251
+ const cleanup = installer(async (chunk = { done: true }) => {
252
+ const { done: isDone = true, value, error } = chunk;
253
+ if (error) return await done(error);
254
+ if (isDone) return await done();
255
+ return await next(value);
256
+ });
257
+ if (cleanup) return async () => {
258
+ await cleanup();
259
+ };
260
+ });
261
+ }
262
+ /**
263
+ * Drain an async iterator into a sink that consumes one chunk at a time.
264
+ *
265
+ * Each yielded value becomes `{ done: false, value }`. Completion emits
266
+ * `{ done: true }`. If the iterator throws, the error is caught and the
267
+ * final `done` chunk carries it so the peer can rethrow on its side.
268
+ */
269
+ async function sendIterator(send, it) {
270
+ let error;
271
+ try {
272
+ for await (const value of it) await send({
273
+ done: false,
274
+ value
275
+ });
276
+ } catch (err) {
277
+ error = err;
278
+ } finally {
279
+ await send({
280
+ done: true,
281
+ error
282
+ });
283
+ }
284
+ }
285
+ //#endregion
286
+ //#region ../webrun-http-streams/dist/index.js
287
+ const CR = 13;
288
+ const LF = 10;
289
+ const EMPTY = /* @__PURE__ */ new Uint8Array(0);
290
+ var ByteStreamError = class extends Error {
291
+ name = "ByteStreamError";
292
+ };
293
+ function toAsyncIterator(input) {
294
+ const asyncIter = input[Symbol.asyncIterator];
295
+ if (asyncIter) return asyncIter.call(input);
296
+ const syncIter = input[Symbol.iterator]();
297
+ return { next() {
298
+ return Promise.resolve(syncIter.next());
299
+ } };
300
+ }
301
+ /**
302
+ * Discard an iterable we are contractually forbidden from consuming — a body
303
+ * skipped for HEAD/204, or one abandoned because the peer reported an error.
304
+ *
305
+ * The `.next()` is not optional: `.return()` on a generator still in suspended
306
+ * start is a no-op, so the body never runs and its `try/finally` never unwinds.
307
+ * Without it a wrapped ReadableStream or socket is never cancelled.
308
+ */
309
+ async function discard(source) {
310
+ if (source === void 0) return;
311
+ const it = toAsyncIterator(source);
312
+ try {
313
+ await it.next();
314
+ await it.return?.();
315
+ } catch {}
316
+ }
317
+ function concatChunks(parts, totalLen) {
318
+ if (parts.length === 1) {
319
+ const only = parts[0];
320
+ if (only !== void 0) return only;
321
+ }
322
+ const out = new Uint8Array(totalLen);
323
+ let off = 0;
324
+ for (const p of parts) {
325
+ out.set(p, off);
326
+ off += p.byteLength;
327
+ }
328
+ return out;
329
+ }
330
+ /**
331
+ * Pull-based reader over a byte source. Holds at most one pending buffer, and
332
+ * hands out `subarray` views rather than copies — a body never passes through
333
+ * an allocation here.
334
+ */
335
+ var ByteReader = class {
336
+ #iter;
337
+ #buf = EMPTY;
338
+ #done = false;
339
+ constructor(input) {
340
+ this.#iter = toAsyncIterator(input);
341
+ }
342
+ /** Bytes already pulled from the source but not yet consumed. */
343
+ bufferedLength() {
344
+ return this.#buf.byteLength;
345
+ }
346
+ /** Pull one more non-empty chunk. Returns false at end of stream. */
347
+ async #pull() {
348
+ if (this.#done) return false;
349
+ while (true) {
350
+ const next = await this.#iter.next();
351
+ if (next.done) {
352
+ this.#done = true;
353
+ return false;
354
+ }
355
+ const chunk = next.value;
356
+ if (chunk.byteLength === 0) continue;
357
+ this.#buf = this.#buf.byteLength === 0 ? chunk : concatChunks([this.#buf, chunk], this.#buf.byteLength + chunk.byteLength);
358
+ return true;
359
+ }
360
+ }
361
+ async peekByte() {
362
+ while (this.#buf.byteLength === 0) if (!await this.#pull()) return void 0;
363
+ return this.#buf[0];
364
+ }
365
+ /** Up to `max` bytes. `undefined` means end of stream. */
366
+ async readSome(max) {
367
+ while (this.#buf.byteLength === 0) if (!await this.#pull()) return void 0;
368
+ const take = Math.min(max, this.#buf.byteLength);
369
+ const out = this.#buf.subarray(0, take);
370
+ this.#buf = this.#buf.subarray(take);
371
+ return out;
372
+ }
373
+ /**
374
+ * One CRLF-terminated line, without the CRLF. A bare LF is rejected: real
375
+ * peers always send CRLF, and tolerating a bare LF is precisely the lenience
376
+ * that lets request smuggling through a proxy pair.
377
+ *
378
+ * The `maxBytes` bound is best-effort: it only rejects a line if the check
379
+ * happens to run before the line is fully buffered. A line already sitting in
380
+ * the buffer bypasses the check. Callers needing a hard per-line limit or
381
+ * aggregate bounds must keep their own running total.
382
+ */
383
+ async readLine(maxBytes) {
384
+ let searched = 0;
385
+ while (true) {
386
+ const idx = this.#buf.indexOf(LF, searched);
387
+ if (idx !== -1) {
388
+ if (idx === 0 || this.#buf[idx - 1] !== CR) throw new ByteStreamError("bare LF line terminator; CRLF required");
389
+ const line = this.#buf.subarray(0, idx - 1);
390
+ this.#buf = this.#buf.subarray(idx + 1);
391
+ return line;
392
+ }
393
+ searched = this.#buf.byteLength;
394
+ if (searched > maxBytes) throw new ByteStreamError(`line exceeds ${maxBytes} bytes without CRLF`);
395
+ if (!await this.#pull()) throw new ByteStreamError(`stream ended after ${searched} bytes without CRLF`);
396
+ }
397
+ }
398
+ /** Everything not yet consumed, lazily. */
399
+ async *rest() {
400
+ while (true) {
401
+ if (this.#buf.byteLength > 0) {
402
+ const out = this.#buf;
403
+ this.#buf = EMPTY;
404
+ yield out;
405
+ continue;
406
+ }
407
+ if (!await this.#pull()) return;
408
+ }
409
+ }
410
+ };
411
+ /**
412
+ * Raised for any byte sequence this codec refuses to interpret. Every case is
413
+ * a refusal to guess: HTTP/1.1 parsers that guess are how request smuggling
414
+ * works.
415
+ */
416
+ var HttpParseError = class extends Error {
417
+ name = "HttpParseError";
418
+ };
419
+ const NEWLINE = 10;
420
+ /** Mirrors the HTTP/1.1 codec's default `maxHeaderBytes`. */
421
+ const MAX_ENVELOPE_BYTES = 65536;
422
+ const encoder$1 = new TextEncoder();
423
+ const decoder = new TextDecoder();
424
+ /**
425
+ * Encode an HTTP envelope plus optional body as one continuous byte stream:
426
+ *
427
+ * <JSON.stringify(envelope)>\n<body bytes...>
428
+ *
429
+ * `JSON.stringify` with default whitespace never emits a literal `\n`, so the
430
+ * first `0x0a` byte unambiguously terminates the envelope.
431
+ *
432
+ * This is the same wire shape used by the legacy `webrun-http-port` package.
433
+ */
434
+ async function* encodeMessage(envelope, body) {
435
+ yield encoder$1.encode(`${JSON.stringify(envelope)}\n`);
436
+ if (!body) return;
437
+ for await (const chunk of body) if (chunk.byteLength > 0) yield chunk;
438
+ }
439
+ /**
440
+ * Consume an envelope-then-body byte stream. Returns the parsed envelope and
441
+ * an async iterable over the remaining body bytes.
442
+ */
443
+ async function decodeMessage(input) {
444
+ const iter = toAsyncIterator(input);
445
+ const accum = [];
446
+ let accumLen = 0;
447
+ let before;
448
+ let tail;
449
+ while (true) {
450
+ const next = await iter.next();
451
+ if (next.done) throw new HttpParseError(`decodeMessage: stream ended after ${accumLen} bytes without delimiter (\\n)`);
452
+ const chunk = next.value;
453
+ if (chunk.byteLength === 0) continue;
454
+ const nl = chunk.indexOf(NEWLINE);
455
+ if (nl === -1) {
456
+ accum.push(chunk);
457
+ accumLen += chunk.byteLength;
458
+ if (accumLen > MAX_ENVELOPE_BYTES) throw new HttpParseError(`decodeMessage: envelope exceeds ${MAX_ENVELOPE_BYTES} bytes without delimiter (\\n)`);
459
+ continue;
460
+ }
461
+ accum.push(chunk.subarray(0, nl));
462
+ accumLen += nl;
463
+ before = concatChunks(accum, accumLen);
464
+ tail = chunk.subarray(nl + 1);
465
+ break;
466
+ }
467
+ let envelope;
468
+ try {
469
+ envelope = JSON.parse(decoder.decode(before));
470
+ } catch (err) {
471
+ throw new HttpParseError(`decodeMessage: malformed envelope JSON at bytes 0..${before.byteLength}: ${err.message}`);
472
+ }
473
+ async function* body() {
474
+ if (tail.byteLength > 0) yield tail;
475
+ while (true) {
476
+ const next = await iter.next();
477
+ if (next.done) return;
478
+ if (next.value.byteLength > 0) yield next.value;
479
+ }
480
+ }
481
+ return {
482
+ envelope,
483
+ body: body()
484
+ };
485
+ }
486
+ const OPEN_BRACE = 123;
487
+ /**
488
+ * The original wire format — `<JSON.stringify(envelope)>\n<body bytes…>` —
489
+ * expressed as a `MessageCodec`. Direction-agnostic: requests and responses
490
+ * serialise identically.
491
+ *
492
+ * Retained so a peer pair can be upgraded in either order; see ADR-0006.
493
+ */
494
+ const jsonEnvelopeCodec = {
495
+ name: "json-envelope",
496
+ sniff: (byte) => byte === OPEN_BRACE,
497
+ encodeRequest: (env, body) => encodeMessage(env, body),
498
+ encodeResponse: (env, body) => encodeMessage(env, body),
499
+ decodeRequest: (input) => decodeMessage(input),
500
+ decodeResponse: (input) => decodeMessage(input)
501
+ };
502
+ const TCHAR = /* @__PURE__ */ new Set("!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
503
+ const SP = 32;
504
+ const HTAB = 9;
505
+ function isTokenChar(byte) {
506
+ return byte > SP && byte < 127 && TCHAR.has(String.fromCharCode(byte));
507
+ }
508
+ function isToken(value) {
509
+ if (value.length === 0) return false;
510
+ for (const ch of value) if (!TCHAR.has(ch)) return false;
511
+ return true;
512
+ }
513
+ /**
514
+ * Header bytes are latin-1: byte-preserving, matching Node, and lossless
515
+ * across a decode/encode round-trip. Control characters are rejected
516
+ * separately by `assertValidHeaderValue`.
517
+ */
518
+ function decodeLatin1(bytes) {
519
+ let out = "";
520
+ for (const byte of bytes) out += String.fromCharCode(byte);
521
+ return out;
522
+ }
523
+ function encodeLatin1(text) {
524
+ const out = new Uint8Array(text.length);
525
+ for (let i = 0; i < text.length; i++) {
526
+ const code = text.charCodeAt(i);
527
+ if (code > 255) throw new HttpParseError(`not latin-1 encodable: ${JSON.stringify(text)}`);
528
+ out[i] = code;
529
+ }
530
+ return out;
531
+ }
532
+ const HOST_IP_LITERAL = /^\[[0-9A-Fa-f:.]+\](:\d{1,5})?$/;
533
+ const HOST_REG_NAME = /^[A-Za-z0-9._~-]+(:\d{1,5})?$/;
534
+ /**
535
+ * Validates a value that is about to become (or was read as) a `Host`
536
+ * header: untrusted input either way, so an unrecognised shape is a refusal,
537
+ * not a guess. Rejects a present-but-empty value, one carrying userinfo
538
+ * (`evil.com@good.com`), and — the reason this also runs on encode — one
539
+ * smuggling a CRLF-terminated line into the authority of a caller-supplied
540
+ * url. Never applied to trusted configuration (a codec's `opts.host`).
541
+ */
542
+ function assertValidHost(host) {
543
+ if (!HOST_IP_LITERAL.test(host) && !HOST_REG_NAME.test(host)) throw new HttpParseError(`invalid Host header: ${JSON.stringify(host)}`);
544
+ }
545
+ /**
546
+ * A request-target must be entirely visible ASCII (RFC 9110 VCHAR) — nothing
547
+ * `<= 0x20` (space and every control character, CR/LF included) and nothing
548
+ * `>= 0x7F` (DEL and beyond). Applied on encode (`splitTarget`, so a
549
+ * caller-supplied url can never inject a second request line) and on decode
550
+ * (so a relay that decodes then re-encodes can never put an embedded control
551
+ * character back on the wire).
552
+ */
553
+ function assertValidTarget(target) {
554
+ for (let i = 0; i < target.length; i++) {
555
+ const code = target.charCodeAt(i);
556
+ if (code <= SP || code >= 127) throw new HttpParseError(`invalid request-target: ${JSON.stringify(target)}`);
557
+ }
558
+ }
559
+ /**
560
+ * Shared control-character check behind both `assertValidHeaderValue` and
561
+ * `assertValidStatusText` — the two were previously checked by different,
562
+ * looser rules (statusText only rejected CR/LF), which is exactly the
563
+ * asymmetry class C1 and M5 are both instances of. `label` is prepended
564
+ * verbatim to each message, so callers keep their own wording.
565
+ */
566
+ function assertNoControlChars(label, value) {
567
+ for (let i = 0; i < value.length; i++) {
568
+ const code = value.charCodeAt(i);
569
+ if (code === 13 || code === 10) throw new HttpParseError(`${label} contains CR or LF`);
570
+ if (code < SP && code !== HTAB || code === 127) throw new HttpParseError(`${label} contains a control character`);
571
+ if (code > 255) throw new HttpParseError(`${label} is not latin-1 encodable`);
572
+ }
573
+ }
574
+ function assertValidHeaderValue(name, value) {
575
+ assertNoControlChars(`header "${name}" value`, value);
576
+ }
577
+ /** Same character class as a header value (M5) — CR/LF, every C0 control, and DEL. */
578
+ function assertValidStatusText(value) {
579
+ assertNoControlChars("statusText", value);
580
+ }
581
+ function encodeHeaderLines(headers) {
582
+ let out = "";
583
+ for (const [name, value] of headers) {
584
+ if (!isToken(name)) throw new HttpParseError(`invalid header name: ${JSON.stringify(name)}`);
585
+ assertValidHeaderValue(name, value);
586
+ out += `${name}: ${value}\r\n`;
587
+ }
588
+ return out;
589
+ }
590
+ /**
591
+ * Read to the blank line. `alreadyUsed` is the byte count of the start line,
592
+ * so the bound covers the whole head section rather than the headers alone.
593
+ */
594
+ async function readHeaderSection(reader, maxHeaderBytes, alreadyUsed) {
595
+ const headers = [];
596
+ let used = alreadyUsed;
597
+ while (true) {
598
+ const remaining = maxHeaderBytes - used;
599
+ if (remaining <= 0) throw new HttpParseError(`head section exceeds ${maxHeaderBytes} bytes`);
600
+ const lineBytes = await reader.readLine(remaining);
601
+ used += lineBytes.byteLength + 2;
602
+ if (used > maxHeaderBytes) throw new HttpParseError(`head section exceeds ${maxHeaderBytes} bytes`);
603
+ if (lineBytes.byteLength === 0) return headers;
604
+ if (lineBytes[0] === SP || lineBytes[0] === HTAB) throw new HttpParseError("obs-fold header continuation is not accepted");
605
+ const line = decodeLatin1(lineBytes);
606
+ const colon = line.indexOf(":");
607
+ if (colon <= 0) throw new HttpParseError(`malformed header line: ${JSON.stringify(line)}`);
608
+ const name = line.slice(0, colon);
609
+ if (!isToken(name)) throw new HttpParseError(`invalid header name: ${JSON.stringify(name)}`);
610
+ const value = line.slice(colon + 1).replace(/^[ \t]+/, "").replace(/[ \t]+$/, "");
611
+ assertValidHeaderValue(name, value);
612
+ headers.push([name, value]);
613
+ }
614
+ }
615
+ function getAll(headers, name) {
616
+ const lower = name.toLowerCase();
617
+ return headers.filter(([k]) => k.toLowerCase() === lower).map(([, v]) => v);
618
+ }
619
+ function withoutHeaders(headers, names) {
620
+ const drop = new Set(names.map((n) => n.toLowerCase()));
621
+ return headers.filter(([k]) => !drop.has(k.toLowerCase()));
622
+ }
623
+ /**
624
+ * Parse a `Content-Length` field into a single validated value.
625
+ *
626
+ * RFC 9110 §8.6 permits the value to be a comma-separated list of identical
627
+ * numbers (a relay may have appended one), so the list is folded; differing
628
+ * values are a refusal, not a choice. Shared by `resolveFraming` on decode and
629
+ * by the encoder's declared-length check, which previously carried its own
630
+ * copy that did NOT split on commas — so decode accepted `5, 5` while encode
631
+ * rejected it, and a relay that decoded then re-encoded threw.
632
+ *
633
+ * Returns undefined when the field is absent.
634
+ */
635
+ function parseContentLength(values) {
636
+ if (values.length === 0) return void 0;
637
+ const unique = new Set(values.flatMap((v) => v.split(",").map((s) => s.trim())));
638
+ if (unique.size !== 1) throw new HttpParseError(`conflicting Content-Length values: ${[...unique].join(", ")}`);
639
+ const raw = [...unique][0];
640
+ if (!/^\d{1,15}$/.test(raw)) throw new HttpParseError(`invalid Content-Length: ${JSON.stringify(raw)}`);
641
+ return Number(raw);
642
+ }
643
+ /**
644
+ * Statuses that carry no body whatever the headers say (RFC 9110 §8.6): 1xx,
645
+ * 204 and 304. Defined once because the encoder must not frame a body for
646
+ * them and the decoder must not try to read one — two lists that agreed today
647
+ * and were free to drift tomorrow.
648
+ *
649
+ * A response to HEAD is also bodyless, but that depends on the request rather
650
+ * than the status, so callers test it separately.
651
+ */
652
+ function isBodylessStatus(status) {
653
+ return status < 200 || status === 204 || status === 304;
654
+ }
655
+ /**
656
+ * RFC 9112 §6.3, with every ambiguity turned into a refusal. In particular a
657
+ * message declaring both Content-Length and Transfer-Encoding is rejected
658
+ * rather than resolved — disagreeing on which one wins is request smuggling.
659
+ */
660
+ function resolveFraming(headers, version) {
661
+ const te = getAll(headers, "transfer-encoding");
662
+ const cl = getAll(headers, "content-length");
663
+ if (te.length > 0 && cl.length > 0) throw new HttpParseError("message declares both Content-Length and Transfer-Encoding; refusing (request smuggling)");
664
+ if (te.length > 0) {
665
+ const encodings = te.join(",").split(",").map((s) => s.trim().toLowerCase()).filter((s) => s !== "");
666
+ if (encodings.length !== 1 || encodings[0] !== "chunked") throw new HttpParseError(`unsupported Transfer-Encoding: ${JSON.stringify(te.join(", "))}`);
667
+ if (version === "HTTP/1.0") throw new HttpParseError("Transfer-Encoding is not valid in HTTP/1.0");
668
+ return { kind: "chunked" };
669
+ }
670
+ const length = parseContentLength(cl);
671
+ if (length !== void 0) return {
672
+ kind: "length",
673
+ length
674
+ };
675
+ return { kind: "none" };
676
+ }
677
+ const CRLF = new Uint8Array([13, 10]);
678
+ const LAST_CHUNK = new Uint8Array([
679
+ 48,
680
+ 13,
681
+ 10,
682
+ 13,
683
+ 10
684
+ ]);
685
+ const encoder = new TextEncoder();
686
+ /**
687
+ * Chunk sizes are written in HEXADECIMAL — a 21-byte chunk is `15`. Writing
688
+ * them in decimal is the defect note 15 found in @libp2p/http, and it is the
689
+ * one that cannot be caught downstream: decimal digits are also valid hex, so
690
+ * a conforming parser silently reads the wrong length.
691
+ *
692
+ * Zero-length source chunks are skipped; a zero-sized chunk on the wire is the
693
+ * body terminator.
694
+ */
695
+ async function* encodeChunked(body) {
696
+ for await (const chunk of body) {
697
+ if (chunk.byteLength === 0) continue;
698
+ yield encoder.encode(`${chunk.byteLength.toString(16)}\r\n`);
699
+ yield chunk;
700
+ yield CRLF;
701
+ }
702
+ yield LAST_CHUNK;
703
+ }
704
+ /**
705
+ * Decode a chunked body, yielding data chunks as they arrive. Nothing is
706
+ * accumulated: a chunk larger than the transport's frame is yielded in pieces.
707
+ */
708
+ async function* decodeChunked(reader, maxLineBytes) {
709
+ while (true) {
710
+ const sizeLine = decodeLatin1(await reader.readLine(maxLineBytes));
711
+ const semicolon = sizeLine.indexOf(";");
712
+ const sizeText = semicolon === -1 ? sizeLine : sizeLine.slice(0, semicolon);
713
+ if (!/^[0-9a-fA-F]{1,32}$/.test(sizeText)) throw new HttpParseError(`invalid chunk size: ${JSON.stringify(sizeLine)}`);
714
+ const size = Number.parseInt(sizeText, 16);
715
+ if (!Number.isSafeInteger(size)) throw new HttpParseError(`chunk size is too large: ${JSON.stringify(sizeLine)}`);
716
+ if (size === 0) {
717
+ let used = 0;
718
+ while (true) {
719
+ const remaining = maxLineBytes - used;
720
+ if (remaining <= 0) throw new HttpParseError(`trailer section exceeds ${maxLineBytes} bytes`);
721
+ const lineBytes = await reader.readLine(remaining);
722
+ used += lineBytes.byteLength + 2;
723
+ if (used > maxLineBytes) throw new HttpParseError(`trailer section exceeds ${maxLineBytes} bytes`);
724
+ if (lineBytes.byteLength === 0) break;
725
+ }
726
+ return;
727
+ }
728
+ let remaining = size;
729
+ while (remaining > 0) {
730
+ const part = await reader.readSome(remaining);
731
+ if (part === void 0) throw new HttpParseError(`chunk truncated: ${remaining} of ${size} bytes missing`);
732
+ remaining -= part.byteLength;
733
+ yield part;
734
+ }
735
+ try {
736
+ if ((await reader.readLine(2)).byteLength !== 0) throw new HttpParseError("chunk data not terminated by CRLF");
737
+ } catch (err) {
738
+ if (err instanceof ByteStreamError) throw new HttpParseError("chunk data not terminated by CRLF");
739
+ throw err;
740
+ }
741
+ }
742
+ }
743
+ const VERSIONS = /* @__PURE__ */ new Set(["HTTP/1.1", "HTTP/1.0"]);
744
+ const ABSOLUTE_FORM = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;
745
+ /**
746
+ * One message per Duplex call (ADR-0006), so bytes after a complete message
747
+ * are an error. Checked against what is ALREADY BUFFERED rather than by
748
+ * awaiting end-of-stream: a live socket from a keep-alive peer never reaches
749
+ * EOF, so awaiting one would hang instead of failing.
750
+ */
751
+ function assertNoBufferedBytes(reader) {
752
+ const extra = reader.bufferedLength();
753
+ if (extra > 0) throw new HttpParseError(`${extra} trailing bytes after a complete message`);
754
+ }
755
+ /**
756
+ * The public error contract (I2): everything leaving `decodeRequest` /
757
+ * `decodeResponse` is an `HttpParseError`, whether the refusal happened
758
+ * synchronously (a malformed start line or header) or lazily while the body
759
+ * is later drained. `ByteStreamError` — the `ByteReader`'s own class, never
760
+ * exported — is the one thing converted here, message and all preserved via
761
+ * `cause`. Anything else is a genuine failure of the underlying source (a
762
+ * dropped socket, say) and must reach the caller unchanged: blanket-catching
763
+ * would hide that distinction.
764
+ */
765
+ function toHttpParseError(err) {
766
+ if (err instanceof ByteStreamError) throw new HttpParseError(err.message, { cause: err });
767
+ throw err;
768
+ }
769
+ /** Applies `toHttpParseError` across the whole lifetime of a body generator. */
770
+ async function* convertBodyErrors(source) {
771
+ try {
772
+ yield* source;
773
+ } catch (err) {
774
+ toHttpParseError(err);
775
+ }
776
+ }
777
+ async function* readBody(reader, framing, opts, noneMeansEof) {
778
+ if (framing.kind === "chunked") {
779
+ yield* decodeChunked(reader, opts.maxHeaderBytes);
780
+ assertNoBufferedBytes(reader);
781
+ return;
782
+ }
783
+ if (framing.kind === "length") {
784
+ let remaining = framing.length;
785
+ while (remaining > 0) {
786
+ const part = await reader.readSome(remaining);
787
+ if (part === void 0) throw new HttpParseError(`body truncated: ${remaining} of ${framing.length} bytes missing`);
788
+ remaining -= part.byteLength;
789
+ yield part;
790
+ }
791
+ assertNoBufferedBytes(reader);
792
+ return;
793
+ }
794
+ if (noneMeansEof) {
795
+ yield* reader.rest();
796
+ return;
797
+ }
798
+ assertNoBufferedBytes(reader);
799
+ }
800
+ /**
801
+ * `readLine`'s bound is best-effort — it is skipped when the line is already
802
+ * buffered — so a very long start line can reach these messages intact. Since
803
+ * a refusal is now echoed back to the sender in a 400 body, quote only enough
804
+ * to diagnose rather than reflecting the whole thing.
805
+ */
806
+ function quoteLine(line) {
807
+ const MAX = 120;
808
+ return line.length <= MAX ? JSON.stringify(line) : `${JSON.stringify(line.slice(0, MAX))} (truncated from ${line.length} chars)`;
809
+ }
810
+ async function decodeRequest(input, opts) {
811
+ const reader = new ByteReader(input);
812
+ try {
813
+ const startBytes = await reader.readLine(opts.maxHeaderBytes);
814
+ const startLine = decodeLatin1(startBytes);
815
+ const parts = startLine.split(" ");
816
+ if (parts.length !== 3) throw new HttpParseError(`malformed request line: ${quoteLine(startLine)}`);
817
+ const [method, target, version] = parts;
818
+ if (!isToken(method)) throw new HttpParseError(`invalid method: ${JSON.stringify(method)}`);
819
+ if (!VERSIONS.has(version)) throw new HttpParseError(`unsupported HTTP version: ${JSON.stringify(version)}`);
820
+ if (target === "*") throw new HttpParseError("asterisk-form request target is not supported");
821
+ assertValidTarget(target);
822
+ const headers = await readHeaderSection(reader, opts.maxHeaderBytes, startBytes.byteLength + 2);
823
+ const hosts = getAll(headers, "host");
824
+ if (hosts.length > 1) throw new HttpParseError("multiple Host headers");
825
+ const host = hosts[0];
826
+ let url;
827
+ if (target.startsWith("/")) {
828
+ if (version === "HTTP/1.1" && host === void 0) throw new HttpParseError("HTTP/1.1 request has no Host header");
829
+ if (host !== void 0) assertValidHost(host);
830
+ url = `${opts.scheme}://${host ?? opts.host}${target}`;
831
+ } else if (ABSOLUTE_FORM.test(target)) url = target;
832
+ else throw new HttpParseError(`unsupported request target: ${JSON.stringify(target)}`);
833
+ try {
834
+ new URL(url);
835
+ } catch {
836
+ throw new HttpParseError(`decoded url is not a valid URL: ${JSON.stringify(url)}`);
837
+ }
838
+ return {
839
+ envelope: {
840
+ url,
841
+ method,
842
+ headers
843
+ },
844
+ body: convertBodyErrors(readBody(reader, resolveFraming(headers, version), opts, false))
845
+ };
846
+ } catch (err) {
847
+ toHttpParseError(err);
848
+ }
849
+ }
850
+ async function decodeResponse(input, opts, method) {
851
+ const reader = new ByteReader(input);
852
+ try {
853
+ const startBytes = await reader.readLine(opts.maxHeaderBytes);
854
+ const startLine = decodeLatin1(startBytes);
855
+ const firstSp = startLine.indexOf(" ");
856
+ if (firstSp === -1) throw new HttpParseError(`malformed status line: ${quoteLine(startLine)}`);
857
+ const version = startLine.slice(0, firstSp);
858
+ if (!VERSIONS.has(version)) throw new HttpParseError(`unsupported HTTP version: ${JSON.stringify(version)}`);
859
+ const afterVersion = startLine.slice(firstSp + 1);
860
+ const secondSp = afterVersion.indexOf(" ");
861
+ const codeText = secondSp === -1 ? afterVersion : afterVersion.slice(0, secondSp);
862
+ if (!/^\d{3}$/.test(codeText)) throw new HttpParseError(`invalid status code: ${JSON.stringify(codeText)}`);
863
+ const status = Number(codeText);
864
+ const statusText = secondSp === -1 ? "" : afterVersion.slice(secondSp + 1);
865
+ const headers = await readHeaderSection(reader, opts.maxHeaderBytes, startBytes.byteLength + 2);
866
+ const bodyless = isBodylessStatus(status) || method.toUpperCase() === "HEAD";
867
+ const framing = bodyless ? { kind: "none" } : resolveFraming(headers, version);
868
+ return {
869
+ envelope: {
870
+ status,
871
+ statusText,
872
+ headers
873
+ },
874
+ body: convertBodyErrors(readBody(reader, framing, opts, !bodyless))
875
+ };
876
+ } catch (err) {
877
+ toHttpParseError(err);
878
+ }
879
+ }
880
+ /** Headers the codec owns: a caller-supplied copy is dropped and re-derived. */
881
+ const REQUEST_OWNED = [
882
+ "host",
883
+ "connection",
884
+ "transfer-encoding"
885
+ ];
886
+ const RESPONSE_OWNED = ["connection", "transfer-encoding"];
887
+ /**
888
+ * Split a URL into an origin-form request target and an authority *without*
889
+ * going through `new URL()`. `URL` normalises percent-encoding and would
890
+ * re-serialise the target — which is the exact class of defect note 15 found
891
+ * in @libp2p/http, where rebuilding the request line silently dropped
892
+ * `url.search`. Here the target is a verbatim slice of the caller's string.
893
+ */
894
+ function splitTarget(url, opts) {
895
+ if (url.startsWith("/")) {
896
+ assertValidTarget(url);
897
+ return {
898
+ target: url,
899
+ authority: opts.host
900
+ };
901
+ }
902
+ const match = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/([^/?#]*)([^#]*)/.exec(url);
903
+ if (!match) throw new HttpParseError(`cannot derive a request target from url: ${JSON.stringify(url)}`);
904
+ const rawAuthority = match[1];
905
+ if (rawAuthority === "") throw new HttpParseError(`url has no authority: ${JSON.stringify(url)}`);
906
+ const at = rawAuthority.lastIndexOf("@");
907
+ const authority = at === -1 ? rawAuthority : rawAuthority.slice(at + 1);
908
+ assertValidHost(authority);
909
+ const rawTarget = match[2];
910
+ const target = rawTarget === "" ? "/" : rawTarget.startsWith("/") ? rawTarget : `/${rawTarget}`;
911
+ assertValidTarget(target);
912
+ return {
913
+ target,
914
+ authority
915
+ };
916
+ }
917
+ async function* emitBody(body, declared) {
918
+ if (declared === void 0) {
919
+ yield* encodeChunked(body);
920
+ return;
921
+ }
922
+ let sent = 0;
923
+ for await (const chunk of body) {
924
+ if (chunk.byteLength === 0) continue;
925
+ sent += chunk.byteLength;
926
+ if (sent > declared) throw new HttpParseError(`body exceeds declared Content-Length ${declared} (${sent} bytes so far)`);
927
+ yield chunk;
928
+ }
929
+ if (sent !== declared) throw new HttpParseError(`body is ${sent} bytes but Content-Length declares ${declared}`);
930
+ }
931
+ async function* encodeRequest(env, body, opts) {
932
+ if (!isToken(env.method)) throw new HttpParseError(`invalid method: ${JSON.stringify(env.method)}`);
933
+ const { target, authority } = splitTarget(env.url, opts);
934
+ if (authority === "") throw new HttpParseError("no Host available: url has no authority and no host is configured");
935
+ const carried = withoutHeaders(env.headers, REQUEST_OWNED);
936
+ const declared = parseContentLength(getAll(carried, "content-length"));
937
+ let head = `${env.method} ${target} HTTP/1.1\r\n`;
938
+ head += `Host: ${authority}\r\n`;
939
+ head += encodeHeaderLines(carried);
940
+ head += "Connection: close\r\n";
941
+ if (body !== void 0 && declared === void 0) head += "Transfer-Encoding: chunked\r\n";
942
+ head += "\r\n";
943
+ yield encodeLatin1(head);
944
+ if (body === void 0) {
945
+ if (declared !== void 0 && declared !== 0) throw new HttpParseError(`body is 0 bytes but Content-Length declares ${declared}`);
946
+ return;
947
+ }
948
+ yield* emitBody(body, declared);
949
+ }
950
+ async function* encodeResponse(env, body, _opts, requestMethod) {
951
+ if (!Number.isInteger(env.status) || env.status < 100 || env.status > 599) throw new HttpParseError(`invalid status: ${env.status}`);
952
+ const reason = env.statusText ?? "";
953
+ assertValidStatusText(reason);
954
+ const bodylessStatus = isBodylessStatus(env.status);
955
+ const bodyless = bodylessStatus || requestMethod?.toUpperCase() === "HEAD";
956
+ const owned = bodylessStatus ? [...RESPONSE_OWNED, "content-length"] : RESPONSE_OWNED;
957
+ const carried = withoutHeaders(env.headers, owned);
958
+ const declared = parseContentLength(getAll(carried, "content-length"));
959
+ let head = `HTTP/1.1 ${env.status} ${reason}\r\n`;
960
+ head += encodeHeaderLines(carried);
961
+ head += "Connection: close\r\n";
962
+ if (!bodyless && body !== void 0 && declared === void 0) head += "Transfer-Encoding: chunked\r\n";
963
+ head += "\r\n";
964
+ yield encodeLatin1(head);
965
+ if (bodyless) {
966
+ await discard(body);
967
+ return;
968
+ }
969
+ if (body === void 0) {
970
+ if (declared !== void 0 && declared !== 0) throw new HttpParseError(`body is 0 bytes but Content-Length declares ${declared}`);
971
+ return;
972
+ }
973
+ yield* emitBody(body, declared);
974
+ }
975
+ function newHttpCodec(options = {}) {
976
+ const opts = {
977
+ scheme: options.scheme ?? "http",
978
+ host: options.host ?? "localhost",
979
+ maxHeaderBytes: options.maxHeaderBytes ?? 65536
980
+ };
981
+ return {
982
+ name: "http/1.1",
983
+ sniff: (byte) => isTokenChar(byte),
984
+ encodeRequest: (env, body) => encodeRequest(env, body, opts),
985
+ encodeResponse: (env, body, o) => encodeResponse(env, body, opts, o?.method),
986
+ decodeRequest: (input) => decodeRequest(input, opts),
987
+ decodeResponse: (input, o) => decodeResponse(input, opts, o.method)
988
+ };
989
+ }
990
+ const httpCodec = newHttpCodec();
991
+ /**
992
+ * Dispatches on byte 0. The formats are self-identifying — a JSON envelope
993
+ * always begins `{`, which is not a token character and so can never begin an
994
+ * HTTP start-line — so no negotiation handshake, magic prefix, or version byte
995
+ * is needed.
996
+ *
997
+ * This is what makes a mixed-version peer pair safe: readers accept either
998
+ * format, so the two ends can be upgraded in any order.
999
+ */
1000
+ function newSniffingCodec(options) {
1001
+ const { write, accept } = options;
1002
+ async function pick(input) {
1003
+ const reader = new ByteReader(input);
1004
+ const first = await reader.peekByte();
1005
+ if (first === void 0) throw new HttpParseError("sniff: stream ended before any bytes arrived");
1006
+ const codec = accept.find((c) => c.sniff(first));
1007
+ if (!codec) throw new HttpParseError(`sniff: no accepted codec recognises a message starting with byte 0x${first.toString(16).padStart(2, "0")}`);
1008
+ return {
1009
+ codec,
1010
+ input: reader.rest()
1011
+ };
1012
+ }
1013
+ return {
1014
+ name: `sniff(write=${write.name}; accept=${accept.map((c) => c.name).join(",")})`,
1015
+ sniff: (byte) => accept.some((c) => c.sniff(byte)),
1016
+ encodeRequest: (env, body) => write.encodeRequest(env, body),
1017
+ encodeResponse: (env, body, o) => write.encodeResponse(env, body, o),
1018
+ decodeRequest: async (input) => {
1019
+ const picked = await pick(input);
1020
+ try {
1021
+ return {
1022
+ ...await picked.codec.decodeRequest(picked.input),
1023
+ codec: picked.codec
1024
+ };
1025
+ } catch (error) {
1026
+ if (error !== null && typeof error === "object") error.codec = picked.codec;
1027
+ throw error;
1028
+ }
1029
+ },
1030
+ decodeResponse: async (input, o) => {
1031
+ const picked = await pick(input);
1032
+ return picked.codec.decodeResponse(picked.input, o);
1033
+ }
1034
+ };
1035
+ }
1036
+ newSniffingCodec({
1037
+ write: httpCodec,
1038
+ accept: [httpCodec, jsonEnvelopeCodec]
1039
+ });
1040
+ /**
1041
+ * The one place that knows a runtime may not implement request body streams,
1042
+ * and the buffering both fallbacks need. `fetch.ts` and `http-stubs.ts` each
1043
+ * carry a client and a server direction that must agree on the answer, so the
1044
+ * predicate lives here rather than being written out four times.
1045
+ */
1046
+ /**
1047
+ * Whether `Request.prototype` exposes a `body` accessor. Two call sites read
1048
+ * that property, and two more depend on the constructor accepting a
1049
+ * `ReadableStream` as `init.body`; this predicate answers for all four.
1050
+ *
1051
+ * What was verified, and all that is claimed here: Firefox (146 at the time of
1052
+ * writing) has *neither*, and Chromium and Node have *both*. On Firefox it is
1053
+ * not that `body` is `undefined` on the instance —
1054
+ * `Object.getOwnPropertyDescriptor(Request.prototype, "body")` is `null`, the
1055
+ * accessor is genuinely absent — and because a `ReadableStream` is then not a
1056
+ * recognised `BodyInit`, the constructor falls through to the string branch and
1057
+ * stores the literal text `[object ReadableStream]`.
1058
+ *
1059
+ * The two halves are NOT guaranteed to ship together, so do not read this as a
1060
+ * test for "request streams" in general. Safari is the counterexample: it has
1061
+ * had `Request.body` since 11.1 but only accepts a stream as `init.body` from
1062
+ * Technology Preview 250, so a shipping Safari has the reader half without the
1063
+ * upload half and this returns `true` there. That looks benign — WebKit appears
1064
+ * to store the stream on the `Request` rather than stringify it, and its error
1065
+ * comes from `fetch()`, which this package never calls on the objects it builds
1066
+ * — but it is untested, and it is the case to look at first if a Safari report
1067
+ * arrives. The sharper probe, if one is ever needed, is whether
1068
+ * `new Request(url, {method:"POST", body:new ReadableStream(), duplex:"half"})`
1069
+ * has a `content-type` of `text/plain;charset=UTF-8` (stringified) or `null`
1070
+ * (stored); it is not used here because it costs a `Request` and a
1071
+ * `ReadableStream` per call and agrees with the descriptor check on every
1072
+ * runtime measured.
1073
+ *
1074
+ * A capability check, never a user-agent test: the question is what this
1075
+ * runtime does, and the answer flips on its own the day Firefox ships request
1076
+ * streams. Evaluated per call rather than cached at module load so that a test
1077
+ * can install a `Request` without the capability and exercise the real branch
1078
+ * under Node.
1079
+ */
1080
+ function supportsRequestStreams() {
1081
+ return typeof Request === "function" && Object.getOwnPropertyDescriptor(Request.prototype, "body") != null;
1082
+ }
1083
+ const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
1084
+ 101,
1085
+ 103,
1086
+ 204,
1087
+ 205,
1088
+ 304
1089
+ ]);
1090
+ const REQUEST_FIELDS = [
1091
+ "url",
1092
+ "method",
1093
+ "mode",
1094
+ "credentials",
1095
+ "cache",
1096
+ "redirect",
1097
+ "referrer",
1098
+ "referrerPolicy",
1099
+ "integrity",
1100
+ "keepalive"
1101
+ ];
1102
+ /** `SerializedHttpEnvelope.content` is never absent, only empty. */
1103
+ async function* noBytes() {}
1104
+ async function* oneChunk(chunk) {
1105
+ yield chunk;
1106
+ }
1107
+ /**
1108
+ * Returns an HTTP handler that serializes a Request, hands the envelope to
1109
+ * `send` for transport, and deserializes the reply into a Response. Used on
1110
+ * the caller side.
1111
+ */
1112
+ function newHttpClientStub(send) {
1113
+ return async (requestOrPromise) => {
1114
+ const request = await requestOrPromise;
1115
+ const headers = [...request.headers].map(([k, v]) => [k, v]);
1116
+ const options = {
1117
+ url: request.url,
1118
+ headers
1119
+ };
1120
+ for (const field of REQUEST_FIELDS) {
1121
+ const val = request[field];
1122
+ if (val !== void 0 && field !== "url") options[field] = val;
1123
+ }
1124
+ let content;
1125
+ if (request.body != null) content = fromReadableStream(request.body);
1126
+ else if (!supportsRequestStreams()) content = oneChunk(new Uint8Array(await request.arrayBuffer()));
1127
+ else content = noBytes();
1128
+ const result = await send({
1129
+ options,
1130
+ content
1131
+ });
1132
+ if (!result) return new Response(null, {
1133
+ status: 404,
1134
+ statusText: "Error 404: Not Found"
1135
+ });
1136
+ const responseOptions = result.options;
1137
+ const method = options.method;
1138
+ if (method === "HEAD" || method === "OPTIONS" || NULL_BODY_STATUSES.has(responseOptions.status)) {
1139
+ await discard(result.content);
1140
+ return new Response(null, responseOptions);
1141
+ }
1142
+ return new Response(toReadableStream(result.content[Symbol.asyncIterator]()), responseOptions);
1143
+ };
1144
+ }
1145
+ var HttpError = class HttpError extends Error {
1146
+ status;
1147
+ statusText;
1148
+ constructor(options = {}) {
1149
+ super(options.message ?? options.statusText ?? "HTTP Error");
1150
+ this.status = options.status;
1151
+ this.statusText = options.statusText;
1152
+ }
1153
+ getResponseOptions(options = {}) {
1154
+ return {
1155
+ ...this.toJson(),
1156
+ ...options
1157
+ };
1158
+ }
1159
+ toJson() {
1160
+ return {
1161
+ status: this.status,
1162
+ statusText: this.statusText,
1163
+ message: this.message
1164
+ };
1165
+ }
1166
+ static fromError(error) {
1167
+ if (error instanceof HttpError) return error;
1168
+ const message = error instanceof Error ? error.message : String(error);
1169
+ return new HttpError({
1170
+ status: 500,
1171
+ statusText: "Bad Request",
1172
+ message
1173
+ });
1174
+ }
1175
+ static errorResourceNotFound(options = {}) {
1176
+ return new HttpError({
1177
+ status: 404,
1178
+ statusText: "Error 404: Resource not found",
1179
+ ...options
1180
+ });
1181
+ }
1182
+ static errorForbidden(options = {}) {
1183
+ return new HttpError({
1184
+ status: 403,
1185
+ statusText: "Error 403: Forbidden",
1186
+ ...options
1187
+ });
1188
+ }
1189
+ static errorResourceGone(options = {}) {
1190
+ return new HttpError({
1191
+ status: 410,
1192
+ statusText: "Error 410: Resource Gone",
1193
+ ...options
1194
+ });
1195
+ }
1196
+ static errorInternalError(options = {}) {
1197
+ return new HttpError({
1198
+ ...options,
1199
+ status: 500,
1200
+ statusText: "Error 500: Internal error"
1201
+ });
1202
+ }
1203
+ };
1204
+ //#endregion
1205
+ //#region ../../../../node_modules/.pnpm/idb-keyval@6.3.0/node_modules/idb-keyval/dist/index.js
1206
+ function promisifyRequest(request) {
1207
+ return new Promise((resolve, reject) => {
1208
+ request.oncomplete = request.onsuccess = () => resolve(request.result);
1209
+ request.onabort = request.onerror = () => reject(request.error);
1210
+ });
1211
+ }
1212
+ function createStore(dbName, storeName) {
1213
+ let dbp;
1214
+ const getDB = () => {
1215
+ if (dbp) return dbp;
1216
+ const request = indexedDB.open(dbName);
1217
+ request.onupgradeneeded = () => request.result.createObjectStore(storeName);
1218
+ dbp = promisifyRequest(request);
1219
+ dbp.then((db) => {
1220
+ db.onclose = () => dbp = void 0;
1221
+ }, () => {
1222
+ dbp = void 0;
1223
+ });
1224
+ return dbp;
1225
+ };
1226
+ return (txMode, callback) => getDB().then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
1227
+ }
1228
+ let defaultGetStoreFunc;
1229
+ function defaultGetStore() {
1230
+ if (!defaultGetStoreFunc) defaultGetStoreFunc = createStore("keyval-store", "keyval");
1231
+ return defaultGetStoreFunc;
1232
+ }
1233
+ /**
1234
+ * Get a value by its key.
1235
+ *
1236
+ * @param key
1237
+ * @param customStore Method to get a custom store. Use with caution (see the docs).
1238
+ */
1239
+ function get(key, customStore = defaultGetStore()) {
1240
+ return customStore("readonly", (store) => promisifyRequest(store.get(key)));
1241
+ }
1242
+ /**
1243
+ * Set a value with a key.
1244
+ *
1245
+ * @param key
1246
+ * @param value
1247
+ * @param customStore Method to get a custom store. Use with caution (see the docs).
1248
+ */
1249
+ function set(key, value, customStore = defaultGetStore()) {
1250
+ return customStore("readwrite", (store) => {
1251
+ store.put(value, key);
1252
+ return promisifyRequest(store.transaction);
1253
+ });
1254
+ }
1255
+ //#endregion
1256
+ //#region src/core/data-calls.ts
1257
+ function callChannel(target, callType, params, ...transfers) {
1258
+ return new Promise((resolve, reject) => {
1259
+ const channel = new MessageChannel();
1260
+ channel.port1.onmessage = (ev) => {
1261
+ const { result, error } = ev.data;
1262
+ if (error) reject(deserializeError(error));
1263
+ else resolve(result);
1264
+ };
1265
+ target.postMessage({
1266
+ type: callType,
1267
+ params
1268
+ }, [channel.port2, ...transfers]);
1269
+ });
1270
+ }
1271
+ function handleChannelCalls(target, callType, handler) {
1272
+ const listener = async (event) => {
1273
+ if (!event.data || event.data.type !== callType) return;
1274
+ const [port, ...transfers] = event.ports ?? [];
1275
+ const response = {};
1276
+ try {
1277
+ response.result = await handler(event, event.data.params, ...transfers);
1278
+ } catch (error) {
1279
+ response.error = serializeError(error);
1280
+ }
1281
+ port?.postMessage(response);
1282
+ };
1283
+ target.addEventListener("message", listener);
1284
+ target.start?.();
1285
+ return () => target.removeEventListener("message", listener);
1286
+ }
1287
+ //#endregion
1288
+ //#region src/core/registry.ts
1289
+ function newRegistry(onError = console.error) {
1290
+ let counter = 0;
1291
+ const registrations = {};
1292
+ const register = (action) => {
1293
+ const id = counter++;
1294
+ const fn = Object.assign((skip) => {
1295
+ try {
1296
+ delete registrations[id];
1297
+ return skip ? void 0 : action();
1298
+ } catch (error) {
1299
+ onError(error);
1300
+ }
1301
+ }, { action });
1302
+ registrations[id] = fn;
1303
+ return fn;
1304
+ };
1305
+ const unregister = (action) => {
1306
+ for (const r of Object.values(registrations)) if (r.action === action) r(true);
1307
+ };
1308
+ const clear = () => {
1309
+ for (const r of Object.values(registrations)) r();
1310
+ };
1311
+ return Object.assign([
1312
+ register,
1313
+ clear,
1314
+ unregister
1315
+ ], {
1316
+ register,
1317
+ clear,
1318
+ unregister
1319
+ });
1320
+ }
1321
+ //#endregion
1322
+ //#region src/core/data-channels.ts
1323
+ const MESSAGE_TYPE_REQUEST = "REQUEST";
1324
+ const MESSAGE_TYPE_RESPONSE = "RESPONSE";
1325
+ let __invocationCounter = 0;
1326
+ function newInvokationChannel({ port, handler = () => {
1327
+ throw new Error("Handler not implemented");
1328
+ }, onError = console.error, newCallId = () => ++__invocationCounter }) {
1329
+ const requests = {};
1330
+ const listener = async (event) => {
1331
+ const data = event.data ?? {};
1332
+ if (data.type === MESSAGE_TYPE_REQUEST) try {
1333
+ const result = await handler(data.request, ...event.ports);
1334
+ const [response, ...transfers] = Array.isArray(result) ? result : result !== void 0 ? [result] : [];
1335
+ port.postMessage({
1336
+ type: MESSAGE_TYPE_RESPONSE,
1337
+ callId: data.callId,
1338
+ response
1339
+ }, transfers);
1340
+ } catch (error) {
1341
+ port.postMessage({
1342
+ type: MESSAGE_TYPE_RESPONSE,
1343
+ callId: data.callId,
1344
+ error: serializeError(error)
1345
+ });
1346
+ }
1347
+ else if (data.type === MESSAGE_TYPE_RESPONSE) {
1348
+ const pending = requests[data.callId];
1349
+ delete requests[data.callId];
1350
+ if (!pending) return;
1351
+ if (data.error) pending.reject(deserializeError(data.error));
1352
+ else pending.resolve(data.response);
1353
+ }
1354
+ };
1355
+ const start = async () => {
1356
+ try {
1357
+ port.addEventListener("message", listener);
1358
+ await port.start?.();
1359
+ } catch (e) {
1360
+ onError(e);
1361
+ }
1362
+ };
1363
+ const close = async () => {
1364
+ try {
1365
+ port.removeEventListener("message", listener);
1366
+ await port.close?.();
1367
+ } catch (e) {
1368
+ onError(e);
1369
+ }
1370
+ };
1371
+ const invoke = (request = {}, ...transfers) => {
1372
+ const callId = newCallId();
1373
+ return new Promise((resolve, reject) => {
1374
+ try {
1375
+ requests[callId] = {
1376
+ resolve,
1377
+ reject
1378
+ };
1379
+ port.postMessage({
1380
+ type: MESSAGE_TYPE_REQUEST,
1381
+ callId,
1382
+ request
1383
+ }, transfers);
1384
+ } catch (error) {
1385
+ delete requests[callId];
1386
+ reject(error);
1387
+ }
1388
+ });
1389
+ };
1390
+ return {
1391
+ start,
1392
+ close,
1393
+ invoke
1394
+ };
1395
+ }
1396
+ async function* sendStream(communicationPort, input, params = {}) {
1397
+ const messageChannel = new MessageChannel();
1398
+ communicationPort.postMessage({
1399
+ type: "START_CALL",
1400
+ params
1401
+ }, [messageChannel.port2]);
1402
+ const channel = newStreamChannel(messageChannel.port1);
1403
+ let drained = false;
1404
+ try {
1405
+ await channel.start();
1406
+ channel.sendAll(input);
1407
+ yield* channel.recieveAll();
1408
+ drained = true;
1409
+ } finally {
1410
+ if (!drained) channel.cancel();
1411
+ await channel.close();
1412
+ }
1413
+ }
1414
+ function newStreamChannel(port) {
1415
+ let listeners = [];
1416
+ let iterators = [];
1417
+ const notifyAll = async (data) => {
1418
+ for (const listener of listeners) await listener(data);
1419
+ };
1420
+ /**
1421
+ * Release whatever we are sending. NOT awaited: `.return()` on an async
1422
+ * generator parked awaiting its own source is queued behind that pending
1423
+ * `next()`, so awaiting it here would block the message handler — and the
1424
+ * chunk that would unblock it can only arrive through that same handler.
1425
+ */
1426
+ const cancelOutgoing = () => {
1427
+ for (const it of [...iterators]) {
1428
+ const iterable = it;
1429
+ Promise.resolve(iterable.return?.()).catch(() => {});
1430
+ }
1431
+ };
1432
+ const channel = newInvokationChannel({
1433
+ port,
1434
+ handler: (data) => {
1435
+ const message = data;
1436
+ if (message?.cancel) {
1437
+ cancelOutgoing();
1438
+ return;
1439
+ }
1440
+ return notifyAll(message);
1441
+ }
1442
+ });
1443
+ const start = () => channel.start();
1444
+ const cancel = () => {
1445
+ channel.invoke({ cancel: true }).catch(() => {});
1446
+ };
1447
+ const close = async () => {
1448
+ await notifyAll({ done: true });
1449
+ for (const it of [...iterators]) await it.return?.();
1450
+ await channel.close();
1451
+ };
1452
+ async function* recieveAll() {
1453
+ yield* recieveIterator((deliver) => {
1454
+ listeners.push(deliver);
1455
+ return () => {
1456
+ listeners = listeners.filter((l) => l !== deliver);
1457
+ };
1458
+ });
1459
+ }
1460
+ async function sendAll(it) {
1461
+ await sendIterator((chunk) => void channel.invoke(chunk), (async function* () {
1462
+ try {
1463
+ iterators.push(it);
1464
+ yield* it;
1465
+ } finally {
1466
+ iterators = iterators.filter((i) => i !== it);
1467
+ }
1468
+ })());
1469
+ }
1470
+ return {
1471
+ start,
1472
+ close,
1473
+ cancel,
1474
+ recieveAll,
1475
+ sendAll
1476
+ };
1477
+ }
1478
+ //#endregion
1479
+ //#region src/http/http-send-recieve.ts
1480
+ async function* httpToIterator(envelopeOrPromise) {
1481
+ const { options, content } = await envelopeOrPromise;
1482
+ yield new TextEncoder().encode(JSON.stringify(options));
1483
+ yield* content;
1484
+ }
1485
+ async function httpFromIterator(iterable) {
1486
+ const it = (await iterable)[Symbol.asyncIterator]();
1487
+ const { done, value } = await it.next();
1488
+ let options = {};
1489
+ if (!done && value) {
1490
+ const str = new TextDecoder().decode(value);
1491
+ options = JSON.parse(str);
1492
+ }
1493
+ return {
1494
+ options,
1495
+ content: { [Symbol.asyncIterator]() {
1496
+ return it;
1497
+ } }
1498
+ };
1499
+ }
1500
+ /**
1501
+ * Ship a `Request` over a `MessageTarget` and await the `Response`, using this
1502
+ * package's own `sendStream` transport.
1503
+ *
1504
+ * @deprecated Prefer the port stack in `@statewalker/webrun-rpc`: open a port
1505
+ * (`multiplexPort` over one pipe, or `transferPortMux` where the platform can
1506
+ * transfer a real `MessagePort`), turn it into a `Duplex` with
1507
+ * `duplexOverPort`, and drive HTTP over it with `httpFetch` from
1508
+ * `@statewalker/webrun-http-streams`.
1509
+ *
1510
+ * Same caveat as {@link handleHttpRequests}: the transport underneath this
1511
+ * helper has no backpressure, no per-stream timeout, and no chunking to a
1512
+ * transport's message ceiling. Kept for existing ServiceWorker setups.
1513
+ */
1514
+ async function sendHttpRequest(communicationPort, request) {
1515
+ return await newHttpClientStub(async (req) => {
1516
+ return await httpFromIterator(sendStream(communicationPort, httpToIterator(req)));
1517
+ })(request);
1518
+ }
1519
+ //#endregion
1520
+ //#region src/relay/split-service-url.ts
1521
+ /**
1522
+ * Splits a URL of the form `<base>/<separator><key>/<path>` into parts.
1523
+ * Example: `https://host/~FS/a/b` → `{ baseUrl: "https://host/~FS/", key: "FS", path: "a/b" }`.
1524
+ */
1525
+ function splitServiceUrl(url, separator = "~") {
1526
+ const str = `${url}`;
1527
+ const idx = str.indexOf(separator);
1528
+ let baseUrl = "";
1529
+ let key = "";
1530
+ let path = "";
1531
+ if (idx >= 0) {
1532
+ baseUrl = str.substring(0, idx + separator.length);
1533
+ str.substring(idx + separator.length).replace(/^([^/]+)/, (match, $1) => {
1534
+ baseUrl += match;
1535
+ if (baseUrl.length < str.length) baseUrl += "/";
1536
+ key = $1;
1537
+ path = str.substring(baseUrl.length);
1538
+ return "";
1539
+ });
1540
+ }
1541
+ return {
1542
+ url: str,
1543
+ key,
1544
+ baseUrl,
1545
+ path
1546
+ };
1547
+ }
1548
+ //#endregion
1549
+ //#region src/relay/index-sw.ts
1550
+ /**
1551
+ * Boots the relay ServiceWorker: routes fetches shaped `<origin>/~<key>/…` to
1552
+ * the client that registered `key`, and exposes REGISTER/UNREGISTER/CONNECT
1553
+ * channel calls used by the page-side relay client.
1554
+ */
1555
+ function startRelayServiceWorker(self) {
1556
+ const [register, clear] = newRegistry();
1557
+ if (typeof self.skipWaiting === "function") self.addEventListener("install", (e) => {
1558
+ e.waitUntil(self.skipWaiting());
1559
+ });
1560
+ if (self.clients && typeof self.clients.claim === "function") self.addEventListener("activate", (e) => {
1561
+ e.waitUntil(self.clients.claim());
1562
+ });
1563
+ const clientsRegistry = newClientsRegistry({ self });
1564
+ register(handleChannelCalls(self, "REGISTER", async (event, data) => {
1565
+ const source = event.source;
1566
+ if (!source) return false;
1567
+ const { key } = data;
1568
+ return await clientsRegistry.addClient(key, source);
1569
+ }));
1570
+ register(handleChannelCalls(self, "UNREGISTER", async (_event, data) => {
1571
+ const { key } = data;
1572
+ return await clientsRegistry.removeClient(key);
1573
+ }));
1574
+ register(handleChannelCalls(self, "CONNECT", async (_event, data, port) => {
1575
+ const { key } = data;
1576
+ const client = await clientsRegistry.getClient(key);
1577
+ if (!client) throw new Error(`Target client was not found. Target key: "${key}".`);
1578
+ return await callChannel(client, "CONNECT", data, port);
1579
+ }));
1580
+ const fetchListener = (event) => {
1581
+ const request = event.request;
1582
+ const params = splitServiceUrl(request.url);
1583
+ const { key } = params;
1584
+ if (!key) return;
1585
+ event.respondWith((async () => {
1586
+ try {
1587
+ const channel = new MessageChannel();
1588
+ const client = await clientsRegistry.getClient(key);
1589
+ if (!client) throw HttpError.errorResourceGone(params);
1590
+ if (!await callChannel(client, "CONNECT", {
1591
+ type: "http",
1592
+ key
1593
+ }, channel.port2)) throw HttpError.errorForbidden(params);
1594
+ return await sendHttpRequest(channel.port1, request);
1595
+ } catch (error) {
1596
+ const httpError = HttpError.fromError(error);
1597
+ const options = httpError.getResponseOptions(params);
1598
+ return new Response(JSON.stringify(options), {
1599
+ status: httpError.status ?? 500,
1600
+ statusText: httpError.statusText ?? "Internal Error",
1601
+ headers: { "Content-Type": "application/json" }
1602
+ });
1603
+ }
1604
+ })());
1605
+ };
1606
+ self.addEventListener("fetch", fetchListener);
1607
+ register(() => self.removeEventListener("fetch", fetchListener));
1608
+ return clear;
1609
+ }
1610
+ function newClientsRegistry({ self, key = "clientsIds" }) {
1611
+ let _index;
1612
+ async function loadClientsIndex() {
1613
+ if (!_index) {
1614
+ const entries = await get(key) ?? [];
1615
+ _index = Object.fromEntries(entries);
1616
+ }
1617
+ return _index;
1618
+ }
1619
+ async function storeClientsIndex() {
1620
+ const index = await loadClientsIndex();
1621
+ await set(key, Object.entries(index));
1622
+ return index;
1623
+ }
1624
+ async function addClient(clientKey, client) {
1625
+ const index = await loadClientsIndex();
1626
+ const clientId = client.id;
1627
+ if (index[clientKey] === clientId) return false;
1628
+ index[clientKey] = clientId;
1629
+ await storeClientsIndex();
1630
+ return true;
1631
+ }
1632
+ async function removeClient(clientKey) {
1633
+ const index = await loadClientsIndex();
1634
+ if (!(clientKey in index)) return false;
1635
+ delete index[clientKey];
1636
+ await storeClientsIndex();
1637
+ return true;
1638
+ }
1639
+ async function getClient(clientKey) {
1640
+ const index = await loadClientsIndex();
1641
+ const clientId = index[clientKey];
1642
+ if (!clientId) return void 0;
1643
+ const client = await self.clients.get(clientId);
1644
+ if (!client) {
1645
+ delete index[clientKey];
1646
+ await storeClientsIndex();
1647
+ }
1648
+ return client ?? void 0;
1649
+ }
1650
+ return {
1651
+ getClient,
1652
+ addClient,
1653
+ removeClient
1654
+ };
1655
+ }
1656
+ //#endregion
1657
+ //#region src/relay-sw.ts
1658
+ startRelayServiceWorker(self);
1659
+ //#endregion
1660
+ })();