@sveltejs/kit 1.0.0-next.22 → 1.0.0-next.223

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 (82) hide show
  1. package/README.md +12 -9
  2. package/assets/components/error.svelte +19 -3
  3. package/assets/kit.js +1996 -0
  4. package/assets/runtime/app/env.js +20 -0
  5. package/assets/runtime/app/navigation.js +55 -13
  6. package/assets/runtime/app/paths.js +1 -2
  7. package/assets/runtime/app/stores.js +19 -15
  8. package/assets/runtime/chunks/utils.js +13 -0
  9. package/assets/runtime/env.js +8 -0
  10. package/assets/runtime/internal/singletons.js +12 -9
  11. package/assets/runtime/internal/start.js +1015 -354
  12. package/assets/runtime/paths.js +13 -0
  13. package/dist/chunks/cert.js +29255 -0
  14. package/dist/chunks/constants.js +8 -0
  15. package/dist/chunks/error.js +12 -0
  16. package/dist/chunks/index.js +476 -0
  17. package/dist/chunks/index2.js +817 -0
  18. package/dist/chunks/index3.js +640 -0
  19. package/dist/chunks/index4.js +109 -0
  20. package/dist/chunks/index5.js +635 -0
  21. package/dist/chunks/index6.js +827 -0
  22. package/dist/chunks/index7.js +15575 -0
  23. package/dist/chunks/index8.js +4207 -0
  24. package/dist/chunks/misc.js +3 -0
  25. package/dist/chunks/multipart-parser.js +449 -0
  26. package/dist/chunks/url.js +62 -0
  27. package/dist/cli.js +996 -83
  28. package/dist/hooks.js +28 -0
  29. package/dist/install-fetch.js +6514 -0
  30. package/dist/node.js +51 -0
  31. package/dist/ssr.js +1926 -0
  32. package/package.json +96 -54
  33. package/svelte-kit.js +2 -0
  34. package/types/ambient-modules.d.ts +191 -0
  35. package/types/app.d.ts +45 -0
  36. package/types/config.d.ts +168 -0
  37. package/types/endpoint.d.ts +20 -0
  38. package/types/helper.d.ts +53 -0
  39. package/types/hooks.d.ts +55 -0
  40. package/types/index.d.ts +18 -0
  41. package/types/internal.d.ts +237 -0
  42. package/types/page.d.ts +73 -0
  43. package/CHANGELOG.md +0 -288
  44. package/assets/runtime/app/navigation.js.map +0 -1
  45. package/assets/runtime/app/paths.js.map +0 -1
  46. package/assets/runtime/app/stores.js.map +0 -1
  47. package/assets/runtime/internal/singletons.js.map +0 -1
  48. package/assets/runtime/internal/start.js.map +0 -1
  49. package/assets/runtime/utils-85ebcc60.js +0 -18
  50. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  51. package/dist/api.js +0 -44
  52. package/dist/api.js.map +0 -1
  53. package/dist/build.js +0 -246
  54. package/dist/build.js.map +0 -1
  55. package/dist/cli.js.map +0 -1
  56. package/dist/colors.js +0 -37
  57. package/dist/colors.js.map +0 -1
  58. package/dist/create_app.js +0 -578
  59. package/dist/create_app.js.map +0 -1
  60. package/dist/index.js +0 -12042
  61. package/dist/index.js.map +0 -1
  62. package/dist/index2.js +0 -544
  63. package/dist/index2.js.map +0 -1
  64. package/dist/index3.js +0 -71
  65. package/dist/index3.js.map +0 -1
  66. package/dist/index4.js +0 -466
  67. package/dist/index4.js.map +0 -1
  68. package/dist/index5.js +0 -729
  69. package/dist/index5.js.map +0 -1
  70. package/dist/index6.js +0 -730
  71. package/dist/index6.js.map +0 -1
  72. package/dist/logging.js +0 -43
  73. package/dist/logging.js.map +0 -1
  74. package/dist/package.js +0 -432
  75. package/dist/package.js.map +0 -1
  76. package/dist/renderer.js +0 -2391
  77. package/dist/renderer.js.map +0 -1
  78. package/dist/standard.js +0 -101
  79. package/dist/standard.js.map +0 -1
  80. package/dist/utils.js +0 -54
  81. package/dist/utils.js.map +0 -1
  82. package/svelte-kit +0 -3
