sepal 0.2.0-alpha.0 → 0.3.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +14 -5
  2. package/cli.js +127 -10
  3. package/package.json +48 -4
  4. package/src/abort.js +129 -0
  5. package/src/app.js +13 -0
  6. package/src/dom.js +173 -60
  7. package/src/fetch.js +347 -80
  8. package/src/form-data.js +141 -0
  9. package/src/host-call.js +57 -0
  10. package/src/index.js +9 -11
  11. package/src/lru.js +45 -0
  12. package/src/native.js +32 -0
  13. package/src/notifications.js +60 -0
  14. package/src/os.js +35 -0
  15. package/src/process.js +164 -0
  16. package/src/protocol.js +3 -4
  17. package/src/renderer.js +140 -10
  18. package/src/secrets.js +42 -0
  19. package/src/settings.js +52 -0
  20. package/src/shims.js +30 -8
  21. package/src/stem.js +125 -0
  22. package/src/updater.js +3 -2
  23. package/src/url.js +65 -20
  24. package/src/web.js +86 -0
  25. package/src/window.js +6 -2
  26. package/types/abort.d.ts +46 -0
  27. package/types/app.d.ts +7 -0
  28. package/types/fetch.d.ts +118 -28
  29. package/types/form-data.d.ts +19 -0
  30. package/types/host-call.d.ts +18 -0
  31. package/types/index.d.ts +5 -2
  32. package/types/lru.d.ts +18 -0
  33. package/types/native.d.ts +22 -0
  34. package/types/notifications.d.ts +53 -0
  35. package/types/os.d.ts +53 -0
  36. package/types/process.d.ts +90 -0
  37. package/types/protocol.d.ts +0 -2
  38. package/types/renderer.d.ts +16 -1
  39. package/types/secrets.d.ts +22 -0
  40. package/types/settings.d.ts +29 -0
  41. package/types/shims.d.ts +1 -0
  42. package/types/stem.d.ts +21 -0
  43. package/types/updater.d.ts +6 -4
  44. package/types/url.d.ts +1 -1
  45. package/types/vite/adapter.d.ts +22 -0
  46. package/types/vite/add.d.ts +77 -0
  47. package/types/vite/app.d.ts +52 -1
  48. package/types/vite/licenses.d.ts +11 -0
  49. package/types/vite/native.d.ts +135 -0
  50. package/types/vite/page.d.ts +20 -0
  51. package/types/vite/permissions.d.ts +56 -0
  52. package/types/vite/sveltekit.d.ts +5 -42
  53. package/types/vite/vite.d.ts +86 -29
  54. package/types/web.d.ts +17 -0
  55. package/types/window.d.ts +5 -1
  56. package/vite/adapter.js +118 -0
  57. package/vite/add.js +254 -0
  58. package/vite/app.js +195 -27
  59. package/vite/head.js +2 -2
  60. package/vite/licenses.js +115 -0
  61. package/vite/native.js +535 -0
  62. package/vite/page.js +95 -0
  63. package/vite/permissions.d.ts +56 -0
  64. package/vite/sveltekit.js +11 -263
  65. package/vite/vite.js +378 -109
package/src/fetch.js CHANGED
@@ -1,20 +1,34 @@
1
1
  // `fetch`, and the Fetch API classes around it (`Request`, `Headers`,
2
- // `Response`), installed as globals when the engine has none.
2
+ // `Response`), installed as globals by `web.js` when the engine has none.
3
3
  //
4
4
  // The host makes the request, and only to URLs the app's `permissions.http`
5
- // allows. This is the everyday part of the Fetch API: method, headers, a
6
- // string or byte body, and `text()`, `json()`, `arrayBuffer()`, `bytes()` on
7
- // the response. There is no streaming, no `AbortSignal` and no `FormData`.
8
- // The classes are there because libraries test for them and build them:
9
- // SvelteKit's client asks `input instanceof Request` on every fetch.
5
+ // allows. `fetch` resolves once the status and headers are in, and the body
6
+ // stays with the host until it is read: all at once (`text()`, `bytes()`,
7
+ // `json()`, ...) or a chunk at a time as it arrives (`response.body`, a
8
+ // `ReadableStream`). A body can be a string, bytes, a `Blob`, `FormData`,
9
+ // `URLSearchParams` or a `ReadableStream`; `AbortSignal` stops a request and
10
+ // its body. SvelteKit's client asks `input instanceof Request` on every
11
+ // fetch, and its server builds and reads these classes.
10
12
 
