@sveltejs/kit 1.0.0-next.30 → 1.0.0-next.302

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