@sveltejs/kit 1.0.0-next.47 → 1.0.0-next.472

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 (117) hide show
  1. package/README.md +12 -9
  2. package/package.json +93 -64
  3. package/scripts/special-types/$env+dynamic+private.md +8 -0
  4. package/scripts/special-types/$env+dynamic+public.md +8 -0
  5. package/scripts/special-types/$env+static+private.md +19 -0
  6. package/scripts/special-types/$env+static+public.md +7 -0
  7. package/scripts/special-types/$lib.md +1 -0
  8. package/src/cli.js +112 -0
  9. package/src/constants.js +7 -0
  10. package/src/core/adapt/builder.js +207 -0
  11. package/src/core/adapt/index.js +31 -0
  12. package/src/core/config/default-error.html +56 -0
  13. package/src/core/config/index.js +105 -0
  14. package/src/core/config/options.js +492 -0
  15. package/src/core/config/types.d.ts +1 -0
  16. package/src/core/env.js +121 -0
  17. package/src/core/generate_manifest/index.js +92 -0
  18. package/src/core/prerender/crawl.js +194 -0
  19. package/src/core/prerender/prerender.js +431 -0
  20. package/src/core/prerender/queue.js +80 -0
  21. package/src/core/sync/create_manifest_data/index.js +472 -0
  22. package/src/core/sync/create_manifest_data/types.d.ts +37 -0
  23. package/src/core/sync/sync.js +59 -0
  24. package/src/core/sync/utils.js +33 -0
  25. package/src/core/sync/write_ambient.js +53 -0
  26. package/src/core/sync/write_client_manifest.js +94 -0
  27. package/src/core/sync/write_matchers.js +25 -0
  28. package/src/core/sync/write_root.js +91 -0
  29. package/src/core/sync/write_tsconfig.js +195 -0
  30. package/src/core/sync/write_types/index.js +673 -0
  31. package/src/core/utils.js +70 -0
  32. package/src/exports/hooks/index.js +1 -0
  33. package/src/exports/hooks/sequence.js +44 -0
  34. package/src/exports/index.js +54 -0
  35. package/src/exports/node/index.js +145 -0
  36. package/src/exports/node/polyfills.js +41 -0
  37. package/src/exports/vite/build/build_server.js +357 -0
  38. package/src/exports/vite/build/build_service_worker.js +90 -0
  39. package/src/exports/vite/build/utils.js +162 -0
  40. package/src/exports/vite/dev/index.js +554 -0
  41. package/src/exports/vite/index.js +591 -0
  42. package/src/exports/vite/preview/index.js +186 -0
  43. package/src/exports/vite/types.d.ts +3 -0
  44. package/src/exports/vite/utils.js +361 -0
  45. package/src/runtime/app/env.js +1 -0
  46. package/src/runtime/app/environment.js +11 -0
  47. package/src/runtime/app/forms.js +65 -0
  48. package/src/runtime/app/navigation.js +23 -0
  49. package/src/runtime/app/paths.js +1 -0
  50. package/src/runtime/app/stores.js +102 -0
  51. package/src/runtime/client/ambient.d.ts +24 -0
  52. package/src/runtime/client/client.js +1558 -0
  53. package/src/runtime/client/fetcher.js +107 -0
  54. package/src/runtime/client/parse.js +60 -0
  55. package/src/runtime/client/singletons.js +21 -0
  56. package/src/runtime/client/start.js +37 -0
  57. package/src/runtime/client/types.d.ts +87 -0
  58. package/src/runtime/client/utils.js +159 -0
  59. package/src/runtime/components/error.svelte +16 -0
  60. package/{assets → src/runtime}/components/layout.svelte +0 -0
  61. package/src/runtime/control.js +100 -0
  62. package/src/runtime/env/dynamic/private.js +1 -0
  63. package/src/runtime/env/dynamic/public.js +1 -0
  64. package/src/runtime/env-private.js +6 -0
  65. package/src/runtime/env-public.js +6 -0
  66. package/src/runtime/env.js +6 -0
  67. package/src/runtime/hash.js +16 -0
  68. package/src/runtime/paths.js +11 -0
  69. package/src/runtime/server/cookie.js +76 -0
  70. package/src/runtime/server/data/index.js +146 -0
  71. package/src/runtime/server/endpoint.js +66 -0
  72. package/src/runtime/server/index.js +339 -0
  73. package/src/runtime/server/page/actions.js +225 -0
  74. package/src/runtime/server/page/crypto.js +239 -0
  75. package/src/runtime/server/page/csp.js +249 -0
  76. package/src/runtime/server/page/fetch.js +286 -0
  77. package/src/runtime/server/page/index.js +308 -0
  78. package/src/runtime/server/page/load_data.js +124 -0
  79. package/src/runtime/server/page/render.js +359 -0
  80. package/src/runtime/server/page/respond_with_error.js +92 -0
  81. package/src/runtime/server/page/serialize_data.js +87 -0
  82. package/src/runtime/server/page/types.d.ts +41 -0
  83. package/src/runtime/server/utils.js +220 -0
  84. package/src/utils/array.js +9 -0
  85. package/src/utils/error.js +22 -0
  86. package/src/utils/escape.js +46 -0
  87. package/src/utils/filesystem.js +108 -0
  88. package/src/utils/functions.js +16 -0
  89. package/src/utils/http.js +55 -0
  90. package/src/utils/misc.js +1 -0
  91. package/src/utils/routing.js +117 -0
  92. package/src/utils/url.js +142 -0
  93. package/svelte-kit.js +1 -1
  94. package/types/ambient.d.ts +404 -0
  95. package/types/index.d.ts +396 -0
  96. package/types/internal.d.ts +377 -0
  97. package/types/private.d.ts +210 -0
  98. package/CHANGELOG.md +0 -463
  99. package/assets/components/error.svelte +0 -13
  100. package/assets/runtime/app/env.js +0 -5
  101. package/assets/runtime/app/navigation.js +0 -44
  102. package/assets/runtime/app/paths.js +0 -1
  103. package/assets/runtime/app/stores.js +0 -93
  104. package/assets/runtime/chunks/utils.js +0 -22
  105. package/assets/runtime/internal/singletons.js +0 -23
  106. package/assets/runtime/internal/start.js +0 -773
  107. package/assets/runtime/paths.js +0 -12
  108. package/dist/chunks/index.js +0 -3517
  109. package/dist/chunks/index2.js +0 -587
  110. package/dist/chunks/index3.js +0 -246
  111. package/dist/chunks/index4.js +0 -530
  112. package/dist/chunks/index5.js +0 -763
  113. package/dist/chunks/index6.js +0 -322
  114. package/dist/chunks/standard.js +0 -99
  115. package/dist/chunks/utils.js +0 -83
  116. package/dist/cli.js +0 -553
  117. package/dist/ssr.js +0 -2581
