@statewalker/webrun-http-browser 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +321 -50
- package/demo/demo-1.html +109 -194
- package/demo/demo-2.html +119 -580
- package/dist/core/data-calls.d.ts +5 -0
- package/dist/core/data-calls.d.ts.map +1 -0
- package/dist/core/data-channels.d.ts +17 -0
- package/dist/core/data-channels.d.ts.map +1 -0
- package/dist/core/index.d.ts +6 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/message-target.d.ts +16 -0
- package/dist/core/message-target.d.ts.map +1 -0
- package/dist/core/registry.d.ts +18 -0
- package/dist/core/registry.d.ts.map +1 -0
- package/dist/http/http-send-recieve.d.ts +23 -0
- package/dist/http/http-send-recieve.d.ts.map +1 -0
- package/dist/http/index.d.ts +4 -0
- package/dist/http/index.d.ts.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2541 -807
- package/dist/relay/index-sw.d.ts +7 -0
- package/dist/relay/index-sw.d.ts.map +1 -0
- package/dist/relay/index.d.ts +69 -0
- package/dist/relay/index.d.ts.map +1 -0
- package/dist/relay/split-service-url.d.ts +13 -0
- package/dist/relay/split-service-url.d.ts.map +1 -0
- package/dist/relay-sw.d.ts +2 -0
- package/dist/relay-sw.d.ts.map +1 -0
- package/dist/relay-sw.js +878 -0
- package/dist/sw/http-sw-dispatcher.d.ts +28 -0
- package/dist/sw/http-sw-dispatcher.d.ts.map +1 -0
- package/dist/sw/index.d.ts +3 -0
- package/dist/sw/index.d.ts.map +1 -0
- package/dist/sw/sw-dispatcher.d.ts +74 -0
- package/dist/sw/sw-dispatcher.d.ts.map +1 -0
- package/dist/sw-worker.d.ts +2 -0
- package/dist/sw-worker.d.ts.map +1 -0
- package/dist/sw-worker.js +813 -0
- package/dist/sw.d.ts +2 -0
- package/dist/sw.d.ts.map +1 -0
- package/dist/sw.js +1076 -0
- package/package.json +50 -37
- package/public/index.html +61 -97
- package/public/index.js +7 -4
- package/public/sw-worker.js +4 -0
- package/public-relay/heartbeat.js +4 -3
- package/public-relay/relay-sw.js +4 -6
- package/public-relay/relay.html +16 -11
- package/src/core/data-calls.ts +46 -0
- package/src/core/data-channels.ts +224 -0
- package/src/core/index.ts +9 -0
- package/src/core/message-target.ts +18 -0
- package/src/core/registry.ts +54 -0
- package/src/http/http-send-recieve.ts +81 -0
- package/src/http/index.ts +7 -0
- package/src/index.ts +3 -0
- package/src/relay/index-sw.ts +145 -0
- package/src/relay/index.ts +261 -0
- package/src/relay/split-service-url.ts +30 -0
- package/src/relay-sw.ts +7 -0
- package/src/sw/http-sw-dispatcher.ts +122 -0
- package/src/sw/index.ts +2 -0
- package/src/sw/sw-dispatcher.ts +307 -0
- package/src/sw-worker.ts +7 -0
- package/src/sw.ts +1 -0
- package/CHANGELOG.md +0 -1
- package/demo/demo-3.html +0 -167
- package/dist/index-sw-umd.js +0 -798
- package/dist/index-sw-umd.min.js +0 -2
- package/dist/index-sw.js +0 -791
- package/dist/index-sw.min.js +0 -2
- package/dist/index-umd.js +0 -853
- package/dist/index-umd.min.js +0 -2
- package/dist/index.min.js +0 -2
- package/index.js +0 -1
- package/src/core/data-calls.js +0 -36
- package/src/core/data-channels.js +0 -192
- package/src/core/data-send-recieve.js +0 -28
- package/src/core/errors.js +0 -13
- package/src/core/index.js +0 -4
- package/src/http/HttpError.js +0 -59
- package/src/http/http-send-recieve.js +0 -40
- package/src/http/http-stubs.js +0 -135
- package/src/http/index.js +0 -3
- package/src/http/readable-streams.js +0 -33
- package/src/index.js +0 -7
- package/src/relay/index-sw.js +0 -216
- package/src/relay/index.js +0 -263
- package/src/relay/splitServiceUrl.js +0 -24
- package/src/sw/http-sw-dispatcher.js +0 -128
- package/src/sw/sw-dispatcher.js +0 -264
|
@@ -0,0 +1,813 @@
|
|
|
1
|
+
(function() {
|
|
2
|
+
//#region ../webrun-http-streams/src/bytes.ts
|
|
3
|
+
function toAsyncIterator(input) {
|
|
4
|
+
const asyncIter = input[Symbol.asyncIterator];
|
|
5
|
+
if (asyncIter) return asyncIter.call(input);
|
|
6
|
+
const syncIter = input[Symbol.iterator]();
|
|
7
|
+
return { next() {
|
|
8
|
+
return Promise.resolve(syncIter.next());
|
|
9
|
+
} };
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Discard an iterable we are contractually forbidden from consuming — a body
|
|
13
|
+
* skipped for HEAD/204, or one abandoned because the peer reported an error.
|
|
14
|
+
*
|
|
15
|
+
* The `.next()` is not optional: `.return()` on a generator still in suspended
|
|
16
|
+
* start is a no-op, so the body never runs and its `try/finally` never unwinds.
|
|
17
|
+
* Without it a wrapped ReadableStream or socket is never cancelled.
|
|
18
|
+
*/
|
|
19
|
+
async function discard(source) {
|
|
20
|
+
if (source === void 0) return;
|
|
21
|
+
const it = toAsyncIterator(source);
|
|
22
|
+
try {
|
|
23
|
+
await it.next();
|
|
24
|
+
await it.return?.();
|
|
25
|
+
} catch {}
|
|
26
|
+
}
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region ../webrun-streams/src/errors.ts
|
|
29
|
+
function serializeError(error) {
|
|
30
|
+
if (error instanceof Error) {
|
|
31
|
+
const out = {
|
|
32
|
+
message: error.message,
|
|
33
|
+
stack: error.stack
|
|
34
|
+
};
|
|
35
|
+
const bag = error;
|
|
36
|
+
for (const key of Object.keys(bag)) out[key] = bag[key];
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
if (typeof error === "object" && error !== null) {
|
|
40
|
+
const bag = error;
|
|
41
|
+
return {
|
|
42
|
+
message: String(bag.message ?? error),
|
|
43
|
+
...bag
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
return { message: String(error) };
|
|
47
|
+
}
|
|
48
|
+
function deserializeError(error) {
|
|
49
|
+
const payload = typeof error === "string" ? { message: error } : error;
|
|
50
|
+
return Object.assign(new Error(payload.message), payload);
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region ../webrun-streams/src/new-async-generator.ts
|
|
54
|
+
/**
|
|
55
|
+
* The newAsyncGenerator function creates async generators from callback-based initialization
|
|
56
|
+
* functions, providing a bridge between imperative event handling and declarative async
|
|
57
|
+
* iteration patterns.
|
|
58
|
+
*
|
|
59
|
+
* The initialization function receives two callback functions that control the generator's
|
|
60
|
+
* behavior. The `next` function yields values to consumers, while the `done` function
|
|
61
|
+
* signals completion or error conditions. The initialization function can return a cleanup
|
|
62
|
+
* function that will be called when the generator is closed or an error occurs.
|
|
63
|
+
*
|
|
64
|
+
* The generator manages an internal queue of values and completion signals, ensuring that
|
|
65
|
+
* producers can yield values without overwhelming consumers. Proper backpressure is implemented
|
|
66
|
+
* by having the `next` and `done` functions return promises that resolve only after the
|
|
67
|
+
* consumer has processed the values. This prevents memory leaks and ensures that producers
|
|
68
|
+
* are aware of whether their values were successfully handled.
|
|
69
|
+
* The generator also handles cleanup by draining any remaining items in the queue and notifying
|
|
70
|
+
* producers that their values were not processed if the generator is closed early. This ensures
|
|
71
|
+
* that resources are properly managed and that no memory leaks occur.
|
|
72
|
+
*
|
|
73
|
+
* Example usage:
|
|
74
|
+
* ```typescript
|
|
75
|
+
* const asyncGen = newAsyncGenerator<number>((next, done) => {
|
|
76
|
+
* let count = 0;
|
|
77
|
+
* const interval = setInterval(() => {
|
|
78
|
+
* if (count < 5) {
|
|
79
|
+
* next(count++);
|
|
80
|
+
* } else {
|
|
81
|
+
* done();
|
|
82
|
+
* clearInterval(interval);
|
|
83
|
+
* }
|
|
84
|
+
* }, 1000);
|
|
85
|
+
* return () => clearInterval(interval); // Cleanup function
|
|
86
|
+
* });
|
|
87
|
+
* (async () => {
|
|
88
|
+
* for await (const num of asyncGen) {
|
|
89
|
+
* console.log(num); // Logs numbers 0 to 4 at 1 second intervals
|
|
90
|
+
* }
|
|
91
|
+
* console.log("Completed");
|
|
92
|
+
* })();
|
|
93
|
+
* ```
|
|
94
|
+
* @template T The type of values yielded by the generator
|
|
95
|
+
* @template E The type of errors that can be thrown; defaults to Error
|
|
96
|
+
* @param init Initialization function that sets up the generator behavior with next/done callbacks;
|
|
97
|
+
* The first parameter - `next` function - is used to yield values to consumers;
|
|
98
|
+
* It returns a Promise<boolean> indicating whether the value was successfully handled;
|
|
99
|
+
* The second parameter - `done` function - is used to signal completion or error;
|
|
100
|
+
* It returns a Promise<boolean> indicating whether the completion was successfully handled;
|
|
101
|
+
* The initialization function can optionally return a cleanup function that will be called
|
|
102
|
+
* when the generator is closed or an error occurs;
|
|
103
|
+
* @param skipValues If true, only the most recent value is kept in the queue,
|
|
104
|
+
* skipping intermediate values (not consumed values are considered skipped);
|
|
105
|
+
* This is useful for scenarios where only the latest value matters, such as UI updates.
|
|
106
|
+
* Defaults to false, meaning all values are queued and processed in order.
|
|
107
|
+
* @returns AsyncGenerator that properly manages backpressure and resource cleanup
|
|
108
|
+
*/
|
|
109
|
+
async function* newAsyncGenerator(init, skipValues = false) {
|
|
110
|
+
let head;
|
|
111
|
+
let tail;
|
|
112
|
+
/** Flag to prevent new values from being queued after generator closes */
|
|
113
|
+
let closed = false;
|
|
114
|
+
/** Wake-up function to notify the generator loop of new items */
|
|
115
|
+
let wakeUp;
|
|
116
|
+
/**
|
|
117
|
+
* Drains the internal queue, notifying all pending producers that their values
|
|
118
|
+
* were not processed due to generator closure. This prevents memory leaks and
|
|
119
|
+
* ensures proper backpressure signaling.
|
|
120
|
+
*/
|
|
121
|
+
const drainQueue = () => {
|
|
122
|
+
for (; head; head = head.next) {
|
|
123
|
+
closed = closed || head.done;
|
|
124
|
+
head.resolve(false);
|
|
125
|
+
}
|
|
126
|
+
tail = void 0;
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Enqueues a value or completion signal with a promise that resolves when the item
|
|
130
|
+
* is processed. This enables backpressure by allowing producers to know when their
|
|
131
|
+
* values have been consumed.
|
|
132
|
+
*/
|
|
133
|
+
const enqueue = (params) => {
|
|
134
|
+
if (skipValues) drainQueue();
|
|
135
|
+
return !closed ? new Promise((resolve) => {
|
|
136
|
+
const next = {
|
|
137
|
+
...params,
|
|
138
|
+
next: void 0,
|
|
139
|
+
resolve
|
|
140
|
+
};
|
|
141
|
+
if (tail) tail.next = next;
|
|
142
|
+
tail = next;
|
|
143
|
+
if (!head) head = tail;
|
|
144
|
+
wakeUp?.();
|
|
145
|
+
}) : Promise.resolve(false);
|
|
146
|
+
};
|
|
147
|
+
/**
|
|
148
|
+
* Producer function to yield a value to consumers. Returns a promise that resolves
|
|
149
|
+
* to true if the value was successfully processed, false if the generator is closed
|
|
150
|
+
* or the value was skipped due to backpressure.
|
|
151
|
+
*/
|
|
152
|
+
const next = (value) => enqueue({
|
|
153
|
+
done: false,
|
|
154
|
+
value
|
|
155
|
+
});
|
|
156
|
+
/**
|
|
157
|
+
* Producer function to signal completion or error. Optional error parameter will
|
|
158
|
+
* cause the generator to throw that error to consumers.
|
|
159
|
+
*/
|
|
160
|
+
const done = (error) => enqueue({
|
|
161
|
+
done: true,
|
|
162
|
+
error
|
|
163
|
+
});
|
|
164
|
+
const unsubscribe = init(next, done);
|
|
165
|
+
try {
|
|
166
|
+
while (!closed) {
|
|
167
|
+
if (!head) {
|
|
168
|
+
await new Promise((resolve) => {
|
|
169
|
+
wakeUp = resolve;
|
|
170
|
+
}).then(() => {
|
|
171
|
+
wakeUp = void 0;
|
|
172
|
+
});
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
const slot = head;
|
|
176
|
+
head = head.next;
|
|
177
|
+
if (tail === slot) tail = head;
|
|
178
|
+
try {
|
|
179
|
+
if (slot.done) {
|
|
180
|
+
closed = true;
|
|
181
|
+
if (slot.error !== void 0) throw slot.error;
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
yield slot.value;
|
|
185
|
+
} finally {
|
|
186
|
+
slot.resolve(true);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
} finally {
|
|
190
|
+
/**
|
|
191
|
+
* Cleanup phase - ensures proper resource management and notification of any
|
|
192
|
+
* remaining producers. This runs whether the generator completes normally,
|
|
193
|
+
* encounters an error, or is closed early by the consumer.
|
|
194
|
+
*/
|
|
195
|
+
closed = true;
|
|
196
|
+
wakeUp?.();
|
|
197
|
+
if (typeof unsubscribe === "function") await unsubscribe();
|
|
198
|
+
/**
|
|
199
|
+
* Drain any remaining items in the queue and notify their producers that
|
|
200
|
+
* the values were not processed. This prevents memory leaks and ensures
|
|
201
|
+
* proper backpressure signaling.
|
|
202
|
+
*/
|
|
203
|
+
drainQueue();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
//#endregion
|
|
207
|
+
//#region ../webrun-streams/src/readable-streams.ts
|
|
208
|
+
function toReadableStream(it) {
|
|
209
|
+
return new ReadableStream({ async pull(controller) {
|
|
210
|
+
let handled = false;
|
|
211
|
+
try {
|
|
212
|
+
while (true) {
|
|
213
|
+
const slot = await it.next();
|
|
214
|
+
if (!slot || slot.done) break;
|
|
215
|
+
const value = await slot.value;
|
|
216
|
+
controller.enqueue(value);
|
|
217
|
+
}
|
|
218
|
+
} catch (error) {
|
|
219
|
+
handled = true;
|
|
220
|
+
controller.error(error);
|
|
221
|
+
} finally {
|
|
222
|
+
if (!handled) controller.close();
|
|
223
|
+
}
|
|
224
|
+
} });
|
|
225
|
+
}
|
|
226
|
+
async function* fromReadableStream(stream) {
|
|
227
|
+
const reader = stream.getReader();
|
|
228
|
+
while (true) {
|
|
229
|
+
const { done, value } = await reader.read();
|
|
230
|
+
if (done) break;
|
|
231
|
+
if (value !== void 0) yield value;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
//#endregion
|
|
235
|
+
//#region ../webrun-streams/src/recieve-iterator.ts
|
|
236
|
+
/**
|
|
237
|
+
* Inverse of {@link sendIterator}: turns a sequence of `{done, value, error}`
|
|
238
|
+
* chunks (delivered to the supplied callback by `installer`) into an async
|
|
239
|
+
* generator.
|
|
240
|
+
*
|
|
241
|
+
* The `installer` is given a `deliver` function. It should call `deliver`
|
|
242
|
+
* once for each incoming chunk and may return a cleanup callback that
|
|
243
|
+
* runs when the consumer stops iterating.
|
|
244
|
+
*/
|
|
245
|
+
function recieveIterator(installer) {
|
|
246
|
+
return newAsyncGenerator((next, done) => {
|
|
247
|
+
const cleanup = installer(async (chunk = { done: true }) => {
|
|
248
|
+
const { done: isDone = true, value, error } = chunk;
|
|
249
|
+
if (error) return await done(error);
|
|
250
|
+
if (isDone) return await done();
|
|
251
|
+
return await next(value);
|
|
252
|
+
});
|
|
253
|
+
if (cleanup) return async () => {
|
|
254
|
+
await cleanup();
|
|
255
|
+
};
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
//#endregion
|
|
259
|
+
//#region ../webrun-streams/src/send-iterator.ts
|
|
260
|
+
/**
|
|
261
|
+
* Drain an async iterator into a sink that consumes one chunk at a time.
|
|
262
|
+
*
|
|
263
|
+
* Each yielded value becomes `{ done: false, value }`. Completion emits
|
|
264
|
+
* `{ done: true }`. If the iterator throws, the error is caught and the
|
|
265
|
+
* final `done` chunk carries it so the peer can rethrow on its side.
|
|
266
|
+
*/
|
|
267
|
+
async function sendIterator(send, it) {
|
|
268
|
+
let error;
|
|
269
|
+
try {
|
|
270
|
+
for await (const value of it) await send({
|
|
271
|
+
done: false,
|
|
272
|
+
value
|
|
273
|
+
});
|
|
274
|
+
} catch (err) {
|
|
275
|
+
error = err;
|
|
276
|
+
} finally {
|
|
277
|
+
await send({
|
|
278
|
+
done: true,
|
|
279
|
+
error
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
//#endregion
|
|
284
|
+
//#region ../webrun-http-streams/src/request-streams.ts
|
|
285
|
+
/**
|
|
286
|
+
* The one place that knows a runtime may not implement request body streams,
|
|
287
|
+
* and the buffering both fallbacks need. `fetch.ts` and `http-stubs.ts` each
|
|
288
|
+
* carry a client and a server direction that must agree on the answer, so the
|
|
289
|
+
* predicate lives here rather than being written out four times.
|
|
290
|
+
*/
|
|
291
|
+
/**
|
|
292
|
+
* Whether `Request.prototype` exposes a `body` accessor. Two call sites read
|
|
293
|
+
* that property, and two more depend on the constructor accepting a
|
|
294
|
+
* `ReadableStream` as `init.body`; this predicate answers for all four.
|
|
295
|
+
*
|
|
296
|
+
* What was verified, and all that is claimed here: Firefox (146 at the time of
|
|
297
|
+
* writing) has *neither*, and Chromium and Node have *both*. On Firefox it is
|
|
298
|
+
* not that `body` is `undefined` on the instance —
|
|
299
|
+
* `Object.getOwnPropertyDescriptor(Request.prototype, "body")` is `null`, the
|
|
300
|
+
* accessor is genuinely absent — and because a `ReadableStream` is then not a
|
|
301
|
+
* recognised `BodyInit`, the constructor falls through to the string branch and
|
|
302
|
+
* stores the literal text `[object ReadableStream]`.
|
|
303
|
+
*
|
|
304
|
+
* The two halves are NOT guaranteed to ship together, so do not read this as a
|
|
305
|
+
* test for "request streams" in general. Safari is the counterexample: it has
|
|
306
|
+
* had `Request.body` since 11.1 but only accepts a stream as `init.body` from
|
|
307
|
+
* Technology Preview 250, so a shipping Safari has the reader half without the
|
|
308
|
+
* upload half and this returns `true` there. That looks benign — WebKit appears
|
|
309
|
+
* to store the stream on the `Request` rather than stringify it, and its error
|
|
310
|
+
* comes from `fetch()`, which this package never calls on the objects it builds
|
|
311
|
+
* — but it is untested, and it is the case to look at first if a Safari report
|
|
312
|
+
* arrives. The sharper probe, if one is ever needed, is whether
|
|
313
|
+
* `new Request(url, {method:"POST", body:new ReadableStream(), duplex:"half"})`
|
|
314
|
+
* has a `content-type` of `text/plain;charset=UTF-8` (stringified) or `null`
|
|
315
|
+
* (stored); it is not used here because it costs a `Request` and a
|
|
316
|
+
* `ReadableStream` per call and agrees with the descriptor check on every
|
|
317
|
+
* runtime measured.
|
|
318
|
+
*
|
|
319
|
+
* A capability check, never a user-agent test: the question is what this
|
|
320
|
+
* runtime does, and the answer flips on its own the day Firefox ships request
|
|
321
|
+
* streams. Evaluated per call rather than cached at module load so that a test
|
|
322
|
+
* can install a `Request` without the capability and exercise the real branch
|
|
323
|
+
* under Node.
|
|
324
|
+
*/
|
|
325
|
+
function supportsRequestStreams() {
|
|
326
|
+
return typeof Request === "function" && Object.getOwnPropertyDescriptor(Request.prototype, "body") != null;
|
|
327
|
+
}
|
|
328
|
+
//#endregion
|
|
329
|
+
//#region ../webrun-http-streams/src/http-stubs.ts
|
|
330
|
+
const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
|
|
331
|
+
101,
|
|
332
|
+
103,
|
|
333
|
+
204,
|
|
334
|
+
205,
|
|
335
|
+
304
|
|
336
|
+
]);
|
|
337
|
+
const REQUEST_FIELDS = [
|
|
338
|
+
"url",
|
|
339
|
+
"method",
|
|
340
|
+
"mode",
|
|
341
|
+
"credentials",
|
|
342
|
+
"cache",
|
|
343
|
+
"redirect",
|
|
344
|
+
"referrer",
|
|
345
|
+
"referrerPolicy",
|
|
346
|
+
"integrity",
|
|
347
|
+
"keepalive"
|
|
348
|
+
];
|
|
349
|
+
/** `SerializedHttpEnvelope.content` is never absent, only empty. */
|
|
350
|
+
async function* noBytes() {}
|
|
351
|
+
async function* oneChunk(chunk) {
|
|
352
|
+
yield chunk;
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Returns an HTTP handler that serializes a Request, hands the envelope to
|
|
356
|
+
* `send` for transport, and deserializes the reply into a Response. Used on
|
|
357
|
+
* the caller side.
|
|
358
|
+
*/
|
|
359
|
+
function newHttpClientStub(send) {
|
|
360
|
+
return async (requestOrPromise) => {
|
|
361
|
+
const request = await requestOrPromise;
|
|
362
|
+
const headers = [...request.headers].map(([k, v]) => [k, v]);
|
|
363
|
+
const options = {
|
|
364
|
+
url: request.url,
|
|
365
|
+
headers
|
|
366
|
+
};
|
|
367
|
+
for (const field of REQUEST_FIELDS) {
|
|
368
|
+
const val = request[field];
|
|
369
|
+
if (val !== void 0 && field !== "url") options[field] = val;
|
|
370
|
+
}
|
|
371
|
+
let content;
|
|
372
|
+
if (request.body != null) content = fromReadableStream(request.body);
|
|
373
|
+
else if (!supportsRequestStreams()) content = oneChunk(new Uint8Array(await request.arrayBuffer()));
|
|
374
|
+
else content = noBytes();
|
|
375
|
+
const result = await send({
|
|
376
|
+
options,
|
|
377
|
+
content
|
|
378
|
+
});
|
|
379
|
+
if (!result) return new Response(null, {
|
|
380
|
+
status: 404,
|
|
381
|
+
statusText: "Error 404: Not Found"
|
|
382
|
+
});
|
|
383
|
+
const responseOptions = result.options;
|
|
384
|
+
const method = options.method;
|
|
385
|
+
if (method === "HEAD" || method === "OPTIONS" || NULL_BODY_STATUSES.has(responseOptions.status)) {
|
|
386
|
+
await discard(result.content);
|
|
387
|
+
return new Response(null, responseOptions);
|
|
388
|
+
}
|
|
389
|
+
return new Response(toReadableStream(result.content[Symbol.asyncIterator]()), responseOptions);
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
//#endregion
|
|
393
|
+
//#region src/core/data-channels.ts
|
|
394
|
+
const MESSAGE_TYPE_REQUEST = "REQUEST";
|
|
395
|
+
const MESSAGE_TYPE_RESPONSE = "RESPONSE";
|
|
396
|
+
let __invocationCounter = 0;
|
|
397
|
+
function newInvokationChannel({ port, handler = () => {
|
|
398
|
+
throw new Error("Handler not implemented");
|
|
399
|
+
}, onError = console.error, newCallId = () => ++__invocationCounter }) {
|
|
400
|
+
const requests = {};
|
|
401
|
+
const listener = async (event) => {
|
|
402
|
+
const data = event.data ?? {};
|
|
403
|
+
if (data.type === MESSAGE_TYPE_REQUEST) try {
|
|
404
|
+
const result = await handler(data.request, ...event.ports);
|
|
405
|
+
const [response, ...transfers] = Array.isArray(result) ? result : result !== void 0 ? [result] : [];
|
|
406
|
+
port.postMessage({
|
|
407
|
+
type: MESSAGE_TYPE_RESPONSE,
|
|
408
|
+
callId: data.callId,
|
|
409
|
+
response
|
|
410
|
+
}, transfers);
|
|
411
|
+
} catch (error) {
|
|
412
|
+
port.postMessage({
|
|
413
|
+
type: MESSAGE_TYPE_RESPONSE,
|
|
414
|
+
callId: data.callId,
|
|
415
|
+
error: serializeError(error)
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
else if (data.type === MESSAGE_TYPE_RESPONSE) {
|
|
419
|
+
const pending = requests[data.callId];
|
|
420
|
+
delete requests[data.callId];
|
|
421
|
+
if (!pending) return;
|
|
422
|
+
if (data.error) pending.reject(deserializeError(data.error));
|
|
423
|
+
else pending.resolve(data.response);
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
const start = async () => {
|
|
427
|
+
try {
|
|
428
|
+
port.addEventListener("message", listener);
|
|
429
|
+
await port.start?.();
|
|
430
|
+
} catch (e) {
|
|
431
|
+
onError(e);
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
const close = async () => {
|
|
435
|
+
try {
|
|
436
|
+
port.removeEventListener("message", listener);
|
|
437
|
+
await port.close?.();
|
|
438
|
+
} catch (e) {
|
|
439
|
+
onError(e);
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
const invoke = (request = {}, ...transfers) => {
|
|
443
|
+
const callId = newCallId();
|
|
444
|
+
return new Promise((resolve, reject) => {
|
|
445
|
+
try {
|
|
446
|
+
requests[callId] = {
|
|
447
|
+
resolve,
|
|
448
|
+
reject
|
|
449
|
+
};
|
|
450
|
+
port.postMessage({
|
|
451
|
+
type: MESSAGE_TYPE_REQUEST,
|
|
452
|
+
callId,
|
|
453
|
+
request
|
|
454
|
+
}, transfers);
|
|
455
|
+
} catch (error) {
|
|
456
|
+
delete requests[callId];
|
|
457
|
+
reject(error);
|
|
458
|
+
}
|
|
459
|
+
});
|
|
460
|
+
};
|
|
461
|
+
return {
|
|
462
|
+
start,
|
|
463
|
+
close,
|
|
464
|
+
invoke
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
async function* sendStream(communicationPort, input, params = {}) {
|
|
468
|
+
const messageChannel = new MessageChannel();
|
|
469
|
+
communicationPort.postMessage({
|
|
470
|
+
type: "START_CALL",
|
|
471
|
+
params
|
|
472
|
+
}, [messageChannel.port2]);
|
|
473
|
+
const channel = newStreamChannel(messageChannel.port1);
|
|
474
|
+
try {
|
|
475
|
+
await channel.start();
|
|
476
|
+
channel.sendAll(input);
|
|
477
|
+
yield* channel.recieveAll();
|
|
478
|
+
} finally {
|
|
479
|
+
await channel.close();
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
function newStreamChannel(port) {
|
|
483
|
+
let listeners = [];
|
|
484
|
+
let iterators = [];
|
|
485
|
+
const notifyAll = async (data) => {
|
|
486
|
+
for (const listener of listeners) await listener(data);
|
|
487
|
+
};
|
|
488
|
+
const channel = newInvokationChannel({
|
|
489
|
+
port,
|
|
490
|
+
handler: (data) => notifyAll(data)
|
|
491
|
+
});
|
|
492
|
+
const start = () => channel.start();
|
|
493
|
+
const close = async () => {
|
|
494
|
+
await notifyAll({ done: true });
|
|
495
|
+
for (const it of [...iterators]) await it.return?.();
|
|
496
|
+
await channel.close();
|
|
497
|
+
};
|
|
498
|
+
async function* recieveAll() {
|
|
499
|
+
yield* recieveIterator((deliver) => {
|
|
500
|
+
listeners.push(deliver);
|
|
501
|
+
return () => {
|
|
502
|
+
listeners = listeners.filter((l) => l !== deliver);
|
|
503
|
+
};
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
async function sendAll(it) {
|
|
507
|
+
await sendIterator((chunk) => void channel.invoke(chunk), (async function* () {
|
|
508
|
+
try {
|
|
509
|
+
iterators.push(it);
|
|
510
|
+
yield* it;
|
|
511
|
+
} finally {
|
|
512
|
+
iterators = iterators.filter((i) => i !== it);
|
|
513
|
+
}
|
|
514
|
+
})());
|
|
515
|
+
}
|
|
516
|
+
return {
|
|
517
|
+
start,
|
|
518
|
+
close,
|
|
519
|
+
recieveAll,
|
|
520
|
+
sendAll
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
//#endregion
|
|
524
|
+
//#region src/http/http-send-recieve.ts
|
|
525
|
+
async function* httpToIterator(envelopeOrPromise) {
|
|
526
|
+
const { options, content } = await envelopeOrPromise;
|
|
527
|
+
yield new TextEncoder().encode(JSON.stringify(options));
|
|
528
|
+
yield* content;
|
|
529
|
+
}
|
|
530
|
+
async function httpFromIterator(iterable) {
|
|
531
|
+
const it = (await iterable)[Symbol.asyncIterator]();
|
|
532
|
+
const { done, value } = await it.next();
|
|
533
|
+
let options = {};
|
|
534
|
+
if (!done && value) {
|
|
535
|
+
const str = new TextDecoder().decode(value);
|
|
536
|
+
options = JSON.parse(str);
|
|
537
|
+
}
|
|
538
|
+
return {
|
|
539
|
+
options,
|
|
540
|
+
content: { [Symbol.asyncIterator]() {
|
|
541
|
+
return it;
|
|
542
|
+
} }
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* @deprecated For new code, prefer the `MessagePort`-based stack from
|
|
547
|
+
* `@statewalker/webrun-http-port/fetch`. Once the page and SW share a
|
|
548
|
+
* `MessagePort`, `fetchOverPort(port, request)` provides the same
|
|
549
|
+
* `Request → Response` semantics with multiplexing via `callBidi`, JSONL
|
|
550
|
+
* envelope framing, and native `AbortSignal` support. This helper remains for
|
|
551
|
+
* existing ServiceWorker setups; it will be reimplemented on top of
|
|
552
|
+
* `webrun-http-port` in a follow-up release.
|
|
553
|
+
*/
|
|
554
|
+
async function sendHttpRequest(communicationPort, request) {
|
|
555
|
+
return await newHttpClientStub(async (req) => {
|
|
556
|
+
return await httpFromIterator(sendStream(communicationPort, httpToIterator(req)));
|
|
557
|
+
})(request);
|
|
558
|
+
}
|
|
559
|
+
//#endregion
|
|
560
|
+
//#region ../../node_modules/.pnpm/idb-keyval@6.3.0/node_modules/idb-keyval/dist/index.js
|
|
561
|
+
function promisifyRequest(request) {
|
|
562
|
+
return new Promise((resolve, reject) => {
|
|
563
|
+
request.oncomplete = request.onsuccess = () => resolve(request.result);
|
|
564
|
+
request.onabort = request.onerror = () => reject(request.error);
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
function createStore(dbName, storeName) {
|
|
568
|
+
let dbp;
|
|
569
|
+
const getDB = () => {
|
|
570
|
+
if (dbp) return dbp;
|
|
571
|
+
const request = indexedDB.open(dbName);
|
|
572
|
+
request.onupgradeneeded = () => request.result.createObjectStore(storeName);
|
|
573
|
+
dbp = promisifyRequest(request);
|
|
574
|
+
dbp.then((db) => {
|
|
575
|
+
db.onclose = () => dbp = void 0;
|
|
576
|
+
}, () => {
|
|
577
|
+
dbp = void 0;
|
|
578
|
+
});
|
|
579
|
+
return dbp;
|
|
580
|
+
};
|
|
581
|
+
return (txMode, callback) => getDB().then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
|
|
582
|
+
}
|
|
583
|
+
let defaultGetStoreFunc;
|
|
584
|
+
function defaultGetStore() {
|
|
585
|
+
if (!defaultGetStoreFunc) defaultGetStoreFunc = createStore("keyval-store", "keyval");
|
|
586
|
+
return defaultGetStoreFunc;
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Get a value by its key.
|
|
590
|
+
*
|
|
591
|
+
* @param key
|
|
592
|
+
* @param customStore Method to get a custom store. Use with caution (see the docs).
|
|
593
|
+
*/
|
|
594
|
+
function get(key, customStore = defaultGetStore()) {
|
|
595
|
+
return customStore("readonly", (store) => promisifyRequest(store.get(key)));
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* Set a value with a key.
|
|
599
|
+
*
|
|
600
|
+
* @param key
|
|
601
|
+
* @param value
|
|
602
|
+
* @param customStore Method to get a custom store. Use with caution (see the docs).
|
|
603
|
+
*/
|
|
604
|
+
function set(key, value, customStore = defaultGetStore()) {
|
|
605
|
+
return customStore("readwrite", (store) => {
|
|
606
|
+
store.put(value, key);
|
|
607
|
+
return promisifyRequest(store.transaction);
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
//#endregion
|
|
611
|
+
//#region src/core/data-calls.ts
|
|
612
|
+
function callChannel(target, callType, params, ...transfers) {
|
|
613
|
+
return new Promise((resolve, reject) => {
|
|
614
|
+
const channel = new MessageChannel();
|
|
615
|
+
channel.port1.onmessage = (ev) => {
|
|
616
|
+
const { result, error } = ev.data;
|
|
617
|
+
if (error) reject(deserializeError(error));
|
|
618
|
+
else resolve(result);
|
|
619
|
+
};
|
|
620
|
+
target.postMessage({
|
|
621
|
+
type: callType,
|
|
622
|
+
params
|
|
623
|
+
}, [channel.port2, ...transfers]);
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
function handleChannelCalls(target, callType, handler) {
|
|
627
|
+
const listener = async (event) => {
|
|
628
|
+
if (!event.data || event.data.type !== callType) return;
|
|
629
|
+
const [port, ...transfers] = event.ports ?? [];
|
|
630
|
+
const response = {};
|
|
631
|
+
try {
|
|
632
|
+
response.result = await handler(event, event.data.params, ...transfers);
|
|
633
|
+
} catch (error) {
|
|
634
|
+
response.error = serializeError(error);
|
|
635
|
+
}
|
|
636
|
+
port?.postMessage(response);
|
|
637
|
+
};
|
|
638
|
+
target.addEventListener("message", listener);
|
|
639
|
+
target.start?.();
|
|
640
|
+
return () => target.removeEventListener("message", listener);
|
|
641
|
+
}
|
|
642
|
+
//#endregion
|
|
643
|
+
//#region src/sw/sw-dispatcher.ts
|
|
644
|
+
/**
|
|
645
|
+
* ServiceWorker-side counterpart: maintains an index of connected clients keyed by
|
|
646
|
+
* clientId, persisted in IndexedDB so it can reclaim ports across SW restarts.
|
|
647
|
+
*/
|
|
648
|
+
var SwPortDispatcher = class {
|
|
649
|
+
self;
|
|
650
|
+
log;
|
|
651
|
+
handlersIndex = /* @__PURE__ */ new Map();
|
|
652
|
+
/**
|
|
653
|
+
* Set of keys that were registered at some point on this SW (sticky —
|
|
654
|
+
* survives client closures + SW wake-ups via IndexedDB). Lets the fetch
|
|
655
|
+
* handler distinguish "site URL whose owner is gone → 404" from
|
|
656
|
+
* "unknown URL under scope → pass through to the network".
|
|
657
|
+
*/
|
|
658
|
+
claimedKeys = /* @__PURE__ */ new Set();
|
|
659
|
+
_cleanup;
|
|
660
|
+
_activationPromise;
|
|
661
|
+
constructor({ self, log = () => {} }) {
|
|
662
|
+
this.self = self;
|
|
663
|
+
this.log = log;
|
|
664
|
+
}
|
|
665
|
+
get scope() {
|
|
666
|
+
return `${new URL("./", this.self.location.href)}`;
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Look up the active channel for a key. Returns `undefined` when there
|
|
670
|
+
* is no registration (or the registering client has gone away — stale
|
|
671
|
+
* entries are pruned in place).
|
|
672
|
+
*/
|
|
673
|
+
async loadChannelInfo(key) {
|
|
674
|
+
await this._checkActivation();
|
|
675
|
+
for (const channelInfo of this.handlersIndex.values()) {
|
|
676
|
+
if (channelInfo.key !== key) continue;
|
|
677
|
+
const clientId = channelInfo.clientId;
|
|
678
|
+
if (!clientId) continue;
|
|
679
|
+
if (!await this.self.clients.get(clientId)) {
|
|
680
|
+
this.handlersIndex.delete(clientId);
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
return channelInfo;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
/** Whether `key` has ever been registered on this SW. */
|
|
687
|
+
isClaimedKey(key) {
|
|
688
|
+
return this.claimedKeys.has(key);
|
|
689
|
+
}
|
|
690
|
+
start() {
|
|
691
|
+
this._cleanup = handleChannelCalls(this.self, "UPDATE_COMMUNICATION_PORT", async (event, channelInfo, port) => {
|
|
692
|
+
const clientId = event.source?.id;
|
|
693
|
+
this.log("[UPDATE_COMMUNICATION_PORT]", clientId, channelInfo);
|
|
694
|
+
await this._updateChannelInfo({
|
|
695
|
+
...channelInfo,
|
|
696
|
+
port,
|
|
697
|
+
clientId
|
|
698
|
+
});
|
|
699
|
+
return { ...channelInfo };
|
|
700
|
+
});
|
|
701
|
+
this.self.addEventListener("install", (event) => {
|
|
702
|
+
this.log("Skip waiting on install.", event);
|
|
703
|
+
this.self.skipWaiting();
|
|
704
|
+
});
|
|
705
|
+
this.self.addEventListener("activate", (event) => {
|
|
706
|
+
this.log("Claim control over all clients.", event);
|
|
707
|
+
event.waitUntil((async () => {
|
|
708
|
+
await this.self.clients.claim();
|
|
709
|
+
await this._checkActivation();
|
|
710
|
+
})());
|
|
711
|
+
});
|
|
712
|
+
}
|
|
713
|
+
async stop() {
|
|
714
|
+
if (this._cleanup) {
|
|
715
|
+
this._cleanup();
|
|
716
|
+
this._cleanup = void 0;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
_checkActivation() {
|
|
720
|
+
if (!this._activationPromise) this._activationPromise = this._activate();
|
|
721
|
+
return this._activationPromise;
|
|
722
|
+
}
|
|
723
|
+
async _activate() {
|
|
724
|
+
this.log("[checkActivation]");
|
|
725
|
+
const clientsIndex = await this._loadClientIds();
|
|
726
|
+
for (const [clientId, client] of clientsIndex.entries()) {
|
|
727
|
+
const messageChannel = new MessageChannel();
|
|
728
|
+
const port = messageChannel.port1;
|
|
729
|
+
const channelInfo = await callChannel(client, "UPDATE_COMMUNICATION_PORT", {}, messageChannel.port2);
|
|
730
|
+
await this._updateChannelInfo({
|
|
731
|
+
...channelInfo,
|
|
732
|
+
port,
|
|
733
|
+
clientId
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
async _updateChannelInfo(channelInfo) {
|
|
738
|
+
this.log("[updateClientInfo]", channelInfo);
|
|
739
|
+
if (!channelInfo.clientId) return;
|
|
740
|
+
this.handlersIndex.set(channelInfo.clientId, channelInfo);
|
|
741
|
+
if (channelInfo.key && !this.claimedKeys.has(channelInfo.key)) {
|
|
742
|
+
this.claimedKeys.add(channelInfo.key);
|
|
743
|
+
await set("claimedKeys", [...this.claimedKeys].sort());
|
|
744
|
+
}
|
|
745
|
+
await this._updateClientIds([]);
|
|
746
|
+
}
|
|
747
|
+
async _loadClientIds() {
|
|
748
|
+
const storedKeys = await get("claimedKeys") ?? [];
|
|
749
|
+
for (const key of storedKeys) this.claimedKeys.add(key);
|
|
750
|
+
const stored = await get("clientIds") ?? [];
|
|
751
|
+
return await this._updateClientIds(new Set(stored));
|
|
752
|
+
}
|
|
753
|
+
async _updateClientIds(clientIds) {
|
|
754
|
+
const ids = new Set(clientIds);
|
|
755
|
+
for (const clientId of this.handlersIndex.keys()) ids.add(clientId);
|
|
756
|
+
const index = /* @__PURE__ */ new Map();
|
|
757
|
+
for (const clientId of ids) {
|
|
758
|
+
const client = await this.self.clients.get(clientId);
|
|
759
|
+
if (client) index.set(clientId, client);
|
|
760
|
+
else this.handlersIndex.delete(clientId);
|
|
761
|
+
}
|
|
762
|
+
await set("clientIds", [...index.keys()].sort());
|
|
763
|
+
return index;
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
//#endregion
|
|
767
|
+
//#region src/sw/http-sw-dispatcher.ts
|
|
768
|
+
var SwHttpDispatcher = class extends SwPortDispatcher {
|
|
769
|
+
start() {
|
|
770
|
+
super.start();
|
|
771
|
+
this.self.addEventListener("fetch", this._handleFetchEvent.bind(this));
|
|
772
|
+
}
|
|
773
|
+
_handleFetchEvent(event) {
|
|
774
|
+
event.respondWith((async () => {
|
|
775
|
+
const request = event.request;
|
|
776
|
+
try {
|
|
777
|
+
const requestUrl = request.url;
|
|
778
|
+
const rootUrl = this.scope;
|
|
779
|
+
if (requestUrl.indexOf(rootUrl) === 0) {
|
|
780
|
+
const key = requestUrl.substring(rootUrl.length).replace(/^\/?([^/]+).*$/, "$1");
|
|
781
|
+
const channelInfo = await this.loadChannelInfo(key);
|
|
782
|
+
if (channelInfo?.port) return await sendHttpRequest(channelInfo.port, request);
|
|
783
|
+
if (this.isClaimedKey(key)) return new Response(null, {
|
|
784
|
+
status: 404,
|
|
785
|
+
statusText: "Not Found (no active handler)"
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
return await fetch(request);
|
|
789
|
+
} catch (error) {
|
|
790
|
+
console.error(error);
|
|
791
|
+
return new Response(null, {
|
|
792
|
+
status: 500,
|
|
793
|
+
statusText: "Error 500: Internal error"
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
})());
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
function startHttpDispatcher(options) {
|
|
800
|
+
const dispatcher = new SwHttpDispatcher(options);
|
|
801
|
+
dispatcher.start();
|
|
802
|
+
return () => {
|
|
803
|
+
dispatcher.stop();
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
//#endregion
|
|
807
|
+
//#region src/sw-worker.ts
|
|
808
|
+
startHttpDispatcher({
|
|
809
|
+
self,
|
|
810
|
+
log: console.log
|
|
811
|
+
});
|
|
812
|
+
//#endregion
|
|
813
|
+
})();
|