@sveltejs/kit 1.0.0-next.32 → 1.0.0-next.320

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 (73) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +20 -0
  3. package/assets/app/navigation.js +24 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/app/stores.js +97 -0
  6. package/assets/client/singletons.js +13 -0
  7. package/assets/client/start.js +1687 -0
  8. package/assets/components/error.svelte +18 -2
  9. package/assets/env.js +8 -0
  10. package/assets/paths.js +13 -0
  11. package/assets/server/index.js +3411 -0
  12. package/dist/chunks/amp_hook.js +56 -0
  13. package/dist/chunks/cert.js +28154 -0
  14. package/dist/chunks/constants.js +663 -0
  15. package/dist/chunks/filesystem.js +110 -0
  16. package/dist/chunks/index.js +515 -0
  17. package/dist/chunks/index2.js +1335 -0
  18. package/dist/chunks/index3.js +118 -0
  19. package/dist/chunks/index4.js +186 -0
  20. package/dist/chunks/index5.js +251 -0
  21. package/dist/chunks/index6.js +15737 -0
  22. package/dist/chunks/index7.js +4207 -0
  23. package/dist/chunks/misc.js +78 -0
  24. package/dist/chunks/multipart-parser.js +449 -0
  25. package/dist/chunks/object.js +83 -0
  26. package/dist/chunks/sync.js +974 -0
  27. package/dist/chunks/url.js +56 -0
  28. package/dist/cli.js +1024 -65
  29. package/dist/hooks.js +28 -0
  30. package/dist/install-fetch.js +6518 -0
  31. package/dist/node.js +94 -0
  32. package/package.json +95 -62
  33. package/svelte-kit.js +0 -1
  34. package/types/ambient.d.ts +298 -0
  35. package/types/index.d.ts +278 -0
  36. package/types/internal.d.ts +320 -0
  37. package/types/private.d.ts +242 -0
  38. package/CHANGELOG.md +0 -350
  39. package/assets/runtime/app/navigation.js +0 -23
  40. package/assets/runtime/app/navigation.js.map +0 -1
  41. package/assets/runtime/app/paths.js +0 -2
  42. package/assets/runtime/app/paths.js.map +0 -1
  43. package/assets/runtime/app/stores.js +0 -78
  44. package/assets/runtime/app/stores.js.map +0 -1
  45. package/assets/runtime/internal/singletons.js +0 -15
  46. package/assets/runtime/internal/singletons.js.map +0 -1
  47. package/assets/runtime/internal/start.js +0 -591
  48. package/assets/runtime/internal/start.js.map +0 -1
  49. package/assets/runtime/utils-85ebcc60.js +0 -18
  50. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  51. package/dist/api.js +0 -32
  52. package/dist/api.js.map +0 -1
  53. package/dist/cli.js.map +0 -1
  54. package/dist/create_app.js +0 -577
  55. package/dist/create_app.js.map +0 -1
  56. package/dist/index.js +0 -329
  57. package/dist/index.js.map +0 -1
  58. package/dist/index2.js +0 -14363
  59. package/dist/index2.js.map +0 -1
  60. package/dist/index3.js +0 -544
  61. package/dist/index3.js.map +0 -1
  62. package/dist/index4.js +0 -71
  63. package/dist/index4.js.map +0 -1
  64. package/dist/index5.js +0 -465
  65. package/dist/index5.js.map +0 -1
  66. package/dist/index6.js +0 -727
  67. package/dist/index6.js.map +0 -1
  68. package/dist/renderer.js +0 -2413
  69. package/dist/renderer.js.map +0 -1
  70. package/dist/standard.js +0 -100
  71. package/dist/standard.js.map +0 -1
  72. package/dist/utils.js +0 -57
  73. package/dist/utils.js.map +0 -1
