@sveltejs/kit 1.0.0-next.41 → 1.0.0-next.412

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 (129) hide show
  1. package/README.md +12 -9
  2. package/package.json +97 -63
  3. package/src/cli.js +119 -0
  4. package/src/core/adapt/builder.js +207 -0
  5. package/src/core/adapt/index.js +19 -0
  6. package/src/core/config/index.js +86 -0
  7. package/src/core/config/options.js +488 -0
  8. package/src/core/config/types.d.ts +1 -0
  9. package/src/core/constants.js +3 -0
  10. package/src/core/generate_manifest/index.js +99 -0
  11. package/src/core/prerender/crawl.js +194 -0
  12. package/src/core/prerender/prerender.js +378 -0
  13. package/src/core/prerender/queue.js +80 -0
  14. package/src/core/sync/create_manifest_data/index.js +496 -0
  15. package/src/core/sync/create_manifest_data/types.d.ts +40 -0
  16. package/src/core/sync/sync.js +59 -0
  17. package/src/core/sync/utils.js +97 -0
  18. package/src/core/sync/write_ambient.js +87 -0
  19. package/src/core/sync/write_client_manifest.js +82 -0
  20. package/src/core/sync/write_matchers.js +25 -0
  21. package/src/core/sync/write_root.js +88 -0
  22. package/src/core/sync/write_tsconfig.js +189 -0
  23. package/src/core/sync/write_types.js +727 -0
  24. package/src/core/utils.js +58 -0
  25. package/src/hooks.js +26 -0
  26. package/src/index/index.js +45 -0
  27. package/src/index/private.js +33 -0
  28. package/src/node/index.js +145 -0
  29. package/src/node/polyfills.js +40 -0
  30. package/src/packaging/index.js +218 -0
  31. package/src/packaging/types.d.ts +8 -0
  32. package/src/packaging/typescript.js +150 -0
  33. package/src/packaging/utils.js +143 -0
  34. package/src/runtime/app/env.js +11 -0
  35. package/src/runtime/app/navigation.js +22 -0
  36. package/src/runtime/app/paths.js +1 -0
  37. package/src/runtime/app/stores.js +94 -0
  38. package/src/runtime/client/ambient.d.ts +17 -0
  39. package/src/runtime/client/client.js +1281 -0
  40. package/src/runtime/client/fetcher.js +60 -0
  41. package/src/runtime/client/parse.js +36 -0
  42. package/src/runtime/client/singletons.js +11 -0
  43. package/src/runtime/client/start.js +48 -0
  44. package/src/runtime/client/types.d.ts +106 -0
  45. package/src/runtime/client/utils.js +113 -0
  46. package/src/runtime/components/error.svelte +16 -0
  47. package/{assets → src/runtime}/components/layout.svelte +0 -0
  48. package/src/runtime/env/dynamic/private.js +1 -0
  49. package/src/runtime/env/dynamic/public.js +1 -0
  50. package/src/runtime/env-private.js +7 -0
  51. package/src/runtime/env-public.js +7 -0
  52. package/src/runtime/env.js +6 -0
  53. package/src/runtime/hash.js +16 -0
  54. package/src/runtime/paths.js +11 -0
  55. package/src/runtime/server/endpoint.js +42 -0
  56. package/src/runtime/server/index.js +434 -0
  57. package/src/runtime/server/page/cookie.js +25 -0
  58. package/src/runtime/server/page/crypto.js +239 -0
  59. package/src/runtime/server/page/csp.js +249 -0
  60. package/src/runtime/server/page/fetch.js +266 -0
  61. package/src/runtime/server/page/index.js +418 -0
  62. package/src/runtime/server/page/load_data.js +94 -0
  63. package/src/runtime/server/page/render.js +363 -0
  64. package/src/runtime/server/page/respond_with_error.js +105 -0
  65. package/src/runtime/server/page/types.d.ts +44 -0
  66. package/src/runtime/server/utils.js +116 -0
  67. package/src/utils/error.js +22 -0
  68. package/src/utils/escape.js +104 -0
  69. package/src/utils/filesystem.js +108 -0
  70. package/src/utils/http.js +55 -0
  71. package/src/utils/misc.js +1 -0
  72. package/src/utils/routing.js +107 -0
  73. package/src/utils/url.js +97 -0
  74. package/src/vite/build/build_server.js +339 -0
  75. package/src/vite/build/build_service_worker.js +90 -0
  76. package/src/vite/build/utils.js +153 -0
  77. package/src/vite/dev/index.js +569 -0
  78. package/src/vite/index.js +540 -0
  79. package/src/vite/preview/index.js +186 -0
  80. package/src/vite/types.d.ts +3 -0
  81. package/src/vite/utils.js +335 -0
  82. package/svelte-kit.js +1 -1
  83. package/types/ambient.d.ts +368 -0
  84. package/types/index.d.ts +345 -0
  85. package/types/internal.d.ts +309 -0
  86. package/types/private.d.ts +236 -0
  87. package/CHANGELOG.md +0 -419
  88. package/assets/components/error.svelte +0 -13
  89. package/assets/runtime/app/env.js +0 -5
  90. package/assets/runtime/app/navigation.js +0 -41
  91. package/assets/runtime/app/paths.js +0 -1
  92. package/assets/runtime/app/stores.js +0 -93
  93. package/assets/runtime/chunks/utils.js +0 -19
  94. package/assets/runtime/internal/singletons.js +0 -23
  95. package/assets/runtime/internal/start.js +0 -770
  96. package/assets/runtime/paths.js +0 -12
  97. package/dist/api.js +0 -28
  98. package/dist/api.js.map +0 -1
  99. package/dist/chunks/index.js +0 -3519
  100. package/dist/chunks/index2.js +0 -587
  101. package/dist/chunks/index3.js +0 -246
  102. package/dist/chunks/index4.js +0 -524
  103. package/dist/chunks/index5.js +0 -761
  104. package/dist/chunks/index6.js +0 -322
  105. package/dist/chunks/standard.js +0 -99
  106. package/dist/chunks/utils.js +0 -83
  107. package/dist/cli.js +0 -546
  108. package/dist/cli.js.map +0 -1
  109. package/dist/create_app.js +0 -592
  110. package/dist/create_app.js.map +0 -1
  111. package/dist/index.js +0 -392
  112. package/dist/index.js.map +0 -1
  113. package/dist/index2.js +0 -3519
  114. package/dist/index2.js.map +0 -1
  115. package/dist/index3.js +0 -320
  116. package/dist/index3.js.map +0 -1
  117. package/dist/index4.js +0 -323
  118. package/dist/index4.js.map +0 -1
  119. package/dist/index5.js +0 -247
  120. package/dist/index5.js.map +0 -1
  121. package/dist/index6.js +0 -761
  122. package/dist/index6.js.map +0 -1
  123. package/dist/renderer.js +0 -2499
  124. package/dist/renderer.js.map +0 -1
  125. package/dist/ssr.js +0 -2581
  126. package/dist/standard.js +0 -100
  127. package/dist/standard.js.map +0 -1
  128. package/dist/utils.js +0 -84
  129. package/dist/utils.js.map +0 -1