@@ -0,0 +1,8 @@
1
+ const SVELTE_KIT = '.svelte-kit';
2
+
3
+ // in `svelte-kit dev` and `svelte-kit preview`, we use a fake
4
+ // asset path so that we can serve local assets while still
5
+ // verifying that requests are correctly prefixed
6
+ const SVELTE_KIT_ASSETS = '/_svelte_kit_assets';
7
+
8
+ export { SVELTE_KIT as S, SVELTE_KIT_ASSETS as a };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @param {unknown} err
3
+ * @return {Error}
4
+ */
5
+ function coalesce_to_error(err) {
6
+ return err instanceof Error ||
7
+ (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message)
8
+ ? /** @type {Error} */ (err)
9
+ : new Error(JSON.stringify(err));
10
+ }
11
+
12
+ export { coalesce_to_error as c };
@@ -0,0 +1,476 @@
1
+ import path__default from 'path';
2
+ import { svelte } from '@sveltejs/vite-plugin-svelte';
3
+ import vite from 'vite';
4
+ import { r as resolve_entry, $, l as load_template, g as get_mime_lookup, a as rimraf, c as copy_assets, p as print_config_conflicts } from '../cli.js';
5
+ import { c as create_manifest_data, a as create_app, d as deep_merge } from './index2.js';
6
+ import { S as SVELTE_KIT, a as SVELTE_KIT_ASSETS } from './constants.js';
7
+ import fs__default from 'fs';
8
+ import { URL } from 'url';
9
+ import { respond } from '../ssr.js';
10
+ import { __fetch_polyfill } from '../install-fetch.js';
11
+ import { getRawBody } from '../node.js';
12
+ import { c as coalesce_to_error } from './error.js';
13
+ import 'sade';
14
+ import 'child_process';
15
+ import 'net';
16
+ import 'os';
17
+ import './misc.js';
18
+ import './url.js';
19
+ import 'node:http';
20
+ import 'node:https';
21
+ import 'node:zlib';
22
+ import 'node:stream';
23
+ import 'node:util';
24
+ import 'node:url';
25
+
26
+ /**
27
+ * @param {import('types/config').ValidatedConfig} config
28
+ * @param {string} output
29
+ * @param {string} cwd
30
+ * @returns {Promise<import('vite').Plugin>}
31
+ */
32
+ async function create_plugin(config, output, cwd) {
33
+ /** @type {import('amphtml-validator').Validator} */
34
+ let amp;
35
+
36
+ if (config.kit.amp) {
37
+ process.env.VITE_SVELTEKIT_AMP = 'true';
38
+ amp = await (await import('./index8.js').then(function (n) { return n.i; })).getInstance();
39
+ }
40
+
41
+ return {
42
+ name: 'vite-plugin-svelte-kit',
43
+
44
+ configureServer(vite) {
45
+ __fetch_polyfill();
46
+
47
+ /** @type {import('types/app').SSRManifest} */
48
+ let manifest;
49
+
50
+ function update_manifest() {
51
+ const manifest_data = create_manifest_data({ config, output, cwd });
52
+
53
+ create_app({ manifest_data, output, cwd });
54
+
55
+ manifest = {
56
+ appDir: config.kit.appDir,
57
+ assets: new Set(manifest_data.assets.map((asset) => asset.file)),
58
+ _: {
59
+ mime: get_mime_lookup(manifest_data),
60
+ entry: {
61
+ file: `/${SVELTE_KIT}/dev/runtime/internal/start.js`,
62
+ css: [],
63
+ js: []
64
+ },
65
+ nodes: manifest_data.components.map((id) => {
66
+ return async () => {
67
+ const url = `/${id}`;
68
+
69
+ const module = /** @type {import('types/internal').SSRComponent} */ (
70
+ await vite.ssrLoadModule(url)
71
+ );
72
+ const node = await vite.moduleGraph.getModuleByUrl(url);
73
+
74
+ if (!node) throw new Error(`Could not find node for ${url}`);
75
+
76
+ const deps = new Set();
77
+ find_deps(node, deps);
78
+
79
+ const styles = new Set();
80
+
81
+ for (const dep of deps) {
82
+ const parsed = new URL(dep.url, 'http://localhost/');
83
+ const query = parsed.searchParams;
84
+
85
+ // TODO what about .scss files, etc?
86
+ if (
87
+ dep.file.endsWith('.css') ||
88
+ (query.has('svelte') && query.get('type') === 'style')
89
+ ) {
90
+ try {
91
+ const mod = await vite.ssrLoadModule(dep.url);
92
+ styles.add(mod.default);
93
+ } catch {
94
+ // this can happen with dynamically imported modules, I think
95
+ // because the Vite module graph doesn't distinguish between
96
+ // static and dynamic imports? TODO investigate, submit fix
97
+ }
98
+ }
99
+ }
100
+
101
+ return {
102
+ module,
103
+ entry: url.endsWith('.svelte') ? url : url + '?import',
104
+ css: [],
105
+ js: [],
106
+ styles: Array.from(styles)
107
+ };
108
+ };
109
+ }),
110
+ routes: manifest_data.routes.map((route) => {
111
+ if (route.type === 'page') {
112
+ return {
113
+ type: 'page',
114
+ pattern: route.pattern,
115
+ params: get_params(route.params),
116
+ a: route.a.map((id) => manifest_data.components.indexOf(id)),
117
+ b: route.b.map((id) => manifest_data.components.indexOf(id))
118
+ };
119
+ }
120
+
121
+ return {
122
+ type: 'endpoint',
123
+ pattern: route.pattern,
124
+ params: get_params(route.params),
125
+ load: async () => {
126
+ const url = path__default.resolve(cwd, route.file);
127
+ return await vite.ssrLoadModule(url);
128
+ }
129
+ };
130
+ })
131
+ }
132
+ };
133
+ }
134
+
135
+ update_manifest();
136
+
137
+ vite.watcher.on('add', update_manifest);
138
+ vite.watcher.on('remove', update_manifest);
139
+
140
+ return () => {
141
+ remove_html_middlewares(vite.middlewares);
142
+
143
+ vite.middlewares.use(async (req, res) => {
144
+ try {
145
+ if (!req.url || !req.method) throw new Error('Incomplete request');
146
+ if (req.url === '/favicon.ico') return not_found(res);
147
+
148
+ const parsed = new URL(req.url, 'http://localhost/');
149
+ if (!parsed.pathname.startsWith(config.kit.paths.base)) return not_found(res);
150
+
151
+ /** @type {Partial<import('types/internal').Hooks>} */
152
+ const user_hooks = resolve_entry(config.kit.files.hooks)
153
+ ? await vite.ssrLoadModule(`/${config.kit.files.hooks}`)
154
+ : {};
155
+
156
+ /** @type {import('types/internal').Hooks} */
157
+ const hooks = {
158
+ getSession: user_hooks.getSession || (() => ({})),
159
+ handle: user_hooks.handle || (({ request, resolve }) => resolve(request)),
160
+ handleError:
161
+ user_hooks.handleError ||
162
+ (({ /** @type {Error & { frame?: string }} */ error }) => {
163
+ console.error($.bold().red(error.message));
164
+ if (error.frame) {
165
+ console.error($.gray(error.frame));
166
+ }
167
+ if (error.stack) {
168
+ console.error($.gray(error.stack));
169
+ }
170
+ }),
171
+ externalFetch: user_hooks.externalFetch || fetch
172
+ };
173
+
174
+ if (/** @type {any} */ (hooks).getContext) {
175
+ // TODO remove this for 1.0
176
+ throw new Error(
177
+ 'The getContext hook has been removed. See https://kit.svelte.dev/docs#hooks'
178
+ );
179
+ }
180
+
181
+ if (/** @type {any} */ (hooks).serverFetch) {
182
+ // TODO remove this for 1.0
183
+ throw new Error('The serverFetch hook has been renamed to externalFetch.');
184
+ }
185
+
186
+ const root = (await vite.ssrLoadModule(`/${output}/generated/root.svelte`)).default;
187
+
188
+ const paths = await vite.ssrLoadModule(`/${SVELTE_KIT}/dev/runtime/paths.js`);
189
+
190
+ paths.set_paths({
191
+ base: config.kit.paths.base,
192
+ assets: config.kit.paths.assets ? SVELTE_KIT_ASSETS : config.kit.paths.base
193
+ });
194
+
195
+ let body;
196
+
197
+ try {
198
+ body = await getRawBody(req);
199
+ } catch (/** @type {any} */ err) {
200
+ res.statusCode = err.status || 400;
201
+ return res.end(err.reason || 'Invalid request body');
202
+ }
203
+
204
+ const rendered = await respond(
205
+ {
206
+ url: new URL(
207
+ `${vite.config.server.https ? 'https' : 'http'}://${req.headers.host}${req.url}`
208
+ ),
209
+ headers: /** @type {import('types/helper').RequestHeaders} */ (req.headers),
210
+ method: req.method,
211
+ rawBody: body
212
+ },
213
+ {
214
+ amp: config.kit.amp,
215
+ dev: true,
216
+ floc: config.kit.floc,
217
+ get_stack: (error) => {
218
+ vite.ssrFixStacktrace(error);
219
+ return error.stack;
220
+ },
221
+ handle_error: (error, request) => {
222
+ vite.ssrFixStacktrace(error);
223
+ hooks.handleError({ error, request });
224
+ },
225
+ hooks,
226
+ hydrate: config.kit.hydrate,
227
+ manifest,
228
+ method_override: config.kit.methodOverride,
229
+ paths: {
230
+ base: config.kit.paths.base,
231
+ assets: config.kit.paths.assets ? SVELTE_KIT_ASSETS : config.kit.paths.base
232
+ },
233
+ prefix: '',
234
+ prerender: config.kit.prerender.enabled,
235
+ read: (file) => fs__default.readFileSync(path__default.join(config.kit.files.assets, file)),
236
+ root,
237
+ router: config.kit.router,
238
+ target: config.kit.target,
239
+ template: ({ head, body, assets }) => {
240
+ let rendered = load_template(cwd, config)
241
+ .replace('%svelte.head%', () => head)
242
+ .replace('%svelte.body%', () => body)
243
+ .replace(/%svelte\.assets%/g, assets);
244
+
245
+ if (amp) {
246
+ const result = amp.validateString(rendered);
247
+
248
+ if (result.status !== 'PASS') {
249
+ const lines = rendered.split('\n');
250
+
251
+ /** @param {string} str */
252
+ const escape = (str) =>
253
+ str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
254
+
255
+ rendered = `<!doctype html>
256
+ <head>
257
+ <meta charset="utf-8" />
258
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
259
+ <style>
260
+ body {
261
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
262
+ color: #333;
263
+ }
264
+
265
+ pre {
266
+ background: #f4f4f4;
267
+ padding: 1em;
268
+ overflow-x: auto;
269
+ }
270
+ </style>
271
+ </head>
272
+ <h1>AMP validation failed</h1>
273
+
274
+ ${result.errors
275
+ .map(
276
+ (error) => `
277
+ <h2>${error.severity}</h2>
278
+ <p>Line ${error.line}, column ${error.col}: ${error.message} (<a href="${error.specUrl}">${
279
+ error.code
280
+ }</a>)</p>
281
+ <pre>${escape(lines[error.line - 1])}</pre>
282
+ `
283
+ )
284
+ .join('\n\n')}
285
+ `;
286
+ }
287
+ }
288
+
289
+ return rendered;
290
+ },
291
+ trailing_slash: config.kit.trailingSlash
292
+ }
293
+ );
294
+
295
+ if (rendered) {
296
+ res.writeHead(rendered.status, rendered.headers);
297
+ if (rendered.body) res.write(rendered.body);
298
+ res.end();
299
+ } else {
300
+ not_found(res);
301
+ }
302
+ } catch (e) {
303
+ const error = coalesce_to_error(e);
304
+ vite.ssrFixStacktrace(error);
305
+ res.statusCode = 500;
306
+ res.end(error.stack);
307
+ }
308
+ });
309
+ };
310
+ }
311
+ };
312
+ }
313
+
314
+ /** @param {string[]} array */
315
+ function get_params(array) {
316
+ // given an array of params like `['x', 'y', 'z']` for
317
+ // src/routes/[x]/[y]/[z]/svelte, create a function
318
+ // that turns a RegExpExecArray into ({ x, y, z })
319
+
320
+ /** @param {RegExpExecArray} match */
321
+ const fn = (match) => {
322
+ /** @type {Record<string, string>} */
323
+ const params = {};
324
+ array.forEach((key, i) => {
325
+ if (key.startsWith('...')) {
326
+ params[key.slice(3)] = match[i + 1] || '';
327
+ } else {
328
+ params[key] = match[i + 1];
329
+ }
330
+ });
331
+ return params;
332
+ };
333
+
334
+ return fn;
335
+ }
336
+
337
+ /** @param {import('http').ServerResponse} res */
338
+ function not_found(res) {
339
+ res.statusCode = 404;
340
+ res.end('Not found');
341
+ }
342
+
343
+ /**
344
+ * @param {import('connect').Server} server
345
+ */
346
+ function remove_html_middlewares(server) {
347
+ const html_middlewares = [
348
+ 'viteIndexHtmlMiddleware',
349
+ 'vite404Middleware',
350
+ 'viteSpaFallbackMiddleware'
351
+ ];
352
+ for (let i = server.stack.length - 1; i > 0; i--) {
353
+ // @ts-expect-error using internals until https://github.com/vitejs/vite/pull/4640 is merged
354
+ if (html_middlewares.includes(server.stack[i].handle.name)) {
355
+ server.stack.splice(i, 1);
356
+ }
357
+ }
358
+ }
359
+
360
+ /**
361
+ * @param {import('vite').ModuleNode} node
362
+ * @param {Set<import('vite').ModuleNode>} deps
363
+ */
364
+ function find_deps(node, deps) {
365
+ for (const dep of node.importedModules) {
366
+ if (!deps.has(dep)) {
367
+ deps.add(dep);
368
+ find_deps(dep, deps);
369
+ }
370
+ }
371
+ }
372
+
373
+ /**
374
+ * @typedef {{
375
+ * cwd: string,
376
+ * port: number,
377
+ * host?: string,
378
+ * https: boolean,
379
+ * config: import('types/config').ValidatedConfig
380
+ * }} Options
381
+ * @typedef {import('types/internal').SSRComponent} SSRComponent
382
+ */
383
+
384
+ /** @param {Options} opts */
385
+ async function dev({ cwd, port, host, https, config }) {
386
+ const output = path__default.resolve(cwd, `${SVELTE_KIT}/dev`);
387
+
388
+ rimraf(output);
389
+ copy_assets(output);
390
+
391
+ const [vite_config] = deep_merge(
392
+ {
393
+ server: {
394
+ fs: {
395
+ allow: [
396
+ ...new Set([
397
+ config.kit.files.assets,
398
+ config.kit.files.lib,
399
+ config.kit.files.routes,
400
+ path__default.resolve(cwd, 'src'),
401
+ path__default.resolve(cwd, SVELTE_KIT),
402
+ path__default.resolve(cwd, 'node_modules'),
403
+ path__default.resolve(vite.searchForWorkspaceRoot(cwd), 'node_modules')
404
+ ])
405
+ ]
406
+ },
407
+ strictPort: true
408
+ }
409
+ },
410
+ config.kit.vite()
411
+ );
412
+
413
+ /** @type {[any, string[]]} */
414
+ const [merged_config, conflicts] = deep_merge(vite_config, {
415
+ configFile: false,
416
+ root: cwd,
417
+ resolve: {
418
+ alias: {
419
+ $app: path__default.resolve(`${output}/runtime/app`),
420
+ $lib: config.kit.files.lib
421
+ }
422
+ },
423
+ build: {
424
+ rollupOptions: {
425
+ // Vite dependency crawler needs an explicit JS entry point
426
+ // eventhough server otherwise works without it
427
+ input: path__default.resolve(`${output}/runtime/internal/start.js`)
428
+ }
429
+ },
430
+ plugins: [
431
+ svelte({
432
+ extensions: config.extensions,
433
+ emitCss: !config.kit.amp,
434
+ compilerOptions: {
435
+ hydratable: !!config.kit.hydrate
436
+ }
437
+ }),
438
+ await create_plugin(config, output, cwd)
439
+ ],
440
+ publicDir: config.kit.files.assets,
441
+ base: '/'
442
+ });
443
+
444
+ print_config_conflicts(conflicts, 'kit.vite.');
445
+
446
+ // optional config from command-line flags
447
+ // these should take precedence, but not print conflict warnings
448
+ if (host) {
449
+ merged_config.server.host = host;
450
+ }
451
+
452
+ // if https is already enabled then do nothing. it could be an object and we
453
+ // don't want to overwrite with a boolean
454
+ if (https && !merged_config.server.https) {
455
+ merged_config.server.https = https;
456
+ }
457
+
458
+ if (port) {
459
+ merged_config.server.port = port;
460
+ }
461
+
462
+ const server = await vite.createServer(merged_config);
463
+ await server.listen(port);
464
+
465
+ const address_info = /** @type {import('net').AddressInfo} */ (
466
+ /** @type {import('http').Server} */ (server.httpServer).address()
467
+ );
468
+
469
+ return {
470
+ address_info,
471
+ server_config: vite_config.server,
472
+ close: () => server.close()
473
+ };
474
+ }
475
+
476
+ export { dev };