@sveltejs/kit 1.0.0-next.392 → 1.0.0-next.395

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.
@@ -0,0 +1,788 @@
1
+ import { readFileSync, writeFileSync } from 'fs';
2
+ import { join, dirname } from 'path';
3
+ import { URL as URL$1, pathToFileURL } from 'url';
4
+ import { w as walk, p as posixify, m as mkdirp } from './chunks/filesystem.js';
5
+ import { installPolyfills } from './node/polyfills.js';
6
+ import { l as logger } from './chunks/utils.js';
7
+ import { l as load_config } from './chunks/index.js';
8
+ import 'assert';
9
+ import 'net';
10
+ import 'http';
11
+ import 'stream';
12
+ import 'buffer';
13
+ import 'util';
14
+ import 'stream/web';
15
+ import 'perf_hooks';
16
+ import 'util/types';
17
+ import 'events';
18
+ import 'tls';
19
+ import 'async_hooks';
20
+ import 'console';
21
+ import 'zlib';
22
+ import 'node:http';
23
+ import 'node:https';
24
+ import 'node:zlib';
25
+ import 'node:stream';
26
+ import 'node:buffer';
27
+ import 'node:util';
28
+ import 'node:url';
29
+ import 'node:net';
30
+ import 'node:fs';
31
+ import 'node:path';
32
+ import 'crypto';
33
+
34
+ const absolute = /^([a-z]+:)?\/?\//;
35
+ const scheme = /^[a-z]+:/;
36
+
37
+ /**
38
+ * @param {string} base
39
+ * @param {string} path
40
+ */
41
+ function resolve(base, path) {
42
+ if (scheme.test(path)) return path;
43
+
44
+ const base_match = absolute.exec(base);
45
+ const path_match = absolute.exec(path);
46
+
47
+ if (!base_match) {
48
+ throw new Error(`bad base path: "${base}"`);
49
+ }
50
+
51
+ const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
52
+ const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
53
+
54
+ baseparts.pop();
55
+
56
+ for (let i = 0; i < pathparts.length; i += 1) {
57
+ const part = pathparts[i];
58
+ if (part === '.') continue;
59
+ else if (part === '..') baseparts.pop();
60
+ else baseparts.push(part);
61
+ }
62
+
63
+ const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
64
+
65
+ return `${prefix}${baseparts.join('/')}`;
66
+ }
67
+
68
+ /** @param {string} path */
69
+ function is_root_relative(path) {
70
+ return path[0] === '/' && path[1] !== '/';
71
+ }
72
+
73
+ /**
74
+ * @typedef {{
75
+ * fn: () => Promise<any>,
76
+ * fulfil: (value: any) => void,
77
+ * reject: (error: Error) => void
78
+ * }} Task
79
+ */
80
+
81
+ /** @param {number} concurrency */
82
+ function queue(concurrency) {
83
+ /** @type {Task[]} */
84
+ const tasks = [];
85
+
86
+ let current = 0;
87
+
88
+ /** @type {(value?: any) => void} */
89
+ let fulfil;
90
+
91
+ /** @type {(error: Error) => void} */
92
+ let reject;
93
+
94
+ let closed = false;
95
+
96
+ const done = new Promise((f, r) => {
97
+ fulfil = f;
98
+ reject = r;
99
+ });
100
+
101
+ done.catch(() => {
102
+ // this is necessary in case a catch handler is never added
103
+ // to the done promise by the user
104
+ });
105
+
106
+ function dequeue() {
107
+ if (current < concurrency) {
108
+ const task = tasks.shift();
109
+
110
+ if (task) {
111
+ current += 1;
112
+ const promise = Promise.resolve(task.fn());
113
+
114
+ promise
115
+ .then(task.fulfil, (err) => {
116
+ task.reject(err);
117
+ reject(err);
118
+ })
119
+ .then(() => {
120
+ current -= 1;
121
+ dequeue();
122
+ });
123
+ } else if (current === 0) {
124
+ closed = true;
125
+ fulfil();
126
+ }
127
+ }
128
+ }
129
+
130
+ return {
131
+ /** @param {() => any} fn */
132
+ add: (fn) => {
133
+ if (closed) throw new Error('Cannot add tasks to a queue that has ended');
134
+
135
+ const promise = new Promise((fulfil, reject) => {
136
+ tasks.push({ fn, fulfil, reject });
137
+ });
138
+
139
+ dequeue();
140
+ return promise;
141
+ },
142
+
143
+ done: () => {
144
+ if (current === 0) {
145
+ closed = true;
146
+ fulfil();
147
+ }
148
+
149
+ return done;
150
+ }
151
+ };
152
+ }
153
+
154
+ const DOCTYPE = 'DOCTYPE';
155
+ const CDATA_OPEN = '[CDATA[';
156
+ const CDATA_CLOSE = ']]>';
157
+ const COMMENT_OPEN = '--';
158
+ const COMMENT_CLOSE = '-->';
159
+
160
+ const TAG_OPEN = /[a-zA-Z]/;
161
+ const TAG_CHAR = /[a-zA-Z0-9]/;
162
+ const ATTRIBUTE_NAME = /[^\t\n\f />"'=]/;
163
+
164
+ const WHITESPACE = /[\s\n\r]/;
165
+
166
+ /** @param {string} html */
167
+ function crawl(html) {
168
+ /** @type {string[]} */
169
+ const hrefs = [];
170
+
171
+ let i = 0;
172
+ main: while (i < html.length) {
173
+ const char = html[i];
174
+
175
+ if (char === '<') {
176
+ if (html[i + 1] === '!') {
177
+ i += 2;
178
+
179
+ if (html.slice(i, i + DOCTYPE.length).toUpperCase() === DOCTYPE) {
180
+ i += DOCTYPE.length;
181
+ while (i < html.length) {
182
+ if (html[i++] === '>') {
183
+ continue main;
184
+ }
185
+ }
186
+ }
187
+
188
+ // skip cdata
189
+ if (html.slice(i, i + CDATA_OPEN.length) === CDATA_OPEN) {
190
+ i += CDATA_OPEN.length;
191
+ while (i < html.length) {
192
+ if (html.slice(i, i + CDATA_CLOSE.length) === CDATA_CLOSE) {
193
+ i += CDATA_CLOSE.length;
194
+ continue main;
195
+ }
196
+
197
+ i += 1;
198
+ }
199
+ }
200
+
201
+ // skip comments
202
+ if (html.slice(i, i + COMMENT_OPEN.length) === COMMENT_OPEN) {
203
+ i += COMMENT_OPEN.length;
204
+ while (i < html.length) {
205
+ if (html.slice(i, i + COMMENT_CLOSE.length) === COMMENT_CLOSE) {
206
+ i += COMMENT_CLOSE.length;
207
+ continue main;
208
+ }
209
+
210
+ i += 1;
211
+ }
212
+ }
213
+ }
214
+
215
+ // parse opening tags
216
+ const start = ++i;
217
+ if (TAG_OPEN.test(html[start])) {
218
+ while (i < html.length) {
219
+ if (!TAG_CHAR.test(html[i])) {
220
+ break;
221
+ }
222
+
223
+ i += 1;
224
+ }
225
+
226
+ const tag = html.slice(start, i).toUpperCase();
227
+
228
+ if (tag === 'SCRIPT' || tag === 'STYLE') {
229
+ while (i < html.length) {
230
+ if (
231
+ html[i] === '<' &&
232
+ html[i + 1] === '/' &&
233
+ html.slice(i + 2, i + 2 + tag.length).toUpperCase() === tag
234
+ ) {
235
+ continue main;
236
+ }
237
+
238
+ i += 1;
239
+ }
240
+ }
241
+
242
+ let href = '';
243
+ let rel = '';
244
+
245
+ while (i < html.length) {
246
+ const start = i;
247
+
248
+ const char = html[start];
249
+ if (char === '>') break;
250
+
251
+ if (ATTRIBUTE_NAME.test(char)) {
252
+ i += 1;
253
+
254
+ while (i < html.length) {
255
+ if (!ATTRIBUTE_NAME.test(html[i])) {
256
+ break;
257
+ }
258
+
259
+ i += 1;
260
+ }
261
+
262
+ const name = html.slice(start, i).toLowerCase();
263
+
264
+ while (WHITESPACE.test(html[i])) i += 1;
265
+
266
+ if (html[i] === '=') {
267
+ i += 1;
268
+ while (WHITESPACE.test(html[i])) i += 1;
269
+
270
+ let value;
271
+
272
+ if (html[i] === "'" || html[i] === '"') {
273
+ const quote = html[i++];
274
+
275
+ const start = i;
276
+ let escaped = false;
277
+
278
+ while (i < html.length) {
279
+ if (!escaped) {
280
+ const char = html[i];
281
+
282
+ if (html[i] === quote) {
283
+ break;
284
+ }
285
+
286
+ if (char === '\\') {
287
+ escaped = true;
288
+ }
289
+ }
290
+
291
+ i += 1;
292
+ }
293
+
294
+ value = html.slice(start, i);
295
+ } else {
296
+ const start = i;
297
+ while (html[i] !== '>' && !WHITESPACE.test(html[i])) i += 1;
298
+ value = html.slice(start, i);
299
+
300
+ i -= 1;
301
+ }
302
+
303
+ if (name === 'href') {
304
+ href = value;
305
+ } else if (name === 'rel') {
306
+ rel = value;
307
+ } else if (name === 'src') {
308
+ hrefs.push(value);
309
+ } else if (name === 'srcset') {
310
+ const candidates = [];
311
+ let insideURL = true;
312
+ value = value.trim();
313
+ for (let i = 0; i < value.length; i++) {
314
+ if (value[i] === ',' && (!insideURL || (insideURL && value[i + 1] === ' '))) {
315
+ candidates.push(value.slice(0, i));
316
+ value = value.substring(i + 1).trim();
317
+ i = 0;
318
+ insideURL = true;
319
+ } else if (value[i] === ' ') {
320
+ insideURL = false;
321
+ }
322
+ }
323
+ candidates.push(value);
324
+ for (const candidate of candidates) {
325
+ const src = candidate.split(WHITESPACE)[0];
326
+ hrefs.push(src);
327
+ }
328
+ }
329
+ } else {
330
+ i -= 1;
331
+ }
332
+ }
333
+
334
+ i += 1;
335
+ }
336
+
337
+ if (href && !/\bexternal\b/i.test(rel)) {
338
+ hrefs.push(href);
339
+ }
340
+ }
341
+ }
342
+
343
+ i += 1;
344
+ }
345
+
346
+ return hrefs;
347
+ }
348
+
349
+ /**
350
+ * Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
351
+ *
352
+ * The first closes the script element, so everything after is treated as raw HTML.
353
+ * The second disables further parsing until `-->`, so the script element might be unexpectedly
354
+ * kept open until until an unrelated HTML comment in the page.
355
+ *
356
+ * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
357
+ * browsers.
358
+ *
359
+ * @see tests for unsafe parsing examples.
360
+ * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
361
+ * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
362
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
363
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
364
+ * @see https://github.com/tc39/proposal-json-superset
365
+ * @type {Record<string, string>}
366
+ */
367
+ const render_json_payload_script_dict = {
368
+ '<': '\\u003C',
369
+ '\u2028': '\\u2028',
370
+ '\u2029': '\\u2029'
371
+ };
372
+
373
+ new RegExp(
374
+ `[${Object.keys(render_json_payload_script_dict).join('')}]`,
375
+ 'g'
376
+ );
377
+
378
+ /**
379
+ * When inside a double-quoted attribute value, only `&` and `"` hold special meaning.
380
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state
381
+ * @type {Record<string, string>}
382
+ */
383
+ const escape_html_attr_dict = {
384
+ '&': '&amp;',
385
+ '"': '&quot;'
386
+ };
387
+
388
+ const escape_html_attr_regex = new RegExp(
389
+ // special characters
390
+ `[${Object.keys(escape_html_attr_dict).join('')}]|` +
391
+ // high surrogate without paired low surrogate
392
+ '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' +
393
+ // a valid surrogate pair, the only match with 2 code units
394
+ // we match it so that we can match unpaired low surrogates in the same pass
395
+ // TODO: use lookbehind assertions once they are widely supported: (?<![\ud800-udbff])[\udc00-\udfff]
396
+ '[\\ud800-\\udbff][\\udc00-\\udfff]|' +
397
+ // unpaired low surrogate (see previous match)
398
+ '[\\udc00-\\udfff]',
399
+ 'g'
400
+ );
401
+
402
+ /**
403
+ * Formats a string to be used as an attribute's value in raw HTML.
404
+ *
405
+ * It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes
406
+ * characters that are special in attributes, and surrounds the whole string in double-quotes.
407
+ *
408
+ * @param {string} str
409
+ * @returns {string} Escaped string surrounded by double-quotes.
410
+ * @example const html = `<tag data-value=${escape_html_attr('value')}>...</tag>`;
411
+ */
412
+ function escape_html_attr(str) {
413
+ const escaped_str = str.replace(escape_html_attr_regex, (match) => {
414
+ if (match.length === 2) {
415
+ // valid surrogate pair
416
+ return match;
417
+ }
418
+
419
+ return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`;
420
+ });
421
+
422
+ return `"${escaped_str}"`;
423
+ }
424
+
425
+ /**
426
+ * @typedef {import('types').PrerenderErrorHandler} PrerenderErrorHandler
427
+ * @typedef {import('types').Logger} Logger
428
+ */
429
+
430
+ const [, , client_out_dir, results_path, manifest_path, verbose] = process.argv;
431
+
432
+ prerender();
433
+
434
+ /**
435
+ * @param {Parameters<PrerenderErrorHandler>[0]} details
436
+ * @param {import('types').ValidatedKitConfig} config
437
+ */
438
+ function format_error({ status, path, referrer, referenceType }, config) {
439
+ const message =
440
+ status === 404 && !path.startsWith(config.paths.base)
441
+ ? `${path} does not begin with \`base\`, which is configured in \`paths.base\` and can be imported from \`$app/paths\``
442
+ : path;
443
+
444
+ return `${status} ${message}${referrer ? ` (${referenceType} from ${referrer})` : ''}`;
445
+ }
446
+
447
+ /**
448
+ * @param {Logger} log
449
+ * @param {import('types').ValidatedKitConfig} config
450
+ * @returns {PrerenderErrorHandler}
451
+ */
452
+ function normalise_error_handler(log, config) {
453
+ switch (config.prerender.onError) {
454
+ case 'continue':
455
+ return (details) => {
456
+ log.error(format_error(details, config));
457
+ };
458
+ case 'fail':
459
+ return (details) => {
460
+ throw new Error(format_error(details, config));
461
+ };
462
+ default:
463
+ return config.prerender.onError;
464
+ }
465
+ }
466
+
467
+ const OK = 2;
468
+ const REDIRECT = 3;
469
+
470
+ /**
471
+ * @param {import('types').Prerendered} prerendered
472
+ */
473
+ const output_and_exit = (prerendered) => {
474
+ writeFileSync(
475
+ results_path,
476
+ JSON.stringify(prerendered, (_key, value) =>
477
+ value instanceof Map ? Array.from(value.entries()) : value
478
+ )
479
+ );
480
+ process.exit(0);
481
+ };
482
+
483
+ async function prerender() {
484
+ /** @type {import('types').Prerendered} */
485
+ const prerendered = {
486
+ pages: new Map(),
487
+ assets: new Map(),
488
+ redirects: new Map(),
489
+ paths: []
490
+ };
491
+
492
+ /** @type {import('types').ValidatedKitConfig} */
493
+ const config = (await load_config()).kit;
494
+
495
+ if (!config.prerender.enabled) {
496
+ output_and_exit(prerendered);
497
+ return;
498
+ }
499
+
500
+ /** @type {import('types').Logger} */
501
+ const log = logger({
502
+ verbose: verbose === 'true'
503
+ });
504
+
505
+ installPolyfills();
506
+ const { fetch } = globalThis;
507
+ globalThis.fetch = async (info, init) => {
508
+ /** @type {string} */
509
+ let url;
510
+
511
+ /** @type {RequestInit} */
512
+ let opts = {};
513
+
514
+ if (info instanceof Request) {
515
+ url = info.url;
516
+
517
+ opts = {
518
+ method: info.method,
519
+ headers: info.headers,
520
+ body: info.body,
521
+ mode: info.mode,
522
+ credentials: info.credentials,
523
+ cache: info.cache,
524
+ redirect: info.redirect,
525
+ referrer: info.referrer,
526
+ integrity: info.integrity
527
+ };
528
+ } else {
529
+ url = info.toString();
530
+ }
531
+
532
+ if (url.startsWith(config.prerender.origin + '/')) {
533
+ const request = new Request(url, opts);
534
+ const response = await server.respond(request, {
535
+ getClientAddress,
536
+ prerendering: {
537
+ dependencies: new Map()
538
+ }
539
+ });
540
+
541
+ const decoded = new URL$1(url).pathname;
542
+
543
+ save(
544
+ 'dependencies',
545
+ response,
546
+ Buffer.from(await response.clone().arrayBuffer()),
547
+ decoded,
548
+ encodeURI(decoded),
549
+ null,
550
+ 'fetched'
551
+ );
552
+
553
+ return response;
554
+ }
555
+
556
+ return fetch(info, init);
557
+ };
558
+
559
+ const server_root = join(config.outDir, 'output');
560
+
561
+ /** @type {import('types').ServerModule} */
562
+ const { Server, override } = await import(pathToFileURL(`${server_root}/server/index.js`).href);
563
+
564
+ /** @type {import('types').SSRManifest} */
565
+ const manifest = (await import(pathToFileURL(`${server_root}/server/manifest.js`).href)).manifest;
566
+
567
+ override({
568
+ paths: config.paths,
569
+ prerendering: true,
570
+ read: (file) => readFileSync(join(config.files.assets, file))
571
+ });
572
+
573
+ const server = new Server(manifest);
574
+
575
+ const error = normalise_error_handler(log, config);
576
+
577
+ const q = queue(config.prerender.concurrency);
578
+
579
+ /**
580
+ * @param {string} path
581
+ * @param {boolean} is_html
582
+ */
583
+ function output_filename(path, is_html) {
584
+ const file = path.slice(config.paths.base.length + 1) || 'index.html';
585
+
586
+ if (is_html && !file.endsWith('.html')) {
587
+ return file + (file.endsWith('/') ? 'index.html' : '.html');
588
+ }
589
+
590
+ return file;
591
+ }
592
+
593
+ const files = new Set(walk(client_out_dir).map(posixify));
594
+ const seen = new Set();
595
+ const written = new Set();
596
+
597
+ /**
598
+ * @param {string | null} referrer
599
+ * @param {string} decoded
600
+ * @param {string} [encoded]
601
+ */
602
+ function enqueue(referrer, decoded, encoded) {
603
+ if (seen.has(decoded)) return;
604
+ seen.add(decoded);
605
+
606
+ const file = decoded.slice(config.paths.base.length + 1);
607
+ if (files.has(file)) return;
608
+
609
+ return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer));
610
+ }
611
+
612
+ /**
613
+ * @param {string} decoded
614
+ * @param {string} encoded
615
+ * @param {string?} referrer
616
+ */
617
+ async function visit(decoded, encoded, referrer) {
618
+ if (!decoded.startsWith(config.paths.base)) {
619
+ error({ status: 404, path: decoded, referrer, referenceType: 'linked' });
620
+ return;
621
+ }
622
+
623
+ /** @type {Map<string, import('types').PrerenderDependency>} */
624
+ const dependencies = new Map();
625
+
626
+ const response = await server.respond(new Request(config.prerender.origin + encoded), {
627
+ getClientAddress,
628
+ prerendering: {
629
+ dependencies
630
+ }
631
+ });
632
+
633
+ const body = Buffer.from(await response.arrayBuffer());
634
+
635
+ save('pages', response, body, decoded, encoded, referrer, 'linked');
636
+
637
+ for (const [dependency_path, result] of dependencies) {
638
+ // this seems circuitous, but using new URL allows us to not care
639
+ // whether dependency_path is encoded or not
640
+ const encoded_dependency_path = new URL$1(dependency_path, 'http://localhost').pathname;
641
+ const decoded_dependency_path = decodeURI(encoded_dependency_path);
642
+
643
+ const body = result.body ?? new Uint8Array(await result.response.arrayBuffer());
644
+ save(
645
+ 'dependencies',
646
+ result.response,
647
+ body,
648
+ decoded_dependency_path,
649
+ encoded_dependency_path,
650
+ decoded,
651
+ 'fetched'
652
+ );
653
+ }
654
+
655
+ if (config.prerender.crawl && response.headers.get('content-type') === 'text/html') {
656
+ for (const href of crawl(body.toString())) {
657
+ if (href.startsWith('data:') || href.startsWith('#')) continue;
658
+
659
+ const resolved = resolve(encoded, href);
660
+ if (!is_root_relative(resolved)) continue;
661
+
662
+ const { pathname, search } = new URL$1(resolved, 'http://localhost');
663
+
664
+ enqueue(decoded, decodeURI(pathname), pathname);
665
+ }
666
+ }
667
+ }
668
+
669
+ /**
670
+ * @param {'pages' | 'dependencies'} category
671
+ * @param {Response} response
672
+ * @param {string | Uint8Array} body
673
+ * @param {string} decoded
674
+ * @param {string} encoded
675
+ * @param {string | null} referrer
676
+ * @param {'linked' | 'fetched'} referenceType
677
+ */
678
+ function save(category, response, body, decoded, encoded, referrer, referenceType) {
679
+ const response_type = Math.floor(response.status / 100);
680
+ const type = /** @type {string} */ (response.headers.get('content-type'));
681
+ const is_html = response_type === REDIRECT || type === 'text/html';
682
+
683
+ const file = output_filename(decoded, is_html);
684
+ const dest = `${config.outDir}/output/prerendered/${category}/${file}`;
685
+
686
+ if (written.has(file)) return;
687
+
688
+ if (response_type === REDIRECT) {
689
+ const location = response.headers.get('location');
690
+
691
+ if (location) {
692
+ const resolved = resolve(encoded, location);
693
+ if (is_root_relative(resolved)) {
694
+ enqueue(decoded, decodeURI(resolved), resolved);
695
+ }
696
+
697
+ if (!response.headers.get('x-sveltekit-normalize')) {
698
+ mkdirp(dirname(dest));
699
+
700
+ log.warn(`${response.status} ${decoded} -> ${location}`);
701
+
702
+ writeFileSync(
703
+ dest,
704
+ `<meta http-equiv="refresh" content=${escape_html_attr(`0;url=${location}`)}>`
705
+ );
706
+
707
+ written.add(file);
708
+
709
+ if (!prerendered.redirects.has(decoded)) {
710
+ prerendered.redirects.set(decoded, {
711
+ status: response.status,
712
+ location: resolved
713
+ });
714
+
715
+ prerendered.paths.push(decoded);
716
+ }
717
+ }
718
+ } else {
719
+ log.warn(`location header missing on redirect received from ${decoded}`);
720
+ }
721
+
722
+ return;
723
+ }
724
+
725
+ if (response.status === 200) {
726
+ mkdirp(dirname(dest));
727
+
728
+ log.info(`${response.status} ${decoded}`);
729
+ writeFileSync(dest, body);
730
+ written.add(file);
731
+
732
+ if (is_html) {
733
+ prerendered.pages.set(decoded, {
734
+ file
735
+ });
736
+ } else {
737
+ prerendered.assets.set(decoded, {
738
+ type
739
+ });
740
+ }
741
+
742
+ prerendered.paths.push(decoded);
743
+ } else if (response_type !== OK) {
744
+ error({ status: response.status, path: decoded, referrer, referenceType });
745
+ }
746
+ }
747
+
748
+ if (config.prerender.enabled) {
749
+ for (const entry of config.prerender.entries) {
750
+ if (entry === '*') {
751
+ /** @type {import('types').ManifestData} */
752
+ const { routes } = (await import(pathToFileURL(manifest_path).href)).manifest._;
753
+ const entries = routes
754
+ .map((route) => (route.type === 'page' ? route.path : ''))
755
+ .filter(Boolean);
756
+
757
+ for (const entry of entries) {
758
+ enqueue(null, config.paths.base + entry); // TODO can we pre-normalize these?
759
+ }
760
+ } else {
761
+ enqueue(null, config.paths.base + entry);
762
+ }
763
+ }
764
+
765
+ await q.done();
766
+ }
767
+
768
+ const rendered = await server.respond(new Request(config.prerender.origin + '/[fallback]'), {
769
+ getClientAddress,
770
+ prerendering: {
771
+ fallback: true,
772
+ dependencies: new Map()
773
+ }
774
+ });
775
+
776
+ const file = `${config.outDir}/output/prerendered/fallback.html`;
777
+ mkdirp(dirname(file));
778
+ writeFileSync(file, await rendered.text());
779
+
780
+ output_and_exit(prerendered);
781
+ }
782
+
783
+ /** @return {string} */
784
+ function getClientAddress() {
785
+ throw new Error('Cannot read clientAddress during prerendering');
786
+ }
787
+
788
+ export { prerender };