@@ -0,0 +1,569 @@
1
+ import fs from 'fs';
2
+ import colors from 'kleur';
3
+ import path from 'path';
4
+ import sirv from 'sirv';
5
+ import { URL } from 'url';
6
+ import { getRequest, setResponse } from '../../node/index.js';
7
+ import { installPolyfills } from '../../node/polyfills.js';
8
+ import { coalesce_to_error } from '../../utils/error.js';
9
+ import { posixify } from '../../utils/filesystem.js';
10
+ import { parse_route_id } from '../../utils/routing.js';
11
+ import { load_template } from '../../core/config/index.js';
12
+ import { SVELTE_KIT_ASSETS } from '../../core/constants.js';
13
+ import * as sync from '../../core/sync/sync.js';
14
+ import { get_mime_lookup, runtime_directory, runtime_prefix } from '../../core/utils.js';
15
+ import { get_env, prevent_illegal_vite_imports, resolve_entry } from '../utils.js';
16
+
17
+ // Vite doesn't expose this so we just copy the list for now
18
+ // https://github.com/vitejs/vite/blob/3edd1af56e980aef56641a5a51cf2932bb580d41/packages/vite/src/node/plugins/css.ts#L96
19
+ const style_pattern = /\.(css|less|sass|scss|styl|stylus|pcss|postcss)$/;
20
+
21
+ const cwd = process.cwd();
22
+
23
+ /**
24
+ * @param {import('vite').ViteDevServer} vite
25
+ * @param {import('vite').ResolvedConfig} vite_config
26
+ * @param {import('types').ValidatedConfig} svelte_config
27
+ * @param {Set<string>} illegal_imports
28
+ * @return {Promise<Promise<() => void>>}
29
+ */
30
+ export async function dev(vite, vite_config, svelte_config, illegal_imports) {
31
+ installPolyfills();
32
+
33
+ sync.init(svelte_config, vite_config.mode);
34
+
35
+ /** @type {import('types').Respond} */
36
+ const respond = (await import(`${runtime_prefix}/server/index.js`)).respond;
37
+
38
+ /** @type {import('types').ManifestData} */
39
+ let manifest_data;
40
+ /** @type {import('types').SSRManifest} */
41
+ let manifest;
42
+
43
+ const extensions = [...svelte_config.extensions, ...svelte_config.kit.moduleExtensions];
44
+
45
+ /** @param {string} id */
46
+ async function resolve(id) {
47
+ const url = id.startsWith('..') ? `/@fs${path.posix.resolve(id)}` : `/${id}`;
48
+
49
+ const module = await vite.ssrLoadModule(url);
50
+
51
+ const module_node = await vite.moduleGraph.getModuleByUrl(url);
52
+ if (!module_node) throw new Error(`Could not find node for ${url}`);
53
+
54
+ return { module, module_node, url };
55
+ }
56
+
57
+ async function update_manifest() {
58
+ ({ manifest_data } = await sync.create(svelte_config));
59
+
60
+ manifest = {
61
+ appDir: svelte_config.kit.appDir,
62
+ assets: new Set(manifest_data.assets.map((asset) => asset.file)),
63
+ mimeTypes: get_mime_lookup(manifest_data),
64
+ _: {
65
+ entry: {
66
+ file: `/@fs${runtime_prefix}/client/start.js`,
67
+ imports: [],
68
+ stylesheets: []
69
+ },
70
+ nodes: manifest_data.nodes.map((node, index) => {
71
+ return async () => {
72
+ /** @type {import('types').SSRNode} */
73
+ const result = {};
74
+
75
+ /** @type {import('vite').ModuleNode[]} */
76
+ const module_nodes = [];
77
+
78
+ result.index = index;
79
+
80
+ // these are unused in dev, it's easier to include them
81
+ result.imports = [];
82
+ result.stylesheets = [];
83
+
84
+ if (node.component) {
85
+ result.component = async () => {
86
+ const { module_node, module, url } = await resolve(
87
+ /** @type {string} */ (node.component)
88
+ );
89
+
90
+ module_nodes.push(module_node);
91
+ result.file = url.endsWith('.svelte') ? url : url + '?import'; // TODO what is this for?
92
+
93
+ prevent_illegal_vite_imports(
94
+ module_node,
95
+ illegal_imports,
96
+ extensions,
97
+ svelte_config.kit.outDir
98
+ );
99
+
100
+ return module.default;
101
+ };
102
+ }
103
+
104
+ if (node.shared) {
105
+ const { module, module_node } = await resolve(node.shared);
106
+
107
+ module_nodes.push(module_node);
108
+
109
+ result.shared = module;
110
+
111
+ prevent_illegal_vite_imports(
112
+ module_node,
113
+ illegal_imports,
114
+ extensions,
115
+ svelte_config.kit.outDir
116
+ );
117
+ }
118
+
119
+ if (node.server) {
120
+ const { module } = await resolve(node.server);
121
+ result.server = module;
122
+ }
123
+
124
+ // in dev we inline all styles to avoid FOUC. this gets populated lazily so that
125
+ // components/stylesheets loaded via import() during `load` are included
126
+ result.inline_styles = async () => {
127
+ const deps = new Set();
128
+
129
+ for (const module_node of module_nodes) {
130
+ await find_deps(vite, module_node, deps);
131
+ }
132
+
133
+ /** @type {Record<string, string>} */
134
+ const styles = {};
135
+
136
+ for (const dep of deps) {
137
+ const parsed = new URL(dep.url, 'http://localhost/');
138
+ const query = parsed.searchParams;
139
+
140
+ if (
141
+ style_pattern.test(dep.file) ||
142
+ (query.has('svelte') && query.get('type') === 'style')
143
+ ) {
144
+ try {
145
+ const mod = await vite.ssrLoadModule(dep.url);
146
+ styles[dep.url] = mod.default;
147
+ } catch {
148
+ // this can happen with dynamically imported modules, I think
149
+ // because the Vite module graph doesn't distinguish between
150
+ // static and dynamic imports? TODO investigate, submit fix
151
+ }
152
+ }
153
+ }
154
+
155
+ return styles;
156
+ };
157
+
158
+ return result;
159
+ };
160
+ }),
161
+ routes: manifest_data.routes.map((route) => {
162
+ const { pattern, names, types } = parse_route_id(route.id);
163
+
164
+ if (route.type === 'page') {
165
+ return {
166
+ type: 'page',
167
+ id: route.id,
168
+ pattern,
169
+ names,
170
+ types,
171
+ errors: route.errors.map((id) => (id ? manifest_data.nodes.indexOf(id) : undefined)),
172
+ layouts: route.layouts.map((id) =>
173
+ id ? manifest_data.nodes.indexOf(id) : undefined
174
+ ),
175
+ leaf: manifest_data.nodes.indexOf(route.leaf)
176
+ };
177
+ }
178
+
179
+ return {
180
+ type: 'endpoint',
181
+ id: route.id,
182
+ pattern,
183
+ names,
184
+ types,
185
+ load: async () => {
186
+ const url = path.resolve(cwd, route.file);
187
+ return await vite.ssrLoadModule(url);
188
+ }
189
+ };
190
+ }),
191
+ matchers: async () => {
192
+ /** @type {Record<string, import('types').ParamMatcher>} */
193
+ const matchers = {};
194
+
195
+ for (const key in manifest_data.matchers) {
196
+ const file = manifest_data.matchers[key];
197
+ const url = path.resolve(cwd, file);
198
+ const module = await vite.ssrLoadModule(url);
199
+
200
+ if (module.match) {
201
+ matchers[key] = module.match;
202
+ } else {
203
+ throw new Error(`${file} does not export a \`match\` function`);
204
+ }
205
+ }
206
+
207
+ return matchers;
208
+ }
209
+ }
210
+ };
211
+ }
212
+
213
+ /** @param {Error} error */
214
+ function fix_stack_trace(error) {
215
+ return error.stack ? vite.ssrRewriteStacktrace(error.stack) : error.stack;
216
+ }
217
+
218
+ await update_manifest();
219
+
220
+ /**
221
+ * @param {string} event
222
+ * @param {(file: string) => void} cb
223
+ */
224
+ const watch = (event, cb) => {
225
+ vite.watcher.on(event, (file) => {
226
+ if (file.startsWith(svelte_config.kit.files.routes + path.sep)) {
227
+ cb(file);
228
+ }
229
+ });
230
+ };
231
+ /** @type {NodeJS.Timeout | null } */
232
+ let timeout = null;
233
+ /** @param {() => void} to_run */
234
+ const debounce = (to_run) => {
235
+ timeout && clearTimeout(timeout);
236
+ timeout = setTimeout(() => {
237
+ timeout = null;
238
+ to_run();
239
+ }, 100);
240
+ };
241
+ // Debounce add/unlink events because in case of folder deletion or moves
242
+ // they fire in rapid succession, causing needless invocations.
243
+ watch('add', () => debounce(update_manifest));
244
+ watch('unlink', () => debounce(update_manifest));
245
+ watch('change', (file) => {
246
+ // Don't run for a single file if the whole manifest is about to get updated
247
+ if (!timeout) {
248
+ sync.update(svelte_config, manifest_data, file);
249
+ }
250
+ });
251
+
252
+ const assets = svelte_config.kit.paths.assets ? SVELTE_KIT_ASSETS : svelte_config.kit.paths.base;
253
+ const asset_server = sirv(svelte_config.kit.files.assets, {
254
+ dev: true,
255
+ etag: true,
256
+ maxAge: 0,
257
+ extensions: []
258
+ });
259
+
260
+ vite.middlewares.use(async (req, res, next) => {
261
+ try {
262
+ const base = `${vite.config.server.https ? 'https' : 'http'}://${
263
+ req.headers[':authority'] || req.headers.host
264
+ }`;
265
+
266
+ const decoded = decodeURI(new URL(base + req.url).pathname);
267
+
268
+ if (decoded.startsWith(assets)) {
269
+ const pathname = decoded.slice(assets.length);
270
+ const file = svelte_config.kit.files.assets + pathname;
271
+
272
+ if (fs.existsSync(file) && !fs.statSync(file).isDirectory()) {
273
+ if (has_correct_case(file, svelte_config.kit.files.assets)) {
274
+ req.url = encodeURI(pathname); // don't need query/hash
275
+ asset_server(req, res);
276
+ return;
277
+ }
278
+ }
279
+ }
280
+
281
+ next();
282
+ } catch (e) {
283
+ const error = coalesce_to_error(e);
284
+ res.statusCode = 500;
285
+ res.end(fix_stack_trace(error));
286
+ }
287
+ });
288
+
289
+ return () => {
290
+ const serve_static_middleware = vite.middlewares.stack.find(
291
+ (middleware) =>
292
+ /** @type {function} */ (middleware.handle).name === 'viteServeStaticMiddleware'
293
+ );
294
+
295
+ remove_static_middlewares(vite.middlewares);
296
+
297
+ vite.middlewares.use(async (req, res) => {
298
+ try {
299
+ const base = `${vite.config.server.https ? 'https' : 'http'}://${
300
+ req.headers[':authority'] || req.headers.host
301
+ }`;
302
+
303
+ const decoded = decodeURI(new URL(base + req.url).pathname);
304
+ const file = posixify(path.resolve(decoded.slice(1)));
305
+ const is_file = fs.existsSync(file) && !fs.statSync(file).isDirectory();
306
+ const allowed =
307
+ !vite_config.server.fs.strict ||
308
+ vite_config.server.fs.allow.some((dir) => file.startsWith(dir));
309
+
310
+ if (is_file && allowed) {
311
+ // @ts-expect-error
312
+ serve_static_middleware.handle(req, res);
313
+ return;
314
+ }
315
+
316
+ if (!decoded.startsWith(svelte_config.kit.paths.base)) {
317
+ return not_found(
318
+ res,
319
+ `Not found (did you mean ${svelte_config.kit.paths.base + req.url}?)`
320
+ );
321
+ }
322
+
323
+ // For some reason using runtime_prefix here is buggy, since Vite will later load the modules
324
+ // again with a slightly different url (with the drive letter) on windows
325
+ const runtime_base = `/@fs${
326
+ // Windows/Linux separation - Windows starts with a drive letter, we need a / in front there
327
+ runtime_directory.startsWith('/') ? '' : '/'
328
+ }${runtime_directory}`;
329
+
330
+ const { set_private_env } = await vite.ssrLoadModule(`${runtime_base}/env-private.js`);
331
+ const { set_public_env } = await vite.ssrLoadModule(`${runtime_base}/env-public.js`);
332
+
333
+ const env = get_env(vite_config.mode, svelte_config.kit.env.publicPrefix);
334
+ set_private_env(env.private);
335
+ set_public_env(env.public);
336
+
337
+ /** @type {Partial<import('types').Hooks>} */
338
+ const user_hooks = resolve_entry(svelte_config.kit.files.hooks)
339
+ ? await vite.ssrLoadModule(`/${svelte_config.kit.files.hooks}`)
340
+ : {};
341
+
342
+ const handle = user_hooks.handle || (({ event, resolve }) => resolve(event));
343
+
344
+ /** @type {import('types').Hooks} */
345
+ const hooks = {
346
+ getSession: user_hooks.getSession || (() => ({})),
347
+ handle,
348
+ handleError:
349
+ user_hooks.handleError ||
350
+ (({ /** @type {Error & { frame?: string }} */ error }) => {
351
+ console.error(colors.bold().red(error.message));
352
+ if (error.frame) {
353
+ console.error(colors.gray(error.frame));
354
+ }
355
+ if (error.stack) {
356
+ console.error(colors.gray(error.stack));
357
+ }
358
+ }),
359
+ externalFetch: user_hooks.externalFetch || fetch
360
+ };
361
+
362
+ if (/** @type {any} */ (hooks).getContext) {
363
+ // TODO remove this for 1.0
364
+ throw new Error(
365
+ 'The getContext hook has been removed. See https://kit.svelte.dev/docs/hooks'
366
+ );
367
+ }
368
+
369
+ if (/** @type {any} */ (hooks).serverFetch) {
370
+ // TODO remove this for 1.0
371
+ throw new Error('The serverFetch hook has been renamed to externalFetch.');
372
+ }
373
+
374
+ // TODO the / prefix will probably fail if outDir is outside the cwd (which
375
+ // could be the case in a monorepo setup), but without it these modules
376
+ // can get loaded twice via different URLs, which causes failures. Might
377
+ // require changes to Vite to fix
378
+ const { default: root } = await vite.ssrLoadModule(
379
+ `/${posixify(path.relative(cwd, `${svelte_config.kit.outDir}/generated/root.svelte`))}`
380
+ );
381
+
382
+ const paths = await vite.ssrLoadModule(`${runtime_base}/paths.js`);
383
+
384
+ paths.set_paths({
385
+ base: svelte_config.kit.paths.base,
386
+ assets
387
+ });
388
+
389
+ let request;
390
+
391
+ try {
392
+ request = await getRequest(base, req);
393
+ } catch (/** @type {any} */ err) {
394
+ res.statusCode = err.status || 400;
395
+ return res.end(err.reason || 'Invalid request body');
396
+ }
397
+
398
+ const template = load_template(cwd, svelte_config);
399
+
400
+ const rendered = await respond(
401
+ request,
402
+ {
403
+ csp: svelte_config.kit.csp,
404
+ dev: true,
405
+ get_stack: (error) => fix_stack_trace(error),
406
+ handle_error: (error, event) => {
407
+ hooks.handleError({
408
+ error: new Proxy(error, {
409
+ get: (target, property) => {
410
+ if (property === 'stack') {
411
+ return fix_stack_trace(error);
412
+ }
413
+
414
+ return Reflect.get(target, property, target);
415
+ }
416
+ }),
417
+ event,
418
+
419
+ // TODO remove for 1.0
420
+ // @ts-expect-error
421
+ get request() {
422
+ throw new Error(
423
+ 'request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details'
424
+ );
425
+ }
426
+ });
427
+ },
428
+ hooks,
429
+ hydrate: svelte_config.kit.browser.hydrate,
430
+ manifest,
431
+ method_override: svelte_config.kit.methodOverride,
432
+ paths: {
433
+ base: svelte_config.kit.paths.base,
434
+ assets
435
+ },
436
+ prefix: '',
437
+ prerender: {
438
+ default: svelte_config.kit.prerender.default,
439
+ enabled: svelte_config.kit.prerender.enabled
440
+ },
441
+ public_env: env.public,
442
+ read: (file) => fs.readFileSync(path.join(svelte_config.kit.files.assets, file)),
443
+ root,
444
+ router: svelte_config.kit.browser.router,
445
+ template: ({ head, body, assets, nonce }) => {
446
+ return (
447
+ template
448
+ .replace(/%sveltekit\.assets%/g, assets)
449
+ .replace(/%sveltekit\.nonce%/g, nonce)
450
+ // head and body must be replaced last, in case someone tries to sneak in %sveltekit.assets% etc
451
+ .replace('%sveltekit.head%', () => head)
452
+ .replace('%sveltekit.body%', () => body)
453
+ );
454
+ },
455
+ template_contains_nonce: template.includes('%sveltekit.nonce%'),
456
+ trailing_slash: svelte_config.kit.trailingSlash
457
+ },
458
+ {
459
+ getClientAddress: () => {
460
+ const { remoteAddress } = req.socket;
461
+ if (remoteAddress) return remoteAddress;
462
+ throw new Error('Could not determine clientAddress');
463
+ }
464
+ }
465
+ );
466
+
467
+ if (rendered.status === 404) {
468
+ // @ts-expect-error
469
+ serve_static_middleware.handle(req, res, () => {
470
+ setResponse(res, rendered);
471
+ });
472
+ } else {
473
+ setResponse(res, rendered);
474
+ }
475
+ } catch (e) {
476
+ const error = coalesce_to_error(e);
477
+ res.statusCode = 500;
478
+ res.end(fix_stack_trace(error));
479
+ }
480
+ });
481
+ };
482
+ }
483
+
484
+ /** @param {import('http').ServerResponse} res */
485
+ function not_found(res, message = 'Not found') {
486
+ res.statusCode = 404;
487
+ res.end(message);
488
+ }
489
+
490
+ /**
491
+ * @param {import('connect').Server} server
492
+ */
493
+ function remove_static_middlewares(server) {
494
+ // We don't use viteServePublicMiddleware because of the following issues:
495
+ // https://github.com/vitejs/vite/issues/9260
496
+ // https://github.com/vitejs/vite/issues/9236
497
+ // https://github.com/vitejs/vite/issues/9234
498
+ const static_middlewares = ['viteServePublicMiddleware', 'viteServeStaticMiddleware'];
499
+ for (let i = server.stack.length - 1; i > 0; i--) {
500
+ // @ts-expect-error using internals
501
+ if (static_middlewares.includes(server.stack[i].handle.name)) {
502
+ server.stack.splice(i, 1);
503
+ }
504
+ }
505
+ }
506
+
507
+ /**
508
+ * @param {import('vite').ViteDevServer} vite
509
+ * @param {import('vite').ModuleNode} node
510
+ * @param {Set<import('vite').ModuleNode>} deps
511
+ */
512
+ async function find_deps(vite, node, deps) {
513
+ // since `ssrTransformResult.deps` contains URLs instead of `ModuleNode`s, this process is asynchronous.
514
+ // instead of using `await`, we resolve all branches in parallel.
515
+ /** @type {Promise<void>[]} */
516
+ const branches = [];
517
+
518
+ /** @param {import('vite').ModuleNode} node */
519
+ async function add(node) {
520
+ if (!deps.has(node)) {
521
+ deps.add(node);
522
+ await find_deps(vite, node, deps);
523
+ }
524
+ }
525
+
526
+ /** @param {string} url */
527
+ async function add_by_url(url) {
528
+ const node = await vite.moduleGraph.getModuleByUrl(url);
529
+
530
+ if (node) {
531
+ await add(node);
532
+ }
533
+ }
534
+
535
+ if (node.ssrTransformResult) {
536
+ if (node.ssrTransformResult.deps) {
537
+ node.ssrTransformResult.deps.forEach((url) => branches.push(add_by_url(url)));
538
+ }
539
+
540
+ if (node.ssrTransformResult.dynamicDeps) {
541
+ node.ssrTransformResult.dynamicDeps.forEach((url) => branches.push(add_by_url(url)));
542
+ }
543
+ } else {
544
+ node.importedModules.forEach((node) => branches.push(add(node)));
545
+ }
546
+
547
+ await Promise.all(branches);
548
+ }
549
+
550
+ /**
551
+ * Determine if a file is being requested with the correct case,
552
+ * to ensure consistent behaviour between dev and prod and across
553
+ * operating systems. Note that we can't use realpath here,
554
+ * because we don't want to follow symlinks
555
+ * @param {string} file
556
+ * @param {string} assets
557
+ * @returns {boolean}
558
+ */
559
+ function has_correct_case(file, assets) {
560
+ if (file === assets) return true;
561
+
562
+ const parent = path.dirname(file);
563
+
564
+ if (fs.readdirSync(parent).includes(path.basename(file))) {
565
+ return has_correct_case(parent, assets);
566
+ }
567
+
568
+ return false;
569
+ }