@sveltejs/kit 1.0.0-next.39 → 1.0.0-next.390

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 (41) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +13 -0
  3. package/assets/app/navigation.js +24 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/{runtime/app → app}/stores.js +33 -29
  6. package/assets/client/singletons.js +13 -0
  7. package/assets/client/start.js +1836 -0
  8. package/assets/components/error.svelte +18 -2
  9. package/assets/env.js +8 -0
  10. package/assets/{runtime/chunks/paths.js → paths.js} +4 -3
  11. package/assets/server/index.js +3565 -0
  12. package/dist/chunks/error.js +682 -0
  13. package/dist/chunks/index.js +15292 -3067
  14. package/dist/chunks/index2.js +175 -548
  15. package/dist/chunks/multipart-parser.js +458 -0
  16. package/dist/chunks/sync.js +1007 -0
  17. package/dist/chunks/write_tsconfig.js +274 -0
  18. package/dist/cli.js +66 -514
  19. package/dist/hooks.js +28 -0
  20. package/dist/node/polyfills.js +17778 -0
  21. package/dist/node.js +348 -0
  22. package/dist/vite.js +3289 -0
  23. package/package.json +97 -64
  24. package/types/ambient.d.ts +328 -0
  25. package/types/index.d.ts +290 -0
  26. package/types/internal.d.ts +327 -0
  27. package/types/private.d.ts +235 -0
  28. package/CHANGELOG.md +0 -405
  29. package/assets/runtime/app/env.js +0 -5
  30. package/assets/runtime/app/navigation.js +0 -41
  31. package/assets/runtime/app/paths.js +0 -1
  32. package/assets/runtime/chunks/utils.js +0 -19
  33. package/assets/runtime/internal/singletons.js +0 -23
  34. package/assets/runtime/internal/start.js +0 -770
  35. package/dist/chunks/index3.js +0 -246
  36. package/dist/chunks/index4.js +0 -517
  37. package/dist/chunks/index5.js +0 -761
  38. package/dist/chunks/index6.js +0 -322
  39. package/dist/chunks/standard.js +0 -99
  40. package/dist/chunks/utils.js +0 -83
  41. package/dist/ssr.js +0 -2523
