@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/relay-sw.js CHANGED
@@ -23,8 +23,6 @@
23
23
  const payload = typeof error === "string" ? { message: error } : error;
24
24
  return Object.assign(new Error(payload.message), payload);
25
25
  }
26
- new TextEncoder();
27
- new TextDecoder();
28
26
  /**
29
27
  * The newAsyncGenerator function creates async generators from callback-based initialization
30
28
  * functions, providing a bridge between imperative event handling and declarative async
@@ -177,7 +175,6 @@
177
175
  drainQueue();
178
176
  }
179
177
  }
180
- new TextEncoder();
181
178
  /**
182
179
  * The iterator ↔ `ReadableStream` boundary.
183
180
  *
@@ -282,6 +279,34 @@
282
279
  });
283
280
  }
284
281
  }
282
+ const DEFAULT_CHUNK_SIZE = 16384;
283
+ /**
284
+ * Curried `Duplex`-shaped transformer that splits incoming `Uint8Array`s into
285
+ * chunks no larger than `size` bytes. Empty input chunks are skipped; small
286
+ * input chunks pass through unchanged (zero-copy `subarray` views are used
287
+ * when splitting, so no allocation per chunk).
288
+ *
289
+ * Use to respect transport MTUs before reaching `channel.send`. Reassembly on
290
+ * the receive side is not needed — consumers iterate a continuous byte stream.
291
+ */
292
+ function toChunks(size = DEFAULT_CHUNK_SIZE) {
293
+ if (!(Number.isInteger(size) && size > 0)) throw new RangeError(`toChunks: size must be a positive integer, got ${size}`);
294
+ return async function* (input) {
295
+ for await (const block of input) {
296
+ if (block.byteLength === 0) continue;
297
+ if (block.byteLength <= size) {
298
+ yield block;
299
+ continue;
300
+ }
301
+ let offset = 0;
302
+ while (offset < block.byteLength) {
303
+ const end = Math.min(offset + size, block.byteLength);
304
+ yield block.subarray(offset, end);
305
+ offset = end;
306
+ }
307
+ }
308
+ };
309
+ }
285
310
  //#endregion
286
311
  //#region ../webrun-http-streams/dist/index.js
287
312
  const CR = 13;
@@ -419,8 +444,8 @@
419
444
  const NEWLINE = 10;
420
445
  /** Mirrors the HTTP/1.1 codec's default `maxHeaderBytes`. */
421
446
  const MAX_ENVELOPE_BYTES = 65536;
422
- const encoder$1 = new TextEncoder();
423
- const decoder = new TextDecoder();
447
+ const encoder$1 = /* @__PURE__ */ new TextEncoder();
448
+ const decoder = /* @__PURE__ */ new TextDecoder();
424
449
  /**
425
450
  * Encode an HTTP envelope plus optional body as one continuous byte stream:
426
451
  *
@@ -674,15 +699,15 @@
674
699
  };
675
700
  return { kind: "none" };
676
701
  }
677
- const CRLF = new Uint8Array([13, 10]);
678
- const LAST_CHUNK = new Uint8Array([
702
+ const CRLF = /* @__PURE__ */ new Uint8Array([13, 10]);
703
+ const LAST_CHUNK = /* @__PURE__ */ new Uint8Array([
679
704
  48,
680
705
  13,
681
706
  10,
682
707
  13,
683
708
  10
684
709
  ]);
685
- const encoder = new TextEncoder();
710
+ const encoder = /* @__PURE__ */ new TextEncoder();
686
711
  /**
687
712
  * Chunk sizes are written in HEXADECIMAL — a 21-byte chunk is `15`. Writing
688
713
  * them in decimal is the defect note 15 found in @libp2p/http, and it is the
@@ -987,7 +1012,7 @@
987
1012
  decodeResponse: (input, o) => decodeResponse(input, opts, o.method)
988
1013
  };
989
1014
  }
990
- const httpCodec = newHttpCodec();
1015
+ const httpCodec = /* @__PURE__ */ newHttpCodec();
991
1016
  /**
992
1017
  * Dispatches on byte 0. The formats are self-identifying — a JSON envelope
993
1018
  * always begins `{`, which is not a token character and so can never begin an
@@ -1033,10 +1058,163 @@
1033
1058
  }
1034
1059
  };
1035
1060
  }
1036
- newSniffingCodec({
1061
+ /**
1062
+ * Writes HTTP/1.1; accepts HTTP/1.1 or the legacy JSON envelope. Used whenever
1063
+ * no `codec` option is supplied.
1064
+ */
1065
+ const defaultCodec = /* @__PURE__ */ newSniffingCodec({
1037
1066
  write: httpCodec,
1038
1067
  accept: [httpCodec, jsonEnvelopeCodec]
1039
1068
  });
