@statewalker/webrun-http-browser 0.6.4 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +319 -65
- package/dist/core/data-calls.d.ts +17 -0
- package/dist/core/data-calls.d.ts.map +1 -1
- package/dist/core/service-worker-control.d.ts +3 -1
- package/dist/core/service-worker-control.d.ts.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3907 -266
- package/dist/link/errors.d.ts +2 -0
- package/dist/link/errors.d.ts.map +1 -0
- package/dist/link/http-link.d.ts +58 -0
- package/dist/link/http-link.d.ts.map +1 -0
- package/dist/link/index.d.ts +4 -0
- package/dist/link/index.d.ts.map +1 -0
- package/dist/link/locks.d.ts +39 -0
- package/dist/link/locks.d.ts.map +1 -0
- package/dist/link/rendezvous.d.ts +21 -0
- package/dist/link/rendezvous.d.ts.map +1 -0
- package/dist/relay/index-sw.d.ts +12 -2
- package/dist/relay/index-sw.d.ts.map +1 -1
- package/dist/relay/index.d.ts +66 -8
- package/dist/relay/index.d.ts.map +1 -1
- package/dist/relay-sw.js +1160 -55
- package/dist/relay-worker.js +1161 -55
- package/dist/sw/handler-endpoint.d.ts +81 -0
- package/dist/sw/handler-endpoint.d.ts.map +1 -0
- package/dist/sw/handler-table.d.ts +53 -0
- package/dist/sw/handler-table.d.ts.map +1 -0
- package/dist/sw/http-sw-dispatcher.d.ts +162 -21
- package/dist/sw/http-sw-dispatcher.d.ts.map +1 -1
- package/dist/sw/index.d.ts +5 -0
- package/dist/sw/index.d.ts.map +1 -1
- package/dist/sw/protocol.d.ts +115 -0
- package/dist/sw/protocol.d.ts.map +1 -0
- package/dist/sw/sw-dispatcher.d.ts +2 -1
- package/dist/sw/sw-dispatcher.d.ts.map +1 -1
- package/dist/sw/sw-http-adapter.d.ts +199 -0
- package/dist/sw/sw-http-adapter.d.ts.map +1 -0
- package/dist/sw/sw-websocket.d.ts +16 -0
- package/dist/sw/sw-websocket.d.ts.map +1 -0
- package/dist/sw/worker-service.d.ts +45 -0
- package/dist/sw/worker-service.d.ts.map +1 -0
- package/dist/sw/worker-url.d.ts +9 -0
- package/dist/sw/worker-url.d.ts.map +1 -0
- package/dist/sw-worker.js +2075 -210
- package/dist/sw.d.ts +2 -0
- package/dist/sw.d.ts.map +1 -1
- package/dist/sw.js +3853 -480
- package/dist/worker.d.ts +10 -0
- package/dist/worker.d.ts.map +1 -0
- package/dist/worker.js +3507 -0
- package/dist/ws/client.d.ts +73 -0
- package/dist/ws/client.d.ts.map +1 -0
- package/dist/ws/frames.d.ts +68 -0
- package/dist/ws/frames.d.ts.map +1 -0
- package/dist/ws/index.d.ts +6 -0
- package/dist/ws/index.d.ts.map +1 -0
- package/dist/ws/server.d.ts +53 -0
- package/dist/ws/server.d.ts.map +1 -0
- package/dist/ws/socket-core.d.ts +91 -0
- package/dist/ws/socket-core.d.ts.map +1 -0
- package/dist/ws/upgrade.d.ts +93 -0
- package/dist/ws/upgrade.d.ts.map +1 -0
- package/package.json +10 -5
- package/src/core/data-calls.ts +52 -2
- package/src/core/service-worker-control.ts +7 -1
- package/src/index.ts +3 -0
- package/src/link/errors.ts +3 -0
- package/src/link/http-link.ts +222 -0
- package/src/link/index.ts +3 -0
- package/src/link/locks.ts +97 -0
- package/src/link/rendezvous.ts +60 -0
- package/src/relay/index-sw.ts +84 -12
- package/src/relay/index.ts +205 -29
- package/src/sw/handler-endpoint.ts +278 -0
- package/src/sw/handler-table.ts +130 -0
- package/src/sw/http-sw-dispatcher.ts +649 -90
- package/src/sw/index.ts +5 -0
- package/src/sw/protocol.ts +103 -0
- package/src/sw/sw-dispatcher.ts +12 -30
- package/src/sw/sw-http-adapter.ts +613 -0
- package/src/sw/sw-websocket.ts +43 -0
- package/src/sw/worker-service.ts +133 -0
- package/src/sw/worker-url.ts +19 -0
- package/src/sw-worker.ts +8 -3
- package/src/sw.ts +2 -0
- package/src/worker.ts +9 -0
- package/src/ws/client.ts +346 -0
- package/src/ws/frames.ts +119 -0
- package/src/ws/index.ts +11 -0
- package/src/ws/server.ts +132 -0
- package/src/ws/socket-core.ts +251 -0
- package/src/ws/upgrade.ts +200 -0
package/dist/relay-sw.js
CHANGED
|
@@ -282,6 +282,34 @@
|
|
|
282
282
|
});
|
|
283
283
|
}
|
|
284
284
|
}
|
|
285
|
+
const DEFAULT_CHUNK_SIZE = 16384;
|
|
286
|
+
/**
|
|
287
|
+
* Curried `Duplex`-shaped transformer that splits incoming `Uint8Array`s into
|
|
288
|
+
* chunks no larger than `size` bytes. Empty input chunks are skipped; small
|
|
289
|
+
* input chunks pass through unchanged (zero-copy `subarray` views are used
|
|
290
|
+
* when splitting, so no allocation per chunk).
|
|
291
|
+
*
|
|
292
|
+
* Use to respect transport MTUs before reaching `channel.send`. Reassembly on
|
|
293
|
+
* the receive side is not needed — consumers iterate a continuous byte stream.
|
|
294
|
+
*/
|
|
295
|
+
function toChunks(size = DEFAULT_CHUNK_SIZE) {
|
|
296
|
+
if (!(Number.isInteger(size) && size > 0)) throw new RangeError(`toChunks: size must be a positive integer, got ${size}`);
|
|
297
|
+
return async function* (input) {
|
|
298
|
+
for await (const block of input) {
|
|
299
|
+
if (block.byteLength === 0) continue;
|
|
300
|
+
if (block.byteLength <= size) {
|
|
301
|
+
yield block;
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
let offset = 0;
|
|
305
|
+
while (offset < block.byteLength) {
|
|
306
|
+
const end = Math.min(offset + size, block.byteLength);
|
|
307
|
+
yield block.subarray(offset, end);
|
|
308
|
+
offset = end;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
}
|
|
285
313
|
//#endregion
|
|
286
314
|
//#region ../webrun-http-streams/dist/index.js
|
|
287
315
|
const CR = 13;
|
|
@@ -1033,10 +1061,99 @@
|
|
|
1033
1061
|
}
|
|
1034
1062
|
};
|
|
1035
1063
|
}
|
|
1036
|
-
|
|
1064
|
+
/**
|
|
1065
|
+
* Writes HTTP/1.1; accepts HTTP/1.1 or the legacy JSON envelope. Used whenever
|
|
1066
|
+
* no `codec` option is supplied.
|
|
1067
|
+
*/
|
|
1068
|
+
const defaultCodec = newSniffingCodec({
|
|
1037
1069
|
write: httpCodec,
|
|
1038
1070
|
accept: [httpCodec, jsonEnvelopeCodec]
|
|
1039
1071
|
});
|
|
1072
|
+
/** Carries the serialized JS error between two webrun peers. */
|
|
1073
|
+
const PEER_ERROR_HEADER = "x-webrun-error";
|
|
1074
|
+
/**
|
|
1075
|
+
* `output` is the `Duplex` call's own generator — one logical call, per the
|
|
1076
|
+
* `Duplex` contract in `@statewalker/webrun-streams`: "Consumer `.return()`
|
|
1077
|
+
* on the output → producer's `finally` runs." On a mux transport
|
|
1078
|
+
* (`emulateMux`), that `finally` is what frees the stream-table slot; skip it
|
|
1079
|
+
* and every peer-error response leaks one slot, unboundedly, until the mux
|
|
1080
|
+
* itself is exhausted (`maxStreams` reached, every further call rejected).
|
|
1081
|
+
*
|
|
1082
|
+
* Cancelling `output` here — not inside the codec's own decode logic — is
|
|
1083
|
+
* deliberate. `codec.decodeResponse` already pulled from `output` to read the
|
|
1084
|
+
* head before this function runs, so unlike the body case above there's no
|
|
1085
|
+
* suspended-start no-op to worry about. And it's safe specifically *because*
|
|
1086
|
+
* this is the client's own response-only generator: the request was already
|
|
1087
|
+
* fully sent before we got here, so there is nothing left to write on it.
|
|
1088
|
+
* The equivalent is NOT safe inside `src/http1/decode.ts`'s `ByteReader` —
|
|
1089
|
+
* that code also runs when a caller wires `codec.decodeRequest`/
|
|
1090
|
+
* `decodeResponse` directly onto a raw bidirectional socket (see
|
|
1091
|
+
* `tests/http1-node-interop.test.ts`), where the *same* object is read from
|
|
1092
|
+
* and then written back to (a server reads the request, then replies on the
|
|
1093
|
+
* same socket); cancelling the read side there tears down the whole
|
|
1094
|
+
* connection out from under the pending write. That was tried and reverted —
|
|
1095
|
+
* see the Task 11 report for the "socket hang up" failure it caused.
|
|
1096
|
+
*/
|
|
1097
|
+
async function throwIfPeerError(result, output) {
|
|
1098
|
+
const found = result.envelope.headers.find(([k]) => k.toLowerCase() === PEER_ERROR_HEADER);
|
|
1099
|
+
if (!found) return;
|
|
1100
|
+
await discard(result.body);
|
|
1101
|
+
try {
|
|
1102
|
+
await output.return?.(void 0);
|
|
1103
|
+
} catch {}
|
|
1104
|
+
let payload;
|
|
1105
|
+
try {
|
|
1106
|
+
payload = JSON.parse(found[1]);
|
|
1107
|
+
} catch {
|
|
1108
|
+
payload = { message: found[1] };
|
|
1109
|
+
}
|
|
1110
|
+
throw deserializeError(payload);
|
|
1111
|
+
}
|
|
1112
|
+
/**
|
|
1113
|
+
* Initiate an HTTP call over a `Duplex`. The caller's `call: Duplex` is
|
|
1114
|
+
* obtained from any `webrun-streams-*` adapter's `connect`. Returns the
|
|
1115
|
+
* response envelope and an async iterable over the response body bytes.
|
|
1116
|
+
*
|
|
1117
|
+
* The call is one logical Duplex invocation; multiplexing of concurrent
|
|
1118
|
+
* calls is the adapter's concern (native or `emulateMux`).
|
|
1119
|
+
*/
|
|
1120
|
+
async function httpFetch(call, env, body, options = {}) {
|
|
1121
|
+
const codec = options.codec ?? defaultCodec;
|
|
1122
|
+
const output = call(codec.encodeRequest(env, body));
|
|
1123
|
+
const decoded = await codec.decodeResponse(output, { method: env.method });
|
|
1124
|
+
const release = async () => {
|
|
1125
|
+
try {
|
|
1126
|
+
await output.return?.(void 0);
|
|
1127
|
+
} catch {}
|
|
1128
|
+
};
|
|
1129
|
+
const result = {
|
|
1130
|
+
envelope: decoded.envelope,
|
|
1131
|
+
body: releasingOnExit(decoded.body, release),
|
|
1132
|
+
release
|
|
1133
|
+
};
|
|
1134
|
+
await throwIfPeerError(result, output);
|
|
1135
|
+
return result;
|
|
1136
|
+
}
|
|
1137
|
+
/**
|
|
1138
|
+
* `body`, but leaving it before its end releases the call.
|
|
1139
|
+
*
|
|
1140
|
+
* The body the codec hands back is a generator of its own over a `ByteReader`,
|
|
1141
|
+
* and `.return()` on it never reaches the call's `output` (see
|
|
1142
|
+
* `throwIfPeerError` for why the codec must not do that itself). So a caller
|
|
1143
|
+
* that stopped reading — an aborted `fetch`, a cancelled response stream —
|
|
1144
|
+
* left the peer's producer parked forever, holding its handler open. Safe here
|
|
1145
|
+
* for the same reason it is safe in `throwIfPeerError`: `output` is this
|
|
1146
|
+
* call's own response-only generator, and the request was fully sent.
|
|
1147
|
+
*/
|
|
1148
|
+
async function* releasingOnExit(body, release) {
|
|
1149
|
+
let completed = false;
|
|
1150
|
+
try {
|
|
1151
|
+
yield* body;
|
|
1152
|
+
completed = true;
|
|
1153
|
+
} finally {
|
|
1154
|
+
if (!completed) await release();
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1040
1157
|
/**
|
|
1041
1158
|
* The one place that knows a runtime may not implement request body streams,
|
|
1042
1159
|
* and the buffering both fallbacks need. `fetch.ts` and `http-stubs.ts` each
|
|
@@ -1142,6 +1259,121 @@
|
|
|
1142
1259
|
return new Response(toReadableStream(result.content[Symbol.asyncIterator]()), responseOptions);
|
|
1143
1260
|
};
|
|
1144
1261
|
}
|
|
1262
|
+
/**
|
|
1263
|
+
* Connection-scoped headers. The codec surfaces them verbatim (decision 12),
|
|
1264
|
+
* but they are meaningless to a `Request`/`Response`, and re-emitting them
|
|
1265
|
+
* from a relay would corrupt its framing.
|
|
1266
|
+
*/
|
|
1267
|
+
const HOP_BY_HOP = /* @__PURE__ */ new Set([
|
|
1268
|
+
"connection",
|
|
1269
|
+
"host",
|
|
1270
|
+
"keep-alive",
|
|
1271
|
+
"proxy-authenticate",
|
|
1272
|
+
"proxy-authorization",
|
|
1273
|
+
"te",
|
|
1274
|
+
"trailer",
|
|
1275
|
+
"transfer-encoding",
|
|
1276
|
+
"upgrade"
|
|
1277
|
+
]);
|
|
1278
|
+
function forwardableHeaders(headers) {
|
|
1279
|
+
return headers.filter(([name]) => !HOP_BY_HOP.has(name.toLowerCase()));
|
|
1280
|
+
}
|
|
1281
|
+
function headersToArray(headers) {
|
|
1282
|
+
const out = [];
|
|
1283
|
+
headers.forEach((value, key) => {
|
|
1284
|
+
out.push([key, value]);
|
|
1285
|
+
});
|
|
1286
|
+
return out;
|
|
1287
|
+
}
|
|
1288
|
+
async function* readableToAsyncIterable(stream) {
|
|
1289
|
+
if (!stream) return;
|
|
1290
|
+
const reader = stream.getReader();
|
|
1291
|
+
let consumed = false;
|
|
1292
|
+
try {
|
|
1293
|
+
while (true) {
|
|
1294
|
+
const { done, value } = await reader.read();
|
|
1295
|
+
if (done) {
|
|
1296
|
+
consumed = true;
|
|
1297
|
+
return;
|
|
1298
|
+
}
|
|
1299
|
+
if (value) yield value;
|
|
1300
|
+
}
|
|
1301
|
+
} finally {
|
|
1302
|
+
if (!consumed) try {
|
|
1303
|
+
await reader.cancel();
|
|
1304
|
+
} catch {}
|
|
1305
|
+
try {
|
|
1306
|
+
reader.releaseLock();
|
|
1307
|
+
} catch {}
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
function asyncIterableToReadable(iter) {
|
|
1311
|
+
const it = iter[Symbol.asyncIterator]();
|
|
1312
|
+
return new ReadableStream({
|
|
1313
|
+
async pull(controller) {
|
|
1314
|
+
try {
|
|
1315
|
+
const { done, value } = await it.next();
|
|
1316
|
+
if (done) {
|
|
1317
|
+
controller.close();
|
|
1318
|
+
return;
|
|
1319
|
+
}
|
|
1320
|
+
controller.enqueue(value);
|
|
1321
|
+
} catch (err) {
|
|
1322
|
+
controller.error(err);
|
|
1323
|
+
}
|
|
1324
|
+
},
|
|
1325
|
+
async cancel() {
|
|
1326
|
+
await it.return?.();
|
|
1327
|
+
}
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
/**
|
|
1331
|
+
* Run a `Request` through a `Duplex` call and reconstruct the `Response` on
|
|
1332
|
+
* the other side. The request's `signal` is plumbed into the body iteration —
|
|
1333
|
+
* abort terminates the underlying call.
|
|
1334
|
+
*/
|
|
1335
|
+
async function fetchOverDuplex(call, request, options = {}) {
|
|
1336
|
+
if (request.signal?.aborted) throw abortReason$1(request.signal);
|
|
1337
|
+
const env = {
|
|
1338
|
+
url: request.url,
|
|
1339
|
+
method: request.method,
|
|
1340
|
+
headers: headersToArray(request.headers)
|
|
1341
|
+
};
|
|
1342
|
+
let body;
|
|
1343
|
+
if (request.body != null) body = readableToAsyncIterable(request.body);
|
|
1344
|
+
else if (!supportsRequestStreams()) {
|
|
1345
|
+
const buffered = new Uint8Array(await request.arrayBuffer());
|
|
1346
|
+
if (buffered.byteLength > 0) body = [buffered];
|
|
1347
|
+
}
|
|
1348
|
+
const { envelope, body: respBody, release } = await httpFetch(call, env, body, options);
|
|
1349
|
+
const responseInit = {
|
|
1350
|
+
status: envelope.status,
|
|
1351
|
+
statusText: envelope.statusText,
|
|
1352
|
+
headers: forwardableHeaders(envelope.headers)
|
|
1353
|
+
};
|
|
1354
|
+
if (request.method === "HEAD" || request.method === "OPTIONS" || NULL_BODY_STATUSES.has(envelope.status)) {
|
|
1355
|
+
await release?.();
|
|
1356
|
+
return new Response(null, responseInit);
|
|
1357
|
+
}
|
|
1358
|
+
return new Response(asyncIterableToReadable(withAbort(respBody, request.signal)), responseInit);
|
|
1359
|
+
}
|
|
1360
|
+
async function* withAbort(iter, signal) {
|
|
1361
|
+
if (!signal) {
|
|
1362
|
+
yield* iter;
|
|
1363
|
+
return;
|
|
1364
|
+
}
|
|
1365
|
+
for await (const chunk of iter) {
|
|
1366
|
+
if (signal.aborted) throw abortReason$1(signal);
|
|
1367
|
+
yield chunk;
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
function abortReason$1(signal) {
|
|
1371
|
+
const reason = signal.reason;
|
|
1372
|
+
if (reason instanceof Error) return reason;
|
|
1373
|
+
const err = new Error(reason === void 0 ? "Aborted" : String(reason));
|
|
1374
|
+
err.name = "AbortError";
|
|
1375
|
+
return err;
|
|
1376
|
+
}
|
|
1145
1377
|
var HttpError = class HttpError extends Error {
|
|
1146
1378
|
status;
|
|
1147
1379
|
statusText;
|
|
@@ -1254,6 +1486,32 @@
|
|
|
1254
1486
|
}
|
|
1255
1487
|
//#endregion
|
|
1256
1488
|
//#region src/core/data-calls.ts
|
|
1489
|
+
const TRANSFER = Symbol.for("webrun-http-browser:transfer");
|
|
1490
|
+
/**
|
|
1491
|
+
* A channel call's result that carries transferables, a `MessagePort` say:
|
|
1492
|
+
* return `withTransfer({ port }, [port])` from a `handleChannelCalls` handler
|
|
1493
|
+
* and `callChannel` resolves with `{ port }`.
|
|
1494
|
+
*/
|
|
1495
|
+
function withTransfer(value, transfer) {
|
|
1496
|
+
return {
|
|
1497
|
+
[TRANSFER]: true,
|
|
1498
|
+
value,
|
|
1499
|
+
transfer
|
|
1500
|
+
};
|
|
1501
|
+
}
|
|
1502
|
+
function isTransferResult(value) {
|
|
1503
|
+
return typeof value === "object" && value !== null && TRANSFER in value;
|
|
1504
|
+
}
|
|
1505
|
+
/** Splits a handler's result into the value to post and its transfer list. */
|
|
1506
|
+
function unwrapTransfer(result) {
|
|
1507
|
+
return isTransferResult(result) ? {
|
|
1508
|
+
value: result.value,
|
|
1509
|
+
transfer: result.transfer
|
|
1510
|
+
} : {
|
|
1511
|
+
value: result,
|
|
1512
|
+
transfer: []
|
|
1513
|
+
};
|
|
1514
|
+
}
|
|
1257
1515
|
function callChannel(target, callType, params, ...transfers) {
|
|
1258
1516
|
return new Promise((resolve, reject) => {
|
|
1259
1517
|
const channel = new MessageChannel();
|
|
@@ -1273,12 +1531,14 @@
|
|
|
1273
1531
|
if (!event.data || event.data.type !== callType) return;
|
|
1274
1532
|
const [port, ...transfers] = event.ports ?? [];
|
|
1275
1533
|
const response = {};
|
|
1534
|
+
let transfer = [];
|
|
1276
1535
|
try {
|
|
1277
|
-
|
|
1536
|
+
const result = await handler(event, event.data.params, ...transfers);
|
|
1537
|
+
({value: response.result, transfer} = unwrapTransfer(result));
|
|
1278
1538
|
} catch (error) {
|
|
1279
1539
|
response.error = serializeError(error);
|
|
1280
1540
|
}
|
|
1281
|
-
port?.postMessage(response);
|
|
1541
|
+
port?.postMessage(response, transfer);
|
|
1282
1542
|
};
|
|
1283
1543
|
target.addEventListener("message", listener);
|
|
1284
1544
|
target.start?.();
|
|
@@ -1335,6 +1595,798 @@
|
|
|
1335
1595
|
});
|
|
1336
1596
|
}
|
|
1337
1597
|
//#endregion
|
|
1598
|
+
//#region ../webrun-rpc/dist/index.js
|
|
1599
|
+
const closeSignals = /* @__PURE__ */ new WeakMap();
|
|
1600
|
+
/**
|
|
1601
|
+
* Internal: register a port's close signal. Called once by `bindBytesToPort`.
|
|
1602
|
+
*
|
|
1603
|
+
* @internal
|
|
1604
|
+
*/
|
|
1605
|
+
function setPortCloseSignal(port, signal) {
|
|
1606
|
+
closeSignals.set(port, signal);
|
|
1607
|
+
}
|
|
1608
|
+
/**
|
|
1609
|
+
* Return the AbortSignal that fires when `port`'s transport closes, or
|
|
1610
|
+
* `undefined` if `port` is not transport-backed (e.g., a raw
|
|
1611
|
+
* `MessageChannel().port1`).
|
|
1612
|
+
*/
|
|
1613
|
+
function getPortCloseSignal(port) {
|
|
1614
|
+
return closeSignals.get(port);
|
|
1615
|
+
}
|
|
1616
|
+
/**
|
|
1617
|
+
* Pass as `timeout` to install no deadline at all. Used by the stream tier,
|
|
1618
|
+
* where the deadline belongs to the stream rather than to one chunk (spec D8):
|
|
1619
|
+
* a slow consumer is throttled, never failed.
|
|
1620
|
+
*/
|
|
1621
|
+
const NO_TIMEOUT = Number.POSITIVE_INFINITY;
|
|
1622
|
+
/**
|
|
1623
|
+
* Asynchronous request/response over any `MessageTarget`.
|
|
1624
|
+
*
|
|
1625
|
+
* Sends `params` to the peer listening with `listenPort`, waits up to
|
|
1626
|
+
* `timeout` ms for a matching reply, and either resolves with the result or
|
|
1627
|
+
* rejects with the deserialised error.
|
|
1628
|
+
*/
|
|
1629
|
+
function callPort(port, params, { timeout = 1e3, channelName = "", log = () => {}, newCallId = () => `call-${Date.now()}-${String(Math.random()).substring(2)}`, signal } = {}) {
|
|
1630
|
+
const callId = newCallId();
|
|
1631
|
+
log("[callPort]", {
|
|
1632
|
+
channelName,
|
|
1633
|
+
callId,
|
|
1634
|
+
params
|
|
1635
|
+
});
|
|
1636
|
+
const combinedSignal = combineSignals(signal, getPortCloseSignal(port));
|
|
1637
|
+
let timerId;
|
|
1638
|
+
let onMessage;
|
|
1639
|
+
let onAbort;
|
|
1640
|
+
const promise = new Promise((resolve, reject) => {
|
|
1641
|
+
if (combinedSignal?.aborted) {
|
|
1642
|
+
reject(abortReason(combinedSignal));
|
|
1643
|
+
return;
|
|
1644
|
+
}
|
|
1645
|
+
if (Number.isFinite(timeout) && timeout > 0) timerId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Call timeout. CallId: "${callId}".`)), timeout);
|
|
1646
|
+
onMessage = (event) => {
|
|
1647
|
+
const data = event.data;
|
|
1648
|
+
if (!data) return;
|
|
1649
|
+
if (data.channelName !== channelName) return;
|
|
1650
|
+
if (data.callId !== callId) return;
|
|
1651
|
+
if (data.type === "response:error") reject(deserializeError(data.error));
|
|
1652
|
+
else if (data.type === "response:result") resolve(data.result);
|
|
1653
|
+
};
|
|
1654
|
+
port.addEventListener("message", onMessage);
|
|
1655
|
+
if (combinedSignal) {
|
|
1656
|
+
onAbort = () => reject(abortReason(combinedSignal));
|
|
1657
|
+
combinedSignal.addEventListener("abort", onAbort, { once: true });
|
|
1658
|
+
}
|
|
1659
|
+
});
|
|
1660
|
+
promise.catch(() => {}).finally(() => {
|
|
1661
|
+
if (timerId !== void 0) clearTimeout(timerId);
|
|
1662
|
+
if (onMessage) port.removeEventListener("message", onMessage);
|
|
1663
|
+
if (onAbort && combinedSignal) combinedSignal.removeEventListener("abort", onAbort);
|
|
1664
|
+
});
|
|
1665
|
+
port.postMessage({
|
|
1666
|
+
type: "request",
|
|
1667
|
+
channelName,
|
|
1668
|
+
callId,
|
|
1669
|
+
params
|
|
1670
|
+
});
|
|
1671
|
+
return promise;
|
|
1672
|
+
}
|
|
1673
|
+
function abortReason(signal) {
|
|
1674
|
+
const reason = signal.reason;
|
|
1675
|
+
if (reason instanceof Error) return reason;
|
|
1676
|
+
const err = new Error(reason === void 0 ? "Aborted" : String(reason));
|
|
1677
|
+
err.name = "AbortError";
|
|
1678
|
+
return err;
|
|
1679
|
+
}
|
|
1680
|
+
function combineSignals(...signals) {
|
|
1681
|
+
const live = signals.filter((s) => s !== void 0);
|
|
1682
|
+
if (live.length === 0) return void 0;
|
|
1683
|
+
if (live.length === 1) return live[0];
|
|
1684
|
+
return AbortSignal.any(live);
|
|
1685
|
+
}
|
|
1686
|
+
/**
|
|
1687
|
+
* Installs `handler` as the server side of a `callPort` / `listenPort`
|
|
1688
|
+
* request/response pair on `port`.
|
|
1689
|
+
*
|
|
1690
|
+
* Returns a cleanup function that removes the listener.
|
|
1691
|
+
*/
|
|
1692
|
+
function listenPort(port, handler, { channelName = "", log = () => {} } = {}) {
|
|
1693
|
+
const onMessage = async (event) => {
|
|
1694
|
+
const data = event.data;
|
|
1695
|
+
if (!data || data.channelName !== channelName || data.type !== "request") return;
|
|
1696
|
+
const { callId, params } = data;
|
|
1697
|
+
log("[listenPort]", {
|
|
1698
|
+
channelName,
|
|
1699
|
+
callId,
|
|
1700
|
+
params
|
|
1701
|
+
});
|
|
1702
|
+
let result;
|
|
1703
|
+
let error;
|
|
1704
|
+
let type;
|
|
1705
|
+
try {
|
|
1706
|
+
result = await handler(params);
|
|
1707
|
+
type = "response:result";
|
|
1708
|
+
} catch (e) {
|
|
1709
|
+
error = serializeError(e);
|
|
1710
|
+
type = "response:error";
|
|
1711
|
+
}
|
|
1712
|
+
port.postMessage({
|
|
1713
|
+
callId,
|
|
1714
|
+
channelName,
|
|
1715
|
+
type,
|
|
1716
|
+
result,
|
|
1717
|
+
error
|
|
1718
|
+
});
|
|
1719
|
+
};
|
|
1720
|
+
port.addEventListener("message", onMessage);
|
|
1721
|
+
return () => port.removeEventListener("message", onMessage);
|
|
1722
|
+
}
|
|
1723
|
+
/**
|
|
1724
|
+
* Wraps an async iterable so that an `AbortSignal` firing causes the wrapper
|
|
1725
|
+
* to return cleanly, forwarding `return()` to the underlying iterator so the
|
|
1726
|
+
* producer (e.g., a user-supplied generator) sees its own `finally` blocks
|
|
1727
|
+
* run immediately rather than waiting for the next yield.
|
|
1728
|
+
*/
|
|
1729
|
+
async function* throughAbort(input, signal) {
|
|
1730
|
+
const iter = input[Symbol.asyncIterator] ? input[Symbol.asyncIterator]() : input[Symbol.iterator]();
|
|
1731
|
+
const onAbort = () => {
|
|
1732
|
+
iter.return?.(void 0);
|
|
1733
|
+
};
|
|
1734
|
+
if (signal.aborted) {
|
|
1735
|
+
iter.return?.(void 0);
|
|
1736
|
+
return;
|
|
1737
|
+
}
|
|
1738
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1739
|
+
try {
|
|
1740
|
+
while (true) {
|
|
1741
|
+
const r = await iter.next();
|
|
1742
|
+
if (r.done) return;
|
|
1743
|
+
if (signal.aborted) return;
|
|
1744
|
+
yield r.value;
|
|
1745
|
+
}
|
|
1746
|
+
} finally {
|
|
1747
|
+
signal.removeEventListener("abort", onAbort);
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
/**
|
|
1751
|
+
* The `type` of the out-of-band notice a side posts when it abandons a stream.
|
|
1752
|
+
*
|
|
1753
|
+
* Layer 1's `close` is not observable to layer 2 — a closed virtual port drops
|
|
1754
|
+
* its listeners silently and is indistinguishable from a working port nobody
|
|
1755
|
+
* is answering — so the peer would otherwise wait forever. Exported because
|
|
1756
|
+
* tests and adapters assert on it.
|
|
1757
|
+
*/
|
|
1758
|
+
const STREAM_ABORT = "webrun-rpc:stream-abort";
|
|
1759
|
+
/** Caller's input travels on this channel; the handler listens on it. */
|
|
1760
|
+
const CHANNEL_IN = "in";
|
|
1761
|
+
/** The handler's output travels on this channel; the caller listens on it. */
|
|
1762
|
+
const CHANNEL_OUT = "out";
|
|
1763
|
+
/**
|
|
1764
|
+
* One port in, one `Duplex` out (spec D9).
|
|
1765
|
+
*
|
|
1766
|
+
* The returned `Duplex` runs a single stream on `port`: the caller's `input`
|
|
1767
|
+
* is sent chunk by chunk with `callPort`, and the handler's output arrives the
|
|
1768
|
+
* same way on the other channel. Within each direction the next chunk is never
|
|
1769
|
+
* sent until the previous one has been delivered *and* pulled past by the
|
|
1770
|
+
* consumer (spec D11) — the reply to a chunk call *is* the confirmation, and
|
|
1771
|
+
* `listenPort` withholds it until then.
|
|
1772
|
+
*
|
|
1773
|
+
* A stream port carries exactly one invocation. To make several calls, open
|
|
1774
|
+
* several ports: `mux.openPort({ kind: "stream" })` per call.
|
|
1775
|
+
*/
|
|
1776
|
+
function duplexOverPort(port, options = {}) {
|
|
1777
|
+
return (input) => runCallerSide(port, input, options);
|
|
1778
|
+
}
|
|
1779
|
+
function runCallerSide(port, input, options) {
|
|
1780
|
+
const controller = new AbortController();
|
|
1781
|
+
const notice = installAbortNotice(port, controller);
|
|
1782
|
+
abortOnPortClose(port, controller);
|
|
1783
|
+
const clock = installStreamTimeout(controller, options.timeout);
|
|
1784
|
+
const inbound = receiveChunks(port, CHANNEL_OUT, controller, clock.touch);
|
|
1785
|
+
const pump = sendChunks(port, CHANNEL_IN, input, options, controller.signal, clock.touch);
|
|
1786
|
+
pump.catch(() => {});
|
|
1787
|
+
return (async function* () {
|
|
1788
|
+
try {
|
|
1789
|
+
yield* inbound.stream;
|
|
1790
|
+
} finally {
|
|
1791
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the caller abandoned the stream"));
|
|
1792
|
+
notice.post();
|
|
1793
|
+
notice.stop();
|
|
1794
|
+
clock.stop();
|
|
1795
|
+
inbound.stop();
|
|
1796
|
+
await pump.catch(() => {});
|
|
1797
|
+
try {
|
|
1798
|
+
await port.close?.();
|
|
1799
|
+
} catch {}
|
|
1800
|
+
}
|
|
1801
|
+
})();
|
|
1802
|
+
}
|
|
1803
|
+
/**
|
|
1804
|
+
* Listens for the peer's abort notice, and can post our own. The notice is a
|
|
1805
|
+
* plain message with no `channelName` and a `type` that is not `"request"`,
|
|
1806
|
+
* so neither `callPort` nor `listenPort` reacts to it, and it carries no
|
|
1807
|
+
* numeric `id`, so `structuredCodec` never mistakes it for a layer 1 envelope.
|
|
1808
|
+
*/
|
|
1809
|
+
function installAbortNotice(port, controller) {
|
|
1810
|
+
const onMessage = (event) => {
|
|
1811
|
+
const data = event.data;
|
|
1812
|
+
if (!data || data.type !== "webrun-rpc:stream-abort") return;
|
|
1813
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the peer abandoned the stream"));
|
|
1814
|
+
};
|
|
1815
|
+
port.addEventListener("message", onMessage);
|
|
1816
|
+
let posted = false;
|
|
1817
|
+
return {
|
|
1818
|
+
post() {
|
|
1819
|
+
if (posted) return;
|
|
1820
|
+
posted = true;
|
|
1821
|
+
try {
|
|
1822
|
+
port.postMessage({ type: STREAM_ABORT });
|
|
1823
|
+
} catch {}
|
|
1824
|
+
},
|
|
1825
|
+
stop() {
|
|
1826
|
+
port.removeEventListener("message", onMessage);
|
|
1827
|
+
}
|
|
1828
|
+
};
|
|
1829
|
+
}
|
|
1830
|
+
/**
|
|
1831
|
+
* Aborts the stream when its port closes underneath it — the multiplexer was
|
|
1832
|
+
* closed, or the peer closed the port — for ports that report it (see
|
|
1833
|
+
* `getPortCloseSignal`). Without this a stream waiting for the peer's next
|
|
1834
|
+
* chunk would wait forever on a port that can no longer deliver one: the
|
|
1835
|
+
* outbound half's `callPort` already fails on the close signal, but nothing
|
|
1836
|
+
* failed the inbound half.
|
|
1837
|
+
*/
|
|
1838
|
+
function abortOnPortClose(port, controller) {
|
|
1839
|
+
const closed = getPortCloseSignal(port);
|
|
1840
|
+
if (!closed) return;
|
|
1841
|
+
const onClose = () => {
|
|
1842
|
+
if (!controller.signal.aborted) controller.abort(closed.reason);
|
|
1843
|
+
};
|
|
1844
|
+
if (closed.aborted) {
|
|
1845
|
+
onClose();
|
|
1846
|
+
return;
|
|
1847
|
+
}
|
|
1848
|
+
closed.addEventListener("abort", onClose, { once: true });
|
|
1849
|
+
controller.signal.addEventListener("abort", () => closed.removeEventListener("abort", onClose), { once: true });
|
|
1850
|
+
}
|
|
1851
|
+
/**
|
|
1852
|
+
* The per-stream inactivity timeout (spec D8). Reset by any chunk in either
|
|
1853
|
+
* direction; elapsing aborts the stream. Unset, zero or non-finite installs no
|
|
1854
|
+
* timer at all, which is the default: a slow consumer is throttled, not failed.
|
|
1855
|
+
*/
|
|
1856
|
+
function installStreamTimeout(controller, timeout) {
|
|
1857
|
+
if (timeout === void 0 || !Number.isFinite(timeout) || timeout <= 0) return {
|
|
1858
|
+
touch() {},
|
|
1859
|
+
stop() {}
|
|
1860
|
+
};
|
|
1861
|
+
let timer;
|
|
1862
|
+
let stopped = false;
|
|
1863
|
+
const arm = () => {
|
|
1864
|
+
timer = setTimeout(() => {
|
|
1865
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error(`webrun-rpc: stream idle for ${timeout} ms`));
|
|
1866
|
+
}, timeout);
|
|
1867
|
+
};
|
|
1868
|
+
arm();
|
|
1869
|
+
return {
|
|
1870
|
+
touch() {
|
|
1871
|
+
if (stopped) return;
|
|
1872
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1873
|
+
arm();
|
|
1874
|
+
},
|
|
1875
|
+
stop() {
|
|
1876
|
+
stopped = true;
|
|
1877
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1878
|
+
timer = void 0;
|
|
1879
|
+
}
|
|
1880
|
+
};
|
|
1881
|
+
}
|
|
1882
|
+
/**
|
|
1883
|
+
* The receiving half of one direction.
|
|
1884
|
+
*
|
|
1885
|
+
* The `listenPort` listener is installed **eagerly**, not lazily inside
|
|
1886
|
+
* `recieveIterator`'s installer, because a handler that never drains its input
|
|
1887
|
+
* would otherwise leave the peer's chunk calls with nobody to answer them. If
|
|
1888
|
+
* the local consumer has not started iterating, an inbound chunk waits for it —
|
|
1889
|
+
* which is the correct backpressure, and different from having no listener.
|
|
1890
|
+
*/
|
|
1891
|
+
function receiveChunks(port, channelName, controller, touch) {
|
|
1892
|
+
let deliver;
|
|
1893
|
+
const waiting = [];
|
|
1894
|
+
let finished = false;
|
|
1895
|
+
let outstanding = false;
|
|
1896
|
+
let poison;
|
|
1897
|
+
let resolveEnded = () => {};
|
|
1898
|
+
const ended = new Promise((resolve) => {
|
|
1899
|
+
resolveEnded = resolve;
|
|
1900
|
+
});
|
|
1901
|
+
let aborted = false;
|
|
1902
|
+
let abortReason;
|
|
1903
|
+
const ready = () => deliver || finished ? Promise.resolve() : new Promise((r) => waiting.push(r));
|
|
1904
|
+
const wake = () => {
|
|
1905
|
+
for (const r of waiting.splice(0)) r();
|
|
1906
|
+
};
|
|
1907
|
+
const off = listenPort(port, async ({ done, value, error }) => {
|
|
1908
|
+
touch();
|
|
1909
|
+
if (poison) throw poison;
|
|
1910
|
+
if (outstanding) {
|
|
1911
|
+
poison = /* @__PURE__ */ new Error("webrun-rpc: peer sent a second unconfirmed chunk; the stream port is closed");
|
|
1912
|
+
controller.abort(poison);
|
|
1913
|
+
setTimeout(() => {
|
|
1914
|
+
try {
|
|
1915
|
+
port.close?.();
|
|
1916
|
+
} catch {}
|
|
1917
|
+
}, 0);
|
|
1918
|
+
throw poison;
|
|
1919
|
+
}
|
|
1920
|
+
outstanding = true;
|
|
1921
|
+
try {
|
|
1922
|
+
await ready();
|
|
1923
|
+
if (finished) throw poison ?? /* @__PURE__ */ new Error("webrun-rpc: the stream is closed");
|
|
1924
|
+
await deliver?.({
|
|
1925
|
+
done,
|
|
1926
|
+
value,
|
|
1927
|
+
error: error ? deserializeError(error) : void 0
|
|
1928
|
+
});
|
|
1929
|
+
} finally {
|
|
1930
|
+
outstanding = false;
|
|
1931
|
+
}
|
|
1932
|
+
if (done) resolveEnded();
|
|
1933
|
+
}, { channelName });
|
|
1934
|
+
const detach = () => {
|
|
1935
|
+
finished = true;
|
|
1936
|
+
wake();
|
|
1937
|
+
off();
|
|
1938
|
+
controller.signal.removeEventListener("abort", onAbort);
|
|
1939
|
+
resolveEnded();
|
|
1940
|
+
};
|
|
1941
|
+
const onAbort = () => {
|
|
1942
|
+
aborted = true;
|
|
1943
|
+
abortReason = controller.signal.reason;
|
|
1944
|
+
finished = true;
|
|
1945
|
+
wake();
|
|
1946
|
+
deliver?.({
|
|
1947
|
+
done: true,
|
|
1948
|
+
error: abortReason
|
|
1949
|
+
});
|
|
1950
|
+
resolveEnded();
|
|
1951
|
+
};
|
|
1952
|
+
controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
1953
|
+
return {
|
|
1954
|
+
stream: recieveIterator((d) => {
|
|
1955
|
+
if (aborted) {
|
|
1956
|
+
d({
|
|
1957
|
+
done: true,
|
|
1958
|
+
error: abortReason
|
|
1959
|
+
});
|
|
1960
|
+
return detach;
|
|
1961
|
+
}
|
|
1962
|
+
deliver = d;
|
|
1963
|
+
wake();
|
|
1964
|
+
return detach;
|
|
1965
|
+
}),
|
|
1966
|
+
stop: detach,
|
|
1967
|
+
ended
|
|
1968
|
+
};
|
|
1969
|
+
}
|
|
1970
|
+
/**
|
|
1971
|
+
* The sending half of one direction: one `callPort` per chunk, one call
|
|
1972
|
+
* outstanding at a time (spec D11/D12), with no per-chunk deadline (spec D8).
|
|
1973
|
+
*/
|
|
1974
|
+
async function sendChunks(port, channelName, output, { maxMessageSize, log }, signal, touch) {
|
|
1975
|
+
const stream = throughAbort(maxMessageSize ? toChunks(maxMessageSize)(output) : output, signal);
|
|
1976
|
+
try {
|
|
1977
|
+
await sendIterator(async ({ done, value, error }) => {
|
|
1978
|
+
if (signal.aborted) return;
|
|
1979
|
+
const chunk = {
|
|
1980
|
+
done,
|
|
1981
|
+
value,
|
|
1982
|
+
error: error === void 0 ? void 0 : serializeError(error)
|
|
1983
|
+
};
|
|
1984
|
+
log?.("[duplexOverPort] send", {
|
|
1985
|
+
channelName,
|
|
1986
|
+
done,
|
|
1987
|
+
size: value?.byteLength
|
|
1988
|
+
});
|
|
1989
|
+
await callPort(port, chunk, {
|
|
1990
|
+
channelName,
|
|
1991
|
+
timeout: NO_TIMEOUT,
|
|
1992
|
+
signal
|
|
1993
|
+
});
|
|
1994
|
+
touch();
|
|
1995
|
+
}, stream);
|
|
1996
|
+
} catch (err) {
|
|
1997
|
+
if (signal.aborted) return;
|
|
1998
|
+
throw err;
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
/**
|
|
2002
|
+
* One virtual port.
|
|
2003
|
+
*
|
|
2004
|
+
* `deliver` and `markClosed` are deliberately not on `port`: the consumer holds
|
|
2005
|
+
* only a `MessageTarget`, so it cannot forge inbound traffic or close the port
|
|
2006
|
+
* out from under the multiplexer's bookkeeping.
|
|
2007
|
+
*/
|
|
2008
|
+
function newVirtualPort(send, requestClose) {
|
|
2009
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
2010
|
+
let closed = false;
|
|
2011
|
+
const closing = new AbortController();
|
|
2012
|
+
const abort = (reason) => {
|
|
2013
|
+
if (closing.signal.aborted) return;
|
|
2014
|
+
closing.abort(reason ?? /* @__PURE__ */ new Error("webrun-rpc: the port was closed"));
|
|
2015
|
+
};
|
|
2016
|
+
const port = {
|
|
2017
|
+
addEventListener(_type, listener) {
|
|
2018
|
+
listeners.add(listener);
|
|
2019
|
+
},
|
|
2020
|
+
removeEventListener(_type, listener) {
|
|
2021
|
+
listeners.delete(listener);
|
|
2022
|
+
},
|
|
2023
|
+
postMessage(message, transfer) {
|
|
2024
|
+
if (closed) return;
|
|
2025
|
+
send(message, transfer);
|
|
2026
|
+
},
|
|
2027
|
+
close() {
|
|
2028
|
+
if (closed) return;
|
|
2029
|
+
closed = true;
|
|
2030
|
+
const notify = requestClose;
|
|
2031
|
+
listeners.clear();
|
|
2032
|
+
notify();
|
|
2033
|
+
abort();
|
|
2034
|
+
}
|
|
2035
|
+
};
|
|
2036
|
+
setPortCloseSignal(port, closing.signal);
|
|
2037
|
+
return {
|
|
2038
|
+
port,
|
|
2039
|
+
deliver(payload) {
|
|
2040
|
+
if (closed) return;
|
|
2041
|
+
const event = new MessageEvent("message", { data: payload });
|
|
2042
|
+
for (const listener of [...listeners]) try {
|
|
2043
|
+
listener(event);
|
|
2044
|
+
} catch {}
|
|
2045
|
+
},
|
|
2046
|
+
markClosed(reason) {
|
|
2047
|
+
closed = true;
|
|
2048
|
+
listeners.clear();
|
|
2049
|
+
abort(reason);
|
|
2050
|
+
},
|
|
2051
|
+
isClosed() {
|
|
2052
|
+
return closed;
|
|
2053
|
+
}
|
|
2054
|
+
};
|
|
2055
|
+
}
|
|
2056
|
+
/**
|
|
2057
|
+
* The message of the error that fails the calls still in flight on a
|
|
2058
|
+
* multiplexer when it is closed (`PortMux.close()`).
|
|
2059
|
+
*/
|
|
2060
|
+
const MUX_CLOSED_MESSAGE = "webrun-rpc: the multiplexer was closed";
|
|
2061
|
+
/** Ceiling on concurrently open virtual ports. Bounds the id table only. */
|
|
2062
|
+
const DEFAULT_MAX_PORTS = 1024;
|
|
2063
|
+
/**
|
|
2064
|
+
* The default `PortMux`: emulates multiplexing over a single port.
|
|
2065
|
+
*
|
|
2066
|
+
* A transport that already multiplexes natively supplies its own `PortMux`
|
|
2067
|
+
* instead — this implementation is for transports that offer one pipe.
|
|
2068
|
+
*/
|
|
2069
|
+
function multiplexPort(port, options) {
|
|
2070
|
+
const { codec, onPort, side = "initiator", maxPorts = DEFAULT_MAX_PORTS, maxMessageSize } = options;
|
|
2071
|
+
const open = /* @__PURE__ */ new Map();
|
|
2072
|
+
let nextId = side === "initiator" ? 0 : 1;
|
|
2073
|
+
let muxClosed = false;
|
|
2074
|
+
const post = (envelope, transfer) => {
|
|
2075
|
+
if (muxClosed) return;
|
|
2076
|
+
try {
|
|
2077
|
+
codec.post(port, envelope, transfer);
|
|
2078
|
+
} catch {}
|
|
2079
|
+
};
|
|
2080
|
+
const attach = (id) => {
|
|
2081
|
+
let self;
|
|
2082
|
+
self = newVirtualPort((payload, transfer) => post({
|
|
2083
|
+
type: "message",
|
|
2084
|
+
id,
|
|
2085
|
+
payload
|
|
2086
|
+
}, transfer), (reason) => {
|
|
2087
|
+
post({
|
|
2088
|
+
type: "close",
|
|
2089
|
+
id,
|
|
2090
|
+
reason
|
|
2091
|
+
});
|
|
2092
|
+
open.delete(id);
|
|
2093
|
+
self.markClosed();
|
|
2094
|
+
});
|
|
2095
|
+
open.set(id, self);
|
|
2096
|
+
return self;
|
|
2097
|
+
};
|
|
2098
|
+
const handleEnvelope = (envelope) => {
|
|
2099
|
+
if (muxClosed) return;
|
|
2100
|
+
if (envelope.type === "open") {
|
|
2101
|
+
if (open.has(envelope.id)) return;
|
|
2102
|
+
if (open.size >= maxPorts) {
|
|
2103
|
+
post({
|
|
2104
|
+
type: "close",
|
|
2105
|
+
id: envelope.id,
|
|
2106
|
+
reason: "max-ports"
|
|
2107
|
+
});
|
|
2108
|
+
return;
|
|
2109
|
+
}
|
|
2110
|
+
const handle = attach(envelope.id);
|
|
2111
|
+
let accepted = false;
|
|
2112
|
+
if (onPort) try {
|
|
2113
|
+
accepted = onPort(handle.port, envelope.meta) !== false;
|
|
2114
|
+
} catch {
|
|
2115
|
+
accepted = false;
|
|
2116
|
+
}
|
|
2117
|
+
if (!accepted) {
|
|
2118
|
+
open.delete(envelope.id);
|
|
2119
|
+
handle.markClosed(/* @__PURE__ */ new Error("webrun-rpc: the port was rejected"));
|
|
2120
|
+
post({
|
|
2121
|
+
type: "close",
|
|
2122
|
+
id: envelope.id,
|
|
2123
|
+
reason: "rejected"
|
|
2124
|
+
});
|
|
2125
|
+
}
|
|
2126
|
+
return;
|
|
2127
|
+
}
|
|
2128
|
+
const handle = open.get(envelope.id);
|
|
2129
|
+
if (envelope.type === "message") {
|
|
2130
|
+
if (!handle) return;
|
|
2131
|
+
handle.deliver(envelope.payload);
|
|
2132
|
+
return;
|
|
2133
|
+
}
|
|
2134
|
+
if (!handle) return;
|
|
2135
|
+
open.delete(envelope.id);
|
|
2136
|
+
handle.markClosed(/* @__PURE__ */ new Error("webrun-rpc: the peer closed the port"));
|
|
2137
|
+
};
|
|
2138
|
+
const listener = (event) => {
|
|
2139
|
+
const envelope = codec.read(event);
|
|
2140
|
+
if (envelope) handleEnvelope(envelope);
|
|
2141
|
+
};
|
|
2142
|
+
port.addEventListener("message", listener);
|
|
2143
|
+
port.start?.();
|
|
2144
|
+
return {
|
|
2145
|
+
maxMessageSize,
|
|
2146
|
+
async openPort(meta) {
|
|
2147
|
+
if (muxClosed) throw new Error("webrun-rpc: the multiplexer is closed");
|
|
2148
|
+
if (open.size >= maxPorts) throw new RangeError(`webrun-rpc: maxPorts (${maxPorts}) reached`);
|
|
2149
|
+
while (open.has(nextId)) nextId += 2;
|
|
2150
|
+
const id = nextId;
|
|
2151
|
+
nextId += 2;
|
|
2152
|
+
const handle = attach(id);
|
|
2153
|
+
post({
|
|
2154
|
+
type: "open",
|
|
2155
|
+
id,
|
|
2156
|
+
meta
|
|
2157
|
+
});
|
|
2158
|
+
return handle.port;
|
|
2159
|
+
},
|
|
2160
|
+
async close() {
|
|
2161
|
+
if (muxClosed) return;
|
|
2162
|
+
for (const [id, handle] of [...open]) {
|
|
2163
|
+
post({
|
|
2164
|
+
type: "close",
|
|
2165
|
+
id
|
|
2166
|
+
});
|
|
2167
|
+
open.delete(id);
|
|
2168
|
+
handle.markClosed(/* @__PURE__ */ new Error(MUX_CLOSED_MESSAGE));
|
|
2169
|
+
}
|
|
2170
|
+
muxClosed = true;
|
|
2171
|
+
port.removeEventListener("message", listener);
|
|
2172
|
+
await port.close?.();
|
|
2173
|
+
}
|
|
2174
|
+
};
|
|
2175
|
+
}
|
|
2176
|
+
/**
|
|
2177
|
+
* Announced with every port this pair opens. Layer 1 never reads `meta` — it is
|
|
2178
|
+
* here so a peer running something else over the same multiplexer can tell a
|
|
2179
|
+
* stream port from whatever else it hands out, and so a packet capture says
|
|
2180
|
+
* what the port is for.
|
|
2181
|
+
*/
|
|
2182
|
+
const STREAM_META = { kind: "stream" };
|
|
2183
|
+
/**
|
|
2184
|
+
* One port source in, one caller `Duplex` out.
|
|
2185
|
+
*
|
|
2186
|
+
* A call is a port: the mux allocates one, `duplexOverPort` runs the single
|
|
2187
|
+
* invocation on it, and closing the stream closes the port. No stream ids, no
|
|
2188
|
+
* framing and no credit accounting live here — the mux owns the first, and
|
|
2189
|
+
* `duplexOverPort` owns the one-chunk window that makes memory bounded.
|
|
2190
|
+
*/
|
|
2191
|
+
const connect = async ({ mux: factory, timeout }) => {
|
|
2192
|
+
const mux = await factory();
|
|
2193
|
+
const streamOptions = {
|
|
2194
|
+
maxMessageSize: mux.maxMessageSize,
|
|
2195
|
+
timeout
|
|
2196
|
+
};
|
|
2197
|
+
const call = (input) => (async function* () {
|
|
2198
|
+
yield* duplexOverPort(await mux.openPort(STREAM_META), streamOptions)(input);
|
|
2199
|
+
})();
|
|
2200
|
+
return {
|
|
2201
|
+
call,
|
|
2202
|
+
async close() {
|
|
2203
|
+
await mux.close();
|
|
2204
|
+
}
|
|
2205
|
+
};
|
|
2206
|
+
};
|
|
2207
|
+
/**
|
|
2208
|
+
* Ports over ONE PIPE OF BYTES — a `MessagePort`, a worker, a WebSocket.
|
|
2209
|
+
*
|
|
2210
|
+
* There is no second port to be had, so `multiplexPort`'s id table invents
|
|
2211
|
+
* them. Use this when the transport gives you exactly one channel.
|
|
2212
|
+
*/
|
|
2213
|
+
function overPipe(pipe, options) {
|
|
2214
|
+
return (onPort) => multiplexPort(pipe, {
|
|
2215
|
+
...options,
|
|
2216
|
+
onPort
|
|
2217
|
+
});
|
|
2218
|
+
}
|
|
2219
|
+
function isEnvelope(value) {
|
|
2220
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2221
|
+
const candidate = value;
|
|
2222
|
+
if (typeof candidate.id !== "number") return false;
|
|
2223
|
+
if (!Number.isInteger(candidate.id) || candidate.id < 0) return false;
|
|
2224
|
+
return candidate.type === "open" || candidate.type === "message" || candidate.type === "close";
|
|
2225
|
+
}
|
|
2226
|
+
/**
|
|
2227
|
+
* For ports whose messages are structured values — a real `MessagePort`, a
|
|
2228
|
+
* worker, an iframe.
|
|
2229
|
+
*
|
|
2230
|
+
* Envelopes are posted as-is, so nothing is encoded, `ArrayBuffer`s move
|
|
2231
|
+
* zero-copy through the transfer list, and structured clone does the work the
|
|
2232
|
+
* platform already does well. This is a performance choice only: layer 2 may
|
|
2233
|
+
* not send anything a byte codec could not also carry.
|
|
2234
|
+
*/
|
|
2235
|
+
const structuredCodec = {
|
|
2236
|
+
post(port, envelope, transfer) {
|
|
2237
|
+
if (transfer && transfer.length > 0) port.postMessage(envelope, transfer);
|
|
2238
|
+
else port.postMessage(envelope);
|
|
2239
|
+
},
|
|
2240
|
+
read(event) {
|
|
2241
|
+
return isEnvelope(event.data) ? event.data : void 0;
|
|
2242
|
+
}
|
|
2243
|
+
};
|
|
2244
|
+
//#endregion
|
|
2245
|
+
//#region src/link/http-link.ts
|
|
2246
|
+
/**
|
|
2247
|
+
* The version of the HTTP-over-`MessagePort` protocol this package speaks,
|
|
2248
|
+
* sent in every hand-shake that sets up a link. Version 1 was this package's
|
|
2249
|
+
* own `handleStreams` / `sendStream` (no backpressure); version 2 is
|
|
2250
|
+
* webrun-rpc's `connect` / `serve` over `overPipe` with webrun-http-streams'
|
|
2251
|
+
* `fetchOverDuplex` / `serveFetchOverDuplex`: one port per link, calls
|
|
2252
|
+
* multiplexed on it, each call a stream with a one-chunk window in both
|
|
2253
|
+
* directions, and cancellation that reaches the handler.
|
|
2254
|
+
*/
|
|
2255
|
+
const HTTP_LINK_PROTOCOL = "webrun-http-link/2";
|
|
2256
|
+
/**
|
|
2257
|
+
* Why a request failed when its link went away under it: the far side (the
|
|
2258
|
+
* handler, or the ServiceWorker) was lost. The request may or may not have
|
|
2259
|
+
* been applied.
|
|
2260
|
+
*/
|
|
2261
|
+
var LinkLostError = class extends Error {
|
|
2262
|
+
constructor(message = "The link was lost while this request was in flight") {
|
|
2263
|
+
super(`${message}; it may or may not have been applied.`);
|
|
2264
|
+
this.name = "LinkLostError";
|
|
2265
|
+
}
|
|
2266
|
+
};
|
|
2267
|
+
/**
|
|
2268
|
+
* Posted on a link's port by the calling end when it closes the link, so the
|
|
2269
|
+
* answering end can release it: a `MessagePort` never reports that its other
|
|
2270
|
+
* end is gone.
|
|
2271
|
+
*/
|
|
2272
|
+
const LINK_CLOSE = "webrun-http:link-close";
|
|
2273
|
+
/** Opens the calling end of a link on `port` (one port per link). */
|
|
2274
|
+
async function connectHttpLink(port, { streamTimeout } = {}) {
|
|
2275
|
+
const { call, close } = await connect({
|
|
2276
|
+
mux: overPipe(port, {
|
|
2277
|
+
codec: structuredCodec,
|
|
2278
|
+
side: "initiator"
|
|
2279
|
+
}),
|
|
2280
|
+
timeout: streamTimeout
|
|
2281
|
+
});
|
|
2282
|
+
return trackedLink((request) => fetchOverDuplex(call, request), async () => {
|
|
2283
|
+
try {
|
|
2284
|
+
port.postMessage({ type: LINK_CLOSE });
|
|
2285
|
+
} catch {}
|
|
2286
|
+
await close();
|
|
2287
|
+
});
|
|
2288
|
+
}
|
|
2289
|
+
/**
|
|
2290
|
+
* Wraps a `send` so the link knows its requests in flight (for draining and
|
|
2291
|
+
* load-based routing) and can fail them all at once when it is closed.
|
|
2292
|
+
*/
|
|
2293
|
+
function trackedLink(send, release) {
|
|
2294
|
+
let inflight = 0;
|
|
2295
|
+
let closed = false;
|
|
2296
|
+
let lostReason;
|
|
2297
|
+
const failers = /* @__PURE__ */ new Set();
|
|
2298
|
+
const idleWaiters = [];
|
|
2299
|
+
const done = () => {
|
|
2300
|
+
inflight--;
|
|
2301
|
+
if (inflight === 0) for (const resolve of idleWaiters.splice(0)) resolve();
|
|
2302
|
+
};
|
|
2303
|
+
return {
|
|
2304
|
+
get inflight() {
|
|
2305
|
+
return inflight;
|
|
2306
|
+
},
|
|
2307
|
+
get closed() {
|
|
2308
|
+
return closed;
|
|
2309
|
+
},
|
|
2310
|
+
whenIdle() {
|
|
2311
|
+
return inflight === 0 ? Promise.resolve() : new Promise((r) => idleWaiters.push(r));
|
|
2312
|
+
},
|
|
2313
|
+
async send(request) {
|
|
2314
|
+
if (closed) throw lostReason ?? new LinkLostError("The link is closed");
|
|
2315
|
+
inflight++;
|
|
2316
|
+
let finished = false;
|
|
2317
|
+
const finish = () => {
|
|
2318
|
+
if (finished) return;
|
|
2319
|
+
finished = true;
|
|
2320
|
+
failers.delete(fail);
|
|
2321
|
+
done();
|
|
2322
|
+
};
|
|
2323
|
+
let fail = () => {};
|
|
2324
|
+
const lost = new Promise((_, reject) => {
|
|
2325
|
+
fail = reject;
|
|
2326
|
+
});
|
|
2327
|
+
failers.add(fail);
|
|
2328
|
+
lost.catch(() => {});
|
|
2329
|
+
let response;
|
|
2330
|
+
try {
|
|
2331
|
+
response = await Promise.race([send(request), lost]);
|
|
2332
|
+
} catch (error) {
|
|
2333
|
+
finish();
|
|
2334
|
+
throw lostReason ?? error;
|
|
2335
|
+
}
|
|
2336
|
+
if (!response.body) {
|
|
2337
|
+
finish();
|
|
2338
|
+
return response;
|
|
2339
|
+
}
|
|
2340
|
+
return new Response(guardBody(response.body, lost, () => lostReason, finish), {
|
|
2341
|
+
status: response.status,
|
|
2342
|
+
statusText: response.statusText,
|
|
2343
|
+
headers: response.headers
|
|
2344
|
+
});
|
|
2345
|
+
},
|
|
2346
|
+
async close(reason) {
|
|
2347
|
+
if (closed) return;
|
|
2348
|
+
closed = true;
|
|
2349
|
+
lostReason = reason ?? new LinkLostError("The link was closed");
|
|
2350
|
+
for (const fail of [...failers]) fail(lostReason);
|
|
2351
|
+
try {
|
|
2352
|
+
await release();
|
|
2353
|
+
} catch {}
|
|
2354
|
+
}
|
|
2355
|
+
};
|
|
2356
|
+
}
|
|
2357
|
+
/**
|
|
2358
|
+
* A response body that reports its end (done, cancelled or failed) and fails
|
|
2359
|
+
* with the link's reason when the link is lost mid-stream.
|
|
2360
|
+
*/
|
|
2361
|
+
function guardBody(body, lost, reason, finish) {
|
|
2362
|
+
const reader = body.getReader();
|
|
2363
|
+
return new ReadableStream({
|
|
2364
|
+
async pull(controller) {
|
|
2365
|
+
try {
|
|
2366
|
+
const { done, value } = await Promise.race([reader.read(), lost]);
|
|
2367
|
+
if (done) {
|
|
2368
|
+
finish();
|
|
2369
|
+
controller.close();
|
|
2370
|
+
return;
|
|
2371
|
+
}
|
|
2372
|
+
controller.enqueue(value);
|
|
2373
|
+
} catch (error) {
|
|
2374
|
+
finish();
|
|
2375
|
+
reader.cancel().catch(() => {});
|
|
2376
|
+
controller.error(reason() ?? error);
|
|
2377
|
+
}
|
|
2378
|
+
},
|
|
2379
|
+
async cancel(why) {
|
|
2380
|
+
finish();
|
|
2381
|
+
await reader.cancel(why).catch(() => {});
|
|
2382
|
+
}
|
|
2383
|
+
});
|
|
2384
|
+
}
|
|
2385
|
+
//#endregion
|
|
2386
|
+
//#region src/sw/protocol.ts
|
|
2387
|
+
/** Page → ServiceWorker: open a WebSocket to a handler. */
|
|
2388
|
+
const WS_CONNECT_CALL = "webrun-http:ws-connect";
|
|
2389
|
+
//#endregion
|
|
1338
2390
|
//#region src/core/data-channels.ts
|
|
1339
2391
|
const MESSAGE_TYPE_REQUEST = "REQUEST";
|
|
1340
2392
|
const MESSAGE_TYPE_RESPONSE = "RESPONSE";
|
|
@@ -1533,51 +2585,6 @@
|
|
|
1533
2585
|
})(request);
|
|
1534
2586
|
}
|
|
1535
2587
|
//#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
2588
|
//#region src/relay/split-service-url.ts
|
|
1582
2589
|
/**
|
|
1583
2590
|
* Splits a URL of the form `<base>/<separator><key>/<path>` into parts.
|
|
@@ -1635,6 +2642,69 @@
|
|
|
1635
2642
|
path: slash < 0 ? "" : rest.slice(slash + 1)
|
|
1636
2643
|
};
|
|
1637
2644
|
}
|
|
2645
|
+
self.location.href;
|
|
2646
|
+
/**
|
|
2647
|
+
* Sends `request` on a port a service accepted with `reply`: over an HTTP link
|
|
2648
|
+
* when the service speaks `HTTP_LINK_PROTOCOL`, over version 1's transport
|
|
2649
|
+
* when it answered `true`. The link is closed once the response is done.
|
|
2650
|
+
*/
|
|
2651
|
+
async function sendOverConnection(port, reply, request, options = {}) {
|
|
2652
|
+
if (reply === true) return await sendHttpRequest(port, request);
|
|
2653
|
+
const link = await connectHttpLink(port, options);
|
|
2654
|
+
try {
|
|
2655
|
+
const response = await link.send(request);
|
|
2656
|
+
link.whenIdle().then(() => link.close());
|
|
2657
|
+
return response;
|
|
2658
|
+
} catch (error) {
|
|
2659
|
+
await link.close();
|
|
2660
|
+
throw error;
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
//#endregion
|
|
2664
|
+
//#region src/relay/mount-table.ts
|
|
2665
|
+
/** `/` stays `/`; `/peers` and `/peers/` both become `/peers/`. */
|
|
2666
|
+
function normalise(path) {
|
|
2667
|
+
if (path === "" || path === "/") return "/";
|
|
2668
|
+
const withSlash = path.startsWith("/") ? path : `/${path}`;
|
|
2669
|
+
return withSlash.endsWith("/") ? withSlash : `${withSlash}/`;
|
|
2670
|
+
}
|
|
2671
|
+
/** Does `prefix` own `pathname`? `/peers/` owns `/peers/`, `/peers` and `/peers/x`. */
|
|
2672
|
+
function owns(prefix, pathname) {
|
|
2673
|
+
if (prefix === "/") return true;
|
|
2674
|
+
if (pathname.startsWith(prefix)) return true;
|
|
2675
|
+
return `${pathname}/` === prefix;
|
|
2676
|
+
}
|
|
2677
|
+
function newMountTable(options = {}) {
|
|
2678
|
+
const entries = /* @__PURE__ */ new Map();
|
|
2679
|
+
let seq = 0;
|
|
2680
|
+
return {
|
|
2681
|
+
set(key, spec) {
|
|
2682
|
+
entries.set(key, {
|
|
2683
|
+
key,
|
|
2684
|
+
prefix: spec.path == null ? "" : normalise(spec.path),
|
|
2685
|
+
match: spec.match,
|
|
2686
|
+
seq: seq++
|
|
2687
|
+
});
|
|
2688
|
+
},
|
|
2689
|
+
remove(key) {
|
|
2690
|
+
entries.delete(key);
|
|
2691
|
+
},
|
|
2692
|
+
excludes(url) {
|
|
2693
|
+
return options.exclude?.(url) === true;
|
|
2694
|
+
},
|
|
2695
|
+
find(url) {
|
|
2696
|
+
if (options.exclude?.(url) === true) return void 0;
|
|
2697
|
+
let best;
|
|
2698
|
+
for (const entry of entries.values()) {
|
|
2699
|
+
if (entry.prefix === "" || !owns(entry.prefix, url.pathname)) continue;
|
|
2700
|
+
if (best == null || entry.prefix.length > best.prefix.length) best = entry;
|
|
2701
|
+
}
|
|
2702
|
+
if (best != null) return best.key;
|
|
2703
|
+
const predicates = [...entries.values()].filter((entry) => entry.match != null).sort((a, b) => a.seq - b.seq);
|
|
2704
|
+
for (const entry of predicates) if (entry.match?.(url) === true) return entry.key;
|
|
2705
|
+
}
|
|
2706
|
+
};
|
|
2707
|
+
}
|
|
1638
2708
|
//#endregion
|
|
1639
2709
|
//#region src/relay/index-sw.ts
|
|
1640
2710
|
/**
|
|
@@ -1762,7 +2832,7 @@
|
|
|
1762
2832
|
const source = event.source;
|
|
1763
2833
|
if (!source) return false;
|
|
1764
2834
|
const { key, path } = data;
|
|
1765
|
-
if (options.canRegister != null && !await options.canRegister(source, key)) throw new Error(`this client may not register "${key}"`);
|
|
2835
|
+
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
2836
|
if (takeover === "first-wins") {
|
|
1767
2837
|
const current = await clientsRegistry.getMount(key);
|
|
1768
2838
|
const isCurrentLive = current != null && await clientsRegistry.getClient(key) != null;
|
|
@@ -1777,8 +2847,14 @@
|
|
|
1777
2847
|
applyRegisteredMount(mounts, key, path, hostKeys);
|
|
1778
2848
|
return added;
|
|
1779
2849
|
}));
|
|
1780
|
-
register(handleChannelCalls(self, "UNREGISTER", async (
|
|
2850
|
+
register(handleChannelCalls(self, "UNREGISTER", async (event, data) => {
|
|
2851
|
+
const source = event.source;
|
|
2852
|
+
if (!source) return false;
|
|
1781
2853
|
const { key } = data;
|
|
2854
|
+
const current = await clientsRegistry.getMount(key);
|
|
2855
|
+
if (current == null) return false;
|
|
2856
|
+
if (await clientsRegistry.getClient(key) != null && current.clientId !== source.id) throw new Error(`"${key}" is served by another client`);
|
|
2857
|
+
if (options.canRegister != null && !await options.canRegister(source, key, current.path)) throw new Error(`this client may not unregister "${key}"`);
|
|
1782
2858
|
removeRegisteredMount(mounts, key, hostKeys);
|
|
1783
2859
|
return await clientsRegistry.removeClient(key);
|
|
1784
2860
|
}));
|
|
@@ -1786,7 +2862,34 @@
|
|
|
1786
2862
|
const { key } = data;
|
|
1787
2863
|
const client = await clientsRegistry.getClient(key);
|
|
1788
2864
|
if (!client) throw new Error(`Target client was not found. Target key: "${key}".`);
|
|
1789
|
-
|
|
2865
|
+
const reply = await callChannel(client, "CONNECT", data, port);
|
|
2866
|
+
const socketPort = reply?.port;
|
|
2867
|
+
return socketPort ? withTransfer(reply, [socketPort]) : reply;
|
|
2868
|
+
}));
|
|
2869
|
+
register(handleChannelCalls(self, WS_CONNECT_CALL, async (event, data) => {
|
|
2870
|
+
const source = event.source;
|
|
2871
|
+
if (!source?.url || new URL(source.url).origin !== self.location.origin) throw new Error("Only this origin's pages may open sockets");
|
|
2872
|
+
const { url, protocols = [] } = data;
|
|
2873
|
+
const httpUrl = new URL(url);
|
|
2874
|
+
if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
|
|
2875
|
+
else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
|
|
2876
|
+
await restored.catch(() => {});
|
|
2877
|
+
const key = resolveServiceKey(httpUrl, mounts, self.location.origin);
|
|
2878
|
+
if (key == null) throw new Error(`No service serves ${url}`);
|
|
2879
|
+
const client = await clientsRegistry.getClient(key);
|
|
2880
|
+
if (!client) throw new Error(`No service serves ${url}`);
|
|
2881
|
+
const channel = new MessageChannel();
|
|
2882
|
+
try {
|
|
2883
|
+
const connection = await callChannel(client, "CONNECT", {
|
|
2884
|
+
type: "ws",
|
|
2885
|
+
key,
|
|
2886
|
+
url: `${httpUrl}`,
|
|
2887
|
+
protocols
|
|
2888
|
+
}, channel.port2);
|
|
2889
|
+
return withTransfer(connection, [connection.port]);
|
|
2890
|
+
} finally {
|
|
2891
|
+
channel.port1.close();
|
|
2892
|
+
}
|
|
1790
2893
|
}));
|
|
1791
2894
|
/** Answers `request` as the service registered under `key`. */
|
|
1792
2895
|
async function serve(key, request, url) {
|
|
@@ -1795,11 +2898,13 @@
|
|
|
1795
2898
|
const channel = new MessageChannel();
|
|
1796
2899
|
const client = await clientsRegistry.getClient(key);
|
|
1797
2900
|
if (!client) throw HttpError.errorResourceGone(params);
|
|
1798
|
-
|
|
2901
|
+
const reply = await callChannel(client, "CONNECT", {
|
|
1799
2902
|
type: "http",
|
|
1800
|
-
key
|
|
1801
|
-
|
|
1802
|
-
|
|
2903
|
+
key,
|
|
2904
|
+
wire: HTTP_LINK_PROTOCOL
|
|
2905
|
+
}, channel.port2);
|
|
2906
|
+
if (!reply) throw HttpError.errorForbidden(params);
|
|
2907
|
+
const response = await sendOverConnection(channel.port1, reply, request, { streamTimeout: options.streamTimeout });
|
|
1803
2908
|
return options.decorateResponse?.(response, request) ?? response;
|
|
1804
2909
|
} catch (error) {
|
|
1805
2910
|
const httpError = HttpError.fromError(error);
|