11
- import { host_call } from './host-call.js';
13
+ import { Blob, FormData } from 'formdata-node';
14
+ import { ReadableStream } from 'web-streams-polyfill';
15
+ import { AbortController, abort_error } from './abort.js';
12
16
  import { decode, encode, to_bytes } from './base64.js';
17
+ import { concat, encode_multipart, make_boundary, parse_form } from './form-data.js';
18
+ import { host_call } from './host-call.js';
19
+ import { TextDecoder, TextEncoder } from './text.js';
20
+ import { URLSearchParams } from './url.js';
21
+
22
+ /** @typedef {import('./abort.js').AbortSignal} AbortSignal */
23
+
24
+ const encoder = new TextEncoder();
13
25
 
14
26
  /** Headers: names are case-insensitive and kept in lower case, as in the Fetch API. */
15
27
  export class Headers {
16
28
  /** @type {Map<string, string>} */
17
29
  #map = new Map();
30
+ /** `Set-Cookie` lines, which are never joined: one cookie each. @type {string[]} */
31
+ #cookies = [];
18
32
 
19
33
  /** @param {unknown} [init] a plain object, a list of pairs, or another `Headers` */
20
34
  constructor(init) {
@@ -23,136 +37,379 @@ export class Headers {
23
37
  /** @param {string} name @param {string} value */
24
38
  append(name, value) {
25
39
  const key = name.toLowerCase();
40
+ if (key === 'set-cookie') {
41
+ this.#cookies.push(String(value));
42
+ return;
43
+ }
26
44
  const earlier = this.#map.get(key);
27
45
  this.#map.set(key, earlier === undefined ? String(value) : `${earlier}, ${value}`);
28
46
  }
29
47
  /** @param {string} name @param {string} value */
30
48
  set(name, value) {
31
- this.#map.set(name.toLowerCase(), String(value));
49
+ const key = name.toLowerCase();
50
+ if (key === 'set-cookie') this.#cookies = [String(value)];
51
+ else this.#map.set(key, String(value));
32
52
  }
33
53
  /** @param {string} name */
34
54
  get(name) {
35
- return this.#map.get(name.toLowerCase()) ?? null;
55
+ const key = name.toLowerCase();
56
+ if (key === 'set-cookie') return this.#cookies.length > 0 ? this.#cookies.join(', ') : null;
57
+ return this.#map.get(key) ?? null;
58
+ }
59
+ /** Each `Set-Cookie` line, as the Fetch API keeps them. */
60
+ getSetCookie() {
61
+ return [...this.#cookies];
36
62
  }
37
63
  /** @param {string} name */
38
64
  has(name) {
39
- return this.#map.has(name.toLowerCase());
65
+ const key = name.toLowerCase();
66
+ return key === 'set-cookie' ? this.#cookies.length > 0 : this.#map.has(key);
40
67
  }
41
68
  /** @param {string} name */
42
69
  delete(name) {
43
- this.#map.delete(name.toLowerCase());
70
+ const key = name.toLowerCase();
71
+ if (key === 'set-cookie') this.#cookies = [];
72
+ else this.#map.delete(key);
44
73
  }
45
74
  /** @param {(value: string, name: string, headers: Headers) => void} callback */
46
75
  forEach(callback) {
47
- this.#map.forEach((value, name) => callback(value, name, this));
76
+ for (const [name, value] of this) callback(value, name, this);
48
77
  }
49
- entries() {
50
- return this.#map.entries();
78
+ /** In name order, with each `Set-Cookie` line on its own, as the Fetch API iterates. */
79
+ *entries() {
80
+ /** @type {[string, string][]} */
81
+ const pairs = [...this.#map];
82
+ for (const cookie of this.#cookies) pairs.push(['set-cookie', cookie]);
83
+ pairs.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
84
+ yield* pairs;
51
85
  }
52
- keys() {
53
- return this.#map.keys();
86
+ *keys() {
87
+ for (const [name] of this.entries()) yield name;
54
88
  }
55
- values() {
56
- return this.#map.values();
89
+ *values() {
90
+ for (const [, value] of this.entries()) yield value;
57
91
  }
58
92
  [Symbol.iterator]() {
59
- return this.#map.entries();
93
+ return this.entries();
94
+ }
95
+ }
96
+
97
+ /**
98
+ * What a body was made from, and how it is read.
99
+ * @typedef {{ text: string } | { bytes: Uint8Array } | { blob: Blob } | { form: FormData, boundary: string } | { stream: ReadableStream<Uint8Array> } | { host: number }} Source
100
+ */
101
+
102
+ /**
103
+ * A body as given to `new Request` or `new Response`, and the content type it
104
+ * implies.
105
+ * @param {unknown} body
106
+ * @returns {{ source: Source | null, type: string | null }}
107
+ */
108
+ function extract(body) {
109
+ if (body == null) return { source: null, type: null };
110
+ if (typeof body === 'string') return { source: { text: body }, type: 'text/plain;charset=UTF-8' };
111
+ if (body instanceof URLSearchParams) {
112
+ return { source: { text: body.toString() }, type: 'application/x-www-form-urlencoded;charset=UTF-8' };
113
+ }
114
+ if (body instanceof FormData) {
115
+ const boundary = make_boundary();
116
+ return { source: { form: body, boundary }, type: `multipart/form-data; boundary=${boundary}` };
117
+ }
118
+ if (body instanceof Blob) return { source: { blob: body }, type: body.type || null };
119
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return { source: { bytes: to_bytes(body).slice() }, type: null };
120
+ if (body instanceof ReadableStream) return { source: { stream: body }, type: null };
121
+ return { source: { text: String(body) }, type: 'text/plain;charset=UTF-8' };
122
+ }
123
+
124
+ /** @param {ReadableStream<Uint8Array>} stream */
125
+ async function read_stream(stream) {
126
+ const reader = stream.getReader();
127
+ /** @type {Uint8Array[]} */
128
+ const chunks = [];
129
+ for (;;) {
130
+ const { done, value } = await reader.read();
131
+ if (done) break;
132
+ chunks.push(typeof value === 'string' ? encoder.encode(value) : to_bytes(value));
133
+ }
134
+ return concat(chunks);
135
+ }
136
+
137
+ /** A body source, all of it, as bytes. @param {Source} source @returns {Promise<Uint8Array>} */
138
+ async function source_bytes(source) {
139
+ if ('text' in source) return encoder.encode(source.text);
140
+ if ('bytes' in source) return source.bytes;
141
+ if ('blob' in source) return new Uint8Array(await source.blob.arrayBuffer());
142
+ if ('form' in source) return encode_multipart(source.form, source.boundary);
143
+ if ('stream' in source) return read_stream(source.stream);
144
+ return decode(await host_call('http.body', { id: source.host, as: 'base64' }));
145
+ }
146
+
147
+ /** A body source as a stream. @param {Source} source @param {AbortSignal | null} [signal] @returns {ReadableStream<Uint8Array>} */
148
+ function source_stream(source, signal) {
149
+ if ('stream' in source) return source.stream;
150
+ if ('host' in source) return host_stream(source.host, signal ?? null);
151
+ return new ReadableStream({
152
+ async start(controller) {
153
+ const bytes = await source_bytes(source);
154
+ if (bytes.length > 0) controller.enqueue(bytes);
155
+ controller.close();
156
+ }
157
+ });
158
+ }
159
+
160
+ /** A response body the host still has, read a chunk at a time as it arrives. @param {number} id @param {AbortSignal | null} signal */
161
+ function host_stream(id, signal) {
162
+ let cancelled = false;
163
+ return new ReadableStream({
164
+ /** @param {import('web-streams-polyfill').ReadableStreamDefaultController<Uint8Array>} controller */
165
+ async pull(controller) {
166
+ if (signal?.aborted) {
167
+ controller.error(signal.reason);
168
+ return;
169
+ }
170
+ const { chunk, done } = await host_call('http.read', { id });
171
+ if (cancelled) return;
172
+ if (signal?.aborted) controller.error(signal.reason);
173
+ else if (done) controller.close();
174
+ else controller.enqueue(decode(chunk));
175
+ },
176
+ // The host lets go of the body, and a server still making it stops
177
+ // (a stream from the app's server code), even while a read waits.
178
+ cancel() {
179
+ cancelled = true;
180
+ return host_call('http.cancel', { id }).then(
181
+ () => {},
182
+ () => {}
183
+ );
184
+ }
185
+ });
186
+ }
187
+
188
+ /** What `Request` and `Response` share: a body, read once. */
189
+ class Body {
190
+ /** @type {Source | null} */
191
+ #source;
192
+ /** @type {ReadableStream<Uint8Array> | null} */
193
+ #stream = null;
194
+ #used = false;
195
+
196
+ /** @param {Source | null} source */
197
+ constructor(source) {
198
+ this.#source = source;
199
+ }
200
+
201
+ /** What this body belongs to, for messages. */
202
+ get kind() {
203
+ return 'response';
204
+ }
205
+
206
+ /** For `clone()`: the source, turned into a stream that can be split. @returns {Source | null} */
207
+ split_source() {
208
+ if (this.#source === null) return null;
209
+ if (this.#used) throw new TypeError(`the ${this.kind} body was already read`);
210
+ const [mine, theirs] = this.body_stream().tee();
211
+ this.#stream = mine;
212
+ this.#source = { stream: mine };
213
+ return { stream: theirs };
214
+ }
215
+
216
+ /** @returns {AbortSignal | null} */
217
+ body_signal() {
218
+ return null;
219
+ }
220
+
221
+ /** @returns {ReadableStream<Uint8Array>} */
222
+ body_stream() {
223
+ if (this.#stream === null) this.#stream = source_stream(/** @type {Source} */ (this.#source), this.body_signal());
224
+ return this.#stream;
225
+ }
226
+
227
+ /** Whether there is a body, without making its stream. */
228
+ has_body() {
229
+ return this.#source !== null;
230
+ }
231
+
232
+ /** The body as a stream, or `null` for none. */
233
+ get body() {
234
+ if (this.#source === null) return null;
235
+ return this.body_stream();
236
+ }
237
+
238
+ /** Read, or its stream taken to be read. */
239
+ get bodyUsed() {
240
+ return this.#used || (this.#stream?.locked ?? false);
241
+ }
242
+
243
+ /** The source, once: reading a body uses it up. @returns {Source | null} */
244
+ take() {
245
+ if (this.#used) throw new TypeError(`the ${this.kind} body was already read`);
246
+ this.#used = true;
247
+ if (this.#stream !== null) return { stream: this.#stream };
248
+ return this.#source;
249
+ }
250
+
251
+ /** @returns {string | null} */
252
+ content_type() {
253
+ return null;
254
+ }
255
+
256
+ /** The body for the host: text as it is, anything else as base64. @returns {Promise<{ body: string } | { body_base64: string }>} */
257
+ async for_host() {
258
+ const source = this.take();
259
+ if (source !== null && 'text' in source) return { body: source.text };
260
+ return { body_base64: encode(source === null ? new Uint8Array(0) : await source_bytes(source)) };
261
+ }
262
+
263
+ /** @returns {Promise<Uint8Array>} */
264
+ async bytes() {
265
+ const source = this.take();
266
+ return source === null ? new Uint8Array(0) : source_bytes(source);
267
+ }
268
+ async arrayBuffer() {
269
+ const bytes = await this.bytes();
270
+ return /** @type {ArrayBuffer} */ (bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
271
+ }
272
+ /** @returns {Promise<string>} */
273
+ async text() {
274
+ const source = this.take();
275
+ if (source === null) return '';
276
+ if ('text' in source) return source.text;
277
+ if ('host' in source) return host_call('http.body', { id: source.host, as: 'text' });
278
+ return new TextDecoder().decode(await source_bytes(source));
279
+ }
280
+ async json() {
281
+ return JSON.parse(await this.text());
282
+ }
283
+ async blob() {
284
+ return new Blob([await this.bytes()], { type: this.content_type() ?? '' });
285
+ }
286
+ async formData() {
287
+ const source = this.take();
288
+ if (source !== null && 'form' in source) return source.form;
289
+ return parse_form(source === null ? new Uint8Array(0) : await source_bytes(source), this.content_type());
60
290
  }
61
291
  }
62
292
 
63
293
  const METHODS = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'PATCH'];
64
294
 
65
295
  /** A request to make: what `fetch` takes, as a string, a URL or one of these. */
66
- export class Request {
296
+ export class Request extends Body {
67
297
  /**
68
298
  * @param {string | Request | { url?: string, href?: string }} input
69
- * @param {{ method?: string, headers?: unknown, body?: string | ArrayBuffer | ArrayBufferView | null }} [init]
299
+ * @param {{ method?: string, headers?: unknown, body?: unknown, signal?: AbortSignal | null, credentials?: string, mode?: string, cache?: string, redirect?: string, referrer?: string, integrity?: string, keepalive?: boolean, duplex?: string }} [init]
70
300
  */
71
301
  constructor(input, init = {}) {
72
302
  /** @type {Request | null} */
73
303
  const from = input instanceof Request ? input : null;
304
+ const given = init.body !== undefined ? extract(init.body) : null;
305
+ super(given ? given.source : from ? from.split_source() : null);
74
306
  const target = /** @type {any} */ (input);
75
307
  /** @type {string} */
76
308
  this.url = from ? from.url : typeof input === 'string' ? input : String(target?.url ?? target?.href ?? input);
77
- /** @type {string} */
78
309
  const method = init.method ?? from?.method ?? 'GET';
79
310
  // As the Fetch API does: the standard methods in upper case, any other as written.
80
311
  /** @type {string} */
81
312
  this.method = METHODS.includes(method.toUpperCase()) ? method.toUpperCase() : method;
82
313
  /** @type {Headers} */
83
314
  this.headers = new Headers(init.headers ?? from?.headers);
84
- /** @type {string | ArrayBuffer | ArrayBufferView | null} */
85
- this.body = init.body ?? from?.body ?? null;
315
+ if (given?.type && !this.headers.has('content-type')) this.headers.set('content-type', given.type);
316
+ /** @type {AbortSignal} */
317
+ this.signal = init.signal ?? from?.signal ?? new AbortController().signal;
318
+ /** @type {string} */
319
+ this.credentials = init.credentials ?? from?.credentials ?? 'same-origin';
320
+ /** @type {string} */
321
+ this.mode = init.mode ?? from?.mode ?? 'cors';
322
+ /** @type {string} */
323
+ this.cache = init.cache ?? from?.cache ?? 'default';
324
+ /** @type {string} */
325
+ this.redirect = init.redirect ?? from?.redirect ?? 'follow';
326
+ /** @type {string} */
327
+ this.referrer = init.referrer ?? from?.referrer ?? 'about:client';
328
+ this.referrerPolicy = '';
329
+ /** @type {string} */
330
+ this.integrity = init.integrity ?? from?.integrity ?? '';
331
+ /** @type {boolean} */
332
+ this.keepalive = init.keepalive ?? from?.keepalive ?? false;
333
+ this.destination = '';
334
+ this.duplex = init.duplex ?? 'half';
335
+ }
336
+ content_type() {
337
+ return this.headers.get('content-type');
338
+ }
339
+ get kind() {
340
+ return 'request';
341
+ }
342
+ clone() {
343
+ return new Request(this);
86
344
  }
87
345
  }
88
346
 
89
- /** A response with its body in hand: what `new Response(body, init)` makes. `fetch` answers with a subclass. */
90
- export class Response {
347
+ /** A response with its body: what `new Response(body, init)` makes. `fetch` answers with a subclass. */
348
+ export class Response extends Body {
91
349
  /**
92
- * @param {string | ArrayBuffer | ArrayBufferView | null} [body]
350
+ * @param {unknown} [body]
93
351
  * @param {{ status?: number, statusText?: string, headers?: unknown }} [init]
352
+ * @param {Source | null} [source] for `clone()` and `fetch`: the body as it is already held
94
353
  */
95
- constructor(body = null, init = {}) {
354
+ constructor(body = null, init = {}, source) {
355
+ const given = source === undefined ? extract(body) : { source, type: null };
356
+ super(given.source);
96
357
  this.status = init.status ?? 200;
358
+ if (this.status !== 0 && (this.status < 200 || this.status > 599)) {
359
+ throw new RangeError(`Response: ${this.status} is not a status between 200 and 599`);
360
+ }
97
361
  this.statusText = init.statusText ?? '';
98
362
  this.ok = this.status >= 200 && this.status < 300;
99
363
  this.headers = new Headers(init.headers);
364
+ if (given.type && !this.headers.has('content-type')) this.headers.set('content-type', given.type);
100
365
  this.url = '';
101
366
  this.redirected = false;
102
- this.bodyUsed = false;
103
- /** @type {string | Uint8Array | null} */
104
- this.held = body == null || typeof body === 'string' ? body : to_bytes(body);
367
+ /** @type {'default' | 'basic' | 'error'} */
368
+ this.type = 'default';
105
369
  }
106
-
107
- /** @returns {string | Uint8Array} */
108
- take() {
109
- if (this.bodyUsed) throw new TypeError('the response body was already read');
110
- this.bodyUsed = true;
111
- return this.held ?? '';
370
+ content_type() {
371
+ return this.headers.get('content-type');
112
372
  }
113
-
114
- /** @returns {Promise<string>} */
115
- async text() {
116
- const body = this.take();
117
- if (typeof body !== 'string') throw new TypeError('text() of a byte body is not supported; use bytes()');
118
- return body;
373
+ clone() {
374
+ const copy = new Response(null, { status: this.status, statusText: this.statusText, headers: this.headers }, this.split_source());
375
+ copy.url = this.url;
376
+ copy.redirected = this.redirected;
377
+ copy.type = this.type;
378
+ return copy;
119
379
  }
120
- async json() {
121
- return JSON.parse(await this.text());
380
+ /** @param {unknown} data @param {{ status?: number, statusText?: string, headers?: unknown }} [init] */
381
+ static json(data, init = {}) {
382
+ const headers = new Headers(init.headers);
383
+ if (!headers.has('content-type')) headers.set('content-type', 'application/json');
384
+ return new Response(JSON.stringify(data), { ...init, headers });
122
385
  }
123
- /** @returns {Promise<Uint8Array>} */
124
- async bytes() {
125
- const body = this.take();
126
- if (typeof body === 'string') throw new TypeError('bytes() of a string body is not supported; use text()');
127
- return body;
386
+ /** @param {string | { href: string }} url @param {number} [status] */
387
+ static redirect(url, status = 302) {
388
+ if (![301, 302, 303, 307, 308].includes(status)) throw new RangeError(`Response.redirect: ${status} is not a redirect status`);
389
+ return new Response(null, { status, headers: { location: typeof url === 'string' ? url : url.href } });
128
390
  }
129
- async arrayBuffer() {
130
- return /** @type {ArrayBuffer} */ ((await this.bytes()).buffer);
391
+ static error() {
392
+ const response = new Response(null, { status: 0 });
393
+ response.type = 'error';
394
+ return response;
131
395
  }
132
396
  }
133
397
 
134
- /** What `fetch` answers with: the body stays with the host until it is asked for. */
398
+ /** What `fetch` answers with: the body stays with the host until it is read. */
135
399
  class FetchResponse extends Response {
136
- /** @param {{ id: number, status: number, status_text: string, url: string, redirected: boolean, headers: [string, string][] }} head */
137
- constructor(head) {
138
- super(null, { status: head.status, statusText: head.status_text, headers: head.headers });
400
+ /** @type {AbortSignal | null} */
401
+ #signal;
402
+
403
+ /** @param {{ id: number, status: number, status_text: string, url: string, redirected: boolean, headers: [string, string][] }} head @param {AbortSignal | null} signal */
404
+ constructor(head, signal) {
405
+ super(null, { status: head.status, statusText: head.status_text, headers: head.headers }, { host: head.id });
139
406
  this.url = head.url;
140
407
  this.redirected = head.redirected;
141
- this.body_id = head.id;
408
+ this.type = /** @type {'basic'} */ ('basic');
409
+ this.#signal = signal;
142
410
  }
143
-
144
- /** @param {'text' | 'base64'} format @returns {Promise<string>} */
145
- read(format) {
146
- if (this.bodyUsed) return Promise.reject(new TypeError('the response body was already read'));
147
- this.bodyUsed = true;
148
- return host_call('http.body', { id: this.body_id, as: format });
149
- }
150
-
151
- text() {
152
- return this.read('text');
153
- }
154
- async bytes() {
155
- return decode(await this.read('base64'));
411
+ body_signal() {
412
+ return this.#signal;
156
413
  }
157
414
  }
158
415
 
@@ -166,7 +423,9 @@ function header_pairs(headers) {
166
423
  /** @type {[string, string][]} */
167
424
  const pairs = [];
168
425
  const object = /** @type {any} */ (headers);
169
- if (typeof object.forEach === 'function') {
426
+ if (object instanceof Headers) {
427
+ for (const pair of object) pairs.push(pair);
428
+ } else if (typeof object.forEach === 'function') {
170
429
  object.forEach((/** @type {unknown} */ value, /** @type {unknown} */ name) => pairs.push([String(name), String(value)]));
171
430
  } else {
172
431
  for (const name of Object.keys(object)) pairs.push([name, String(object[name])]);
@@ -176,17 +435,25 @@ function header_pairs(headers) {
176
435
 
177
436
  /**
178
437
  * @param {string | Request | { url?: string, href?: string }} input
179
- * @param {{ method?: string, headers?: unknown, body?: string | ArrayBuffer | ArrayBufferView | null }} [init]
438
+ * @param {ConstructorParameters<typeof Request>[1]} [init]
180
439
  * @returns {Promise<Response>}
181
440
  */
182
441
  export async function fetch(input, init = {}) {
183
- const { url, method, headers, body } = new Request(input, init);
442
+ // A request on its own is sent as it is: its body is used up, as the Fetch API says.
443
+ const request = input instanceof Request && Object.keys(init).length === 0 ? input : new Request(input, init);
444
+ const signal = request.signal;
445
+ signal.throwIfAborted();
446
+ // A relative URL is relative to the page the app is on (the DOM layer's
447
+ // `location`), or to the app's origin.
184
448
  /** @type {Record<string, unknown>} */
185
- const request = { url, method, headers: [...headers] };
186
-
187
- if (typeof body === 'string') request.body = body;
188
- else if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) request.body_base64 = encode(to_bytes(body));
189
- else if (body != null) throw new TypeError('fetch: the body must be a string, an ArrayBuffer or a typed array');
190
-
191
- return new FetchResponse(await host_call('http.fetch', request));
449
+ const call = { url: request.url, method: request.method, headers: [...request.headers], base: /** @type {any} */ (globalThis).location?.href };
450
+ if (request.has_body()) Object.assign(call, await request.for_host());
451
+ /** @type {Promise<never>} */
452
+ const aborted = new Promise((_, reject) => {
453
+ if (signal.aborted) reject(signal.reason);
454
+ signal.addEventListener('abort', () => reject(signal.reason ?? abort_error('the request was aborted')), { once: true });
455
+ });
456
+ aborted.catch(() => {});
457
+ const head = await Promise.race([host_call('http.fetch', call), aborted]);
458
+ return new FetchResponse(head, signal);
192
459
  }
@@ -0,0 +1,141 @@
1
+ // `FormData` as a request or response body, both ways: `multipart/form-data`
2
+ // (with files) and `application/x-www-form-urlencoded`, as browsers write and
3
+ // read them. The classes are formdata-node's (`web.js`).
4
+
5
+ import { File, FormData } from 'formdata-node';
6
+ import { TextDecoder, TextEncoder } from './text.js';
7
+ import { URLSearchParams } from './url.js';
8
+
9
+ const encoder = new TextEncoder();
10
+ const decoder = new TextDecoder();
11
+
12
+ /** A boundary that will not be in the content, as browsers choose them. */
13
+ export function make_boundary() {
14
+ let random = '';
15
+ for (let i = 0; i < 24; i++) random += Math.floor(Math.random() * 16).toString(16);
16
+ return `----SepalFormBoundary${random}`;
17
+ }
18
+
19
+ /** A name or file name inside a quoted header parameter, as HTML escapes it. @param {string} text */
20
+ const quote = (text) => text.replace(/"/g, '%22').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
21
+
22
+ /**
23
+ * `form` as a `multipart/form-data` body with `boundary`.
24
+ * @param {FormData} form
25
+ * @param {string} boundary
26
+ * @returns {Promise<Uint8Array>}
27
+ */
28
+ export async function encode_multipart(form, boundary) {
29
+ /** @type {Uint8Array[]} */
30
+ const parts = [];
31
+ for (const [name, value] of form) {
32
+ let head = `--${boundary}\r\nContent-Disposition: form-data; name="${quote(name)}"`;
33
+ if (typeof value === 'string') {
34
+ parts.push(encoder.encode(`${head}\r\n\r\n`), encoder.encode(value.replace(/\r?\n|\r/g, '\r\n')), encoder.encode('\r\n'));
35
+ } else {
36
+ head += `; filename="${quote(value.name)}"\r\nContent-Type: ${value.type || 'application/octet-stream'}\r\n\r\n`;
37
+ parts.push(encoder.encode(head), new Uint8Array(await value.arrayBuffer()), encoder.encode('\r\n'));
38
+ }
39
+ }
40
+ parts.push(encoder.encode(`--${boundary}--\r\n`));
41
+ return concat(parts);
42
+ }
43
+
44
+ /** @param {Uint8Array[]} parts */
45
+ export function concat(parts) {
46
+ const all = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
47
+ let at = 0;
48
+ for (const part of parts) {
49
+ all.set(part, at);
50
+ at += part.length;
51
+ }
52
+ return all;
53
+ }
54
+
55
+ /**
56
+ * A body as `FormData`, by its content type, as `formData()` reads it.
57
+ * @param {Uint8Array} bytes
58
+ * @param {string | null} content_type
59
+ * @returns {FormData}
60
+ */
61
+ export function parse_form(bytes, content_type) {
62
+ const type = (content_type ?? '').toLowerCase();
63
+ if (type.startsWith('application/x-www-form-urlencoded')) {
64
+ const form = new FormData();
65
+ for (const [name, value] of new URLSearchParams(decoder.decode(bytes))) form.append(name, value);
66
+ return form;
67
+ }
68
+ if (type.startsWith('multipart/form-data')) {
69
+ const boundary = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(content_type ?? '');
70
+ if (boundary) return parse_multipart(bytes, boundary[1] ?? boundary[2]);
71
+ }
72
+ throw new TypeError(`formData(): the body is ${content_type ?? 'of no type'}, not a form`);
73
+ }
74
+
75
+ /** @param {Uint8Array} bytes @param {string} boundary */
76
+ function parse_multipart(bytes, boundary) {
77
+ const form = new FormData();
78
+ const delimiter = encoder.encode(`--${boundary}`);
79
+ let at = find(bytes, delimiter, 0);
80
+ if (at < 0) throw new TypeError('formData(): the multipart body has no boundary');
81
+ for (;;) {
82
+ at += delimiter.length;
83
+ // `--` after a delimiter ends the body.
84
+ if (bytes[at] === 45 && bytes[at + 1] === 45) break;
85
+ at = skip_line_end(bytes, at);
86
+ const head_end = find(bytes, encoder.encode('\r\n\r\n'), at);
87
+ if (head_end < 0) throw new TypeError('formData(): a part of the multipart body has no end of headers');
88
+ const headers = decoder.decode(bytes.subarray(at, head_end));
89
+ const start = head_end + 4;
90
+ const next = find(bytes, delimiter, start);
91
+ if (next < 0) throw new TypeError('formData(): the multipart body is cut off');
92
+ // The part's content ends with the line break before the next delimiter.
93
+ let end = next;
94
+ if (bytes[end - 1] === 10) end--;
95
+ if (bytes[end - 1] === 13) end--;
96
+ add_part(form, headers, bytes.slice(start, end));
97
+ at = next;
98
+ }
99
+ return form;
100
+ }
101
+
102
+ /** @param {Uint8Array} bytes @param {number} at */
103
+ function skip_line_end(bytes, at) {
104
+ if (bytes[at] === 13) at++;
105
+ if (bytes[at] === 10) at++;
106
+ return at;
107
+ }
108
+
109
+ /** @param {FormData} form @param {string} headers @param {Uint8Array} content */
110
+ function add_part(form, headers, content) {
111
+ /** @type {Record<string, string>} */
112
+ const fields = {};
113
+ for (const line of headers.split(/\r?\n/)) {
114
+ const colon = line.indexOf(':');
115
+ if (colon > 0) fields[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
116
+ }
117
+ const disposition = fields['content-disposition'] ?? '';
118
+ const name = parameter(disposition, 'name');
119
+ if (name === null) return;
120
+ const filename = parameter(disposition, 'filename');
121
+ if (filename === null) form.append(name, decoder.decode(content));
122
+ else form.append(name, new File([content], filename, { type: fields['content-type'] ?? 'application/octet-stream' }));
123
+ }
124
+
125
+ /** A quoted or bare parameter of a header value. @param {string} header @param {string} name */
126
+ function parameter(header, name) {
127
+ const match = new RegExp(`(?:^|;)\\s*${name}=(?:"((?:[^"\\\\]|\\\\.)*)"|([^;]*))`, 'i').exec(header);
128
+ if (!match) return null;
129
+ const value = match[1] ?? match[2].trim();
130
+ return value.replace(/%22/g, '"').replace(/%0D/gi, '\r').replace(/%0A/gi, '\n');
131
+ }
132
+
133
+ /** Where `needle` starts in `bytes` from `from`, or -1. @param {Uint8Array} bytes @param {Uint8Array} needle @param {number} from */
134
+ function find(bytes, needle, from) {
135
+ const first = needle[0];
136
+ outer: for (let i = bytes.indexOf(first, from); i >= 0 && i <= bytes.length - needle.length; i = bytes.indexOf(first, i + 1)) {
137
+ for (let j = 1; j < needle.length; j++) if (bytes[i + j] !== needle[j]) continue outer;
138
+ return i;
139
+ }
140
+ return -1;
141
+ }