@sveltejs/kit 1.0.0-next.45 → 1.0.0-next.452

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 (108) hide show
  1. package/README.md +12 -9
  2. package/package.json +92 -63
  3. package/src/cli.js +112 -0
  4. package/src/constants.js +7 -0
  5. package/src/core/adapt/builder.js +223 -0
  6. package/src/core/adapt/index.js +19 -0
  7. package/src/core/config/index.js +86 -0
  8. package/src/core/config/options.js +488 -0
  9. package/src/core/config/types.d.ts +1 -0
  10. package/src/core/env.js +112 -0
  11. package/src/core/generate_manifest/index.js +78 -0
  12. package/src/core/prerender/crawl.js +194 -0
  13. package/src/core/prerender/prerender.js +380 -0
  14. package/src/core/prerender/queue.js +80 -0
  15. package/src/core/sync/create_manifest_data/index.js +452 -0
  16. package/src/core/sync/create_manifest_data/types.d.ts +37 -0
  17. package/src/core/sync/sync.js +59 -0
  18. package/src/core/sync/utils.js +33 -0
  19. package/src/core/sync/write_ambient.js +53 -0
  20. package/src/core/sync/write_client_manifest.js +94 -0
  21. package/src/core/sync/write_matchers.js +25 -0
  22. package/src/core/sync/write_root.js +91 -0
  23. package/src/core/sync/write_tsconfig.js +195 -0
  24. package/src/core/sync/write_types/index.js +596 -0
  25. package/src/core/utils.js +70 -0
  26. package/src/exports/hooks/index.js +1 -0
  27. package/src/exports/hooks/sequence.js +26 -0
  28. package/src/exports/index.js +45 -0
  29. package/src/exports/node/index.js +145 -0
  30. package/src/exports/node/polyfills.js +40 -0
  31. package/src/exports/vite/build/build_server.js +348 -0
  32. package/src/exports/vite/build/build_service_worker.js +90 -0
  33. package/src/exports/vite/build/utils.js +160 -0
  34. package/src/exports/vite/dev/index.js +543 -0
  35. package/src/exports/vite/index.js +588 -0
  36. package/src/exports/vite/preview/index.js +186 -0
  37. package/src/exports/vite/types.d.ts +3 -0
  38. package/src/exports/vite/utils.js +345 -0
  39. package/src/runtime/app/env.js +1 -0
  40. package/src/runtime/app/environment.js +11 -0
  41. package/src/runtime/app/navigation.js +22 -0
  42. package/src/runtime/app/paths.js +1 -0
  43. package/src/runtime/app/stores.js +102 -0
  44. package/src/runtime/client/ambient.d.ts +24 -0
  45. package/src/runtime/client/client.js +1394 -0
  46. package/src/runtime/client/fetcher.js +60 -0
  47. package/src/runtime/client/parse.js +60 -0
  48. package/src/runtime/client/singletons.js +21 -0
  49. package/src/runtime/client/start.js +48 -0
  50. package/src/runtime/client/types.d.ts +88 -0
  51. package/src/runtime/client/utils.js +113 -0
  52. package/src/runtime/components/error.svelte +16 -0
  53. package/{assets → src/runtime}/components/layout.svelte +0 -0
  54. package/src/runtime/control.js +33 -0
  55. package/src/runtime/env/dynamic/private.js +1 -0
  56. package/src/runtime/env/dynamic/public.js +1 -0
  57. package/src/runtime/env-private.js +6 -0
  58. package/src/runtime/env-public.js +6 -0
  59. package/src/runtime/env.js +6 -0
  60. package/src/runtime/hash.js +16 -0
  61. package/src/runtime/paths.js +11 -0
  62. package/src/runtime/server/data/index.js +146 -0
  63. package/src/runtime/server/endpoint.js +50 -0
  64. package/src/runtime/server/index.js +369 -0
  65. package/src/runtime/server/page/cookie.js +25 -0
  66. package/src/runtime/server/page/crypto.js +239 -0
  67. package/src/runtime/server/page/csp.js +249 -0
  68. package/src/runtime/server/page/fetch.js +266 -0
  69. package/src/runtime/server/page/index.js +413 -0
  70. package/src/runtime/server/page/load_data.js +124 -0
  71. package/src/runtime/server/page/render.js +379 -0
  72. package/src/runtime/server/page/respond_with_error.js +94 -0
  73. package/src/runtime/server/page/types.d.ts +44 -0
  74. package/src/runtime/server/utils.js +137 -0
  75. package/src/utils/array.js +9 -0
  76. package/src/utils/error.js +22 -0
  77. package/src/utils/escape.js +104 -0
  78. package/src/utils/filesystem.js +108 -0
  79. package/src/utils/functions.js +16 -0
  80. package/src/utils/http.js +55 -0
  81. package/src/utils/misc.js +1 -0
  82. package/src/utils/routing.js +146 -0
  83. package/src/utils/url.js +142 -0
  84. package/svelte-kit.js +1 -1
  85. package/types/ambient.d.ts +319 -0
  86. package/types/index.d.ts +345 -0
  87. package/types/internal.d.ts +379 -0
  88. package/types/private.d.ts +209 -0
  89. package/CHANGELOG.md +0 -450
  90. package/assets/components/error.svelte +0 -13
  91. package/assets/runtime/app/env.js +0 -5
  92. package/assets/runtime/app/navigation.js +0 -41
  93. package/assets/runtime/app/paths.js +0 -1
  94. package/assets/runtime/app/stores.js +0 -93
  95. package/assets/runtime/chunks/utils.js +0 -19
  96. package/assets/runtime/internal/singletons.js +0 -23
  97. package/assets/runtime/internal/start.js +0 -770
  98. package/assets/runtime/paths.js +0 -12
  99. package/dist/chunks/index.js +0 -3521
  100. package/dist/chunks/index2.js +0 -587
  101. package/dist/chunks/index3.js +0 -246
  102. package/dist/chunks/index4.js +0 -536
  103. package/dist/chunks/index5.js +0 -761
  104. package/dist/chunks/index6.js +0 -322
  105. package/dist/chunks/standard.js +0 -99
  106. package/dist/chunks/utils.js +0 -83
  107. package/dist/cli.js +0 -546
  108. package/dist/ssr.js +0 -2580