1069
+ /** Carries the serialized JS error between two webrun peers. */
1070
+ const PEER_ERROR_HEADER = "x-webrun-error";
1071
+ /**
1072
+ * `output` is the `Duplex` call's own generator — one logical call, per the
1073
+ * `Duplex` contract in `@statewalker/webrun-streams`: "Consumer `.return()`
1074
+ * on the output → producer's `finally` runs." On a mux transport
1075
+ * (`emulateMux`), that `finally` is what frees the stream-table slot; skip it
1076
+ * and every peer-error response leaks one slot, unboundedly, until the mux
1077
+ * itself is exhausted (`maxStreams` reached, every further call rejected).
1078
+ *
1079
+ * Cancelling `output` here — not inside the codec's own decode logic — is
1080
+ * deliberate. `codec.decodeResponse` already pulled from `output` to read the
1081
+ * head before this function runs, so unlike the body case above there's no
1082
+ * suspended-start no-op to worry about. And it's safe specifically *because*
1083
+ * this is the client's own response-only generator: the request was already
1084
+ * fully sent before we got here, so there is nothing left to write on it.
1085
+ * The equivalent is NOT safe inside `src/http1/decode.ts`'s `ByteReader` —
1086
+ * that code also runs when a caller wires `codec.decodeRequest`/
1087
+ * `decodeResponse` directly onto a raw bidirectional socket (see
1088
+ * `tests/http1-node-interop.test.ts`), where the *same* object is read from
1089
+ * and then written back to (a server reads the request, then replies on the
1090
+ * same socket); cancelling the read side there tears down the whole
1091
+ * connection out from under the pending write. That was tried and reverted —
1092
+ * see the Task 11 report for the "socket hang up" failure it caused.
1093
+ */
1094
+ async function throwIfPeerError(result, output) {
1095
+ const found = result.envelope.headers.find(([k]) => k.toLowerCase() === PEER_ERROR_HEADER);
1096
+ if (!found) return;
1097
+ await discard(result.body);
1098
+ try {
1099
+ await output.return?.(void 0);
1100
+ } catch {}
1101
+ let payload;
1102
+ try {
1103
+ payload = JSON.parse(found[1]);
1104
+ } catch {
1105
+ payload = { message: found[1] };
1106
+ }
1107
+ throw deserializeError(payload);
1108
+ }
1109
+ /**
1110
+ * Initiate an HTTP call over a `Duplex`. The caller's `call: Duplex` is
1111
+ * obtained from any `webrun-streams-*` adapter's `connect`. Returns the
1112
+ * response envelope and an async iterable over the response body bytes.
1113
+ *
1114
+ * The call is one logical Duplex invocation; multiplexing of concurrent
1115
+ * calls is the adapter's concern (native or `emulateMux`).
1116
+ */
1117
+ async function httpFetch(call, env, body, options = {}) {
1118
+ const codec = options.codec ?? defaultCodec;
1119
+ const { signal } = options;
1120
+ if (signal?.aborted) throw abortReason$1(signal);
1121
+ const output = call(codec.encodeRequest(env, body));
1122
+ let released;
1123
+ const release = () => {
1124
+ released ??= (async () => {
1125
+ try {
1126
+ await output.return?.(void 0);
1127
+ } catch {}
1128
+ })();
1129
+ return released;
1130
+ };
1131
+ let finished = false;
1132
+ const finish = () => {
1133
+ if (finished || released) return;
1134
+ finished = true;
1135
+ if (signal?.aborted) {
1136
+ release();
1137
+ return;
1138
+ }
1139
+ const onAbort = () => void release();
1140
+ signal?.addEventListener("abort", onAbort, { once: true });
1141
+ drain(output).finally(() => signal?.removeEventListener("abort", onAbort));
1142
+ };
1143
+ let decoded;
1144
+ try {
1145
+ decoded = await untilAborted(codec.decodeResponse(output, { method: env.method }), signal);
1146
+ } catch (error) {
1147
+ if (signal?.aborted) release();
1148
+ else await release();
1149
+ throw error;
1150
+ }
1151
+ const result = {
1152
+ envelope: decoded.envelope,
1153
+ body: releasingOnExit(decoded.body, finish, release),
1154
+ release,
1155
+ finish
1156
+ };
1157
+ await throwIfPeerError(result, output);
1158
+ return result;
1159
+ }
1160
+ /** `promise`, rejected with the signal's reason if it aborts first. */
1161
+ function untilAborted(promise, signal) {
1162
+ if (!signal) return promise;
1163
+ return new Promise((resolve, reject) => {
1164
+ const onAbort = () => reject(abortReason$1(signal));
1165
+ if (signal.aborted) return onAbort();
1166
+ signal.addEventListener("abort", onAbort, { once: true });
1167
+ promise.then((value) => {
1168
+ signal.removeEventListener("abort", onAbort);
1169
+ resolve(value);
1170
+ }, (error) => {
1171
+ signal.removeEventListener("abort", onAbort);
1172
+ reject(error);
1173
+ });
1174
+ });
1175
+ }
1176
+ /** The signal's reason as an `Error` (`AbortError` when it gave none). */
1177
+ function abortReason$1(signal) {
1178
+ const reason = signal.reason;
1179
+ if (reason instanceof Error) return reason;
1180
+ const err = new Error(reason === void 0 ? "Aborted" : String(reason));
1181
+ err.name = "AbortError";
1182
+ return err;
1183
+ }
1184
+ /**
1185
+ * `body`, ending the call however it is left: read to its end, or left early.
1186
+ *
1187
+ * The body the codec hands back is a generator of its own over a `ByteReader`,
1188
+ * and its ending never reaches the call's `output` (see `throwIfPeerError` for
1189
+ * why the codec must not do that itself). A caller that stopped reading — an
1190
+ * aborted `fetch`, a cancelled response stream — left the peer's producer
1191
+ * parked forever; and one that read the body to its end left the call itself
1192
+ * open, which on a multiplexed transport is one port per exchange until the
1193
+ * multiplexer refuses to open more (`maxPorts`).
1194
+ *
1195
+ * Left early, the call is abandoned (`.return()`): the peer's producer is
1196
+ * released. Read to its end, the call is not cut short but read to ITS end, in
1197
+ * the background: the peer ends it once its side of the exchange is over,
1198
+ * which may be later than the response — a handler that answered before it
1199
+ * read the request body is still receiving it (`HttpDataHandlerResult.settled`),
1200
+ * and abandoning the call would abort that upload.
1201
+ */
1202
+ async function* releasingOnExit(body, finish, release) {
1203
+ let completed = false;
1204
+ try {
1205
+ yield* body;
1206
+ completed = true;
1207
+ } finally {
1208
+ if (completed) finish();
1209
+ else await release();
1210
+ }
1211
+ }
1212
+ /** Reads `output` to its end, discarding what is left, ignoring a failure. */
1213
+ async function drain(output) {
1214
+ try {
1215
+ for (let r = await output.next(); !r.done; r = await output.next());
1216
+ } catch {}
1217
+ }
1040
1218
  /**
1041
1219
  * The one place that knows a runtime may not implement request body streams,
1042
1220
  * and the buffering both fallbacks need. `fetch.ts` and `http-stubs.ts` each
@@ -1142,6 +1320,118 @@
1142
1320
  return new Response(toReadableStream(result.content[Symbol.asyncIterator]()), responseOptions);
1143
1321
  };
1144
1322
  }
1323
+ /**
1324
+ * Connection-scoped headers. The codec surfaces them verbatim (decision 12),
1325
+ * but they are meaningless to a `Request`/`Response`, and re-emitting them
1326
+ * from a relay would corrupt its framing.
1327
+ */
1328
+ const HOP_BY_HOP = /* @__PURE__ */ new Set([
1329
+ "connection",
1330
+ "host",
1331
+ "keep-alive",
1332
+ "proxy-authenticate",
1333
+ "proxy-authorization",
1334
+ "te",
1335
+ "trailer",
1336
+ "transfer-encoding",
1337
+ "upgrade"
1338
+ ]);
1339
+ function forwardableHeaders(headers) {
1340
+ return headers.filter(([name]) => !HOP_BY_HOP.has(name.toLowerCase()));
1341
+ }
1342
+ function headersToArray(headers) {
1343
+ const out = [];
1344
+ headers.forEach((value, key) => {
1345
+ out.push([key, value]);
1346
+ });
1347
+ return out;
1348
+ }
1349
+ async function* readableToAsyncIterable(stream) {
1350
+ if (!stream) return;
1351
+ const reader = stream.getReader();
1352
+ let consumed = false;
1353
+ try {
1354
+ while (true) {
1355
+ const { done, value } = await reader.read();
1356
+ if (done) {
1357
+ consumed = true;
1358
+ return;
1359
+ }
1360
+ if (value) yield value;
1361
+ }
1362
+ } finally {
1363
+ if (!consumed) try {
1364
+ await reader.cancel();
1365
+ } catch {}
1366
+ try {
1367
+ reader.releaseLock();
1368
+ } catch {}
1369
+ }
1370
+ }
1371
+ function asyncIterableToReadable(iter) {
1372
+ const it = iter[Symbol.asyncIterator]();
1373
+ return new ReadableStream({
1374
+ async pull(controller) {
1375
+ try {
1376
+ const { done, value } = await it.next();
1377
+ if (done) {
1378
+ controller.close();
1379
+ return;
1380
+ }
1381
+ controller.enqueue(value);
1382
+ } catch (err) {
1383
+ controller.error(err);
1384
+ }
1385
+ },
1386
+ async cancel() {
1387
+ await it.return?.();
1388
+ }
1389
+ });
1390
+ }
1391
+ /**
1392
+ * Run a `Request` through a `Duplex` call and reconstruct the `Response` on
1393
+ * the other side. The request's `signal` is plumbed into the body iteration —
1394
+ * abort terminates the underlying call.
1395
+ */
1396
+ async function fetchOverDuplex(call, request, options = {}) {
1397
+ if (request.signal?.aborted) throw abortReason$1(request.signal);
1398
+ const env = {
1399
+ url: request.url,
1400
+ method: request.method,
1401
+ headers: headersToArray(request.headers)
1402
+ };
1403
+ let body;
1404
+ if (request.body != null) body = readableToAsyncIterable(request.body);
1405
+ else if (!supportsRequestStreams()) {
1406
+ const buffered = new Uint8Array(await request.arrayBuffer());
1407
+ if (buffered.byteLength > 0) body = [buffered];
1408
+ }
1409
+ const { envelope, body: respBody, release, finish } = await httpFetch(call, env, body, {
1410
+ ...options,
1411
+ signal: request.signal ?? void 0
1412
+ });
1413
+ const responseInit = {
1414
+ status: envelope.status,
1415
+ statusText: envelope.statusText,
1416
+ headers: forwardableHeaders(envelope.headers)
1417
+ };
1418
+ if (request.method === "HEAD" || request.method === "OPTIONS" || NULL_BODY_STATUSES.has(envelope.status)) {
1419
+ if (finish) finish();
1420
+ else await release?.();
1421
+ return new Response(null, responseInit);
1422
+ }
1423
+ return new Response(asyncIterableToReadable(withAbort(respBody, request.signal)), responseInit);
1424
+ }
1425
+ async function* withAbort(iter, signal) {
1426
+ if (!signal) {
1427
+ yield* iter;
1428
+ return;
1429
+ }
1430
+ for await (const chunk of iter) {
1431
+ if (signal.aborted) throw abortReason$1(signal);
1432
+ yield chunk;
1433
+ }
1434
+ }
1145
1435
  var HttpError = class HttpError extends Error {
1146
1436
  status;
1147
1437
  statusText;
@@ -1254,6 +1544,32 @@
1254
1544
  }