@@ -0,0 +1,1335 @@
1
+ import fs__default, { readFileSync, writeFileSync } from 'fs';
2
+ import path__default, { join, dirname } from 'path';
3
+ import { p as posixify, m as mkdirp, r as rimraf } from './filesystem.js';
4
+ import { all } from './sync.js';
5
+ import { p as print_config_conflicts, b as get_aliases, r as resolve_entry, g as get_runtime_path, l as load_template } from '../cli.js';
6
+ import { g as generate_manifest } from './index3.js';
7
+ import vite from 'vite';
8
+ import { s } from './misc.js';
9
+ import { d as deep_merge } from './object.js';
10
+ import { n as normalize_path, r as resolve, i as is_root_relative } from './url.js';
11
+ import { svelte } from '@sveltejs/vite-plugin-svelte';
12
+ import { pathToFileURL, URL as URL$1 } from 'url';
13
+ import { installFetch } from '../install-fetch.js';
14
+ import 'sade';
15
+ import 'child_process';
16
+ import 'net';
17
+ import 'os';
18
+ import 'node:http';
19
+ import 'node:https';
20
+ import 'node:zlib';
21
+ import 'node:stream';
22
+ import 'node:util';
23
+ import 'node:url';
24
+
25
+ /**
26
+ * @param {{
27
+ * cwd: string;
28
+ * assets_base: string;
29
+ * config: import('types').ValidatedConfig;
30
+ * manifest_data: import('types').ManifestData;
31
+ * output_dir: string;
32
+ * service_worker_entry_file: string | null;
33
+ * }} options
34
+ * @param {import('types').Prerendered} prerendered
35
+ * @param {import('vite').Manifest} client_manifest
36
+ */
37
+ async function build_service_worker(
38
+ { cwd, assets_base, config, manifest_data, output_dir, service_worker_entry_file },
39
+ prerendered,
40
+ client_manifest
41
+ ) {
42
+ // TODO add any assets referenced in template .html file, e.g. favicon?
43
+ const app_files = new Set();
44
+ for (const key in client_manifest) {
45
+ const { file, css } = client_manifest[key];
46
+ app_files.add(file);
47
+ if (css) {
48
+ css.forEach((file) => {
49
+ app_files.add(file);
50
+ });
51
+ }
52
+ }
53
+
54
+ const service_worker = `${config.kit.outDir}/generated/service-worker.js`;
55
+
56
+ fs__default.writeFileSync(
57
+ service_worker,
58
+ `
59
+ // TODO remove for 1.0
60
+ export const timestamp = {
61
+ toString: () => {
62
+ throw new Error('\`timestamp\` has been removed from $service-worker. Use \`version\` instead');
63
+ }
64
+ };
65
+
66
+ export const build = [
67
+ ${Array.from(app_files)
68
+ .map((file) => `${s(`${config.kit.paths.base}/${config.kit.appDir}/${file}`)}`)
69
+ .join(',\n\t\t\t\t')}
70
+ ];
71
+
72
+ export const files = [
73
+ ${manifest_data.assets
74
+ .filter((asset) => config.kit.serviceWorker.files(asset.file))
75
+ .map((asset) => `${s(`${config.kit.paths.base}/${asset.file}`)}`)
76
+ .join(',\n\t\t\t\t')}
77
+ ];
78
+
79
+ export const prerendered = [
80
+ ${prerendered.paths
81
+ .map((path) => s(normalize_path(path, config.kit.trailingSlash)))
82
+ .join(',\n\t\t\t\t')}
83
+ ];
84
+
85
+ export const version = ${s(config.kit.version.name)};
86
+ `
87
+ .replace(/^\t{3}/gm, '')
88
+ .trim()
89
+ );
90
+
91
+ /** @type {[any, string[]]} */
92
+ const [merged_config, conflicts] = deep_merge(await config.kit.vite(), {
93
+ configFile: false,
94
+ root: cwd,
95
+ base: assets_base,
96
+ build: {
97
+ lib: {
98
+ entry: service_worker_entry_file,
99
+ name: 'app',
100
+ formats: ['es']
101
+ },
102
+ rollupOptions: {
103
+ output: {
104
+ entryFileNames: 'service-worker.js'
105
+ }
106
+ },
107
+ outDir: `${output_dir}/client`,
108
+ emptyOutDir: false
109
+ },
110
+ resolve: {
111
+ alias: {
112
+ '$service-worker': service_worker,
113
+ $lib: config.kit.files.lib
114
+ }
115
+ }
116
+ });
117
+
118
+ print_config_conflicts(conflicts, 'kit.vite.', 'build_service_worker');
119
+
120
+ await vite.build(merged_config);
121
+ }
122
+
123
+ /**
124
+ * @typedef {import('rollup').RollupOutput} RollupOutput
125
+ * @typedef {import('rollup').OutputChunk} OutputChunk
126
+ * @typedef {import('rollup').OutputAsset} OutputAsset
127
+ */
128
+
129
+ /** @param {import('vite').UserConfig} config */
130
+ async function create_build(config) {
131
+ const { output } = /** @type {RollupOutput} */ (await vite.build(config));
132
+
133
+ const chunks = output.filter(
134
+ /** @returns {output is OutputChunk} */ (output) => output.type === 'chunk'
135
+ );
136
+
137
+ const assets = output.filter(
138
+ /** @returns {output is OutputAsset} */ (output) => output.type === 'asset'
139
+ );
140
+
141
+ return { chunks, assets };
142
+ }
143
+
144
+ /**
145
+ * @param {string} file
146
+ * @param {import('vite').Manifest} manifest
147
+ * @param {Set<string>} css
148
+ * @param {Set<string>} js
149
+ */
150
+ function find_deps(file, manifest, js, css) {
151
+ const chunk = manifest[file];
152
+
153
+ if (js.has(chunk.file)) return;
154
+ js.add(chunk.file);
155
+
156
+ if (chunk.css) {
157
+ chunk.css.forEach((file) => css.add(file));
158
+ }
159
+
160
+ if (chunk.imports) {
161
+ chunk.imports.forEach((file) => find_deps(file, manifest, js, css));
162
+ }
163
+ }
164
+
165
+ /**
166
+ * @param {{
167
+ * cwd: string;
168
+ * assets_base: string;
169
+ * config: import('types').ValidatedConfig
170
+ * manifest_data: import('types').ManifestData
171
+ * output_dir: string;
172
+ * client_entry_file: string;
173
+ * service_worker_entry_file: string | null;
174
+ * service_worker_register: boolean;
175
+ * }} options
176
+ */
177
+ async function build_client({
178
+ cwd,
179
+ assets_base,
180
+ config,
181
+ manifest_data,
182
+ output_dir,
183
+ client_entry_file
184
+ }) {
185
+ process.env.VITE_SVELTEKIT_APP_VERSION = config.kit.version.name;
186
+ process.env.VITE_SVELTEKIT_APP_VERSION_FILE = `${config.kit.appDir}/version.json`;
187
+ process.env.VITE_SVELTEKIT_APP_VERSION_POLL_INTERVAL = `${config.kit.version.pollInterval}`;
188
+
189
+ process.env.VITE_SVELTEKIT_AMP = config.kit.amp ? 'true' : '';
190
+
191
+ const client_out_dir = `${output_dir}/client/${config.kit.appDir}`;
192
+
193
+ /** @type {Record<string, string>} */
194
+ const input = {
195
+ start: path__default.resolve(cwd, client_entry_file)
196
+ };
197
+
198
+ // This step is optional — Vite/Rollup will create the necessary chunks
199
+ // for everything regardless — but it means that entry chunks reflect
200
+ // their location in the source code, which is helpful for debugging
201
+ manifest_data.components.forEach((file) => {
202
+ const resolved = path__default.resolve(cwd, file);
203
+ const relative = path__default.relative(config.kit.files.routes, resolved);
204
+
205
+ const name = relative.startsWith('..')
206
+ ? path__default.basename(file)
207
+ : posixify(path__default.join('pages', relative));
208
+ input[name] = resolved;
209
+ });
210
+
211
+ /** @type {[any, string[]]} */
212
+ const [merged_config, conflicts] = deep_merge(await config.kit.vite(), {
213
+ configFile: false,
214
+ root: cwd,
215
+ base: assets_base,
216
+ build: {
217
+ cssCodeSplit: true,
218
+ manifest: true,
219
+ outDir: client_out_dir,
220
+ polyfillDynamicImport: false,
221
+ rollupOptions: {
222
+ input,
223
+ output: {
224
+ entryFileNames: '[name]-[hash].js',
225
+ chunkFileNames: 'chunks/[name]-[hash].js',
226
+ assetFileNames: 'assets/[name]-[hash][extname]'
227
+ },
228
+ preserveEntrySignatures: 'strict'
229
+ }
230
+ },
231
+ resolve: {
232
+ alias: get_aliases(config)
233
+ },
234
+ plugins: [
235
+ svelte({
236
+ extensions: config.extensions,
237
+ // In AMP mode, we know that there are no conditional component imports. In that case, we
238
+ // don't need to include CSS for components that are imported but unused, so we can just
239
+ // include rendered CSS.
240
+ // This would also apply if hydrate and router are both false, but we don't know if one
241
+ // has been enabled at the page level, so we don't do anything there.
242
+ emitCss: !config.kit.amp,
243
+ compilerOptions: {
244
+ hydratable: !!config.kit.browser.hydrate
245
+ }
246
+ })
247
+ ],
248
+ // prevent Vite copying the contents of `config.kit.files.assets`,
249
+ // if it happens to be 'public' instead of 'static'
250
+ publicDir: false
251
+ });
252
+
253
+ print_config_conflicts(conflicts, 'kit.vite.', 'build_client');
254
+
255
+ const { chunks, assets } = await create_build(merged_config);
256
+
257
+ /** @type {import('vite').Manifest} */
258
+ const vite_manifest = JSON.parse(fs__default.readFileSync(`${client_out_dir}/manifest.json`, 'utf-8'));
259
+
260
+ const entry = posixify(client_entry_file);
261
+ const entry_js = new Set();
262
+ const entry_css = new Set();
263
+ find_deps(entry, vite_manifest, entry_js, entry_css);
264
+
265
+ fs__default.writeFileSync(
266
+ `${client_out_dir}/version.json`,
267
+ JSON.stringify({ version: process.env.VITE_SVELTEKIT_APP_VERSION })
268
+ );
269
+
270
+ return {
271
+ assets,
272
+ chunks,
273
+ entry: {
274
+ file: vite_manifest[entry].file,
275
+ js: Array.from(entry_js),
276
+ css: Array.from(entry_css)
277
+ },
278
+ vite_manifest
279
+ };
280
+ }
281
+
282
+ /**
283
+ * @param {{
284
+ * hooks: string;
285
+ * config: import('types').ValidatedConfig;
286
+ * has_service_worker: boolean;
287
+ * runtime: string;
288
+ * template: string;
289
+ * }} opts
290
+ */
291
+ const server_template = ({ config, hooks, has_service_worker, runtime, template }) => `
292
+ import root from '__GENERATED__/root.svelte';
293
+ import { respond } from '${runtime}/server/index.js';
294
+ import { set_paths, assets, base } from '${runtime}/paths.js';
295
+ import { set_prerendering } from '${runtime}/env.js';
296
+
297
+ const template = ({ head, body, assets, nonce }) => ${s(template)
298
+ .replace('%svelte.head%', '" + head + "')
299
+ .replace('%svelte.body%', '" + body + "')
300
+ .replace(/%svelte\.assets%/g, '" + assets + "')
301
+ .replace(/%svelte\.nonce%/g, '" + nonce + "')};
302
+
303
+ let read = null;
304
+
305
+ set_paths(${s(config.kit.paths)});
306
+
307
+ let default_protocol = 'https';
308
+
309
+ // allow paths to be globally overridden
310
+ // in svelte-kit preview and in prerendering
311
+ export function override(settings) {
312
+ default_protocol = settings.protocol || default_protocol;
313
+ set_paths(settings.paths);
314
+ set_prerendering(settings.prerendering);
315
+ read = settings.read;
316
+ }
317
+
318
+ export class Server {
319
+ constructor(manifest) {
320
+ this.options = {
321
+ amp: ${config.kit.amp},
322
+ csp: ${s(config.kit.csp)},
323
+ dev: false,
324
+ floc: ${config.kit.floc},
325
+ get_stack: error => String(error), // for security
326
+ handle_error: (error, event) => {
327
+ this.options.hooks.handleError({
328
+ error,
329
+ event,
330
+
331
+ // TODO remove for 1.0
332
+ // @ts-expect-error
333
+ get request() {
334
+ throw new Error('request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details');
335
+ }
336
+ });
337
+ error.stack = this.options.get_stack(error);
338
+ },
339
+ hooks: null,
340
+ hydrate: ${s(config.kit.browser.hydrate)},
341
+ manifest,
342
+ method_override: ${s(config.kit.methodOverride)},
343
+ paths: { base, assets },
344
+ prefix: assets + '/${config.kit.appDir}/',
345
+ prerender: ${config.kit.prerender.enabled},
346
+ read,
347
+ root,
348
+ service_worker: ${has_service_worker ? "base + '/service-worker.js'" : 'null'},
349
+ router: ${s(config.kit.browser.router)},
350
+ template,
351
+ template_contains_nonce: ${template.includes('%svelte.nonce%')},
352
+ trailing_slash: ${s(config.kit.trailingSlash)}
353
+ };
354
+ }
355
+
356
+ async respond(request, options = {}) {
357
+ if (!(request instanceof Request)) {
358
+ throw new Error('The first argument to server.respond must be a Request object. See https://github.com/sveltejs/kit/pull/3384 for details');
359
+ }
360
+
361
+ if (!this.options.hooks) {
362
+ const module = await import(${s(hooks)});
363
+ this.options.hooks = {
364
+ getSession: module.getSession || (() => ({})),
365
+ handle: module.handle || (({ event, resolve }) => resolve(event)),
366
+ handleError: module.handleError || (({ error }) => console.error(error.stack)),
367
+ externalFetch: module.externalFetch || fetch
368
+ };
369
+ }
370
+
371
+ return respond(request, this.options, options);
372
+ }
373
+ }
374
+ `;
375
+
376
+ /**
377
+ * @param {{
378
+ * cwd: string;
379
+ * assets_base: string;
380
+ * config: import('types').ValidatedConfig
381
+ * manifest_data: import('types').ManifestData
382
+ * build_dir: string;
383
+ * output_dir: string;
384
+ * service_worker_entry_file: string | null;
385
+ * service_worker_register: boolean;
386
+ * }} options
387
+ * @param {{ vite_manifest: import('vite').Manifest, assets: import('rollup').OutputAsset[] }} client
388
+ */
389
+ async function build_server(
390
+ {
391
+ cwd,
392
+ assets_base,
393
+ config,
394
+ manifest_data,
395
+ build_dir,
396
+ output_dir,
397
+ service_worker_entry_file,
398
+ service_worker_register
399
+ },
400
+ client
401
+ ) {
402
+ let hooks_file = resolve_entry(config.kit.files.hooks);
403
+ if (!hooks_file || !fs__default.existsSync(hooks_file)) {
404
+ hooks_file = path__default.join(config.kit.outDir, 'build/hooks.js');
405
+ fs__default.writeFileSync(hooks_file, '');
406
+ }
407
+
408
+ /** @type {Record<string, string>} */
409
+ const input = {
410
+ index: `${build_dir}/index.js`
411
+ };
412
+
413
+ // add entry points for every endpoint...
414
+ manifest_data.routes.forEach((route) => {
415
+ const file = route.type === 'endpoint' ? route.file : route.shadow;
416
+
417
+ if (file) {
418
+ const resolved = path__default.resolve(cwd, file);
419
+ const relative = path__default.relative(config.kit.files.routes, resolved);
420
+ const name = posixify(path__default.join('entries/endpoints', relative.replace(/\.js$/, '')));
421
+ input[name] = resolved;
422
+ }
423
+ });
424
+
425
+ // ...and every component used by pages...
426
+ manifest_data.components.forEach((file) => {
427
+ const resolved = path__default.resolve(cwd, file);
428
+ const relative = path__default.relative(config.kit.files.routes, resolved);
429
+
430
+ const name = relative.startsWith('..')
431
+ ? posixify(path__default.join('entries/fallbacks', path__default.basename(file)))
432
+ : posixify(path__default.join('entries/pages', relative));
433
+ input[name] = resolved;
434
+ });
435
+
436
+ // ...and every matcher
437
+ Object.entries(manifest_data.matchers).forEach(([key, file]) => {
438
+ const name = posixify(path__default.join('entries/matchers', key));
439
+ input[name] = path__default.resolve(cwd, file);
440
+ });
441
+
442
+ /** @type {(file: string) => string} */
443
+ const app_relative = (file) => {
444
+ const relative_file = path__default.relative(build_dir, path__default.resolve(cwd, file));
445
+ return relative_file[0] === '.' ? relative_file : `./${relative_file}`;
446
+ };
447
+
448
+ fs__default.writeFileSync(
449
+ input.index,
450
+ server_template({
451
+ config,
452
+ hooks: app_relative(hooks_file),
453
+ has_service_worker: service_worker_register && !!service_worker_entry_file,
454
+ runtime: get_runtime_path(config),
455
+ template: load_template(cwd, config)
456
+ })
457
+ );
458
+
459
+ /** @type {import('vite').UserConfig} */
460
+ const vite_config = await config.kit.vite();
461
+
462
+ const default_config = {
463
+ build: {
464
+ target: 'es2020'
465
+ },
466
+ ssr: {
467
+ // when developing against the Kit src code, we want to ensure that
468
+ // our dependencies are bundled so that apps don't need to install
469
+ // them as peerDependencies
470
+ noExternal: []
471
+
472
+ }
473
+ };
474
+
475
+ // don't warn on overriding defaults
476
+ const [modified_vite_config] = deep_merge(default_config, vite_config);
477
+
478
+ /** @type {[any, string[]]} */
479
+ const [merged_config, conflicts] = deep_merge(modified_vite_config, {
480
+ configFile: false,
481
+ root: cwd,
482
+ base: assets_base,
483
+ build: {
484
+ ssr: true,
485
+ outDir: `${output_dir}/server`,
486
+ manifest: true,
487
+ polyfillDynamicImport: false,
488
+ rollupOptions: {
489
+ input,
490
+ output: {
491
+ format: 'esm',
492
+ entryFileNames: '[name].js',
493
+ chunkFileNames: 'chunks/[name]-[hash].js',
494
+ assetFileNames: 'assets/[name]-[hash][extname]'
495
+ },
496
+ preserveEntrySignatures: 'strict'
497
+ }
498
+ },
499
+ plugins: [
500
+ svelte({
501
+ extensions: config.extensions,
502
+ compilerOptions: {
503
+ hydratable: !!config.kit.browser.hydrate
504
+ }
505
+ })
506
+ ],
507
+ resolve: {
508
+ alias: get_aliases(config)
509
+ }
510
+ });
511
+
512
+ print_config_conflicts(conflicts, 'kit.vite.', 'build_server');
513
+
514
+ process.env.VITE_SVELTEKIT_ADAPTER_NAME = config.kit.adapter?.name;
515
+
516
+ const { chunks } = await create_build(merged_config);
517
+
518
+ /** @type {import('vite').Manifest} */
519
+ const vite_manifest = JSON.parse(fs__default.readFileSync(`${output_dir}/server/manifest.json`, 'utf-8'));
520
+
521
+ mkdirp(`${output_dir}/server/nodes`);
522
+ mkdirp(`${output_dir}/server/stylesheets`);
523
+
524
+ const stylesheet_lookup = new Map();
525
+
526
+ client.assets.forEach((asset) => {
527
+ if (asset.fileName.endsWith('.css')) {
528
+ if (config.kit.amp || asset.source.length < config.kit.inlineStyleThreshold) {
529
+ const index = stylesheet_lookup.size;
530
+ const file = `${output_dir}/server/stylesheets/${index}.js`;
531
+
532
+ fs__default.writeFileSync(file, `// ${asset.fileName}\nexport default ${s(asset.source)};`);
533
+ stylesheet_lookup.set(asset.fileName, index);
534
+ }
535
+ }
536
+ });
537
+
538
+ manifest_data.components.forEach((component, i) => {
539
+ const file = `${output_dir}/server/nodes/${i}.js`;
540
+
541
+ const js = new Set();
542
+ const css = new Set();
543
+ find_deps(component, client.vite_manifest, js, css);
544
+
545
+ const imports = [`import * as module from '../${vite_manifest[component].file}';`];
546
+
547
+ const exports = [
548
+ 'export { module };',
549
+ `export const entry = '${client.vite_manifest[component].file}';`,
550
+ `export const js = ${s(Array.from(js))};`,
551
+ `export const css = ${s(Array.from(css))};`
552
+ ];
553
+
554
+ /** @type {string[]} */
555
+ const styles = [];
556
+
557
+ css.forEach((file) => {
558
+ if (stylesheet_lookup.has(file)) {
559
+ const index = stylesheet_lookup.get(file);
560
+ const name = `stylesheet_${index}`;
561
+ imports.push(`import ${name} from '../stylesheets/${index}.js';`);
562
+ styles.push(`\t${s(file)}: ${name}`);
563
+ }
564
+ });
565
+
566
+ if (styles.length > 0) {
567
+ exports.push(`export const styles = {\n${styles.join(',\n')}\n};`);
568
+ }
569
+
570
+ fs__default.writeFileSync(file, `${imports.join('\n')}\n\n${exports.join('\n')}\n`);
571
+ });
572
+
573
+ return {
574
+ chunks,
575
+ vite_manifest,
576
+ methods: get_methods(cwd, chunks, manifest_data)
577
+ };
578
+ }
579
+
580
+ /** @type {Record<string, string>} */
581
+ const method_names = {
582
+ get: 'get',
583
+ head: 'head',
584
+ post: 'post',
585
+ put: 'put',
586
+ del: 'delete',
587
+ patch: 'patch'
588
+ };
589
+
590
+ /**
591
+ * @param {string} cwd
592
+ * @param {import('rollup').OutputChunk[]} output
593
+ * @param {import('types').ManifestData} manifest_data
594
+ */
595
+ function get_methods(cwd, output, manifest_data) {
596
+ /** @type {Record<string, string[]>} */
597
+ const lookup = {};
598
+ output.forEach((chunk) => {
599
+ if (!chunk.facadeModuleId) return;
600
+ const id = chunk.facadeModuleId.slice(cwd.length + 1);
601
+ lookup[id] = chunk.exports;
602
+ });
603
+
604
+ /** @type {Record<string, import('types').HttpMethod[]>} */
605
+ const methods = {};
606
+ manifest_data.routes.forEach((route) => {
607
+ const file = route.type === 'endpoint' ? route.file : route.shadow;
608
+
609
+ if (file && lookup[file]) {
610
+ methods[file] = lookup[file]
611
+ .map((x) => /** @type {import('types').HttpMethod} */ (method_names[x]))
612
+ .filter(Boolean);
613
+ }
614
+ });
615
+
616
+ return methods;
617
+ }
618
+
619
+ /** @typedef {{
620
+ * fn: () => Promise<any>,
621
+ * fulfil: (value: any) => void,
622
+ * reject: (error: Error) => void
623
+ * }} Task */
624
+
625
+ /** @param {number} concurrency */
626
+ function queue(concurrency) {
627
+ /** @type {Task[]} */
628
+ const tasks = [];
629
+
630
+ let current = 0;
631
+
632
+ /** @type {(value?: any) => void} */
633
+ let fulfil;
634
+
635
+ /** @type {(error: Error) => void} */
636
+ let reject;
637
+
638
+ let closed = false;
639
+
640
+ const done = new Promise((f, r) => {
641
+ fulfil = f;
642
+ reject = r;
643
+ });
644
+
645
+ done.catch(() => {
646
+ // this is necessary in case a catch handler is never added
647
+ // to the done promise by the user
648
+ });
649
+
650
+ function dequeue() {
651
+ if (current < concurrency) {
652
+ const task = tasks.shift();
653
+
654
+ if (task) {
655
+ current += 1;
656
+ const promise = Promise.resolve(task.fn());
657
+
658
+ promise
659
+ .then(task.fulfil, (err) => {
660
+ task.reject(err);
661
+ reject(err);
662
+ })
663
+ .then(() => {
664
+ current -= 1;
665
+ dequeue();
666
+ });
667
+ } else if (current === 0) {
668
+ closed = true;
669
+ fulfil();
670
+ }
671
+ }
672
+ }
673
+
674
+ return {
675
+ /** @param {() => any} fn */
676
+ add: (fn) => {
677
+ if (closed) throw new Error('Cannot add tasks to a queue that has ended');
678
+
679
+ const promise = new Promise((fulfil, reject) => {
680
+ tasks.push({ fn, fulfil, reject });
681
+ });
682
+
683
+ dequeue();
684
+ return promise;
685
+ },
686
+
687
+ done: () => {
688
+ if (current === 0) {
689
+ closed = true;
690
+ fulfil();
691
+ }
692
+
693
+ return done;
694
+ }
695
+ };
696
+ }
697
+
698
+ const DOCTYPE = 'DOCTYPE';
699
+ const CDATA_OPEN = '[CDATA[';
700
+ const CDATA_CLOSE = ']]>';
701
+ const COMMENT_OPEN = '--';
702
+ const COMMENT_CLOSE = '-->';
703
+
704
+ const TAG_OPEN = /[a-zA-Z]/;
705
+ const TAG_CHAR = /[a-zA-Z0-9]/;
706
+ const ATTRIBUTE_NAME = /[^\t\n\f />"'=]/;
707
+
708
+ const WHITESPACE = /[\s\n\r]/;
709
+
710
+ /** @param {string} html */
711
+ function crawl(html) {
712
+ /** @type {string[]} */
713
+ const hrefs = [];
714
+
715
+ let i = 0;
716
+ main: while (i < html.length) {
717
+ const char = html[i];
718
+
719
+ if (char === '<') {
720
+ if (html[i + 1] === '!') {
721
+ i += 2;
722
+
723
+ if (html.slice(i, i + DOCTYPE.length).toUpperCase() === DOCTYPE) {
724
+ i += DOCTYPE.length;
725
+ while (i < html.length) {
726
+ if (html[i++] === '>') {
727
+ continue main;
728
+ }
729
+ }
730
+ }
731
+
732
+ // skip cdata
733
+ if (html.slice(i, i + CDATA_OPEN.length) === CDATA_OPEN) {
734
+ i += CDATA_OPEN.length;
735
+ while (i < html.length) {
736
+ if (html.slice(i, i + CDATA_CLOSE.length) === CDATA_CLOSE) {
737
+ i += CDATA_CLOSE.length;
738
+ continue main;
739
+ }
740
+
741
+ i += 1;
742
+ }
743
+ }
744
+
745
+ // skip comments
746
+ if (html.slice(i, i + COMMENT_OPEN.length) === COMMENT_OPEN) {
747
+ i += COMMENT_OPEN.length;
748
+ while (i < html.length) {
749
+ if (html.slice(i, i + COMMENT_CLOSE.length) === COMMENT_CLOSE) {
750
+ i += COMMENT_CLOSE.length;
751
+ continue main;
752
+ }
753
+
754
+ i += 1;
755
+ }
756
+ }
757
+ }
758
+
759
+ // parse opening tags
760
+ const start = ++i;
761
+ if (TAG_OPEN.test(html[start])) {
762
+ while (i < html.length) {
763
+ if (!TAG_CHAR.test(html[i])) {
764
+ break;
765
+ }
766
+
767
+ i += 1;
768
+ }
769
+
770
+ const tag = html.slice(start, i).toUpperCase();
771
+
772
+ if (tag === 'SCRIPT' || tag === 'STYLE') {
773
+ while (i < html.length) {
774
+ if (
775
+ html[i] === '<' &&
776
+ html[i + 1] === '/' &&
777
+ html.slice(i + 2, i + 2 + tag.length).toUpperCase() === tag
778
+ ) {
779
+ continue main;
780
+ }
781
+
782
+ i += 1;
783
+ }
784
+ }
785
+
786
+ let href = '';
787
+ let rel = '';
788
+
789
+ while (i < html.length) {
790
+ const start = i;
791
+
792
+ const char = html[start];
793
+ if (char === '>') break;
794
+
795
+ if (ATTRIBUTE_NAME.test(char)) {
796
+ i += 1;
797
+
798
+ while (i < html.length) {
799
+ if (!ATTRIBUTE_NAME.test(html[i])) {
800
+ break;
801
+ }
802
+
803
+ i += 1;
804
+ }
805
+
806
+ const name = html.slice(start, i).toLowerCase();
807
+
808
+ while (WHITESPACE.test(html[i])) i += 1;
809
+
810
+ if (html[i] === '=') {
811
+ i += 1;
812
+ while (WHITESPACE.test(html[i])) i += 1;
813
+
814
+ let value;
815
+
816
+ if (html[i] === "'" || html[i] === '"') {
817
+ const quote = html[i++];
818
+
819
+ const start = i;
820
+ let escaped = false;
821
+
822
+ while (i < html.length) {
823
+ if (!escaped) {
824
+ const char = html[i];
825
+
826
+ if (html[i] === quote) {
827
+ break;
828
+ }
829
+
830
+ if (char === '\\') {
831
+ escaped = true;
832
+ }
833
+ }
834
+
835
+ i += 1;
836
+ }
837
+
838
+ value = html.slice(start, i);
839
+ } else {
840
+ const start = i;
841
+ while (html[i] !== '>' && !WHITESPACE.test(html[i])) i += 1;
842
+ value = html.slice(start, i);
843
+
844
+ i -= 1;
845
+ }
846
+
847
+ if (name === 'href') {
848
+ href = value;
849
+ } else if (name === 'rel') {
850
+ rel = value;
851
+ } else if (name === 'src') {
852
+ hrefs.push(value);
853
+ } else if (name === 'srcset') {
854
+ const candidates = [];
855
+ let insideURL = true;
856
+ value = value.trim();
857
+ for (let i = 0; i < value.length; i++) {
858
+ if (value[i] === ',' && (!insideURL || (insideURL && value[i + 1] === ' '))) {
859
+ candidates.push(value.slice(0, i));
860
+ value = value.substring(i + 1).trim();
861
+ i = 0;
862
+ insideURL = true;
863
+ } else if (value[i] === ' ') {
864
+ insideURL = false;
865
+ }
866
+ }
867
+ candidates.push(value);
868
+ for (const candidate of candidates) {
869
+ const src = candidate.split(WHITESPACE)[0];
870
+ hrefs.push(src);
871
+ }
872
+ }
873
+ } else {
874
+ i -= 1;
875
+ }
876
+ }
877
+
878
+ i += 1;
879
+ }
880
+
881
+ if (href && !/\bexternal\b/i.test(rel)) {
882
+ hrefs.push(href);
883
+ }
884
+ }
885
+ }
886
+
887
+ i += 1;
888
+ }
889
+
890
+ return hrefs;
891
+ }
892
+
893
+ /**
894
+ * Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
895
+ *
896
+ * The first closes the script element, so everything after is treated as raw HTML.
897
+ * The second disables further parsing until `-->`, so the script element might be unexpectedly
898
+ * kept open until until an unrelated HTML comment in the page.
899
+ *
900
+ * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
901
+ * browsers.
902
+ *
903
+ * @see tests for unsafe parsing examples.
904
+ * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
905
+ * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
906
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
907
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
908
+ * @see https://github.com/tc39/proposal-json-superset
909
+ * @type {Record<string, string>}
910
+ */
911
+ const render_json_payload_script_dict = {
912
+ '<': '\\u003C',
913
+ '\u2028': '\\u2028',
914
+ '\u2029': '\\u2029'
915
+ };
916
+
917
+ new RegExp(
918
+ `[${Object.keys(render_json_payload_script_dict).join('')}]`,
919
+ 'g'
920
+ );
921
+
922
+ /**
923
+ * When inside a double-quoted attribute value, only `&` and `"` hold special meaning.
924
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state
925
+ * @type {Record<string, string>}
926
+ */
927
+ const escape_html_attr_dict = {
928
+ '&': '&amp;',
929
+ '"': '&quot;'
930
+ };
931
+
932
+ const escape_html_attr_regex = new RegExp(
933
+ // special characters
934
+ `[${Object.keys(escape_html_attr_dict).join('')}]|` +
935
+ // high surrogate without paired low surrogate
936
+ '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' +
937
+ // a valid surrogate pair, the only match with 2 code units
938
+ // we match it so that we can match unpaired low surrogates in the same pass
939
+ // TODO: use lookbehind assertions once they are widely supported: (?<![\ud800-udbff])[\udc00-\udfff]
940
+ '[\\ud800-\\udbff][\\udc00-\\udfff]|' +
941
+ // unpaired low surrogate (see previous match)
942
+ '[\\udc00-\\udfff]',
943
+ 'g'
944
+ );
945
+
946
+ /**
947
+ * Formats a string to be used as an attribute's value in raw HTML.
948
+ *
949
+ * It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes
950
+ * characters that are special in attributes, and surrounds the whole string in double-quotes.
951
+ *
952
+ * @param {string} str
953
+ * @returns {string} Escaped string surrounded by double-quotes.
954
+ * @example const html = `<tag data-value=${escape_html_attr('value')}>...</tag>`;
955
+ */
956
+ function escape_html_attr(str) {
957
+ const escaped_str = str.replace(escape_html_attr_regex, (match) => {
958
+ if (match.length === 2) {
959
+ // valid surrogate pair
960
+ return match;
961
+ }
962
+
963
+ return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`;
964
+ });
965
+
966
+ return `"${escaped_str}"`;
967
+ }
968
+
969
+ /**
970
+ * @typedef {import('types').PrerenderErrorHandler} PrerenderErrorHandler
971
+ * @typedef {import('types').PrerenderOnErrorValue} OnError
972
+ * @typedef {import('types').Logger} Logger
973
+ */
974
+
975
+ /** @type {(details: Parameters<PrerenderErrorHandler>[0] ) => string} */
976
+ function format_error({ status, path, referrer, referenceType }) {
977
+ return `${status} ${path}${referrer ? ` (${referenceType} from ${referrer})` : ''}`;
978
+ }
979
+
980
+ /** @type {(log: Logger, onError: OnError) => PrerenderErrorHandler} */
981
+ function normalise_error_handler(log, onError) {
982
+ switch (onError) {
983
+ case 'continue':
984
+ return (details) => {
985
+ log.error(format_error(details));
986
+ };
987
+ case 'fail':
988
+ return (details) => {
989
+ throw new Error(format_error(details));
990
+ };
991
+ default:
992
+ return onError;
993
+ }
994
+ }
995
+
996
+ const OK = 2;
997
+ const REDIRECT = 3;
998
+
999
+ /**
1000
+ * @param {{
1001
+ * config: import('types').ValidatedConfig;
1002
+ * entries: string[];
1003
+ * files: Set<string>;
1004
+ * log: Logger;
1005
+ * }} opts
1006
+ */
1007
+ async function prerender({ config, entries, files, log }) {
1008
+ /** @type {import('types').Prerendered} */
1009
+ const prerendered = {
1010
+ pages: new Map(),
1011
+ assets: new Map(),
1012
+ redirects: new Map(),
1013
+ paths: []
1014
+ };
1015
+
1016
+ if (!config.kit.prerender.enabled) {
1017
+ return prerendered;
1018
+ }
1019
+
1020
+ installFetch();
1021
+
1022
+ const server_root = join(config.kit.outDir, 'output');
1023
+
1024
+ /** @type {import('types').ServerModule} */
1025
+ const { Server, override } = await import(pathToFileURL(`${server_root}/server/index.js`).href);
1026
+ const { manifest } = await import(pathToFileURL(`${server_root}/server/manifest.js`).href);
1027
+
1028
+ override({
1029
+ paths: config.kit.paths,
1030
+ prerendering: true,
1031
+ read: (file) => readFileSync(join(config.kit.files.assets, file))
1032
+ });
1033
+
1034
+ const server = new Server(manifest);
1035
+
1036
+ const error = normalise_error_handler(log, config.kit.prerender.onError);
1037
+
1038
+ const q = queue(config.kit.prerender.concurrency);
1039
+
1040
+ /**
1041
+ * @param {string} path
1042
+ * @param {boolean} is_html
1043
+ */
1044
+ function output_filename(path, is_html) {
1045
+ const file = path.slice(config.kit.paths.base.length + 1);
1046
+
1047
+ if (file === '') {
1048
+ return 'index.html';
1049
+ }
1050
+
1051
+ if (is_html && !file.endsWith('.html')) {
1052
+ return file + (config.kit.trailingSlash === 'always' ? 'index.html' : '.html');
1053
+ }
1054
+
1055
+ return file;
1056
+ }
1057
+
1058
+ const seen = new Set();
1059
+ const written = new Set();
1060
+
1061
+ /**
1062
+ * @param {string | null} referrer
1063
+ * @param {string} decoded
1064
+ * @param {string} [encoded]
1065
+ */
1066
+ function enqueue(referrer, decoded, encoded) {
1067
+ if (seen.has(decoded)) return;
1068
+ seen.add(decoded);
1069
+
1070
+ const file = decoded.slice(config.kit.paths.base.length + 1);
1071
+ if (files.has(file)) return;
1072
+
1073
+ return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer));
1074
+ }
1075
+
1076
+ /**
1077
+ * @param {string} decoded
1078
+ * @param {string} encoded
1079
+ * @param {string?} referrer
1080
+ */
1081
+ async function visit(decoded, encoded, referrer) {
1082
+ if (!decoded.startsWith(config.kit.paths.base)) {
1083
+ error({ status: 404, path: decoded, referrer, referenceType: 'linked' });
1084
+ return;
1085
+ }
1086
+
1087
+ /** @type {Map<string, import('types').PrerenderDependency>} */
1088
+ const dependencies = new Map();
1089
+
1090
+ const response = await server.respond(new Request(`http://sveltekit-prerender${encoded}`), {
1091
+ getClientAddress,
1092
+ prerender: {
1093
+ default: config.kit.prerender.default,
1094
+ dependencies
1095
+ }
1096
+ });
1097
+
1098
+ const text = await response.text();
1099
+
1100
+ save('pages', response, text, decoded, encoded, referrer, 'linked');
1101
+
1102
+ for (const [dependency_path, result] of dependencies) {
1103
+ // this seems circuitous, but using new URL allows us to not care
1104
+ // whether dependency_path is encoded or not
1105
+ const encoded_dependency_path = new URL$1(dependency_path, 'http://localhost').pathname;
1106
+ const decoded_dependency_path = decodeURI(encoded_dependency_path);
1107
+
1108
+ const body = result.body ?? new Uint8Array(await result.response.arrayBuffer());
1109
+ save(
1110
+ 'dependencies',
1111
+ result.response,
1112
+ body,
1113
+ decoded_dependency_path,
1114
+ encoded_dependency_path,
1115
+ decoded,
1116
+ 'fetched'
1117
+ );
1118
+ }
1119
+
1120
+ if (config.kit.prerender.crawl && response.headers.get('content-type') === 'text/html') {
1121
+ for (const href of crawl(text)) {
1122
+ if (href.startsWith('data:') || href.startsWith('#')) continue;
1123
+
1124
+ const resolved = resolve(encoded, href);
1125
+ if (!is_root_relative(resolved)) continue;
1126
+
1127
+ const parsed = new URL$1(resolved, 'http://localhost');
1128
+
1129
+ if (parsed.search) ;
1130
+
1131
+ const pathname = normalize_path(parsed.pathname, config.kit.trailingSlash);
1132
+ enqueue(decoded, decodeURI(pathname), pathname);
1133
+ }
1134
+ }
1135
+ }
1136
+
1137
+ /**
1138
+ * @param {'pages' | 'dependencies'} category
1139
+ * @param {Response} response
1140
+ * @param {string | Uint8Array} body
1141
+ * @param {string} decoded
1142
+ * @param {string} encoded
1143
+ * @param {string | null} referrer
1144
+ * @param {'linked' | 'fetched'} referenceType
1145
+ */
1146
+ function save(category, response, body, decoded, encoded, referrer, referenceType) {
1147
+ const response_type = Math.floor(response.status / 100);
1148
+ const type = /** @type {string} */ (response.headers.get('content-type'));
1149
+ const is_html = response_type === REDIRECT || type === 'text/html';
1150
+
1151
+ const file = output_filename(decoded, is_html);
1152
+ const dest = `${config.kit.outDir}/output/prerendered/${category}/${file}`;
1153
+
1154
+ if (written.has(file)) return;
1155
+ written.add(file);
1156
+
1157
+ if (response_type === REDIRECT) {
1158
+ const location = response.headers.get('location');
1159
+
1160
+ if (location) {
1161
+ mkdirp(dirname(dest));
1162
+
1163
+ log.warn(`${response.status} ${decoded} -> ${location}`);
1164
+
1165
+ writeFileSync(
1166
+ dest,
1167
+ `<meta http-equiv="refresh" content=${escape_html_attr(`0;url=${location}`)}>`
1168
+ );
1169
+
1170
+ let resolved = resolve(encoded, location);
1171
+ if (is_root_relative(resolved)) {
1172
+ resolved = normalize_path(resolved, config.kit.trailingSlash);
1173
+ enqueue(decoded, decodeURI(resolved), resolved);
1174
+ }
1175
+
1176
+ if (!prerendered.redirects.has(decoded)) {
1177
+ prerendered.redirects.set(decoded, {
1178
+ status: response.status,
1179
+ location: resolved
1180
+ });
1181
+
1182
+ prerendered.paths.push(normalize_path(decoded, 'never'));
1183
+ }
1184
+ } else {
1185
+ log.warn(`location header missing on redirect received from ${decoded}`);
1186
+ }
1187
+
1188
+ return;
1189
+ }
1190
+
1191
+ if (response.status === 200) {
1192
+ mkdirp(dirname(dest));
1193
+
1194
+ log.info(`${response.status} ${decoded}`);
1195
+ writeFileSync(dest, body);
1196
+
1197
+ if (is_html) {
1198
+ prerendered.pages.set(decoded, {
1199
+ file
1200
+ });
1201
+ } else {
1202
+ prerendered.assets.set(decoded, {
1203
+ type
1204
+ });
1205
+ }
1206
+
1207
+ prerendered.paths.push(normalize_path(decoded, 'never'));
1208
+ } else if (response_type !== OK) {
1209
+ error({ status: response.status, path: decoded, referrer, referenceType });
1210
+ }
1211
+ }
1212
+
1213
+ if (config.kit.prerender.enabled) {
1214
+ for (const entry of config.kit.prerender.entries) {
1215
+ if (entry === '*') {
1216
+ for (const entry of entries) {
1217
+ enqueue(null, normalize_path(config.kit.paths.base + entry, config.kit.trailingSlash)); // TODO can we pre-normalize these?
1218
+ }
1219
+ } else {
1220
+ enqueue(null, normalize_path(config.kit.paths.base + entry, config.kit.trailingSlash));
1221
+ }
1222
+ }
1223
+
1224
+ await q.done();
1225
+ }
1226
+
1227
+ const rendered = await server.respond(new Request('http://sveltekit-prerender/[fallback]'), {
1228
+ getClientAddress,
1229
+ prerender: {
1230
+ fallback: true,
1231
+ default: false,
1232
+ dependencies: new Map()
1233
+ }
1234
+ });
1235
+
1236
+ const file = `${config.kit.outDir}/output/prerendered/fallback.html`;
1237
+ mkdirp(dirname(file));
1238
+ writeFileSync(file, await rendered.text());
1239
+
1240
+ return prerendered;
1241
+ }
1242
+
1243
+ /** @return {string} */
1244
+ function getClientAddress() {
1245
+ throw new Error('Cannot read clientAddress during prerendering');
1246
+ }
1247
+
1248
+ /**
1249
+ * @param {import('types').ValidatedConfig} config
1250
+ * @param {{ log: import('types').Logger }} opts
1251
+ */
1252
+ async function build(config, { log }) {
1253
+ const cwd = process.cwd(); // TODO is this necessary?
1254
+
1255
+ const build_dir = path__default.join(config.kit.outDir, 'build');
1256
+ rimraf(build_dir);
1257
+ mkdirp(build_dir);
1258
+
1259
+ const output_dir = path__default.join(config.kit.outDir, 'output');
1260
+ rimraf(output_dir);
1261
+ mkdirp(output_dir);
1262
+
1263
+ const { manifest_data } = all(config);
1264
+
1265
+ const options = {
1266
+ cwd,
1267
+ config,
1268
+ build_dir,
1269
+ // TODO this is so that Vite's preloading works. Unfortunately, it fails
1270
+ // during `svelte-kit preview`, because we use a local asset path. If Vite
1271
+ // used relative paths, I _think_ this could get fixed. Issue here:
1272
+ // https://github.com/vitejs/vite/issues/2009
1273
+ assets_base: `${config.kit.paths.assets || config.kit.paths.base}/${config.kit.appDir}/`,
1274
+ manifest_data,
1275
+ output_dir,
1276
+ client_entry_file: path__default.relative(cwd, `${get_runtime_path(config)}/client/start.js`),
1277
+ service_worker_entry_file: resolve_entry(config.kit.files.serviceWorker),
1278
+ service_worker_register: config.kit.serviceWorker.register
1279
+ };
1280
+
1281
+ const client = await build_client(options);
1282
+ const server = await build_server(options, client);
1283
+
1284
+ /** @type {import('types').BuildData} */
1285
+ const build_data = {
1286
+ app_dir: config.kit.appDir,
1287
+ manifest_data: options.manifest_data,
1288
+ service_worker: options.service_worker_entry_file ? 'service-worker.js' : null, // TODO make file configurable?
1289
+ client,
1290
+ server
1291
+ };
1292
+
1293
+ const manifest = `export const manifest = ${generate_manifest({
1294
+ build_data,
1295
+ relative_path: '.',
1296
+ routes: options.manifest_data.routes
1297
+ })};\n`;
1298
+ fs__default.writeFileSync(`${output_dir}/server/manifest.js`, manifest);
1299
+
1300
+ const static_files = options.manifest_data.assets.map((asset) => posixify(asset.file));
1301
+
1302
+ const files = new Set([
1303
+ ...static_files,
1304
+ ...client.chunks.map((chunk) => `${config.kit.appDir}/${chunk.fileName}`),
1305
+ ...client.assets.map((chunk) => `${config.kit.appDir}/${chunk.fileName}`)
1306
+ ]);
1307
+
1308
+ // TODO is this right?
1309
+ static_files.forEach((file) => {
1310
+ if (file.endsWith('/index.html')) {
1311
+ files.add(file.slice(0, -11));
1312
+ }
1313
+ });
1314
+
1315
+ const prerendered = await prerender({
1316
+ config,
1317
+ entries: options.manifest_data.routes
1318
+ .map((route) => (route.type === 'page' ? route.path : ''))
1319
+ .filter(Boolean),
1320
+ files,
1321
+ log
1322
+ });
1323
+
1324
+ if (options.service_worker_entry_file) {
1325
+ if (config.kit.paths.assets) {
1326
+ throw new Error('Cannot use service worker alongside config.kit.paths.assets');
1327
+ }
1328
+
1329
+ await build_service_worker(options, prerendered, client.vite_manifest);
1330
+ }
1331
+
1332
+ return { build_data, prerendered };
1333
+ }
1334
+
1335
+ export { build };