@statewalker/webrun-http-browser 0.3.3 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +406 -51
- package/demo/demo-1.html +109 -194
- package/demo/demo-2.html +118 -299
- 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 +2 -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 +36 -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 +2670 -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 +1660 -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 +1597 -0
- package/dist/sw.d.ts +2 -0
- package/dist/sw.d.ts.map +1 -0
- package/dist/sw.js +1883 -0
- package/package.json +51 -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 +262 -0
- package/src/core/index.ts +9 -0
- package/src/core/message-target.ts +8 -0
- package/src/core/registry.ts +54 -0
- package/src/http/http-send-recieve.ts +94 -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 +332 -0
- package/src/sw-worker.ts +7 -0
- package/src/sw.ts +1 -0
- package/CHANGELOG.md +0 -1
- package/LICENSE +0 -21
- package/demo/demo-2 copy.html +0 -598
- 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
package/dist/index.js
CHANGED
|
@@ -1,820 +1,2683 @@
|
|
|
1
|
-
|
|
1
|
+
//#region ../webrun-streams/dist/index.js
|
|
2
|
+
/** Collect all items from an async iterable into an array. */
|
|
3
|
+
async function collect(input) {
|
|
4
|
+
const items = [];
|
|
5
|
+
for await (const item of input) items.push(item);
|
|
6
|
+
return items;
|
|
7
|
+
}
|
|
8
|
+
/** Concatenate all Uint8Array chunks into a single Uint8Array. */
|
|
9
|
+
async function collectBytes(input) {
|
|
10
|
+
const chunks = [];
|
|
11
|
+
let total = 0;
|
|
12
|
+
for await (const chunk of input) {
|
|
13
|
+
chunks.push(chunk);
|
|
14
|
+
total += chunk.length;
|
|
15
|
+
}
|
|
16
|
+
if (chunks.length === 1) return chunks[0] ?? /* @__PURE__ */ new Uint8Array(0);
|
|
17
|
+
const result = new Uint8Array(total);
|
|
18
|
+
let offset = 0;
|
|
19
|
+
for (const chunk of chunks) {
|
|
20
|
+
result.set(chunk, offset);
|
|
21
|
+
offset += chunk.length;
|
|
22
|
+
}
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
/** Concatenate all string chunks into a single string. */
|
|
26
|
+
async function collectString(input) {
|
|
27
|
+
let result = "";
|
|
28
|
+
for await (const chunk of input) result += chunk;
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Thrown by `emulateMux` and adapters when the underlying transport closes
|
|
33
|
+
* while one or more `Duplex` calls are in flight. Consumers can catch by
|
|
34
|
+
* `instanceof TransportClosedError` or by checking `error.name`.
|
|
35
|
+
*/
|
|
36
|
+
var TransportClosedError = class extends Error {
|
|
37
|
+
name = "TransportClosedError";
|
|
38
|
+
constructor(message = "transport closed") {
|
|
39
|
+
super(message);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
2
42
|
function serializeError(error) {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
43
|
+
if (error instanceof Error) {
|
|
44
|
+
const out = {
|
|
45
|
+
message: error.message,
|
|
46
|
+
stack: error.stack
|
|
47
|
+
};
|
|
48
|
+
const bag = error;
|
|
49
|
+
for (const key of Object.keys(bag)) out[key] = bag[key];
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
if (typeof error === "object" && error !== null) {
|
|
53
|
+
const bag = error;
|
|
54
|
+
return {
|
|
55
|
+
message: String(bag.message ?? error),
|
|
56
|
+
...bag
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
return { message: String(error) };
|
|
7
60
|
}
|
|
8
|
-
|
|
9
61
|
function deserializeError(error) {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
}
|
|
332
|
-
|
|
62
|
+
const payload = typeof error === "string" ? { message: error } : error;
|
|
63
|
+
return Object.assign(new Error(payload.message), payload);
|
|
64
|
+
}
|
|
65
|
+
function newCreditLedger(initial = 0) {
|
|
66
|
+
let available = initial;
|
|
67
|
+
let failure;
|
|
68
|
+
const waiters = [];
|
|
69
|
+
const pump = () => {
|
|
70
|
+
while (waiters.length > 0 && available > 0) {
|
|
71
|
+
const next = waiters[0];
|
|
72
|
+
if (!next) return;
|
|
73
|
+
waiters.shift();
|
|
74
|
+
const granted = Math.min(next.upTo, available);
|
|
75
|
+
available -= granted;
|
|
76
|
+
next.resolve(granted);
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
return {
|
|
80
|
+
get available() {
|
|
81
|
+
return available;
|
|
82
|
+
},
|
|
83
|
+
reserve(upTo) {
|
|
84
|
+
if (failure) return Promise.reject(failure);
|
|
85
|
+
if (!(upTo >= 1)) return Promise.reject(/* @__PURE__ */ new RangeError(`newCreditLedger: reserve(${upTo}) — upTo must be at least 1`));
|
|
86
|
+
if (waiters.length === 0 && available > 0) {
|
|
87
|
+
const granted = Math.min(upTo, available);
|
|
88
|
+
available -= granted;
|
|
89
|
+
return Promise.resolve(granted);
|
|
90
|
+
}
|
|
91
|
+
return new Promise((resolve, reject) => {
|
|
92
|
+
waiters.push({
|
|
93
|
+
upTo,
|
|
94
|
+
resolve,
|
|
95
|
+
reject
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
},
|
|
99
|
+
grant(units) {
|
|
100
|
+
if (failure) return;
|
|
101
|
+
available += units;
|
|
102
|
+
pump();
|
|
103
|
+
},
|
|
104
|
+
fail(err) {
|
|
105
|
+
failure ??= err;
|
|
106
|
+
while (waiters.length > 0) waiters.shift()?.reject(err);
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Grants are batched: replenishing on every chunk while the receiver is
|
|
112
|
+
* behind would reinvent the per-frame ACK this change exists to remove.
|
|
113
|
+
* `threshold` is the fraction of the window that must drain before a grant is
|
|
114
|
+
* emitted.
|
|
115
|
+
*
|
|
116
|
+
* The batch is flushed unconditionally once the receive queue is empty, even
|
|
117
|
+
* below the threshold, so the receiver never sits on credit it owes. Note what
|
|
118
|
+
* this is and is not: paired with a {@link CreditLedger}, a sender blocks only
|
|
119
|
+
* at *exactly* zero credit, and at that point the receiver holds the entire
|
|
120
|
+
* window as `pending` — above any threshold at or below the whole window — so
|
|
121
|
+
* the threshold alone cannot deadlock that pairing. The flush is what keeps
|
|
122
|
+
* that from being an argument about a global accounting identity: it is
|
|
123
|
+
* locally decidable from one boolean, and it returns owed credit now rather
|
|
124
|
+
* than at the next threshold crossing. It costs an extra frame only when the
|
|
125
|
+
* consumer is keeping pace, which is exactly when the sender is not blocked
|
|
126
|
+
* and the frame is cheap.
|
|
127
|
+
*/
|
|
128
|
+
function newCreditGrantor(window, threshold = .5) {
|
|
129
|
+
const trigger = Math.max(1, Math.floor(window * threshold));
|
|
130
|
+
let pending = 0;
|
|
131
|
+
return { consumed(units, queueEmpty) {
|
|
132
|
+
pending += units;
|
|
133
|
+
if (pending === 0) return 0;
|
|
134
|
+
if (pending < trigger && !queueEmpty) return 0;
|
|
135
|
+
const grant = pending;
|
|
136
|
+
pending = 0;
|
|
137
|
+
return grant;
|
|
138
|
+
} };
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Credit payloads are a single big-endian uint32, matching the frame header's
|
|
142
|
+
* byte order.
|
|
143
|
+
*
|
|
144
|
+
* Deliberately **not** re-exported from `index.ts`: this is an internal codec
|
|
145
|
+
* for the `emulateMux` wire format, not a compatibility commitment. Tests
|
|
146
|
+
* import it by path.
|
|
147
|
+
*/
|
|
148
|
+
/** The largest credit a single frame can advertise or grant: 2^32 - 1. */
|
|
149
|
+
const MAX_UINT32 = 4294967295;
|
|
150
|
+
/**
|
|
151
|
+
* Clamps rather than wraps. `n >>> 0` is the obvious spelling and it is wrong
|
|
152
|
+
* here: 2^32 becomes **0**, so a 4 GiB window advertises *zero credit* and the
|
|
153
|
+
* peer stalls forever with no error — the exact silent hang credit exists to
|
|
154
|
+
* remove. 2^32 + 5 becomes 5, which looks like a working window and is worse.
|
|
155
|
+
* Anything above the ceiling is advertised as the ceiling.
|
|
156
|
+
*/
|
|
157
|
+
function encodeUint32(n) {
|
|
158
|
+
const bytes = /* @__PURE__ */ new Uint8Array(4);
|
|
159
|
+
const clamped = Number.isFinite(n) ? Math.min(MAX_UINT32, Math.max(0, Math.floor(n))) : 0;
|
|
160
|
+
new DataView(bytes.buffer).setUint32(0, clamped, false);
|
|
161
|
+
return bytes;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Returns `undefined` rather than a garbage number when the payload is too
|
|
165
|
+
* short, so a truncated frame — or one from a peer predating credit — is
|
|
166
|
+
* detectable at the call site instead of silently granting nonsense.
|
|
167
|
+
*/
|
|
168
|
+
function decodeUint32(bytes) {
|
|
169
|
+
if (bytes.byteLength < 4) return void 0;
|
|
170
|
+
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0, false);
|
|
171
|
+
}
|
|
172
|
+
const TYPE_OPEN = 1;
|
|
173
|
+
const TYPE_DATA = 2;
|
|
174
|
+
const TYPE_ACK = 3;
|
|
175
|
+
const TYPE_END = 4;
|
|
176
|
+
const TYPE_ERROR = 5;
|
|
177
|
+
const TYPE_CLOSE = 6;
|
|
178
|
+
const DEFAULT_MAX_STREAMS = 256;
|
|
179
|
+
const DEFAULT_MTU = 65536;
|
|
180
|
+
const DEFAULT_MAX_STREAM_BUFFER = 8388608;
|
|
181
|
+
const textEncoder = new TextEncoder();
|
|
182
|
+
const textDecoder = new TextDecoder();
|
|
183
|
+
function emulateMux(channel, opts = {}) {
|
|
184
|
+
const maxStreams = opts.maxStreams ?? DEFAULT_MAX_STREAMS;
|
|
185
|
+
const mtu = opts.mtu ?? DEFAULT_MTU;
|
|
186
|
+
const maxStreamBuffer = opts.maxStreamBuffer ?? DEFAULT_MAX_STREAM_BUFFER;
|
|
187
|
+
if (!(maxStreamBuffer >= 1)) throw new RangeError(`emulateMux: maxStreamBuffer must be at least 1, got ${maxStreamBuffer}`);
|
|
188
|
+
const side = opts.side ?? "initiator";
|
|
189
|
+
const streams = /* @__PURE__ */ new Map();
|
|
190
|
+
let nextLocalId = side === "initiator" ? 2 : 1;
|
|
191
|
+
let handler = null;
|
|
192
|
+
let muxClosed = false;
|
|
193
|
+
const sendFrame = (id, type, payload) => {
|
|
194
|
+
if (muxClosed) return;
|
|
195
|
+
const idEnc = encodeVarint(id);
|
|
196
|
+
const total = idEnc.length + 1 + (payload?.byteLength ?? 0);
|
|
197
|
+
const frame = new Uint8Array(total);
|
|
198
|
+
frame.set(idEnc, 0);
|
|
199
|
+
frame[idEnc.length] = type;
|
|
200
|
+
if (payload && payload.byteLength > 0) frame.set(payload, idEnc.length + 1);
|
|
201
|
+
try {
|
|
202
|
+
channel.send(frame);
|
|
203
|
+
} catch {}
|
|
204
|
+
};
|
|
205
|
+
const teardownStream = (s, err) => {
|
|
206
|
+
if (s.closed) return;
|
|
207
|
+
s.closed = true;
|
|
208
|
+
s.outboundCredit.fail(err ?? new TransportClosedError("emulateMux: stream closed"));
|
|
209
|
+
s.doneIn(err);
|
|
210
|
+
s.cancelInput?.();
|
|
211
|
+
streams.delete(s.id);
|
|
212
|
+
};
|
|
213
|
+
/**
|
|
214
|
+
* Graceful counterpart to `teardownStream`. A stream occupies a slot in
|
|
215
|
+
* `streams` until BOTH directions finish; releasing on inbound END alone
|
|
216
|
+
* would set `closed` while our own `pumpOutbound` is still sending, and it
|
|
217
|
+
* checks that flag to decide whether to keep going.
|
|
218
|
+
*
|
|
219
|
+
* Without this, only abnormal endings (cancel, ERROR, CLOSE, transport
|
|
220
|
+
* failure) ever freed a slot, so every normally-completed call leaked one
|
|
221
|
+
* until `maxStreams` began rejecting new calls.
|
|
222
|
+
*/
|
|
223
|
+
const releaseIfComplete = (s) => {
|
|
224
|
+
if (s.closed || !s.inDone || !s.outDone) return;
|
|
225
|
+
s.closed = true;
|
|
226
|
+
streams.delete(s.id);
|
|
227
|
+
};
|
|
228
|
+
const failAll = (err) => {
|
|
229
|
+
if (muxClosed) return;
|
|
230
|
+
muxClosed = true;
|
|
231
|
+
for (const s of [...streams.values()]) teardownStream(s, err);
|
|
232
|
+
streams.clear();
|
|
233
|
+
};
|
|
234
|
+
const createStream = (id) => {
|
|
235
|
+
const queue = makeInboundQueue();
|
|
236
|
+
const state = {
|
|
237
|
+
id,
|
|
238
|
+
inbound: queue.generator(() => {
|
|
239
|
+
if (!state.closed && !muxClosed) sendFrame(state.id, TYPE_CLOSE);
|
|
240
|
+
teardownStream(state);
|
|
241
|
+
}),
|
|
242
|
+
pushIn: queue.push,
|
|
243
|
+
doneIn: queue.done,
|
|
244
|
+
outboundCredit: newCreditLedger(0),
|
|
245
|
+
grantor: newCreditGrantor(maxStreamBuffer),
|
|
246
|
+
closed: false,
|
|
247
|
+
inDone: false,
|
|
248
|
+
outDone: false,
|
|
249
|
+
queuedBytes: 0
|
|
250
|
+
};
|
|
251
|
+
return state;
|
|
252
|
+
};
|
|
253
|
+
const pumpOutbound = async (s, input) => {
|
|
254
|
+
const iterator = input[Symbol.asyncIterator]?.() ?? input[Symbol.iterator]();
|
|
255
|
+
s.cancelInput = () => {
|
|
256
|
+
iterator.return?.(void 0);
|
|
257
|
+
};
|
|
258
|
+
try {
|
|
259
|
+
for (;;) {
|
|
260
|
+
const next = await iterator.next();
|
|
261
|
+
if (next.done === true) break;
|
|
262
|
+
const chunk = next.value;
|
|
263
|
+
if (s.closed || muxClosed) return;
|
|
264
|
+
if (chunk.byteLength === 0) continue;
|
|
265
|
+
let off = 0;
|
|
266
|
+
while (off < chunk.byteLength) {
|
|
267
|
+
if (s.closed || muxClosed) return;
|
|
268
|
+
const take = await s.outboundCredit.reserve(Math.min(mtu, chunk.byteLength - off));
|
|
269
|
+
if (s.closed || muxClosed) return;
|
|
270
|
+
const end = off + take;
|
|
271
|
+
sendFrame(s.id, TYPE_DATA, chunk.subarray(off, end));
|
|
272
|
+
off = end;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (!s.closed && !muxClosed) {
|
|
276
|
+
sendFrame(s.id, TYPE_END);
|
|
277
|
+
s.outDone = true;
|
|
278
|
+
releaseIfComplete(s);
|
|
279
|
+
}
|
|
280
|
+
} catch (err) {
|
|
281
|
+
if (!s.closed && !muxClosed) {
|
|
282
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
283
|
+
sendFrame(s.id, TYPE_ERROR, encodeError(e));
|
|
284
|
+
teardownStream(s, e);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
const runHandler = async (s, h) => {
|
|
289
|
+
let outbound;
|
|
290
|
+
try {
|
|
291
|
+
outbound = h(s.inbound);
|
|
292
|
+
} catch (err) {
|
|
293
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
294
|
+
sendFrame(s.id, TYPE_ERROR, encodeError(e));
|
|
295
|
+
teardownStream(s, e);
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
await pumpOutbound(s, outbound);
|
|
299
|
+
if (!s.inDone && !s.closed && !muxClosed) {
|
|
300
|
+
sendFrame(s.id, TYPE_CLOSE);
|
|
301
|
+
teardownStream(s);
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
const handleFrame = (frame) => {
|
|
305
|
+
if (muxClosed) return;
|
|
306
|
+
if (frame.byteLength < 2) return;
|
|
307
|
+
let id;
|
|
308
|
+
let offset;
|
|
309
|
+
try {
|
|
310
|
+
({value: id, offset} = decodeVarint(frame, 0));
|
|
311
|
+
} catch {
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
if (offset >= frame.byteLength) return;
|
|
315
|
+
const type = frame[offset];
|
|
316
|
+
const payload = frame.subarray(offset + 1);
|
|
317
|
+
if (type === TYPE_OPEN) {
|
|
318
|
+
if (streams.has(id)) return;
|
|
319
|
+
if (streams.size >= maxStreams) {
|
|
320
|
+
sendFrame(id, TYPE_ERROR, encodeError(/* @__PURE__ */ new RangeError(`emulateMux: maxStreams=${maxStreams} exceeded`)));
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
if (!handler) {
|
|
324
|
+
sendFrame(id, TYPE_ERROR, encodeError(/* @__PURE__ */ new Error("emulateMux: no handler registered")));
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const s = createStream(id);
|
|
328
|
+
streams.set(id, s);
|
|
329
|
+
const advertised = decodeUint32(payload);
|
|
330
|
+
if (advertised !== void 0) s.outboundCredit.grant(advertised);
|
|
331
|
+
sendFrame(id, TYPE_ACK, encodeUint32(maxStreamBuffer));
|
|
332
|
+
runHandler(s, handler);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
const s = streams.get(id);
|
|
336
|
+
if (!s) return;
|
|
337
|
+
switch (type) {
|
|
338
|
+
case TYPE_DATA: {
|
|
339
|
+
s.queuedBytes += payload.byteLength;
|
|
340
|
+
if (s.queuedBytes > maxStreamBuffer) {
|
|
341
|
+
const err = /* @__PURE__ */ new RangeError(`emulateMux: stream ${id} buffered ${s.queuedBytes} bytes past maxStreamBuffer=${maxStreamBuffer} without being drained`);
|
|
342
|
+
sendFrame(id, TYPE_ERROR, encodeError(err));
|
|
343
|
+
teardownStream(s, err);
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
const copy = payload.byteLength === 0 ? payload : new Uint8Array(payload);
|
|
347
|
+
s.pushIn(copy).then((handled) => {
|
|
348
|
+
s.queuedBytes -= copy.byteLength;
|
|
349
|
+
if (!handled || s.closed || muxClosed) return;
|
|
350
|
+
const grant = s.grantor.consumed(copy.byteLength, s.queuedBytes === 0);
|
|
351
|
+
if (grant > 0) sendFrame(id, TYPE_ACK, encodeUint32(grant));
|
|
352
|
+
});
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
case TYPE_ACK: {
|
|
356
|
+
const granted = decodeUint32(payload);
|
|
357
|
+
if (granted !== void 0) s.outboundCredit.grant(granted);
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
case TYPE_END:
|
|
361
|
+
s.inDone = true;
|
|
362
|
+
s.doneIn();
|
|
363
|
+
releaseIfComplete(s);
|
|
364
|
+
return;
|
|
365
|
+
case TYPE_ERROR:
|
|
366
|
+
teardownStream(s, decodeError(payload));
|
|
367
|
+
return;
|
|
368
|
+
case TYPE_CLOSE:
|
|
369
|
+
teardownStream(s);
|
|
370
|
+
return;
|
|
371
|
+
default: return;
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
(async () => {
|
|
375
|
+
try {
|
|
376
|
+
for await (const frame of channel.recv) {
|
|
377
|
+
if (muxClosed) break;
|
|
378
|
+
handleFrame(frame);
|
|
379
|
+
}
|
|
380
|
+
} catch (err) {
|
|
381
|
+
failAll(err instanceof Error ? err : new Error(String(err)));
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
failAll(new TransportClosedError());
|
|
385
|
+
})();
|
|
386
|
+
channel.closed.then(() => failAll(new TransportClosedError())).catch(() => {});
|
|
387
|
+
const call = (input) => {
|
|
388
|
+
if (muxClosed) return failedGenerator(new TransportClosedError());
|
|
389
|
+
if (streams.size >= maxStreams) return failedGenerator(/* @__PURE__ */ new RangeError(`emulateMux: maxStreams=${maxStreams} exceeded`));
|
|
390
|
+
const id = nextLocalId;
|
|
391
|
+
nextLocalId += 2;
|
|
392
|
+
const s = createStream(id);
|
|
393
|
+
streams.set(id, s);
|
|
394
|
+
sendFrame(id, TYPE_OPEN, encodeUint32(maxStreamBuffer));
|
|
395
|
+
pumpOutbound(s, input);
|
|
396
|
+
return s.inbound;
|
|
397
|
+
};
|
|
398
|
+
const serve = (h) => {
|
|
399
|
+
handler = h;
|
|
400
|
+
let torn = false;
|
|
401
|
+
return async () => {
|
|
402
|
+
if (torn) return;
|
|
403
|
+
torn = true;
|
|
404
|
+
if (handler === h) handler = null;
|
|
405
|
+
};
|
|
406
|
+
};
|
|
407
|
+
const close = async () => {
|
|
408
|
+
if (muxClosed) return;
|
|
409
|
+
failAll(new TransportClosedError());
|
|
410
|
+
try {
|
|
411
|
+
channel.close();
|
|
412
|
+
} catch {}
|
|
413
|
+
};
|
|
414
|
+
return {
|
|
415
|
+
call,
|
|
416
|
+
serve,
|
|
417
|
+
close
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
function failedGenerator(err) {
|
|
421
|
+
return (async function* () {
|
|
422
|
+
throw err;
|
|
423
|
+
})();
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Push/pull queue with eager push/done handles. Unlike `newAsyncGenerator`, the
|
|
427
|
+
* push and done functions are usable *before* the consumer begins iterating —
|
|
428
|
+
* `emulateMux` needs to enqueue frames from inbound traffic regardless of when
|
|
429
|
+
* (or whether) the consumer pulls them.
|
|
430
|
+
*
|
|
431
|
+
* `onCancel` fires only when the consumer terminates the generator before
|
|
432
|
+
* `done()` was called — i.e., a unilateral cancellation. If `done()` is
|
|
433
|
+
* called first (peer END/ERROR/CLOSE), the generator ends naturally and
|
|
434
|
+
* `onCancel` does not fire.
|
|
435
|
+
*/
|
|
436
|
+
function makeInboundQueue() {
|
|
437
|
+
const slots = [];
|
|
438
|
+
let wake = null;
|
|
439
|
+
let queueClosed = false;
|
|
440
|
+
let doneCalled = false;
|
|
441
|
+
const push = (chunk) => {
|
|
442
|
+
if (queueClosed) return Promise.resolve(false);
|
|
443
|
+
return new Promise((resolve) => {
|
|
444
|
+
slots.push({
|
|
445
|
+
type: "value",
|
|
446
|
+
value: chunk,
|
|
447
|
+
resolve
|
|
448
|
+
});
|
|
449
|
+
wake?.();
|
|
450
|
+
});
|
|
451
|
+
};
|
|
452
|
+
const done = (err) => {
|
|
453
|
+
if (queueClosed || doneCalled) return Promise.resolve(false);
|
|
454
|
+
doneCalled = true;
|
|
455
|
+
return new Promise((resolve) => {
|
|
456
|
+
slots.push({
|
|
457
|
+
type: "done",
|
|
458
|
+
err,
|
|
459
|
+
resolve
|
|
460
|
+
});
|
|
461
|
+
wake?.();
|
|
462
|
+
});
|
|
463
|
+
};
|
|
464
|
+
async function* generator(onCancel) {
|
|
465
|
+
try {
|
|
466
|
+
while (true) {
|
|
467
|
+
if (slots.length === 0) {
|
|
468
|
+
await new Promise((r) => {
|
|
469
|
+
wake = r;
|
|
470
|
+
});
|
|
471
|
+
wake = null;
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
const slot = slots.shift();
|
|
475
|
+
if (slot.type === "done") {
|
|
476
|
+
slot.resolve(true);
|
|
477
|
+
if (slot.err) throw slot.err;
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
yield slot.value;
|
|
481
|
+
slot.resolve(true);
|
|
482
|
+
}
|
|
483
|
+
} finally {
|
|
484
|
+
queueClosed = true;
|
|
485
|
+
for (const s of slots) s.resolve(false);
|
|
486
|
+
slots.length = 0;
|
|
487
|
+
if (!doneCalled) onCancel();
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
return {
|
|
491
|
+
generator,
|
|
492
|
+
push,
|
|
493
|
+
done
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
function encodeVarint(value) {
|
|
497
|
+
if (!Number.isInteger(value) || value < 0) throw new RangeError(`encodeVarint: ${value} is not a non-negative integer`);
|
|
498
|
+
const out = [];
|
|
499
|
+
let v = value;
|
|
500
|
+
while (v >= 128) {
|
|
501
|
+
out.push(v & 127 | 128);
|
|
502
|
+
v >>>= 7;
|
|
503
|
+
}
|
|
504
|
+
out.push(v & 127);
|
|
505
|
+
return new Uint8Array(out);
|
|
506
|
+
}
|
|
507
|
+
function decodeVarint(buf, start) {
|
|
508
|
+
let value = 0;
|
|
509
|
+
let shift = 0;
|
|
510
|
+
let i = start;
|
|
511
|
+
while (i < buf.length) {
|
|
512
|
+
const b = buf[i++];
|
|
513
|
+
value |= (b & 127) << shift;
|
|
514
|
+
if ((b & 128) === 0) return {
|
|
515
|
+
value: value >>> 0,
|
|
516
|
+
offset: i
|
|
517
|
+
};
|
|
518
|
+
shift += 7;
|
|
519
|
+
if (shift > 28) throw new Error("decodeVarint: too long");
|
|
520
|
+
}
|
|
521
|
+
throw new Error("decodeVarint: truncated");
|
|
522
|
+
}
|
|
523
|
+
function encodeError(err) {
|
|
524
|
+
return textEncoder.encode(JSON.stringify(serializeError(err)));
|
|
525
|
+
}
|
|
526
|
+
function decodeError(buf) {
|
|
527
|
+
if (buf.byteLength === 0) return /* @__PURE__ */ new Error("unknown stream error");
|
|
528
|
+
try {
|
|
529
|
+
return deserializeError(JSON.parse(textDecoder.decode(buf)));
|
|
530
|
+
} catch {
|
|
531
|
+
return new Error(textDecoder.decode(buf));
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
/** Split a stream of string chunks into individual lines (delimited by \n). */
|
|
535
|
+
async function* splitLines(input) {
|
|
536
|
+
let buffer = "";
|
|
537
|
+
for await (const chunk of input) {
|
|
538
|
+
buffer += chunk;
|
|
539
|
+
let idx = buffer.indexOf("\n");
|
|
540
|
+
while (idx !== -1) {
|
|
541
|
+
yield buffer.slice(0, idx);
|
|
542
|
+
buffer = buffer.slice(idx + 1);
|
|
543
|
+
idx = buffer.indexOf("\n");
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
if (buffer) yield buffer;
|
|
547
|
+
}
|
|
548
|
+
/** Append \n to each string in the stream. */
|
|
549
|
+
async function* joinLines(input) {
|
|
550
|
+
for await (const line of input) yield `${line}\n`;
|
|
551
|
+
}
|
|
552
|
+
/** Apply a sync or async function to each item in a stream. */
|
|
553
|
+
async function* map(input, fn) {
|
|
554
|
+
for await (const item of input) yield await fn(item);
|
|
555
|
+
}
|
|
556
|
+
/** Encode each value as a JSON line (terminated by \n). */
|
|
557
|
+
async function* encodeJsonl(input) {
|
|
558
|
+
yield* map(input, (item) => `${JSON.stringify(item)}\n`);
|
|
559
|
+
}
|
|
560
|
+
/** Decode each line as a JSON value. Skips empty lines. */
|
|
561
|
+
async function* decodeJsonl(input) {
|
|
562
|
+
for await (const line of splitLines(input)) {
|
|
563
|
+
const trimmed = line.trim();
|
|
564
|
+
if (trimmed) yield JSON.parse(trimmed);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* The newAsyncGenerator function creates async generators from callback-based initialization
|
|
569
|
+
* functions, providing a bridge between imperative event handling and declarative async
|
|
570
|
+
* iteration patterns.
|
|
571
|
+
*
|
|
572
|
+
* The initialization function receives two callback functions that control the generator's
|
|
573
|
+
* behavior. The `next` function yields values to consumers, while the `done` function
|
|
574
|
+
* signals completion or error conditions. The initialization function can return a cleanup
|
|
575
|
+
* function that will be called when the generator is closed or an error occurs.
|
|
576
|
+
*
|
|
577
|
+
* The generator manages an internal queue of values and completion signals, ensuring that
|
|
578
|
+
* producers can yield values without overwhelming consumers. Proper backpressure is implemented
|
|
579
|
+
* by having the `next` and `done` functions return promises that resolve only after the
|
|
580
|
+
* consumer has processed the values. This prevents memory leaks and ensures that producers
|
|
581
|
+
* are aware of whether their values were successfully handled.
|
|
582
|
+
* The generator also handles cleanup by draining any remaining items in the queue and notifying
|
|
583
|
+
* producers that their values were not processed if the generator is closed early. This ensures
|
|
584
|
+
* that resources are properly managed and that no memory leaks occur.
|
|
585
|
+
*
|
|
586
|
+
* Example usage:
|
|
587
|
+
* ```typescript
|
|
588
|
+
* const asyncGen = newAsyncGenerator<number>((next, done) => {
|
|
589
|
+
* let count = 0;
|
|
590
|
+
* const interval = setInterval(() => {
|
|
591
|
+
* if (count < 5) {
|
|
592
|
+
* next(count++);
|
|
593
|
+
* } else {
|
|
594
|
+
* done();
|
|
595
|
+
* clearInterval(interval);
|
|
596
|
+
* }
|
|
597
|
+
* }, 1000);
|
|
598
|
+
* return () => clearInterval(interval); // Cleanup function
|
|
599
|
+
* });
|
|
600
|
+
* (async () => {
|
|
601
|
+
* for await (const num of asyncGen) {
|
|
602
|
+
* console.log(num); // Logs numbers 0 to 4 at 1 second intervals
|
|
603
|
+
* }
|
|
604
|
+
* console.log("Completed");
|
|
605
|
+
* })();
|
|
606
|
+
* ```
|
|
607
|
+
* @template T The type of values yielded by the generator
|
|
608
|
+
* @template E The type of errors that can be thrown; defaults to Error
|
|
609
|
+
* @param init Initialization function that sets up the generator behavior with next/done callbacks;
|
|
610
|
+
* The first parameter - `next` function - is used to yield values to consumers;
|
|
611
|
+
* It returns a Promise<boolean> indicating whether the value was successfully handled;
|
|
612
|
+
* The second parameter - `done` function - is used to signal completion or error;
|
|
613
|
+
* It returns a Promise<boolean> indicating whether the completion was successfully handled;
|
|
614
|
+
* The initialization function can optionally return a cleanup function that will be called
|
|
615
|
+
* when the generator is closed or an error occurs;
|
|
616
|
+
* @param skipValues If true, only the most recent value is kept in the queue,
|
|
617
|
+
* skipping intermediate values (not consumed values are considered skipped);
|
|
618
|
+
* This is useful for scenarios where only the latest value matters, such as UI updates.
|
|
619
|
+
* Defaults to false, meaning all values are queued and processed in order.
|
|
620
|
+
* @returns AsyncGenerator that properly manages backpressure and resource cleanup
|
|
621
|
+
*/
|
|
622
|
+
async function* newAsyncGenerator(init, skipValues = false) {
|
|
623
|
+
let head;
|
|
624
|
+
let tail;
|
|
625
|
+
/** Flag to prevent new values from being queued after generator closes */
|
|
626
|
+
let closed = false;
|
|
627
|
+
/** Wake-up function to notify the generator loop of new items */
|
|
628
|
+
let wakeUp;
|
|
629
|
+
/**
|
|
630
|
+
* Drains the internal queue, notifying all pending producers that their values
|
|
631
|
+
* were not processed due to generator closure. This prevents memory leaks and
|
|
632
|
+
* ensures proper backpressure signaling.
|
|
633
|
+
*/
|
|
634
|
+
const drainQueue = () => {
|
|
635
|
+
for (; head; head = head.next) {
|
|
636
|
+
closed = closed || head.done;
|
|
637
|
+
head.resolve(false);
|
|
638
|
+
}
|
|
639
|
+
tail = void 0;
|
|
640
|
+
};
|
|
641
|
+
/**
|
|
642
|
+
* Enqueues a value or completion signal with a promise that resolves when the item
|
|
643
|
+
* is processed. This enables backpressure by allowing producers to know when their
|
|
644
|
+
* values have been consumed.
|
|
645
|
+
*/
|
|
646
|
+
const enqueue = (params) => {
|
|
647
|
+
if (skipValues) drainQueue();
|
|
648
|
+
return !closed ? new Promise((resolve) => {
|
|
649
|
+
const next = {
|
|
650
|
+
...params,
|
|
651
|
+
next: void 0,
|
|
652
|
+
resolve
|
|
653
|
+
};
|
|
654
|
+
if (tail) tail.next = next;
|
|
655
|
+
tail = next;
|
|
656
|
+
if (!head) head = tail;
|
|
657
|
+
wakeUp?.();
|
|
658
|
+
}) : Promise.resolve(false);
|
|
659
|
+
};
|
|
660
|
+
/**
|
|
661
|
+
* Producer function to yield a value to consumers. Returns a promise that resolves
|
|
662
|
+
* to true if the value was successfully processed, false if the generator is closed
|
|
663
|
+
* or the value was skipped due to backpressure.
|
|
664
|
+
*/
|
|
665
|
+
const next = (value) => enqueue({
|
|
666
|
+
done: false,
|
|
667
|
+
value
|
|
668
|
+
});
|
|
669
|
+
/**
|
|
670
|
+
* Producer function to signal completion or error. Optional error parameter will
|
|
671
|
+
* cause the generator to throw that error to consumers.
|
|
672
|
+
*/
|
|
673
|
+
const done = (error) => enqueue({
|
|
674
|
+
done: true,
|
|
675
|
+
error
|
|
676
|
+
});
|
|
677
|
+
const unsubscribe = init(next, done);
|
|
678
|
+
try {
|
|
679
|
+
while (!closed) {
|
|
680
|
+
if (!head) {
|
|
681
|
+
await new Promise((resolve) => {
|
|
682
|
+
wakeUp = resolve;
|
|
683
|
+
}).then(() => {
|
|
684
|
+
wakeUp = void 0;
|
|
685
|
+
});
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
const slot = head;
|
|
689
|
+
head = head.next;
|
|
690
|
+
if (tail === slot) tail = head;
|
|
691
|
+
try {
|
|
692
|
+
if (slot.done) {
|
|
693
|
+
closed = true;
|
|
694
|
+
if (slot.error !== void 0) throw slot.error;
|
|
695
|
+
break;
|
|
696
|
+
}
|
|
697
|
+
yield slot.value;
|
|
698
|
+
} finally {
|
|
699
|
+
slot.resolve(true);
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
} finally {
|
|
703
|
+
/**
|
|
704
|
+
* Cleanup phase - ensures proper resource management and notification of any
|
|
705
|
+
* remaining producers. This runs whether the generator completes normally,
|
|
706
|
+
* encounters an error, or is closed early by the consumer.
|
|
707
|
+
*/
|
|
708
|
+
closed = true;
|
|
709
|
+
wakeUp?.();
|
|
710
|
+
if (typeof unsubscribe === "function") await unsubscribe();
|
|
711
|
+
/**
|
|
712
|
+
* Drain any remaining items in the queue and notify their producers that
|
|
713
|
+
* the values were not processed. This prevents memory leaks and ensures
|
|
714
|
+
* proper backpressure signaling.
|
|
715
|
+
*/
|
|
716
|
+
drainQueue();
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
const utf8 = new TextEncoder();
|
|
720
|
+
/**
|
|
721
|
+
* Coerce common byte-like inputs into a `Uint8Array`. Strings encode as UTF-8.
|
|
722
|
+
* Blobs return a `Promise<Uint8Array>`; every other input returns synchronously.
|
|
723
|
+
* Throws `TypeError` for anything else.
|
|
724
|
+
*/
|
|
725
|
+
function normalizeToUint8Array(data) {
|
|
726
|
+
if (data instanceof Uint8Array) return data;
|
|
727
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
728
|
+
if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
729
|
+
if (typeof Blob !== "undefined" && data instanceof Blob) return data.arrayBuffer().then((buf) => new Uint8Array(buf));
|
|
730
|
+
if (typeof data === "string") return utf8.encode(data);
|
|
731
|
+
throw new TypeError(`normalizeToUint8Array: unsupported input ${describe(data)}; expected Uint8Array, ArrayBuffer, ArrayBufferView, Blob, or string`);
|
|
732
|
+
}
|
|
733
|
+
function describe(value) {
|
|
734
|
+
if (value === null) return "null";
|
|
735
|
+
const t = typeof value;
|
|
736
|
+
if (t !== "object") return t;
|
|
737
|
+
return value.constructor?.name ?? "object";
|
|
738
|
+
}
|
|
739
|
+
/**
|
|
740
|
+
* The iterator ↔ `ReadableStream` boundary.
|
|
741
|
+
*
|
|
742
|
+
* Both adapters must carry CANCELLATION, not just data: a response body leaves
|
|
743
|
+
* a handler as a `ReadableStream`, crosses a transport as an iterator, and
|
|
744
|
+
* becomes a `ReadableStream` again at the caller — so when the caller walks
|
|
745
|
+
* away, the only path back to the handler's producer runs through both of
|
|
746
|
+
* these functions. Teardown that stops at an adapter leaves a producer running
|
|
747
|
+
* for ever.
|
|
748
|
+
*/
|
|
333
749
|
function toReadableStream(it) {
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
750
|
+
return new ReadableStream({
|
|
751
|
+
/**
|
|
752
|
+
* One chunk per pull. An earlier version drained the whole iterator inside
|
|
753
|
+
* a single `pull`, which defeated the stream's own backpressure (every
|
|
754
|
+
* chunk was enqueued as fast as the producer could make them, however slow
|
|
755
|
+
* the reader was) and left no point between chunks at which a cancellation
|
|
756
|
+
* could take effect.
|
|
757
|
+
*/
|
|
758
|
+
async pull(controller) {
|
|
759
|
+
try {
|
|
760
|
+
const slot = await it.next();
|
|
761
|
+
if (!slot || slot.done) {
|
|
762
|
+
controller.close();
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
controller.enqueue(await slot.value);
|
|
766
|
+
} catch (error) {
|
|
767
|
+
controller.error(error);
|
|
768
|
+
}
|
|
769
|
+
},
|
|
770
|
+
/**
|
|
771
|
+
* Release the source. NOT awaited: `.return()` on an async generator that
|
|
772
|
+
* is parked awaiting its own source is queued behind that pending
|
|
773
|
+
* `next()`, so awaiting it here would hang `reader.cancel()` on exactly
|
|
774
|
+
* the producers that most need cancelling.
|
|
775
|
+
*/
|
|
776
|
+
cancel(reason) {
|
|
777
|
+
Promise.resolve(it.return?.(reason)).catch(() => {});
|
|
778
|
+
}
|
|
779
|
+
});
|
|
780
|
+
}
|
|
356
781
|
async function* fromReadableStream(stream) {
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
782
|
+
const reader = stream.getReader();
|
|
783
|
+
let drained = false;
|
|
784
|
+
try {
|
|
785
|
+
while (true) {
|
|
786
|
+
const { done, value } = await reader.read();
|
|
787
|
+
if (done) {
|
|
788
|
+
drained = true;
|
|
789
|
+
break;
|
|
790
|
+
}
|
|
791
|
+
if (value !== void 0) yield value;
|
|
792
|
+
}
|
|
793
|
+
} finally {
|
|
794
|
+
if (drained) reader.releaseLock();
|
|
795
|
+
else await reader.cancel().catch(() => {});
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Inverse of {@link sendIterator}: turns a sequence of `{done, value, error}`
|
|
800
|
+
* chunks (delivered to the supplied callback by `installer`) into an async
|
|
801
|
+
* generator.
|
|
802
|
+
*
|
|
803
|
+
* The `installer` is given a `deliver` function. It should call `deliver`
|
|
804
|
+
* once for each incoming chunk and may return a cleanup callback that
|
|
805
|
+
* runs when the consumer stops iterating.
|
|
806
|
+
*/
|
|
807
|
+
function recieveIterator(installer) {
|
|
808
|
+
return newAsyncGenerator((next, done) => {
|
|
809
|
+
const cleanup = installer(async (chunk = { done: true }) => {
|
|
810
|
+
const { done: isDone = true, value, error } = chunk;
|
|
811
|
+
if (error) return await done(error);
|
|
812
|
+
if (isDone) return await done();
|
|
813
|
+
return await next(value);
|
|
814
|
+
});
|
|
815
|
+
if (cleanup) return async () => {
|
|
816
|
+
await cleanup();
|
|
817
|
+
};
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
/**
|
|
821
|
+
* Drain an async iterator into a sink that consumes one chunk at a time.
|
|
822
|
+
*
|
|
823
|
+
* Each yielded value becomes `{ done: false, value }`. Completion emits
|
|
824
|
+
* `{ done: true }`. If the iterator throws, the error is caught and the
|
|
825
|
+
* final `done` chunk carries it so the peer can rethrow on its side.
|
|
826
|
+
*/
|
|
827
|
+
async function sendIterator(send, it) {
|
|
828
|
+
let error;
|
|
829
|
+
try {
|
|
830
|
+
for await (const value of it) await send({
|
|
831
|
+
done: false,
|
|
832
|
+
value
|
|
833
|
+
});
|
|
834
|
+
} catch (err) {
|
|
835
|
+
error = err;
|
|
836
|
+
} finally {
|
|
837
|
+
await send({
|
|
838
|
+
done: true,
|
|
839
|
+
error
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
/** Decode Uint8Array chunks to string chunks via TextDecoder, handling split multi-byte characters. */
|
|
844
|
+
async function* decodeText(input) {
|
|
845
|
+
const decoder = new TextDecoder("utf-8", { fatal: false });
|
|
846
|
+
for await (const chunk of input) {
|
|
847
|
+
const text = decoder.decode(chunk, { stream: true });
|
|
848
|
+
if (text) yield text;
|
|
849
|
+
}
|
|
850
|
+
const tail = decoder.decode();
|
|
851
|
+
if (tail) yield tail;
|
|
852
|
+
}
|
|
853
|
+
/** Encode string chunks to Uint8Array chunks via TextEncoder. */
|
|
854
|
+
async function* encodeText(input) {
|
|
855
|
+
const encoder = new TextEncoder();
|
|
856
|
+
for await (const str of input) yield encoder.encode(str);
|
|
857
|
+
}
|
|
858
|
+
const DEFAULT_CHUNK_SIZE = 16384;
|
|
859
|
+
/**
|
|
860
|
+
* Curried `Duplex`-shaped transformer that splits incoming `Uint8Array`s into
|
|
861
|
+
* chunks no larger than `size` bytes. Empty input chunks are skipped; small
|
|
862
|
+
* input chunks pass through unchanged (zero-copy `subarray` views are used
|
|
863
|
+
* when splitting, so no allocation per chunk).
|
|
864
|
+
*
|
|
865
|
+
* Use to respect transport MTUs before reaching `channel.send`. Reassembly on
|
|
866
|
+
* the receive side is not needed — consumers iterate a continuous byte stream.
|
|
867
|
+
*/
|
|
868
|
+
function toChunks(size = DEFAULT_CHUNK_SIZE) {
|
|
869
|
+
if (!(Number.isInteger(size) && size > 0)) throw new RangeError(`toChunks: size must be a positive integer, got ${size}`);
|
|
870
|
+
return async function* (input) {
|
|
871
|
+
for await (const block of input) {
|
|
872
|
+
if (block.byteLength === 0) continue;
|
|
873
|
+
if (block.byteLength <= size) {
|
|
874
|
+
yield block;
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
let offset = 0;
|
|
878
|
+
while (offset < block.byteLength) {
|
|
879
|
+
const end = Math.min(offset + size, block.byteLength);
|
|
880
|
+
yield block.subarray(offset, end);
|
|
881
|
+
offset = end;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
//#endregion
|
|
887
|
+
//#region src/core/data-calls.ts
|
|
888
|
+
function callChannel(target, callType, params, ...transfers) {
|
|
889
|
+
return new Promise((resolve, reject) => {
|
|
890
|
+
const channel = new MessageChannel();
|
|
891
|
+
channel.port1.onmessage = (ev) => {
|
|
892
|
+
const { result, error } = ev.data;
|
|
893
|
+
if (error) reject(deserializeError(error));
|
|
894
|
+
else resolve(result);
|
|
895
|
+
};
|
|
896
|
+
target.postMessage({
|
|
897
|
+
type: callType,
|
|
898
|
+
params
|
|
899
|
+
}, [channel.port2, ...transfers]);
|
|
900
|
+
});
|
|
901
|
+
}
|
|
902
|
+
function handleChannelCalls(target, callType, handler) {
|
|
903
|
+
const listener = async (event) => {
|
|
904
|
+
if (!event.data || event.data.type !== callType) return;
|
|
905
|
+
const [port, ...transfers] = event.ports ?? [];
|
|
906
|
+
const response = {};
|
|
907
|
+
try {
|
|
908
|
+
response.result = await handler(event, event.data.params, ...transfers);
|
|
909
|
+
} catch (error) {
|
|
910
|
+
response.error = serializeError(error);
|
|
911
|
+
}
|
|
912
|
+
port?.postMessage(response);
|
|
913
|
+
};
|
|
914
|
+
target.addEventListener("message", listener);
|
|
915
|
+
target.start?.();
|
|
916
|
+
return () => target.removeEventListener("message", listener);
|
|
917
|
+
}
|
|
918
|
+
//#endregion
|
|
919
|
+
//#region src/core/data-channels.ts
|
|
920
|
+
const MESSAGE_TYPE_REQUEST = "REQUEST";
|
|
921
|
+
const MESSAGE_TYPE_RESPONSE = "RESPONSE";
|
|
922
|
+
let __invocationCounter = 0;
|
|
923
|
+
function newInvokationChannel({ port, handler = () => {
|
|
924
|
+
throw new Error("Handler not implemented");
|
|
925
|
+
}, onError = console.error, newCallId = () => ++__invocationCounter }) {
|
|
926
|
+
const requests = {};
|
|
927
|
+
const listener = async (event) => {
|
|
928
|
+
const data = event.data ?? {};
|
|
929
|
+
if (data.type === MESSAGE_TYPE_REQUEST) try {
|
|
930
|
+
const result = await handler(data.request, ...event.ports);
|
|
931
|
+
const [response, ...transfers] = Array.isArray(result) ? result : result !== void 0 ? [result] : [];
|
|
932
|
+
port.postMessage({
|
|
933
|
+
type: MESSAGE_TYPE_RESPONSE,
|
|
934
|
+
callId: data.callId,
|
|
935
|
+
response
|
|
936
|
+
}, transfers);
|
|
937
|
+
} catch (error) {
|
|
938
|
+
port.postMessage({
|
|
939
|
+
type: MESSAGE_TYPE_RESPONSE,
|
|
940
|
+
callId: data.callId,
|
|
941
|
+
error: serializeError(error)
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
else if (data.type === MESSAGE_TYPE_RESPONSE) {
|
|
945
|
+
const pending = requests[data.callId];
|
|
946
|
+
delete requests[data.callId];
|
|
947
|
+
if (!pending) return;
|
|
948
|
+
if (data.error) pending.reject(deserializeError(data.error));
|
|
949
|
+
else pending.resolve(data.response);
|
|
950
|
+
}
|
|
951
|
+
};
|
|
952
|
+
const start = async () => {
|
|
953
|
+
try {
|
|
954
|
+
port.addEventListener("message", listener);
|
|
955
|
+
await port.start?.();
|
|
956
|
+
} catch (e) {
|
|
957
|
+
onError(e);
|
|
958
|
+
}
|
|
959
|
+
};
|
|
960
|
+
const close = async () => {
|
|
961
|
+
try {
|
|
962
|
+
port.removeEventListener("message", listener);
|
|
963
|
+
await port.close?.();
|
|
964
|
+
} catch (e) {
|
|
965
|
+
onError(e);
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
const invoke = (request = {}, ...transfers) => {
|
|
969
|
+
const callId = newCallId();
|
|
970
|
+
return new Promise((resolve, reject) => {
|
|
971
|
+
try {
|
|
972
|
+
requests[callId] = {
|
|
973
|
+
resolve,
|
|
974
|
+
reject
|
|
975
|
+
};
|
|
976
|
+
port.postMessage({
|
|
977
|
+
type: MESSAGE_TYPE_REQUEST,
|
|
978
|
+
callId,
|
|
979
|
+
request
|
|
980
|
+
}, transfers);
|
|
981
|
+
} catch (error) {
|
|
982
|
+
delete requests[callId];
|
|
983
|
+
reject(error);
|
|
984
|
+
}
|
|
985
|
+
});
|
|
986
|
+
};
|
|
987
|
+
return {
|
|
988
|
+
start,
|
|
989
|
+
close,
|
|
990
|
+
invoke
|
|
991
|
+
};
|
|
992
|
+
}
|
|
993
|
+
async function* sendStream(communicationPort, input, params = {}) {
|
|
994
|
+
const messageChannel = new MessageChannel();
|
|
995
|
+
communicationPort.postMessage({
|
|
996
|
+
type: "START_CALL",
|
|
997
|
+
params
|
|
998
|
+
}, [messageChannel.port2]);
|
|
999
|
+
const channel = newStreamChannel(messageChannel.port1);
|
|
1000
|
+
let drained = false;
|
|
1001
|
+
try {
|
|
1002
|
+
await channel.start();
|
|
1003
|
+
channel.sendAll(input);
|
|
1004
|
+
yield* channel.recieveAll();
|
|
1005
|
+
drained = true;
|
|
1006
|
+
} finally {
|
|
1007
|
+
if (!drained) channel.cancel();
|
|
1008
|
+
await channel.close();
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
function handleStreams(communicationPort, handler) {
|
|
1012
|
+
const listener = async (event) => {
|
|
1013
|
+
const { type, params } = event.data ?? {};
|
|
1014
|
+
if (type !== "START_CALL") return;
|
|
1015
|
+
const port = event.ports[0];
|
|
1016
|
+
const channel = newStreamChannel(port);
|
|
1017
|
+
try {
|
|
1018
|
+
await channel.start();
|
|
1019
|
+
const response = await handler(channel.recieveAll(), params ?? {});
|
|
1020
|
+
await channel.sendAll(response);
|
|
1021
|
+
} finally {
|
|
1022
|
+
await channel.close();
|
|
1023
|
+
}
|
|
1024
|
+
};
|
|
1025
|
+
communicationPort.addEventListener("message", listener);
|
|
1026
|
+
communicationPort.start?.();
|
|
1027
|
+
return () => communicationPort.removeEventListener("message", listener);
|
|
1028
|
+
}
|
|
1029
|
+
function newStreamChannel(port) {
|
|
1030
|
+
let listeners = [];
|
|
1031
|
+
let iterators = [];
|
|
1032
|
+
const notifyAll = async (data) => {
|
|
1033
|
+
for (const listener of listeners) await listener(data);
|
|
1034
|
+
};
|
|
1035
|
+
/**
|
|
1036
|
+
* Release whatever we are sending. NOT awaited: `.return()` on an async
|
|
1037
|
+
* generator parked awaiting its own source is queued behind that pending
|
|
1038
|
+
* `next()`, so awaiting it here would block the message handler — and the
|
|
1039
|
+
* chunk that would unblock it can only arrive through that same handler.
|
|
1040
|
+
*/
|
|
1041
|
+
const cancelOutgoing = () => {
|
|
1042
|
+
for (const it of [...iterators]) {
|
|
1043
|
+
const iterable = it;
|
|
1044
|
+
Promise.resolve(iterable.return?.()).catch(() => {});
|
|
1045
|
+
}
|
|
1046
|
+
};
|
|
1047
|
+
const channel = newInvokationChannel({
|
|
1048
|
+
port,
|
|
1049
|
+
handler: (data) => {
|
|
1050
|
+
const message = data;
|
|
1051
|
+
if (message?.cancel) {
|
|
1052
|
+
cancelOutgoing();
|
|
1053
|
+
return;
|
|
1054
|
+
}
|
|
1055
|
+
return notifyAll(message);
|
|
1056
|
+
}
|
|
1057
|
+
});
|
|
1058
|
+
const start = () => channel.start();
|
|
1059
|
+
const cancel = () => {
|
|
1060
|
+
channel.invoke({ cancel: true }).catch(() => {});
|
|
1061
|
+
};
|
|
1062
|
+
const close = async () => {
|
|
1063
|
+
await notifyAll({ done: true });
|
|
1064
|
+
for (const it of [...iterators]) await it.return?.();
|
|
1065
|
+
await channel.close();
|
|
1066
|
+
};
|
|
1067
|
+
async function* recieveAll() {
|
|
1068
|
+
yield* recieveIterator((deliver) => {
|
|
1069
|
+
listeners.push(deliver);
|
|
1070
|
+
return () => {
|
|
1071
|
+
listeners = listeners.filter((l) => l !== deliver);
|
|
1072
|
+
};
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
async function sendAll(it) {
|
|
1076
|
+
await sendIterator((chunk) => void channel.invoke(chunk), (async function* () {
|
|
1077
|
+
try {
|
|
1078
|
+
iterators.push(it);
|
|
1079
|
+
yield* it;
|
|
1080
|
+
} finally {
|
|
1081
|
+
iterators = iterators.filter((i) => i !== it);
|
|
1082
|
+
}
|
|
1083
|
+
})());
|
|
1084
|
+
}
|
|
1085
|
+
return {
|
|
1086
|
+
start,
|
|
1087
|
+
close,
|
|
1088
|
+
cancel,
|
|
1089
|
+
recieveAll,
|
|
1090
|
+
sendAll
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
//#endregion
|
|
1094
|
+
//#region src/core/registry.ts
|
|
1095
|
+
function newRegistry(onError = console.error) {
|
|
1096
|
+
let counter = 0;
|
|
1097
|
+
const registrations = {};
|
|
1098
|
+
const register = (action) => {
|
|
1099
|
+
const id = counter++;
|
|
1100
|
+
const fn = Object.assign((skip) => {
|
|
1101
|
+
try {
|
|
1102
|
+
delete registrations[id];
|
|
1103
|
+
return skip ? void 0 : action();
|
|
1104
|
+
} catch (error) {
|
|
1105
|
+
onError(error);
|
|
1106
|
+
}
|
|
1107
|
+
}, { action });
|
|
1108
|
+
registrations[id] = fn;
|
|
1109
|
+
return fn;
|
|
1110
|
+
};
|
|
1111
|
+
const unregister = (action) => {
|
|
1112
|
+
for (const r of Object.values(registrations)) if (r.action === action) r(true);
|
|
1113
|
+
};
|
|
1114
|
+
const clear = () => {
|
|
1115
|
+
for (const r of Object.values(registrations)) r();
|
|
1116
|
+
};
|
|
1117
|
+
return Object.assign([
|
|
1118
|
+
register,
|
|
1119
|
+
clear,
|
|
1120
|
+
unregister
|
|
1121
|
+
], {
|
|
1122
|
+
register,
|
|
1123
|
+
clear,
|
|
1124
|
+
unregister
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
1127
|
+
//#endregion
|
|
1128
|
+
//#region ../webrun-http-streams/dist/index.js
|
|
1129
|
+
const CR = 13;
|
|
1130
|
+
const LF = 10;
|
|
1131
|
+
const EMPTY = /* @__PURE__ */ new Uint8Array(0);
|
|
1132
|
+
var ByteStreamError = class extends Error {
|
|
1133
|
+
name = "ByteStreamError";
|
|
1134
|
+
};
|
|
1135
|
+
function toAsyncIterator(input) {
|
|
1136
|
+
const asyncIter = input[Symbol.asyncIterator];
|
|
1137
|
+
if (asyncIter) return asyncIter.call(input);
|
|
1138
|
+
const syncIter = input[Symbol.iterator]();
|
|
1139
|
+
return { next() {
|
|
1140
|
+
return Promise.resolve(syncIter.next());
|
|
1141
|
+
} };
|
|
1142
|
+
}
|
|
1143
|
+
/**
|
|
1144
|
+
* Discard an iterable we are contractually forbidden from consuming — a body
|
|
1145
|
+
* skipped for HEAD/204, or one abandoned because the peer reported an error.
|
|
1146
|
+
*
|
|
1147
|
+
* The `.next()` is not optional: `.return()` on a generator still in suspended
|
|
1148
|
+
* start is a no-op, so the body never runs and its `try/finally` never unwinds.
|
|
1149
|
+
* Without it a wrapped ReadableStream or socket is never cancelled.
|
|
1150
|
+
*/
|
|
1151
|
+
async function discard(source) {
|
|
1152
|
+
if (source === void 0) return;
|
|
1153
|
+
const it = toAsyncIterator(source);
|
|
1154
|
+
try {
|
|
1155
|
+
await it.next();
|
|
1156
|
+
await it.return?.();
|
|
1157
|
+
} catch {}
|
|
1158
|
+
}
|
|
1159
|
+
function concatChunks(parts, totalLen) {
|
|
1160
|
+
if (parts.length === 1) {
|
|
1161
|
+
const only = parts[0];
|
|
1162
|
+
if (only !== void 0) return only;
|
|
1163
|
+
}
|
|
1164
|
+
const out = new Uint8Array(totalLen);
|
|
1165
|
+
let off = 0;
|
|
1166
|
+
for (const p of parts) {
|
|
1167
|
+
out.set(p, off);
|
|
1168
|
+
off += p.byteLength;
|
|
1169
|
+
}
|
|
1170
|
+
return out;
|
|
1171
|
+
}
|
|
1172
|
+
/**
|
|
1173
|
+
* Pull-based reader over a byte source. Holds at most one pending buffer, and
|
|
1174
|
+
* hands out `subarray` views rather than copies — a body never passes through
|
|
1175
|
+
* an allocation here.
|
|
1176
|
+
*/
|
|
1177
|
+
var ByteReader = class {
|
|
1178
|
+
#iter;
|
|
1179
|
+
#buf = EMPTY;
|
|
1180
|
+
#done = false;
|
|
1181
|
+
constructor(input) {
|
|
1182
|
+
this.#iter = toAsyncIterator(input);
|
|
1183
|
+
}
|
|
1184
|
+
/** Bytes already pulled from the source but not yet consumed. */
|
|
1185
|
+
bufferedLength() {
|
|
1186
|
+
return this.#buf.byteLength;
|
|
1187
|
+
}
|
|
1188
|
+
/** Pull one more non-empty chunk. Returns false at end of stream. */
|
|
1189
|
+
async #pull() {
|
|
1190
|
+
if (this.#done) return false;
|
|
1191
|
+
while (true) {
|
|
1192
|
+
const next = await this.#iter.next();
|
|
1193
|
+
if (next.done) {
|
|
1194
|
+
this.#done = true;
|
|
1195
|
+
return false;
|
|
1196
|
+
}
|
|
1197
|
+
const chunk = next.value;
|
|
1198
|
+
if (chunk.byteLength === 0) continue;
|
|
1199
|
+
this.#buf = this.#buf.byteLength === 0 ? chunk : concatChunks([this.#buf, chunk], this.#buf.byteLength + chunk.byteLength);
|
|
1200
|
+
return true;
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
async peekByte() {
|
|
1204
|
+
while (this.#buf.byteLength === 0) if (!await this.#pull()) return void 0;
|
|
1205
|
+
return this.#buf[0];
|
|
1206
|
+
}
|
|
1207
|
+
/** Up to `max` bytes. `undefined` means end of stream. */
|
|
1208
|
+
async readSome(max) {
|
|
1209
|
+
while (this.#buf.byteLength === 0) if (!await this.#pull()) return void 0;
|
|
1210
|
+
const take = Math.min(max, this.#buf.byteLength);
|
|
1211
|
+
const out = this.#buf.subarray(0, take);
|
|
1212
|
+
this.#buf = this.#buf.subarray(take);
|
|
1213
|
+
return out;
|
|
1214
|
+
}
|
|
1215
|
+
/**
|
|
1216
|
+
* One CRLF-terminated line, without the CRLF. A bare LF is rejected: real
|
|
1217
|
+
* peers always send CRLF, and tolerating a bare LF is precisely the lenience
|
|
1218
|
+
* that lets request smuggling through a proxy pair.
|
|
1219
|
+
*
|
|
1220
|
+
* The `maxBytes` bound is best-effort: it only rejects a line if the check
|
|
1221
|
+
* happens to run before the line is fully buffered. A line already sitting in
|
|
1222
|
+
* the buffer bypasses the check. Callers needing a hard per-line limit or
|
|
1223
|
+
* aggregate bounds must keep their own running total.
|
|
1224
|
+
*/
|
|
1225
|
+
async readLine(maxBytes) {
|
|
1226
|
+
let searched = 0;
|
|
1227
|
+
while (true) {
|
|
1228
|
+
const idx = this.#buf.indexOf(LF, searched);
|
|
1229
|
+
if (idx !== -1) {
|
|
1230
|
+
if (idx === 0 || this.#buf[idx - 1] !== CR) throw new ByteStreamError("bare LF line terminator; CRLF required");
|
|
1231
|
+
const line = this.#buf.subarray(0, idx - 1);
|
|
1232
|
+
this.#buf = this.#buf.subarray(idx + 1);
|
|
1233
|
+
return line;
|
|
1234
|
+
}
|
|
1235
|
+
searched = this.#buf.byteLength;
|
|
1236
|
+
if (searched > maxBytes) throw new ByteStreamError(`line exceeds ${maxBytes} bytes without CRLF`);
|
|
1237
|
+
if (!await this.#pull()) throw new ByteStreamError(`stream ended after ${searched} bytes without CRLF`);
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
/** Everything not yet consumed, lazily. */
|
|
1241
|
+
async *rest() {
|
|
1242
|
+
while (true) {
|
|
1243
|
+
if (this.#buf.byteLength > 0) {
|
|
1244
|
+
const out = this.#buf;
|
|
1245
|
+
this.#buf = EMPTY;
|
|
1246
|
+
yield out;
|
|
1247
|
+
continue;
|
|
1248
|
+
}
|
|
1249
|
+
if (!await this.#pull()) return;
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
};
|
|
1253
|
+
/**
|
|
1254
|
+
* Raised for any byte sequence this codec refuses to interpret. Every case is
|
|
1255
|
+
* a refusal to guess: HTTP/1.1 parsers that guess are how request smuggling
|
|
1256
|
+
* works.
|
|
1257
|
+
*/
|
|
1258
|
+
var HttpParseError = class extends Error {
|
|
1259
|
+
name = "HttpParseError";
|
|
1260
|
+
};
|
|
1261
|
+
const NEWLINE = 10;
|
|
1262
|
+
/** Mirrors the HTTP/1.1 codec's default `maxHeaderBytes`. */
|
|
1263
|
+
const MAX_ENVELOPE_BYTES = 65536;
|
|
1264
|
+
const encoder$1 = new TextEncoder();
|
|
1265
|
+
const decoder = new TextDecoder();
|
|
1266
|
+
/**
|
|
1267
|
+
* Encode an HTTP envelope plus optional body as one continuous byte stream:
|
|
1268
|
+
*
|
|
1269
|
+
* <JSON.stringify(envelope)>\n<body bytes...>
|
|
1270
|
+
*
|
|
1271
|
+
* `JSON.stringify` with default whitespace never emits a literal `\n`, so the
|
|
1272
|
+
* first `0x0a` byte unambiguously terminates the envelope.
|
|
1273
|
+
*
|
|
1274
|
+
* This is the same wire shape used by the legacy `webrun-http-port` package.
|
|
1275
|
+
*/
|
|
1276
|
+
async function* encodeMessage(envelope, body) {
|
|
1277
|
+
yield encoder$1.encode(`${JSON.stringify(envelope)}\n`);
|
|
1278
|
+
if (!body) return;
|
|
1279
|
+
for await (const chunk of body) if (chunk.byteLength > 0) yield chunk;
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* Consume an envelope-then-body byte stream. Returns the parsed envelope and
|
|
1283
|
+
* an async iterable over the remaining body bytes.
|
|
1284
|
+
*/
|
|
1285
|
+
async function decodeMessage(input) {
|
|
1286
|
+
const iter = toAsyncIterator(input);
|
|
1287
|
+
const accum = [];
|
|
1288
|
+
let accumLen = 0;
|
|
1289
|
+
let before;
|
|
1290
|
+
let tail;
|
|
1291
|
+
while (true) {
|
|
1292
|
+
const next = await iter.next();
|
|
1293
|
+
if (next.done) throw new HttpParseError(`decodeMessage: stream ended after ${accumLen} bytes without delimiter (\\n)`);
|
|
1294
|
+
const chunk = next.value;
|
|
1295
|
+
if (chunk.byteLength === 0) continue;
|
|
1296
|
+
const nl = chunk.indexOf(NEWLINE);
|
|
1297
|
+
if (nl === -1) {
|
|
1298
|
+
accum.push(chunk);
|
|
1299
|
+
accumLen += chunk.byteLength;
|
|
1300
|
+
if (accumLen > MAX_ENVELOPE_BYTES) throw new HttpParseError(`decodeMessage: envelope exceeds ${MAX_ENVELOPE_BYTES} bytes without delimiter (\\n)`);
|
|
1301
|
+
continue;
|
|
1302
|
+
}
|
|
1303
|
+
accum.push(chunk.subarray(0, nl));
|
|
1304
|
+
accumLen += nl;
|
|
1305
|
+
before = concatChunks(accum, accumLen);
|
|
1306
|
+
tail = chunk.subarray(nl + 1);
|
|
1307
|
+
break;
|
|
1308
|
+
}
|
|
1309
|
+
let envelope;
|
|
1310
|
+
try {
|
|
1311
|
+
envelope = JSON.parse(decoder.decode(before));
|
|
1312
|
+
} catch (err) {
|
|
1313
|
+
throw new HttpParseError(`decodeMessage: malformed envelope JSON at bytes 0..${before.byteLength}: ${err.message}`);
|
|
1314
|
+
}
|
|
1315
|
+
async function* body() {
|
|
1316
|
+
if (tail.byteLength > 0) yield tail;
|
|
1317
|
+
while (true) {
|
|
1318
|
+
const next = await iter.next();
|
|
1319
|
+
if (next.done) return;
|
|
1320
|
+
if (next.value.byteLength > 0) yield next.value;
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
return {
|
|
1324
|
+
envelope,
|
|
1325
|
+
body: body()
|
|
1326
|
+
};
|
|
1327
|
+
}
|
|
1328
|
+
const OPEN_BRACE = 123;
|
|
1329
|
+
/**
|
|
1330
|
+
* The original wire format — `<JSON.stringify(envelope)>\n<body bytes…>` —
|
|
1331
|
+
* expressed as a `MessageCodec`. Direction-agnostic: requests and responses
|
|
1332
|
+
* serialise identically.
|
|
1333
|
+
*
|
|
1334
|
+
* Retained so a peer pair can be upgraded in either order; see ADR-0006.
|
|
1335
|
+
*/
|
|
1336
|
+
const jsonEnvelopeCodec = {
|
|
1337
|
+
name: "json-envelope",
|
|
1338
|
+
sniff: (byte) => byte === OPEN_BRACE,
|
|
1339
|
+
encodeRequest: (env, body) => encodeMessage(env, body),
|
|
1340
|
+
encodeResponse: (env, body) => encodeMessage(env, body),
|
|
1341
|
+
decodeRequest: (input) => decodeMessage(input),
|
|
1342
|
+
decodeResponse: (input) => decodeMessage(input)
|
|
1343
|
+
};
|
|
1344
|
+
const TCHAR = /* @__PURE__ */ new Set("!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
|
|
1345
|
+
const SP = 32;
|
|
1346
|
+
const HTAB = 9;
|
|
1347
|
+
function isTokenChar(byte) {
|
|
1348
|
+
return byte > SP && byte < 127 && TCHAR.has(String.fromCharCode(byte));
|
|
1349
|
+
}
|
|
1350
|
+
function isToken(value) {
|
|
1351
|
+
if (value.length === 0) return false;
|
|
1352
|
+
for (const ch of value) if (!TCHAR.has(ch)) return false;
|
|
1353
|
+
return true;
|
|
1354
|
+
}
|
|
1355
|
+
/**
|
|
1356
|
+
* Header bytes are latin-1: byte-preserving, matching Node, and lossless
|
|
1357
|
+
* across a decode/encode round-trip. Control characters are rejected
|
|
1358
|
+
* separately by `assertValidHeaderValue`.
|
|
1359
|
+
*/
|
|
1360
|
+
function decodeLatin1(bytes) {
|
|
1361
|
+
let out = "";
|
|
1362
|
+
for (const byte of bytes) out += String.fromCharCode(byte);
|
|
1363
|
+
return out;
|
|
1364
|
+
}
|
|
1365
|
+
function encodeLatin1(text) {
|
|
1366
|
+
const out = new Uint8Array(text.length);
|
|
1367
|
+
for (let i = 0; i < text.length; i++) {
|
|
1368
|
+
const code = text.charCodeAt(i);
|
|
1369
|
+
if (code > 255) throw new HttpParseError(`not latin-1 encodable: ${JSON.stringify(text)}`);
|
|
1370
|
+
out[i] = code;
|
|
1371
|
+
}
|
|
1372
|
+
return out;
|
|
1373
|
+
}
|
|
1374
|
+
const HOST_IP_LITERAL = /^\[[0-9A-Fa-f:.]+\](:\d{1,5})?$/;
|
|
1375
|
+
const HOST_REG_NAME = /^[A-Za-z0-9._~-]+(:\d{1,5})?$/;
|
|
1376
|
+
/**
|
|
1377
|
+
* Validates a value that is about to become (or was read as) a `Host`
|
|
1378
|
+
* header: untrusted input either way, so an unrecognised shape is a refusal,
|
|
1379
|
+
* not a guess. Rejects a present-but-empty value, one carrying userinfo
|
|
1380
|
+
* (`evil.com@good.com`), and — the reason this also runs on encode — one
|
|
1381
|
+
* smuggling a CRLF-terminated line into the authority of a caller-supplied
|
|
1382
|
+
* url. Never applied to trusted configuration (a codec's `opts.host`).
|
|
1383
|
+
*/
|
|
1384
|
+
function assertValidHost(host) {
|
|
1385
|
+
if (!HOST_IP_LITERAL.test(host) && !HOST_REG_NAME.test(host)) throw new HttpParseError(`invalid Host header: ${JSON.stringify(host)}`);
|
|
1386
|
+
}
|
|
1387
|
+
/**
|
|
1388
|
+
* A request-target must be entirely visible ASCII (RFC 9110 VCHAR) — nothing
|
|
1389
|
+
* `<= 0x20` (space and every control character, CR/LF included) and nothing
|
|
1390
|
+
* `>= 0x7F` (DEL and beyond). Applied on encode (`splitTarget`, so a
|
|
1391
|
+
* caller-supplied url can never inject a second request line) and on decode
|
|
1392
|
+
* (so a relay that decodes then re-encodes can never put an embedded control
|
|
1393
|
+
* character back on the wire).
|
|
1394
|
+
*/
|
|
1395
|
+
function assertValidTarget(target) {
|
|
1396
|
+
for (let i = 0; i < target.length; i++) {
|
|
1397
|
+
const code = target.charCodeAt(i);
|
|
1398
|
+
if (code <= SP || code >= 127) throw new HttpParseError(`invalid request-target: ${JSON.stringify(target)}`);
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
/**
|
|
1402
|
+
* Shared control-character check behind both `assertValidHeaderValue` and
|
|
1403
|
+
* `assertValidStatusText` — the two were previously checked by different,
|
|
1404
|
+
* looser rules (statusText only rejected CR/LF), which is exactly the
|
|
1405
|
+
* asymmetry class C1 and M5 are both instances of. `label` is prepended
|
|
1406
|
+
* verbatim to each message, so callers keep their own wording.
|
|
1407
|
+
*/
|
|
1408
|
+
function assertNoControlChars(label, value) {
|
|
1409
|
+
for (let i = 0; i < value.length; i++) {
|
|
1410
|
+
const code = value.charCodeAt(i);
|
|
1411
|
+
if (code === 13 || code === 10) throw new HttpParseError(`${label} contains CR or LF`);
|
|
1412
|
+
if (code < SP && code !== HTAB || code === 127) throw new HttpParseError(`${label} contains a control character`);
|
|
1413
|
+
if (code > 255) throw new HttpParseError(`${label} is not latin-1 encodable`);
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
function assertValidHeaderValue(name, value) {
|
|
1417
|
+
assertNoControlChars(`header "${name}" value`, value);
|
|
1418
|
+
}
|
|
1419
|
+
/** Same character class as a header value (M5) — CR/LF, every C0 control, and DEL. */
|
|
1420
|
+
function assertValidStatusText(value) {
|
|
1421
|
+
assertNoControlChars("statusText", value);
|
|
1422
|
+
}
|
|
1423
|
+
function encodeHeaderLines(headers) {
|
|
1424
|
+
let out = "";
|
|
1425
|
+
for (const [name, value] of headers) {
|
|
1426
|
+
if (!isToken(name)) throw new HttpParseError(`invalid header name: ${JSON.stringify(name)}`);
|
|
1427
|
+
assertValidHeaderValue(name, value);
|
|
1428
|
+
out += `${name}: ${value}\r\n`;
|
|
1429
|
+
}
|
|
1430
|
+
return out;
|
|
1431
|
+
}
|
|
1432
|
+
/**
|
|
1433
|
+
* Read to the blank line. `alreadyUsed` is the byte count of the start line,
|
|
1434
|
+
* so the bound covers the whole head section rather than the headers alone.
|
|
1435
|
+
*/
|
|
1436
|
+
async function readHeaderSection(reader, maxHeaderBytes, alreadyUsed) {
|
|
1437
|
+
const headers = [];
|
|
1438
|
+
let used = alreadyUsed;
|
|
1439
|
+
while (true) {
|
|
1440
|
+
const remaining = maxHeaderBytes - used;
|
|
1441
|
+
if (remaining <= 0) throw new HttpParseError(`head section exceeds ${maxHeaderBytes} bytes`);
|
|
1442
|
+
const lineBytes = await reader.readLine(remaining);
|
|
1443
|
+
used += lineBytes.byteLength + 2;
|
|
1444
|
+
if (used > maxHeaderBytes) throw new HttpParseError(`head section exceeds ${maxHeaderBytes} bytes`);
|
|
1445
|
+
if (lineBytes.byteLength === 0) return headers;
|
|
1446
|
+
if (lineBytes[0] === SP || lineBytes[0] === HTAB) throw new HttpParseError("obs-fold header continuation is not accepted");
|
|
1447
|
+
const line = decodeLatin1(lineBytes);
|
|
1448
|
+
const colon = line.indexOf(":");
|
|
1449
|
+
if (colon <= 0) throw new HttpParseError(`malformed header line: ${JSON.stringify(line)}`);
|
|
1450
|
+
const name = line.slice(0, colon);
|
|
1451
|
+
if (!isToken(name)) throw new HttpParseError(`invalid header name: ${JSON.stringify(name)}`);
|
|
1452
|
+
const value = line.slice(colon + 1).replace(/^[ \t]+/, "").replace(/[ \t]+$/, "");
|
|
1453
|
+
assertValidHeaderValue(name, value);
|
|
1454
|
+
headers.push([name, value]);
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
function getAll(headers, name) {
|
|
1458
|
+
const lower = name.toLowerCase();
|
|
1459
|
+
return headers.filter(([k]) => k.toLowerCase() === lower).map(([, v]) => v);
|
|
1460
|
+
}
|
|
1461
|
+
function withoutHeaders(headers, names) {
|
|
1462
|
+
const drop = new Set(names.map((n) => n.toLowerCase()));
|
|
1463
|
+
return headers.filter(([k]) => !drop.has(k.toLowerCase()));
|
|
1464
|
+
}
|
|
1465
|
+
/**
|
|
1466
|
+
* Parse a `Content-Length` field into a single validated value.
|
|
1467
|
+
*
|
|
1468
|
+
* RFC 9110 §8.6 permits the value to be a comma-separated list of identical
|
|
1469
|
+
* numbers (a relay may have appended one), so the list is folded; differing
|
|
1470
|
+
* values are a refusal, not a choice. Shared by `resolveFraming` on decode and
|
|
1471
|
+
* by the encoder's declared-length check, which previously carried its own
|
|
1472
|
+
* copy that did NOT split on commas — so decode accepted `5, 5` while encode
|
|
1473
|
+
* rejected it, and a relay that decoded then re-encoded threw.
|
|
1474
|
+
*
|
|
1475
|
+
* Returns undefined when the field is absent.
|
|
1476
|
+
*/
|
|
1477
|
+
function parseContentLength(values) {
|
|
1478
|
+
if (values.length === 0) return void 0;
|
|
1479
|
+
const unique = new Set(values.flatMap((v) => v.split(",").map((s) => s.trim())));
|
|
1480
|
+
if (unique.size !== 1) throw new HttpParseError(`conflicting Content-Length values: ${[...unique].join(", ")}`);
|
|
1481
|
+
const raw = [...unique][0];
|
|
1482
|
+
if (!/^\d{1,15}$/.test(raw)) throw new HttpParseError(`invalid Content-Length: ${JSON.stringify(raw)}`);
|
|
1483
|
+
return Number(raw);
|
|
1484
|
+
}
|
|
1485
|
+
/**
|
|
1486
|
+
* Statuses that carry no body whatever the headers say (RFC 9110 §8.6): 1xx,
|
|
1487
|
+
* 204 and 304. Defined once because the encoder must not frame a body for
|
|
1488
|
+
* them and the decoder must not try to read one — two lists that agreed today
|
|
1489
|
+
* and were free to drift tomorrow.
|
|
1490
|
+
*
|
|
1491
|
+
* A response to HEAD is also bodyless, but that depends on the request rather
|
|
1492
|
+
* than the status, so callers test it separately.
|
|
1493
|
+
*/
|
|
1494
|
+
function isBodylessStatus(status) {
|
|
1495
|
+
return status < 200 || status === 204 || status === 304;
|
|
1496
|
+
}
|
|
1497
|
+
/**
|
|
1498
|
+
* RFC 9112 §6.3, with every ambiguity turned into a refusal. In particular a
|
|
1499
|
+
* message declaring both Content-Length and Transfer-Encoding is rejected
|
|
1500
|
+
* rather than resolved — disagreeing on which one wins is request smuggling.
|
|
1501
|
+
*/
|
|
1502
|
+
function resolveFraming(headers, version) {
|
|
1503
|
+
const te = getAll(headers, "transfer-encoding");
|
|
1504
|
+
const cl = getAll(headers, "content-length");
|
|
1505
|
+
if (te.length > 0 && cl.length > 0) throw new HttpParseError("message declares both Content-Length and Transfer-Encoding; refusing (request smuggling)");
|
|
1506
|
+
if (te.length > 0) {
|
|
1507
|
+
const encodings = te.join(",").split(",").map((s) => s.trim().toLowerCase()).filter((s) => s !== "");
|
|
1508
|
+
if (encodings.length !== 1 || encodings[0] !== "chunked") throw new HttpParseError(`unsupported Transfer-Encoding: ${JSON.stringify(te.join(", "))}`);
|
|
1509
|
+
if (version === "HTTP/1.0") throw new HttpParseError("Transfer-Encoding is not valid in HTTP/1.0");
|
|
1510
|
+
return { kind: "chunked" };
|
|
1511
|
+
}
|
|
1512
|
+
const length = parseContentLength(cl);
|
|
1513
|
+
if (length !== void 0) return {
|
|
1514
|
+
kind: "length",
|
|
1515
|
+
length
|
|
1516
|
+
};
|
|
1517
|
+
return { kind: "none" };
|
|
1518
|
+
}
|
|
1519
|
+
const CRLF = new Uint8Array([13, 10]);
|
|
1520
|
+
const LAST_CHUNK = new Uint8Array([
|
|
1521
|
+
48,
|
|
1522
|
+
13,
|
|
1523
|
+
10,
|
|
1524
|
+
13,
|
|
1525
|
+
10
|
|
1526
|
+
]);
|
|
1527
|
+
const encoder = new TextEncoder();
|
|
1528
|
+
/**
|
|
1529
|
+
* Chunk sizes are written in HEXADECIMAL — a 21-byte chunk is `15`. Writing
|
|
1530
|
+
* them in decimal is the defect note 15 found in @libp2p/http, and it is the
|
|
1531
|
+
* one that cannot be caught downstream: decimal digits are also valid hex, so
|
|
1532
|
+
* a conforming parser silently reads the wrong length.
|
|
1533
|
+
*
|
|
1534
|
+
* Zero-length source chunks are skipped; a zero-sized chunk on the wire is the
|
|
1535
|
+
* body terminator.
|
|
1536
|
+
*/
|
|
1537
|
+
async function* encodeChunked(body) {
|
|
1538
|
+
for await (const chunk of body) {
|
|
1539
|
+
if (chunk.byteLength === 0) continue;
|
|
1540
|
+
yield encoder.encode(`${chunk.byteLength.toString(16)}\r\n`);
|
|
1541
|
+
yield chunk;
|
|
1542
|
+
yield CRLF;
|
|
1543
|
+
}
|
|
1544
|
+
yield LAST_CHUNK;
|
|
1545
|
+
}
|
|
1546
|
+
/**
|
|
1547
|
+
* Decode a chunked body, yielding data chunks as they arrive. Nothing is
|
|
1548
|
+
* accumulated: a chunk larger than the transport's frame is yielded in pieces.
|
|
1549
|
+
*/
|
|
1550
|
+
async function* decodeChunked(reader, maxLineBytes) {
|
|
1551
|
+
while (true) {
|
|
1552
|
+
const sizeLine = decodeLatin1(await reader.readLine(maxLineBytes));
|
|
1553
|
+
const semicolon = sizeLine.indexOf(";");
|
|
1554
|
+
const sizeText = semicolon === -1 ? sizeLine : sizeLine.slice(0, semicolon);
|
|
1555
|
+
if (!/^[0-9a-fA-F]{1,32}$/.test(sizeText)) throw new HttpParseError(`invalid chunk size: ${JSON.stringify(sizeLine)}`);
|
|
1556
|
+
const size = Number.parseInt(sizeText, 16);
|
|
1557
|
+
if (!Number.isSafeInteger(size)) throw new HttpParseError(`chunk size is too large: ${JSON.stringify(sizeLine)}`);
|
|
1558
|
+
if (size === 0) {
|
|
1559
|
+
let used = 0;
|
|
1560
|
+
while (true) {
|
|
1561
|
+
const remaining = maxLineBytes - used;
|
|
1562
|
+
if (remaining <= 0) throw new HttpParseError(`trailer section exceeds ${maxLineBytes} bytes`);
|
|
1563
|
+
const lineBytes = await reader.readLine(remaining);
|
|
1564
|
+
used += lineBytes.byteLength + 2;
|
|
1565
|
+
if (used > maxLineBytes) throw new HttpParseError(`trailer section exceeds ${maxLineBytes} bytes`);
|
|
1566
|
+
if (lineBytes.byteLength === 0) break;
|
|
1567
|
+
}
|
|
1568
|
+
return;
|
|
1569
|
+
}
|
|
1570
|
+
let remaining = size;
|
|
1571
|
+
while (remaining > 0) {
|
|
1572
|
+
const part = await reader.readSome(remaining);
|
|
1573
|
+
if (part === void 0) throw new HttpParseError(`chunk truncated: ${remaining} of ${size} bytes missing`);
|
|
1574
|
+
remaining -= part.byteLength;
|
|
1575
|
+
yield part;
|
|
1576
|
+
}
|
|
1577
|
+
try {
|
|
1578
|
+
if ((await reader.readLine(2)).byteLength !== 0) throw new HttpParseError("chunk data not terminated by CRLF");
|
|
1579
|
+
} catch (err) {
|
|
1580
|
+
if (err instanceof ByteStreamError) throw new HttpParseError("chunk data not terminated by CRLF");
|
|
1581
|
+
throw err;
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
const VERSIONS = /* @__PURE__ */ new Set(["HTTP/1.1", "HTTP/1.0"]);
|
|
1586
|
+
const ABSOLUTE_FORM = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;
|
|
1587
|
+
/**
|
|
1588
|
+
* One message per Duplex call (ADR-0006), so bytes after a complete message
|
|
1589
|
+
* are an error. Checked against what is ALREADY BUFFERED rather than by
|
|
1590
|
+
* awaiting end-of-stream: a live socket from a keep-alive peer never reaches
|
|
1591
|
+
* EOF, so awaiting one would hang instead of failing.
|
|
1592
|
+
*/
|
|
1593
|
+
function assertNoBufferedBytes(reader) {
|
|
1594
|
+
const extra = reader.bufferedLength();
|
|
1595
|
+
if (extra > 0) throw new HttpParseError(`${extra} trailing bytes after a complete message`);
|
|
1596
|
+
}
|
|
1597
|
+
/**
|
|
1598
|
+
* The public error contract (I2): everything leaving `decodeRequest` /
|
|
1599
|
+
* `decodeResponse` is an `HttpParseError`, whether the refusal happened
|
|
1600
|
+
* synchronously (a malformed start line or header) or lazily while the body
|
|
1601
|
+
* is later drained. `ByteStreamError` — the `ByteReader`'s own class, never
|
|
1602
|
+
* exported — is the one thing converted here, message and all preserved via
|
|
1603
|
+
* `cause`. Anything else is a genuine failure of the underlying source (a
|
|
1604
|
+
* dropped socket, say) and must reach the caller unchanged: blanket-catching
|
|
1605
|
+
* would hide that distinction.
|
|
1606
|
+
*/
|
|
1607
|
+
function toHttpParseError(err) {
|
|
1608
|
+
if (err instanceof ByteStreamError) throw new HttpParseError(err.message, { cause: err });
|
|
1609
|
+
throw err;
|
|
1610
|
+
}
|
|
1611
|
+
/** Applies `toHttpParseError` across the whole lifetime of a body generator. */
|
|
1612
|
+
async function* convertBodyErrors(source) {
|
|
1613
|
+
try {
|
|
1614
|
+
yield* source;
|
|
1615
|
+
} catch (err) {
|
|
1616
|
+
toHttpParseError(err);
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
async function* readBody(reader, framing, opts, noneMeansEof) {
|
|
1620
|
+
if (framing.kind === "chunked") {
|
|
1621
|
+
yield* decodeChunked(reader, opts.maxHeaderBytes);
|
|
1622
|
+
assertNoBufferedBytes(reader);
|
|
1623
|
+
return;
|
|
1624
|
+
}
|
|
1625
|
+
if (framing.kind === "length") {
|
|
1626
|
+
let remaining = framing.length;
|
|
1627
|
+
while (remaining > 0) {
|
|
1628
|
+
const part = await reader.readSome(remaining);
|
|
1629
|
+
if (part === void 0) throw new HttpParseError(`body truncated: ${remaining} of ${framing.length} bytes missing`);
|
|
1630
|
+
remaining -= part.byteLength;
|
|
1631
|
+
yield part;
|
|
1632
|
+
}
|
|
1633
|
+
assertNoBufferedBytes(reader);
|
|
1634
|
+
return;
|
|
1635
|
+
}
|
|
1636
|
+
if (noneMeansEof) {
|
|
1637
|
+
yield* reader.rest();
|
|
1638
|
+
return;
|
|
1639
|
+
}
|
|
1640
|
+
assertNoBufferedBytes(reader);
|
|
1641
|
+
}
|
|
1642
|
+
/**
|
|
1643
|
+
* `readLine`'s bound is best-effort — it is skipped when the line is already
|
|
1644
|
+
* buffered — so a very long start line can reach these messages intact. Since
|
|
1645
|
+
* a refusal is now echoed back to the sender in a 400 body, quote only enough
|
|
1646
|
+
* to diagnose rather than reflecting the whole thing.
|
|
1647
|
+
*/
|
|
1648
|
+
function quoteLine(line) {
|
|
1649
|
+
const MAX = 120;
|
|
1650
|
+
return line.length <= MAX ? JSON.stringify(line) : `${JSON.stringify(line.slice(0, MAX))} (truncated from ${line.length} chars)`;
|
|
1651
|
+
}
|
|
1652
|
+
async function decodeRequest(input, opts) {
|
|
1653
|
+
const reader = new ByteReader(input);
|
|
1654
|
+
try {
|
|
1655
|
+
const startBytes = await reader.readLine(opts.maxHeaderBytes);
|
|
1656
|
+
const startLine = decodeLatin1(startBytes);
|
|
1657
|
+
const parts = startLine.split(" ");
|
|
1658
|
+
if (parts.length !== 3) throw new HttpParseError(`malformed request line: ${quoteLine(startLine)}`);
|
|
1659
|
+
const [method, target, version] = parts;
|
|
1660
|
+
if (!isToken(method)) throw new HttpParseError(`invalid method: ${JSON.stringify(method)}`);
|
|
1661
|
+
if (!VERSIONS.has(version)) throw new HttpParseError(`unsupported HTTP version: ${JSON.stringify(version)}`);
|
|
1662
|
+
if (target === "*") throw new HttpParseError("asterisk-form request target is not supported");
|
|
1663
|
+
assertValidTarget(target);
|
|
1664
|
+
const headers = await readHeaderSection(reader, opts.maxHeaderBytes, startBytes.byteLength + 2);
|
|
1665
|
+
const hosts = getAll(headers, "host");
|
|
1666
|
+
if (hosts.length > 1) throw new HttpParseError("multiple Host headers");
|
|
1667
|
+
const host = hosts[0];
|
|
1668
|
+
let url;
|
|
1669
|
+
if (target.startsWith("/")) {
|
|
1670
|
+
if (version === "HTTP/1.1" && host === void 0) throw new HttpParseError("HTTP/1.1 request has no Host header");
|
|
1671
|
+
if (host !== void 0) assertValidHost(host);
|
|
1672
|
+
url = `${opts.scheme}://${host ?? opts.host}${target}`;
|
|
1673
|
+
} else if (ABSOLUTE_FORM.test(target)) url = target;
|
|
1674
|
+
else throw new HttpParseError(`unsupported request target: ${JSON.stringify(target)}`);
|
|
1675
|
+
try {
|
|
1676
|
+
new URL(url);
|
|
1677
|
+
} catch {
|
|
1678
|
+
throw new HttpParseError(`decoded url is not a valid URL: ${JSON.stringify(url)}`);
|
|
1679
|
+
}
|
|
1680
|
+
return {
|
|
1681
|
+
envelope: {
|
|
1682
|
+
url,
|
|
1683
|
+
method,
|
|
1684
|
+
headers
|
|
1685
|
+
},
|
|
1686
|
+
body: convertBodyErrors(readBody(reader, resolveFraming(headers, version), opts, false))
|
|
1687
|
+
};
|
|
1688
|
+
} catch (err) {
|
|
1689
|
+
toHttpParseError(err);
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
async function decodeResponse(input, opts, method) {
|
|
1693
|
+
const reader = new ByteReader(input);
|
|
1694
|
+
try {
|
|
1695
|
+
const startBytes = await reader.readLine(opts.maxHeaderBytes);
|
|
1696
|
+
const startLine = decodeLatin1(startBytes);
|
|
1697
|
+
const firstSp = startLine.indexOf(" ");
|
|
1698
|
+
if (firstSp === -1) throw new HttpParseError(`malformed status line: ${quoteLine(startLine)}`);
|
|
1699
|
+
const version = startLine.slice(0, firstSp);
|
|
1700
|
+
if (!VERSIONS.has(version)) throw new HttpParseError(`unsupported HTTP version: ${JSON.stringify(version)}`);
|
|
1701
|
+
const afterVersion = startLine.slice(firstSp + 1);
|
|
1702
|
+
const secondSp = afterVersion.indexOf(" ");
|
|
1703
|
+
const codeText = secondSp === -1 ? afterVersion : afterVersion.slice(0, secondSp);
|
|
1704
|
+
if (!/^\d{3}$/.test(codeText)) throw new HttpParseError(`invalid status code: ${JSON.stringify(codeText)}`);
|
|
1705
|
+
const status = Number(codeText);
|
|
1706
|
+
const statusText = secondSp === -1 ? "" : afterVersion.slice(secondSp + 1);
|
|
1707
|
+
const headers = await readHeaderSection(reader, opts.maxHeaderBytes, startBytes.byteLength + 2);
|
|
1708
|
+
const bodyless = isBodylessStatus(status) || method.toUpperCase() === "HEAD";
|
|
1709
|
+
const framing = bodyless ? { kind: "none" } : resolveFraming(headers, version);
|
|
1710
|
+
return {
|
|
1711
|
+
envelope: {
|
|
1712
|
+
status,
|
|
1713
|
+
statusText,
|
|
1714
|
+
headers
|
|
1715
|
+
},
|
|
1716
|
+
body: convertBodyErrors(readBody(reader, framing, opts, !bodyless))
|
|
1717
|
+
};
|
|
1718
|
+
} catch (err) {
|
|
1719
|
+
toHttpParseError(err);
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
/** Headers the codec owns: a caller-supplied copy is dropped and re-derived. */
|
|
1723
|
+
const REQUEST_OWNED = [
|
|
1724
|
+
"host",
|
|
1725
|
+
"connection",
|
|
1726
|
+
"transfer-encoding"
|
|
1727
|
+
];
|
|
1728
|
+
const RESPONSE_OWNED = ["connection", "transfer-encoding"];
|
|
1729
|
+
/**
|
|
1730
|
+
* Split a URL into an origin-form request target and an authority *without*
|
|
1731
|
+
* going through `new URL()`. `URL` normalises percent-encoding and would
|
|
1732
|
+
* re-serialise the target — which is the exact class of defect note 15 found
|
|
1733
|
+
* in @libp2p/http, where rebuilding the request line silently dropped
|
|
1734
|
+
* `url.search`. Here the target is a verbatim slice of the caller's string.
|
|
1735
|
+
*/
|
|
1736
|
+
function splitTarget(url, opts) {
|
|
1737
|
+
if (url.startsWith("/")) {
|
|
1738
|
+
assertValidTarget(url);
|
|
1739
|
+
return {
|
|
1740
|
+
target: url,
|
|
1741
|
+
authority: opts.host
|
|
1742
|
+
};
|
|
1743
|
+
}
|
|
1744
|
+
const match = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/([^/?#]*)([^#]*)/.exec(url);
|
|
1745
|
+
if (!match) throw new HttpParseError(`cannot derive a request target from url: ${JSON.stringify(url)}`);
|
|
1746
|
+
const rawAuthority = match[1];
|
|
1747
|
+
if (rawAuthority === "") throw new HttpParseError(`url has no authority: ${JSON.stringify(url)}`);
|
|
1748
|
+
const at = rawAuthority.lastIndexOf("@");
|
|
1749
|
+
const authority = at === -1 ? rawAuthority : rawAuthority.slice(at + 1);
|
|
1750
|
+
assertValidHost(authority);
|
|
1751
|
+
const rawTarget = match[2];
|
|
1752
|
+
const target = rawTarget === "" ? "/" : rawTarget.startsWith("/") ? rawTarget : `/${rawTarget}`;
|
|
1753
|
+
assertValidTarget(target);
|
|
1754
|
+
return {
|
|
1755
|
+
target,
|
|
1756
|
+
authority
|
|
1757
|
+
};
|
|
1758
|
+
}
|
|
1759
|
+
async function* emitBody(body, declared) {
|
|
1760
|
+
if (declared === void 0) {
|
|
1761
|
+
yield* encodeChunked(body);
|
|
1762
|
+
return;
|
|
1763
|
+
}
|
|
1764
|
+
let sent = 0;
|
|
1765
|
+
for await (const chunk of body) {
|
|
1766
|
+
if (chunk.byteLength === 0) continue;
|
|
1767
|
+
sent += chunk.byteLength;
|
|
1768
|
+
if (sent > declared) throw new HttpParseError(`body exceeds declared Content-Length ${declared} (${sent} bytes so far)`);
|
|
1769
|
+
yield chunk;
|
|
1770
|
+
}
|
|
1771
|
+
if (sent !== declared) throw new HttpParseError(`body is ${sent} bytes but Content-Length declares ${declared}`);
|
|
1772
|
+
}
|
|
1773
|
+
async function* encodeRequest(env, body, opts) {
|
|
1774
|
+
if (!isToken(env.method)) throw new HttpParseError(`invalid method: ${JSON.stringify(env.method)}`);
|
|
1775
|
+
const { target, authority } = splitTarget(env.url, opts);
|
|
1776
|
+
if (authority === "") throw new HttpParseError("no Host available: url has no authority and no host is configured");
|
|
1777
|
+
const carried = withoutHeaders(env.headers, REQUEST_OWNED);
|
|
1778
|
+
const declared = parseContentLength(getAll(carried, "content-length"));
|
|
1779
|
+
let head = `${env.method} ${target} HTTP/1.1\r\n`;
|
|
1780
|
+
head += `Host: ${authority}\r\n`;
|
|
1781
|
+
head += encodeHeaderLines(carried);
|
|
1782
|
+
head += "Connection: close\r\n";
|
|
1783
|
+
if (body !== void 0 && declared === void 0) head += "Transfer-Encoding: chunked\r\n";
|
|
1784
|
+
head += "\r\n";
|
|
1785
|
+
yield encodeLatin1(head);
|
|
1786
|
+
if (body === void 0) {
|
|
1787
|
+
if (declared !== void 0 && declared !== 0) throw new HttpParseError(`body is 0 bytes but Content-Length declares ${declared}`);
|
|
1788
|
+
return;
|
|
1789
|
+
}
|
|
1790
|
+
yield* emitBody(body, declared);
|
|
1791
|
+
}
|
|
1792
|
+
async function* encodeResponse(env, body, _opts, requestMethod) {
|
|
1793
|
+
if (!Number.isInteger(env.status) || env.status < 100 || env.status > 599) throw new HttpParseError(`invalid status: ${env.status}`);
|
|
1794
|
+
const reason = env.statusText ?? "";
|
|
1795
|
+
assertValidStatusText(reason);
|
|
1796
|
+
const bodylessStatus = isBodylessStatus(env.status);
|
|
1797
|
+
const bodyless = bodylessStatus || requestMethod?.toUpperCase() === "HEAD";
|
|
1798
|
+
const owned = bodylessStatus ? [...RESPONSE_OWNED, "content-length"] : RESPONSE_OWNED;
|
|
1799
|
+
const carried = withoutHeaders(env.headers, owned);
|
|
1800
|
+
const declared = parseContentLength(getAll(carried, "content-length"));
|
|
1801
|
+
let head = `HTTP/1.1 ${env.status} ${reason}\r\n`;
|
|
1802
|
+
head += encodeHeaderLines(carried);
|
|
1803
|
+
head += "Connection: close\r\n";
|
|
1804
|
+
if (!bodyless && body !== void 0 && declared === void 0) head += "Transfer-Encoding: chunked\r\n";
|
|
1805
|
+
head += "\r\n";
|
|
1806
|
+
yield encodeLatin1(head);
|
|
1807
|
+
if (bodyless) {
|
|
1808
|
+
await discard(body);
|
|
1809
|
+
return;
|
|
1810
|
+
}
|
|
1811
|
+
if (body === void 0) {
|
|
1812
|
+
if (declared !== void 0 && declared !== 0) throw new HttpParseError(`body is 0 bytes but Content-Length declares ${declared}`);
|
|
1813
|
+
return;
|
|
1814
|
+
}
|
|
1815
|
+
yield* emitBody(body, declared);
|
|
1816
|
+
}
|
|
1817
|
+
function newHttpCodec(options = {}) {
|
|
1818
|
+
const opts = {
|
|
1819
|
+
scheme: options.scheme ?? "http",
|
|
1820
|
+
host: options.host ?? "localhost",
|
|
1821
|
+
maxHeaderBytes: options.maxHeaderBytes ?? 65536
|
|
1822
|
+
};
|
|
1823
|
+
return {
|
|
1824
|
+
name: "http/1.1",
|
|
1825
|
+
sniff: (byte) => isTokenChar(byte),
|
|
1826
|
+
encodeRequest: (env, body) => encodeRequest(env, body, opts),
|
|
1827
|
+
encodeResponse: (env, body, o) => encodeResponse(env, body, opts, o?.method),
|
|
1828
|
+
decodeRequest: (input) => decodeRequest(input, opts),
|
|
1829
|
+
decodeResponse: (input, o) => decodeResponse(input, opts, o.method)
|
|
1830
|
+
};
|
|
1831
|
+
}
|
|
1832
|
+
const httpCodec = newHttpCodec();
|
|
1833
|
+
/**
|
|
1834
|
+
* Dispatches on byte 0. The formats are self-identifying — a JSON envelope
|
|
1835
|
+
* always begins `{`, which is not a token character and so can never begin an
|
|
1836
|
+
* HTTP start-line — so no negotiation handshake, magic prefix, or version byte
|
|
1837
|
+
* is needed.
|
|
1838
|
+
*
|
|
1839
|
+
* This is what makes a mixed-version peer pair safe: readers accept either
|
|
1840
|
+
* format, so the two ends can be upgraded in any order.
|
|
1841
|
+
*/
|
|
1842
|
+
function newSniffingCodec(options) {
|
|
1843
|
+
const { write, accept } = options;
|
|
1844
|
+
async function pick(input) {
|
|
1845
|
+
const reader = new ByteReader(input);
|
|
1846
|
+
const first = await reader.peekByte();
|
|
1847
|
+
if (first === void 0) throw new HttpParseError("sniff: stream ended before any bytes arrived");
|
|
1848
|
+
const codec = accept.find((c) => c.sniff(first));
|
|
1849
|
+
if (!codec) throw new HttpParseError(`sniff: no accepted codec recognises a message starting with byte 0x${first.toString(16).padStart(2, "0")}`);
|
|
1850
|
+
return {
|
|
1851
|
+
codec,
|
|
1852
|
+
input: reader.rest()
|
|
1853
|
+
};
|
|
1854
|
+
}
|
|
1855
|
+
return {
|
|
1856
|
+
name: `sniff(write=${write.name}; accept=${accept.map((c) => c.name).join(",")})`,
|
|
1857
|
+
sniff: (byte) => accept.some((c) => c.sniff(byte)),
|
|
1858
|
+
encodeRequest: (env, body) => write.encodeRequest(env, body),
|
|
1859
|
+
encodeResponse: (env, body, o) => write.encodeResponse(env, body, o),
|
|
1860
|
+
decodeRequest: async (input) => {
|
|
1861
|
+
const picked = await pick(input);
|
|
1862
|
+
try {
|
|
1863
|
+
return {
|
|
1864
|
+
...await picked.codec.decodeRequest(picked.input),
|
|
1865
|
+
codec: picked.codec
|
|
1866
|
+
};
|
|
1867
|
+
} catch (error) {
|
|
1868
|
+
if (error !== null && typeof error === "object") error.codec = picked.codec;
|
|
1869
|
+
throw error;
|
|
1870
|
+
}
|
|
1871
|
+
},
|
|
1872
|
+
decodeResponse: async (input, o) => {
|
|
1873
|
+
const picked = await pick(input);
|
|
1874
|
+
return picked.codec.decodeResponse(picked.input, o);
|
|
1875
|
+
}
|
|
1876
|
+
};
|
|
1877
|
+
}
|
|
1878
|
+
/**
|
|
1879
|
+
* Writes HTTP/1.1; accepts HTTP/1.1 or the legacy JSON envelope. Used whenever
|
|
1880
|
+
* no `codec` option is supplied.
|
|
1881
|
+
*/
|
|
1882
|
+
const defaultCodec = newSniffingCodec({
|
|
1883
|
+
write: httpCodec,
|
|
1884
|
+
accept: [httpCodec, jsonEnvelopeCodec]
|
|
1885
|
+
});
|
|
1886
|
+
/** Carries the serialized JS error between two webrun peers. */
|
|
1887
|
+
const PEER_ERROR_HEADER = "x-webrun-error";
|
|
1888
|
+
/** Hard cap on the peer-error header (M3): see `encodeErrorResponse`. */
|
|
1889
|
+
const MAX_DETAIL_CHARS = 4096;
|
|
1890
|
+
/**
|
|
1891
|
+
* JSON with every non-printable-ASCII character escaped, so the result is a
|
|
1892
|
+
* legal latin-1 header value whatever the error message contained.
|
|
1893
|
+
*/
|
|
1894
|
+
function asciiJson(value) {
|
|
1895
|
+
return JSON.stringify(value).replace(/[^\x20-\x7E]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
1896
|
+
}
|
|
1897
|
+
/**
|
|
1898
|
+
* Decision 13: a real HTTP peer cannot receive a JavaScript exception, only a
|
|
1899
|
+
* response. So an uncaught handler error becomes a conforming 500 whose body
|
|
1900
|
+
* carries the message, with the serialized error in a namespaced header that
|
|
1901
|
+
* another webrun peer re-throws from.
|
|
1902
|
+
*/
|
|
1903
|
+
function encodeErrorResponse(codec, error, method, status = 500, statusText = "Internal Server Error") {
|
|
1904
|
+
const serialized = serializeError(error);
|
|
1905
|
+
let detail = asciiJson(serialized);
|
|
1906
|
+
if (detail.length > MAX_DETAIL_CHARS) detail = asciiJson({ message: serialized.message });
|
|
1907
|
+
if (detail.length > MAX_DETAIL_CHARS) detail = detail.slice(0, MAX_DETAIL_CHARS);
|
|
1908
|
+
const message = serialized.message ?? statusText;
|
|
1909
|
+
return codec.encodeResponse({
|
|
1910
|
+
status,
|
|
1911
|
+
statusText,
|
|
1912
|
+
headers: [["Content-Type", "text/plain; charset=utf-8"], [PEER_ERROR_HEADER, detail]]
|
|
1913
|
+
}, [new TextEncoder().encode(message)], { method });
|
|
1914
|
+
}
|
|
1915
|
+
/**
|
|
1916
|
+
* `output` is the `Duplex` call's own generator — one logical call, per the
|
|
1917
|
+
* `Duplex` contract in `@statewalker/webrun-streams`: "Consumer `.return()`
|
|
1918
|
+
* on the output → producer's `finally` runs." On a mux transport
|
|
1919
|
+
* (`emulateMux`), that `finally` is what frees the stream-table slot; skip it
|
|
1920
|
+
* and every peer-error response leaks one slot, unboundedly, until the mux
|
|
1921
|
+
* itself is exhausted (`maxStreams` reached, every further call rejected).
|
|
1922
|
+
*
|
|
1923
|
+
* Cancelling `output` here — not inside the codec's own decode logic — is
|
|
1924
|
+
* deliberate. `codec.decodeResponse` already pulled from `output` to read the
|
|
1925
|
+
* head before this function runs, so unlike the body case above there's no
|
|
1926
|
+
* suspended-start no-op to worry about. And it's safe specifically *because*
|
|
1927
|
+
* this is the client's own response-only generator: the request was already
|
|
1928
|
+
* fully sent before we got here, so there is nothing left to write on it.
|
|
1929
|
+
* The equivalent is NOT safe inside `src/http1/decode.ts`'s `ByteReader` —
|
|
1930
|
+
* that code also runs when a caller wires `codec.decodeRequest`/
|
|
1931
|
+
* `decodeResponse` directly onto a raw bidirectional socket (see
|
|
1932
|
+
* `tests/http1-node-interop.test.ts`), where the *same* object is read from
|
|
1933
|
+
* and then written back to (a server reads the request, then replies on the
|
|
1934
|
+
* same socket); cancelling the read side there tears down the whole
|
|
1935
|
+
* connection out from under the pending write. That was tried and reverted —
|
|
1936
|
+
* see the Task 11 report for the "socket hang up" failure it caused.
|
|
1937
|
+
*/
|
|
1938
|
+
async function throwIfPeerError(result, output) {
|
|
1939
|
+
const found = result.envelope.headers.find(([k]) => k.toLowerCase() === PEER_ERROR_HEADER);
|
|
1940
|
+
if (!found) return;
|
|
1941
|
+
await discard(result.body);
|
|
1942
|
+
try {
|
|
1943
|
+
await output.return?.(void 0);
|
|
1944
|
+
} catch {}
|
|
1945
|
+
let payload;
|
|
1946
|
+
try {
|
|
1947
|
+
payload = JSON.parse(found[1]);
|
|
1948
|
+
} catch {
|
|
1949
|
+
payload = { message: found[1] };
|
|
1950
|
+
}
|
|
1951
|
+
throw deserializeError(payload);
|
|
1952
|
+
}
|
|
1953
|
+
/**
|
|
1954
|
+
* Initiate an HTTP call over a `Duplex`. The caller's `call: Duplex` is
|
|
1955
|
+
* obtained from any `webrun-streams-*` adapter's `connect`. Returns the
|
|
1956
|
+
* response envelope and an async iterable over the response body bytes.
|
|
1957
|
+
*
|
|
1958
|
+
* The call is one logical Duplex invocation; multiplexing of concurrent
|
|
1959
|
+
* calls is the adapter's concern (native or `emulateMux`).
|
|
1960
|
+
*/
|
|
1961
|
+
async function httpFetch(call, env, body, options = {}) {
|
|
1962
|
+
const codec = options.codec ?? defaultCodec;
|
|
1963
|
+
const output = call(codec.encodeRequest(env, body));
|
|
1964
|
+
const result = await codec.decodeResponse(output, { method: env.method });
|
|
1965
|
+
await throwIfPeerError(result, output);
|
|
1966
|
+
return result;
|
|
1967
|
+
}
|
|
1968
|
+
/**
|
|
1969
|
+
* Wrap an HTTP handler as a `Duplex` so it can be registered with any
|
|
1970
|
+
* `webrun-streams-*` adapter's `serve`.
|
|
1971
|
+
*/
|
|
1972
|
+
function httpServe(handler, options = {}) {
|
|
1973
|
+
const codec = options.codec ?? defaultCodec;
|
|
1974
|
+
return async function* httpHandlerDuplex(input) {
|
|
1975
|
+
let decoded;
|
|
1976
|
+
try {
|
|
1977
|
+
decoded = await codec.decodeRequest(input);
|
|
1978
|
+
} catch (error) {
|
|
1979
|
+
if (!(error instanceof HttpParseError)) throw error;
|
|
1980
|
+
yield* encodeErrorResponse(error.codec ?? codec, error, "GET", 400, "Bad Request");
|
|
1981
|
+
return;
|
|
1982
|
+
}
|
|
1983
|
+
const replyCodec = decoded.codec ?? codec;
|
|
1984
|
+
let result;
|
|
1985
|
+
try {
|
|
1986
|
+
result = await handler(decoded.envelope, decoded.body);
|
|
1987
|
+
} catch (error) {
|
|
1988
|
+
yield* encodeErrorResponse(replyCodec, error, decoded.envelope.method);
|
|
1989
|
+
return;
|
|
1990
|
+
}
|
|
1991
|
+
yield* replyCodec.encodeResponse(result.envelope, result.body, { method: decoded.envelope.method });
|
|
1992
|
+
};
|
|
1993
|
+
}
|
|
1994
|
+
/**
|
|
1995
|
+
* The one place that knows a runtime may not implement request body streams,
|
|
1996
|
+
* and the buffering both fallbacks need. `fetch.ts` and `http-stubs.ts` each
|
|
1997
|
+
* carry a client and a server direction that must agree on the answer, so the
|
|
1998
|
+
* predicate lives here rather than being written out four times.
|
|
1999
|
+
*/
|
|
2000
|
+
/**
|
|
2001
|
+
* Whether `Request.prototype` exposes a `body` accessor. Two call sites read
|
|
2002
|
+
* that property, and two more depend on the constructor accepting a
|
|
2003
|
+
* `ReadableStream` as `init.body`; this predicate answers for all four.
|
|
2004
|
+
*
|
|
2005
|
+
* What was verified, and all that is claimed here: Firefox (146 at the time of
|
|
2006
|
+
* writing) has *neither*, and Chromium and Node have *both*. On Firefox it is
|
|
2007
|
+
* not that `body` is `undefined` on the instance —
|
|
2008
|
+
* `Object.getOwnPropertyDescriptor(Request.prototype, "body")` is `null`, the
|
|
2009
|
+
* accessor is genuinely absent — and because a `ReadableStream` is then not a
|
|
2010
|
+
* recognised `BodyInit`, the constructor falls through to the string branch and
|
|
2011
|
+
* stores the literal text `[object ReadableStream]`.
|
|
2012
|
+
*
|
|
2013
|
+
* The two halves are NOT guaranteed to ship together, so do not read this as a
|
|
2014
|
+
* test for "request streams" in general. Safari is the counterexample: it has
|
|
2015
|
+
* had `Request.body` since 11.1 but only accepts a stream as `init.body` from
|
|
2016
|
+
* Technology Preview 250, so a shipping Safari has the reader half without the
|
|
2017
|
+
* upload half and this returns `true` there. That looks benign — WebKit appears
|
|
2018
|
+
* to store the stream on the `Request` rather than stringify it, and its error
|
|
2019
|
+
* comes from `fetch()`, which this package never calls on the objects it builds
|
|
2020
|
+
* — but it is untested, and it is the case to look at first if a Safari report
|
|
2021
|
+
* arrives. The sharper probe, if one is ever needed, is whether
|
|
2022
|
+
* `new Request(url, {method:"POST", body:new ReadableStream(), duplex:"half"})`
|
|
2023
|
+
* has a `content-type` of `text/plain;charset=UTF-8` (stringified) or `null`
|
|
2024
|
+
* (stored); it is not used here because it costs a `Request` and a
|
|
2025
|
+
* `ReadableStream` per call and agrees with the descriptor check on every
|
|
2026
|
+
* runtime measured.
|
|
2027
|
+
*
|
|
2028
|
+
* A capability check, never a user-agent test: the question is what this
|
|
2029
|
+
* runtime does, and the answer flips on its own the day Firefox ships request
|
|
2030
|
+
* streams. Evaluated per call rather than cached at module load so that a test
|
|
2031
|
+
* can install a `Request` without the capability and exercise the real branch
|
|
2032
|
+
* under Node.
|
|
2033
|
+
*/
|
|
2034
|
+
function supportsRequestStreams() {
|
|
2035
|
+
return typeof Request === "function" && Object.getOwnPropertyDescriptor(Request.prototype, "body") != null;
|
|
2036
|
+
}
|
|
2037
|
+
/**
|
|
2038
|
+
* Drain a body iterable into one contiguous buffer. Only the fallbacks need it.
|
|
2039
|
+
* Allocates its own buffer rather than reusing `bytes.ts`'s `concatChunks`,
|
|
2040
|
+
* which passes a single chunk straight through: that chunk is a view onto the
|
|
2041
|
+
* decoder's own read buffer, and the result here is handed to `new Request` and
|
|
2042
|
+
* outlives the decode. The allocation is also what makes it a
|
|
2043
|
+
* `Uint8Array<ArrayBuffer>`, which `BodyInit` accepts and the looser
|
|
2044
|
+
* `Uint8Array<ArrayBufferLike>` does not.
|
|
2045
|
+
*/
|
|
2046
|
+
async function collectBytes$1(source) {
|
|
2047
|
+
const parts = [];
|
|
2048
|
+
let total = 0;
|
|
2049
|
+
for await (const chunk of source) {
|
|
2050
|
+
if (chunk.byteLength === 0) continue;
|
|
2051
|
+
parts.push(chunk);
|
|
2052
|
+
total += chunk.byteLength;
|
|
2053
|
+
}
|
|
2054
|
+
const out = new Uint8Array(total);
|
|
2055
|
+
let offset = 0;
|
|
2056
|
+
for (const part of parts) {
|
|
2057
|
+
out.set(part, offset);
|
|
2058
|
+
offset += part.byteLength;
|
|
2059
|
+
}
|
|
2060
|
+
return out;
|
|
2061
|
+
}
|
|
2062
|
+
const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
|
|
2063
|
+
101,
|
|
2064
|
+
103,
|
|
2065
|
+
204,
|
|
2066
|
+
205,
|
|
2067
|
+
304
|
|
2068
|
+
]);
|
|
2069
|
+
const REQUEST_FIELDS = [
|
|
2070
|
+
"url",
|
|
2071
|
+
"method",
|
|
2072
|
+
"mode",
|
|
2073
|
+
"credentials",
|
|
2074
|
+
"cache",
|
|
2075
|
+
"redirect",
|
|
2076
|
+
"referrer",
|
|
2077
|
+
"referrerPolicy",
|
|
2078
|
+
"integrity",
|
|
2079
|
+
"keepalive"
|
|
2080
|
+
];
|
|
2081
|
+
/** `SerializedHttpEnvelope.content` is never absent, only empty. */
|
|
2082
|
+
async function* noBytes() {}
|
|
2083
|
+
async function* oneChunk(chunk) {
|
|
2084
|
+
yield chunk;
|
|
2085
|
+
}
|
|
2086
|
+
/**
|
|
2087
|
+
* Returns an HTTP handler that serializes a Request, hands the envelope to
|
|
2088
|
+
* `send` for transport, and deserializes the reply into a Response. Used on
|
|
2089
|
+
* the caller side.
|
|
2090
|
+
*/
|
|
387
2091
|
function newHttpClientStub(send) {
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
statusText: "Error 404: Not Found",
|
|
425
|
-
};
|
|
426
|
-
} else {
|
|
427
|
-
responseOptions = result.options;
|
|
428
|
-
const responseContent = result.content;
|
|
429
|
-
if (
|
|
430
|
-
requestOptions.method !== "HEAD" &&
|
|
431
|
-
requestOptions.method !== "OPTIONS"
|
|
432
|
-
) {
|
|
433
|
-
responseBody = toReadableStream(responseContent);
|
|
434
|
-
} else if (responseContent && responseContent.return) {
|
|
435
|
-
responseContent.return();
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
return new Response(responseBody, responseOptions);
|
|
439
|
-
};
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
/**
|
|
443
|
-
* This method returns the server-side call handler transforming
|
|
444
|
-
* serialized requests to HTTP Request instances, delegating
|
|
445
|
-
* their handing to the given `handler` method. This handler
|
|
446
|
-
* should handle the HTTP request and return a valid Response instance.
|
|
447
|
-
* The resulting instance is serialized as an object with the same
|
|
448
|
-
* structure as the initial serialized request:
|
|
449
|
-
* - `options` - contains serialized request or response parameters
|
|
450
|
-
* - `content` - an async iterator over binary blocks for
|
|
451
|
-
* the request or response
|
|
452
|
-
* @param {*} handler this handler method accepts standard HTTP Request
|
|
453
|
-
* and returns back an HTTP Response instance
|
|
454
|
-
* @returns a method deserializing HTTP requests and returning back
|
|
455
|
-
* serialized HTTP responses
|
|
456
|
-
*/
|
|
2092
|
+
return async (requestOrPromise) => {
|
|
2093
|
+
const request = await requestOrPromise;
|
|
2094
|
+
const headers = [...request.headers].map(([k, v]) => [k, v]);
|
|
2095
|
+
const options = {
|
|
2096
|
+
url: request.url,
|
|
2097
|
+
headers
|
|
2098
|
+
};
|
|
2099
|
+
for (const field of REQUEST_FIELDS) {
|
|
2100
|
+
const val = request[field];
|
|
2101
|
+
if (val !== void 0 && field !== "url") options[field] = val;
|
|
2102
|
+
}
|
|
2103
|
+
let content;
|
|
2104
|
+
if (request.body != null) content = fromReadableStream(request.body);
|
|
2105
|
+
else if (!supportsRequestStreams()) content = oneChunk(new Uint8Array(await request.arrayBuffer()));
|
|
2106
|
+
else content = noBytes();
|
|
2107
|
+
const result = await send({
|
|
2108
|
+
options,
|
|
2109
|
+
content
|
|
2110
|
+
});
|
|
2111
|
+
if (!result) return new Response(null, {
|
|
2112
|
+
status: 404,
|
|
2113
|
+
statusText: "Error 404: Not Found"
|
|
2114
|
+
});
|
|
2115
|
+
const responseOptions = result.options;
|
|
2116
|
+
const method = options.method;
|
|
2117
|
+
if (method === "HEAD" || method === "OPTIONS" || NULL_BODY_STATUSES.has(responseOptions.status)) {
|
|
2118
|
+
await discard(result.content);
|
|
2119
|
+
return new Response(null, responseOptions);
|
|
2120
|
+
}
|
|
2121
|
+
return new Response(toReadableStream(result.content[Symbol.asyncIterator]()), responseOptions);
|
|
2122
|
+
};
|
|
2123
|
+
}
|
|
2124
|
+
/**
|
|
2125
|
+
* Returns a server-side transport handler. It deserializes the incoming
|
|
2126
|
+
* request envelope, delegates to `handler`, and serializes the response.
|
|
2127
|
+
*/
|
|
457
2128
|
function newHttpServerStub(handler) {
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
2129
|
+
return async (envelopeOrPromise) => {
|
|
2130
|
+
const { options, content } = await envelopeOrPromise;
|
|
2131
|
+
const { url, method, headers = [], ...rest } = options;
|
|
2132
|
+
const { mode: _mode, ...forwardable } = rest;
|
|
2133
|
+
const requestHeaders = new Headers();
|
|
2134
|
+
for (const [key, value] of headers) requestHeaders.append(key, value);
|
|
2135
|
+
const hasBody = method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
|
|
2136
|
+
const requestInit = {
|
|
2137
|
+
...forwardable,
|
|
2138
|
+
method,
|
|
2139
|
+
headers: requestHeaders
|
|
2140
|
+
};
|
|
2141
|
+
if (!hasBody) await discard(content);
|
|
2142
|
+
else if (supportsRequestStreams()) {
|
|
2143
|
+
requestInit.body = toReadableStream(content[Symbol.asyncIterator]());
|
|
2144
|
+
requestInit.duplex = "half";
|
|
2145
|
+
} else requestInit.body = await collectBytes$1(content);
|
|
2146
|
+
const response = await handler(new Request(url, requestInit));
|
|
2147
|
+
return {
|
|
2148
|
+
options: {
|
|
2149
|
+
status: response.status,
|
|
2150
|
+
statusText: response.statusText,
|
|
2151
|
+
headers: Object.fromEntries([...response.headers])
|
|
2152
|
+
},
|
|
2153
|
+
content: response.body ? fromReadableStream(response.body) : (async function* () {})()
|
|
2154
|
+
};
|
|
2155
|
+
};
|
|
2156
|
+
}
|
|
2157
|
+
/**
|
|
2158
|
+
* Connection-scoped headers. The codec surfaces them verbatim (decision 12),
|
|
2159
|
+
* but they are meaningless to a `Request`/`Response`, and re-emitting them
|
|
2160
|
+
* from a relay would corrupt its framing.
|
|
2161
|
+
*/
|
|
2162
|
+
const HOP_BY_HOP = /* @__PURE__ */ new Set([
|
|
2163
|
+
"connection",
|
|
2164
|
+
"host",
|
|
2165
|
+
"keep-alive",
|
|
2166
|
+
"proxy-authenticate",
|
|
2167
|
+
"proxy-authorization",
|
|
2168
|
+
"te",
|
|
2169
|
+
"trailer",
|
|
2170
|
+
"transfer-encoding",
|
|
2171
|
+
"upgrade"
|
|
2172
|
+
]);
|
|
2173
|
+
function forwardableHeaders(headers) {
|
|
2174
|
+
return headers.filter(([name]) => !HOP_BY_HOP.has(name.toLowerCase()));
|
|
2175
|
+
}
|
|
2176
|
+
function headersToArray(headers) {
|
|
2177
|
+
const out = [];
|
|
2178
|
+
headers.forEach((value, key) => {
|
|
2179
|
+
out.push([key, value]);
|
|
2180
|
+
});
|
|
2181
|
+
return out;
|
|
2182
|
+
}
|
|
2183
|
+
async function* readableToAsyncIterable(stream) {
|
|
2184
|
+
if (!stream) return;
|
|
2185
|
+
const reader = stream.getReader();
|
|
2186
|
+
let consumed = false;
|
|
2187
|
+
try {
|
|
2188
|
+
while (true) {
|
|
2189
|
+
const { done, value } = await reader.read();
|
|
2190
|
+
if (done) {
|
|
2191
|
+
consumed = true;
|
|
2192
|
+
return;
|
|
2193
|
+
}
|
|
2194
|
+
if (value) yield value;
|
|
2195
|
+
}
|
|
2196
|
+
} finally {
|
|
2197
|
+
if (!consumed) try {
|
|
2198
|
+
await reader.cancel();
|
|
2199
|
+
} catch {}
|
|
2200
|
+
try {
|
|
2201
|
+
reader.releaseLock();
|
|
2202
|
+
} catch {}
|
|
2203
|
+
}
|
|
2204
|
+
}
|
|
2205
|
+
function asyncIterableToReadable(iter) {
|
|
2206
|
+
const it = iter[Symbol.asyncIterator]();
|
|
2207
|
+
return new ReadableStream({
|
|
2208
|
+
async pull(controller) {
|
|
2209
|
+
try {
|
|
2210
|
+
const { done, value } = await it.next();
|
|
2211
|
+
if (done) {
|
|
2212
|
+
controller.close();
|
|
2213
|
+
return;
|
|
2214
|
+
}
|
|
2215
|
+
controller.enqueue(value);
|
|
2216
|
+
} catch (err) {
|
|
2217
|
+
controller.error(err);
|
|
2218
|
+
}
|
|
2219
|
+
},
|
|
2220
|
+
async cancel() {
|
|
2221
|
+
await it.return?.();
|
|
2222
|
+
}
|
|
2223
|
+
});
|
|
2224
|
+
}
|
|
2225
|
+
/**
|
|
2226
|
+
* Run a `Request` through a `Duplex` call and reconstruct the `Response` on
|
|
2227
|
+
* the other side. The request's `signal` is plumbed into the body iteration —
|
|
2228
|
+
* abort terminates the underlying call.
|
|
2229
|
+
*/
|
|
2230
|
+
async function fetchOverDuplex(call, request, options = {}) {
|
|
2231
|
+
if (request.signal?.aborted) throw abortReason(request.signal);
|
|
2232
|
+
const env = {
|
|
2233
|
+
url: request.url,
|
|
2234
|
+
method: request.method,
|
|
2235
|
+
headers: headersToArray(request.headers)
|
|
2236
|
+
};
|
|
2237
|
+
let body;
|
|
2238
|
+
if (request.body != null) body = readableToAsyncIterable(request.body);
|
|
2239
|
+
else if (!supportsRequestStreams()) {
|
|
2240
|
+
const buffered = new Uint8Array(await request.arrayBuffer());
|
|
2241
|
+
if (buffered.byteLength > 0) body = [buffered];
|
|
2242
|
+
}
|
|
2243
|
+
const { envelope, body: respBody } = await httpFetch(call, env, body, options);
|
|
2244
|
+
const responseInit = {
|
|
2245
|
+
status: envelope.status,
|
|
2246
|
+
statusText: envelope.statusText,
|
|
2247
|
+
headers: forwardableHeaders(envelope.headers)
|
|
2248
|
+
};
|
|
2249
|
+
if (request.method === "HEAD" || request.method === "OPTIONS" || NULL_BODY_STATUSES.has(envelope.status)) {
|
|
2250
|
+
await respBody.return?.();
|
|
2251
|
+
return new Response(null, responseInit);
|
|
2252
|
+
}
|
|
2253
|
+
return new Response(asyncIterableToReadable(withAbort(respBody, request.signal)), responseInit);
|
|
2254
|
+
}
|
|
2255
|
+
/**
|
|
2256
|
+
* Wrap a `(Request) => Promise<Response>` handler as a `Duplex` so it can be
|
|
2257
|
+
* registered with any `webrun-streams-*` adapter's `serve`.
|
|
2258
|
+
*/
|
|
2259
|
+
function serveFetchOverDuplex(handler, options = {}) {
|
|
2260
|
+
return httpServe(async (env, body) => {
|
|
2261
|
+
const reqInit = {
|
|
2262
|
+
method: env.method,
|
|
2263
|
+
headers: forwardableHeaders(env.headers)
|
|
2264
|
+
};
|
|
2265
|
+
if (env.method !== "GET" && env.method !== "HEAD") {
|
|
2266
|
+
if (supportsRequestStreams()) {
|
|
2267
|
+
reqInit.body = asyncIterableToReadable(body);
|
|
2268
|
+
reqInit.duplex = "half";
|
|
2269
|
+
} else reqInit.body = await collectBytes$1(body);
|
|
2270
|
+
}
|
|
2271
|
+
const response = await handler(new Request(env.url, reqInit));
|
|
2272
|
+
const respEnv = {
|
|
2273
|
+
status: response.status,
|
|
2274
|
+
statusText: response.statusText,
|
|
2275
|
+
headers: headersToArray(response.headers)
|
|
2276
|
+
};
|
|
2277
|
+
if (env.method === "HEAD" || env.method === "OPTIONS" || NULL_BODY_STATUSES.has(response.status)) {
|
|
2278
|
+
await response.body?.cancel();
|
|
2279
|
+
return {
|
|
2280
|
+
envelope: respEnv,
|
|
2281
|
+
body: void 0
|
|
2282
|
+
};
|
|
2283
|
+
}
|
|
2284
|
+
return {
|
|
2285
|
+
envelope: respEnv,
|
|
2286
|
+
body: response.body ? readableToAsyncIterable(response.body) : void 0
|
|
2287
|
+
};
|
|
2288
|
+
}, options);
|
|
2289
|
+
}
|
|
2290
|
+
async function* withAbort(iter, signal) {
|
|
2291
|
+
if (!signal) {
|
|
2292
|
+
yield* iter;
|
|
2293
|
+
return;
|
|
2294
|
+
}
|
|
2295
|
+
for await (const chunk of iter) {
|
|
2296
|
+
if (signal.aborted) throw abortReason(signal);
|
|
2297
|
+
yield chunk;
|
|
2298
|
+
}
|
|
2299
|
+
}
|
|
2300
|
+
function abortReason(signal) {
|
|
2301
|
+
const reason = signal.reason;
|
|
2302
|
+
if (reason instanceof Error) return reason;
|
|
2303
|
+
const err = new Error(reason === void 0 ? "Aborted" : String(reason));
|
|
2304
|
+
err.name = "AbortError";
|
|
2305
|
+
return err;
|
|
2306
|
+
}
|
|
2307
|
+
/**
|
|
2308
|
+
* Host a `SiteHandler` over a `Connect/Serve` pair. The `start(serve, params)`
|
|
2309
|
+
* call hands the handler to any `webrun-streams-*` adapter's `serve`.
|
|
2310
|
+
*
|
|
2311
|
+
* ```ts
|
|
2312
|
+
* import { SiteBuilder } from "@statewalker/webrun-site-builder";
|
|
2313
|
+
* import { DuplexSiteBuilder } from "@statewalker/webrun-http-streams";
|
|
2314
|
+
* import { serve } from "@statewalker/webrun-rpc";
|
|
2315
|
+
*
|
|
2316
|
+
* const handler = new SiteBuilder()
|
|
2317
|
+
* .setEndpoint("/api/time", () => new Response(new Date().toISOString()))
|
|
2318
|
+
* .build();
|
|
2319
|
+
*
|
|
2320
|
+
* const stop = await new DuplexSiteBuilder().setHandler(handler).start(serve, { port });
|
|
2321
|
+
* // later: await stop();
|
|
2322
|
+
* ```
|
|
2323
|
+
*
|
|
2324
|
+
* Holds no site-configuration state. Endpoints, files, auth belong to the
|
|
2325
|
+
* `SiteHandler` producer (typically `SiteBuilder`).
|
|
2326
|
+
*/
|
|
2327
|
+
var DuplexSiteBuilder = class {
|
|
2328
|
+
#handler;
|
|
2329
|
+
#codec;
|
|
2330
|
+
setHandler(handler) {
|
|
2331
|
+
this.#handler = handler;
|
|
2332
|
+
return this;
|
|
2333
|
+
}
|
|
2334
|
+
/** Pin the wire format. Defaults to HTTP/1.1 with legacy acceptance. */
|
|
2335
|
+
setCodec(codec) {
|
|
2336
|
+
this.#codec = codec;
|
|
2337
|
+
return this;
|
|
2338
|
+
}
|
|
2339
|
+
async start(serve, params) {
|
|
2340
|
+
if (!this.#handler) throw new Error("DuplexSiteBuilder.start: setHandler(handler) must be called before start()");
|
|
2341
|
+
const handler = this.#handler;
|
|
2342
|
+
return serve(params, serveFetchOverDuplex(async (req) => handler(req), { codec: this.#codec }));
|
|
2343
|
+
}
|
|
2344
|
+
};
|
|
2345
|
+
var HttpError = class HttpError extends Error {
|
|
2346
|
+
status;
|
|
2347
|
+
statusText;
|
|
2348
|
+
constructor(options = {}) {
|
|
2349
|
+
super(options.message ?? options.statusText ?? "HTTP Error");
|
|
2350
|
+
this.status = options.status;
|
|
2351
|
+
this.statusText = options.statusText;
|
|
2352
|
+
}
|
|
2353
|
+
getResponseOptions(options = {}) {
|
|
2354
|
+
return {
|
|
2355
|
+
...this.toJson(),
|
|
2356
|
+
...options
|
|
2357
|
+
};
|
|
2358
|
+
}
|
|
2359
|
+
toJson() {
|
|
2360
|
+
return {
|
|
2361
|
+
status: this.status,
|
|
2362
|
+
statusText: this.statusText,
|
|
2363
|
+
message: this.message
|
|
2364
|
+
};
|
|
2365
|
+
}
|
|
2366
|
+
static fromError(error) {
|
|
2367
|
+
if (error instanceof HttpError) return error;
|
|
2368
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2369
|
+
return new HttpError({
|
|
2370
|
+
status: 500,
|
|
2371
|
+
statusText: "Bad Request",
|
|
2372
|
+
message
|
|
2373
|
+
});
|
|
2374
|
+
}
|
|
2375
|
+
static errorResourceNotFound(options = {}) {
|
|
2376
|
+
return new HttpError({
|
|
2377
|
+
status: 404,
|
|
2378
|
+
statusText: "Error 404: Resource not found",
|
|
2379
|
+
...options
|
|
2380
|
+
});
|
|
2381
|
+
}
|
|
2382
|
+
static errorForbidden(options = {}) {
|
|
2383
|
+
return new HttpError({
|
|
2384
|
+
status: 403,
|
|
2385
|
+
statusText: "Error 403: Forbidden",
|
|
2386
|
+
...options
|
|
2387
|
+
});
|
|
2388
|
+
}
|
|
2389
|
+
static errorResourceGone(options = {}) {
|
|
2390
|
+
return new HttpError({
|
|
2391
|
+
status: 410,
|
|
2392
|
+
statusText: "Error 410: Resource Gone",
|
|
2393
|
+
...options
|
|
2394
|
+
});
|
|
2395
|
+
}
|
|
2396
|
+
static errorInternalError(options = {}) {
|
|
2397
|
+
return new HttpError({
|
|
2398
|
+
...options,
|
|
2399
|
+
status: 500,
|
|
2400
|
+
statusText: "Error 500: Internal error"
|
|
2401
|
+
});
|
|
2402
|
+
}
|
|
2403
|
+
};
|
|
2404
|
+
//#endregion
|
|
2405
|
+
//#region src/http/http-send-recieve.ts
|
|
2406
|
+
async function* httpToIterator(envelopeOrPromise) {
|
|
2407
|
+
const { options, content } = await envelopeOrPromise;
|
|
2408
|
+
yield new TextEncoder().encode(JSON.stringify(options));
|
|
2409
|
+
yield* content;
|
|
2410
|
+
}
|
|
2411
|
+
async function httpFromIterator(iterable) {
|
|
2412
|
+
const it = (await iterable)[Symbol.asyncIterator]();
|
|
2413
|
+
const { done, value } = await it.next();
|
|
2414
|
+
let options = {};
|
|
2415
|
+
if (!done && value) {
|
|
2416
|
+
const str = new TextDecoder().decode(value);
|
|
2417
|
+
options = JSON.parse(str);
|
|
2418
|
+
}
|
|
2419
|
+
return {
|
|
2420
|
+
options,
|
|
2421
|
+
content: { [Symbol.asyncIterator]() {
|
|
2422
|
+
return it;
|
|
2423
|
+
} }
|
|
2424
|
+
};
|
|
2425
|
+
}
|
|
2426
|
+
/**
|
|
2427
|
+
* Serve an `HttpHandler` over a `MessageTarget`, using this package's own
|
|
2428
|
+
* `handleStreams` transport.
|
|
2429
|
+
*
|
|
2430
|
+
* @deprecated Prefer the port stack in `@statewalker/webrun-rpc`: open a port
|
|
2431
|
+
* (`multiplexPort` over one pipe, or `transferPortMux` where the platform can
|
|
2432
|
+
* transfer a real `MessagePort`), turn it into a `Duplex` with
|
|
2433
|
+
* `serveDuplexOverPort`, and serve HTTP on that with
|
|
2434
|
+
* `httpServe(handler, options)` from `@statewalker/webrun-http-streams`.
|
|
2435
|
+
*
|
|
2436
|
+
* That path has backpressure; **this one does not.** `sendStream`'s chunk
|
|
2437
|
+
* sender discards the promise it is given, so a fast producer over a slow
|
|
2438
|
+
* consumer accumulates without bound. It also has no per-stream timeout and no
|
|
2439
|
+
* chunking to a transport's message ceiling.
|
|
2440
|
+
*
|
|
2441
|
+
* Kept for existing ServiceWorker setups built on the `MessageTarget` surface.
|
|
2442
|
+
*/
|
|
523
2443
|
function handleHttpRequests(communicationPort, handler) {
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
2444
|
+
const serverStub = newHttpServerStub(handler);
|
|
2445
|
+
return handleStreams(communicationPort, async (it) => {
|
|
2446
|
+
const envelope = await httpFromIterator(it);
|
|
2447
|
+
return httpToIterator(await serverStub(envelope));
|
|
2448
|
+
});
|
|
528
2449
|
}
|
|
529
|
-
|
|
2450
|
+
/**
|
|
2451
|
+
* Ship a `Request` over a `MessageTarget` and await the `Response`, using this
|
|
2452
|
+
* package's own `sendStream` transport.
|
|
2453
|
+
*
|
|
2454
|
+
* @deprecated Prefer the port stack in `@statewalker/webrun-rpc`: open a port
|
|
2455
|
+
* (`multiplexPort` over one pipe, or `transferPortMux` where the platform can
|
|
2456
|
+
* transfer a real `MessagePort`), turn it into a `Duplex` with
|
|
2457
|
+
* `duplexOverPort`, and drive HTTP over it with `httpFetch` from
|
|
2458
|
+
* `@statewalker/webrun-http-streams`.
|
|
2459
|
+
*
|
|
2460
|
+
* Same caveat as {@link handleHttpRequests}: the transport underneath this
|
|
2461
|
+
* helper has no backpressure, no per-stream timeout, and no chunking to a
|
|
2462
|
+
* transport's message ceiling. Kept for existing ServiceWorker setups.
|
|
2463
|
+
*/
|
|
530
2464
|
async function sendHttpRequest(communicationPort, request) {
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
2465
|
+
return await newHttpClientStub(async (req) => {
|
|
2466
|
+
return await httpFromIterator(sendStream(communicationPort, httpToIterator(req)));
|
|
2467
|
+
})(request);
|
|
2468
|
+
}
|
|
2469
|
+
//#endregion
|
|
2470
|
+
//#region src/relay/split-service-url.ts
|
|
2471
|
+
/**
|
|
2472
|
+
* Splits a URL of the form `<base>/<separator><key>/<path>` into parts.
|
|
2473
|
+
* Example: `https://host/~FS/a/b` → `{ baseUrl: "https://host/~FS/", key: "FS", path: "a/b" }`.
|
|
2474
|
+
*/
|
|
539
2475
|
function splitServiceUrl(url, separator = "~") {
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
2476
|
+
const str = `${url}`;
|
|
2477
|
+
const idx = str.indexOf(separator);
|
|
2478
|
+
let baseUrl = "";
|
|
2479
|
+
let key = "";
|
|
2480
|
+
let path = "";
|
|
2481
|
+
if (idx >= 0) {
|
|
2482
|
+
baseUrl = str.substring(0, idx + separator.length);
|
|
2483
|
+
str.substring(idx + separator.length).replace(/^([^/]+)/, (match, $1) => {
|
|
2484
|
+
baseUrl += match;
|
|
2485
|
+
if (baseUrl.length < str.length) baseUrl += "/";
|
|
2486
|
+
key = $1;
|
|
2487
|
+
path = str.substring(baseUrl.length);
|
|
2488
|
+
return "";
|
|
2489
|
+
});
|
|
2490
|
+
}
|
|
2491
|
+
return {
|
|
2492
|
+
url: str,
|
|
2493
|
+
key,
|
|
2494
|
+
baseUrl,
|
|
2495
|
+
path
|
|
2496
|
+
};
|
|
2497
|
+
}
|
|
2498
|
+
//#endregion
|
|
2499
|
+
//#region src/relay/index.ts
|
|
2500
|
+
/**
|
|
2501
|
+
* Returns a MessagePort that transparently bridges messages to/from the
|
|
2502
|
+
* ServiceWorker controlling this page.
|
|
2503
|
+
*/
|
|
564
2504
|
function newServiceWorkerPort() {
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
const {
|
|
578
|
-
installing,
|
|
579
|
-
waiting,
|
|
580
|
-
active,
|
|
581
|
-
} = await navigator.serviceWorker.register(swUrl, {
|
|
582
|
-
// type: "module",
|
|
583
|
-
scope: scopeUrl,
|
|
584
|
-
});
|
|
585
|
-
(installing || waiting || active).addEventListener("statechange", (e) => {
|
|
586
|
-
console.log("state", e.target.state);
|
|
587
|
-
});
|
|
588
|
-
|
|
589
|
-
const serviceWorker = navigator.serviceWorker;
|
|
590
|
-
await new Promise((resolve) => {
|
|
591
|
-
// Resolve right away if this page is already controlled.
|
|
592
|
-
if (serviceWorker.controller) {
|
|
593
|
-
resolve();
|
|
594
|
-
} else {
|
|
595
|
-
const onChange = () => {
|
|
596
|
-
resolve();
|
|
597
|
-
serviceWorker.removeEventListener("controllerchange", onChange);
|
|
598
|
-
serviceWorker.oncontrollerchange = null;
|
|
599
|
-
};
|
|
600
|
-
serviceWorker.addEventListener("controllerchange", onChange);
|
|
601
|
-
serviceWorker.oncontrollerchange = onChange;
|
|
602
|
-
}
|
|
603
|
-
});
|
|
604
|
-
const worker = serviceWorker.controller;
|
|
605
|
-
const isActivated = () => worker.state === "activated";
|
|
606
|
-
return await new Promise(async (resolve) => {
|
|
607
|
-
if (isActivated()) resolve(worker);
|
|
608
|
-
else {
|
|
609
|
-
worker.onstatechange = () => {
|
|
610
|
-
if (!isActivated()) return;
|
|
611
|
-
worker.onstatechange = null;
|
|
612
|
-
resolve(worker);
|
|
613
|
-
};
|
|
614
|
-
}
|
|
615
|
-
});
|
|
616
|
-
}
|
|
617
|
-
|
|
2505
|
+
const channel = new MessageChannel();
|
|
2506
|
+
channel.port1.onmessage = (event) => {
|
|
2507
|
+
navigator.serviceWorker.controller?.postMessage(event.data, [...event.ports]);
|
|
2508
|
+
};
|
|
2509
|
+
navigator.serviceWorker.addEventListener("message", (event) => {
|
|
2510
|
+
channel.port1.postMessage(event.data, [...event.ports]);
|
|
2511
|
+
});
|
|
2512
|
+
return channel.port2;
|
|
2513
|
+
}
|
|
2514
|
+
/**
|
|
2515
|
+
* Registers a ServiceWorker and resolves once it's activated and controlling the page.
|
|
2516
|
+
*/
|
|
618
2517
|
async function initServiceWorker({ swUrl, scopeUrl, type }) {
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
...options
|
|
786
|
-
}) {
|
|
787
|
-
const channel = new MessageChannel();
|
|
788
|
-
const accepted = await callChannel(
|
|
789
|
-
communicationPort,
|
|
790
|
-
"CONNECT",
|
|
791
|
-
{ key, ...options },
|
|
792
|
-
channel.port2,
|
|
793
|
-
);
|
|
794
|
-
if (!accepted) {
|
|
795
|
-
channel.port1.close();
|
|
796
|
-
channel.port2.close();
|
|
797
|
-
return null;
|
|
798
|
-
}
|
|
799
|
-
return channel.port1;
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
async function registerConnectionsHandler({
|
|
803
|
-
key,
|
|
804
|
-
handler,
|
|
805
|
-
communicationPort,
|
|
806
|
-
}) {
|
|
807
|
-
const [register, cleanup] = newRegistry();
|
|
808
|
-
await callChannel(communicationPort, "REGISTER", { key });
|
|
809
|
-
register(() => callChannel(communicationPort, "UNREGISTER", { key }));
|
|
810
|
-
register(
|
|
811
|
-
handleChannelCalls(
|
|
812
|
-
communicationPort,
|
|
813
|
-
"CONNECT",
|
|
814
|
-
handler,
|
|
815
|
-
),
|
|
816
|
-
);
|
|
817
|
-
return cleanup;
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
export { callChannel, callHttpService, deserializeError, fromReadableStream, getRelayWindowMessageHandler, handleChannelCalls, handleHttpRequests, handleStreams, initHttpService, initServiceWorker, initServiceWorker1, initializeConnection, newHttpClientStub, newHttpServerStub, newInvokationChannel, newRegistry, newRemoteRelayChannel, newServiceWorkerPort, recieveData, registerConnectionsHandler, sendData, sendHttpRequest, sendStream, serializeError, splitServiceUrl, toReadableStream };
|
|
2518
|
+
await navigator.serviceWorker.register(swUrl, {
|
|
2519
|
+
type,
|
|
2520
|
+
scope: scopeUrl
|
|
2521
|
+
});
|
|
2522
|
+
const worker = await getServiceWorkerController();
|
|
2523
|
+
await awaitServiceWorkerActivation(worker);
|
|
2524
|
+
return worker;
|
|
2525
|
+
}
|
|
2526
|
+
function getServiceWorkerController() {
|
|
2527
|
+
return new Promise((resolve) => {
|
|
2528
|
+
const container = navigator.serviceWorker;
|
|
2529
|
+
if (container.controller) {
|
|
2530
|
+
resolve(container.controller);
|
|
2531
|
+
return;
|
|
2532
|
+
}
|
|
2533
|
+
const onChange = () => {
|
|
2534
|
+
if (!container.controller) return;
|
|
2535
|
+
resolve(container.controller);
|
|
2536
|
+
container.removeEventListener("controllerchange", onChange);
|
|
2537
|
+
};
|
|
2538
|
+
container.addEventListener("controllerchange", onChange);
|
|
2539
|
+
});
|
|
2540
|
+
}
|
|
2541
|
+
function awaitServiceWorkerActivation(worker) {
|
|
2542
|
+
return new Promise((resolve) => {
|
|
2543
|
+
if (worker.state === "activated") {
|
|
2544
|
+
resolve();
|
|
2545
|
+
return;
|
|
2546
|
+
}
|
|
2547
|
+
const onStateChange = () => {
|
|
2548
|
+
if (worker.state !== "activated") return;
|
|
2549
|
+
worker.removeEventListener("statechange", onStateChange);
|
|
2550
|
+
resolve();
|
|
2551
|
+
};
|
|
2552
|
+
worker.addEventListener("statechange", onStateChange);
|
|
2553
|
+
});
|
|
2554
|
+
}
|
|
2555
|
+
/**
|
|
2556
|
+
* Registers `handler` as the server for the given service `key` on the relay.
|
|
2557
|
+
* Returns a cleanup function that unregisters the service.
|
|
2558
|
+
*/
|
|
2559
|
+
async function initHttpService(handler, { key, port }) {
|
|
2560
|
+
return await registerConnectionsHandler({
|
|
2561
|
+
key,
|
|
2562
|
+
communicationPort: port,
|
|
2563
|
+
handler: async (_event, _data, callPort) => {
|
|
2564
|
+
handleHttpRequests(callPort, handler);
|
|
2565
|
+
return true;
|
|
2566
|
+
}
|
|
2567
|
+
});
|
|
2568
|
+
}
|
|
2569
|
+
/**
|
|
2570
|
+
* Sends a `Request` to the service registered under `key` on the relay and
|
|
2571
|
+
* resolves with the corresponding `Response`.
|
|
2572
|
+
*/
|
|
2573
|
+
async function callHttpService(request, { key, port }) {
|
|
2574
|
+
const callPort = await initializeConnection({
|
|
2575
|
+
key,
|
|
2576
|
+
communicationPort: port
|
|
2577
|
+
});
|
|
2578
|
+
if (!callPort) throw new Error(`No service with key "${key}"`);
|
|
2579
|
+
return await sendHttpRequest(callPort, request);
|
|
2580
|
+
}
|
|
2581
|
+
/**
|
|
2582
|
+
* Returns a `window.onmessage` handler for use inside the relay iframe:
|
|
2583
|
+
* it accepts a CONNECT message, starts the relay ServiceWorker, and bridges
|
|
2584
|
+
* the parent's MessagePort with the SW.
|
|
2585
|
+
*/
|
|
2586
|
+
function getRelayWindowMessageHandler({ swUrl = `${new URL("./index-sw.js", import.meta.url)}`, scopeUrl = `${new URL("../", import.meta.url)}` } = {}) {
|
|
2587
|
+
let externalPort;
|
|
2588
|
+
return async (ev) => {
|
|
2589
|
+
if (ev.data?.type !== "CONNECT") return;
|
|
2590
|
+
const newExternalPort = ev.ports?.[0];
|
|
2591
|
+
if (!newExternalPort) return;
|
|
2592
|
+
if (externalPort) {
|
|
2593
|
+
newExternalPort.close();
|
|
2594
|
+
return;
|
|
2595
|
+
}
|
|
2596
|
+
externalPort = newExternalPort;
|
|
2597
|
+
await initServiceWorker({
|
|
2598
|
+
swUrl,
|
|
2599
|
+
scopeUrl
|
|
2600
|
+
});
|
|
2601
|
+
const serviceWorkerPort = newServiceWorkerPort();
|
|
2602
|
+
serviceWorkerPort.onmessage = (event) => {
|
|
2603
|
+
externalPort?.postMessage(event.data, [...event.ports]);
|
|
2604
|
+
};
|
|
2605
|
+
externalPort.onmessage = (event) => {
|
|
2606
|
+
serviceWorkerPort.postMessage(event.data, [...event.ports]);
|
|
2607
|
+
};
|
|
2608
|
+
};
|
|
2609
|
+
}
|
|
2610
|
+
/**
|
|
2611
|
+
* Embeds a hidden relay iframe, establishes a MessageChannel with it, and
|
|
2612
|
+
* returns the port to be used with `initHttpService` / `callHttpService`.
|
|
2613
|
+
*/
|
|
2614
|
+
async function newRemoteRelayChannel({ baseUrl = new URL("../public-relay/", import.meta.url), url = new URL("relay.html", baseUrl), container = document.body } = {}) {
|
|
2615
|
+
const messageChannel = new MessageChannel();
|
|
2616
|
+
const { iframe, promise } = newIFrame(url);
|
|
2617
|
+
Object.assign(iframe.style, {
|
|
2618
|
+
position: "fixed",
|
|
2619
|
+
width: "1px",
|
|
2620
|
+
height: "1px",
|
|
2621
|
+
top: "-1000px",
|
|
2622
|
+
left: "-1000px",
|
|
2623
|
+
display: "block",
|
|
2624
|
+
opacity: "0",
|
|
2625
|
+
border: "none",
|
|
2626
|
+
outline: "none"
|
|
2627
|
+
});
|
|
2628
|
+
container.appendChild(iframe);
|
|
2629
|
+
promise.then(() => {
|
|
2630
|
+
iframe.contentWindow?.postMessage({ type: "CONNECT" }, "*", [messageChannel.port1]);
|
|
2631
|
+
});
|
|
2632
|
+
return {
|
|
2633
|
+
baseUrl,
|
|
2634
|
+
port: messageChannel.port2,
|
|
2635
|
+
close: () => {
|
|
2636
|
+
iframe.parentElement?.removeChild(iframe);
|
|
2637
|
+
messageChannel.port1.close();
|
|
2638
|
+
messageChannel.port2.close();
|
|
2639
|
+
}
|
|
2640
|
+
};
|
|
2641
|
+
function newIFrame(src) {
|
|
2642
|
+
const iframe = document.createElement("iframe");
|
|
2643
|
+
iframe.src = `${src}`;
|
|
2644
|
+
Object.assign(iframe.style, {
|
|
2645
|
+
padding: "0",
|
|
2646
|
+
margin: "0",
|
|
2647
|
+
border: "none",
|
|
2648
|
+
outline: "none",
|
|
2649
|
+
width: "100%",
|
|
2650
|
+
height: "100%"
|
|
2651
|
+
});
|
|
2652
|
+
return {
|
|
2653
|
+
iframe,
|
|
2654
|
+
promise: new Promise((resolve, reject) => {
|
|
2655
|
+
iframe.onerror = () => reject(/* @__PURE__ */ new Error(`Failed to load ${src}`));
|
|
2656
|
+
iframe.onload = () => resolve(iframe);
|
|
2657
|
+
})
|
|
2658
|
+
};
|
|
2659
|
+
}
|
|
2660
|
+
}
|
|
2661
|
+
async function initializeConnection({ key, communicationPort, ...options }) {
|
|
2662
|
+
const channel = new MessageChannel();
|
|
2663
|
+
if (!await callChannel(communicationPort, "CONNECT", {
|
|
2664
|
+
key,
|
|
2665
|
+
...options
|
|
2666
|
+
}, channel.port2)) {
|
|
2667
|
+
channel.port1.close();
|
|
2668
|
+
channel.port2.close();
|
|
2669
|
+
return null;
|
|
2670
|
+
}
|
|
2671
|
+
return channel.port1;
|
|
2672
|
+
}
|
|
2673
|
+
async function registerConnectionsHandler({ key, handler, communicationPort }) {
|
|
2674
|
+
const [register, cleanup] = newRegistry();
|
|
2675
|
+
await callChannel(communicationPort, "REGISTER", { key });
|
|
2676
|
+
register(() => callChannel(communicationPort, "UNREGISTER", { key }));
|
|
2677
|
+
register(handleChannelCalls(communicationPort, "CONNECT", async (event, data, port) => {
|
|
2678
|
+
return await handler(event, data, port);
|
|
2679
|
+
}));
|
|
2680
|
+
return cleanup;
|
|
2681
|
+
}
|
|
2682
|
+
//#endregion
|
|
2683
|
+
export { DuplexSiteBuilder, HttpError, HttpParseError, PEER_ERROR_HEADER, TransportClosedError, callChannel, callHttpService, collect, collectBytes, collectString, decodeJsonl, decodeMessage, decodeText, defaultCodec, deserializeError, emulateMux, encodeJsonl, encodeMessage, encodeText, fetchOverDuplex, fromReadableStream, getRelayWindowMessageHandler, handleChannelCalls, handleHttpRequests, handleStreams, httpCodec, httpFetch, httpServe, initHttpService, initServiceWorker, initializeConnection, joinLines, jsonEnvelopeCodec, map, newAsyncGenerator, newCreditGrantor, newCreditLedger, newHttpClientStub, newHttpCodec, newHttpServerStub, newInvokationChannel, newRegistry, newRemoteRelayChannel, newServiceWorkerPort, newSniffingCodec, normalizeToUint8Array, recieveIterator, registerConnectionsHandler, sendHttpRequest, sendIterator, sendStream, serializeError, serveFetchOverDuplex, splitLines, splitServiceUrl, toChunks, toReadableStream };
|