1255
1545
  //#endregion
1256
1546
  //#region src/core/data-calls.ts
1547
+ const TRANSFER = Symbol.for("webrun-http-browser:transfer");
1548
+ /**
1549
+ * A channel call's result that carries transferables, a `MessagePort` say:
1550
+ * return `withTransfer({ port }, [port])` from a `handleChannelCalls` handler
1551
+ * and `callChannel` resolves with `{ port }`.
1552
+ */
1553
+ function withTransfer(value, transfer) {
1554
+ return {
1555
+ [TRANSFER]: true,
1556
+ value,
1557
+ transfer
1558
+ };
1559
+ }
1560
+ function isTransferResult(value) {
1561
+ return typeof value === "object" && value !== null && TRANSFER in value;
1562
+ }
1563
+ /** Splits a handler's result into the value to post and its transfer list. */
1564
+ function unwrapTransfer(result) {
1565
+ return isTransferResult(result) ? {
1566
+ value: result.value,
1567
+ transfer: result.transfer
1568
+ } : {
1569
+ value: result,
1570
+ transfer: []
1571
+ };
1572
+ }
1257
1573
  function callChannel(target, callType, params, ...transfers) {
1258
1574
  return new Promise((resolve, reject) => {
1259
1575
  const channel = new MessageChannel();
@@ -1273,12 +1589,14 @@
1273
1589
  if (!event.data || event.data.type !== callType) return;
1274
1590
  const [port, ...transfers] = event.ports ?? [];
1275
1591
  const response = {};
1592
+ let transfer = [];
1276
1593
  try {
1277
- response.result = await handler(event, event.data.params, ...transfers);
1594
+ const result = await handler(event, event.data.params, ...transfers);
1595
+ ({value: response.result, transfer} = unwrapTransfer(result));
1278
1596
  } catch (error) {
1279
1597
  response.error = serializeError(error);
1280
1598
  }
1281
- port?.postMessage(response);
1599
+ port?.postMessage(response, transfer);
1282
1600
  };
1283
1601
  target.addEventListener("message", listener);
1284
1602
  target.start?.();
@@ -1335,6 +1653,899 @@
1335
1653
  });
1336
1654
  }
1337
1655
  //#endregion
