-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
render.js
379 lines (314 loc) · 10.6 KB
/
render.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
import { devalue } from 'devalue';
import { readable, writable } from 'svelte/store';
import * as cookie from 'cookie';
import { hash } from '../../hash.js';
import { render_json_payload_script } from '../../../utils/escape.js';
import { s } from '../../../utils/misc.js';
import { Csp } from './csp.js';
import { serialize_error } from '../utils.js';
import { HttpError } from '../../control.js';
// TODO rename this function/module
const updated = {
...readable(false),
check: () => false
};
/**
* Creates the HTML response.
* @param {{
* branch: Array<import('./types').Loaded>;
* fetched: Array<import('./types').Fetched>;
* cookies: import('set-cookie-parser').Cookie[];
* options: import('types').SSROptions;
* state: import('types').SSRState;
* page_config: { hydrate: boolean, router: boolean };
* status: number;
* error: HttpError | Error | null;
* event: import('types').RequestEvent;
* resolve_opts: import('types').RequiredResolveOptions;
* validation_errors: Record<string, string> | undefined;
* }} opts
*/
export async function render_response({
branch,
fetched,
cookies,
options,
state,
page_config,
status,
error = null,
event,
resolve_opts,
validation_errors
}) {
if (state.prerendering) {
if (options.csp.mode === 'nonce') {
throw new Error('Cannot use prerendering if config.kit.csp.mode === "nonce"');
}
if (options.template_contains_nonce) {
throw new Error('Cannot use prerendering if page template contains %sveltekit.nonce%');
}
}
const { entry } = options.manifest._;
const stylesheets = new Set(entry.stylesheets);
const modulepreloads = new Set(entry.imports);
/** @type {Set<string>} */
const link_header_preloads = new Set();
/** @type {Map<string, string>} */
// TODO if we add a client entry point one day, we will need to include inline_styles with the entry, otherwise stylesheets will be linked even if they are below inlineStyleThreshold
const inline_styles = new Map();
let rendered;
const stack = error instanceof HttpError ? undefined : error?.stack;
if (error && options.dev && !(error instanceof HttpError)) {
error.stack = options.get_stack(error);
}
if (resolve_opts.ssr) {
/** @type {Record<string, any>} */
const props = {
stores: {
page: writable(null),
navigating: writable(null),
updated
},
components: await Promise.all(branch.map(({ node }) => node.component()))
};
let data = {};
// props_n (instead of props[n]) makes it easy to avoid
// unnecessary updates for layout components
for (let i = 0; i < branch.length; i += 1) {
data = { ...data, ...branch[i].data };
props[`data_${i}`] = data;
}
props.page = {
error,
params: /** @type {Record<string, any>} */ (event.params),
routeId: event.routeId,
status,
url: event.url,
data
};
if (validation_errors) {
props.errors = validation_errors;
}
// TODO remove this for 1.0
/**
* @param {string} property
* @param {string} replacement
*/
const print_error = (property, replacement) => {
Object.defineProperty(props.page, property, {
get: () => {
throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
}
});
};
print_error('origin', 'origin');
print_error('path', 'pathname');
print_error('query', 'searchParams');
rendered = options.root.render(props);
for (const { node } of branch) {
if (node.imports) {
node.imports.forEach((url) => modulepreloads.add(url));
}
if (node.stylesheets) {
node.stylesheets.forEach((url) => stylesheets.add(url));
}
if (node.inline_styles) {
Object.entries(await node.inline_styles()).forEach(([k, v]) => inline_styles.set(k, v));
}
}
} else {
rendered = { head: '', html: '', css: { code: '', map: null } };
}
let { head, html: body } = rendered;
const csp = new Csp(options.csp, {
dev: options.dev,
prerender: !!state.prerendering
});
const target = hash(body);
/**
* The prefix to use for static assets. Replaces `%sveltekit.assets%` in the template
* @type {string}
*/
let assets;
if (options.paths.assets) {
// if an asset path is specified, use it
assets = options.paths.assets;
} else if (state.prerendering?.fallback) {
// if we're creating a fallback page, asset paths need to be root-relative
assets = options.paths.base;
} else {
// otherwise we want asset paths to be relative to the page, so that they
// will work in odd contexts like IPFS, the internet archive, and so on
const segments = event.url.pathname.slice(options.paths.base.length).split('/').slice(2);
assets = segments.length > 0 ? segments.map(() => '..').join('/') : '.';
}
/** @param {string} path */
const prefixed = (path) => (path.startsWith('/') ? path : `${assets}/${path}`);
const serialized = { data: '', errors: 'null' };
try {
serialized.data = devalue(branch.map(({ server_data }) => server_data));
} catch (e) {
// If we're here, the data could not be serialized with devalue
// TODO if we wanted to get super fancy we could track down the origin of the `load`
// function, but it would mean passing more stuff around than we currently do
const error = /** @type {any} */ (e);
const match = /\[(\d+)\]\.data\.(.+)/.exec(error.path);
if (match) throw new Error(`${error.message} (data.${match[2]})`);
throw error;
}
if (validation_errors) {
try {
serialized.errors = devalue(validation_errors);
} catch (e) {
// If we're here, the data could not be serialized with devalue
const error = /** @type {any} */ (e);
if (error.path) throw new Error(`${error.message} (errors.${error.path})`);
throw error;
}
}
// prettier-ignore
const init_app = `
import { set_public_env, start } from ${s(prefixed(entry.file))};
set_public_env(${s(options.public_env)});
start({
target: document.querySelector('[data-sveltekit-hydrate="${target}"]').parentNode,
paths: ${s(options.paths)},
route: ${!!page_config.router},
spa: ${!resolve_opts.ssr},
trailing_slash: ${s(options.trailing_slash)},
hydrate: ${resolve_opts.ssr && page_config.hydrate ? `{
status: ${status},
error: ${error && serialize_error(error, e => e.stack)},
node_ids: [${branch.map(({ node }) => node.index).join(', ')}],
params: ${devalue(event.params)},
routeId: ${s(event.routeId)},
data: ${serialized.data},
errors: ${serialized.errors}
}` : 'null'}
});
`;
// we use an anonymous function instead of an arrow function to support
// older browsers (https://github.com/sveltejs/kit/pull/5417)
const init_service_worker = `
if ('serviceWorker' in navigator) {
addEventListener('load', function () {
navigator.serviceWorker.register('${options.service_worker}');
});
}
`;
if (inline_styles.size > 0) {
const content = Array.from(inline_styles.values()).join('\n');
const attributes = [];
if (options.dev) attributes.push(' data-sveltekit');
if (csp.style_needs_nonce) attributes.push(` nonce="${csp.nonce}"`);
csp.add_style(content);
head += `\n\t<style${attributes.join('')}>${content}</style>`;
}
for (const dep of stylesheets) {
const path = prefixed(dep);
const attributes = [];
if (csp.style_needs_nonce) {
attributes.push(`nonce="${csp.nonce}"`);
}
if (inline_styles.has(dep)) {
// don't load stylesheets that are already inlined
// include them in disabled state so that Vite can detect them and doesn't try to add them
attributes.push('disabled', 'media="(max-width: 0)"');
} else {
const preload_atts = ['rel="preload"', 'as="style"'].concat(attributes);
link_header_preloads.add(`<${encodeURI(path)}>; ${preload_atts.join(';')}; nopush`);
}
attributes.unshift('rel="stylesheet"');
head += `\n\t<link href="${path}" ${attributes.join(' ')}>`;
}
if (page_config.router || page_config.hydrate) {
for (const dep of modulepreloads) {
const path = prefixed(dep);
link_header_preloads.add(`<${encodeURI(path)}>; rel="modulepreload"; nopush`);
if (state.prerendering) {
head += `\n\t<link rel="modulepreload" href="${path}">`;
}
}
const attributes = ['type="module"', `data-sveltekit-hydrate="${target}"`];
csp.add_script(init_app);
if (csp.script_needs_nonce) {
attributes.push(`nonce="${csp.nonce}"`);
}
body += `\n\t\t<script ${attributes.join(' ')}>${init_app}</script>`;
}
if (resolve_opts.ssr && page_config.hydrate) {
/** @type {string[]} */
const serialized_data = [];
for (const { url, body, response } of fetched) {
serialized_data.push(
render_json_payload_script(
{ type: 'data', url, body: typeof body === 'string' ? hash(body) : undefined },
response
)
);
}
if (validation_errors) {
serialized_data.push(
render_json_payload_script({ type: 'validation_errors' }, validation_errors)
);
}
body += `\n\t${serialized_data.join('\n\t')}`;
}
if (options.service_worker) {
// always include service worker unless it's turned off explicitly
csp.add_script(init_service_worker);
head += `
<script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ''}>${init_service_worker}</script>`;
}
if (state.prerendering) {
// TODO read headers set with setHeaders and convert into http-equiv where possible
const http_equiv = [];
const csp_headers = csp.csp_provider.get_meta();
if (csp_headers) {
http_equiv.push(csp_headers);
}
if (state.prerendering.cache) {
http_equiv.push(`<meta http-equiv="cache-control" content="${state.prerendering.cache}">`);
}
if (http_equiv.length > 0) {
head = http_equiv.join('\n') + head;
}
}
// TODO flush chunks as early as we can
const html =
(await resolve_opts.transformPageChunk({
html: options.template({ head, body, assets, nonce: /** @type {string} */ (csp.nonce) }),
done: true
})) || '';
const headers = new Headers({
'content-type': 'text/html',
etag: `"${hash(html)}"`
});
if (!state.prerendering) {
const csp_header = csp.csp_provider.get_header();
if (csp_header) {
headers.set('content-security-policy', csp_header);
}
const report_only_header = csp.report_only_provider.get_header();
if (report_only_header) {
headers.set('content-security-policy-report-only', report_only_header);
}
for (const new_cookie of cookies) {
const { name, value, ...options } = new_cookie;
// @ts-expect-error
headers.append('set-cookie', cookie.serialize(name, value, options));
}
if (link_header_preloads.size) {
headers.set('link', Array.from(link_header_preloads).join(', '));
}
}
if (error && options.dev && !(error instanceof HttpError)) {
// reset stack, otherwise it may be 'fixed' a second time
error.stack = stack;
}
return new Response(html, {
status,
headers
});
}