@sveltejs/kit 1.0.0-next.50 → 1.0.0-next.500

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