@sveltejs/kit 1.0.0-next.31 → 1.0.0-next.310

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