-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
build_server.js
349 lines (304 loc) · 9.82 KB
/
build_server.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
import fs from 'fs';
import path from 'path';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { mkdirp, posixify } from '../../utils/filesystem.js';
import { deep_merge } from '../../utils/object.js';
import { load_template, print_config_conflicts } from '../config/index.js';
import { get_aliases, resolve_entry, runtime } from '../utils.js';
import { create_build, find_deps } from './utils.js';
import { SVELTE_KIT } from '../constants.js';
import { s } from '../../utils/misc.js';
/**
* @param {{
* hooks: string;
* config: import('types/config').ValidatedConfig;
* has_service_worker: boolean;
* template: string;
* }} opts
* @returns
*/
const app_template = ({ config, hooks, has_service_worker, template }) => `
import root from '__GENERATED__/root.svelte';
import { respond } from '${runtime}/server/index.js';
import { set_paths, assets, base } from '${runtime}/paths.js';
import { set_prerendering } from '${runtime}/env.js';
import * as user_hooks from ${s(hooks)};
const template = ({ head, body, assets, nonce }) => ${s(template)
.replace('%svelte.head%', '" + head + "')
.replace('%svelte.body%', '" + body + "')
.replace(/%svelte\.assets%/g, '" + assets + "')
.replace(/%svelte\.nonce%/g, '" + nonce + "')};
let read = null;
set_paths(${s(config.kit.paths)});
// this looks redundant, but the indirection allows us to access
// named imports without triggering Rollup's missing import detection
const get_hooks = hooks => ({
getSession: hooks.getSession || (() => ({})),
handle: hooks.handle || (({ event, resolve }) => resolve(event)),
handleError: hooks.handleError || (({ error }) => console.error(error.stack)),
externalFetch: hooks.externalFetch || fetch
});
let default_protocol = 'https';
// allow paths to be globally overridden
// in svelte-kit preview and in prerendering
export function override(settings) {
default_protocol = settings.protocol || default_protocol;
set_paths(settings.paths);
set_prerendering(settings.prerendering);
read = settings.read;
}
export class App {
constructor(manifest) {
const hooks = get_hooks(user_hooks);
this.options = {
amp: ${config.kit.amp},
csp: ${s(config.kit.csp)},
dev: false,
floc: ${config.kit.floc},
get_stack: error => String(error), // for security
handle_error: (error, event) => {
hooks.handleError({
error,
event,
// TODO remove for 1.0
// @ts-expect-error
get request() {
throw new Error('request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details');
}
});
error.stack = this.options.get_stack(error);
},
hooks,
hydrate: ${s(config.kit.browser.hydrate)},
manifest,
method_override: ${s(config.kit.methodOverride)},
paths: { base, assets },
prefix: assets + '/${config.kit.appDir}/',
prerender: ${config.kit.prerender.enabled},
read,
root,
service_worker: ${has_service_worker ? "base + '/service-worker.js'" : 'null'},
router: ${s(config.kit.browser.router)},
target: ${s(config.kit.target)},
template,
template_contains_nonce: ${template.includes('%svelte.nonce%')},
trailing_slash: ${s(config.kit.trailingSlash)}
};
}
render(request, options = {}) {
if (!(request instanceof Request)) {
throw new Error('The first argument to app.render must be a Request object. See https://github.com/sveltejs/kit/pull/3384 for details');
}
return respond(request, this.options, options);
}
}
`;
/**
* @param {{
* cwd: string;
* assets_base: string;
* config: import('types/config').ValidatedConfig
* manifest_data: import('types/internal').ManifestData
* build_dir: string;
* output_dir: string;
* service_worker_entry_file: string | null;
* service_worker_register: boolean;
* }} options
* @param {{ vite_manifest: import('vite').Manifest, assets: import('rollup').OutputAsset[] }} client
*/
export async function build_server(
{
cwd,
assets_base,
config,
manifest_data,
build_dir,
output_dir,
service_worker_entry_file,
service_worker_register
},
client
) {
let hooks_file = resolve_entry(config.kit.files.hooks);
if (!hooks_file || !fs.existsSync(hooks_file)) {
hooks_file = path.resolve(cwd, `${SVELTE_KIT}/build/hooks.js`);
fs.writeFileSync(hooks_file, '');
}
/** @type {Record<string, string>} */
const input = {
app: `${build_dir}/app.js`
};
// add entry points for every endpoint...
manifest_data.routes.forEach((route) => {
if (route.type === 'endpoint') {
const resolved = path.resolve(cwd, route.file);
const relative = path.relative(config.kit.files.routes, resolved);
const name = posixify(path.join('entries/endpoints', relative.replace(/\.js$/, '')));
input[name] = resolved;
}
});
// ...and every component used by pages
manifest_data.components.forEach((file) => {
const resolved = path.resolve(cwd, file);
const relative = path.relative(config.kit.files.routes, resolved);
const name = relative.startsWith('..')
? posixify(path.join('entries/pages', path.basename(file)))
: posixify(path.join('entries/pages', relative));
input[name] = resolved;
});
/** @type {(file: string) => string} */
const app_relative = (file) => {
const relative_file = path.relative(build_dir, path.resolve(cwd, file));
return relative_file[0] === '.' ? relative_file : `./${relative_file}`;
};
fs.writeFileSync(
input.app,
app_template({
config,
hooks: app_relative(hooks_file),
has_service_worker: service_worker_register && !!service_worker_entry_file,
template: load_template(cwd, config)
})
);
/** @type {import('vite').UserConfig} */
const vite_config = await config.kit.vite();
const default_config = {
build: {
target: 'es2020'
}
};
// don't warn on overriding defaults
const [modified_vite_config] = deep_merge(default_config, vite_config);
/** @type {[any, string[]]} */
const [merged_config, conflicts] = deep_merge(modified_vite_config, {
configFile: false,
root: cwd,
base: assets_base,
build: {
ssr: true,
outDir: `${output_dir}/server`,
manifest: true,
polyfillDynamicImport: false,
rollupOptions: {
input,
output: {
format: 'esm',
entryFileNames: '[name].js',
chunkFileNames: 'chunks/[name]-[hash].js',
assetFileNames: 'assets/[name]-[hash][extname]'
},
preserveEntrySignatures: 'strict'
}
},
plugins: [
svelte({
extensions: config.extensions,
compilerOptions: {
hydratable: !!config.kit.browser.hydrate
}
})
],
resolve: {
alias: get_aliases(config)
}
});
print_config_conflicts(conflicts, 'kit.vite.', 'build_server');
const { chunks } = await create_build(merged_config);
/** @type {Record<string, string[]>} */
const lookup = {};
chunks.forEach((chunk) => {
if (!chunk.facadeModuleId) return;
const id = chunk.facadeModuleId.slice(cwd.length + 1);
lookup[id] = chunk.exports;
});
/** @type {Record<string, import('types/internal').HttpMethod[]>} */
const methods = {};
manifest_data.routes.forEach((route) => {
if (route.type === 'endpoint' && lookup[route.file]) {
methods[route.file] = lookup[route.file]
.map((x) => /** @type {import('types/internal').HttpMethod} */ (method_names[x]))
.filter(Boolean);
}
});
/** @type {import('vite').Manifest} */
const vite_manifest = JSON.parse(fs.readFileSync(`${output_dir}/server/manifest.json`, 'utf-8'));
mkdirp(`${output_dir}/server/nodes`);
mkdirp(`${output_dir}/server/stylesheets`);
const stylesheet_lookup = new Map();
client.assets.forEach((asset) => {
if (asset.fileName.endsWith('.css')) {
if (config.kit.amp || asset.source.length < config.kit.inlineStyleThreshold) {
const index = stylesheet_lookup.size;
const file = `${output_dir}/server/stylesheets/${index}.js`;
fs.writeFileSync(file, `// ${asset.fileName}\nexport default ${s(asset.source)};`);
stylesheet_lookup.set(asset.fileName, index);
}
}
});
manifest_data.components.forEach((component, i) => {
const file = `${output_dir}/server/nodes/${i}.js`;
const js = new Set();
const css = new Set();
find_deps(component, client.vite_manifest, js, css);
const imports = [`import * as module from '../${vite_manifest[component].file}';`];
const exports = [
'export { module };',
`export const entry = '${client.vite_manifest[component].file}';`,
`export const js = ${s(Array.from(js))};`,
`export const css = ${s(Array.from(css))};`
];
/** @type {string[]} */
const styles = [];
css.forEach((file) => {
if (stylesheet_lookup.has(file)) {
const index = stylesheet_lookup.get(file);
const name = `stylesheet_${index}`;
imports.push(`import ${name} from '../stylesheets/${index}.js';`);
styles.push(`\t${s(file)}: ${name}`);
}
});
if (styles.length > 0) {
exports.push(`export const styles = {\n${styles.join(',\n')}\n};`);
}
fs.writeFileSync(file, `${imports.join('\n')}\n\n${exports.join('\n')}\n`);
});
return {
chunks,
vite_manifest,
methods: get_methods(cwd, chunks, manifest_data)
};
}
/** @type {Record<string, string>} */
const method_names = {
get: 'get',
head: 'head',
post: 'post',
put: 'put',
del: 'delete',
patch: 'patch'
};
/**
*
* @param {string} cwd
* @param {import('rollup').OutputChunk[]} output
* @param {import('types/internal').ManifestData} manifest_data
*/
function get_methods(cwd, output, manifest_data) {
/** @type {Record<string, string[]>} */
const lookup = {};
output.forEach((chunk) => {
if (!chunk.facadeModuleId) return;
const id = chunk.facadeModuleId.slice(cwd.length + 1);
lookup[id] = chunk.exports;
});
/** @type {Record<string, import('types/internal').HttpMethod[]>} */
const methods = {};
manifest_data.routes.forEach((route) => {
if (route.type === 'endpoint' && lookup[route.file]) {
methods[route.file] = lookup[route.file]
.map((x) => /** @type {import('types/internal').HttpMethod} */ (method_names[x]))
.filter(Boolean);
}
});
return methods;
}