@sveltejs/kit 1.0.0-next.29 → 1.0.0-next.290

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 (80) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +20 -0
  3. package/assets/app/navigation.js +79 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/app/stores.js +97 -0
  6. package/assets/chunks/utils.js +13 -0
  7. package/assets/client/singletons.js +21 -0
  8. package/assets/client/start.js +1578 -0
  9. package/assets/components/error.svelte +18 -2
  10. package/assets/env.js +8 -0
  11. package/assets/paths.js +13 -0
  12. package/assets/server/index.js +2783 -0
  13. package/dist/chunks/amp_hook.js +56 -0
  14. package/dist/chunks/cert.js +28154 -0
  15. package/dist/chunks/constants.js +663 -0
  16. package/dist/chunks/index.js +509 -0
  17. package/dist/chunks/index2.js +653 -0
  18. package/dist/chunks/index3.js +120 -0
  19. package/dist/chunks/index4.js +892 -0
  20. package/dist/chunks/index5.js +160 -0
  21. package/dist/chunks/index6.js +15584 -0
  22. package/dist/chunks/index7.js +4207 -0
  23. package/dist/chunks/misc.js +3 -0
  24. package/dist/chunks/multipart-parser.js +449 -0
  25. package/dist/chunks/tsconfig.js +1032 -0
  26. package/dist/cli.js +1130 -86
  27. package/dist/hooks.js +28 -0
  28. package/dist/install-fetch.js +6518 -0
  29. package/dist/node.js +94 -0
  30. package/package.json +106 -54
  31. package/svelte-kit.js +2 -0
  32. package/types/ambient.d.ts +299 -0
  33. package/types/index.d.ts +164 -0
  34. package/types/internal.d.ts +313 -0
  35. package/types/private.d.ts +349 -0
  36. package/CHANGELOG.md +0 -332
  37. package/assets/runtime/app/navigation.js +0 -23
  38. package/assets/runtime/app/navigation.js.map +0 -1
  39. package/assets/runtime/app/paths.js +0 -2
  40. package/assets/runtime/app/paths.js.map +0 -1
  41. package/assets/runtime/app/stores.js +0 -78
  42. package/assets/runtime/app/stores.js.map +0 -1
  43. package/assets/runtime/internal/singletons.js +0 -15
  44. package/assets/runtime/internal/singletons.js.map +0 -1
  45. package/assets/runtime/internal/start.js +0 -591
  46. package/assets/runtime/internal/start.js.map +0 -1
  47. package/assets/runtime/utils-85ebcc60.js +0 -18
  48. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  49. package/dist/api.js +0 -44
  50. package/dist/api.js.map +0 -1
  51. package/dist/build.js +0 -246
  52. package/dist/build.js.map +0 -1
  53. package/dist/cli.js.map +0 -1
  54. package/dist/colors.js +0 -37
  55. package/dist/colors.js.map +0 -1
  56. package/dist/create_app.js +0 -580
  57. package/dist/create_app.js.map +0 -1
  58. package/dist/index.js +0 -368
  59. package/dist/index.js.map +0 -1
  60. package/dist/index2.js +0 -12035
  61. package/dist/index2.js.map +0 -1
  62. package/dist/index3.js +0 -549
  63. package/dist/index3.js.map +0 -1
  64. package/dist/index4.js +0 -74
  65. package/dist/index4.js.map +0 -1
  66. package/dist/index5.js +0 -464
  67. package/dist/index5.js.map +0 -1
  68. package/dist/index6.js +0 -735
  69. package/dist/index6.js.map +0 -1
  70. package/dist/logging.js +0 -43
  71. package/dist/logging.js.map +0 -1
  72. package/dist/package.js +0 -432
  73. package/dist/package.js.map +0 -1
  74. package/dist/renderer.js +0 -2425
  75. package/dist/renderer.js.map +0 -1
  76. package/dist/standard.js +0 -101
  77. package/dist/standard.js.map +0 -1
  78. package/dist/utils.js +0 -58
  79. package/dist/utils.js.map +0 -1
  80. package/svelte-kit +0 -3
