ovr 4.6.0 → 6.0.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 (90) hide show
  1. package/dist/LICENSE.md +26 -0
  2. package/dist/app/index.d.ts +55 -103
  3. package/dist/app/index.d.ts.map +1 -1
  4. package/dist/app/index.js +67 -145
  5. package/dist/context/index.d.ts +138 -0
  6. package/dist/context/index.d.ts.map +1 -0
  7. package/dist/context/index.js +218 -0
  8. package/dist/cookie/index.d.ts +121 -0
  9. package/dist/cookie/index.d.ts.map +1 -0
  10. package/dist/cookie/index.js +56 -0
  11. package/dist/index.d.ts +6 -8
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +4 -7
  14. package/dist/jsx/{intrinsic-elements.d.ts → elements.d.ts} +14 -7
  15. package/dist/jsx/elements.d.ts.map +1 -0
  16. package/dist/jsx/index.d.ts +37 -52
  17. package/dist/jsx/index.d.ts.map +1 -1
  18. package/dist/jsx/index.js +71 -197
  19. package/dist/middleware/index.d.ts +22 -0
  20. package/dist/middleware/index.d.ts.map +1 -0
  21. package/dist/multipart/index.d.ts +122 -0
  22. package/dist/multipart/index.d.ts.map +1 -0
  23. package/dist/multipart/index.js +341 -0
  24. package/dist/render/index.d.ts +78 -0
  25. package/dist/render/index.d.ts.map +1 -0
  26. package/dist/render/index.js +248 -0
  27. package/dist/route/index.d.ts +147 -0
  28. package/dist/route/index.d.ts.map +1 -0
  29. package/dist/route/index.js +126 -0
  30. package/dist/trie/index.d.ts +31 -26
  31. package/dist/trie/index.d.ts.map +1 -1
  32. package/dist/trie/index.js +71 -80
  33. package/dist/util/index.d.ts +38 -0
  34. package/dist/util/index.d.ts.map +1 -0
  35. package/dist/util/index.js +88 -0
  36. package/package.json +4 -4
  37. package/src/app/index.ts +128 -265
  38. package/src/context/index.ts +262 -0
  39. package/src/cookie/index.ts +189 -0
  40. package/src/index.ts +6 -8
  41. package/src/jsx/{intrinsic-elements.ts → elements.ts} +14 -7
  42. package/src/jsx/index.ts +81 -222
  43. package/src/middleware/index.ts +29 -0
  44. package/src/multipart/index.ts +486 -0
  45. package/src/render/index.ts +300 -0
  46. package/src/route/index.ts +332 -0
  47. package/src/trie/index.ts +90 -107
  48. package/src/util/index.ts +112 -0
  49. package/dist/app/context.d.ts +0 -147
  50. package/dist/app/context.d.ts.map +0 -1
  51. package/dist/app/context.js +0 -283
  52. package/dist/app/helper/get.d.ts +0 -30
  53. package/dist/app/helper/get.d.ts.map +0 -1
  54. package/dist/app/helper/get.js +0 -33
  55. package/dist/app/helper/index.d.ts +0 -55
  56. package/dist/app/helper/index.d.ts.map +0 -1
  57. package/dist/app/helper/index.js +0 -96
  58. package/dist/app/helper/post.d.ts +0 -35
  59. package/dist/app/helper/post.d.ts.map +0 -1
  60. package/dist/app/helper/post.js +0 -15
  61. package/dist/app/memo/index.d.ts +0 -12
  62. package/dist/app/memo/index.d.ts.map +0 -1
  63. package/dist/app/memo/index.js +0 -34
  64. package/dist/app/mw/csrf.d.ts +0 -23
  65. package/dist/app/mw/csrf.d.ts.map +0 -1
  66. package/dist/app/mw/csrf.js +0 -30
  67. package/dist/jsx/chunk/index.d.ts +0 -38
  68. package/dist/jsx/chunk/index.d.ts.map +0 -1
  69. package/dist/jsx/chunk/index.js +0 -69
  70. package/dist/jsx/intrinsic-elements.d.ts.map +0 -1
  71. package/dist/jsx/merge-async-generators.d.ts +0 -14
  72. package/dist/jsx/merge-async-generators.d.ts.map +0 -1
  73. package/dist/jsx/merge-async-generators.js +0 -42
  74. package/dist/types/index.d.ts +0 -17
  75. package/dist/types/index.d.ts.map +0 -1
  76. package/dist/util/hash.d.ts +0 -11
  77. package/dist/util/hash.d.ts.map +0 -1
  78. package/dist/util/hash.js +0 -16
  79. package/src/app/context.ts +0 -365
  80. package/src/app/helper/get.ts +0 -46
  81. package/src/app/helper/index.ts +0 -174
  82. package/src/app/helper/post.ts +0 -54
  83. package/src/app/memo/index.ts +0 -40
  84. package/src/app/mw/csrf.ts +0 -32
  85. package/src/jsx/chunk/index.ts +0 -79
  86. package/src/jsx/merge-async-generators.ts +0 -47
  87. package/src/types/index.ts +0 -42
  88. package/src/util/hash.ts +0 -17
  89. /package/dist/jsx/{intrinsic-elements.js → elements.js} +0 -0
  90. /package/dist/{types → middleware}/index.js +0 -0
