-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
index.js
559 lines (480 loc) · 15.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
import { fork } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import colors from 'kleur';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import * as vite from 'vite';
import { mkdirp, posixify, rimraf } from '../utils/filesystem.js';
import * as sync from '../core/sync/sync.js';
import { build_server } from './build/build_server.js';
import { build_service_worker } from './build/build_service_worker.js';
import { load_config } from '../core/config/index.js';
import { dev } from './dev/index.js';
import { generate_manifest } from '../core/generate_manifest/index.js';
import { runtime_directory, logger } from '../core/utils.js';
import { find_deps, get_default_config as get_default_build_config } from './build/utils.js';
import { preview } from './preview/index.js';
import { get_aliases, resolve_entry, prevent_illegal_rollup_imports, get_env } from './utils.js';
import { fileURLToPath } from 'node:url';
import { create_module } from '../core/env.js';
const cwd = process.cwd();
/** @type {import('./types').EnforcedConfig} */
const enforced_config = {
appType: true,
base: true,
build: {
cssCodeSplit: true,
emptyOutDir: true,
lib: {
entry: true,
name: true,
formats: true
},
manifest: true,
outDir: true,
polyfillModulePreload: true,
rollupOptions: {
input: true,
output: {
format: true,
entryFileNames: true,
chunkFileNames: true,
assetFileNames: true
},
preserveEntrySignatures: true
},
ssr: true
},
publicDir: true,
resolve: {
alias: {
$app: true,
$lib: true,
'$service-worker': true
}
},
root: true
};
/**
* @return {import('vite').Plugin[]}
*/
export function sveltekit() {
return [...svelte(), kit()];
}
/**
* Returns the SvelteKit Vite plugin. Vite executes Rollup hooks as well as some of its own.
* Background reading is available at:
* - https://vitejs.dev/guide/api-plugin.html
* - https://rollupjs.org/guide/en/#plugin-development
*
* You can get an idea of the lifecycle by looking at the flow charts here:
* - https://rollupjs.org/guide/en/#build-hooks
* - https://rollupjs.org/guide/en/#output-generation-hooks
*
* @return {import('vite').Plugin}
*/
function kit() {
/** @type {import('types').ValidatedConfig} */
let svelte_config;
/** @type {import('vite').ResolvedConfig} */
let vite_config;
/** @type {import('vite').ConfigEnv} */
let vite_config_env;
/** @type {import('types').ManifestData} */
let manifest_data;
/** @type {boolean} */
let is_build;
/** @type {import('types').Logger} */
let log;
/** @type {import('types').Prerendered} */
let prerendered;
/** @type {import('types').BuildData} */
let build_data;
/** @type {Set<string>} */
let illegal_imports;
/** @type {string | undefined} */
let deferred_warning;
/** @type {{ public: Record<string, string>; private: Record<string, string> }} */
let env;
/**
* @type {{
* build_dir: string;
* output_dir: string;
* client_out_dir: string;
* }}
*/
let paths;
let completed_build = false;
function vite_client_build_config() {
/** @type {Record<string, string>} */
const input = {
// Put unchanging assets in immutable directory. We don't set that in the
// outDir so that other plugins can add mutable assets to the bundle
start: `${runtime_directory}/client/start.js`
};
manifest_data.nodes.forEach((node) => {
if (node.component) {
const resolved = path.resolve(cwd, node.component);
const relative = decodeURIComponent(
path.relative(svelte_config.kit.files.routes, resolved)
);
const name = relative.startsWith('..')
? path.basename(node.component)
: posixify(path.join('pages', relative));
input[`components/${name}`] = resolved;
}
if (node.shared) {
const resolved = path.resolve(cwd, node.shared);
const relative = decodeURIComponent(
path.relative(svelte_config.kit.files.routes, resolved)
);
const name = relative.startsWith('..')
? path.basename(node.shared)
: posixify(path.join('pages', relative));
input[`modules/${name}`] = resolved;
}
});
return get_default_build_config({
config: svelte_config,
input,
ssr: false,
outDir: `${paths.client_out_dir}`
});
}
/**
* @param {import('rollup').OutputAsset[]} assets
* @param {import('rollup').OutputChunk[]} chunks
*/
function client_build_info(assets, chunks) {
/** @type {import('vite').Manifest} */
const vite_manifest = JSON.parse(
fs.readFileSync(`${paths.client_out_dir}/${vite_config.build.manifest}`, 'utf-8')
);
const entry_id = posixify(path.relative(cwd, `${runtime_directory}/client/start.js`));
return {
assets,
chunks,
entry: find_deps(vite_manifest, entry_id, false),
vite_manifest
};
}
// TODO remove this for 1.0
check_vite_version();
return {
name: 'vite-plugin-svelte-kit',
/**
* Build the SvelteKit-provided Vite config to be merged with the user's vite.config.js file.
* @see https://vitejs.dev/guide/api-plugin.html#config
*/
async config(config, config_env) {
vite_config_env = config_env;
svelte_config = await load_config();
env = get_env(vite_config_env.mode, svelte_config.kit.env.publicPrefix);
// The config is created in build_server for SSR mode and passed inline
if (config.build?.ssr) return;
is_build = config_env.command === 'build';
paths = {
build_dir: `${svelte_config.kit.outDir}/build`,
output_dir: `${svelte_config.kit.outDir}/output`,
client_out_dir: `${svelte_config.kit.outDir}/output/client`
};
illegal_imports = new Set([
vite.normalizePath(`${svelte_config.kit.outDir}/runtime/env/dynamic/private.js`),
vite.normalizePath(`${svelte_config.kit.outDir}/runtime/env/static/private.js`)
]);
if (is_build) {
manifest_data = (await sync.all(svelte_config, config_env.mode)).manifest_data;
const new_config = vite_client_build_config();
const warning = warn_overridden_config(config, new_config);
if (warning) console.error(warning + '\n');
return new_config;
}
// dev and preview config can be shared
/** @type {import('vite').UserConfig} */
const result = {
appType: 'custom',
base: './',
build: {
rollupOptions: {
// Vite dependency crawler needs an explicit JS entry point
// eventhough server otherwise works without it
input: `${runtime_directory}/client/start.js`
}
},
define: {
__SVELTEKIT_DEV__: 'true',
__SVELTEKIT_APP_VERSION_POLL_INTERVAL__: '0'
},
publicDir: svelte_config.kit.files.assets,
resolve: {
alias: get_aliases(svelte_config.kit)
},
root: cwd,
server: {
fs: {
allow: [
...new Set([
svelte_config.kit.files.lib,
svelte_config.kit.files.routes,
svelte_config.kit.outDir,
path.resolve(cwd, 'src'),
path.resolve(cwd, 'node_modules'),
path.resolve(vite.searchForWorkspaceRoot(cwd), 'node_modules')
])
]
},
watch: {
ignored: [
// Ignore all siblings of config.kit.outDir/generated
`${posixify(svelte_config.kit.outDir)}/!(generated)`
]
}
}
};
deferred_warning = warn_overridden_config(config, result);
return result;
},
async resolveId(id) {
// treat $env/static/[public|private] as virtual
if (id.startsWith('$env/static/')) return `\0${id}`;
},
async load(id) {
switch (id) {
case '\0$env/static/private':
return create_module('$env/static/private', env.private);
case '\0$env/static/public':
return create_module('$env/static/public', env.public);
}
},
/**
* Stores the final config.
*/
configResolved(config) {
vite_config = config;
},
/**
* Clears the output directories.
*/
buildStart() {
if (vite_config.build.ssr) {
return;
}
// Reset for new build. Goes here because `build --watch` calls buildStart but not config
completed_build = false;
if (is_build) {
rimraf(paths.build_dir);
mkdirp(paths.build_dir);
rimraf(paths.output_dir);
mkdirp(paths.output_dir);
}
},
/**
* Vite builds a single bundle. We need three bundles: client, server, and service worker.
* The user's package.json scripts will invoke the Vite CLI to execute the client build. We
* then use this hook to kick off builds for the server and service worker.
*/
async writeBundle(_options, bundle) {
if (vite_config.build.ssr) {
return;
}
manifest_data.nodes.forEach((_node, i) => {
const id = vite.normalizePath(
path.resolve(svelte_config.kit.outDir, `generated/nodes/${i}.js`)
);
const module_node = this.getModuleInfo(id);
if (module_node) {
prevent_illegal_rollup_imports(
this.getModuleInfo.bind(this),
module_node,
illegal_imports,
svelte_config.kit.outDir
);
}
});
const verbose = vite_config.logLevel === 'info';
log = logger({
verbose
});
fs.writeFileSync(
`${paths.client_out_dir}/${svelte_config.kit.appDir}/version.json`,
JSON.stringify({ version: svelte_config.kit.version.name })
);
const { assets, chunks } = collect_output(bundle);
log.info(`Client build completed. Wrote ${chunks.length} chunks and ${assets.length} assets`);
log.info('Building server');
const options = {
cwd,
config: svelte_config,
vite_config,
vite_config_env,
build_dir: paths.build_dir, // TODO just pass `paths`
manifest_data,
output_dir: paths.output_dir,
service_worker_entry_file: resolve_entry(svelte_config.kit.files.serviceWorker)
};
const client = client_build_info(assets, chunks);
const server = await build_server(options, client);
/** @type {import('types').BuildData} */
build_data = {
app_dir: svelte_config.kit.appDir,
manifest_data,
service_worker: options.service_worker_entry_file ? 'service-worker.js' : null, // TODO make file configurable?
client,
server
};
const manifest_path = `${paths.output_dir}/server/manifest.js`;
fs.writeFileSync(
manifest_path,
`export const manifest = ${generate_manifest({
build_data,
relative_path: '.',
routes: manifest_data.routes
})};\n`
);
log.info('Prerendering');
await new Promise((fulfil, reject) => {
const results_path = `${svelte_config.kit.outDir}/generated/prerendered.json`;
// do prerendering in a subprocess so any dangling stuff gets killed upon completion
const script = fileURLToPath(new URL('../core/prerender/prerender.js', import.meta.url));
const child = fork(
script,
[vite_config.build.outDir, results_path, manifest_path, '' + verbose],
{
stdio: 'inherit'
}
);
child.on('exit', (code) => {
if (code) {
reject(new Error(`Prerendering failed with code ${code}`));
} else {
prerendered = JSON.parse(fs.readFileSync(results_path, 'utf8'), (key, value) => {
if (key === 'pages' || key === 'assets' || key === 'redirects') {
return new Map(value);
}
return value;
});
fulfil(undefined);
}
});
});
if (options.service_worker_entry_file) {
if (svelte_config.kit.paths.assets) {
throw new Error('Cannot use service worker alongside config.kit.paths.assets');
}
log.info('Building service worker');
await build_service_worker(options, prerendered, client.vite_manifest);
}
console.log(
`\nRun ${colors.bold().cyan('npm run preview')} to preview your production build locally.`
);
completed_build = true;
},
/**
* Runs the adapter.
*/
async closeBundle() {
// vite calls closeBundle when dev-server restarts, ignore that,
// and only adapt when build successfully completes.
const is_restart = !completed_build;
if (vite_config.build.ssr || is_restart) {
return;
}
if (svelte_config.kit.adapter) {
const { adapt } = await import('../core/adapt/index.js');
await adapt(svelte_config, build_data, prerendered, { log });
} else {
console.log(colors.bold().yellow('\nNo adapter specified'));
const link = colors.bold().cyan('https://kit.svelte.dev/docs/adapters');
console.log(
`See ${link} to learn how to configure your app to run on the platform of your choosing`
);
}
// avoid making the manifest available to users
fs.unlinkSync(`${paths.output_dir}/client/${vite_config.build.manifest}`);
fs.unlinkSync(`${paths.output_dir}/server/${vite_config.build.manifest}`);
},
/**
* Adds the SvelteKit middleware to do SSR in dev mode.
* @see https://vitejs.dev/guide/api-plugin.html#configureserver
*/
async configureServer(vite) {
// This method is called by Vite after clearing the screen.
// This patch ensures we can log any important messages afterwards for the user to see.
const print_urls = vite.printUrls;
vite.printUrls = function () {
print_urls.apply(this);
if (deferred_warning) console.error('\n' + deferred_warning);
};
return await dev(vite, vite_config, svelte_config, illegal_imports);
},
/**
* Adds the SvelteKit middleware to do SSR in preview mode.
* @see https://vitejs.dev/guide/api-plugin.html#configurepreviewserver
*/
configurePreviewServer(vite) {
return preview(vite, vite_config, svelte_config);
}
};
}
function check_vite_version() {
// TODO parse from kit peer deps and maybe do a full semver compare if we ever require feature releases a min
const min_required_vite_major = 3;
const vite_version = vite.version ?? '2.x'; // vite started exporting it's version in 3.0
const current_vite_major = parseInt(vite_version.split('.')[0], 10);
if (current_vite_major < min_required_vite_major) {
throw new Error(
`Vite version ${current_vite_major} is no longer supported. Please upgrade to version ${min_required_vite_major}`
);
}
}
/** @param {import('rollup').OutputBundle} bundle */
function collect_output(bundle) {
/** @type {import('rollup').OutputChunk[]} */
const chunks = [];
/** @type {import('rollup').OutputAsset[]} */
const assets = [];
for (const value of Object.values(bundle)) {
// collect asset and output chunks
if (value.type === 'asset') {
assets.push(value);
} else {
chunks.push(value);
}
}
return { assets, chunks };
}
/**
* @param {Record<string, any>} config
* @param {Record<string, any>} resolved_config
*/
function warn_overridden_config(config, resolved_config) {
const overridden = find_overridden_config(config, resolved_config, enforced_config, '', []);
if (overridden.length > 0) {
return (
colors.bold().red('The following Vite config options will be overridden by SvelteKit:') +
overridden.map((key) => `\n - ${key}`).join('')
);
}
}
/**
* @param {Record<string, any>} config
* @param {Record<string, any>} resolved_config
* @param {import('./types').EnforcedConfig} enforced_config
* @param {string} path
* @param {string[]} out used locally to compute the return value
*/
function find_overridden_config(config, resolved_config, enforced_config, path, out) {
for (const key in enforced_config) {
if (typeof config === 'object' && config !== null && key in config) {
const enforced = enforced_config[key];
if (enforced === true) {
if (config[key] !== resolved_config[key]) {
out.push(path + key);
}
} else {
find_overridden_config(config[key], resolved_config[key], enforced, path + key + '.', out);
}
}
}
return out;
}