@@ -0,0 +1,509 @@
1
+ import path__default from 'path';
2
+ import { svelte } from '@sveltejs/vite-plugin-svelte';
3
+ import vite from 'vite';
4
+ import { c as create_manifest_data, a as create_app, g as generate_tsconfig, d as deep_merge } from './tsconfig.js';
5
+ import { g as get_runtime_path, r as resolve_entry, $, p as posixify, l as load_template, c as coalesce_to_error, a as get_mime_lookup, b as copy_assets, d as get_aliases, e as print_config_conflicts } from '../cli.js';
6
+ import fs__default from 'fs';
7
+ import { URL } from 'url';
8
+ import { S as SVELTE_KIT_ASSETS, s as sirv } from './constants.js';
9
+ import { installFetch } from '../install-fetch.js';
10
+ import { getRequest, setResponse } from '../node.js';
11
+ import { sequence } from '../hooks.js';
12
+ import './misc.js';
13
+ import 'sade';
14
+ import 'child_process';
15
+ import 'net';
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:util';
23
+ import 'node:url';
24
+ import 'stream';
25
+
26
+ /**
27
+ * @param {import('types').ValidatedConfig} config
28
+ * @param {string} cwd
29
+ * @returns {Promise<import('vite').Plugin>}
30
+ */
31
+ async function create_plugin(config, cwd) {
32
+ const runtime = get_runtime_path(config);
33
+
34
+ /** @type {import('types').Handle} */
35
+ let amp;
36
+
37
+ if (config.kit.amp) {
38
+ process.env.VITE_SVELTEKIT_AMP = 'true';
39
+ amp = (await import('./amp_hook.js')).handle;
40
+ }
41
+
42
+ process.env.VITE_SVELTEKIT_APP_VERSION_POLL_INTERVAL = '0';
43
+
44
+ /** @type {import('types').Respond} */
45
+ const respond = (await import(`${runtime}/server/index.js`)).respond;
46
+
47
+ return {
48
+ name: 'vite-plugin-svelte-kit',
49
+
50
+ configureServer(vite) {
51
+ installFetch();
52
+
53
+ /** @type {import('types').SSRManifest} */
54
+ let manifest;
55
+
56
+ function update_manifest() {
57
+ const manifest_data = create_manifest_data({ config, cwd });
58
+
59
+ create_app({ config, manifest_data, cwd });
60
+
61
+ manifest = {
62
+ appDir: config.kit.appDir,
63
+ assets: new Set(manifest_data.assets.map((asset) => asset.file)),
64
+ _: {
65
+ mime: get_mime_lookup(manifest_data),
66
+ entry: {
67
+ file: `/@fs${runtime}/client/start.js`,
68
+ css: [],
69
+ js: []
70
+ },
71
+ nodes: manifest_data.components.map((id) => {
72
+ return async () => {
73
+ const url = id.startsWith('..') ? `/@fs${path__default.posix.resolve(id)}` : `/${id}`;
74
+
75
+ const module = /** @type {import('types').SSRComponent} */ (
76
+ await vite.ssrLoadModule(url)
77
+ );
78
+ const node = await vite.moduleGraph.getModuleByUrl(url);
79
+
80
+ if (!node) throw new Error(`Could not find node for ${url}`);
81
+
82
+ const deps = new Set();
83
+ find_deps(node, deps);
84
+
85
+ /** @type {Record<string, string>} */
86
+ const styles = {};
87
+
88
+ for (const dep of deps) {
89
+ const parsed = new URL(dep.url, 'http://localhost/');
90
+ const query = parsed.searchParams;
91
+
92
+ // TODO what about .scss files, etc?
93
+ if (
94
+ dep.file.endsWith('.css') ||
95
+ (query.has('svelte') && query.get('type') === 'style')
96
+ ) {
97
+ try {
98
+ const mod = await vite.ssrLoadModule(dep.url);
99
+ styles[dep.url] = mod.default;
100
+ } catch {
101
+ // this can happen with dynamically imported modules, I think
102
+ // because the Vite module graph doesn't distinguish between
103
+ // static and dynamic imports? TODO investigate, submit fix
104
+ }
105
+ }
106
+ }
107
+
108
+ return {
109
+ module,
110
+ entry: url.endsWith('.svelte') ? url : url + '?import',
111
+ css: [],
112
+ js: [],
113
+ // in dev we inline all styles to avoid FOUC
114
+ styles
115
+ };
116
+ };
117
+ }),
118
+ routes: manifest_data.routes.map((route) => {
119
+ if (route.type === 'page') {
120
+ return {
121
+ type: 'page',
122
+ pattern: route.pattern,
123
+ params: get_params(route.params),
124
+ shadow: route.shadow
125
+ ? async () => {
126
+ const url = path__default.resolve(cwd, /** @type {string} */ (route.shadow));
127
+ return await vite.ssrLoadModule(url);
128
+ }
129
+ : null,
130
+ a: route.a.map((id) => manifest_data.components.indexOf(id)),
131
+ b: route.b.map((id) => manifest_data.components.indexOf(id))
132
+ };
133
+ }
134
+
135
+ return {
136
+ type: 'endpoint',
137
+ pattern: route.pattern,
138
+ params: get_params(route.params),
139
+ load: async () => {
140
+ const url = path__default.resolve(cwd, route.file);
141
+ return await vite.ssrLoadModule(url);
142
+ }
143
+ };
144
+ })
145
+ }
146
+ };
147
+ }
148
+
149
+ /** @param {Error} error */
150
+ function fix_stack_trace(error) {
151
+ // TODO https://github.com/vitejs/vite/issues/7045
152
+
153
+ // ideally vite would expose ssrRewriteStacktrace, but
154
+ // in lieu of that, we can implement it ourselves. we
155
+ // don't want to mutate the error object, because
156
+ // the stack trace could be 'fixed' multiple times,
157
+ // and Vite will fix stack traces before we even
158
+ // see them if they occur during ssrLoadModule
159
+ const original = error.stack;
160
+ vite.ssrFixStacktrace(error);
161
+ const fixed = error.stack;
162
+ error.stack = original;
163
+
164
+ return fixed;
165
+ }
166
+
167
+ update_manifest();
168
+
169
+ vite.watcher.on('add', update_manifest);
170
+ vite.watcher.on('remove', update_manifest);
171
+
172
+ const assets = config.kit.paths.assets ? SVELTE_KIT_ASSETS : config.kit.paths.base;
173
+ const asset_server = sirv(config.kit.files.assets, {
174
+ dev: true,
175
+ etag: true,
176
+ maxAge: 0,
177
+ extensions: []
178
+ });
179
+
180
+ return () => {
181
+ remove_html_middlewares(vite.middlewares);
182
+
183
+ vite.middlewares.use(async (req, res) => {
184
+ try {
185
+ if (!req.url || !req.method) throw new Error('Incomplete request');
186
+
187
+ const base = `${vite.config.server.https ? 'https' : 'http'}://${req.headers.host}`;
188
+
189
+ const decoded = decodeURI(new URL(base + req.url).pathname);
190
+
191
+ if (decoded.startsWith(assets)) {
192
+ const pathname = decoded.slice(assets.length);
193
+ const file = config.kit.files.assets + pathname;
194
+
195
+ if (fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory()) {
196
+ req.url = encodeURI(pathname); // don't need query/hash
197
+ asset_server(req, res);
198
+ return;
199
+ }
200
+ }
201
+
202
+ if (req.url === '/favicon.ico') return not_found(res);
203
+
204
+ if (!decoded.startsWith(config.kit.paths.base)) return not_found(res);
205
+
206
+ /** @type {Partial<import('types').Hooks>} */
207
+ const user_hooks = resolve_entry(config.kit.files.hooks)
208
+ ? await vite.ssrLoadModule(`/${config.kit.files.hooks}`)
209
+ : {};
210
+
211
+ const handle = user_hooks.handle || (({ event, resolve }) => resolve(event));
212
+
213
+ /** @type {import('types').Hooks} */
214
+ const hooks = {
215
+ getSession: user_hooks.getSession || (() => ({})),
216
+ handle: amp ? sequence(amp, handle) : handle,
217
+ handleError:
218
+ user_hooks.handleError ||
219
+ (({ /** @type {Error & { frame?: string }} */ error }) => {
220
+ console.error($.bold().red(error.message));
221
+ if (error.frame) {
222
+ console.error($.gray(error.frame));
223
+ }
224
+ if (error.stack) {
225
+ console.error($.gray(error.stack));
226
+ }
227
+ }),
228
+ externalFetch: user_hooks.externalFetch || fetch
229
+ };
230
+
231
+ if (/** @type {any} */ (hooks).getContext) {
232
+ // TODO remove this for 1.0
233
+ throw new Error(
234
+ 'The getContext hook has been removed. See https://kit.svelte.dev/docs/hooks'
235
+ );
236
+ }
237
+
238
+ if (/** @type {any} */ (hooks).serverFetch) {
239
+ // TODO remove this for 1.0
240
+ throw new Error('The serverFetch hook has been renamed to externalFetch.');
241
+ }
242
+
243
+ // TODO the / prefix will probably fail if outDir is outside the cwd (which
244
+ // could be the case in a monorepo setup), but without it these modules
245
+ // can get loaded twice via different URLs, which causes failures. Might
246
+ // require changes to Vite to fix
247
+ const { default: root } = await vite.ssrLoadModule(
248
+ `/${posixify(path__default.relative(cwd, `${config.kit.outDir}/generated/root.svelte`))}`
249
+ );
250
+
251
+ const paths = await vite.ssrLoadModule(
252
+ true
253
+ ? `/${posixify(path__default.relative(cwd, `${config.kit.outDir}/runtime/paths.js`))}`
254
+ : `/@fs${runtime}/paths.js`
255
+ );
256
+
257
+ paths.set_paths({
258
+ base: config.kit.paths.base,
259
+ assets
260
+ });
261
+
262
+ let request;
263
+
264
+ try {
265
+ request = await getRequest(base, req);
266
+ } catch (/** @type {any} */ err) {
267
+ res.statusCode = err.status || 400;
268
+ return res.end(err.reason || 'Invalid request body');
269
+ }
270
+
271
+ const template = load_template(cwd, config);
272
+
273
+ const rendered = await respond(request, {
274
+ amp: config.kit.amp,
275
+ csp: config.kit.csp,
276
+ dev: true,
277
+ floc: config.kit.floc,
278
+ get_stack: (error) => {
279
+ return fix_stack_trace(error);
280
+ },
281
+ handle_error: (error, event) => {
282
+ hooks.handleError({
283
+ error: new Proxy(error, {
284
+ get: (target, property) => {
285
+ if (property === 'stack') {
286
+ return fix_stack_trace(error);
287
+ }
288
+
289
+ return Reflect.get(target, property, target);
290
+ }
291
+ }),
292
+ event,
293
+
294
+ // TODO remove for 1.0
295
+ // @ts-expect-error
296
+ get request() {
297
+ throw new Error(
298
+ 'request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details'
299
+ );
300
+ }
301
+ });
302
+ },
303
+ hooks,
304
+ hydrate: config.kit.browser.hydrate,
305
+ manifest,
306
+ method_override: config.kit.methodOverride,
307
+ paths: {
308
+ base: config.kit.paths.base,
309
+ assets
310
+ },
311
+ prefix: '',
312
+ prerender: config.kit.prerender.enabled,
313
+ read: (file) => fs__default.readFileSync(path__default.join(config.kit.files.assets, file)),
314
+ root,
315
+ router: config.kit.browser.router,
316
+ template: ({ head, body, assets, nonce }) => {
317
+ return (
318
+ template
319
+ .replace(/%svelte\.assets%/g, assets)
320
+ .replace(/%svelte\.nonce%/g, nonce)
321
+ // head and body must be replaced last, in case someone tries to sneak in %svelte.assets% etc
322
+ .replace('%svelte.head%', () => head)
323
+ .replace('%svelte.body%', () => body)
324
+ );
325
+ },
326
+ template_contains_nonce: template.includes('%svelte.nonce%'),
327
+ trailing_slash: config.kit.trailingSlash
328
+ });
329
+
330
+ if (rendered) {
331
+ setResponse(res, rendered);
332
+ } else {
333
+ not_found(res);
334
+ }
335
+ } catch (e) {
336
+ const error = coalesce_to_error(e);
337
+ vite.ssrFixStacktrace(error);
338
+ res.statusCode = 500;
339
+ res.end(error.stack);
340
+ }
341
+ });
342
+ };
343
+ }
344
+ };
345
+ }
346
+
347
+ /** @param {string[]} array */
348
+ function get_params(array) {
349
+ // given an array of params like `['x', 'y', 'z']` for
350
+ // src/routes/[x]/[y]/[z]/svelte, create a function
351
+ // that turns a RegExpExecArray into ({ x, y, z })
352
+
353
+ /** @param {RegExpExecArray} match */
354
+ const fn = (match) => {
355
+ /** @type {Record<string, string>} */
356
+ const params = {};
357
+ array.forEach((key, i) => {
358
+ if (key.startsWith('...')) {
359
+ params[key.slice(3)] = match[i + 1] || '';
360
+ } else {
361
+ params[key] = match[i + 1];
362
+ }
363
+ });
364
+ return params;
365
+ };
366
+
367
+ return fn;
368
+ }
369
+
370
+ /** @param {import('http').ServerResponse} res */
371
+ function not_found(res) {
372
+ res.statusCode = 404;
373
+ res.end('Not found');
374
+ }
375
+
376
+ /**
377
+ * @param {import('connect').Server} server
378
+ */
379
+ function remove_html_middlewares(server) {
380
+ const html_middlewares = [
381
+ 'viteIndexHtmlMiddleware',
382
+ 'vite404Middleware',
383
+ 'viteSpaFallbackMiddleware'
384
+ ];
385
+ for (let i = server.stack.length - 1; i > 0; i--) {
386
+ // @ts-expect-error using internals until https://github.com/vitejs/vite/pull/4640 is merged
387
+ if (html_middlewares.includes(server.stack[i].handle.name)) {
388
+ server.stack.splice(i, 1);
389
+ }
390
+ }
391
+ }
392
+
393
+ /**
394
+ * @param {import('vite').ModuleNode} node
395
+ * @param {Set<import('vite').ModuleNode>} deps
396
+ */
397
+ function find_deps(node, deps) {
398
+ for (const dep of node.importedModules) {
399
+ if (!deps.has(dep)) {
400
+ deps.add(dep);
401
+ find_deps(dep, deps);
402
+ }
403
+ }
404
+ }
405
+
406
+ /**
407
+ * @typedef {{
408
+ * cwd: string,
409
+ * port: number,
410
+ * host?: string,
411
+ * https: boolean,
412
+ * config: import('types').ValidatedConfig
413
+ * }} Options
414
+ * @typedef {import('types').SSRComponent} SSRComponent
415
+ */
416
+
417
+ /** @param {Options} opts */
418
+ async function dev({ cwd, port, host, https, config }) {
419
+ copy_assets(path__default.join(config.kit.outDir, 'runtime'));
420
+
421
+ generate_tsconfig(config);
422
+
423
+ const [vite_config] = deep_merge(
424
+ {
425
+ server: {
426
+ fs: {
427
+ allow: [
428
+ ...new Set([
429
+ config.kit.files.assets,
430
+ config.kit.files.lib,
431
+ config.kit.files.routes,
432
+ config.kit.outDir,
433
+ path__default.resolve(cwd, 'src'),
434
+ path__default.resolve(cwd, 'node_modules'),
435
+ path__default.resolve(vite.searchForWorkspaceRoot(cwd), 'node_modules')
436
+ ])
437
+ ]
438
+ },
439
+ strictPort: true
440
+ }
441
+ },
442
+ await config.kit.vite()
443
+ );
444
+
445
+ /** @type {[any, string[]]} */
446
+ const [merged_config, conflicts] = deep_merge(vite_config, {
447
+ configFile: false,
448
+ root: cwd,
449
+ resolve: {
450
+ alias: get_aliases(config)
451
+ },
452
+ build: {
453
+ rollupOptions: {
454
+ // Vite dependency crawler needs an explicit JS entry point
455
+ // eventhough server otherwise works without it
456
+ input: `${get_runtime_path(config)}/client/start.js`
457
+ }
458
+ },
459
+ plugins: [
460
+ svelte({
461
+ extensions: config.extensions,
462
+ // In AMP mode, we know that there are no conditional component imports. In that case, we
463
+ // don't need to include CSS for components that are imported but unused, so we can just
464
+ // include rendered CSS.
465
+ // This would also apply if hydrate and router are both false, but we don't know if one
466
+ // has been enabled at the page level, so we don't do anything there.
467
+ emitCss: !config.kit.amp,
468
+ compilerOptions: {
469
+ hydratable: !!config.kit.browser.hydrate
470
+ }
471
+ }),
472
+ await create_plugin(config, cwd)
473
+ ],
474
+ base: '/'
475
+ });
476
+
477
+ print_config_conflicts(conflicts, 'kit.vite.');
478
+
479
+ // optional config from command-line flags
480
+ // these should take precedence, but not print conflict warnings
481
+ if (host) {
482
+ merged_config.server.host = host;
483
+ }
484
+
485
+ // if https is already enabled then do nothing. it could be an object and we
486
+ // don't want to overwrite with a boolean
487
+ if (https && !merged_config.server.https) {
488
+ merged_config.server.https = https;
489
+ }
490
+
491
+ if (port) {
492
+ merged_config.server.port = port;
493
+ }
494
+
495
+ const server = await vite.createServer(merged_config);
496
+ await server.listen(port);
497
+
498
+ const address_info = /** @type {import('net').AddressInfo} */ (
499
+ /** @type {import('http').Server} */ (server.httpServer).address()
500
+ );
501
+
502
+ return {
503
+ address_info,
504
+ server_config: vite_config.server,
505
+ close: () => server.close()
506
+ };
507
+ }
508
+
509
+ export { dev };