@@ -0,0 +1,379 @@
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 { render_json_payload_script } from '../../../utils/escape.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: { hydrate: boolean, router: boolean };
27
+ * status: number;
28
+ * error: HttpError | Error | null;
29
+ * event: import('types').RequestEvent;
30
+ * resolve_opts: import('types').RequiredResolveOptions;
31
+ * validation_errors: Record<string, string> | undefined;
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
+ validation_errors
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.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
+ if (resolve_opts.ssr) {
78
+ /** @type {Record<string, any>} */
79
+ const props = {
80
+ stores: {
81
+ page: writable(null),
82
+ navigating: writable(null),
83
+ updated
84
+ },
85
+ components: await Promise.all(branch.map(({ node }) => node.component()))
86
+ };
87
+
88
+ let data = {};
89
+
90
+ // props_n (instead of props[n]) makes it easy to avoid
91
+ // unnecessary updates for layout components
92
+ for (let i = 0; i < branch.length; i += 1) {
93
+ data = { ...data, ...branch[i].data };
94
+ props[`data_${i}`] = data;
95
+ }
96
+
97
+ props.page = {
98
+ error,
99
+ params: /** @type {Record<string, any>} */ (event.params),
100
+ routeId: event.routeId,
101
+ status,
102
+ url: event.url,
103
+ data
104
+ };
105
+
106
+ if (validation_errors) {
107
+ props.errors = validation_errors;
108
+ }
109
+
110
+ // TODO remove this for 1.0
111
+ /**
112
+ * @param {string} property
113
+ * @param {string} replacement
114
+ */
115
+ const print_error = (property, replacement) => {
116
+ Object.defineProperty(props.page, property, {
117
+ get: () => {
118
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
119
+ }
120
+ });
121
+ };
122
+
123
+ print_error('origin', 'origin');
124
+ print_error('path', 'pathname');
125
+ print_error('query', 'searchParams');
126
+
127
+ rendered = options.root.render(props);
128
+
129
+ for (const { node } of branch) {
130
+ if (node.imports) {
131
+ node.imports.forEach((url) => modulepreloads.add(url));
132
+ }
133
+
134
+ if (node.stylesheets) {
135
+ node.stylesheets.forEach((url) => stylesheets.add(url));
136
+ }
137
+
138
+ if (node.inline_styles) {
139
+ Object.entries(await node.inline_styles()).forEach(([k, v]) => inline_styles.set(k, v));
140
+ }
141
+ }
142
+ } else {
143
+ rendered = { head: '', html: '', css: { code: '', map: null } };
144
+ }
145
+
146
+ let { head, html: body } = rendered;
147
+
148
+ const csp = new Csp(options.csp, {
149
+ dev: options.dev,
150
+ prerender: !!state.prerendering
151
+ });
152
+
153
+ const target = hash(body);
154
+
155
+ /**
156
+ * The prefix to use for static assets. Replaces `%sveltekit.assets%` in the template
157
+ * @type {string}
158
+ */
159
+ let assets;
160
+
161
+ if (options.paths.assets) {
162
+ // if an asset path is specified, use it
163
+ assets = options.paths.assets;
164
+ } else if (state.prerendering?.fallback) {
165
+ // if we're creating a fallback page, asset paths need to be root-relative
166
+ assets = options.paths.base;
167
+ } else {
168
+ // otherwise we want asset paths to be relative to the page, so that they
169
+ // will work in odd contexts like IPFS, the internet archive, and so on
170
+ const segments = event.url.pathname.slice(options.paths.base.length).split('/').slice(2);
171
+ assets = segments.length > 0 ? segments.map(() => '..').join('/') : '.';
172
+ }
173
+
174
+ /** @param {string} path */
175
+ const prefixed = (path) => (path.startsWith('/') ? path : `${assets}/${path}`);
176
+
177
+ const serialized = { data: '', errors: 'null' };
178
+
179
+ try {
180
+ serialized.data = devalue(branch.map(({ server_data }) => server_data));
181
+ } catch (e) {
182
+ // If we're here, the data could not be serialized with devalue
183
+ // TODO if we wanted to get super fancy we could track down the origin of the `load`
184
+ // function, but it would mean passing more stuff around than we currently do
185
+ const error = /** @type {any} */ (e);
186
+ const match = /\[(\d+)\]\.data\.(.+)/.exec(error.path);
187
+ if (match) throw new Error(`${error.message} (data.${match[2]})`);
188
+ throw error;
189
+ }
190
+
191
+ if (validation_errors) {
192
+ try {
193
+ serialized.errors = devalue(validation_errors);
194
+ } catch (e) {
195
+ // If we're here, the data could not be serialized with devalue
196
+ const error = /** @type {any} */ (e);
197
+ if (error.path) throw new Error(`${error.message} (errors.${error.path})`);
198
+ throw error;
199
+ }
200
+ }
201
+
202
+ // prettier-ignore
203
+ const init_app = `
204
+ import { set_public_env, start } from ${s(prefixed(entry.file))};
205
+
206
+ set_public_env(${s(options.public_env)});
207
+
208
+ start({
209
+ target: document.querySelector('[data-sveltekit-hydrate="${target}"]').parentNode,
210
+ paths: ${s(options.paths)},
211
+ route: ${!!page_config.router},
212
+ spa: ${!resolve_opts.ssr},
213
+ trailing_slash: ${s(options.trailing_slash)},
214
+ hydrate: ${resolve_opts.ssr && page_config.hydrate ? `{
215
+ status: ${status},
216
+ error: ${error && serialize_error(error, e => e.stack)},
217
+ node_ids: [${branch.map(({ node }) => node.index).join(', ')}],
218
+ params: ${devalue(event.params)},
219
+ routeId: ${s(event.routeId)},
220
+ data: ${serialized.data},
221
+ errors: ${serialized.errors}
222
+ }` : 'null'}
223
+ });
224
+ `;
225
+
226
+ // we use an anonymous function instead of an arrow function to support
227
+ // older browsers (https://github.com/sveltejs/kit/pull/5417)
228
+ const init_service_worker = `
229
+ if ('serviceWorker' in navigator) {
230
+ addEventListener('load', function () {
231
+ navigator.serviceWorker.register('${options.service_worker}');
232
+ });
233
+ }
234
+ `;
235
+
236
+ if (inline_styles.size > 0) {
237
+ const content = Array.from(inline_styles.values()).join('\n');
238
+
239
+ const attributes = [];
240
+ if (options.dev) attributes.push(' data-sveltekit');
241
+ if (csp.style_needs_nonce) attributes.push(` nonce="${csp.nonce}"`);
242
+
243
+ csp.add_style(content);
244
+
245
+ head += `\n\t<style${attributes.join('')}>${content}</style>`;
246
+ }
247
+
248
+ for (const dep of stylesheets) {
249
+ const path = prefixed(dep);
250
+ const attributes = [];
251
+
252
+ if (csp.style_needs_nonce) {
253
+ attributes.push(`nonce="${csp.nonce}"`);
254
+ }
255
+
256
+ if (inline_styles.has(dep)) {
257
+ // don't load stylesheets that are already inlined
258
+ // include them in disabled state so that Vite can detect them and doesn't try to add them
259
+ attributes.push('disabled', 'media="(max-width: 0)"');
260
+ } else {
261
+ const preload_atts = ['rel="preload"', 'as="style"'].concat(attributes);
262
+ link_header_preloads.add(`<${encodeURI(path)}>; ${preload_atts.join(';')}; nopush`);
263
+ }
264
+
265
+ attributes.unshift('rel="stylesheet"');
266
+ head += `\n\t<link href="${path}" ${attributes.join(' ')}>`;
267
+ }
268
+
269
+ if (page_config.router || page_config.hydrate) {
270
+ for (const dep of modulepreloads) {
271
+ const path = prefixed(dep);
272
+ link_header_preloads.add(`<${encodeURI(path)}>; rel="modulepreload"; nopush`);
273
+ if (state.prerendering) {
274
+ head += `\n\t<link rel="modulepreload" href="${path}">`;
275
+ }
276
+ }
277
+
278
+ const attributes = ['type="module"', `data-sveltekit-hydrate="${target}"`];
279
+
280
+ csp.add_script(init_app);
281
+
282
+ if (csp.script_needs_nonce) {
283
+ attributes.push(`nonce="${csp.nonce}"`);
284
+ }
285
+
286
+ body += `\n\t\t<script ${attributes.join(' ')}>${init_app}</script>`;
287
+ }
288
+
289
+ if (resolve_opts.ssr && page_config.hydrate) {
290
+ /** @type {string[]} */
291
+ const serialized_data = [];
292
+
293
+ for (const { url, body, response } of fetched) {
294
+ serialized_data.push(
295
+ render_json_payload_script(
296
+ { type: 'data', url, body: typeof body === 'string' ? hash(body) : undefined },
297
+ response
298
+ )
299
+ );
300
+ }
301
+
302
+ if (validation_errors) {
303
+ serialized_data.push(
304
+ render_json_payload_script({ type: 'validation_errors' }, validation_errors)
305
+ );
306
+ }
307
+
308
+ body += `\n\t${serialized_data.join('\n\t')}`;
309
+ }
310
+
311
+ if (options.service_worker) {
312
+ // always include service worker unless it's turned off explicitly
313
+ csp.add_script(init_service_worker);
314
+
315
+ head += `
316
+ <script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ''}>${init_service_worker}</script>`;
317
+ }
318
+
319
+ if (state.prerendering) {
320
+ // TODO read headers set with setHeaders and convert into http-equiv where possible
321
+ const http_equiv = [];
322
+
323
+ const csp_headers = csp.csp_provider.get_meta();
324
+ if (csp_headers) {
325
+ http_equiv.push(csp_headers);
326
+ }
327
+
328
+ if (state.prerendering.cache) {
329
+ http_equiv.push(`<meta http-equiv="cache-control" content="${state.prerendering.cache}">`);
330
+ }
331
+
332
+ if (http_equiv.length > 0) {
333
+ head = http_equiv.join('\n') + head;
334
+ }
335
+ }
336
+
337
+ // TODO flush chunks as early as we can
338
+ const html =
339
+ (await resolve_opts.transformPageChunk({
340
+ html: options.template({ head, body, assets, nonce: /** @type {string} */ (csp.nonce) }),
341
+ done: true
342
+ })) || '';
343
+
344
+ const headers = new Headers({
345
+ 'content-type': 'text/html',
346
+ etag: `"${hash(html)}"`
347
+ });
348
+
349
+ if (!state.prerendering) {
350
+ const csp_header = csp.csp_provider.get_header();
351
+ if (csp_header) {
352
+ headers.set('content-security-policy', csp_header);
353
+ }
354
+ const report_only_header = csp.report_only_provider.get_header();
355
+ if (report_only_header) {
356
+ headers.set('content-security-policy-report-only', report_only_header);
357
+ }
358
+
359
+ for (const new_cookie of cookies) {
360
+ const { name, value, ...options } = new_cookie;
361
+ // @ts-expect-error
362
+ headers.append('set-cookie', cookie.serialize(name, value, options));
363
+ }
364
+
365
+ if (link_header_preloads.size) {
366
+ headers.set('link', Array.from(link_header_preloads).join(', '));
367
+ }
368
+ }
369
+
370
+ if (error && options.dev && !(error instanceof HttpError)) {
371
+ // reset stack, otherwise it may be 'fixed' a second time
372
+ error.stack = stack;
373
+ }
374
+
375
+ return new Response(html, {
376
+ status,
377
+ headers
378
+ });
379
+ }
@@ -0,0 +1,94 @@
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 } 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
+ });
30
+
31
+ try {
32
+ const branch = [];
33
+
34
+ if (resolve_opts.ssr) {
35
+ const default_layout = await options.manifest._.nodes[0](); // 0 is always the root layout
36
+
37
+ const server_data_promise = load_server_data({
38
+ event,
39
+ state,
40
+ node: default_layout,
41
+ parent: async () => ({})
42
+ });
43
+
44
+ const server_data = await server_data_promise;
45
+
46
+ const data = await load_data({
47
+ event,
48
+ fetcher,
49
+ node: default_layout,
50
+ parent: async () => ({}),
51
+ server_data_promise,
52
+ state
53
+ });
54
+
55
+ branch.push(
56
+ {
57
+ node: default_layout,
58
+ server_data,
59
+ data
60
+ },
61
+ {
62
+ node: await options.manifest._.nodes[1](), // 1 is always the root error
63
+ data: null,
64
+ server_data: null
65
+ }
66
+ );
67
+ }
68
+
69
+ return await render_response({
70
+ options,
71
+ state,
72
+ page_config: {
73
+ hydrate: options.hydrate,
74
+ router: options.router
75
+ },
76
+ status,
77
+ error,
78
+ branch,
79
+ fetched,
80
+ cookies,
81
+ event,
82
+ resolve_opts,
83
+ validation_errors: undefined
84
+ });
85
+ } catch (err) {
86
+ const error = coalesce_to_error(err);
87
+
88
+ options.handle_error(error, event);
89
+
90
+ return new Response(error.stack, {
91
+ status: 500
92
+ });
93
+ }
94
+ }
@@ -0,0 +1,44 @@
1
+ import { ResponseHeaders, SSRNode, CspDirectives } from 'types';
2
+ import { HttpError } from '../../control.js';
3
+
4
+ export interface Fetched {
5
+ url: string;
6
+ body?: string | null;
7
+ response: {
8
+ status: number;
9
+ statusText: string;
10
+ headers: ResponseHeaders;
11
+ body: string;
12
+ };
13
+ }
14
+
15
+ export interface FetchState {
16
+ fetched: Fetched[];
17
+ cookies: string[];
18
+ new_cookies: string[];
19
+ }
20
+
21
+ export type Loaded = {
22
+ node: SSRNode;
23
+ data: Record<string, any> | null;
24
+ server_data: any;
25
+ };
26
+
27
+ type CspMode = 'hash' | 'nonce' | 'auto';
28
+
29
+ export interface CspConfig {
30
+ mode: CspMode;
31
+ directives: CspDirectives;
32
+ reportOnly: CspDirectives;
33
+ }
34
+
35
+ export interface CspOpts {
36
+ dev: boolean;
37
+ prerender: boolean;
38
+ }
39
+
40
+ export interface SerializedHttpError extends Pick<HttpError, 'message' | 'status'> {
41
+ name: 'HttpError';
42
+ stack: '';
43
+ __is_http_error: true;
44
+ }
@@ -0,0 +1,137 @@
1
+ import { devalue } from 'devalue';
2
+ import { HttpError } from '../control.js';
3
+
4
+ /** @param {any} body */
5
+ export function is_pojo(body) {
6
+ if (typeof body !== 'object') return false;
7
+
8
+ if (body) {
9
+ if (body instanceof Uint8Array) return false;
10
+ if (body instanceof ReadableStream) return false;
11
+
12
+ // if body is a node Readable, throw an error
13
+ // TODO remove this for 1.0
14
+ if (body._readableState && typeof body.pipe === 'function') {
15
+ throw new Error('Node streams are no longer supported — use a ReadableStream instead');
16
+ }
17
+ }
18
+
19
+ return true;
20
+ }
21
+
22
+ /**
23
+ * Serialize an error into a JSON string through `error_to_pojo`.
24
+ * This is necessary because `JSON.stringify(error) === '{}'`
25
+ *
26
+ * @param {Error | HttpError} error
27
+ * @param {(error: Error) => string | undefined} get_stack
28
+ */
29
+ export function serialize_error(error, get_stack) {
30
+ return JSON.stringify(error_to_pojo(error, get_stack));
31
+ }
32
+
33
+ /**
34
+ * Transform an error into a POJO, by copying its `name`, `message`
35
+ * and (in dev) `stack`, plus any custom properties, plus recursively
36
+ * serialized `cause` properties.
37
+ * Our own HttpError gets a meta property attached so we can identify it on the client.
38
+ *
39
+ * @param {HttpError | Error } error
40
+ * @param {(error: Error) => string | undefined} get_stack
41
+ */
42
+ export function error_to_pojo(error, get_stack) {
43
+ if (error instanceof HttpError) {
44
+ return /** @type {import('./page/types').SerializedHttpError} */ ({
45
+ message: error.message,
46
+ status: error.status,
47
+ __is_http_error: true // TODO we should probably make this unnecessary
48
+ });
49
+ }
50
+
51
+ const {
52
+ name,
53
+ message,
54
+ stack,
55
+ // @ts-expect-error i guess typescript doesn't know about error.cause yet
56
+ cause,
57
+ ...custom
58
+ } = error;
59
+
60
+ /** @type {Record<string, any>} */
61
+ const object = { name, message, stack: get_stack(error) };
62
+
63
+ if (cause) object.cause = error_to_pojo(cause, get_stack);
64
+
65
+ for (const key in custom) {
66
+ // @ts-expect-error
67
+ object[key] = custom[key];
68
+ }
69
+
70
+ return object;
71
+ }
72
+
73
+ // TODO: Remove for 1.0
74
+ /** @param {Record<string, any>} mod */
75
+ export function check_method_names(mod) {
76
+ ['get', 'post', 'put', 'patch', 'del'].forEach((m) => {
77
+ if (m in mod) {
78
+ const replacement = m === 'del' ? 'DELETE' : m.toUpperCase();
79
+ throw Error(
80
+ `Endpoint method "${m}" has changed to "${replacement}". See https://github.com/sveltejs/kit/discussions/5359 for more information.`
81
+ );
82
+ }
83
+ });
84
+ }
85
+
86
+ /** @type {import('types').SSRErrorPage} */
87
+ export const GENERIC_ERROR = {
88
+ id: '__error'
89
+ };
90
+
91
+ /**
92
+ * @param {Partial<Record<import('types').HttpMethod, any>>} mod
93
+ * @param {import('types').HttpMethod} method
94
+ */
95
+ export function method_not_allowed(mod, method) {
96
+ return new Response(`${method} method not allowed`, {
97
+ status: 405,
98
+ headers: {
99
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
100
+ // "The server must generate an Allow header field in a 405 status code response"
101
+ allow: allowed_methods(mod).join(', ')
102
+ }
103
+ });
104
+ }
105
+
106
+ /** @param {Partial<Record<import('types').HttpMethod, any>>} mod */
107
+ export function allowed_methods(mod) {
108
+ const allowed = [];
109
+
110
+ for (const method in ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']) {
111
+ if (method in mod) allowed.push(method);
112
+ }
113
+
114
+ if (mod.GET || mod.HEAD) allowed.push('HEAD');
115
+
116
+ return allowed;
117
+ }
118
+
119
+ /** @param {any} data */
120
+ export function data_response(data) {
121
+ try {
122
+ return new Response(`window.__sveltekit_data = ${devalue(data)}`, {
123
+ headers: {
124
+ 'content-type': 'application/javascript'
125
+ }
126
+ });
127
+ } catch (e) {
128
+ const error = /** @type {any} */ (e);
129
+ const match = /\[(\d+)\]\.data\.(.+)/.exec(error.path);
130
+ const message = match ? `${error.message} (data.${match[2]})` : error.message;
131
+ return new Response(`throw new Error(${JSON.stringify(message)})`, {
132
+ headers: {
133
+ 'content-type': 'application/javascript'
134
+ }
135
+ });
136
+ }
137
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Removes nullish values from an array.
3
+ *
4
+ * @template T
5
+ * @param {Array<T>} arr
6
+ */
7
+ export function compact(arr) {
8
+ return arr.filter(/** @returns {val is NonNullable<T>} */ (val) => val != null);
9
+ }
@@ -0,0 +1,22 @@
1
+ import { HttpError, Redirect } from '../runtime/control.js';
2
+
3
+ /**
4
+ * @param {unknown} err
5
+ * @return {Error}
6
+ */
7
+ export function coalesce_to_error(err) {
8
+ return err instanceof Error ||
9
+ (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message)
10
+ ? /** @type {Error} */ (err)
11
+ : new Error(JSON.stringify(err));
12
+ }
13
+
14
+ /**
15
+ * This is an identity function that exists to make TypeScript less
16
+ * paranoid about people throwing things that aren't errors, which
17
+ * frankly is not something we should care about
18
+ * @param {unknown} error
19
+ */
20
+ export function normalize_error(error) {
21
+ return /** @type {Redirect | HttpError | Error} */ (error);
22
+ }