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

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