@@ -0,0 +1,341 @@
1
+ import { Codec, Header } from "../util/index.js";
2
+ /** Sequence of bytes to find within the stream */
3
+ class Needle extends Uint8Array {
4
+ /** Index of the last character in the needle */
5
+ end = this.length - 1;
6
+ /**
7
+ * Stores the how far from the last character each char in the needle is so
8
+ * the iterator know how far to safely skip forward when the character is
9
+ * found the rest of the array is filled with the length (default skip)
10
+ */
11
+ skip = new Uint8Array(256).fill(this.length);
12
+ /** Stores where each byte is located in the needle */
13
+ loc = new Array(256);
14
+ /** @param needle String to find within the stream */
15
+ constructor(needle) {
16
+ super(Codec.encode(needle).buffer);
17
+ for (let i = 0; i < this.length; i++) {
18
+ const byte = this[i];
19
+ // skip the last char of the needle since that would be a find
20
+ if (i !== this.end)
21
+ this.skip[byte] = this.end - i;
22
+ (this.loc[byte] ??= []).push(i);
23
+ }
24
+ }
25
+ }
26
+ /** Multipart part */
27
+ class Part extends Request {
28
+ /**
29
+ * Form input `name` attribute
30
+ *
31
+ * @example
32
+ *
33
+ * ```html
34
+ * <input type="file" name="photo">
35
+ * ```
36
+ */
37
+ name;
38
+ /**
39
+ * Filename from Content-Disposition header if file
40
+ *
41
+ * @example "my-image.png"
42
+ */
43
+ filename;
44
+ /**
45
+ * Media type of the part
46
+ *
47
+ * @example "image/png"
48
+ */
49
+ type;
50
+ /**
51
+ * Create a new multipart part
52
+ *
53
+ * @param req Original request
54
+ * @param body Part body
55
+ * @param rawHeaders Raw buffer of HTTP headers for the part
56
+ */
57
+ constructor(req, body, rawHeaders) {
58
+ const headers = [];
59
+ // create headers
60
+ for (const line of Codec.decode(rawHeaders).split("\r\n")) {
61
+ const colon = line.indexOf(":");
62
+ if (colon !== -1) {
63
+ headers.push([
64
+ line.slice(0, colon).trim(),
65
+ // no need to trim value - Headers.set does this already
66
+ line.slice(colon + 1),
67
+ ]);
68
+ }
69
+ }
70
+ super(req, {
71
+ headers,
72
+ body,
73
+ // @ts-expect-error - streaming https://developer.mozilla.org/en-US/docs/Web/API/RequestInit#duplex
74
+ duplex: "half",
75
+ });
76
+ [this.type] = Header.shift(this.headers.get(Header.contentType));
77
+ ({ name: this.name = null, filename: this.filename = null } = Header.params(this.headers.get("content-disposition")));
78
+ }
79
+ }
80
+ /** Multipart request */
81
+ export class Multipart extends Request {
82
+ static #kb = 1024;
83
+ static #mb = 1024 ** 2;
84
+ static #multipartType = "multipart/form-data";
85
+ /** New line needle to share across requests and parts */
86
+ static #newLine = new Needle("\r\n\r\n");
87
+ /** Parser options */
88
+ #options = {
89
+ memory: 4 * Multipart.#mb,
90
+ payload: 16 * Multipart.#mb,
91
+ parts: Infinity,
92
+ };
93
+ /** Request body reader */
94
+ #reader;
95
+ /** Current values being buffered in memory */
96
+ #memory;
97
+ /** Opening boundary needle */
98
+ #opening;
99
+ /** Part boundary needle */
100
+ #boundary;
101
+ /** Where valid data ends, valid < #valid >= invalid or empty space */
102
+ #valid = 0;
103
+ /** Start index of the found needle */
104
+ #start = 0;
105
+ /** End index of the found needle */
106
+ #end = 0;
107
+ /** Total bytes read from the stream */
108
+ #payloadSize = 0;
109
+ /**
110
+ * Split a multipart request into parts.
111
+ *
112
+ * @param req Multipart request
113
+ * @param options Options
114
+ * @yields Multipart form data `Part`(s)
115
+ * @throws {TypeError} If request headers are invalid
116
+ * @example
117
+ *
118
+ * ```ts
119
+ * for await (const part of new Multipart(request)) {
120
+ * // ...
121
+ * }
122
+ * ```
123
+ */
124
+ constructor(req, options) {
125
+ super(req);
126
+ const [type, params] = Header.shift(this.headers.get(Header.contentType));
127
+ if (type !== Multipart.#multipartType) {
128
+ throw new TypeError("Unsupported Media Type");
129
+ }
130
+ const { boundary } = Header.params(params);
131
+ if (!boundary)
132
+ throw new TypeError("Boundary Not Found");
133
+ if (!this.body)
134
+ throw new TypeError("No Request Body");
135
+ Object.assign(this.#options, options);
136
+ this.#reader = this.body.getReader();
137
+ this.#opening = new Needle(`--${boundary}\r\n`);
138
+ this.#boundary = new Needle(`\r\n--${boundary}`);
139
+ this.#memory = new Uint8Array(new ArrayBuffer(
140
+ // slightly larger than common chunk size/high water mark 64kb for leftover boundary
141
+ // prevents having to resize memory for most requests
142
+ 65 * Multipart.#kb,
143
+ // cap max chunk size + leftover
144
+ { maxByteLength: this.#options.memory }));
145
+ }
146
+ /**
147
+ * Reads the next chunk in the request stream and concatenates it
148
+ * onto the buffer.
149
+ *
150
+ * @param append
151
+ * @returns `true` if done
152
+ */
153
+ async #read(append = true) {
154
+ const next = await this.#reader.read();
155
+ if (next.done)
156
+ return true;
157
+ const nextLength = next.value.length;
158
+ if ((this.#payloadSize += nextLength) > this.#options.payload) {
159
+ throw new RangeError("Payload Too Large");
160
+ }
161
+ if (append) {
162
+ const required = this.#valid + nextLength;
163
+ const size = this.#memory.buffer.byteLength;
164
+ // resize if full
165
+ if (required > size) {
166
+ this.#memory.buffer.resize(Math.min(this.#options.memory, // in case double is larger than the max
167
+ Math.max(required, size * 2)));
168
+ }
169
+ // write at the valid cutoff
170
+ this.#memory.set(next.value, this.#valid);
171
+ this.#valid += nextLength;
172
+ }
173
+ }
174
+ /**
175
+ * Cuts off the buffer < end index.
176
+ *
177
+ * @returns Shifted off buffer < start index
178
+ */
179
+ #shift() {
180
+ const before = this.#memory.slice(0, this.#start);
181
+ // how much data is left after the found needle
182
+ const remainder = this.#valid - this.#end;
183
+ if (remainder) {
184
+ // copy remainder to the start of the buffer
185
+ // this doesn't move the chunks, just copies to the start
186
+ // old will be overwritten
187
+ this.#memory.copyWithin(0, this.#end, this.#valid);
188
+ }
189
+ this.#valid = remainder;
190
+ this.#start = this.#end = 0;
191
+ return before;
192
+ }
193
+ /**
194
+ * Attempts to find the needle within the current buffer (haystack).
195
+ * Sets start and end to the start and end of the found needle, or the
196
+ * safe place to start the next search from if not found.
197
+ *
198
+ * @param needle Needle to find
199
+ * @returns If found, shifts the buffer and returns the result.
200
+ */
201
+ #find(needle) {
202
+ const haystackLength = this.#valid;
203
+ // start the search at the last char of the needle
204
+ // since it could be at the very start
205
+ let i = this.#start + needle.end;
206
+ while (i < haystackLength) {
207
+ for (let needleIndex = needle.end, cursor = i; needleIndex >= 0 && needle[needleIndex] === this.#memory[cursor]; needleIndex--, cursor--) {
208
+ if (needleIndex === 0) {
209
+ this.#start = cursor;
210
+ this.#end = cursor + needle.length;
211
+ return this.#shift();
212
+ }
213
+ }
214
+ i += needle.skip[this.#memory[i]];
215
+ }
216
+ // where to safely start the next search in the concatenated chunk result
217
+ // go back len - 1 in case it was partially at the end
218
+ this.#start = this.#end =
219
+ needle.length < haystackLength ? haystackLength - (needle.length - 1) : 0;
220
+ }
221
+ /**
222
+ * Tries to find the needle in the buffer, if not found, the next
223
+ * chunk is read an concatenated onto the buffer.
224
+ *
225
+ * @param needle Needle to find
226
+ * @returns Buffer up until the found needle
227
+ */
228
+ async #findConcat(needle) {
229
+ let found;
230
+ while (!(found = this.#find(needle)) && !(await this.#read()))
231
+ ;
232
+ return found;
233
+ }
234
+ /**
235
+ * @param needle Needle to find
236
+ * @returns Stream that streams the content until the next find
237
+ */
238
+ #findStream(needle) {
239
+ return new ReadableStream({
240
+ type: "bytes",
241
+ pull: async (c) => {
242
+ let found;
243
+ for (let done; !(found = this.#find(needle)) && !done; done = await this.#read()) {
244
+ // not found within current chunk
245
+ const lastIndex = this.#valid - 1;
246
+ const needleIndices = needle.loc[this.#memory[lastIndex]];
247
+ if (needleIndices) {
248
+ // last char is in the boundary, check for partial boundary
249
+ // iterate backwards through the indices
250
+ indices: for (let i = needleIndices.length - 1; i >= 0; i--) {
251
+ for (let needleIndex = needleIndices[i], cursor = lastIndex; needleIndex >= 0 &&
252
+ needle[needleIndex] === this.#memory[cursor]; needleIndex--, cursor--) {
253
+ if (needleIndex === 0) {
254
+ // these are the same since no needle was found
255
+ this.#start = this.#end = cursor;
256
+ // rerun check if next has the rest
257
+ break indices;
258
+ }
259
+ }
260
+ }
261
+ }
262
+ const before = this.#shift();
263
+ if (before.length) {
264
+ c.enqueue(before);
265
+ return; // wait for next pull
266
+ }
267
+ }
268
+ if (found?.length)
269
+ c.enqueue(found);
270
+ c.close();
271
+ },
272
+ });
273
+ }
274
+ /** @yields Multipart form data `Part`(s) */
275
+ async *[Symbol.asyncIterator]() {
276
+ try {
277
+ await this.#findConcat(this.#opening);
278
+ let headers;
279
+ for (let i = 0; (headers = await this.#findConcat(Multipart.#newLine)); i++) {
280
+ if (i === this.#options.parts)
281
+ throw new RangeError("Too Many Parts");
282
+ const part = new Part(this, this.#findStream(this.#boundary), headers);
283
+ yield part;
284
+ // to get next part, the entire body must be read
285
+ // cannot cancel, chunks would be in the next header
286
+ if (part.body && !part.bodyUsed) {
287
+ const partReader = part.body.getReader();
288
+ try {
289
+ while (!(await partReader.read()).done)
290
+ ;
291
+ }
292
+ finally {
293
+ partReader.releaseLock();
294
+ }
295
+ }
296
+ if (
297
+ // ensures invalid characters aren't used to determine if it's done
298
+ this.#valid > 1 &&
299
+ // check for --
300
+ // if not done it would be \r\nNEXT-HEADER
301
+ this.#memory[0] === 45 &&
302
+ this.#memory[1] === 45) {
303
+ // done, drain any epilogue
304
+ while (!(await this.#read(false)))
305
+ ;
306
+ break;
307
+ }
308
+ }
309
+ }
310
+ finally {
311
+ this.#reader.releaseLock();
312
+ }
313
+ }
314
+ /**
315
+ * Drop in replacement for `Request.formData` enhanced with size thresholds.
316
+ *
317
+ * Only use `data` when buffering all content is needed, otherwise iterate through
318
+ * the multipart using `for await...of` instead.
319
+ *
320
+ * @returns Buffered `FormData`
321
+ */
322
+ async data() {
323
+ const data = new FormData();
324
+ for await (const part of this) {
325
+ if (part.name) {
326
+ let value;
327
+ if (part.filename || part.type === "application/octet-stream") {
328
+ const blob = await part.blob();
329
+ value = new File([blob], part.filename ?? "blob", {
330
+ type: blob.type,
331
+ });
332
+ }
333
+ else {
334
+ value = await part.text();
335
+ }
336
+ data.append(part.name, value);
337
+ }
338
+ }
339
+ return data;
340
+ }
341
+ }
@@ -0,0 +1,78 @@
1
+ import type { JSX } from "../jsx/index.js";
2
+ /** Chunk containing the HTML from a rendered element */
3
+ declare class Chunk {
4
+ #private;
5
+ /**
6
+ * Chunk containing the HTML from a rendered element.
7
+ *
8
+ * @param html string of HTML to escape
9
+ * @param safe Set to `true` if the HTML is safe and should not be escaped
10
+ */
11
+ constructor(html: unknown, safe?: boolean);
12
+ /**
13
+ * @returns Safe value to render
14
+ */
15
+ toString(): string;
16
+ /**
17
+ * @param chunk Chunk to append to the end of the chunk
18
+ */
19
+ concat(chunk: Chunk): void;
20
+ }
21
+ export declare namespace Render {
22
+ /** Render options */
23
+ type Options = {
24
+ /** Set to `true` to disable escaping for non-HTML use */
25
+ safe?: boolean;
26
+ };
27
+ /** Rendered `Chunk` instance */
28
+ type Chunk = InstanceType<typeof Chunk>;
29
+ }
30
+ export declare class Render {
31
+ #private;
32
+ /**
33
+ * Creates an `AsyncIterable` that renders the `Element`.
34
+ *
35
+ * @param element Element to render
36
+ * @param options Render options
37
+ */
38
+ constructor(element: JSX.Element, options?: Render.Options);
39
+ /** @yields `Chunk`s as the `Element` resolves */
40
+ [Symbol.asyncIterator](): AsyncGenerator<Chunk, void, unknown>;
41
+ /**
42
+ * `render` piped into a `ReadableStream`.
43
+ * Use `render` when possible to avoid the overhead of the stream.
44
+ *
45
+ * @param element Element to render
46
+ * @param options Render options
47
+ * @returns `ReadableStream` of HTML
48
+ */
49
+ static stream(element: JSX.Element, options?: Render.Options): ReadableStream<Uint8Array<ArrayBufferLike>>;
50
+ /**
51
+ * Converts a render into a fully concatenated string of HTML.
52
+ *
53
+ * ### WARNING
54
+ *
55
+ * This negates streaming benefits and buffers the result into a string.
56
+ * @param element Element to render
57
+ * @param options Render options
58
+ * @returns Concatenated HTML
59
+ */
60
+ string(element: JSX.Element, options?: Render.Options): Promise<string>;
61
+ /**
62
+ * Render raw HTML and dangerously bypass escaping.
63
+ *
64
+ * @param html Safe html to render
65
+ * @returns New _safe_ `Chunk`
66
+ */
67
+ static html(html: unknown): Chunk;
68
+ /**
69
+ * Escapes strings of HTML.
70
+ *
71
+ * @param html String to escape
72
+ * @param attr Set to `true` if the value is an attribute, otherwise it's a string of HTML content
73
+ * @returns Escaped string of HTML
74
+ */
75
+ static escape(html: string, attr?: boolean): string;
76
+ }
77
+ export {};
78
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/render/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAK3C,wDAAwD;AACxD,cAAM,KAAK;;IAIV;;;;;OAKG;gBACS,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,OAAO;IAKzC;;OAEG;IACH,QAAQ;IAIR;;OAEG;IACH,MAAM,CAAC,KAAK,EAAE,KAAK;CAGnB;AAED,yBAAiB,MAAM,CAAC;IACvB,qBAAqB;IACrB,KAAY,OAAO,GAAG;QACrB,yDAAyD;QACzD,IAAI,CAAC,EAAE,OAAO,CAAC;KACf,CAAC;IAEF,gCAAgC;IAChC,KAAY,KAAK,GAAG,YAAY,CAAC,OAAO,KAAK,CAAC,CAAC;CAC/C;AAED,qBAAa,MAAM;;IAgBlB;;;;;OAKG;gBACS,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,OAAO;IAK1D,iDAAiD;IAC1C,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,CAAC;IAmFrE;;;;;;;OAOG;IACH,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,OAAO;IA0C5D;;;;;;;;;OASG;IACG,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,OAAO;IAI3D;;;;;OAKG;IACH,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO;IAIzB;;;;;;OAMG;IACH,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO;CA4D1C"}
@@ -0,0 +1,248 @@
1
+ import { Codec } from "../util/index.js";
2
+ /** Chunk containing the HTML from a rendered element */
3
+ class Chunk {
4
+ /** Safe value to render */
5
+ #value;
6
+ /**
7
+ * Chunk containing the HTML from a rendered element.
8
+ *
9
+ * @param html string of HTML to escape
10
+ * @param safe Set to `true` if the HTML is safe and should not be escaped
11
+ */
12
+ constructor(html, safe) {
13
+ const value = String(html ?? "");
14
+ this.#value = safe ? value : Render.escape(value);
15
+ }
16
+ /**
17
+ * @returns Safe value to render
18
+ */
19
+ toString() {
20
+ return this.#value;
21
+ }
22
+ /**
23
+ * @param chunk Chunk to append to the end of the chunk
24
+ */
25
+ concat(chunk) {
26
+ this.#value += chunk;
27
+ }
28
+ }
29
+ export class Render {
30
+ /** Regex to find escape character for HTML attributes */
31
+ static #attr = /[&"<]/g;
32
+ /** Regex to find escape character for HTML content */
33
+ static #content = /[&<]/g;
34
+ /** Escape character map */
35
+ static #map = { "&": "&amp;", '"': "&quot;", "<": "&lt;" };
36
+ /** Element to render */
37
+ #element;
38
+ /** Render options */
39
+ #options;
40
+ /**
41
+ * Creates an `AsyncIterable` that renders the `Element`.
42
+ *
43
+ * @param element Element to render
44
+ * @param options Render options
45
+ */
46
+ constructor(element, options) {
47
+ this.#element = element;
48
+ this.#options = options;
49
+ }
50
+ /** @yields `Chunk`s as the `Element` resolves */
51
+ async *[Symbol.asyncIterator]() {
52
+ let element = this.#element;
53
+ // modifications
54
+ // these are required to allow functions to be used as children
55
+ // instead of creating a separate component to use them
56
+ if (typeof element === "function")
57
+ element = element();
58
+ if (element instanceof Promise)
59
+ element = await element;
60
+ // resolve based on type
61
+ // should not render
62
+ if (element == null || typeof element === "boolean" || element === "")
63
+ return;
64
+ if (element instanceof Chunk) {
65
+ // already escaped or safe
66
+ yield element;
67
+ return;
68
+ }
69
+ if (typeof element === "object") {
70
+ if (Symbol.asyncIterator in element) {
71
+ // any async iterable - lazily resolve
72
+ for await (const children of element)
73
+ yield* new Render(children, this.#options);
74
+ return;
75
+ }
76
+ if (Symbol.iterator in element) {
77
+ // sync iterable
78
+ if ("next" in element) {
79
+ // sync generator - lazily resolve, avoids loading all in memory
80
+ for (const children of element)
81
+ yield* new Render(children, this.#options);
82
+ return;
83
+ }
84
+ // other iterable - array, set, etc.
85
+ // process children in parallel
86
+ const renders = Array.from(element, (el) => new Render(el, this.#options));
87
+ const n = renders.length;
88
+ const queue = new Array(n);
89
+ const complete = new Uint8Array(n);
90
+ let current = 0;
91
+ for await (const m of Render.#merge(renders)) {
92
+ if (m.result.done) {
93
+ complete[m.i] = 1;
94
+ if (m.i === current) {
95
+ while (++current < n) {
96
+ if (queue[current]) {
97
+ // yield whatever is in the next queue even if it hasn't completed yet
98
+ yield queue[current];
99
+ queue[current] = null;
100
+ }
101
+ // if it hasn't completed, stop iterating to the next
102
+ if (!complete[current])
103
+ break;
104
+ }
105
+ }
106
+ }
107
+ else if (m.i === current) {
108
+ yield m.result.value; // stream the current value directly
109
+ }
110
+ else {
111
+ // queue the value for later
112
+ if (queue[m.i])
113
+ queue[m.i].concat(m.result.value);
114
+ else
115
+ queue[m.i] = m.result.value;
116
+ }
117
+ }
118
+ // clear the queue
119
+ yield* queue.filter((chunk) => chunk !== null);
120
+ return;
121
+ }
122
+ }
123
+ // primitive or other object
124
+ yield new Chunk(element, this.#options?.safe);
125
+ }
126
+ /**
127
+ * `render` piped into a `ReadableStream`.
128
+ * Use `render` when possible to avoid the overhead of the stream.
129
+ *
130
+ * @param element Element to render
131
+ * @param options Render options
132
+ * @returns `ReadableStream` of HTML
133
+ */
134
+ static stream(element, options) {
135
+ const gen = new Render(element, options)[Symbol.asyncIterator]();
136
+ return new ReadableStream({
137
+ // enables zero-copy transfer from underlying source when queue is empty
138
+ // https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams#overview
139
+ type: "bytes",
140
+ // `pull` ensures backpressure and cancelled requests stop the generator
141
+ async pull(c) {
142
+ const result = await gen.next();
143
+ if (result.done) {
144
+ c.close();
145
+ gen.return();
146
+ return;
147
+ }
148
+ c.enqueue(
149
+ // need to encode for Node (ex: during prerendering) or it will error
150
+ // doesn't seem to be needed for browsers
151
+ // faster than piping through a `TextEncoderStream`
152
+ Codec.encode(String(result.value)));
153
+ },
154
+ cancel() {
155
+ gen.return();
156
+ },
157
+ }, {
158
+ // `highWaterMark` defaults to 1
159
+ // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream#highwatermark
160
+ // setting this ensures at least a small buffer is maintained if the
161
+ // underlying server does not have its own high water mark set
162
+ // https://blog.cloudflare.com/unpacking-cloudflare-workers-cpu-performance-benchmarks/#inefficient-streams-adapters
163
+ // in Node, the default is 16kb, so this stacks another 2kb in front
164
+ // https://nodejs.org/api/http.html#outgoingmessagewritablehighwatermark
165
+ highWaterMark: 2048,
166
+ });
167
+ }
168
+ /**
169
+ * Converts a render into a fully concatenated string of HTML.
170
+ *
171
+ * ### WARNING
172
+ *
173
+ * This negates streaming benefits and buffers the result into a string.
174
+ * @param element Element to render
175
+ * @param options Render options
176
+ * @returns Concatenated HTML
177
+ */
178
+ async string(element, options) {
179
+ return (await Array.fromAsync(new Render(element, options))).join("");
180
+ }
181
+ /**
182
+ * Render raw HTML and dangerously bypass escaping.
183
+ *
184
+ * @param html Safe html to render
185
+ * @returns New _safe_ `Chunk`
186
+ */
187
+ static html(html) {
188
+ return new Chunk(html, true);
189
+ }
190
+ /**
191
+ * Escapes strings of HTML.
192
+ *
193
+ * @param html String to escape
194
+ * @param attr Set to `true` if the value is an attribute, otherwise it's a string of HTML content
195
+ * @returns Escaped string of HTML
196
+ */
197
+ static escape(html, attr) {
198
+ return html.replace(attr ? Render.#attr : Render.#content, (c) =>
199
+ // @ts-expect-error - private method type error
200
+ Render.#map[c]);
201
+ }
202
+ /**
203
+ * @param gen
204
+ * @param i index of the generator within the list
205
+ * @returns promise containing the index and the next result of the iteration
206
+ */
207
+ static async #next(gen, i) {
208
+ return { i, result: await gen.next() };
209
+ }
210
+ /**
211
+ * Merges `Render[]` into a single `AsyncGenerator`, resolving all in parallel.
212
+ * The return of each `Render` is yielded from the generator with `done: true`.
213
+ *
214
+ * Adapted from [stack overflow answers](https://stackoverflow.com/questions/50585456).
215
+ *
216
+ * @param renders Resolved in parallel.
217
+ * @yields `NextResult` and index of the resolved generator.
218
+ */
219
+ static async *#merge(renders) {
220
+ const generators = renders.map((render) => render[Symbol.asyncIterator]());
221
+ const promises = new Map();
222
+ for (let i = 0; i < generators.length; i++) {
223
+ promises.set(i, Render.#next(generators[i], i));
224
+ }
225
+ let next;
226
+ try {
227
+ while (promises.size > 0) {
228
+ yield (next = await Promise.race(promises.values()));
229
+ if (next.result.done) {
230
+ promises.delete(next.i);
231
+ }
232
+ else {
233
+ promises.set(next.i, Render.#next(generators[next.i], next.i));
234
+ }
235
+ }
236
+ }
237
+ finally {
238
+ for (const gen of generators) {
239
+ try {
240
+ gen.return();
241
+ }
242
+ catch {
243
+ // could have already returned
244
+ }
245
+ }
246
+ }
247
+ }
248
+ }