@@ -0,0 +1,359 @@
1
+ import { devalue } from 'devalue';
2
+ import { readable, writable } from 'svelte/store';
3
+ import * as cookie from 'cookie';
4
+ import { hash } from '../../hash.js';
5
+ import { serialize_data } from './serialize_data.js';
6
+ import { s } from '../../../utils/misc.js';
7
+ import { Csp } from './csp.js';
8
+ import { serialize_error } from '../utils.js';
9
+ import { HttpError } from '../../control.js';
10
+
11
+ // TODO rename this function/module
12
+
13
+ const updated = {
14
+ ...readable(false),
15
+ check: () => false
16
+ };
17
+
18
+ /**
19
+ * Creates the HTML response.
20
+ * @param {{
21
+ * branch: Array<import('./types').Loaded>;
22
+ * fetched: Array<import('./types').Fetched>;
23
+ * cookies: import('set-cookie-parser').Cookie[];
24
+ * options: import('types').SSROptions;
25
+ * state: import('types').SSRState;
26
+ * page_config: { ssr: boolean; csr: boolean };
27
+ * status: number;
28
+ * error: HttpError | Error | null;
29
+ * event: import('types').RequestEvent;
30
+ * resolve_opts: import('types').RequiredResolveOptions;
31
+ * action_result?: import('types').ActionResult;
32
+ * }} opts
33
+ */
34
+ export async function render_response({
35
+ branch,
36
+ fetched,
37
+ cookies,
38
+ options,
39
+ state,
40
+ page_config,
41
+ status,
42
+ error = null,
43
+ event,
44
+ resolve_opts,
45
+ action_result
46
+ }) {
47
+ if (state.prerendering) {
48
+ if (options.csp.mode === 'nonce') {
49
+ throw new Error('Cannot use prerendering if config.kit.csp.mode === "nonce"');
50
+ }
51
+
52
+ if (options.app_template_contains_nonce) {
53
+ throw new Error('Cannot use prerendering if page template contains %sveltekit.nonce%');
54
+ }
55
+ }
56
+
57
+ const { entry } = options.manifest._;
58
+
59
+ const stylesheets = new Set(entry.stylesheets);
60
+ const modulepreloads = new Set(entry.imports);
61
+
62
+ /** @type {Set<string>} */
63
+ const link_header_preloads = new Set();
64
+
65
+ /** @type {Map<string, string>} */
66
+ // 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
67
+ const inline_styles = new Map();
68
+
69
+ let rendered;
70
+
71
+ const stack = error instanceof HttpError ? undefined : error?.stack;
72
+
73
+ if (error && options.dev && !(error instanceof HttpError)) {
74
+ error.stack = options.get_stack(error);
75
+ }
76
+
77
+ const form_value =
78
+ action_result?.type === 'success' || action_result?.type === 'invalid'
79
+ ? action_result.data ?? null
80
+ : null;
81
+
82
+ if (page_config.ssr) {
83
+ /** @type {Record<string, any>} */
84
+ const props = {
85
+ stores: {
86
+ page: writable(null),
87
+ navigating: writable(null),
88
+ updated
89
+ },
90
+ components: await Promise.all(branch.map(({ node }) => node.component())),
91
+ form: form_value
92
+ };
93
+
94
+ let data = {};
95
+
96
+ // props_n (instead of props[n]) makes it easy to avoid
97
+ // unnecessary updates for layout components
98
+ for (let i = 0; i < branch.length; i += 1) {
99
+ data = { ...data, ...branch[i].data };
100
+ props[`data_${i}`] = data;
101
+ }
102
+
103
+ props.page = {
104
+ error,
105
+ params: /** @type {Record<string, any>} */ (event.params),
106
+ routeId: event.routeId,
107
+ status,
108
+ url: event.url,
109
+ data
110
+ };
111
+
112
+ // TODO remove this for 1.0
113
+ /**
114
+ * @param {string} property
115
+ * @param {string} replacement
116
+ */
117
+ const print_error = (property, replacement) => {
118
+ Object.defineProperty(props.page, property, {
119
+ get: () => {
120
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
121
+ }
122
+ });
123
+ };
124
+
125
+ print_error('origin', 'origin');
126
+ print_error('path', 'pathname');
127
+ print_error('query', 'searchParams');
128
+
129
+ rendered = options.root.render(props);
130
+
131
+ for (const { node } of branch) {
132
+ if (node.imports) {
133
+ node.imports.forEach((url) => modulepreloads.add(url));
134
+ }
135
+
136
+ if (node.stylesheets) {
137
+ node.stylesheets.forEach((url) => stylesheets.add(url));
138
+ }
139
+
140
+ if (node.inline_styles) {
141
+ Object.entries(await node.inline_styles()).forEach(([k, v]) => inline_styles.set(k, v));
142
+ }
143
+ }
144
+ } else {
145
+ rendered = { head: '', html: '', css: { code: '', map: null } };
146
+ }
147
+
148
+ let { head, html: body } = rendered;
149
+
150
+ const csp = new Csp(options.csp, {
151
+ dev: options.dev,
152
+ prerender: !!state.prerendering
153
+ });
154
+
155
+ const target = hash(body);
156
+
157
+ /**
158
+ * The prefix to use for static assets. Replaces `%sveltekit.assets%` in the template
159
+ * @type {string}
160
+ */
161
+ let assets;
162
+
163
+ if (options.paths.assets) {
164
+ // if an asset path is specified, use it
165
+ assets = options.paths.assets;
166
+ } else if (state.prerendering?.fallback) {
167
+ // if we're creating a fallback page, asset paths need to be root-relative
168
+ assets = options.paths.base;
169
+ } else {
170
+ // otherwise we want asset paths to be relative to the page, so that they
171
+ // will work in odd contexts like IPFS, the internet archive, and so on
172
+ const segments = event.url.pathname.slice(options.paths.base.length).split('/').slice(2);
173
+ assets = segments.length > 0 ? segments.map(() => '..').join('/') : '.';
174
+ }
175
+
176
+ /** @param {string} path */
177
+ const prefixed = (path) => (path.startsWith('/') ? path : `${assets}/${path}`);
178
+
179
+ const serialized = { data: '', form: 'null' };
180
+
181
+ try {
182
+ serialized.data = devalue(branch.map(({ server_data }) => server_data));
183
+ } catch (e) {
184
+ // If we're here, the data could not be serialized with devalue
185
+ // TODO if we wanted to get super fancy we could track down the origin of the `load`
186
+ // function, but it would mean passing more stuff around than we currently do
187
+ const error = /** @type {any} */ (e);
188
+ const match = /\[(\d+)\]\.data\.(.+)/.exec(error.path);
189
+ if (match) throw new Error(`${error.message} (data.${match[2]})`);
190
+ throw error;
191
+ }
192
+
193
+ if (form_value) {
194
+ // no need to check it can be serialized, we already verified that it's JSON-friendly
195
+ serialized.form = devalue(form_value);
196
+ }
197
+
198
+ // prettier-ignore
199
+ const init_app = `
200
+ import { start } from ${s(prefixed(entry.file))};
201
+
202
+ start({
203
+ env: ${s(options.public_env)},
204
+ hydrate: ${page_config.ssr ? `{
205
+ status: ${status},
206
+ error: ${error && serialize_error(error, e => e.stack)},
207
+ node_ids: [${branch.map(({ node }) => node.index).join(', ')}],
208
+ params: ${devalue(event.params)},
209
+ routeId: ${s(event.routeId)},
210
+ data: ${serialized.data},
211
+ form: ${serialized.form}
212
+ }` : 'null'},
213
+ paths: ${s(options.paths)},
214
+ target: document.querySelector('[data-sveltekit-hydrate="${target}"]').parentNode,
215
+ trailing_slash: ${s(options.trailing_slash)}
216
+ });
217
+ `;
218
+
219
+ // we use an anonymous function instead of an arrow function to support
220
+ // older browsers (https://github.com/sveltejs/kit/pull/5417)
221
+ const init_service_worker = `
222
+ if ('serviceWorker' in navigator) {
223
+ addEventListener('load', function () {
224
+ navigator.serviceWorker.register('${options.service_worker}');
225
+ });
226
+ }
227
+ `;
228
+
229
+ if (inline_styles.size > 0) {
230
+ const content = Array.from(inline_styles.values()).join('\n');
231
+
232
+ const attributes = [];
233
+ if (options.dev) attributes.push(' data-sveltekit');
234
+ if (csp.style_needs_nonce) attributes.push(` nonce="${csp.nonce}"`);
235
+
236
+ csp.add_style(content);
237
+
238
+ head += `\n\t<style${attributes.join('')}>${content}</style>`;
239
+ }
240
+
241
+ for (const dep of stylesheets) {
242
+ const path = prefixed(dep);
243
+ const attributes = [];
244
+
245
+ if (csp.style_needs_nonce) {
246
+ attributes.push(`nonce="${csp.nonce}"`);
247
+ }
248
+
249
+ if (inline_styles.has(dep)) {
250
+ // don't load stylesheets that are already inlined
251
+ // include them in disabled state so that Vite can detect them and doesn't try to add them
252
+ attributes.push('disabled', 'media="(max-width: 0)"');
253
+ } else {
254
+ const preload_atts = ['rel="preload"', 'as="style"'].concat(attributes);
255
+ link_header_preloads.add(`<${encodeURI(path)}>; ${preload_atts.join(';')}; nopush`);
256
+ }
257
+
258
+ attributes.unshift('rel="stylesheet"');
259
+ head += `\n\t<link href="${path}" ${attributes.join(' ')}>`;
260
+ }
261
+
262
+ if (page_config.csr) {
263
+ for (const dep of modulepreloads) {
264
+ const path = prefixed(dep);
265
+ link_header_preloads.add(`<${encodeURI(path)}>; rel="modulepreload"; nopush`);
266
+ if (state.prerendering) {
267
+ head += `\n\t<link rel="modulepreload" href="${path}">`;
268
+ }
269
+ }
270
+
271
+ const attributes = ['type="module"', `data-sveltekit-hydrate="${target}"`];
272
+
273
+ csp.add_script(init_app);
274
+
275
+ if (csp.script_needs_nonce) {
276
+ attributes.push(`nonce="${csp.nonce}"`);
277
+ }
278
+
279
+ body += `\n\t\t<script ${attributes.join(' ')}>${init_app}</script>`;
280
+ }
281
+
282
+ if (page_config.ssr && page_config.csr) {
283
+ body += `\n\t${fetched
284
+ .map((item) =>
285
+ serialize_data(item, resolve_opts.filterSerializedResponseHeaders, !!state.prerendering)
286
+ )
287
+ .join('\n\t')}`;
288
+ }
289
+
290
+ if (options.service_worker) {
291
+ // always include service worker unless it's turned off explicitly
292
+ csp.add_script(init_service_worker);
293
+
294
+ head += `
295
+ <script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ''}>${init_service_worker}</script>`;
296
+ }
297
+
298
+ if (state.prerendering) {
299
+ // TODO read headers set with setHeaders and convert into http-equiv where possible
300
+ const http_equiv = [];
301
+
302
+ const csp_headers = csp.csp_provider.get_meta();
303
+ if (csp_headers) {
304
+ http_equiv.push(csp_headers);
305
+ }
306
+
307
+ if (state.prerendering.cache) {
308
+ http_equiv.push(`<meta http-equiv="cache-control" content="${state.prerendering.cache}">`);
309
+ }
310
+
311
+ if (http_equiv.length > 0) {
312
+ head = http_equiv.join('\n') + head;
313
+ }
314
+ }
315
+
316
+ // TODO flush chunks as early as we can
317
+ const html =
318
+ (await resolve_opts.transformPageChunk({
319
+ html: options.app_template({ head, body, assets, nonce: /** @type {string} */ (csp.nonce) }),
320
+ done: true
321
+ })) || '';
322
+
323
+ const headers = new Headers({
324
+ 'x-sveltekit-page': 'true',
325
+ 'content-type': 'text/html',
326
+ etag: `"${hash(html)}"`
327
+ });
328
+
329
+ if (!state.prerendering) {
330
+ const csp_header = csp.csp_provider.get_header();
331
+ if (csp_header) {
332
+ headers.set('content-security-policy', csp_header);
333
+ }
334
+ const report_only_header = csp.report_only_provider.get_header();
335
+ if (report_only_header) {
336
+ headers.set('content-security-policy-report-only', report_only_header);
337
+ }
338
+
339
+ for (const new_cookie of cookies) {
340
+ const { name, value, ...options } = new_cookie;
341
+ // @ts-expect-error
342
+ headers.append('set-cookie', cookie.serialize(name, value, options));
343
+ }
344
+
345
+ if (link_header_preloads.size) {
346
+ headers.set('link', Array.from(link_header_preloads).join(', '));
347
+ }
348
+ }
349
+
350
+ if (error && options.dev && !(error instanceof HttpError)) {
351
+ // reset stack, otherwise it may be 'fixed' a second time
352
+ error.stack = stack;
353
+ }
354
+
355
+ return new Response(html, {
356
+ status,
357
+ headers
358
+ });
359
+ }
@@ -0,0 +1,92 @@
1
+ import { render_response } from './render.js';
2
+ import { load_data, load_server_data } from './load_data.js';
3
+ import { coalesce_to_error } from '../../../utils/error.js';
4
+ import { GENERIC_ERROR, get_option, static_error_page } from '../utils.js';
5
+ import { create_fetch } from './fetch.js';
6
+
7
+ /**
8
+ * @typedef {import('./types.js').Loaded} Loaded
9
+ * @typedef {import('types').SSROptions} SSROptions
10
+ * @typedef {import('types').SSRState} SSRState
11
+ */
12
+
13
+ /**
14
+ * @param {{
15
+ * event: import('types').RequestEvent;
16
+ * options: SSROptions;
17
+ * state: SSRState;
18
+ * status: number;
19
+ * error: Error;
20
+ * resolve_opts: import('types').RequiredResolveOptions;
21
+ * }} opts
22
+ */
23
+ export async function respond_with_error({ event, options, state, status, error, resolve_opts }) {
24
+ const { fetcher, fetched, cookies } = create_fetch({
25
+ event,
26
+ options,
27
+ state,
28
+ route: GENERIC_ERROR,
29
+ resolve_opts
30
+ });
31
+
32
+ try {
33
+ const branch = [];
34
+ const default_layout = await options.manifest._.nodes[0](); // 0 is always the root layout
35
+ const ssr = get_option([default_layout], 'ssr') ?? true;
36
+
37
+ if (ssr) {
38
+ const server_data_promise = load_server_data({
39
+ event,
40
+ state,
41
+ node: default_layout,
42
+ parent: async () => ({})
43
+ });
44
+
45
+ const server_data = await server_data_promise;
46
+
47
+ const data = await load_data({
48
+ event,
49
+ fetcher,
50
+ node: default_layout,
51
+ parent: async () => ({}),
52
+ server_data_promise,
53
+ state
54
+ });
55
+
56
+ branch.push(
57
+ {
58
+ node: default_layout,
59
+ server_data,
60
+ data
61
+ },
62
+ {
63
+ node: await options.manifest._.nodes[1](), // 1 is always the root error
64
+ data: null,
65
+ server_data: null
66
+ }
67
+ );
68
+ }
69
+
70
+ return await render_response({
71
+ options,
72
+ state,
73
+ page_config: {
74
+ ssr,
75
+ csr: get_option([default_layout], 'csr') ?? true
76
+ },
77
+ status,
78
+ error,
79
+ branch,
80
+ fetched,
81
+ cookies,
82
+ event,
83
+ resolve_opts
84
+ });
85
+ } catch (err) {
86
+ const error = coalesce_to_error(err);
87
+
88
+ options.handle_error(error, event);
89
+
90
+ return static_error_page(options, 500, error.message);
91
+ }
92
+ }
@@ -0,0 +1,87 @@
1
+ import { escape_html_attr } from '../../../utils/escape.js';
2
+ import { hash } from '../../hash.js';
3
+
4
+ /**
5
+ * Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
6
+ *
7
+ * The first closes the script element, so everything after is treated as raw HTML.
8
+ * The second disables further parsing until `-->`, so the script element might be unexpectedly
9
+ * kept open until until an unrelated HTML comment in the page.
10
+ *
11
+ * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
12
+ * browsers.
13
+ *
14
+ * @see tests for unsafe parsing examples.
15
+ * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
16
+ * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
17
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
18
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
19
+ * @see https://github.com/tc39/proposal-json-superset
20
+ * @type {Record<string, string>}
21
+ */
22
+ const replacements = {
23
+ '<': '\\u003C',
24
+ '\u2028': '\\u2028',
25
+ '\u2029': '\\u2029'
26
+ };
27
+
28
+ const pattern = new RegExp(`[${Object.keys(replacements).join('')}]`, 'g');
29
+
30
+ /**
31
+ * Generates a raw HTML string containing a safe script element carrying data and associated attributes.
32
+ *
33
+ * It escapes all the special characters needed to guarantee the element is unbroken, but care must
34
+ * be taken to ensure it is inserted in the document at an acceptable position for a script element,
35
+ * and that the resulting string isn't further modified.
36
+ *
37
+ * @param {import('./types.js').Fetched} fetched
38
+ * @param {(name: string, value: string) => boolean} filter
39
+ * @param {boolean} [prerendering]
40
+ * @returns {string} The raw HTML of a script element carrying the JSON payload.
41
+ * @example const html = serialize_data('/data.json', null, { foo: 'bar' });
42
+ */
43
+ export function serialize_data(fetched, filter, prerendering = false) {
44
+ /** @type {Record<string, string>} */
45
+ const headers = {};
46
+
47
+ let cache_control = null;
48
+ let age = null;
49
+
50
+ for (const [key, value] of fetched.response.headers) {
51
+ if (filter(key, value)) {
52
+ headers[key] = value;
53
+ }
54
+
55
+ if (key === 'cache-control') cache_control = value;
56
+ if (key === 'age') age = value;
57
+ }
58
+
59
+ const payload = {
60
+ status: fetched.response.status,
61
+ statusText: fetched.response.statusText,
62
+ headers,
63
+ body: fetched.response_body
64
+ };
65
+
66
+ const safe_payload = JSON.stringify(payload).replace(pattern, (match) => replacements[match]);
67
+
68
+ const attrs = [
69
+ 'type="application/json"',
70
+ 'data-sveltekit-fetched',
71
+ `data-url=${escape_html_attr(fetched.url)}`
72
+ ];
73
+
74
+ if (fetched.request_body) {
75
+ attrs.push(`data-hash=${escape_html_attr(hash(fetched.request_body))}`);
76
+ }
77
+
78
+ if (!prerendering && fetched.method === 'GET' && cache_control) {
79
+ const match = /s-maxage=(\d+)/g.exec(cache_control) ?? /max-age=(\d+)/g.exec(cache_control);
80
+ if (match) {
81
+ const ttl = +match[1] - +(age ?? '0');
82
+ attrs.push(`data-ttl="${ttl}"`);
83
+ }
84
+ }
85
+
86
+ return `<script ${attrs.join(' ')}>${safe_payload}</script>`;
87
+ }
@@ -0,0 +1,41 @@
1
+ import { SSRNode, CspDirectives } from 'types';
2
+ import { HttpError } from '../../control.js';
3
+
4
+ export interface Fetched {
5
+ url: string;
6
+ method: string;
7
+ request_body?: string | null;
8
+ response_body: string;
9
+ response: Response;
10
+ }
11
+
12
+ export interface FetchState {
13
+ fetched: Fetched[];
14
+ cookies: string[];
15
+ new_cookies: string[];
16
+ }
17
+
18
+ export type Loaded = {
19
+ node: SSRNode;
20
+ data: Record<string, any> | null;
21
+ server_data: any;
22
+ };
23
+
24
+ type CspMode = 'hash' | 'nonce' | 'auto';
25
+
26
+ export interface CspConfig {
27
+ mode: CspMode;
28
+ directives: CspDirectives;
29
+ reportOnly: CspDirectives;
30
+ }
31
+
32
+ export interface CspOpts {
33
+ dev: boolean;
34
+ prerender: boolean;
35
+ }
36
+
37
+ export interface SerializedHttpError extends Pick<HttpError, 'message' | 'status'> {
38
+ name: 'HttpError';
39
+ stack: '';
40
+ __is_http_error: true;
41
+ }