@sveltejs/kit 1.0.0-next.352 → 1.0.0-next.355

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