1656
+ //#region ../webrun-rpc/dist/index.js
1657
+ const closeSignals = /* @__PURE__ */ new WeakMap();
1658
+ /**
1659
+ * Internal: register a port's close signal. Called once by `bindBytesToPort`.
1660
+ *
1661
+ * @internal
1662
+ */
1663
+ function setPortCloseSignal(port, signal) {
1664
+ closeSignals.set(port, signal);
1665
+ }
1666
+ /**
1667
+ * Return the AbortSignal that fires when `port`'s transport closes, or
1668
+ * `undefined` if `port` is not transport-backed (e.g., a raw
1669
+ * `MessageChannel().port1`).
1670
+ */
1671
+ function getPortCloseSignal(port) {
1672
+ return closeSignals.get(port);
1673
+ }
1674
+ /**
1675
+ * Pass as `timeout` to install no deadline at all. Used by the stream tier,
1676
+ * where the deadline belongs to the stream rather than to one chunk (spec D8):
1677
+ * a slow consumer is throttled, never failed.
1678
+ */
1679
+ const NO_TIMEOUT = Number.POSITIVE_INFINITY;
1680
+ /**
1681
+ * Asynchronous request/response over any `MessageTarget`.
1682
+ *
1683
+ * Sends `params` to the peer listening with `listenPort`, waits up to
1684
+ * `timeout` ms for a matching reply, and either resolves with the result or
1685
+ * rejects with the deserialised error.
1686
+ */
1687
+ function callPort(port, params, { timeout = 1e3, channelName = "", log = () => {}, newCallId = () => `call-${Date.now()}-${String(Math.random()).substring(2)}`, signal } = {}) {
1688
+ const callId = newCallId();
1689
+ log("[callPort]", {
1690
+ channelName,
1691
+ callId,
1692
+ params
1693
+ });
1694
+ const combinedSignal = combineSignals(signal, getPortCloseSignal(port));
1695
+ let timerId;
1696
+ let onMessage;
1697
+ let onAbort;
1698
+ const promise = new Promise((resolve, reject) => {
1699
+ if (combinedSignal?.aborted) {
1700
+ reject(abortReason(combinedSignal));
1701
+ return;
1702
+ }
1703
+ if (Number.isFinite(timeout) && timeout > 0) timerId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Call timeout. CallId: "${callId}".`)), timeout);
1704
+ onMessage = (event) => {
1705
+ const data = event.data;
1706
+ if (!data) return;
1707
+ if (data.channelName !== channelName) return;
1708
+ if (data.callId !== callId) return;
1709
+ if (data.type === "response:error") reject(deserializeError(data.error));
1710
+ else if (data.type === "response:result") resolve(data.result);
1711
+ };
1712
+ port.addEventListener("message", onMessage);
1713
+ if (combinedSignal) {
1714
+ onAbort = () => reject(abortReason(combinedSignal));
1715
+ combinedSignal.addEventListener("abort", onAbort, { once: true });
1716
+ }
1717
+ });
1718
+ promise.catch(() => {}).finally(() => {
1719
+ if (timerId !== void 0) clearTimeout(timerId);
1720
+ if (onMessage) port.removeEventListener("message", onMessage);
1721
+ if (onAbort && combinedSignal) combinedSignal.removeEventListener("abort", onAbort);
1722
+ });
1723
+ port.postMessage({
1724
+ type: "request",
1725
+ channelName,
1726
+ callId,
1727
+ params
1728
+ });
1729
+ return promise;
1730
+ }
1731
+ function abortReason(signal) {
1732
+ const reason = signal.reason;
1733
+ if (reason instanceof Error) return reason;
1734
+ const err = new Error(reason === void 0 ? "Aborted" : String(reason));
1735
+ err.name = "AbortError";
1736
+ return err;
1737
+ }
1738
+ function combineSignals(...signals) {
1739
+ const live = signals.filter((s) => s !== void 0);
1740
+ if (live.length === 0) return void 0;
1741
+ if (live.length === 1) return live[0];
1742
+ return AbortSignal.any(live);
1743
+ }
1744
+ /**
1745
+ * Installs `handler` as the server side of a `callPort` / `listenPort`
1746
+ * request/response pair on `port`.
1747
+ *
1748
+ * Returns a cleanup function that removes the listener.
1749
+ */
1750
+ function listenPort(port, handler, { channelName = "", log = () => {} } = {}) {
1751
+ const onMessage = async (event) => {
1752
+ const data = event.data;
1753
+ if (!data || data.channelName !== channelName || data.type !== "request") return;
1754
+ const { callId, params } = data;
1755
+ log("[listenPort]", {
1756
+ channelName,
1757
+ callId,
1758
+ params
1759
+ });
1760
+ let result;
1761
+ let error;
1762
+ let type;
1763
+ try {
1764
+ result = await handler(params);
1765
+ type = "response:result";
1766
+ } catch (e) {
1767
+ error = serializeError(e);
1768
+ type = "response:error";
1769
+ }
1770
+ port.postMessage({
1771
+ callId,
1772
+ channelName,
1773
+ type,
1774
+ result,
1775
+ error
1776
+ });
1777
+ };
1778
+ port.addEventListener("message", onMessage);
1779
+ return () => port.removeEventListener("message", onMessage);
1780
+ }
1781
+ /**
1782
+ * Wraps an async iterable so that an `AbortSignal` firing causes the wrapper
1783
+ * to return cleanly, forwarding `return()` to the underlying iterator so the
1784
+ * producer (e.g., a user-supplied generator) sees its own `finally` blocks
1785
+ * run immediately rather than waiting for the next yield.
1786
+ */
1787
+ async function* throughAbort(input, signal) {
1788
+ const iter = input[Symbol.asyncIterator] ? input[Symbol.asyncIterator]() : input[Symbol.iterator]();
1789
+ const onAbort = () => {
1790
+ iter.return?.(void 0);
1791
+ };
1792
+ if (signal.aborted) {
1793
+ iter.return?.(void 0);
1794
+ return;
1795
+ }
1796
+ signal.addEventListener("abort", onAbort, { once: true });
1797
+ try {
1798
+ while (true) {
1799
+ const r = await iter.next();
1800
+ if (r.done) return;
1801
+ if (signal.aborted) return;
1802
+ yield r.value;
1803
+ }
1804
+ } finally {
1805
+ signal.removeEventListener("abort", onAbort);
1806
+ }
1807
+ }
1808
+ /**
1809
+ * Makes `target` disposable with `await using`: installs `dispose` as its
1810
+ * `[Symbol.asyncDispose]`, where the runtime defines the symbol. Hand-written
1811
+ * iterators lose what a native generator gets from `AsyncIteratorPrototype`;
1812
+ * this gives it back. A no-op where the symbol is missing. Kept off the
1813
+ * declared types, which would require consumers to compile with the
1814
+ * `esnext.disposable` lib.
1815
+ */
1816
+ function asyncDisposable$1(target, dispose) {
1817
+ const asyncDispose = Symbol.asyncDispose;
1818
+ if (asyncDispose && !(asyncDispose in target)) Object.defineProperty(target, asyncDispose, {
1819
+ value: async () => {
1820
+ await dispose();
1821
+ },
1822
+ configurable: true,
1823
+ writable: true
1824
+ });
1825
+ return target;
1826
+ }
1827
+ /**
1828
+ * `gen`, except that `return()` and `throw()` take effect at once.
1829
+ *
1830
+ * On an async generator both are queued behind a `next()` that is still
1831
+ * pending: a consumer that gives up on a stream while it waits for the peer's
1832
+ * next chunk — an aborted fetch whose response head has not come, say — cannot
1833
+ * end it until that chunk arrives, which for a peer that never answers is
1834
+ * never. The stream's `finally` (which closes its port and tells the peer)
1835
+ * then never runs, and on a multiplexer the port is kept for good.
1836
+ *
1837
+ * So `abandon` runs first, synchronously: it must make the pending `next()`
1838
+ * settle (abort the stream), which then resolves done, after which the
1839
+ * generator's own `return()` / `throw()` proceeds as usual. On a generator
1840
+ * suspended at a `yield` it is the same ending, a step earlier. `abandon` runs once, whichever comes first.
1841
+ */
1842
+ function returningAtOnce(gen, abandon) {
1843
+ let abandoned = false;
1844
+ const giveUp = (reason) => {
1845
+ if (abandoned) return;
1846
+ abandoned = true;
1847
+ abandon(reason);
1848
+ };
1849
+ const wrapped = {
1850
+ next: (...args) => gen.next(...args).catch((error) => {
1851
+ if (abandoned) return {
1852
+ done: true,
1853
+ value: void 0
1854
+ };
1855
+ throw error;
1856
+ }),
1857
+ return(value) {
1858
+ giveUp();
1859
+ return gen.return(value);
1860
+ },
1861
+ throw(error) {
1862
+ giveUp(error);
1863
+ return gen.throw(error);
1864
+ },
1865
+ [Symbol.asyncIterator]() {
1866
+ return wrapped;
1867
+ }
1868
+ };
1869
+ return asyncDisposable$1(wrapped, () => wrapped.return(void 0));
1870
+ }
1871
+ /**
1872
+ * The `type` of the out-of-band notice a side posts when it abandons a stream.
1873
+ *
1874
+ * Layer 1's `close` is not observable to layer 2 — a closed virtual port drops
1875
+ * its listeners silently and is indistinguishable from a working port nobody
1876
+ * is answering — so the peer would otherwise wait forever. Exported because
1877
+ * tests and adapters assert on it.
1878
+ */
1879
+ const STREAM_ABORT = "webrun-rpc:stream-abort";
1880
+ /** Caller's input travels on this channel; the handler listens on it. */
1881
+ const CHANNEL_IN = "in";
1882
+ /** The handler's output travels on this channel; the caller listens on it. */
1883
+ const CHANNEL_OUT = "out";
1884
+ /**
1885
+ * One port in, one `Duplex` out (spec D9).
1886
+ *
1887
+ * The returned `Duplex` runs a single stream on `port`: the caller's `input`
1888
+ * is sent chunk by chunk with `callPort`, and the handler's output arrives the
1889
+ * same way on the other channel. Within each direction the next chunk is never
1890
+ * sent until the previous one has been delivered *and* pulled past by the
1891
+ * consumer (spec D11) — the reply to a chunk call *is* the confirmation, and
1892
+ * `listenPort` withholds it until then.
1893
+ *
1894
+ * A stream port carries exactly one invocation. To make several calls, open
1895
+ * several ports: `mux.openPort({ kind: "stream" })` per call.
1896
+ */
1897
+ function duplexOverPort(port, options = {}) {
1898
+ return (input) => runCallerSide(port, input, options);
1899
+ }
1900
+ function runCallerSide(port, input, options) {
1901
+ const controller = new AbortController();
1902
+ const notice = installAbortNotice(port, controller);
1903
+ abortOnPortClose(port, controller);
1904
+ const clock = installStreamTimeout(controller, options.timeout);
1905
+ const inbound = receiveChunks(port, CHANNEL_OUT, controller, clock.touch);
1906
+ const pump = sendChunks(port, CHANNEL_IN, input, options, controller.signal, clock.touch);
1907
+ pump.catch(() => {});
1908
+ return returningAtOnce((async function* () {
1909
+ try {
1910
+ yield* inbound.stream;
1911
+ } finally {
1912
+ if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the caller abandoned the stream"));
1913
+ notice.post();
1914
+ notice.stop();
1915
+ clock.stop();
1916
+ inbound.stop();
1917
+ await pump.catch(() => {});
1918
+ try {
1919
+ await port.close?.();
1920
+ } catch {}
1921
+ }
1922
+ })(), () => {
1923
+ if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the caller abandoned the stream"));
1924
+ });
1925
+ }
1926
+ /**
1927
+ * Listens for the peer's abort notice, and can post our own. The notice is a
1928
+ * plain message with no `channelName` and a `type` that is not `"request"`,
1929
+ * so neither `callPort` nor `listenPort` reacts to it, and it carries no
1930
+ * numeric `id`, so `structuredCodec` never mistakes it for a layer 1 envelope.
1931
+ */
1932
+ function installAbortNotice(port, controller) {
1933
+ const onMessage = (event) => {
1934
+ const data = event.data;
1935
+ if (!data || data.type !== "webrun-rpc:stream-abort") return;
1936
+ if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the peer abandoned the stream"));
1937
+ };
1938
+ port.addEventListener("message", onMessage);
1939
+ let posted = false;
1940
+ return {
1941
+ post() {
1942
+ if (posted) return;
1943
+ posted = true;
1944
+ try {
1945
+ port.postMessage({ type: STREAM_ABORT });
1946
+ } catch {}
1947
+ },
1948
+ stop() {
1949
+ port.removeEventListener("message", onMessage);
1950
+ }
1951
+ };
1952
+ }
1953
+ /**
1954
+ * Aborts the stream when its port closes underneath it — the multiplexer was
1955
+ * closed, or the peer closed the port — for ports that report it (see
1956
+ * `getPortCloseSignal`). Without this a stream waiting for the peer's next
1957
+ * chunk would wait forever on a port that can no longer deliver one: the
1958
+ * outbound half's `callPort` already fails on the close signal, but nothing
1959
+ * failed the inbound half.
1960
+ */
1961
+ function abortOnPortClose(port, controller) {
1962
+ const closed = getPortCloseSignal(port);
1963
+ if (!closed) return;
1964
+ const onClose = () => {
1965
+ if (!controller.signal.aborted) controller.abort(closed.reason);
1966
+ };
1967
+ if (closed.aborted) {
1968
+ onClose();
1969
+ return;
1970
+ }
1971
+ closed.addEventListener("abort", onClose, { once: true });
1972
+ controller.signal.addEventListener("abort", () => closed.removeEventListener("abort", onClose), { once: true });
1973
+ }
1974
+ /**
1975
+ * The per-stream inactivity timeout (spec D8). Reset by any chunk in either
1976
+ * direction; elapsing aborts the stream. Unset, zero or non-finite installs no
1977
+ * timer at all, which is the default: a slow consumer is throttled, not failed.
1978
+ */
1979
+ function installStreamTimeout(controller, timeout) {
1980
+ if (timeout === void 0 || !Number.isFinite(timeout) || timeout <= 0) return {
1981
+ touch() {},
1982
+ stop() {}
1983
+ };
1984
+ let timer;
1985
+ let stopped = false;
1986
+ const arm = () => {
1987
+ timer = setTimeout(() => {
1988
+ if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error(`webrun-rpc: stream idle for ${timeout} ms`));
1989
+ }, timeout);
1990
+ };
1991
+ arm();
1992
+ return {
1993
+ touch() {
1994
+ if (stopped) return;
1995
+ if (timer !== void 0) clearTimeout(timer);
1996
+ arm();
1997
+ },
1998
+ stop() {
1999
+ stopped = true;
2000
+ if (timer !== void 0) clearTimeout(timer);
2001
+ timer = void 0;
2002
+ }
2003
+ };
2004
+ }
2005
+ /**
2006
+ * The receiving half of one direction.
2007
+ *
2008
+ * The `listenPort` listener is installed **eagerly**, not lazily inside
2009
+ * `recieveIterator`'s installer, because a handler that never drains its input
2010
+ * would otherwise leave the peer's chunk calls with nobody to answer them. If
2011
+ * the local consumer has not started iterating, an inbound chunk waits for it —
2012
+ * which is the correct backpressure, and different from having no listener.
2013
+ */
2014
+ function receiveChunks(port, channelName, controller, touch) {
2015
+ let deliver;
2016
+ const waiting = [];
2017
+ let finished = false;
2018
+ let outstanding = false;
2019
+ let poison;
2020
+ let resolveEnded = () => {};
2021
+ const ended = new Promise((resolve) => {
2022
+ resolveEnded = resolve;
2023
+ });
2024
+ let aborted = false;
2025
+ let abortReason;
2026
+ const ready = () => deliver || finished ? Promise.resolve() : new Promise((r) => waiting.push(r));
2027
+ const wake = () => {
2028
+ for (const r of waiting.splice(0)) r();
2029
+ };
2030
+ const off = listenPort(port, async ({ done, value, error }) => {
2031
+ touch();
2032
+ if (poison) throw poison;
2033
+ if (outstanding) {
2034
+ poison = /* @__PURE__ */ new Error("webrun-rpc: peer sent a second unconfirmed chunk; the stream port is closed");
2035
+ controller.abort(poison);
2036
+ setTimeout(() => {
2037
+ try {
2038
+ port.close?.();
2039
+ } catch {}
2040
+ }, 0);
2041
+ throw poison;
2042
+ }
2043
+ outstanding = true;
2044
+ try {
2045
+ await ready();
2046
+ if (finished) throw poison ?? /* @__PURE__ */ new Error("webrun-rpc: the stream is closed");
2047
+ await deliver?.({
2048
+ done,
2049
+ value,
2050
+ error: error ? deserializeError(error) : void 0
2051
+ });
2052
+ } finally {
2053
+ outstanding = false;
2054
+ }
2055
+ if (done) resolveEnded();
2056
+ }, { channelName });
2057
+ const detach = () => {
2058
+ finished = true;
2059
+ wake();
2060
+ off();
2061
+ controller.signal.removeEventListener("abort", onAbort);
2062
+ resolveEnded();
2063
+ };
2064
+ const onAbort = () => {
2065
+ aborted = true;
2066
+ abortReason = controller.signal.reason;
2067
+ finished = true;
2068
+ wake();
2069
+ deliver?.({
2070
+ done: true,
2071
+ error: abortReason
2072
+ });
2073
+ resolveEnded();
2074
+ };
2075
+ controller.signal.addEventListener("abort", onAbort, { once: true });
2076
+ return {
2077
+ stream: recieveIterator((d) => {
2078
+ if (aborted) {
2079
+ d({
2080
+ done: true,
2081
+ error: abortReason
2082
+ });
2083
+ return detach;
2084
+ }
2085
+ deliver = d;
2086
+ wake();
2087
+ return detach;
2088
+ }),
2089
+ stop: detach,
2090
+ ended
2091
+ };
2092
+ }
2093
+ /**
2094
+ * The sending half of one direction: one `callPort` per chunk, one call
2095
+ * outstanding at a time (spec D11/D12), with no per-chunk deadline (spec D8).
2096
+ */
2097
+ async function sendChunks(port, channelName, output, { maxMessageSize, log }, signal, touch) {
2098
+ const stream = throughAbort(maxMessageSize ? toChunks(maxMessageSize)(output) : output, signal);
2099
+ try {
2100
+ await sendIterator(async ({ done, value, error }) => {
2101
+ if (signal.aborted) return;
2102
+ const chunk = {
2103
+ done,
2104
+ value,
2105
+ error: error === void 0 ? void 0 : serializeError(error)
2106
+ };
2107
+ log?.("[duplexOverPort] send", {
2108
+ channelName,
2109
+ done,
2110
+ size: value?.byteLength
2111
+ });
2112
+ await callPort(port, chunk, {
2113
+ channelName,
2114
+ timeout: NO_TIMEOUT,
2115
+ signal
2116
+ });
2117
+ touch();
2118
+ }, stream);
2119
+ } catch (err) {
2120
+ if (signal.aborted) return;
2121
+ throw err;
2122
+ }
2123
+ }
2124
+ /**
2125
+ * One virtual port.
2126
+ *
2127
+ * `deliver` and `markClosed` are deliberately not on `port`: the consumer holds
2128
+ * only a `MessageTarget`, so it cannot forge inbound traffic or close the port
2129
+ * out from under the multiplexer's bookkeeping.
2130
+ */
2131
+ function newVirtualPort(send, requestClose) {
2132
+ const listeners = /* @__PURE__ */ new Set();
2133
+ let closed = false;
2134
+ const closing = new AbortController();
2135
+ const abort = (reason) => {
2136
+ if (closing.signal.aborted) return;
2137
+ closing.abort(reason ?? /* @__PURE__ */ new Error("webrun-rpc: the port was closed"));
2138
+ };
2139
+ const port = {
2140
+ addEventListener(_type, listener) {
2141
+ listeners.add(listener);
2142
+ },
2143
+ removeEventListener(_type, listener) {
2144
+ listeners.delete(listener);
2145
+ },
2146
+ postMessage(message, transfer) {
2147
+ if (closed) return;
2148
+ send(message, transfer);
2149
+ },
2150
+ close() {
2151
+ if (closed) return;
2152
+ closed = true;
2153
+ const notify = requestClose;
2154
+ listeners.clear();
2155
+ notify();
2156
+ abort();
2157
+ }
2158
+ };
2159
+ setPortCloseSignal(port, closing.signal);
2160
+ return {
2161
+ port,
2162
+ deliver(payload) {
2163
+ if (closed) return;
2164
+ const event = new MessageEvent("message", { data: payload });
2165
+ for (const listener of [...listeners]) try {
2166
+ listener(event);
2167
+ } catch {}
2168
+ },
2169
+ markClosed(reason) {
2170
+ closed = true;
2171
+ listeners.clear();
2172
+ abort(reason);
2173
+ },
2174
+ isClosed() {
2175
+ return closed;
2176
+ }
2177
+ };
2178
+ }
2179
+ /**
2180
+ * The message of the error that fails the calls still in flight on a
2181
+ * multiplexer when it is closed (`PortMux.close()`).
2182
+ */
2183
+ const MUX_CLOSED_MESSAGE = "webrun-rpc: the multiplexer was closed";
2184
+ /** Ceiling on concurrently open virtual ports. Bounds the id table only. */
2185
+ const DEFAULT_MAX_PORTS = 1024;
2186
+ /**
2187
+ * The default `PortMux`: emulates multiplexing over a single port.
2188
+ *
2189
+ * A transport that already multiplexes natively supplies its own `PortMux`
2190
+ * instead — this implementation is for transports that offer one pipe.
2191
+ */
2192
+ function multiplexPort(port, options) {
2193
+ const { codec, onPort, side = "initiator", maxPorts = DEFAULT_MAX_PORTS, maxMessageSize } = options;
2194
+ const open = /* @__PURE__ */ new Map();
2195
+ let nextId = side === "initiator" ? 0 : 1;
2196
+ let muxClosed = false;
2197
+ const post = (envelope, transfer) => {
2198
+ if (muxClosed) return;
2199
+ try {
2200
+ codec.post(port, envelope, transfer);
2201
+ } catch {}
2202
+ };
2203
+ const attach = (id) => {
2204
+ let self;
2205
+ self = newVirtualPort((payload, transfer) => post({
2206
+ type: "message",
2207
+ id,
2208
+ payload
2209
+ }, transfer), (reason) => {
2210
+ post({
2211
+ type: "close",
2212
+ id,
2213
+ reason
2214
+ });
2215
+ open.delete(id);
2216
+ self.markClosed();
2217
+ });
2218
+ open.set(id, self);
2219
+ return self;
2220
+ };
2221
+ const handleEnvelope = (envelope) => {
2222
+ if (muxClosed) return;
2223
+ if (envelope.type === "open") {
2224
+ if (open.has(envelope.id)) return;
2225
+ if (open.size >= maxPorts) {
2226
+ post({
2227
+ type: "close",
2228
+ id: envelope.id,
2229
+ reason: "max-ports"
2230
+ });
2231
+ return;
2232
+ }
2233
+ const handle = attach(envelope.id);
2234
+ let accepted = false;
2235
+ if (onPort) try {
2236
+ accepted = onPort(handle.port, envelope.meta) !== false;
2237
+ } catch {
2238
+ accepted = false;
2239
+ }
2240
+ if (!accepted) {
2241
+ open.delete(envelope.id);
2242
+ handle.markClosed(/* @__PURE__ */ new Error("webrun-rpc: the port was rejected"));
2243
+ post({
2244
+ type: "close",
2245
+ id: envelope.id,
2246
+ reason: "rejected"
2247
+ });
2248
+ }
2249
+ return;
2250
+ }
2251
+ const handle = open.get(envelope.id);
2252
+ if (envelope.type === "message") {
2253
+ if (!handle) return;
2254
+ handle.deliver(envelope.payload);
2255
+ return;
2256
+ }
2257
+ if (!handle) return;
2258
+ open.delete(envelope.id);
2259
+ handle.markClosed(/* @__PURE__ */ new Error("webrun-rpc: the peer closed the port"));
2260
+ };
2261
+ const listener = (event) => {
2262
+ const envelope = codec.read(event);
2263
+ if (envelope) handleEnvelope(envelope);
2264
+ };
2265
+ port.addEventListener("message", listener);
2266
+ port.start?.();
2267
+ return {
2268
+ maxMessageSize,
2269
+ async openPort(meta) {
2270
+ if (muxClosed) throw new Error("webrun-rpc: the multiplexer is closed");
2271
+ if (open.size >= maxPorts) throw new RangeError(`webrun-rpc: maxPorts (${maxPorts}) reached`);
2272
+ while (open.has(nextId)) nextId += 2;
2273
+ const id = nextId;
2274
+ nextId += 2;
2275
+ const handle = attach(id);
2276
+ post({
2277
+ type: "open",
2278
+ id,
2279
+ meta
2280
+ });
2281
+ return handle.port;
2282
+ },
2283
+ async close() {
2284
+ if (muxClosed) return;
2285
+ for (const [id, handle] of [...open]) {
2286
+ post({
2287
+ type: "close",
2288
+ id
2289
+ });
2290
+ open.delete(id);
2291
+ handle.markClosed(/* @__PURE__ */ new Error(MUX_CLOSED_MESSAGE));
2292
+ }
2293
+ muxClosed = true;
2294
+ port.removeEventListener("message", listener);
2295
+ await port.close?.();
2296
+ }
2297
+ };
2298
+ }
2299
+ /**
2300
+ * Announced with every port this pair opens. Layer 1 never reads `meta` — it is
2301
+ * here so a peer running something else over the same multiplexer can tell a
2302
+ * stream port from whatever else it hands out, and so a packet capture says
2303
+ * what the port is for.
2304
+ */
2305
+ const STREAM_META = { kind: "stream" };
2306
+ /**
2307
+ * One port source in, one caller `Duplex` out.
2308
+ *
2309
+ * A call is a port: the mux allocates one, `duplexOverPort` runs the single
2310
+ * invocation on it, and closing the stream closes the port. No stream ids, no
2311
+ * framing and no credit accounting live here — the mux owns the first, and
2312
+ * `duplexOverPort` owns the one-chunk window that makes memory bounded.
2313
+ */
2314
+ const connect = async ({ mux: factory, timeout }) => {
2315
+ const mux = await factory();
2316
+ const streamOptions = {
2317
+ maxMessageSize: mux.maxMessageSize,
2318
+ timeout
2319
+ };
2320
+ const call = (input) => {
2321
+ let stream;
2322
+ let abandoned = false;
2323
+ return returningAtOnce((async function* () {
2324
+ const port = await mux.openPort(STREAM_META);
2325
+ if (abandoned) {
2326
+ await port.close?.();
2327
+ return;
2328
+ }
2329
+ stream = duplexOverPort(port, streamOptions)(input);
2330
+ yield* stream;
2331
+ })(), () => {
2332
+ abandoned = true;
2333
+ stream?.return(void 0).catch(() => {});
2334
+ });
2335
+ };
2336
+ return {
2337
+ call,
2338
+ async close() {
2339
+ await mux.close();
2340
+ }
2341
+ };
2342
+ };
2343
+ /**
2344
+ * Ports over ONE PIPE OF BYTES — a `MessagePort`, a worker, a WebSocket.
2345
+ *
2346
+ * There is no second port to be had, so `multiplexPort`'s id table invents
2347
+ * them. Use this when the transport gives you exactly one channel.
2348
+ */
2349
+ function overPipe(pipe, options) {
2350
+ return (onPort) => multiplexPort(pipe, {
2351
+ ...options,
2352
+ onPort
2353
+ });
2354
+ }
2355
+ function isEnvelope(value) {
2356
+ if (typeof value !== "object" || value === null) return false;
2357
+ const candidate = value;
2358
+ if (typeof candidate.id !== "number") return false;
2359
+ if (!Number.isInteger(candidate.id) || candidate.id < 0) return false;
2360
+ return candidate.type === "open" || candidate.type === "message" || candidate.type === "close";
2361
+ }
2362
+ /**
2363
+ * For ports whose messages are structured values — a real `MessagePort`, a
2364
+ * worker, an iframe.
2365
+ *
2366
+ * Envelopes are posted as-is, so nothing is encoded, `ArrayBuffer`s move
2367
+ * zero-copy through the transfer list, and structured clone does the work the
2368
+ * platform already does well. This is a performance choice only: layer 2 may
2369
+ * not send anything a byte codec could not also carry.
2370
+ */
2371
+ const structuredCodec = {
2372
+ post(port, envelope, transfer) {
2373
+ if (transfer && transfer.length > 0) port.postMessage(envelope, transfer);
2374
+ else port.postMessage(envelope);
2375
+ },
2376
+ read(event) {
2377
+ return isEnvelope(event.data) ? event.data : void 0;
2378
+ }
2379
+ };
2380
+ //#endregion
2381
+ //#region src/link/async-dispose.ts
2382
+ /**
2383
+ * Makes `target` disposable with `await using`: installs `dispose` as its
2384
+ * `[Symbol.asyncDispose]`, where the runtime defines the symbol. Hand-written
2385
+ * iterators lose what a native generator gets from `AsyncIteratorPrototype`;
2386
+ * this gives it back. A no-op where the symbol is missing. Kept off the
2387
+ * declared types, which would require consumers to compile with the
2388
+ * `esnext.disposable` lib.
2389
+ */
2390
+ function asyncDisposable(target, dispose) {
2391
+ const asyncDispose = Symbol.asyncDispose;
2392
+ if (asyncDispose && !(asyncDispose in target)) Object.defineProperty(target, asyncDispose, {
2393
+ value: async () => {
2394
+ await dispose();
2395
+ },
2396
+ configurable: true,
2397
+ writable: true
2398
+ });
2399
+ return target;
2400
+ }
2401
+ //#endregion
2402
+ //#region src/link/http-link.ts
2403
+ /**
2404
+ * The version of the HTTP-over-`MessagePort` protocol this package speaks,
2405
+ * sent in every hand-shake that sets up a link. Version 1 was this package's
2406
+ * own `handleStreams` / `sendStream` (no backpressure); version 2 is
2407
+ * webrun-rpc's `connect` / `serve` over `overPipe` with webrun-http-streams'
2408
+ * `fetchOverDuplex` / `serveFetchOverDuplex`: one port per link, calls
2409
+ * multiplexed on it, each call a stream with a one-chunk window in both
2410
+ * directions, and cancellation that reaches the handler.
2411
+ */
2412
+ const HTTP_LINK_PROTOCOL = "webrun-http-link/2";
2413
+ /**
2414
+ * Why a request failed when its link went away under it: the far side (the
2415
+ * handler, or the ServiceWorker) was lost. The request may or may not have
2416
+ * been applied.
2417
+ */
2418
+ var LinkLostError = class extends Error {
2419
+ constructor(message = "The link was lost while this request was in flight") {
2420
+ super(`${message}; it may or may not have been applied.`);
2421
+ this.name = "LinkLostError";
2422
+ }
2423
+ };
2424
+ /**
2425
+ * Posted on a link's port by the calling end when it closes the link, so the
2426
+ * answering end can release it: a `MessagePort` never reports that its other
2427
+ * end is gone.
2428
+ */
2429
+ const LINK_CLOSE = "webrun-http:link-close";
2430
+ /** Opens the calling end of a link on `port` (one port per link). */
2431
+ async function connectHttpLink(port, { streamTimeout, maxPorts } = {}) {
2432
+ const { call, close } = await connect({
2433
+ mux: overPipe(port, {
2434
+ codec: structuredCodec,
2435
+ side: "initiator",
2436
+ maxPorts
2437
+ }),
2438
+ timeout: streamTimeout
2439
+ });
2440
+ return trackedLink((request) => fetchOverDuplex(call, request), async () => {
2441
+ try {
2442
+ port.postMessage({ type: LINK_CLOSE });
2443
+ } catch {}
2444
+ await close();
2445
+ });
2446
+ }
2447
+ /**
2448
+ * Wraps a `send` so the link knows its requests in flight (for draining and
2449
+ * load-based routing) and can fail them all at once when it is closed.
2450
+ */
2451
+ function trackedLink(send, release) {
2452
+ let inflight = 0;
2453
+ let closed = false;
2454
+ let lostReason;
2455
+ const failers = /* @__PURE__ */ new Set();
2456
+ const idleWaiters = [];
2457
+ const done = () => {
2458
+ inflight--;
2459
+ if (inflight === 0) for (const resolve of idleWaiters.splice(0)) resolve();
2460
+ };
2461
+ const link = {
2462
+ get inflight() {
2463
+ return inflight;
2464
+ },
2465
+ get closed() {
2466
+ return closed;
2467
+ },
2468
+ whenIdle() {
2469
+ return inflight === 0 ? Promise.resolve() : new Promise((r) => idleWaiters.push(r));
2470
+ },
2471
+ async send(request) {
2472
+ if (closed) throw lostReason ?? new LinkLostError("The link is closed");
2473
+ inflight++;
2474
+ let finished = false;
2475
+ const finish = () => {
2476
+ if (finished) return;
2477
+ finished = true;
2478
+ failers.delete(fail);
2479
+ done();
2480
+ };
2481
+ let fail = () => {};
2482
+ const lost = new Promise((_, reject) => {
2483
+ fail = reject;
2484
+ });
2485
+ failers.add(fail);
2486
+ lost.catch(() => {});
2487
+ let response;
2488
+ try {
2489
+ response = await Promise.race([send(request), lost]);
2490
+ } catch (error) {
2491
+ finish();
2492
+ throw lostReason ?? error;
2493
+ }
2494
+ if (!response.body) {
2495
+ finish();
2496
+ return response;
2497
+ }
2498
+ return new Response(guardBody(response.body, lost, () => lostReason, finish), {
2499
+ status: response.status,
2500
+ statusText: response.statusText,
2501
+ headers: response.headers
2502
+ });
2503
+ },
2504
+ async close(reason) {
2505
+ if (closed) return;
2506
+ closed = true;
2507
+ lostReason = reason ?? new LinkLostError("The link was closed");
2508
+ for (const fail of [...failers]) fail(lostReason);
2509
+ try {
2510
+ await release();
2511
+ } catch {}
2512
+ }
2513
+ };
2514
+ return asyncDisposable(link, () => link.close());
2515
+ }
2516
+ /**
2517
+ * A response body that reports its end (done, cancelled or failed) and fails
2518
+ * with the link's reason when the link is lost mid-stream.
2519
+ */
2520
+ function guardBody(body, lost, reason, finish) {
2521
+ const reader = body.getReader();
2522
+ return new ReadableStream({
2523
+ async pull(controller) {
2524
+ try {
2525
+ const { done, value } = await Promise.race([reader.read(), lost]);
2526
+ if (done) {
2527
+ finish();
2528
+ controller.close();
2529
+ return;
2530
+ }
2531
+ controller.enqueue(value);
2532
+ } catch (error) {
2533
+ finish();
2534
+ reader.cancel().catch(() => {});
2535
+ controller.error(reason() ?? error);
2536
+ }
2537
+ },
2538
+ async cancel(why) {
2539
+ finish();
2540
+ await reader.cancel(why).catch(() => {});
2541
+ }
2542
+ });
2543
+ }
2544
+ //#endregion
2545
+ //#region src/sw/protocol.ts
2546
+ /** Page → ServiceWorker: open a WebSocket to a handler. */
2547
+ const WS_CONNECT_CALL = "webrun-http:ws-connect";
2548
+ //#endregion
1338
2549
  //#region src/core/data-channels.ts
1339
2550
  const MESSAGE_TYPE_REQUEST = "REQUEST";
1340
2551
  const MESSAGE_TYPE_RESPONSE = "RESPONSE";
@@ -1533,51 +2744,6 @@
1533
2744
  })(request);
1534
2745
  }
1535
2746
  //#endregion
1536
- //#region src/relay/mount-table.ts
1537
- /** `/` stays `/`; `/peers` and `/peers/` both become `/peers/`. */
1538
- function normalise(path) {
1539
- if (path === "" || path === "/") return "/";
1540
- const withSlash = path.startsWith("/") ? path : `/${path}`;
1541
- return withSlash.endsWith("/") ? withSlash : `${withSlash}/`;
1542
- }
1543
- /** Does `prefix` own `pathname`? `/peers/` owns `/peers/`, `/peers` and `/peers/x`. */
1544
- function owns(prefix, pathname) {
1545
- if (prefix === "/") return true;
1546
- if (pathname.startsWith(prefix)) return true;
1547
- return `${pathname}/` === prefix;
1548
- }
1549
- function newMountTable(options = {}) {
1550
- const entries = /* @__PURE__ */ new Map();
1551
- let seq = 0;
1552
- return {
1553
- set(key, spec) {
1554
- entries.set(key, {
1555
- key,
1556
- prefix: spec.path == null ? "" : normalise(spec.path),
1557
- match: spec.match,
1558
- seq: seq++
1559
- });
1560
- },
1561
- remove(key) {
1562
- entries.delete(key);
1563
- },
1564
- excludes(url) {
1565
- return options.exclude?.(url) === true;
1566
- },
1567
- find(url) {
1568
- if (options.exclude?.(url) === true) return void 0;
1569
- let best;
1570
- for (const entry of entries.values()) {
1571
- if (entry.prefix === "" || !owns(entry.prefix, url.pathname)) continue;
1572
- if (best == null || entry.prefix.length > best.prefix.length) best = entry;
1573
- }
1574
- if (best != null) return best.key;
1575
- const predicates = [...entries.values()].filter((entry) => entry.match != null).sort((a, b) => a.seq - b.seq);
1576
- for (const entry of predicates) if (entry.match?.(url) === true) return entry.key;
1577
- }
1578
- };
1579
- }
1580
- //#endregion
1581
2747
  //#region src/relay/split-service-url.ts
1582
2748
  /**
1583
2749
  * Splits a URL of the form `<base>/<separator><key>/<path>` into parts.
@@ -1635,6 +2801,69 @@
1635
2801
  path: slash < 0 ? "" : rest.slice(slash + 1)
1636
2802
  };
1637
2803
  }
2804
+ self.location.href;
2805
+ /**
2806
+ * Sends `request` on a port a service accepted with `reply`: over an HTTP link
2807
+ * when the service speaks `HTTP_LINK_PROTOCOL`, over version 1's transport
2808
+ * when it answered `true`. The link is closed once the response is done.
2809
+ */
2810
+ async function sendOverConnection(port, reply, request, options = {}) {
2811
+ if (reply === true) return await sendHttpRequest(port, request);
2812
+ const link = await connectHttpLink(port, options);
2813
+ try {
2814
+ const response = await link.send(request);
2815
+ link.whenIdle().then(() => link.close());
2816
+ return response;
2817
+ } catch (error) {
2818
+ await link.close();
2819
+ throw error;
2820
+ }
2821
+ }
2822
+ //#endregion
2823
+ //#region src/relay/mount-table.ts
2824
+ /** `/` stays `/`; `/peers` and `/peers/` both become `/peers/`. */
2825
+ function normalise(path) {
2826
+ if (path === "" || path === "/") return "/";
2827
+ const withSlash = path.startsWith("/") ? path : `/${path}`;
2828
+ return withSlash.endsWith("/") ? withSlash : `${withSlash}/`;
2829
+ }
2830
+ /** Does `prefix` own `pathname`? `/peers/` owns `/peers/`, `/peers` and `/peers/x`. */
2831
+ function owns(prefix, pathname) {
2832
+ if (prefix === "/") return true;
2833
+ if (pathname.startsWith(prefix)) return true;
2834
+ return `${pathname}/` === prefix;
2835
+ }
2836
+ function newMountTable(options = {}) {
2837
+ const entries = /* @__PURE__ */ new Map();
2838
+ let seq = 0;
2839
+ return {
2840
+ set(key, spec) {
2841
+ entries.set(key, {
2842
+ key,
2843
+ prefix: spec.path == null ? "" : normalise(spec.path),
2844
+ match: spec.match,
2845
+ seq: seq++
2846
+ });
2847
+ },
2848
+ remove(key) {
2849
+ entries.delete(key);
2850
+ },
2851
+ excludes(url) {
2852
+ return options.exclude?.(url) === true;
2853
+ },
2854
+ find(url) {
2855
+ if (options.exclude?.(url) === true) return void 0;
2856
+ let best;
2857
+ for (const entry of entries.values()) {
2858
+ if (entry.prefix === "" || !owns(entry.prefix, url.pathname)) continue;
2859
+ if (best == null || entry.prefix.length > best.prefix.length) best = entry;
2860
+ }
2861
+ if (best != null) return best.key;
2862
+ const predicates = [...entries.values()].filter((entry) => entry.match != null).sort((a, b) => a.seq - b.seq);
2863
+ for (const entry of predicates) if (entry.match?.(url) === true) return entry.key;
2864
+ }
2865
+ };
2866
+ }
1638
2867
  //#endregion
1639
2868
  //#region src/relay/index-sw.ts
1640
2869
  /**
@@ -1762,7 +2991,7 @@
1762
2991
  const source = event.source;
1763
2992
  if (!source) return false;
1764
2993
  const { key, path } = data;
1765
- if (options.canRegister != null && !await options.canRegister(source, key)) throw new Error(`this client may not register "${key}"`);
2994
+ if (options.canRegister != null && !await options.canRegister(source, key, path)) throw new Error(path == null ? `this client may not register "${key}"` : `this client may not register "${key}" at "${path}"`);
1766
2995
  if (takeover === "first-wins") {
1767
2996
  const current = await clientsRegistry.getMount(key);
1768
2997
  const isCurrentLive = current != null && await clientsRegistry.getClient(key) != null;
@@ -1777,8 +3006,14 @@
1777
3006
  applyRegisteredMount(mounts, key, path, hostKeys);
1778
3007
  return added;
1779
3008
  }));
1780
- register(handleChannelCalls(self, "UNREGISTER", async (_event, data) => {
3009
+ register(handleChannelCalls(self, "UNREGISTER", async (event, data) => {
3010
+ const source = event.source;
3011
+ if (!source) return false;
1781
3012
  const { key } = data;
3013
+ const current = await clientsRegistry.getMount(key);
3014
+ if (current == null) return false;
3015
+ if (await clientsRegistry.getClient(key) != null && current.clientId !== source.id) throw new Error(`"${key}" is served by another client`);
3016
+ if (options.canRegister != null && !await options.canRegister(source, key, current.path)) throw new Error(`this client may not unregister "${key}"`);
1782
3017
  removeRegisteredMount(mounts, key, hostKeys);
1783
3018
  return await clientsRegistry.removeClient(key);
1784
3019
  }));
@@ -1786,7 +3021,34 @@
1786
3021
  const { key } = data;
1787
3022
  const client = await clientsRegistry.getClient(key);
1788
3023
  if (!client) throw new Error(`Target client was not found. Target key: "${key}".`);
1789
- return await callChannel(client, "CONNECT", data, port);
3024
+ const reply = await callChannel(client, "CONNECT", data, port);
3025
+ const socketPort = reply?.port;
3026
+ return socketPort ? withTransfer(reply, [socketPort]) : reply;
3027
+ }));
3028
+ register(handleChannelCalls(self, WS_CONNECT_CALL, async (event, data) => {
3029
+ const source = event.source;
3030
+ if (!source?.url || new URL(source.url).origin !== self.location.origin) throw new Error("Only this origin's pages may open sockets");
3031
+ const { url, protocols = [] } = data;
3032
+ const httpUrl = new URL(url);
3033
+ if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
3034
+ else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
3035
+ await restored.catch(() => {});
3036
+ const key = resolveServiceKey(httpUrl, mounts, self.location.origin);
3037
+ if (key == null) throw new Error(`No service serves ${url}`);
3038
+ const client = await clientsRegistry.getClient(key);
3039
+ if (!client) throw new Error(`No service serves ${url}`);
3040
+ const channel = new MessageChannel();
3041
+ try {
3042
+ const connection = await callChannel(client, "CONNECT", {
3043
+ type: "ws",
3044
+ key,
3045
+ url: `${httpUrl}`,
3046
+ protocols
3047
+ }, channel.port2);
3048
+ return withTransfer(connection, [connection.port]);
3049
+ } finally {
3050
+ channel.port1.close();
3051
+ }
1790
3052
  }));
1791
3053
  /** Answers `request` as the service registered under `key`. */
1792
3054
  async function serve(key, request, url) {
@@ -1795,11 +3057,13 @@
1795
3057
  const channel = new MessageChannel();
1796
3058
  const client = await clientsRegistry.getClient(key);
1797
3059
  if (!client) throw HttpError.errorResourceGone(params);
1798
- if (!await callChannel(client, "CONNECT", {
3060
+ const reply = await callChannel(client, "CONNECT", {
1799
3061
  type: "http",
1800
- key
1801
- }, channel.port2)) throw HttpError.errorForbidden(params);
1802
- const response = await sendHttpRequest(channel.port1, request);
3062
+ key,
3063
+ wire: HTTP_LINK_PROTOCOL
3064
+ }, channel.port2);
3065
+ if (!reply) throw HttpError.errorForbidden(params);
3066
+ const response = await sendOverConnection(channel.port1, reply, request, { streamTimeout: options.streamTimeout });
1803
3067
  return options.decorateResponse?.(response, request) ?? response;
1804
3068
  } catch (error) {
1805
3069
  const httpError = HttpError.fromError(error);