@sveltejs/kit 1.0.0-next.35 → 1.0.0-next.352

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