package/dist/vite.js ADDED
@@ -0,0 +1,3289 @@
1
+ import * as fs from 'fs';
2
+ import fs__default, { readFileSync, writeFileSync, readdirSync, statSync } from 'fs';
3
+ import path__default, { join, dirname, resolve as resolve$1, normalize } from 'path';
4
+ import { a as load_template, $, c as coalesce_to_error, l as load_config } from './chunks/error.js';
5
+ import { svelte } from '@sveltejs/vite-plugin-svelte';
6
+ import * as vite from 'vite';
7
+ import { loadConfigFromFile } from 'vite';
8
+ import { p as posixify, m as mkdirp, w as walk, r as rimraf } from './chunks/write_tsconfig.js';
9
+ import { g as get_runtime_directory, s, i as init, a as get_runtime_prefix, u as update, b as get_mime_lookup, p as parse_route_id, c as all, l as logger } from './chunks/sync.js';
10
+ import { URL as URL$1, pathToFileURL } from 'url';
11
+ import { installPolyfills } from './node/polyfills.js';
12
+ import * as qs from 'querystring';
13
+ import { getRequest, setResponse } from './node.js';
14
+ import 'assert';
15
+ import 'net';
16
+ import 'http';
17
+ import 'stream';
18
+ import 'buffer';
19
+ import 'util';
20
+ import 'stream/web';
21
+ import 'perf_hooks';
22
+ import 'util/types';
23
+ import 'events';
24
+ import 'tls';
25
+ import 'async_hooks';
26
+ import 'console';
27
+ import 'zlib';
28
+ import 'node:http';
29
+ import 'node:https';
30
+ import 'node:zlib';
31
+ import 'node:stream';
32
+ import 'node:buffer';
33
+ import 'node:util';
34
+ import 'node:url';
35
+ import 'node:net';
36
+ import 'node:fs';
37
+ import 'node:path';
38
+ import 'crypto';
39
+
40
+ /**
41
+ * @param {import('vite').ConfigEnv} config_env
42
+ * @return {Promise<import('vite').UserConfig>}
43
+ */
44
+ async function get_vite_config(config_env) {
45
+ const config = (await loadConfigFromFile(config_env))?.config;
46
+ if (!config) {
47
+ throw new Error('Could not load Vite config');
48
+ }
49
+ return { ...config, mode: config_env.mode };
50
+ }
51
+
52
+ /**
53
+ * @param {...import('vite').UserConfig} configs
54
+ * @returns {import('vite').UserConfig}
55
+ */
56
+ function merge_vite_configs(...configs) {
57
+ return deep_merge(
58
+ ...configs.map((config) => ({
59
+ ...config,
60
+ resolve: {
61
+ ...config.resolve,
62
+ alias: normalize_alias(config.resolve?.alias || {})
63
+ }
64
+ }))
65
+ );
66
+ }
67
+
68
+ /**
69
+ * Takes zero or more objects and returns a new object that has all the values
70
+ * deeply merged together. None of the original objects will be mutated at any
71
+ * level, and the returned object will have no references to the original
72
+ * objects at any depth. If there's a conflict the last one wins, except for
73
+ * arrays which will be combined.
74
+ * @param {...Object} objects
75
+ * @returns {Record<string, any>} the merged object
76
+ */
77
+ function deep_merge(...objects) {
78
+ const result = {};
79
+ /** @type {string[]} */
80
+ objects.forEach((o) => merge_into(result, o));
81
+ return result;
82
+ }
83
+
84
+ /**
85
+ * normalize kit.vite.resolve.alias as an array
86
+ * @param {import('vite').AliasOptions} o
87
+ * @returns {import('vite').Alias[]}
88
+ */
89
+ function normalize_alias(o) {
90
+ if (Array.isArray(o)) return o;
91
+ return Object.entries(o).map(([find, replacement]) => ({ find, replacement }));
92
+ }
93
+
94
+ /**
95
+ * Merges b into a, recursively, mutating a.
96
+ * @param {Record<string, any>} a
97
+ * @param {Record<string, any>} b
98
+ */
99
+ function merge_into(a, b) {
100
+ /**
101
+ * Checks for "plain old Javascript object", typically made as an object
102
+ * literal. Excludes Arrays and built-in types like Buffer.
103
+ * @param {any} x
104
+ */
105
+ const is_plain_object = (x) => typeof x === 'object' && x.constructor === Object;
106
+
107
+ for (const prop in b) {
108
+ if (is_plain_object(b[prop])) {
109
+ if (!is_plain_object(a[prop])) {
110
+ a[prop] = {};
111
+ }
112
+ merge_into(a[prop], b[prop]);
113
+ } else if (Array.isArray(b[prop])) {
114
+ if (!Array.isArray(a[prop])) {
115
+ a[prop] = [];
116
+ }
117
+ a[prop].push(...b[prop]);
118
+ } else {
119
+ a[prop] = b[prop];
120
+ }
121
+ }
122
+ }
123
+
124
+ /** @param {import('types').ValidatedKitConfig} config */
125
+ function get_aliases(config) {
126
+ /** @type {Record<string, string>} */
127
+ const alias = {
128
+ __GENERATED__: path__default.posix.join(config.outDir, 'generated'),
129
+ $app: `${get_runtime_directory(config)}/app`,
130
+
131
+ // For now, we handle `$lib` specially here rather than make it a default value for
132
+ // `config.kit.alias` since it has special meaning for packaging, etc.
133
+ $lib: config.files.lib
134
+ };
135
+
136
+ for (const [key, value] of Object.entries(config.alias)) {
137
+ alias[key] = path__default.resolve(value);
138
+ }
139
+
140
+ return alias;
141
+ }
142
+
143
+ /**
144
+ * Given an entry point like [cwd]/src/hooks, returns a filename like [cwd]/src/hooks.js or [cwd]/src/hooks/index.js
145
+ * @param {string} entry
146
+ * @returns {string|null}
147
+ */
148
+ function resolve_entry(entry) {
149
+ if (fs__default.existsSync(entry)) {
150
+ const stats = fs__default.statSync(entry);
151
+ if (stats.isDirectory()) {
152
+ return resolve_entry(path__default.join(entry, 'index'));
153
+ }
154
+
155
+ return entry;
156
+ } else {
157
+ const dir = path__default.dirname(entry);
158
+
159
+ if (fs__default.existsSync(dir)) {
160
+ const base = path__default.basename(entry);
161
+ const files = fs__default.readdirSync(dir);
162
+
163
+ const found = files.find((file) => file.replace(/\.[^.]+$/, '') === base);
164
+
165
+ if (found) return path__default.join(dir, found);
166
+ }
167
+ }
168
+
169
+ return null;
170
+ }
171
+
172
+ /**
173
+ * @typedef {import('rollup').RollupOutput} RollupOutput
174
+ * @typedef {import('rollup').OutputChunk} OutputChunk
175
+ * @typedef {import('rollup').OutputAsset} OutputAsset
176
+ */
177
+
178
+ /**
179
+ * Invokes Vite.
180
+ * @param {import('vite').UserConfig} config
181
+ */
182
+ async function create_build(config) {
183
+ const { output } = /** @type {RollupOutput} */ (
184
+ await vite.build({ ...config, configFile: false })
185
+ );
186
+
187
+ const chunks = output.filter(
188
+ /** @returns {output is OutputChunk} */ (output) => output.type === 'chunk'
189
+ );
190
+
191
+ const assets = output.filter(
192
+ /** @returns {output is OutputAsset} */ (output) => output.type === 'asset'
193
+ );
194
+
195
+ return { chunks, assets };
196
+ }
197
+
198
+ /**
199
+ * Adds transitive JS and CSS dependencies to the js and css inputs.
200
+ * @param {import('vite').Manifest} manifest
201
+ * @param {string} entry
202
+ * @param {boolean} add_dynamic_css
203
+ */
204
+ function find_deps$1(manifest, entry, add_dynamic_css) {
205
+ /** @type {Set<string>} */
206
+ const seen = new Set();
207
+
208
+ /** @type {Set<string>} */
209
+ const imports = new Set();
210
+
211
+ /** @type {Set<string>} */
212
+ const stylesheets = new Set();
213
+
214
+ /**
215
+ * @param {string} file
216
+ * @param {boolean} add_js
217
+ */
218
+ function traverse(file, add_js) {
219
+ if (seen.has(file)) return;
220
+ seen.add(file);
221
+
222
+ const chunk = manifest[file];
223
+
224
+ if (add_js) imports.add(chunk.file);
225
+
226
+ if (chunk.css) {
227
+ chunk.css.forEach((file) => stylesheets.add(file));
228
+ }
229
+
230
+ if (chunk.imports) {
231
+ chunk.imports.forEach((file) => traverse(file, add_js));
232
+ }
233
+
234
+ if (add_dynamic_css && chunk.dynamicImports) {
235
+ chunk.dynamicImports.forEach((file) => traverse(file, false));
236
+ }
237
+ }
238
+
239
+ traverse(entry, true);
240
+
241
+ return {
242
+ file: manifest[entry].file,
243
+ imports: Array.from(imports),
244
+ stylesheets: Array.from(stylesheets)
245
+ };
246
+ }
247
+
248
+ /**
249
+ * The Vite configuration that we use by default.
250
+ * @param {{
251
+ * config: import('types').ValidatedConfig;
252
+ * input: Record<string, string>;
253
+ * ssr: boolean;
254
+ * outDir: string;
255
+ * }} options
256
+ * @return {import('vite').UserConfig}
257
+ */
258
+ const get_default_config = function ({ config, input, ssr, outDir }) {
259
+ return {
260
+ appType: 'custom',
261
+ base: assets_base(config.kit),
262
+ build: {
263
+ cssCodeSplit: true,
264
+ manifest: true,
265
+ outDir,
266
+ polyfillModulePreload: false,
267
+ rollupOptions: {
268
+ input,
269
+ output: {
270
+ format: 'esm',
271
+ entryFileNames: ssr ? '[name].js' : `${config.kit.appDir}/immutable/[name]-[hash].js`,
272
+ chunkFileNames: `${config.kit.appDir}/immutable/chunks/[name]-[hash].js`,
273
+ assetFileNames: `${config.kit.appDir}/immutable/assets/[name]-[hash][extname]`
274
+ },
275
+ preserveEntrySignatures: 'strict'
276
+ },
277
+ ssr,
278
+ target: ssr ? 'node14.8' : undefined
279
+ },
280
+ define: {
281
+ __SVELTEKIT_ADAPTER_NAME__: JSON.stringify(config.kit.adapter?.name),
282
+ __SVELTEKIT_APP_VERSION__: JSON.stringify(config.kit.version.name),
283
+ __SVELTEKIT_APP_VERSION_FILE__: JSON.stringify(`${config.kit.appDir}/version.json`),
284
+ __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: JSON.stringify(config.kit.version.pollInterval),
285
+ __SVELTEKIT_DEV__: 'false'
286
+ },
287
+ publicDir: ssr ? false : config.kit.files.assets,
288
+ resolve: {
289
+ alias: get_aliases(config.kit)
290
+ },
291
+ ssr: {
292
+ // when developing against the Kit src code, we want to ensure that
293
+ // our dependencies are bundled so that apps don't need to install
294
+ // them as peerDependencies
295
+ noExternal: []
296
+
297
+ }
298
+ };
299
+ };
300
+
301
+ /**
302
+ * @param {import('types').ValidatedKitConfig} config
303
+ * @returns {string}
304
+ */
305
+ function assets_base(config) {
306
+ // TODO this is so that Vite's preloading works. Unfortunately, it fails
307
+ // during `svelte-kit preview`, because we use a local asset path. This
308
+ // may be fixed in Vite 3: https://github.com/vitejs/vite/issues/2009
309
+ const { base, assets } = config.paths;
310
+ return `${assets || base}/`;
311
+ }
312
+
313
+ /**
314
+ * vite.config.js will contain vite-plugin-svelte-kit, which kicks off the server and service
315
+ * worker builds in a hook. When running the server and service worker builds we must remove
316
+ * the SvelteKit plugin so that we do not kick off additional instances of these builds.
317
+ * @param {import('vite').UserConfig} config
318
+ */
319
+ function remove_svelte_kit(config) {
320
+ // TODO i feel like there's a more elegant way to do this
321
+ // @ts-expect-error - it can't handle infinite type expansion
322
+ config.plugins = (config.plugins || [])
323
+ .flat(Infinity)
324
+ .filter((plugin) => plugin.name !== 'vite-plugin-svelte-kit');
325
+ }
326
+
327
+ const method_names = new Set(['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']);
328
+
329
+ // If we'd written this in TypeScript, it could be easy...
330
+ /**
331
+ * @param {string} str
332
+ * @returns {str is import('types').HttpMethod}
333
+ */
334
+ function is_http_method(str) {
335
+ return method_names.has(str);
336
+ }
337
+
338
+ /**
339
+ * @param {{
340
+ * hooks: string;
341
+ * config: import('types').ValidatedConfig;
342
+ * has_service_worker: boolean;
343
+ * runtime: string;
344
+ * template: string;
345
+ * }} opts
346
+ */
347
+ const server_template = ({ config, hooks, has_service_worker, runtime, template }) => `
348
+ import root from '__GENERATED__/root.svelte';
349
+ import { respond } from '${runtime}/server/index.js';
350
+ import { set_paths, assets, base } from '${runtime}/paths.js';
351
+ import { set_prerendering } from '${runtime}/env.js';
352
+
353
+ const template = ({ head, body, assets, nonce }) => ${s(template)
354
+ .replace('%sveltekit.head%', '" + head + "')
355
+ .replace('%sveltekit.body%', '" + body + "')
356
+ .replace(/%sveltekit\.assets%/g, '" + assets + "')
357
+ .replace(/%sveltekit\.nonce%/g, '" + nonce + "')};
358
+
359
+ let read = null;
360
+
361
+ set_paths(${s(config.kit.paths)});
362
+
363
+ let default_protocol = 'https';
364
+
365
+ // allow paths to be globally overridden
366
+ // in svelte-kit preview and in prerendering
367
+ export function override(settings) {
368
+ default_protocol = settings.protocol || default_protocol;
369
+ set_paths(settings.paths);
370
+ set_prerendering(settings.prerendering);
371
+ read = settings.read;
372
+ }
373
+
374
+ export class Server {
375
+ constructor(manifest) {
376
+ this.options = {
377
+ csp: ${s(config.kit.csp)},
378
+ dev: false,
379
+ get_stack: error => String(error), // for security
380
+ handle_error: (error, event) => {
381
+ this.options.hooks.handleError({
382
+ error,
383
+ event,
384
+
385
+ // TODO remove for 1.0
386
+ // @ts-expect-error
387
+ get request() {
388
+ throw new Error('request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details');
389
+ }
390
+ });
391
+ error.stack = this.options.get_stack(error);
392
+ },
393
+ hooks: null,
394
+ hydrate: ${s(config.kit.browser.hydrate)},
395
+ manifest,
396
+ method_override: ${s(config.kit.methodOverride)},
397
+ paths: { base, assets },
398
+ prefix: assets + '/',
399
+ prerender: {
400
+ default: ${config.kit.prerender.default},
401
+ enabled: ${config.kit.prerender.enabled}
402
+ },
403
+ read,
404
+ root,
405
+ service_worker: ${has_service_worker ? "base + '/service-worker.js'" : 'null'},
406
+ router: ${s(config.kit.browser.router)},
407
+ template,
408
+ template_contains_nonce: ${template.includes('%sveltekit.nonce%')},
409
+ trailing_slash: ${s(config.kit.trailingSlash)}
410
+ };
411
+ }
412
+
413
+ async respond(request, options = {}) {
414
+ if (!(request instanceof Request)) {
415
+ throw new Error('The first argument to server.respond must be a Request object. See https://github.com/sveltejs/kit/pull/3384 for details');
416
+ }
417
+
418
+ if (!this.options.hooks) {
419
+ const module = await import(${s(hooks)});
420
+ this.options.hooks = {
421
+ getSession: module.getSession || (() => ({})),
422
+ handle: module.handle || (({ event, resolve }) => resolve(event)),
423
+ handleError: module.handleError || (({ error }) => console.error(error.stack)),
424
+ externalFetch: module.externalFetch || fetch
425
+ };
426
+ }
427
+
428
+ return respond(request, this.options, options);
429
+ }
430
+ }
431
+ `;
432
+
433
+ /**
434
+ * @param {{
435
+ * cwd: string;
436
+ * config: import('types').ValidatedConfig;
437
+ * vite_config_env: import('vite').ConfigEnv;
438
+ * manifest_data: import('types').ManifestData;
439
+ * build_dir: string;
440
+ * output_dir: string;
441
+ * service_worker_entry_file: string | null;
442
+ * }} options
443
+ * @param {{ vite_manifest: import('vite').Manifest, assets: import('rollup').OutputAsset[] }} client
444
+ */
445
+ async function build_server(options, client) {
446
+ const {
447
+ cwd,
448
+ config,
449
+ vite_config_env,
450
+ manifest_data,
451
+ build_dir,
452
+ output_dir,
453
+ service_worker_entry_file
454
+ } = options;
455
+
456
+ let hooks_file = resolve_entry(config.kit.files.hooks);
457
+ if (!hooks_file || !fs__default.existsSync(hooks_file)) {
458
+ hooks_file = path__default.join(config.kit.outDir, 'build/hooks.js');
459
+ fs__default.writeFileSync(hooks_file, '');
460
+ }
461
+
462
+ /** @type {Record<string, string>} */
463
+ const input = {
464
+ index: `${build_dir}/index.js`
465
+ };
466
+
467
+ // add entry points for every endpoint...
468
+ manifest_data.routes.forEach((route) => {
469
+ const file = route.type === 'endpoint' ? route.file : route.shadow;
470
+
471
+ if (file) {
472
+ const resolved = path__default.resolve(cwd, file);
473
+ const relative = decodeURIComponent(path__default.relative(config.kit.files.routes, resolved));
474
+ const name = posixify(path__default.join('entries/endpoints', relative.replace(/\.js$/, '')));
475
+ input[name] = resolved;
476
+ }
477
+ });
478
+
479
+ // ...and every component used by pages...
480
+ manifest_data.components.forEach((file) => {
481
+ const resolved = path__default.resolve(cwd, file);
482
+ const relative = decodeURIComponent(path__default.relative(config.kit.files.routes, resolved));
483
+
484
+ const name = relative.startsWith('..')
485
+ ? posixify(path__default.join('entries/fallbacks', path__default.basename(file)))
486
+ : posixify(path__default.join('entries/pages', relative));
487
+ input[name] = resolved;
488
+ });
489
+
490
+ // ...and every matcher
491
+ Object.entries(manifest_data.matchers).forEach(([key, file]) => {
492
+ const name = posixify(path__default.join('entries/matchers', key));
493
+ input[name] = path__default.resolve(cwd, file);
494
+ });
495
+
496
+ /** @type {(file: string) => string} */
497
+ const app_relative = (file) => {
498
+ const relative_file = path__default.relative(build_dir, path__default.resolve(cwd, file));
499
+ return relative_file[0] === '.' ? relative_file : `./${relative_file}`;
500
+ };
501
+
502
+ fs__default.writeFileSync(
503
+ input.index,
504
+ server_template({
505
+ config,
506
+ hooks: app_relative(hooks_file),
507
+ has_service_worker: config.kit.serviceWorker.register && !!service_worker_entry_file,
508
+ runtime: posixify(path__default.relative(build_dir, get_runtime_directory(config.kit))),
509
+ template: load_template(cwd, config)
510
+ })
511
+ );
512
+
513
+ const vite_config = await get_vite_config(vite_config_env);
514
+
515
+ const merged_config = merge_vite_configs(
516
+ get_default_config({ config, input, ssr: true, outDir: `${output_dir}/server` }),
517
+ vite_config
518
+ );
519
+
520
+ remove_svelte_kit(merged_config);
521
+
522
+ const { chunks } = await create_build(merged_config);
523
+
524
+ /** @type {import('vite').Manifest} */
525
+ const vite_manifest = JSON.parse(fs__default.readFileSync(`${output_dir}/server/manifest.json`, 'utf-8'));
526
+
527
+ mkdirp(`${output_dir}/server/nodes`);
528
+ mkdirp(`${output_dir}/server/stylesheets`);
529
+
530
+ const stylesheet_lookup = new Map();
531
+
532
+ client.assets.forEach((asset) => {
533
+ if (asset.fileName.endsWith('.css')) {
534
+ if (asset.source.length < config.kit.inlineStyleThreshold) {
535
+ const index = stylesheet_lookup.size;
536
+ const file = `${output_dir}/server/stylesheets/${index}.js`;
537
+
538
+ fs__default.writeFileSync(file, `// ${asset.fileName}\nexport default ${s(asset.source)};`);
539
+ stylesheet_lookup.set(asset.fileName, index);
540
+ }
541
+ }
542
+ });
543
+
544
+ manifest_data.components.forEach((component, i) => {
545
+ const entry = find_deps$1(client.vite_manifest, component, true);
546
+
547
+ const imports = [`import * as module from '../${vite_manifest[component].file}';`];
548
+
549
+ const exports = [
550
+ 'export { module };',
551
+ `export const index = ${i};`,
552
+ `export const file = '${entry.file}';`,
553
+ `export const imports = ${s(entry.imports)};`,
554
+ `export const stylesheets = ${s(entry.stylesheets)};`
555
+ ];
556
+
557
+ /** @type {string[]} */
558
+ const styles = [];
559
+
560
+ entry.stylesheets.forEach((file) => {
561
+ if (stylesheet_lookup.has(file)) {
562
+ const index = stylesheet_lookup.get(file);
563
+ const name = `stylesheet_${index}`;
564
+ imports.push(`import ${name} from '../stylesheets/${index}.js';`);
565
+ styles.push(`\t${s(file)}: ${name}`);
566
+ }
567
+ });
568
+
569
+ if (styles.length > 0) {
570
+ exports.push(`export const inline_styles = () => ({\n${styles.join(',\n')}\n});`);
571
+ }
572
+
573
+ const out = `${output_dir}/server/nodes/${i}.js`;
574
+ fs__default.writeFileSync(out, `${imports.join('\n')}\n\n${exports.join('\n')}\n`);
575
+ });
576
+
577
+ return {
578
+ chunks,
579
+ vite_manifest,
580
+ methods: get_methods(cwd, chunks, manifest_data)
581
+ };
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].filter(is_http_method);
605
+ }
606
+ });
607
+
608
+ return methods;
609
+ }
610
+
611
+ /**
612
+ * @param {{
613
+ * config: import('types').ValidatedConfig;
614
+ * vite_config_env: import('vite').ConfigEnv;
615
+ * manifest_data: import('types').ManifestData;
616
+ * output_dir: string;
617
+ * service_worker_entry_file: string | null;
618
+ * }} options
619
+ * @param {import('types').Prerendered} prerendered
620
+ * @param {import('vite').Manifest} client_manifest
621
+ */
622
+ async function build_service_worker(
623
+ { config, vite_config_env, manifest_data, output_dir, service_worker_entry_file },
624
+ prerendered,
625
+ client_manifest
626
+ ) {
627
+ const build = new Set();
628
+ for (const key in client_manifest) {
629
+ const { file, css = [], assets = [] } = client_manifest[key];
630
+ build.add(file);
631
+ css.forEach((file) => build.add(file));
632
+ assets.forEach((file) => build.add(file));
633
+ }
634
+
635
+ const service_worker = `${config.kit.outDir}/generated/service-worker.js`;
636
+
637
+ fs__default.writeFileSync(
638
+ service_worker,
639
+ `
640
+ // TODO remove for 1.0
641
+ export const timestamp = {
642
+ toString: () => {
643
+ throw new Error('\`timestamp\` has been removed from $service-worker. Use \`version\` instead');
644
+ }
645
+ };
646
+
647
+ export const build = [
648
+ ${Array.from(build)
649
+ .map((file) => `${s(`${config.kit.paths.base}/${file}`)}`)
650
+ .join(',\n\t\t\t\t')}
651
+ ];
652
+
653
+ export const files = [
654
+ ${manifest_data.assets
655
+ .filter((asset) => config.kit.serviceWorker.files(asset.file))
656
+ .map((asset) => `${s(`${config.kit.paths.base}/${asset.file}`)}`)
657
+ .join(',\n\t\t\t\t')}
658
+ ];
659
+
660
+ export const prerendered = [
661
+ ${prerendered.paths.map((path) => s(path)).join(',\n\t\t\t\t')}
662
+ ];
663
+
664
+ export const version = ${s(config.kit.version.name)};
665
+ `
666
+ .replace(/^\t{3}/gm, '')
667
+ .trim()
668
+ );
669
+
670
+ const vite_config = await get_vite_config(vite_config_env);
671
+ const merged_config = merge_vite_configs(vite_config, {
672
+ base: assets_base(config.kit),
673
+ build: {
674
+ lib: {
675
+ entry: /** @type {string} */ (service_worker_entry_file),
676
+ name: 'app',
677
+ formats: ['es']
678
+ },
679
+ rollupOptions: {
680
+ output: {
681
+ entryFileNames: 'service-worker.js'
682
+ }
683
+ },
684
+ outDir: `${output_dir}/client`,
685
+ emptyOutDir: false
686
+ },
687
+ // @ts-expect-error
688
+ configFile: false,
689
+ resolve: {
690
+ alias: {
691
+ '$service-worker': service_worker,
692
+ $lib: config.kit.files.lib
693
+ }
694
+ }
695
+ });
696
+
697
+ remove_svelte_kit(merged_config);
698
+
699
+ await vite.build(merged_config);
700
+ }
701
+
702
+ const absolute = /^([a-z]+:)?\/?\//;
703
+ const scheme = /^[a-z]+:/;
704
+
705
+ /**
706
+ * @param {string} base
707
+ * @param {string} path
708
+ */
709
+ function resolve(base, path) {
710
+ if (scheme.test(path)) return path;
711
+
712
+ const base_match = absolute.exec(base);
713
+ const path_match = absolute.exec(path);
714
+
715
+ if (!base_match) {
716
+ throw new Error(`bad base path: "${base}"`);
717
+ }
718
+
719
+ const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
720
+ const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
721
+
722
+ baseparts.pop();
723
+
724
+ for (let i = 0; i < pathparts.length; i += 1) {
725
+ const part = pathparts[i];
726
+ if (part === '.') continue;
727
+ else if (part === '..') baseparts.pop();
728
+ else baseparts.push(part);
729
+ }
730
+
731
+ const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
732
+
733
+ return `${prefix}${baseparts.join('/')}`;
734
+ }
735
+
736
+ /** @param {string} path */
737
+ function is_root_relative(path) {
738
+ return path[0] === '/' && path[1] !== '/';
739
+ }
740
+
741
+ /**
742
+ * @typedef {{
743
+ * fn: () => Promise<any>,
744
+ * fulfil: (value: any) => void,
745
+ * reject: (error: Error) => void
746
+ * }} Task
747
+ */
748
+
749
+ /** @param {number} concurrency */
750
+ function queue(concurrency) {
751
+ /** @type {Task[]} */
752
+ const tasks = [];
753
+
754
+ let current = 0;
755
+
756
+ /** @type {(value?: any) => void} */
757
+ let fulfil;
758
+
759
+ /** @type {(error: Error) => void} */
760
+ let reject;
761
+
762
+ let closed = false;
763
+
764
+ const done = new Promise((f, r) => {
765
+ fulfil = f;
766
+ reject = r;
767
+ });
768
+
769
+ done.catch(() => {
770
+ // this is necessary in case a catch handler is never added
771
+ // to the done promise by the user
772
+ });
773
+
774
+ function dequeue() {
775
+ if (current < concurrency) {
776
+ const task = tasks.shift();
777
+
778
+ if (task) {
779
+ current += 1;
780
+ const promise = Promise.resolve(task.fn());
781
+
782
+ promise
783
+ .then(task.fulfil, (err) => {
784
+ task.reject(err);
785
+ reject(err);
786
+ })
787
+ .then(() => {
788
+ current -= 1;
789
+ dequeue();
790
+ });
791
+ } else if (current === 0) {
792
+ closed = true;
793
+ fulfil();
794
+ }
795
+ }
796
+ }
797
+
798
+ return {
799
+ /** @param {() => any} fn */
800
+ add: (fn) => {
801
+ if (closed) throw new Error('Cannot add tasks to a queue that has ended');
802
+
803
+ const promise = new Promise((fulfil, reject) => {
804
+ tasks.push({ fn, fulfil, reject });
805
+ });
806
+
807
+ dequeue();
808
+ return promise;
809
+ },
810
+
811
+ done: () => {
812
+ if (current === 0) {
813
+ closed = true;
814
+ fulfil();
815
+ }
816
+
817
+ return done;
818
+ }
819
+ };
820
+ }
821
+
822
+ const DOCTYPE = 'DOCTYPE';
823
+ const CDATA_OPEN = '[CDATA[';
824
+ const CDATA_CLOSE = ']]>';
825
+ const COMMENT_OPEN = '--';
826
+ const COMMENT_CLOSE = '-->';
827
+
828
+ const TAG_OPEN = /[a-zA-Z]/;
829
+ const TAG_CHAR = /[a-zA-Z0-9]/;
830
+ const ATTRIBUTE_NAME = /[^\t\n\f />"'=]/;
831
+
832
+ const WHITESPACE = /[\s\n\r]/;
833
+
834
+ /** @param {string} html */
835
+ function crawl(html) {
836
+ /** @type {string[]} */
837
+ const hrefs = [];
838
+
839
+ let i = 0;
840
+ main: while (i < html.length) {
841
+ const char = html[i];
842
+
843
+ if (char === '<') {
844
+ if (html[i + 1] === '!') {
845
+ i += 2;
846
+
847
+ if (html.slice(i, i + DOCTYPE.length).toUpperCase() === DOCTYPE) {
848
+ i += DOCTYPE.length;
849
+ while (i < html.length) {
850
+ if (html[i++] === '>') {
851
+ continue main;
852
+ }
853
+ }
854
+ }
855
+
856
+ // skip cdata
857
+ if (html.slice(i, i + CDATA_OPEN.length) === CDATA_OPEN) {
858
+ i += CDATA_OPEN.length;
859
+ while (i < html.length) {
860
+ if (html.slice(i, i + CDATA_CLOSE.length) === CDATA_CLOSE) {
861
+ i += CDATA_CLOSE.length;
862
+ continue main;
863
+ }
864
+
865
+ i += 1;
866
+ }
867
+ }
868
+
869
+ // skip comments
870
+ if (html.slice(i, i + COMMENT_OPEN.length) === COMMENT_OPEN) {
871
+ i += COMMENT_OPEN.length;
872
+ while (i < html.length) {
873
+ if (html.slice(i, i + COMMENT_CLOSE.length) === COMMENT_CLOSE) {
874
+ i += COMMENT_CLOSE.length;
875
+ continue main;
876
+ }
877
+
878
+ i += 1;
879
+ }
880
+ }
881
+ }
882
+
883
+ // parse opening tags
884
+ const start = ++i;
885
+ if (TAG_OPEN.test(html[start])) {
886
+ while (i < html.length) {
887
+ if (!TAG_CHAR.test(html[i])) {
888
+ break;
889
+ }
890
+
891
+ i += 1;
892
+ }
893
+
894
+ const tag = html.slice(start, i).toUpperCase();
895
+
896
+ if (tag === 'SCRIPT' || tag === 'STYLE') {
897
+ while (i < html.length) {
898
+ if (
899
+ html[i] === '<' &&
900
+ html[i + 1] === '/' &&
901
+ html.slice(i + 2, i + 2 + tag.length).toUpperCase() === tag
902
+ ) {
903
+ continue main;
904
+ }
905
+
906
+ i += 1;
907
+ }
908
+ }
909
+
910
+ let href = '';
911
+ let rel = '';
912
+
913
+ while (i < html.length) {
914
+ const start = i;
915
+
916
+ const char = html[start];
917
+ if (char === '>') break;
918
+
919
+ if (ATTRIBUTE_NAME.test(char)) {
920
+ i += 1;
921
+
922
+ while (i < html.length) {
923
+ if (!ATTRIBUTE_NAME.test(html[i])) {
924
+ break;
925
+ }
926
+
927
+ i += 1;
928
+ }
929
+
930
+ const name = html.slice(start, i).toLowerCase();
931
+
932
+ while (WHITESPACE.test(html[i])) i += 1;
933
+
934
+ if (html[i] === '=') {
935
+ i += 1;
936
+ while (WHITESPACE.test(html[i])) i += 1;
937
+
938
+ let value;
939
+
940
+ if (html[i] === "'" || html[i] === '"') {
941
+ const quote = html[i++];
942
+
943
+ const start = i;
944
+ let escaped = false;
945
+
946
+ while (i < html.length) {
947
+ if (!escaped) {
948
+ const char = html[i];
949
+
950
+ if (html[i] === quote) {
951
+ break;
952
+ }
953
+
954
+ if (char === '\\') {
955
+ escaped = true;
956
+ }
957
+ }
958
+
959
+ i += 1;
960
+ }
961
+
962
+ value = html.slice(start, i);
963
+ } else {
964
+ const start = i;
965
+ while (html[i] !== '>' && !WHITESPACE.test(html[i])) i += 1;
966
+ value = html.slice(start, i);
967
+
968
+ i -= 1;
969
+ }
970
+
971
+ if (name === 'href') {
972
+ href = value;
973
+ } else if (name === 'rel') {
974
+ rel = value;
975
+ } else if (name === 'src') {
976
+ hrefs.push(value);
977
+ } else if (name === 'srcset') {
978
+ const candidates = [];
979
+ let insideURL = true;
980
+ value = value.trim();
981
+ for (let i = 0; i < value.length; i++) {
982
+ if (value[i] === ',' && (!insideURL || (insideURL && value[i + 1] === ' '))) {
983
+ candidates.push(value.slice(0, i));
984
+ value = value.substring(i + 1).trim();
985
+ i = 0;
986
+ insideURL = true;
987
+ } else if (value[i] === ' ') {
988
+ insideURL = false;
989
+ }
990
+ }
991
+ candidates.push(value);
992
+ for (const candidate of candidates) {
993
+ const src = candidate.split(WHITESPACE)[0];
994
+ hrefs.push(src);
995
+ }
996
+ }
997
+ } else {
998
+ i -= 1;
999
+ }
1000
+ }
1001
+
1002
+ i += 1;
1003
+ }
1004
+
1005
+ if (href && !/\bexternal\b/i.test(rel)) {
1006
+ hrefs.push(href);
1007
+ }
1008
+ }
1009
+ }
1010
+
1011
+ i += 1;
1012
+ }
1013
+
1014
+ return hrefs;
1015
+ }
1016
+
1017
+ /**
1018
+ * Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
1019
+ *
1020
+ * The first closes the script element, so everything after is treated as raw HTML.
1021
+ * The second disables further parsing until `-->`, so the script element might be unexpectedly
1022
+ * kept open until until an unrelated HTML comment in the page.
1023
+ *
1024
+ * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
1025
+ * browsers.
1026
+ *
1027
+ * @see tests for unsafe parsing examples.
1028
+ * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
1029
+ * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
1030
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
1031
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
1032
+ * @see https://github.com/tc39/proposal-json-superset
1033
+ * @type {Record<string, string>}
1034
+ */
1035
+ const render_json_payload_script_dict = {
1036
+ '<': '\\u003C',
1037
+ '\u2028': '\\u2028',
1038
+ '\u2029': '\\u2029'
1039
+ };
1040
+
1041
+ new RegExp(
1042
+ `[${Object.keys(render_json_payload_script_dict).join('')}]`,
1043
+ 'g'
1044
+ );
1045
+
1046
+ /**
1047
+ * When inside a double-quoted attribute value, only `&` and `"` hold special meaning.
1048
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state
1049
+ * @type {Record<string, string>}
1050
+ */
1051
+ const escape_html_attr_dict = {
1052
+ '&': '&amp;',
1053
+ '"': '&quot;'
1054
+ };
1055
+
1056
+ const escape_html_attr_regex = new RegExp(
1057
+ // special characters
1058
+ `[${Object.keys(escape_html_attr_dict).join('')}]|` +
1059
+ // high surrogate without paired low surrogate
1060
+ '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' +
1061
+ // a valid surrogate pair, the only match with 2 code units
1062
+ // we match it so that we can match unpaired low surrogates in the same pass
1063
+ // TODO: use lookbehind assertions once they are widely supported: (?<![\ud800-udbff])[\udc00-\udfff]
1064
+ '[\\ud800-\\udbff][\\udc00-\\udfff]|' +
1065
+ // unpaired low surrogate (see previous match)
1066
+ '[\\udc00-\\udfff]',
1067
+ 'g'
1068
+ );
1069
+
1070
+ /**
1071
+ * Formats a string to be used as an attribute's value in raw HTML.
1072
+ *
1073
+ * It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes
1074
+ * characters that are special in attributes, and surrounds the whole string in double-quotes.
1075
+ *
1076
+ * @param {string} str
1077
+ * @returns {string} Escaped string surrounded by double-quotes.
1078
+ * @example const html = `<tag data-value=${escape_html_attr('value')}>...</tag>`;
1079
+ */
1080
+ function escape_html_attr(str) {
1081
+ const escaped_str = str.replace(escape_html_attr_regex, (match) => {
1082
+ if (match.length === 2) {
1083
+ // valid surrogate pair
1084
+ return match;
1085
+ }
1086
+
1087
+ return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`;
1088
+ });
1089
+
1090
+ return `"${escaped_str}"`;
1091
+ }
1092
+
1093
+ /**
1094
+ * @typedef {import('types').PrerenderErrorHandler} PrerenderErrorHandler
1095
+ * @typedef {import('types').Logger} Logger
1096
+ */
1097
+
1098
+ /**
1099
+ * @param {Parameters<PrerenderErrorHandler>[0]} details
1100
+ * @param {import('types').ValidatedKitConfig} config
1101
+ */
1102
+ function format_error({ status, path, referrer, referenceType }, config) {
1103
+ const message =
1104
+ status === 404 && !path.startsWith(config.paths.base)
1105
+ ? `${path} does not begin with \`base\`, which is configured in \`paths.base\` and can be imported from \`$app/paths\``
1106
+ : path;
1107
+
1108
+ return `${status} ${message}${referrer ? ` (${referenceType} from ${referrer})` : ''}`;
1109
+ }
1110
+
1111
+ /**
1112
+ * @param {Logger} log
1113
+ * @param {import('types').ValidatedKitConfig} config
1114
+ * @returns {PrerenderErrorHandler}
1115
+ */
1116
+ function normalise_error_handler(log, config) {
1117
+ switch (config.prerender.onError) {
1118
+ case 'continue':
1119
+ return (details) => {
1120
+ log.error(format_error(details, config));
1121
+ };
1122
+ case 'fail':
1123
+ return (details) => {
1124
+ throw new Error(format_error(details, config));
1125
+ };
1126
+ default:
1127
+ return config.prerender.onError;
1128
+ }
1129
+ }
1130
+
1131
+ const OK = 2;
1132
+ const REDIRECT = 3;
1133
+
1134
+ /**
1135
+ * @param {{
1136
+ * config: import('types').ValidatedKitConfig;
1137
+ * client_out_dir: string;
1138
+ * manifest_path: string;
1139
+ * log: Logger;
1140
+ * }} opts
1141
+ */
1142
+ async function prerender({ config, client_out_dir, manifest_path, log }) {
1143
+ /** @type {import('types').Prerendered} */
1144
+ const prerendered = {
1145
+ pages: new Map(),
1146
+ assets: new Map(),
1147
+ redirects: new Map(),
1148
+ paths: []
1149
+ };
1150
+
1151
+ if (!config.prerender.enabled) {
1152
+ return prerendered;
1153
+ }
1154
+
1155
+ installPolyfills();
1156
+ const { fetch } = globalThis;
1157
+ globalThis.fetch = async (info, init) => {
1158
+ /** @type {string} */
1159
+ let url;
1160
+
1161
+ /** @type {RequestInit} */
1162
+ let opts = {};
1163
+
1164
+ if (info instanceof Request) {
1165
+ url = info.url;
1166
+
1167
+ opts = {
1168
+ method: info.method,
1169
+ headers: info.headers,
1170
+ body: info.body,
1171
+ mode: info.mode,
1172
+ credentials: info.credentials,
1173
+ cache: info.cache,
1174
+ redirect: info.redirect,
1175
+ referrer: info.referrer,
1176
+ integrity: info.integrity
1177
+ };
1178
+ } else {
1179
+ url = info.toString();
1180
+ }
1181
+
1182
+ if (url.startsWith(config.prerender.origin + '/')) {
1183
+ const request = new Request(url, opts);
1184
+ const response = await server.respond(request, {
1185
+ getClientAddress,
1186
+ prerendering: {
1187
+ dependencies: new Map()
1188
+ }
1189
+ });
1190
+
1191
+ const decoded = new URL$1(url).pathname;
1192
+
1193
+ save(
1194
+ 'dependencies',
1195
+ response,
1196
+ Buffer.from(await response.clone().arrayBuffer()),
1197
+ decoded,
1198
+ encodeURI(decoded),
1199
+ null,
1200
+ 'fetched'
1201
+ );
1202
+
1203
+ return response;
1204
+ }
1205
+
1206
+ return fetch(info, init);
1207
+ };
1208
+
1209
+ const server_root = join(config.outDir, 'output');
1210
+
1211
+ /** @type {import('types').ServerModule} */
1212
+ const { Server, override } = await import(pathToFileURL(`${server_root}/server/index.js`).href);
1213
+
1214
+ /** @type {import('types').SSRManifest} */
1215
+ const manifest = (await import(pathToFileURL(`${server_root}/server/manifest.js`).href)).manifest;
1216
+
1217
+ override({
1218
+ paths: config.paths,
1219
+ prerendering: true,
1220
+ read: (file) => readFileSync(join(config.files.assets, file))
1221
+ });
1222
+
1223
+ const server = new Server(manifest);
1224
+
1225
+ const error = normalise_error_handler(log, config);
1226
+
1227
+ const q = queue(config.prerender.concurrency);
1228
+
1229
+ /**
1230
+ * @param {string} path
1231
+ * @param {boolean} is_html
1232
+ */
1233
+ function output_filename(path, is_html) {
1234
+ const file = path.slice(config.paths.base.length + 1) || 'index.html';
1235
+
1236
+ if (is_html && !file.endsWith('.html')) {
1237
+ return file + (file.endsWith('/') ? 'index.html' : '.html');
1238
+ }
1239
+
1240
+ return file;
1241
+ }
1242
+
1243
+ const files = new Set(walk(client_out_dir).map(posixify));
1244
+ const seen = new Set();
1245
+ const written = new Set();
1246
+
1247
+ /**
1248
+ * @param {string | null} referrer
1249
+ * @param {string} decoded
1250
+ * @param {string} [encoded]
1251
+ */
1252
+ function enqueue(referrer, decoded, encoded) {
1253
+ if (seen.has(decoded)) return;
1254
+ seen.add(decoded);
1255
+
1256
+ const file = decoded.slice(config.paths.base.length + 1);
1257
+ if (files.has(file)) return;
1258
+
1259
+ return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer));
1260
+ }
1261
+
1262
+ /**
1263
+ * @param {string} decoded
1264
+ * @param {string} encoded
1265
+ * @param {string?} referrer
1266
+ */
1267
+ async function visit(decoded, encoded, referrer) {
1268
+ if (!decoded.startsWith(config.paths.base)) {
1269
+ error({ status: 404, path: decoded, referrer, referenceType: 'linked' });
1270
+ return;
1271
+ }
1272
+
1273
+ /** @type {Map<string, import('types').PrerenderDependency>} */
1274
+ const dependencies = new Map();
1275
+
1276
+ const response = await server.respond(new Request(config.prerender.origin + encoded), {
1277
+ getClientAddress,
1278
+ prerendering: {
1279
+ dependencies
1280
+ }
1281
+ });
1282
+
1283
+ const body = Buffer.from(await response.arrayBuffer());
1284
+
1285
+ save('pages', response, body, decoded, encoded, referrer, 'linked');
1286
+
1287
+ for (const [dependency_path, result] of dependencies) {
1288
+ // this seems circuitous, but using new URL allows us to not care
1289
+ // whether dependency_path is encoded or not
1290
+ const encoded_dependency_path = new URL$1(dependency_path, 'http://localhost').pathname;
1291
+ const decoded_dependency_path = decodeURI(encoded_dependency_path);
1292
+
1293
+ const body = result.body ?? new Uint8Array(await result.response.arrayBuffer());
1294
+ save(
1295
+ 'dependencies',
1296
+ result.response,
1297
+ body,
1298
+ decoded_dependency_path,
1299
+ encoded_dependency_path,
1300
+ decoded,
1301
+ 'fetched'
1302
+ );
1303
+ }
1304
+
1305
+ if (config.prerender.crawl && response.headers.get('content-type') === 'text/html') {
1306
+ for (const href of crawl(body.toString())) {
1307
+ if (href.startsWith('data:') || href.startsWith('#')) continue;
1308
+
1309
+ const resolved = resolve(encoded, href);
1310
+ if (!is_root_relative(resolved)) continue;
1311
+
1312
+ const { pathname, search } = new URL$1(resolved, 'http://localhost');
1313
+
1314
+ enqueue(decoded, decodeURI(pathname), pathname);
1315
+ }
1316
+ }
1317
+ }
1318
+
1319
+ /**
1320
+ * @param {'pages' | 'dependencies'} category
1321
+ * @param {Response} response
1322
+ * @param {string | Uint8Array} body
1323
+ * @param {string} decoded
1324
+ * @param {string} encoded
1325
+ * @param {string | null} referrer
1326
+ * @param {'linked' | 'fetched'} referenceType
1327
+ */
1328
+ function save(category, response, body, decoded, encoded, referrer, referenceType) {
1329
+ const response_type = Math.floor(response.status / 100);
1330
+ const type = /** @type {string} */ (response.headers.get('content-type'));
1331
+ const is_html = response_type === REDIRECT || type === 'text/html';
1332
+
1333
+ const file = output_filename(decoded, is_html);
1334
+ const dest = `${config.outDir}/output/prerendered/${category}/${file}`;
1335
+
1336
+ if (written.has(file)) return;
1337
+
1338
+ if (response_type === REDIRECT) {
1339
+ const location = response.headers.get('location');
1340
+
1341
+ if (location) {
1342
+ const resolved = resolve(encoded, location);
1343
+ if (is_root_relative(resolved)) {
1344
+ enqueue(decoded, decodeURI(resolved), resolved);
1345
+ }
1346
+
1347
+ if (!response.headers.get('x-sveltekit-normalize')) {
1348
+ mkdirp(dirname(dest));
1349
+
1350
+ log.warn(`${response.status} ${decoded} -> ${location}`);
1351
+
1352
+ writeFileSync(
1353
+ dest,
1354
+ `<meta http-equiv="refresh" content=${escape_html_attr(`0;url=${location}`)}>`
1355
+ );
1356
+
1357
+ written.add(file);
1358
+
1359
+ if (!prerendered.redirects.has(decoded)) {
1360
+ prerendered.redirects.set(decoded, {
1361
+ status: response.status,
1362
+ location: resolved
1363
+ });
1364
+
1365
+ prerendered.paths.push(decoded);
1366
+ }
1367
+ }
1368
+ } else {
1369
+ log.warn(`location header missing on redirect received from ${decoded}`);
1370
+ }
1371
+
1372
+ return;
1373
+ }
1374
+
1375
+ if (response.status === 200) {
1376
+ mkdirp(dirname(dest));
1377
+
1378
+ log.info(`${response.status} ${decoded}`);
1379
+ writeFileSync(dest, body);
1380
+ written.add(file);
1381
+
1382
+ if (is_html) {
1383
+ prerendered.pages.set(decoded, {
1384
+ file
1385
+ });
1386
+ } else {
1387
+ prerendered.assets.set(decoded, {
1388
+ type
1389
+ });
1390
+ }
1391
+
1392
+ prerendered.paths.push(decoded);
1393
+ } else if (response_type !== OK) {
1394
+ error({ status: response.status, path: decoded, referrer, referenceType });
1395
+ }
1396
+ }
1397
+
1398
+ if (config.prerender.enabled) {
1399
+ for (const entry of config.prerender.entries) {
1400
+ if (entry === '*') {
1401
+ /** @type {import('types').ManifestData} */
1402
+ const { routes } = (await import(pathToFileURL(manifest_path).href)).manifest._;
1403
+ const entries = routes
1404
+ .map((route) => (route.type === 'page' ? route.path : ''))
1405
+ .filter(Boolean);
1406
+
1407
+ for (const entry of entries) {
1408
+ enqueue(null, config.paths.base + entry); // TODO can we pre-normalize these?
1409
+ }
1410
+ } else {
1411
+ enqueue(null, config.paths.base + entry);
1412
+ }
1413
+ }
1414
+
1415
+ await q.done();
1416
+ }
1417
+
1418
+ const rendered = await server.respond(new Request(config.prerender.origin + '/[fallback]'), {
1419
+ getClientAddress,
1420
+ prerendering: {
1421
+ fallback: true,
1422
+ dependencies: new Map()
1423
+ }
1424
+ });
1425
+
1426
+ const file = `${config.outDir}/output/prerendered/fallback.html`;
1427
+ mkdirp(dirname(file));
1428
+ writeFileSync(file, await rendered.text());
1429
+
1430
+ return prerendered;
1431
+ }
1432
+
1433
+ /** @return {string} */
1434
+ function getClientAddress() {
1435
+ throw new Error('Cannot read clientAddress during prerendering');
1436
+ }
1437
+
1438
+ function totalist(dir, callback, pre='') {
1439
+ dir = resolve$1('.', dir);
1440
+ let arr = readdirSync(dir);
1441
+ let i=0, abs, stats;
1442
+ for (; i < arr.length; i++) {
1443
+ abs = join(dir, arr[i]);
1444
+ stats = statSync(abs);
1445
+ stats.isDirectory()
1446
+ ? totalist(abs, callback, join(pre, arr[i]))
1447
+ : callback(join(pre, arr[i]), abs, stats);
1448
+ }
1449
+ }
1450
+
1451
+ /**
1452
+ * @typedef ParsedURL
1453
+ * @type {import('.').ParsedURL}
1454
+ */
1455
+
1456
+ /**
1457
+ * @typedef Request
1458
+ * @property {string} url
1459
+ * @property {ParsedURL} _parsedUrl
1460
+ */
1461
+
1462
+ /**
1463
+ * @param {Request} req
1464
+ * @returns {ParsedURL|void}
1465
+ */
1466
+ function parse(req) {
1467
+ let raw = req.url;
1468
+ if (raw == null) return;
1469
+
1470
+ let prev = req._parsedUrl;
1471
+ if (prev && prev.raw === raw) return prev;
1472
+
1473
+ let pathname=raw, search='', query;
1474
+
1475
+ if (raw.length > 1) {
1476
+ let idx = raw.indexOf('?', 1);
1477
+
1478
+ if (idx !== -1) {
1479
+ search = raw.substring(idx);
1480
+ pathname = raw.substring(0, idx);
1481
+ if (search.length > 1) {
1482
+ query = qs.parse(search.substring(1));
1483
+ }
1484
+ }
1485
+ }
1486
+
1487
+ return req._parsedUrl = { pathname, search, query, raw };
1488
+ }
1489
+
1490
+ const mimes = {
1491
+ "ez": "application/andrew-inset",
1492
+ "aw": "application/applixware",
1493
+ "atom": "application/atom+xml",
1494
+ "atomcat": "application/atomcat+xml",
1495
+ "atomdeleted": "application/atomdeleted+xml",
1496
+ "atomsvc": "application/atomsvc+xml",
1497
+ "dwd": "application/atsc-dwd+xml",
1498
+ "held": "application/atsc-held+xml",
1499
+ "rsat": "application/atsc-rsat+xml",
1500
+ "bdoc": "application/bdoc",
1501
+ "xcs": "application/calendar+xml",
1502
+ "ccxml": "application/ccxml+xml",
1503
+ "cdfx": "application/cdfx+xml",
1504
+ "cdmia": "application/cdmi-capability",
1505
+ "cdmic": "application/cdmi-container",
1506
+ "cdmid": "application/cdmi-domain",
1507
+ "cdmio": "application/cdmi-object",
1508
+ "cdmiq": "application/cdmi-queue",
1509
+ "cu": "application/cu-seeme",
1510
+ "mpd": "application/dash+xml",
1511
+ "davmount": "application/davmount+xml",
1512
+ "dbk": "application/docbook+xml",
1513
+ "dssc": "application/dssc+der",
1514
+ "xdssc": "application/dssc+xml",
1515
+ "es": "application/ecmascript",
1516
+ "ecma": "application/ecmascript",
1517
+ "emma": "application/emma+xml",
1518
+ "emotionml": "application/emotionml+xml",
1519
+ "epub": "application/epub+zip",
1520
+ "exi": "application/exi",
1521
+ "fdt": "application/fdt+xml",
1522
+ "pfr": "application/font-tdpfr",
1523
+ "geojson": "application/geo+json",
1524
+ "gml": "application/gml+xml",
1525
+ "gpx": "application/gpx+xml",
1526
+ "gxf": "application/gxf",
1527
+ "gz": "application/gzip",
1528
+ "hjson": "application/hjson",
1529
+ "stk": "application/hyperstudio",
1530
+ "ink": "application/inkml+xml",
1531
+ "inkml": "application/inkml+xml",
1532
+ "ipfix": "application/ipfix",
1533
+ "its": "application/its+xml",
1534
+ "jar": "application/java-archive",
1535
+ "war": "application/java-archive",
1536
+ "ear": "application/java-archive",
1537
+ "ser": "application/java-serialized-object",
1538
+ "class": "application/java-vm",
1539
+ "js": "application/javascript",
1540
+ "mjs": "application/javascript",
1541
+ "json": "application/json",
1542
+ "map": "application/json",
1543
+ "json5": "application/json5",
1544
+ "jsonml": "application/jsonml+json",
1545
+ "jsonld": "application/ld+json",
1546
+ "lgr": "application/lgr+xml",
1547
+ "lostxml": "application/lost+xml",
1548
+ "hqx": "application/mac-binhex40",
1549
+ "cpt": "application/mac-compactpro",
1550
+ "mads": "application/mads+xml",
1551
+ "webmanifest": "application/manifest+json",
1552
+ "mrc": "application/marc",
1553
+ "mrcx": "application/marcxml+xml",
1554
+ "ma": "application/mathematica",
1555
+ "nb": "application/mathematica",
1556
+ "mb": "application/mathematica",
1557
+ "mathml": "application/mathml+xml",
1558
+ "mbox": "application/mbox",
1559
+ "mscml": "application/mediaservercontrol+xml",
1560
+ "metalink": "application/metalink+xml",
1561
+ "meta4": "application/metalink4+xml",
1562
+ "mets": "application/mets+xml",
1563
+ "maei": "application/mmt-aei+xml",
1564
+ "musd": "application/mmt-usd+xml",
1565
+ "mods": "application/mods+xml",
1566
+ "m21": "application/mp21",
1567
+ "mp21": "application/mp21",
1568
+ "mp4s": "application/mp4",
1569
+ "m4p": "application/mp4",
1570
+ "doc": "application/msword",
1571
+ "dot": "application/msword",
1572
+ "mxf": "application/mxf",
1573
+ "nq": "application/n-quads",
1574
+ "nt": "application/n-triples",
1575
+ "cjs": "application/node",
1576
+ "bin": "application/octet-stream",
1577
+ "dms": "application/octet-stream",
1578
+ "lrf": "application/octet-stream",
1579
+ "mar": "application/octet-stream",
1580
+ "so": "application/octet-stream",
1581
+ "dist": "application/octet-stream",
1582
+ "distz": "application/octet-stream",
1583
+ "pkg": "application/octet-stream",
1584
+ "bpk": "application/octet-stream",
1585
+ "dump": "application/octet-stream",
1586
+ "elc": "application/octet-stream",
1587
+ "deploy": "application/octet-stream",
1588
+ "exe": "application/octet-stream",
1589
+ "dll": "application/octet-stream",
1590
+ "deb": "application/octet-stream",
1591
+ "dmg": "application/octet-stream",
1592
+ "iso": "application/octet-stream",
1593
+ "img": "application/octet-stream",
1594
+ "msi": "application/octet-stream",
1595
+ "msp": "application/octet-stream",
1596
+ "msm": "application/octet-stream",
1597
+ "buffer": "application/octet-stream",
1598
+ "oda": "application/oda",
1599
+ "opf": "application/oebps-package+xml",
1600
+ "ogx": "application/ogg",
1601
+ "omdoc": "application/omdoc+xml",
1602
+ "onetoc": "application/onenote",
1603
+ "onetoc2": "application/onenote",
1604
+ "onetmp": "application/onenote",
1605
+ "onepkg": "application/onenote",
1606
+ "oxps": "application/oxps",
1607
+ "relo": "application/p2p-overlay+xml",
1608
+ "xer": "application/patch-ops-error+xml",
1609
+ "pdf": "application/pdf",
1610
+ "pgp": "application/pgp-encrypted",
1611
+ "asc": "application/pgp-signature",
1612
+ "sig": "application/pgp-signature",
1613
+ "prf": "application/pics-rules",
1614
+ "p10": "application/pkcs10",
1615
+ "p7m": "application/pkcs7-mime",
1616
+ "p7c": "application/pkcs7-mime",
1617
+ "p7s": "application/pkcs7-signature",
1618
+ "p8": "application/pkcs8",
1619
+ "ac": "application/pkix-attr-cert",
1620
+ "cer": "application/pkix-cert",
1621
+ "crl": "application/pkix-crl",
1622
+ "pkipath": "application/pkix-pkipath",
1623
+ "pki": "application/pkixcmp",
1624
+ "pls": "application/pls+xml",
1625
+ "ai": "application/postscript",
1626
+ "eps": "application/postscript",
1627
+ "ps": "application/postscript",
1628
+ "provx": "application/provenance+xml",
1629
+ "cww": "application/prs.cww",
1630
+ "pskcxml": "application/pskc+xml",
1631
+ "raml": "application/raml+yaml",
1632
+ "rdf": "application/rdf+xml",
1633
+ "owl": "application/rdf+xml",
1634
+ "rif": "application/reginfo+xml",
1635
+ "rnc": "application/relax-ng-compact-syntax",
1636
+ "rl": "application/resource-lists+xml",
1637
+ "rld": "application/resource-lists-diff+xml",
1638
+ "rs": "application/rls-services+xml",
1639
+ "rapd": "application/route-apd+xml",
1640
+ "sls": "application/route-s-tsid+xml",
1641
+ "rusd": "application/route-usd+xml",
1642
+ "gbr": "application/rpki-ghostbusters",
1643
+ "mft": "application/rpki-manifest",
1644
+ "roa": "application/rpki-roa",
1645
+ "rsd": "application/rsd+xml",
1646
+ "rss": "application/rss+xml",
1647
+ "rtf": "application/rtf",
1648
+ "sbml": "application/sbml+xml",
1649
+ "scq": "application/scvp-cv-request",
1650
+ "scs": "application/scvp-cv-response",
1651
+ "spq": "application/scvp-vp-request",
1652
+ "spp": "application/scvp-vp-response",
1653
+ "sdp": "application/sdp",
1654
+ "senmlx": "application/senml+xml",
1655
+ "sensmlx": "application/sensml+xml",
1656
+ "setpay": "application/set-payment-initiation",
1657
+ "setreg": "application/set-registration-initiation",
1658
+ "shf": "application/shf+xml",
1659
+ "siv": "application/sieve",
1660
+ "sieve": "application/sieve",
1661
+ "smi": "application/smil+xml",
1662
+ "smil": "application/smil+xml",
1663
+ "rq": "application/sparql-query",
1664
+ "srx": "application/sparql-results+xml",
1665
+ "gram": "application/srgs",
1666
+ "grxml": "application/srgs+xml",
1667
+ "sru": "application/sru+xml",
1668
+ "ssdl": "application/ssdl+xml",
1669
+ "ssml": "application/ssml+xml",
1670
+ "swidtag": "application/swid+xml",
1671
+ "tei": "application/tei+xml",
1672
+ "teicorpus": "application/tei+xml",
1673
+ "tfi": "application/thraud+xml",
1674
+ "tsd": "application/timestamped-data",
1675
+ "toml": "application/toml",
1676
+ "trig": "application/trig",
1677
+ "ttml": "application/ttml+xml",
1678
+ "ubj": "application/ubjson",
1679
+ "rsheet": "application/urc-ressheet+xml",
1680
+ "td": "application/urc-targetdesc+xml",
1681
+ "vxml": "application/voicexml+xml",
1682
+ "wasm": "application/wasm",
1683
+ "wgt": "application/widget",
1684
+ "hlp": "application/winhlp",
1685
+ "wsdl": "application/wsdl+xml",
1686
+ "wspolicy": "application/wspolicy+xml",
1687
+ "xaml": "application/xaml+xml",
1688
+ "xav": "application/xcap-att+xml",
1689
+ "xca": "application/xcap-caps+xml",
1690
+ "xdf": "application/xcap-diff+xml",
1691
+ "xel": "application/xcap-el+xml",
1692
+ "xns": "application/xcap-ns+xml",
1693
+ "xenc": "application/xenc+xml",
1694
+ "xhtml": "application/xhtml+xml",
1695
+ "xht": "application/xhtml+xml",
1696
+ "xlf": "application/xliff+xml",
1697
+ "xml": "application/xml",
1698
+ "xsl": "application/xml",
1699
+ "xsd": "application/xml",
1700
+ "rng": "application/xml",
1701
+ "dtd": "application/xml-dtd",
1702
+ "xop": "application/xop+xml",
1703
+ "xpl": "application/xproc+xml",
1704
+ "xslt": "application/xml",
1705
+ "xspf": "application/xspf+xml",
1706
+ "mxml": "application/xv+xml",
1707
+ "xhvml": "application/xv+xml",
1708
+ "xvml": "application/xv+xml",
1709
+ "xvm": "application/xv+xml",
1710
+ "yang": "application/yang",
1711
+ "yin": "application/yin+xml",
1712
+ "zip": "application/zip",
1713
+ "3gpp": "video/3gpp",
1714
+ "adp": "audio/adpcm",
1715
+ "amr": "audio/amr",
1716
+ "au": "audio/basic",
1717
+ "snd": "audio/basic",
1718
+ "mid": "audio/midi",
1719
+ "midi": "audio/midi",
1720
+ "kar": "audio/midi",
1721
+ "rmi": "audio/midi",
1722
+ "mxmf": "audio/mobile-xmf",
1723
+ "mp3": "audio/mpeg",
1724
+ "m4a": "audio/mp4",
1725
+ "mp4a": "audio/mp4",
1726
+ "mpga": "audio/mpeg",
1727
+ "mp2": "audio/mpeg",
1728
+ "mp2a": "audio/mpeg",
1729
+ "m2a": "audio/mpeg",
1730
+ "m3a": "audio/mpeg",
1731
+ "oga": "audio/ogg",
1732
+ "ogg": "audio/ogg",
1733
+ "spx": "audio/ogg",
1734
+ "opus": "audio/ogg",
1735
+ "s3m": "audio/s3m",
1736
+ "sil": "audio/silk",
1737
+ "wav": "audio/wav",
1738
+ "weba": "audio/webm",
1739
+ "xm": "audio/xm",
1740
+ "ttc": "font/collection",
1741
+ "otf": "font/otf",
1742
+ "ttf": "font/ttf",
1743
+ "woff": "font/woff",
1744
+ "woff2": "font/woff2",
1745
+ "exr": "image/aces",
1746
+ "apng": "image/apng",
1747
+ "avif": "image/avif",
1748
+ "bmp": "image/bmp",
1749
+ "cgm": "image/cgm",
1750
+ "drle": "image/dicom-rle",
1751
+ "emf": "image/emf",
1752
+ "fits": "image/fits",
1753
+ "g3": "image/g3fax",
1754
+ "gif": "image/gif",
1755
+ "heic": "image/heic",
1756
+ "heics": "image/heic-sequence",
1757
+ "heif": "image/heif",
1758
+ "heifs": "image/heif-sequence",
1759
+ "hej2": "image/hej2k",
1760
+ "hsj2": "image/hsj2",
1761
+ "ief": "image/ief",
1762
+ "jls": "image/jls",
1763
+ "jp2": "image/jp2",
1764
+ "jpg2": "image/jp2",
1765
+ "jpeg": "image/jpeg",
1766
+ "jpg": "image/jpeg",
1767
+ "jpe": "image/jpeg",
1768
+ "jph": "image/jph",
1769
+ "jhc": "image/jphc",
1770
+ "jpm": "image/jpm",
1771
+ "jpx": "image/jpx",
1772
+ "jpf": "image/jpx",
1773
+ "jxr": "image/jxr",
1774
+ "jxra": "image/jxra",
1775
+ "jxrs": "image/jxrs",
1776
+ "jxs": "image/jxs",
1777
+ "jxsc": "image/jxsc",
1778
+ "jxsi": "image/jxsi",
1779
+ "jxss": "image/jxss",
1780
+ "ktx": "image/ktx",
1781
+ "ktx2": "image/ktx2",
1782
+ "png": "image/png",
1783
+ "btif": "image/prs.btif",
1784
+ "pti": "image/prs.pti",
1785
+ "sgi": "image/sgi",
1786
+ "svg": "image/svg+xml",
1787
+ "svgz": "image/svg+xml",
1788
+ "t38": "image/t38",
1789
+ "tif": "image/tiff",
1790
+ "tiff": "image/tiff",
1791
+ "tfx": "image/tiff-fx",
1792
+ "webp": "image/webp",
1793
+ "wmf": "image/wmf",
1794
+ "disposition-notification": "message/disposition-notification",
1795
+ "u8msg": "message/global",
1796
+ "u8dsn": "message/global-delivery-status",
1797
+ "u8mdn": "message/global-disposition-notification",
1798
+ "u8hdr": "message/global-headers",
1799
+ "eml": "message/rfc822",
1800
+ "mime": "message/rfc822",
1801
+ "3mf": "model/3mf",
1802
+ "gltf": "model/gltf+json",
1803
+ "glb": "model/gltf-binary",
1804
+ "igs": "model/iges",
1805
+ "iges": "model/iges",
1806
+ "msh": "model/mesh",
1807
+ "mesh": "model/mesh",
1808
+ "silo": "model/mesh",
1809
+ "mtl": "model/mtl",
1810
+ "obj": "model/obj",
1811
+ "stpz": "model/step+zip",
1812
+ "stpxz": "model/step-xml+zip",
1813
+ "stl": "model/stl",
1814
+ "wrl": "model/vrml",
1815
+ "vrml": "model/vrml",
1816
+ "x3db": "model/x3d+fastinfoset",
1817
+ "x3dbz": "model/x3d+binary",
1818
+ "x3dv": "model/x3d-vrml",
1819
+ "x3dvz": "model/x3d+vrml",
1820
+ "x3d": "model/x3d+xml",
1821
+ "x3dz": "model/x3d+xml",
1822
+ "appcache": "text/cache-manifest",
1823
+ "manifest": "text/cache-manifest",
1824
+ "ics": "text/calendar",
1825
+ "ifb": "text/calendar",
1826
+ "coffee": "text/coffeescript",
1827
+ "litcoffee": "text/coffeescript",
1828
+ "css": "text/css",
1829
+ "csv": "text/csv",
1830
+ "html": "text/html",
1831
+ "htm": "text/html",
1832
+ "shtml": "text/html",
1833
+ "jade": "text/jade",
1834
+ "jsx": "text/jsx",
1835
+ "less": "text/less",
1836
+ "markdown": "text/markdown",
1837
+ "md": "text/markdown",
1838
+ "mml": "text/mathml",
1839
+ "mdx": "text/mdx",
1840
+ "n3": "text/n3",
1841
+ "txt": "text/plain",
1842
+ "text": "text/plain",
1843
+ "conf": "text/plain",
1844
+ "def": "text/plain",
1845
+ "list": "text/plain",
1846
+ "log": "text/plain",
1847
+ "in": "text/plain",
1848
+ "ini": "text/plain",
1849
+ "dsc": "text/prs.lines.tag",
1850
+ "rtx": "text/richtext",
1851
+ "sgml": "text/sgml",
1852
+ "sgm": "text/sgml",
1853
+ "shex": "text/shex",
1854
+ "slim": "text/slim",
1855
+ "slm": "text/slim",
1856
+ "spdx": "text/spdx",
1857
+ "stylus": "text/stylus",
1858
+ "styl": "text/stylus",
1859
+ "tsv": "text/tab-separated-values",
1860
+ "t": "text/troff",
1861
+ "tr": "text/troff",
1862
+ "roff": "text/troff",
1863
+ "man": "text/troff",
1864
+ "me": "text/troff",
1865
+ "ms": "text/troff",
1866
+ "ttl": "text/turtle",
1867
+ "uri": "text/uri-list",
1868
+ "uris": "text/uri-list",
1869
+ "urls": "text/uri-list",
1870
+ "vcard": "text/vcard",
1871
+ "vtt": "text/vtt",
1872
+ "yaml": "text/yaml",
1873
+ "yml": "text/yaml",
1874
+ "3gp": "video/3gpp",
1875
+ "3g2": "video/3gpp2",
1876
+ "h261": "video/h261",
1877
+ "h263": "video/h263",
1878
+ "h264": "video/h264",
1879
+ "m4s": "video/iso.segment",
1880
+ "jpgv": "video/jpeg",
1881
+ "jpgm": "image/jpm",
1882
+ "mj2": "video/mj2",
1883
+ "mjp2": "video/mj2",
1884
+ "ts": "video/mp2t",
1885
+ "mp4": "video/mp4",
1886
+ "mp4v": "video/mp4",
1887
+ "mpg4": "video/mp4",
1888
+ "mpeg": "video/mpeg",
1889
+ "mpg": "video/mpeg",
1890
+ "mpe": "video/mpeg",
1891
+ "m1v": "video/mpeg",
1892
+ "m2v": "video/mpeg",
1893
+ "ogv": "video/ogg",
1894
+ "qt": "video/quicktime",
1895
+ "mov": "video/quicktime",
1896
+ "webm": "video/webm"
1897
+ };
1898
+
1899
+ function lookup(extn) {
1900
+ let tmp = ('' + extn).trim().toLowerCase();
1901
+ let idx = tmp.lastIndexOf('.');
1902
+ return mimes[!~idx ? tmp : tmp.substring(++idx)];
1903
+ }
1904
+
1905
+ const noop = () => {};
1906
+
1907
+ function isMatch(uri, arr) {
1908
+ for (let i=0; i < arr.length; i++) {
1909
+ if (arr[i].test(uri)) return true;
1910
+ }
1911
+ }
1912
+
1913
+ function toAssume(uri, extns) {
1914
+ let i=0, x, len=uri.length - 1;
1915
+ if (uri.charCodeAt(len) === 47) {
1916
+ uri = uri.substring(0, len);
1917
+ }
1918
+
1919
+ let arr=[], tmp=`${uri}/index`;
1920
+ for (; i < extns.length; i++) {
1921
+ x = extns[i] ? `.${extns[i]}` : '';
1922
+ if (uri) arr.push(uri + x);
1923
+ arr.push(tmp + x);
1924
+ }
1925
+
1926
+ return arr;
1927
+ }
1928
+
1929
+ function viaCache(cache, uri, extns) {
1930
+ let i=0, data, arr=toAssume(uri, extns);
1931
+ for (; i < arr.length; i++) {
1932
+ if (data = cache[arr[i]]) return data;
1933
+ }
1934
+ }
1935
+
1936
+ function viaLocal(dir, isEtag, uri, extns) {
1937
+ let i=0, arr=toAssume(uri, extns);
1938
+ let abs, stats, name, headers;
1939
+ for (; i < arr.length; i++) {
1940
+ abs = normalize(join(dir, name=arr[i]));
1941
+ if (abs.startsWith(dir) && fs.existsSync(abs)) {
1942
+ stats = fs.statSync(abs);
1943
+ if (stats.isDirectory()) continue;
1944
+ headers = toHeaders(name, stats, isEtag);
1945
+ headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
1946
+ return { abs, stats, headers };
1947
+ }
1948
+ }
1949
+ }
1950
+
1951
+ function is404(req, res) {
1952
+ return (res.statusCode=404,res.end());
1953
+ }
1954
+
1955
+ function send(req, res, file, stats, headers) {
1956
+ let code=200, tmp, opts={};
1957
+ headers = { ...headers };
1958
+
1959
+ for (let key in headers) {
1960
+ tmp = res.getHeader(key);
1961
+ if (tmp) headers[key] = tmp;
1962
+ }
1963
+
1964
+ if (tmp = res.getHeader('content-type')) {
1965
+ headers['Content-Type'] = tmp;
1966
+ }
1967
+
1968
+ if (req.headers.range) {
1969
+ code = 206;
1970
+ let [x, y] = req.headers.range.replace('bytes=', '').split('-');
1971
+ let end = opts.end = parseInt(y, 10) || stats.size - 1;
1972
+ let start = opts.start = parseInt(x, 10) || 0;
1973
+
1974
+ if (start >= stats.size || end >= stats.size) {
1975
+ res.setHeader('Content-Range', `bytes */${stats.size}`);
1976
+ res.statusCode = 416;
1977
+ return res.end();
1978
+ }
1979
+
1980
+ headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
1981
+ headers['Content-Length'] = (end - start + 1);
1982
+ headers['Accept-Ranges'] = 'bytes';
1983
+ }
1984
+
1985
+ res.writeHead(code, headers);
1986
+ fs.createReadStream(file, opts).pipe(res);
1987
+ }
1988
+
1989
+ const ENCODING = {
1990
+ '.br': 'br',
1991
+ '.gz': 'gzip',
1992
+ };
1993
+
1994
+ function toHeaders(name, stats, isEtag) {
1995
+ let enc = ENCODING[name.slice(-3)];
1996
+
1997
+ let ctype = lookup(name.slice(0, enc && -3)) || '';
1998
+ if (ctype === 'text/html') ctype += ';charset=utf-8';
1999
+
2000
+ let headers = {
2001
+ 'Content-Length': stats.size,
2002
+ 'Content-Type': ctype,
2003
+ 'Last-Modified': stats.mtime.toUTCString(),
2004
+ };
2005
+
2006
+ if (enc) headers['Content-Encoding'] = enc;
2007
+ if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
2008
+
2009
+ return headers;
2010
+ }
2011
+
2012
+ function sirv (dir, opts={}) {
2013
+ dir = resolve$1(dir || '.');
2014
+
2015
+ let isNotFound = opts.onNoMatch || is404;
2016
+ let setHeaders = opts.setHeaders || noop;
2017
+
2018
+ let extensions = opts.extensions || ['html', 'htm'];
2019
+ let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
2020
+ let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
2021
+
2022
+ const FILES = {};
2023
+
2024
+ let fallback = '/';
2025
+ let isEtag = !!opts.etag;
2026
+ let isSPA = !!opts.single;
2027
+ if (typeof opts.single === 'string') {
2028
+ let idx = opts.single.lastIndexOf('.');
2029
+ fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
2030
+ }
2031
+
2032
+ let ignores = [];
2033
+ if (opts.ignores !== false) {
2034
+ ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
2035
+ if (opts.dotfiles) ignores.push(/\/\.\w/);
2036
+ else ignores.push(/\/\.well-known/);
2037
+ [].concat(opts.ignores || []).forEach(x => {
2038
+ ignores.push(new RegExp(x, 'i'));
2039
+ });
2040
+ }
2041
+
2042
+ let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
2043
+ if (cc && opts.immutable) cc += ',immutable';
2044
+ else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
2045
+
2046
+ if (!opts.dev) {
2047
+ totalist(dir, (name, abs, stats) => {
2048
+ if (/\.well-known[\\+\/]/.test(name)) ; // keep
2049
+ else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
2050
+
2051
+ let headers = toHeaders(name, stats, isEtag);
2052
+ if (cc) headers['Cache-Control'] = cc;
2053
+
2054
+ FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
2055
+ });
2056
+ }
2057
+
2058
+ let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
2059
+
2060
+ return function (req, res, next) {
2061
+ let extns = [''];
2062
+ let pathname = parse(req).pathname;
2063
+ let val = req.headers['accept-encoding'] || '';
2064
+ if (gzips && val.includes('gzip')) extns.unshift(...gzips);
2065
+ if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
2066
+ extns.push(...extensions); // [...br, ...gz, orig, ...exts]
2067
+
2068
+ if (pathname.indexOf('%') !== -1) {
2069
+ try { pathname = decodeURIComponent(pathname); }
2070
+ catch (err) { /* malform uri */ }
2071
+ }
2072
+
2073
+ let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
2074
+ if (!data) return next ? next() : isNotFound(req, res);
2075
+
2076
+ if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
2077
+ res.writeHead(304);
2078
+ return res.end();
2079
+ }
2080
+
2081
+ if (gzips || brots) {
2082
+ res.setHeader('Vary', 'Accept-Encoding');
2083
+ }
2084
+
2085
+ setHeaders(res, pathname, data.stats);
2086
+ send(req, res, data.abs, data.stats, data.headers);
2087
+ };
2088
+ }
2089
+
2090
+ // in `vite dev` and `vite preview`, we use a fake asset path so that we can
2091
+ // serve local assets while verifying that requests are correctly prefixed
2092
+ const SVELTE_KIT_ASSETS = '/_svelte_kit_assets';
2093
+
2094
+ // Vite doesn't expose this so we just copy the list for now
2095
+ // https://github.com/vitejs/vite/blob/3edd1af56e980aef56641a5a51cf2932bb580d41/packages/vite/src/node/plugins/css.ts#L96
2096
+ const style_pattern = /\.(css|less|sass|scss|styl|stylus|pcss|postcss)$/;
2097
+
2098
+ const cwd$1 = process.cwd();
2099
+
2100
+ /**
2101
+ * @param {import('vite').ViteDevServer} vite
2102
+ * @param {import('vite').ResolvedConfig} vite_config
2103
+ * @param {import('types').ValidatedConfig} svelte_config
2104
+ * @return {Promise<Promise<() => void>>}
2105
+ */
2106
+ async function dev(vite, vite_config, svelte_config) {
2107
+ installPolyfills();
2108
+
2109
+ init(svelte_config);
2110
+
2111
+ const runtime = get_runtime_prefix(svelte_config.kit);
2112
+
2113
+ /** @type {import('types').Respond} */
2114
+ const respond = (await import(`${runtime}/server/index.js`)).respond;
2115
+
2116
+ /** @type {import('types').SSRManifest} */
2117
+ let manifest;
2118
+
2119
+ function update_manifest() {
2120
+ const { manifest_data } = update(svelte_config);
2121
+
2122
+ manifest = {
2123
+ appDir: svelte_config.kit.appDir,
2124
+ assets: new Set(manifest_data.assets.map((asset) => asset.file)),
2125
+ mimeTypes: get_mime_lookup(manifest_data),
2126
+ _: {
2127
+ entry: {
2128
+ file: `/@fs${runtime}/client/start.js`,
2129
+ imports: [],
2130
+ stylesheets: []
2131
+ },
2132
+ nodes: manifest_data.components.map((id, index) => {
2133
+ return async () => {
2134
+ const url = id.startsWith('..') ? `/@fs${path__default.posix.resolve(id)}` : `/${id}`;
2135
+
2136
+ const module = /** @type {import('types').SSRComponent} */ (
2137
+ await vite.ssrLoadModule(url)
2138
+ );
2139
+
2140
+ return {
2141
+ module,
2142
+ index,
2143
+ file: url.endsWith('.svelte') ? url : url + '?import',
2144
+ imports: [],
2145
+ stylesheets: [],
2146
+ // in dev we inline all styles to avoid FOUC
2147
+ inline_styles: async () => {
2148
+ const node = await vite.moduleGraph.getModuleByUrl(url);
2149
+
2150
+ if (!node) throw new Error(`Could not find node for ${url}`);
2151
+
2152
+ const deps = new Set();
2153
+ await find_deps(vite, node, deps);
2154
+
2155
+ /** @type {Record<string, string>} */
2156
+ const styles = {};
2157
+
2158
+ for (const dep of deps) {
2159
+ const parsed = new URL$1(dep.url, 'http://localhost/');
2160
+ const query = parsed.searchParams;
2161
+
2162
+ if (
2163
+ style_pattern.test(dep.file) ||
2164
+ (query.has('svelte') && query.get('type') === 'style')
2165
+ ) {
2166
+ try {
2167
+ const mod = await vite.ssrLoadModule(dep.url);
2168
+ styles[dep.url] = mod.default;
2169
+ } catch {
2170
+ // this can happen with dynamically imported modules, I think
2171
+ // because the Vite module graph doesn't distinguish between
2172
+ // static and dynamic imports? TODO investigate, submit fix
2173
+ }
2174
+ }
2175
+ }
2176
+
2177
+ return styles;
2178
+ }
2179
+ };
2180
+ };
2181
+ }),
2182
+ routes: manifest_data.routes.map((route) => {
2183
+ const { pattern, names, types } = parse_route_id(route.id);
2184
+
2185
+ if (route.type === 'page') {
2186
+ return {
2187
+ type: 'page',
2188
+ id: route.id,
2189
+ pattern,
2190
+ names,
2191
+ types,
2192
+ shadow: route.shadow
2193
+ ? async () => {
2194
+ const url = path__default.resolve(cwd$1, /** @type {string} */ (route.shadow));
2195
+ return await vite.ssrLoadModule(url);
2196
+ }
2197
+ : null,
2198
+ a: route.a.map((id) => (id ? manifest_data.components.indexOf(id) : undefined)),
2199
+ b: route.b.map((id) => (id ? manifest_data.components.indexOf(id) : undefined))
2200
+ };
2201
+ }
2202
+
2203
+ return {
2204
+ type: 'endpoint',
2205
+ id: route.id,
2206
+ pattern,
2207
+ names,
2208
+ types,
2209
+ load: async () => {
2210
+ const url = path__default.resolve(cwd$1, route.file);
2211
+ return await vite.ssrLoadModule(url);
2212
+ }
2213
+ };
2214
+ }),
2215
+ matchers: async () => {
2216
+ /** @type {Record<string, import('types').ParamMatcher>} */
2217
+ const matchers = {};
2218
+
2219
+ for (const key in manifest_data.matchers) {
2220
+ const file = manifest_data.matchers[key];
2221
+ const url = path__default.resolve(cwd$1, file);
2222
+ const module = await vite.ssrLoadModule(url);
2223
+
2224
+ if (module.match) {
2225
+ matchers[key] = module.match;
2226
+ } else {
2227
+ throw new Error(`${file} does not export a \`match\` function`);
2228
+ }
2229
+ }
2230
+
2231
+ return matchers;
2232
+ }
2233
+ }
2234
+ };
2235
+ }
2236
+
2237
+ /** @param {Error} error */
2238
+ function fix_stack_trace(error) {
2239
+ return error.stack ? vite.ssrRewriteStacktrace(error.stack) : error.stack;
2240
+ }
2241
+
2242
+ update_manifest();
2243
+
2244
+ for (const event of ['add', 'unlink']) {
2245
+ vite.watcher.on(event, (file) => {
2246
+ if (file.startsWith(svelte_config.kit.files.routes + path__default.sep)) {
2247
+ update_manifest();
2248
+ }
2249
+ });
2250
+ }
2251
+
2252
+ const assets = svelte_config.kit.paths.assets ? SVELTE_KIT_ASSETS : svelte_config.kit.paths.base;
2253
+ const asset_server = sirv(svelte_config.kit.files.assets, {
2254
+ dev: true,
2255
+ etag: true,
2256
+ maxAge: 0,
2257
+ extensions: []
2258
+ });
2259
+
2260
+ return () => {
2261
+ const serve_static_middleware = vite.middlewares.stack.find(
2262
+ (middleware) =>
2263
+ /** @type {function} */ (middleware.handle).name === 'viteServeStaticMiddleware'
2264
+ );
2265
+
2266
+ remove_static_middlewares(vite.middlewares);
2267
+
2268
+ vite.middlewares.use(async (req, res) => {
2269
+ try {
2270
+ if (!req.url || !req.method) throw new Error('Incomplete request');
2271
+
2272
+ const base = `${vite.config.server.https ? 'https' : 'http'}://${
2273
+ req.headers[':authority'] || req.headers.host
2274
+ }`;
2275
+
2276
+ const decoded = decodeURI(new URL$1(base + req.url).pathname);
2277
+
2278
+ if (decoded.startsWith(assets)) {
2279
+ const pathname = decoded.slice(assets.length);
2280
+ const file = svelte_config.kit.files.assets + pathname;
2281
+
2282
+ if (fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory()) {
2283
+ if (has_correct_case(file, svelte_config.kit.files.assets)) {
2284
+ req.url = encodeURI(pathname); // don't need query/hash
2285
+ asset_server(req, res);
2286
+ return;
2287
+ }
2288
+ }
2289
+ }
2290
+
2291
+ const file = posixify(path__default.resolve(decoded.slice(1)));
2292
+ const is_file = fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory();
2293
+ const allowed =
2294
+ !vite_config.server.fs.strict ||
2295
+ vite_config.server.fs.allow.some((dir) => file.startsWith(dir));
2296
+
2297
+ if (is_file && allowed) {
2298
+ // @ts-expect-error
2299
+ serve_static_middleware.handle(req, res);
2300
+ return;
2301
+ }
2302
+
2303
+ if (!decoded.startsWith(svelte_config.kit.paths.base)) {
2304
+ return not_found(
2305
+ res,
2306
+ `Not found (did you mean ${svelte_config.kit.paths.base + req.url}?)`
2307
+ );
2308
+ }
2309
+
2310
+ /** @type {Partial<import('types').Hooks>} */
2311
+ const user_hooks = resolve_entry(svelte_config.kit.files.hooks)
2312
+ ? await vite.ssrLoadModule(`/${svelte_config.kit.files.hooks}`)
2313
+ : {};
2314
+
2315
+ const handle = user_hooks.handle || (({ event, resolve }) => resolve(event));
2316
+
2317
+ /** @type {import('types').Hooks} */
2318
+ const hooks = {
2319
+ getSession: user_hooks.getSession || (() => ({})),
2320
+ handle,
2321
+ handleError:
2322
+ user_hooks.handleError ||
2323
+ (({ /** @type {Error & { frame?: string }} */ error }) => {
2324
+ console.error($.bold().red(error.message));
2325
+ if (error.frame) {
2326
+ console.error($.gray(error.frame));
2327
+ }
2328
+ if (error.stack) {
2329
+ console.error($.gray(error.stack));
2330
+ }
2331
+ }),
2332
+ externalFetch: user_hooks.externalFetch || fetch
2333
+ };
2334
+
2335
+ if (/** @type {any} */ (hooks).getContext) {
2336
+ // TODO remove this for 1.0
2337
+ throw new Error(
2338
+ 'The getContext hook has been removed. See https://kit.svelte.dev/docs/hooks'
2339
+ );
2340
+ }
2341
+
2342
+ if (/** @type {any} */ (hooks).serverFetch) {
2343
+ // TODO remove this for 1.0
2344
+ throw new Error('The serverFetch hook has been renamed to externalFetch.');
2345
+ }
2346
+
2347
+ // TODO the / prefix will probably fail if outDir is outside the cwd (which
2348
+ // could be the case in a monorepo setup), but without it these modules
2349
+ // can get loaded twice via different URLs, which causes failures. Might
2350
+ // require changes to Vite to fix
2351
+ const { default: root } = await vite.ssrLoadModule(
2352
+ `/${posixify(path__default.relative(cwd$1, `${svelte_config.kit.outDir}/generated/root.svelte`))}`
2353
+ );
2354
+
2355
+ const paths = await vite.ssrLoadModule(
2356
+ true
2357
+ ? `/${posixify(path__default.relative(cwd$1, `${svelte_config.kit.outDir}/runtime/paths.js`))}`
2358
+ : `/@fs${runtime}/paths.js`
2359
+ );
2360
+
2361
+ paths.set_paths({
2362
+ base: svelte_config.kit.paths.base,
2363
+ assets
2364
+ });
2365
+
2366
+ let request;
2367
+
2368
+ try {
2369
+ request = await getRequest(base, req);
2370
+ } catch (/** @type {any} */ err) {
2371
+ res.statusCode = err.status || 400;
2372
+ return res.end(err.reason || 'Invalid request body');
2373
+ }
2374
+
2375
+ const template = load_template(cwd$1, svelte_config);
2376
+
2377
+ const rendered = await respond(
2378
+ request,
2379
+ {
2380
+ csp: svelte_config.kit.csp,
2381
+ dev: true,
2382
+ get_stack: (error) => fix_stack_trace(error),
2383
+ handle_error: (error, event) => {
2384
+ hooks.handleError({
2385
+ error: new Proxy(error, {
2386
+ get: (target, property) => {
2387
+ if (property === 'stack') {
2388
+ return fix_stack_trace(error);
2389
+ }
2390
+
2391
+ return Reflect.get(target, property, target);
2392
+ }
2393
+ }),
2394
+ event,
2395
+
2396
+ // TODO remove for 1.0
2397
+ // @ts-expect-error
2398
+ get request() {
2399
+ throw new Error(
2400
+ 'request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details'
2401
+ );
2402
+ }
2403
+ });
2404
+ },
2405
+ hooks,
2406
+ hydrate: svelte_config.kit.browser.hydrate,
2407
+ manifest,
2408
+ method_override: svelte_config.kit.methodOverride,
2409
+ paths: {
2410
+ base: svelte_config.kit.paths.base,
2411
+ assets
2412
+ },
2413
+ prefix: '',
2414
+ prerender: {
2415
+ default: svelte_config.kit.prerender.default,
2416
+ enabled: svelte_config.kit.prerender.enabled
2417
+ },
2418
+ read: (file) => fs__default.readFileSync(path__default.join(svelte_config.kit.files.assets, file)),
2419
+ root,
2420
+ router: svelte_config.kit.browser.router,
2421
+ template: ({ head, body, assets, nonce }) => {
2422
+ return (
2423
+ template
2424
+ .replace(/%sveltekit\.assets%/g, assets)
2425
+ .replace(/%sveltekit\.nonce%/g, nonce)
2426
+ // head and body must be replaced last, in case someone tries to sneak in %sveltekit.assets% etc
2427
+ .replace('%sveltekit.head%', () => head)
2428
+ .replace('%sveltekit.body%', () => body)
2429
+ );
2430
+ },
2431
+ template_contains_nonce: template.includes('%sveltekit.nonce%'),
2432
+ trailing_slash: svelte_config.kit.trailingSlash
2433
+ },
2434
+ {
2435
+ getClientAddress: () => {
2436
+ const { remoteAddress } = req.socket;
2437
+ if (remoteAddress) return remoteAddress;
2438
+ throw new Error('Could not determine clientAddress');
2439
+ }
2440
+ }
2441
+ );
2442
+
2443
+ if (rendered.status === 404) {
2444
+ // @ts-expect-error
2445
+ serve_static_middleware.handle(req, res, () => {
2446
+ setResponse(res, rendered);
2447
+ });
2448
+ } else {
2449
+ setResponse(res, rendered);
2450
+ }
2451
+ } catch (e) {
2452
+ const error = coalesce_to_error(e);
2453
+ res.statusCode = 500;
2454
+ res.end(fix_stack_trace(error));
2455
+ }
2456
+ });
2457
+ };
2458
+ }
2459
+
2460
+ /** @param {import('http').ServerResponse} res */
2461
+ function not_found(res, message = 'Not found') {
2462
+ res.statusCode = 404;
2463
+ res.end(message);
2464
+ }
2465
+
2466
+ /**
2467
+ * @param {import('connect').Server} server
2468
+ */
2469
+ function remove_static_middlewares(server) {
2470
+ // We don't use viteServePublicMiddleware because of the following issues:
2471
+ // https://github.com/vitejs/vite/issues/9260
2472
+ // https://github.com/vitejs/vite/issues/9236
2473
+ // https://github.com/vitejs/vite/issues/9234
2474
+ const static_middlewares = ['viteServePublicMiddleware', 'viteServeStaticMiddleware'];
2475
+ for (let i = server.stack.length - 1; i > 0; i--) {
2476
+ // @ts-expect-error using internals
2477
+ if (static_middlewares.includes(server.stack[i].handle.name)) {
2478
+ server.stack.splice(i, 1);
2479
+ }
2480
+ }
2481
+ }
2482
+
2483
+ /**
2484
+ * @param {import('vite').ViteDevServer} vite
2485
+ * @param {import('vite').ModuleNode} node
2486
+ * @param {Set<import('vite').ModuleNode>} deps
2487
+ */
2488
+ async function find_deps(vite, node, deps) {
2489
+ // since `ssrTransformResult.deps` contains URLs instead of `ModuleNode`s, this process is asynchronous.
2490
+ // instead of using `await`, we resolve all branches in parallel.
2491
+ /** @type {Promise<void>[]} */
2492
+ const branches = [];
2493
+
2494
+ /** @param {import('vite').ModuleNode} node */
2495
+ async function add(node) {
2496
+ if (!deps.has(node)) {
2497
+ deps.add(node);
2498
+ await find_deps(vite, node, deps);
2499
+ }
2500
+ }
2501
+
2502
+ /** @param {string} url */
2503
+ async function add_by_url(url) {
2504
+ const node = await vite.moduleGraph.getModuleByUrl(url);
2505
+
2506
+ if (node) {
2507
+ await add(node);
2508
+ }
2509
+ }
2510
+
2511
+ if (node.ssrTransformResult) {
2512
+ if (node.ssrTransformResult.deps) {
2513
+ node.ssrTransformResult.deps.forEach((url) => branches.push(add_by_url(url)));
2514
+ }
2515
+
2516
+ if (node.ssrTransformResult.dynamicDeps) {
2517
+ node.ssrTransformResult.dynamicDeps.forEach((url) => branches.push(add_by_url(url)));
2518
+ }
2519
+ } else {
2520
+ node.importedModules.forEach((node) => branches.push(add(node)));
2521
+ }
2522
+
2523
+ await Promise.all(branches);
2524
+ }
2525
+
2526
+ /**
2527
+ * Determine if a file is being requested with the correct case,
2528
+ * to ensure consistent behaviour between dev and prod and across
2529
+ * operating systems. Note that we can't use realpath here,
2530
+ * because we don't want to follow symlinks
2531
+ * @param {string} file
2532
+ * @param {string} assets
2533
+ * @returns {boolean}
2534
+ */
2535
+ function has_correct_case(file, assets) {
2536
+ if (file === assets) return true;
2537
+
2538
+ const parent = path__default.dirname(file);
2539
+
2540
+ if (fs__default.readdirSync(parent).includes(path__default.basename(file))) {
2541
+ return has_correct_case(parent, assets);
2542
+ }
2543
+
2544
+ return false;
2545
+ }
2546
+
2547
+ /**
2548
+ * Generates the data used to write the server-side manifest.js file. This data is used in the Vite
2549
+ * build process, to power routing, etc.
2550
+ * @param {{
2551
+ * build_data: import('types').BuildData;
2552
+ * relative_path: string;
2553
+ * routes: import('types').RouteData[];
2554
+ * format?: 'esm' | 'cjs'
2555
+ * }} opts
2556
+ */
2557
+ function generate_manifest({ build_data, relative_path, routes, format = 'esm' }) {
2558
+ /** @typedef {{ index: number, path: string }} LookupEntry */
2559
+ /** @type {Map<string, LookupEntry>} */
2560
+ const bundled_nodes = new Map();
2561
+
2562
+ // 0 and 1 are special, they correspond to the root layout and root error nodes
2563
+ bundled_nodes.set(build_data.manifest_data.components[0], {
2564
+ path: `${relative_path}/nodes/0.js`,
2565
+ index: 0
2566
+ });
2567
+
2568
+ bundled_nodes.set(build_data.manifest_data.components[1], {
2569
+ path: `${relative_path}/nodes/1.js`,
2570
+ index: 1
2571
+ });
2572
+
2573
+ routes.forEach((route) => {
2574
+ if (route.type === 'page') {
2575
+ [...route.a, ...route.b].forEach((component) => {
2576
+ if (component && !bundled_nodes.has(component)) {
2577
+ const i = build_data.manifest_data.components.indexOf(component);
2578
+
2579
+ bundled_nodes.set(component, {
2580
+ path: `${relative_path}/nodes/${i}.js`,
2581
+ index: bundled_nodes.size
2582
+ });
2583
+ }
2584
+ });
2585
+ }
2586
+ });
2587
+
2588
+ /** @type {(path: string) => string} */
2589
+ const load =
2590
+ format === 'esm'
2591
+ ? (path) => `import('${path}')`
2592
+ : (path) => `Promise.resolve().then(() => require('${path}'))`;
2593
+
2594
+ /** @type {(path: string) => string} */
2595
+ const loader = (path) => `() => ${load(path)}`;
2596
+
2597
+ const assets = build_data.manifest_data.assets.map((asset) => asset.file);
2598
+ if (build_data.service_worker) {
2599
+ assets.push(build_data.service_worker);
2600
+ }
2601
+
2602
+ /** @param {string | undefined} id */
2603
+ const get_index = (id) => id && /** @type {LookupEntry} */ (bundled_nodes.get(id)).index;
2604
+
2605
+ const matchers = new Set();
2606
+
2607
+ // prettier-ignore
2608
+ return `{
2609
+ appDir: ${s(build_data.app_dir)},
2610
+ assets: new Set(${s(assets)}),
2611
+ mimeTypes: ${s(get_mime_lookup(build_data.manifest_data))},
2612
+ _: {
2613
+ entry: ${s(build_data.client.entry)},
2614
+ nodes: [
2615
+ ${Array.from(bundled_nodes.values()).map(node => loader(node.path)).join(',\n\t\t\t\t')}
2616
+ ],
2617
+ routes: [
2618
+ ${routes.map(route => {
2619
+ const { pattern, names, types } = parse_route_id(route.id);
2620
+
2621
+ types.forEach(type => {
2622
+ if (type) matchers.add(type);
2623
+ });
2624
+
2625
+ if (route.type === 'page') {
2626
+ return `{
2627
+ type: 'page',
2628
+ id: ${s(route.id)},
2629
+ pattern: ${pattern},
2630
+ names: ${s(names)},
2631
+ types: ${s(types)},
2632
+ path: ${route.path ? s(route.path) : null},
2633
+ shadow: ${route.shadow ? loader(`${relative_path}/${build_data.server.vite_manifest[route.shadow].file}`) : null},
2634
+ a: ${s(route.a.map(get_index))},
2635
+ b: ${s(route.b.map(get_index))}
2636
+ }`.replace(/^\t\t/gm, '');
2637
+ } else {
2638
+ if (!build_data.server.vite_manifest[route.file]) {
2639
+ // this is necessary in cases where a .css file snuck in —
2640
+ // perhaps it would be better to disallow these (and others?)
2641
+ return null;
2642
+ }
2643
+
2644
+ return `{
2645
+ type: 'endpoint',
2646
+ id: ${s(route.id)},
2647
+ pattern: ${pattern},
2648
+ names: ${s(names)},
2649
+ types: ${s(types)},
2650
+ load: ${loader(`${relative_path}/${build_data.server.vite_manifest[route.file].file}`)}
2651
+ }`.replace(/^\t\t/gm, '');
2652
+ }
2653
+ }).filter(Boolean).join(',\n\t\t\t\t')}
2654
+ ],
2655
+ matchers: async () => {
2656
+ ${Array.from(matchers).map(type => `const { match: ${type} } = await ${load(`${relative_path}/entries/matchers/${type}.js`)}`).join('\n\t\t\t\t')}
2657
+ return { ${Array.from(matchers).join(', ')} };
2658
+ }
2659
+ }
2660
+ }`.replace(/^\t/gm, '');
2661
+ }
2662
+
2663
+ /** @typedef {import('http').IncomingMessage} Req */
2664
+ /** @typedef {import('http').ServerResponse} Res */
2665
+ /** @typedef {(req: Req, res: Res, next: () => void) => void} Handler */
2666
+
2667
+ /**
2668
+ * @param {{
2669
+ * middlewares: import('connect').Server;
2670
+ * httpServer: import('http').Server;
2671
+ * }} vite
2672
+ * @param {import('types').ValidatedConfig} config
2673
+ * @param {'http' | 'https'} protocol
2674
+ */
2675
+ async function preview(vite, config, protocol) {
2676
+ installPolyfills();
2677
+
2678
+ const { paths } = config.kit;
2679
+ const base = paths.base;
2680
+ const assets = paths.assets ? SVELTE_KIT_ASSETS : paths.base;
2681
+
2682
+ const etag = `"${Date.now()}"`;
2683
+
2684
+ const index_file = join(config.kit.outDir, 'output/server/index.js');
2685
+ const manifest_file = join(config.kit.outDir, 'output/server/manifest.js');
2686
+
2687
+ /** @type {import('types').ServerModule} */
2688
+ const { Server, override } = await import(pathToFileURL(index_file).href);
2689
+ const { manifest } = await import(pathToFileURL(manifest_file).href);
2690
+
2691
+ override({
2692
+ paths: { base, assets },
2693
+ prerendering: false,
2694
+ protocol,
2695
+ read: (file) => fs__default.readFileSync(join(config.kit.files.assets, file))
2696
+ });
2697
+
2698
+ const server = new Server(manifest);
2699
+
2700
+ return () => {
2701
+ // generated client assets and the contents of `static`
2702
+ vite.middlewares.use(
2703
+ scoped(
2704
+ assets,
2705
+ sirv(join(config.kit.outDir, 'output/client'), {
2706
+ setHeaders: (res, pathname) => {
2707
+ // only apply to immutable directory, not e.g. version.json
2708
+ if (pathname.startsWith(`/${config.kit.appDir}/immutable`)) {
2709
+ res.setHeader('cache-control', 'public,max-age=31536000,immutable');
2710
+ }
2711
+ }
2712
+ })
2713
+ )
2714
+ );
2715
+
2716
+ vite.middlewares.use((req, res, next) => {
2717
+ const original_url = /** @type {string} */ (req.url);
2718
+ const { pathname } = new URL(original_url, 'http://dummy');
2719
+
2720
+ if (pathname.startsWith(base)) {
2721
+ next();
2722
+ } else {
2723
+ res.statusCode = 404;
2724
+ res.end(`Not found (did you mean ${base + pathname}?)`);
2725
+ }
2726
+ });
2727
+
2728
+ // prerendered dependencies
2729
+ vite.middlewares.use(
2730
+ scoped(base, mutable(join(config.kit.outDir, 'output/prerendered/dependencies')))
2731
+ );
2732
+
2733
+ // prerendered pages (we can't just use sirv because we need to
2734
+ // preserve the correct trailingSlash behaviour)
2735
+ vite.middlewares.use(
2736
+ scoped(base, (req, res, next) => {
2737
+ let if_none_match_value = req.headers['if-none-match'];
2738
+
2739
+ if (if_none_match_value?.startsWith('W/"')) {
2740
+ if_none_match_value = if_none_match_value.substring(2);
2741
+ }
2742
+
2743
+ if (if_none_match_value === etag) {
2744
+ res.statusCode = 304;
2745
+ res.end();
2746
+ return;
2747
+ }
2748
+
2749
+ const { pathname } = new URL(/** @type {string} */ (req.url), 'http://dummy');
2750
+
2751
+ // only treat this as a page if it doesn't include an extension
2752
+ if (pathname === '/' || /\/[^./]+\/?$/.test(pathname)) {
2753
+ const file = join(
2754
+ config.kit.outDir,
2755
+ 'output/prerendered/pages' +
2756
+ pathname +
2757
+ (pathname.endsWith('/') ? 'index.html' : '.html')
2758
+ );
2759
+
2760
+ if (fs__default.existsSync(file)) {
2761
+ res.writeHead(200, {
2762
+ 'content-type': 'text/html',
2763
+ etag
2764
+ });
2765
+
2766
+ fs__default.createReadStream(file).pipe(res);
2767
+ return;
2768
+ }
2769
+ }
2770
+
2771
+ next();
2772
+ })
2773
+ );
2774
+
2775
+ // SSR
2776
+ vite.middlewares.use(async (req, res) => {
2777
+ const host = req.headers['host'];
2778
+
2779
+ let request;
2780
+
2781
+ try {
2782
+ request = await getRequest(`${protocol}://${host}`, req);
2783
+ } catch (/** @type {any} */ err) {
2784
+ res.statusCode = err.status || 400;
2785
+ return res.end(err.reason || 'Invalid request body');
2786
+ }
2787
+
2788
+ setResponse(
2789
+ res,
2790
+ await server.respond(request, {
2791
+ getClientAddress: () => {
2792
+ const { remoteAddress } = req.socket;
2793
+ if (remoteAddress) return remoteAddress;
2794
+ throw new Error('Could not determine clientAddress');
2795
+ }
2796
+ })
2797
+ );
2798
+ });
2799
+ };
2800
+ }
2801
+
2802
+ /**
2803
+ * @param {string} dir
2804
+ * @returns {Handler}
2805
+ */
2806
+ const mutable = (dir) =>
2807
+ fs__default.existsSync(dir)
2808
+ ? sirv(dir, {
2809
+ etag: true,
2810
+ maxAge: 0
2811
+ })
2812
+ : (req, res, next) => next();
2813
+
2814
+ /**
2815
+ * @param {string} scope
2816
+ * @param {Handler} handler
2817
+ * @returns {Handler}
2818
+ */
2819
+ function scoped(scope, handler) {
2820
+ if (scope === '') return handler;
2821
+
2822
+ return (req, res, next) => {
2823
+ if (req.url?.startsWith(scope)) {
2824
+ const original_url = req.url;
2825
+ req.url = req.url.slice(scope.length);
2826
+ handler(req, res, () => {
2827
+ req.url = original_url;
2828
+ next();
2829
+ });
2830
+ } else {
2831
+ next();
2832
+ }
2833
+ };
2834
+ }
2835
+
2836
+ const cwd = process.cwd();
2837
+
2838
+ /** @type {import('./types').EnforcedConfig} */
2839
+ const enforced_config = {
2840
+ appType: true,
2841
+ base: true,
2842
+ build: {
2843
+ cssCodeSplit: true,
2844
+ emptyOutDir: true,
2845
+ lib: {
2846
+ entry: true,
2847
+ name: true,
2848
+ formats: true
2849
+ },
2850
+ manifest: true,
2851
+ outDir: true,
2852
+ polyfillModulePreload: true,
2853
+ rollupOptions: {
2854
+ input: true,
2855
+ output: {
2856
+ format: true,
2857
+ entryFileNames: true,
2858
+ chunkFileNames: true,
2859
+ assetFileNames: true
2860
+ },
2861
+ preserveEntrySignatures: true
2862
+ },
2863
+ ssr: true
2864
+ },
2865
+ publicDir: true,
2866
+ resolve: {
2867
+ alias: {
2868
+ $app: true,
2869
+ $lib: true,
2870
+ '$service-worker': true
2871
+ }
2872
+ },
2873
+ root: true
2874
+ };
2875
+
2876
+ /**
2877
+ * @return {import('vite').Plugin[]}
2878
+ */
2879
+ function sveltekit() {
2880
+ return [...svelte(), kit()];
2881
+ }
2882
+
2883
+ /**
2884
+ * Returns the SvelteKit Vite plugin. Vite executes Rollup hooks as well as some of its own.
2885
+ * Background reading is available at:
2886
+ * - https://vitejs.dev/guide/api-plugin.html
2887
+ * - https://rollupjs.org/guide/en/#plugin-development
2888
+ *
2889
+ * You can get an idea of the lifecycle by looking at the flow charts here:
2890
+ * - https://rollupjs.org/guide/en/#build-hooks
2891
+ * - https://rollupjs.org/guide/en/#output-generation-hooks
2892
+ *
2893
+ * @return {import('vite').Plugin}
2894
+ */
2895
+ function kit() {
2896
+ /** @type {import('types').ValidatedConfig} */
2897
+ let svelte_config;
2898
+
2899
+ /** @type {import('vite').ResolvedConfig} */
2900
+ let vite_config;
2901
+
2902
+ /** @type {import('vite').ConfigEnv} */
2903
+ let vite_config_env;
2904
+
2905
+ /** @type {import('types').ManifestData} */
2906
+ let manifest_data;
2907
+
2908
+ /** @type {boolean} */
2909
+ let is_build;
2910
+
2911
+ /** @type {import('types').Logger} */
2912
+ let log;
2913
+
2914
+ /** @type {import('types').Prerendered} */
2915
+ let prerendered;
2916
+
2917
+ /** @type {import('types').BuildData} */
2918
+ let build_data;
2919
+
2920
+ /** @type {string | undefined} */
2921
+ let deferred_warning;
2922
+
2923
+ /**
2924
+ * @type {{
2925
+ * build_dir: string;
2926
+ * output_dir: string;
2927
+ * client_out_dir: string;
2928
+ * }}
2929
+ */
2930
+ let paths;
2931
+
2932
+ let completed_build = false;
2933
+
2934
+ function vite_client_build_config() {
2935
+ /** @type {Record<string, string>} */
2936
+ const input = {
2937
+ // Put unchanging assets in immutable directory. We don't set that in the
2938
+ // outDir so that other plugins can add mutable assets to the bundle
2939
+ start: `${get_runtime_directory(svelte_config.kit)}/client/start.js`
2940
+ };
2941
+
2942
+ // This step is optional — Vite/Rollup will create the necessary chunks
2943
+ // for everything regardless — but it means that entry chunks reflect
2944
+ // their location in the source code, which is helpful for debugging
2945
+ manifest_data.components.forEach((file) => {
2946
+ const resolved = path__default.resolve(cwd, file);
2947
+ const relative = decodeURIComponent(path__default.relative(svelte_config.kit.files.routes, resolved));
2948
+
2949
+ const name = relative.startsWith('..')
2950
+ ? path__default.basename(file)
2951
+ : posixify(path__default.join('pages', relative));
2952
+ input[name] = resolved;
2953
+ });
2954
+
2955
+ return get_default_config({
2956
+ config: svelte_config,
2957
+ input,
2958
+ ssr: false,
2959
+ outDir: `${paths.client_out_dir}`
2960
+ });
2961
+ }
2962
+
2963
+ /**
2964
+ * @param {import('rollup').OutputAsset[]} assets
2965
+ * @param {import('rollup').OutputChunk[]} chunks
2966
+ */
2967
+ function client_build_info(assets, chunks) {
2968
+ /** @type {import('vite').Manifest} */
2969
+ const vite_manifest = JSON.parse(
2970
+ fs__default.readFileSync(`${paths.client_out_dir}/manifest.json`, 'utf-8')
2971
+ );
2972
+
2973
+ const entry_id = posixify(
2974
+ path__default.relative(cwd, `${get_runtime_directory(svelte_config.kit)}/client/start.js`)
2975
+ );
2976
+
2977
+ return {
2978
+ assets,
2979
+ chunks,
2980
+ entry: find_deps$1(vite_manifest, entry_id, false),
2981
+ vite_manifest
2982
+ };
2983
+ }
2984
+
2985
+ // TODO remove this for 1.0
2986
+ check_vite_version();
2987
+
2988
+ return {
2989
+ name: 'vite-plugin-svelte-kit',
2990
+
2991
+ /**
2992
+ * Build the SvelteKit-provided Vite config to be merged with the user's vite.config.js file.
2993
+ * @see https://vitejs.dev/guide/api-plugin.html#config
2994
+ */
2995
+ async config(config, config_env) {
2996
+ vite_config_env = config_env;
2997
+ svelte_config = await load_config();
2998
+ is_build = config_env.command === 'build';
2999
+
3000
+ paths = {
3001
+ build_dir: `${svelte_config.kit.outDir}/build`,
3002
+ output_dir: `${svelte_config.kit.outDir}/output`,
3003
+ client_out_dir: `${svelte_config.kit.outDir}/output/client/`
3004
+ };
3005
+
3006
+ if (is_build) {
3007
+ manifest_data = all(svelte_config).manifest_data;
3008
+
3009
+ const new_config = vite_client_build_config();
3010
+
3011
+ const warning = warn_overridden_config(config, new_config);
3012
+ if (warning) console.error(warning + '\n');
3013
+
3014
+ return new_config;
3015
+ }
3016
+
3017
+ // dev and preview config can be shared
3018
+ /** @type {import('vite').UserConfig} */
3019
+ const result = {
3020
+ appType: 'custom',
3021
+ base: '/',
3022
+ build: {
3023
+ rollupOptions: {
3024
+ // Vite dependency crawler needs an explicit JS entry point
3025
+ // eventhough server otherwise works without it
3026
+ input: `${get_runtime_directory(svelte_config.kit)}/client/start.js`
3027
+ }
3028
+ },
3029
+ define: {
3030
+ __SVELTEKIT_DEV__: 'true',
3031
+ __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: '0'
3032
+ },
3033
+ publicDir: svelte_config.kit.files.assets,
3034
+ resolve: {
3035
+ alias: get_aliases(svelte_config.kit)
3036
+ },
3037
+ root: cwd,
3038
+ server: {
3039
+ fs: {
3040
+ allow: [
3041
+ ...new Set([
3042
+ svelte_config.kit.files.lib,
3043
+ svelte_config.kit.files.routes,
3044
+ svelte_config.kit.outDir,
3045
+ path__default.resolve(cwd, 'src'),
3046
+ path__default.resolve(cwd, 'node_modules'),
3047
+ path__default.resolve(vite.searchForWorkspaceRoot(cwd), 'node_modules')
3048
+ ])
3049
+ ]
3050
+ },
3051
+ watch: {
3052
+ ignored: [
3053
+ // Ignore all siblings of config.kit.outDir/generated
3054
+ `${posixify(svelte_config.kit.outDir)}/!(generated)`
3055
+ ]
3056
+ }
3057
+ }
3058
+ };
3059
+
3060
+ deferred_warning = warn_overridden_config(config, result);
3061
+ return result;
3062
+ },
3063
+
3064
+ /**
3065
+ * Stores the final config.
3066
+ */
3067
+ configResolved(config) {
3068
+ vite_config = config;
3069
+ },
3070
+
3071
+ /**
3072
+ * Clears the output directories.
3073
+ */
3074
+ buildStart() {
3075
+ // Reset for new build. Goes here because `build --watch` calls buildStart but not config
3076
+ completed_build = false;
3077
+
3078
+ if (is_build) {
3079
+ rimraf(paths.build_dir);
3080
+ mkdirp(paths.build_dir);
3081
+
3082
+ rimraf(paths.output_dir);
3083
+ mkdirp(paths.output_dir);
3084
+ }
3085
+ },
3086
+
3087
+ /**
3088
+ * Vite builds a single bundle. We need three bundles: client, server, and service worker.
3089
+ * The user's package.json scripts will invoke the Vite CLI to execute the client build. We
3090
+ * then use this hook to kick off builds for the server and service worker.
3091
+ */
3092
+ async writeBundle(_options, bundle) {
3093
+ log = logger({
3094
+ verbose: vite_config.logLevel === 'info'
3095
+ });
3096
+
3097
+ fs__default.writeFileSync(
3098
+ `${paths.client_out_dir}/${svelte_config.kit.appDir}/version.json`,
3099
+ JSON.stringify({ version: svelte_config.kit.version.name })
3100
+ );
3101
+
3102
+ const { assets, chunks } = collect_output(bundle);
3103
+ log.info(`Client build completed. Wrote ${chunks.length} chunks and ${assets.length} assets`);
3104
+
3105
+ log.info('Building server');
3106
+ const options = {
3107
+ cwd,
3108
+ config: svelte_config,
3109
+ vite_config_env,
3110
+ build_dir: paths.build_dir, // TODO just pass `paths`
3111
+ manifest_data,
3112
+ output_dir: paths.output_dir,
3113
+ service_worker_entry_file: resolve_entry(svelte_config.kit.files.serviceWorker)
3114
+ };
3115
+ const client = client_build_info(assets, chunks);
3116
+ const server = await build_server(options, client);
3117
+
3118
+ /** @type {import('types').BuildData} */
3119
+ build_data = {
3120
+ app_dir: svelte_config.kit.appDir,
3121
+ manifest_data,
3122
+ service_worker: options.service_worker_entry_file ? 'service-worker.js' : null, // TODO make file configurable?
3123
+ client,
3124
+ server
3125
+ };
3126
+
3127
+ const manifest_path = `${paths.output_dir}/server/manifest.js`;
3128
+ fs__default.writeFileSync(
3129
+ manifest_path,
3130
+ `export const manifest = ${generate_manifest({
3131
+ build_data,
3132
+ relative_path: '.',
3133
+ routes: manifest_data.routes
3134
+ })};\n`
3135
+ );
3136
+
3137
+ process.env.SVELTEKIT_SERVER_BUILD_COMPLETED = 'true';
3138
+ log.info('Prerendering');
3139
+
3140
+ prerendered = await prerender({
3141
+ config: svelte_config.kit,
3142
+ client_out_dir: vite_config.build.outDir,
3143
+ manifest_path,
3144
+ log
3145
+ });
3146
+
3147
+ if (options.service_worker_entry_file) {
3148
+ if (svelte_config.kit.paths.assets) {
3149
+ throw new Error('Cannot use service worker alongside config.kit.paths.assets');
3150
+ }
3151
+
3152
+ log.info('Building service worker');
3153
+
3154
+ await build_service_worker(options, prerendered, client.vite_manifest);
3155
+ }
3156
+
3157
+ console.log(
3158
+ `\nRun ${$.bold().cyan('npm run preview')} to preview your production build locally.`
3159
+ );
3160
+
3161
+ completed_build = true;
3162
+ },
3163
+
3164
+ /**
3165
+ * Runs the adapter.
3166
+ */
3167
+ async closeBundle() {
3168
+ if (!completed_build) {
3169
+ // vite calls closeBundle when dev-server restarts, ignore that,
3170
+ // and only adapt when build successfully completes.
3171
+ return;
3172
+ }
3173
+
3174
+ if (svelte_config.kit.adapter) {
3175
+ const { adapt } = await import('./chunks/index2.js');
3176
+ await adapt(svelte_config, build_data, prerendered, { log });
3177
+ } else {
3178
+ console.log($.bold().yellow('\nNo adapter specified'));
3179
+ // prettier-ignore
3180
+ console.log(
3181
+ `See ${$.bold().cyan('https://kit.svelte.dev/docs/adapters')} to learn how to configure your app to run on the platform of your choosing`
3182
+ );
3183
+ }
3184
+
3185
+ if (svelte_config.kit.prerender.enabled) {
3186
+ // this is necessary to close any open db connections, etc.
3187
+ // TODO: prerender in a subprocess so we can exit in isolation and then remove this
3188
+ // https://github.com/sveltejs/kit/issues/5306
3189
+ process.exit(0);
3190
+ }
3191
+ },
3192
+
3193
+ /**
3194
+ * Adds the SvelteKit middleware to do SSR in dev mode.
3195
+ * @see https://vitejs.dev/guide/api-plugin.html#configureserver
3196
+ */
3197
+ async configureServer(vite) {
3198
+ // This method is called by Vite after clearing the screen.
3199
+ // This patch ensures we can log any important messages afterwards for the user to see.
3200
+ const print_urls = vite.printUrls;
3201
+ vite.printUrls = function () {
3202
+ print_urls.apply(this);
3203
+ if (deferred_warning) console.error('\n' + deferred_warning);
3204
+ };
3205
+
3206
+ return await dev(vite, vite_config, svelte_config);
3207
+ },
3208
+
3209
+ /**
3210
+ * Adds the SvelteKit middleware to do SSR in preview mode.
3211
+ * @see https://vitejs.dev/guide/api-plugin.html#configurepreviewserver
3212
+ */
3213
+ configurePreviewServer(vite) {
3214
+ return preview(vite, svelte_config, vite_config.preview.https ? 'https' : 'http');
3215
+ }
3216
+ };
3217
+ }
3218
+
3219
+ function check_vite_version() {
3220
+ // TODO parse from kit peer deps and maybe do a full semver compare if we ever require feature releases a min
3221
+ const min_required_vite_major = 3;
3222
+ const vite_version = vite.version ?? '2.x'; // vite started exporting it's version in 3.0
3223
+ const current_vite_major = parseInt(vite_version.split('.')[0], 10);
3224
+
3225
+ if (current_vite_major < min_required_vite_major) {
3226
+ throw new Error(
3227
+ `Vite version ${current_vite_major} is no longer supported. Please upgrade to version ${min_required_vite_major}`
3228
+ );
3229
+ }
3230
+ }
3231
+
3232
+ /** @param {import('rollup').OutputBundle} bundle */
3233
+ function collect_output(bundle) {
3234
+ /** @type {import('rollup').OutputChunk[]} */
3235
+ const chunks = [];
3236
+ /** @type {import('rollup').OutputAsset[]} */
3237
+ const assets = [];
3238
+ for (const value of Object.values(bundle)) {
3239
+ // collect asset and output chunks
3240
+ if (value.type === 'asset') {
3241
+ assets.push(value);
3242
+ } else {
3243
+ chunks.push(value);
3244
+ }
3245
+ }
3246
+ return { assets, chunks };
3247
+ }
3248
+
3249
+ /**
3250
+ * @param {Record<string, any>} config
3251
+ * @param {Record<string, any>} resolved_config
3252
+ */
3253
+ function warn_overridden_config(config, resolved_config) {
3254
+ const overridden = find_overridden_config(config, resolved_config, enforced_config, '', []);
3255
+
3256
+ if (overridden.length > 0) {
3257
+ return (
3258
+ $.bold().red('The following Vite config options will be overridden by SvelteKit:') +
3259
+ overridden.map((key) => `\n - ${key}`).join('')
3260
+ );
3261
+ }
3262
+ }
3263
+
3264
+ /**
3265
+ * @param {Record<string, any>} config
3266
+ * @param {Record<string, any>} resolved_config
3267
+ * @param {import('./types').EnforcedConfig} enforced_config
3268
+ * @param {string} path
3269
+ * @param {string[]} out used locally to compute the return value
3270
+ */
3271
+ function find_overridden_config(config, resolved_config, enforced_config, path, out) {
3272
+ for (const key in enforced_config) {
3273
+ if (typeof config === 'object' && config !== null && key in config) {
3274
+ const enforced = enforced_config[key];
3275
+
3276
+ if (enforced === true) {
3277
+ if (config[key] !== resolved_config[key]) {
3278
+ out.push(path + key);
3279
+ }
3280
+ } else {
3281
+ find_overridden_config(config[key], resolved_config[key], enforced, path + key + '.', out);
3282
+ }
3283
+ }
3284
+ }
3285
+
3286
+ return out;
3287
+ }
3288
+
3289
+ export { generate_manifest as g, sveltekit };