@sveltejs/kit 1.0.0-next.52 → 1.0.0-next.520

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