@sveltejs/kit 1.0.0-next.36 → 1.0.0-next.360

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