@sveltejs/kit 1.0.0-next.403 → 1.0.0-next.407

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 (99) hide show
  1. package/package.json +24 -25
  2. package/{dist → src}/cli.js +19 -18
  3. package/{dist/chunks/index3.js → src/core/adapt/builder.js} +52 -63
  4. package/src/core/adapt/index.js +19 -0
  5. package/src/core/config/index.js +86 -0
  6. package/{dist/chunks/index.js → src/core/config/options.js} +7 -194
  7. package/src/core/config/types.d.ts +1 -0
  8. package/src/core/constants.js +3 -0
  9. package/src/core/generate_manifest/index.js +99 -0
  10. package/src/core/prerender/crawl.js +194 -0
  11. package/src/core/prerender/prerender.js +378 -0
  12. package/src/core/prerender/queue.js +80 -0
  13. package/src/core/sync/create_manifest_data/index.js +492 -0
  14. package/src/core/sync/create_manifest_data/types.d.ts +40 -0
  15. package/src/core/sync/sync.js +59 -0
  16. package/src/core/sync/utils.js +97 -0
  17. package/src/core/sync/write_ambient.js +87 -0
  18. package/src/core/sync/write_client_manifest.js +82 -0
  19. package/src/core/sync/write_matchers.js +25 -0
  20. package/src/core/sync/write_root.js +88 -0
  21. package/{dist/chunks → src/core/sync}/write_tsconfig.js +24 -108
  22. package/src/core/sync/write_types.js +738 -0
  23. package/src/core/utils.js +58 -0
  24. package/{dist → src}/hooks.js +1 -3
  25. package/src/index/index.js +45 -0
  26. package/src/index/private.js +33 -0
  27. package/src/node/index.js +145 -0
  28. package/src/node/polyfills.js +40 -0
  29. package/src/packaging/index.js +218 -0
  30. package/src/packaging/types.d.ts +8 -0
  31. package/src/packaging/typescript.js +150 -0
  32. package/src/packaging/utils.js +143 -0
  33. package/{assets → src/runtime}/app/env.js +3 -5
  34. package/src/runtime/app/navigation.js +22 -0
  35. package/src/runtime/app/paths.js +1 -0
  36. package/{assets → src/runtime}/app/stores.js +6 -9
  37. package/src/runtime/client/ambient.d.ts +17 -0
  38. package/{assets/client/start.js → src/runtime/client/client.js} +302 -878
  39. package/src/runtime/client/fetcher.js +60 -0
  40. package/src/runtime/client/parse.js +36 -0
  41. package/{assets → src/runtime}/client/singletons.js +2 -4
  42. package/src/runtime/client/start.js +48 -0
  43. package/src/runtime/client/types.d.ts +106 -0
  44. package/src/runtime/client/utils.js +113 -0
  45. package/src/runtime/components/error.svelte +16 -0
  46. package/{assets → src/runtime}/components/layout.svelte +0 -0
  47. package/{assets → src/runtime}/env/dynamic/private.js +0 -0
  48. package/{assets → src/runtime}/env/dynamic/public.js +0 -0
  49. package/{assets → src/runtime}/env-private.js +2 -4
  50. package/{assets → src/runtime}/env-public.js +2 -4
  51. package/src/runtime/env.js +6 -0
  52. package/src/runtime/hash.js +16 -0
  53. package/{assets → src/runtime}/paths.js +3 -5
  54. package/src/runtime/server/endpoint.js +42 -0
  55. package/src/runtime/server/index.js +434 -0
  56. package/src/runtime/server/page/cookie.js +25 -0
  57. package/src/runtime/server/page/crypto.js +239 -0
  58. package/src/runtime/server/page/csp.js +249 -0
  59. package/src/runtime/server/page/fetch.js +265 -0
  60. package/src/runtime/server/page/index.js +418 -0
  61. package/src/runtime/server/page/load_data.js +94 -0
  62. package/src/runtime/server/page/render.js +357 -0
  63. package/src/runtime/server/page/respond_with_error.js +105 -0
  64. package/src/runtime/server/page/types.d.ts +44 -0
  65. package/src/runtime/server/utils.js +116 -0
  66. package/src/utils/error.js +22 -0
  67. package/src/utils/escape.js +104 -0
  68. package/{dist/chunks → src/utils}/filesystem.js +22 -24
  69. package/src/utils/http.js +55 -0
  70. package/src/utils/misc.js +1 -0
  71. package/src/utils/routing.js +107 -0
  72. package/src/utils/url.js +97 -0
  73. package/src/vite/build/build_server.js +335 -0
  74. package/src/vite/build/build_service_worker.js +90 -0
  75. package/src/vite/build/utils.js +153 -0
  76. package/src/vite/dev/index.js +565 -0
  77. package/src/vite/index.js +540 -0
  78. package/src/vite/preview/index.js +186 -0
  79. package/src/vite/types.d.ts +3 -0
  80. package/src/vite/utils.js +335 -0
  81. package/svelte-kit.js +1 -10
  82. package/types/ambient.d.ts +5 -12
  83. package/types/index.d.ts +91 -44
  84. package/types/internal.d.ts +50 -72
  85. package/types/private.d.ts +2 -1
  86. package/assets/app/navigation.js +0 -24
  87. package/assets/app/paths.js +0 -1
  88. package/assets/components/error.svelte +0 -29
  89. package/assets/env.js +0 -8
  90. package/assets/server/index.js +0 -3579
  91. package/dist/chunks/error.js +0 -12
  92. package/dist/chunks/index2.js +0 -15745
  93. package/dist/chunks/multipart-parser.js +0 -458
  94. package/dist/chunks/sync.js +0 -1366
  95. package/dist/chunks/utils.js +0 -66
  96. package/dist/node/polyfills.js +0 -17928
  97. package/dist/node.js +0 -348
  98. package/dist/prerender.js +0 -788
  99. package/dist/vite.js +0 -2520
@@ -1,3579 +0,0 @@
1
- /** @param {Partial<import('types').ResponseHeaders> | undefined} object */
2
- function to_headers(object) {
3
- const headers = new Headers();
4
-
5
- if (object) {
6
- for (const key in object) {
7
- const value = object[key];
8
- if (!value) continue;
9
-
10
- if (Array.isArray(value)) {
11
- value.forEach((value) => {
12
- headers.append(key, /** @type {string} */ (value));
13
- });
14
- } else {
15
- headers.set(key, /** @type {string} */ (value));
16
- }
17
- }
18
- }
19
-
20
- return headers;
21
- }
22
-
23
- /**
24
- * Given an Accept header and a list of possible content types, pick
25
- * the most suitable one to respond with
26
- * @param {string} accept
27
- * @param {string[]} types
28
- */
29
- function negotiate(accept, types) {
30
- /** @type {Array<{ type: string, subtype: string, q: number, i: number }>} */
31
- const parts = [];
32
-
33
- accept.split(',').forEach((str, i) => {
34
- const match = /([^/]+)\/([^;]+)(?:;q=([0-9.]+))?/.exec(str);
35
-
36
- // no match equals invalid header — ignore
37
- if (match) {
38
- const [, type, subtype, q = '1'] = match;
39
- parts.push({ type, subtype, q: +q, i });
40
- }
41
- });
42
-
43
- parts.sort((a, b) => {
44
- if (a.q !== b.q) {
45
- return b.q - a.q;
46
- }
47
-
48
- if ((a.subtype === '*') !== (b.subtype === '*')) {
49
- return a.subtype === '*' ? 1 : -1;
50
- }
51
-
52
- if ((a.type === '*') !== (b.type === '*')) {
53
- return a.type === '*' ? 1 : -1;
54
- }
55
-
56
- return a.i - b.i;
57
- });
58
-
59
- let accepted;
60
- let min_priority = Infinity;
61
-
62
- for (const mimetype of types) {
63
- const [type, subtype] = mimetype.split('/');
64
- const priority = parts.findIndex(
65
- (part) =>
66
- (part.type === type || part.type === '*') &&
67
- (part.subtype === subtype || part.subtype === '*')
68
- );
69
-
70
- if (priority !== -1 && priority < min_priority) {
71
- accepted = mimetype;
72
- min_priority = priority;
73
- }
74
- }
75
-
76
- return accepted;
77
- }
78
-
79
- /**
80
- * Hash using djb2
81
- * @param {import('types').StrictBody} value
82
- */
83
- function hash(value) {
84
- let hash = 5381;
85
- let i = value.length;
86
-
87
- if (typeof value === 'string') {
88
- while (i) hash = (hash * 33) ^ value.charCodeAt(--i);
89
- } else {
90
- while (i) hash = (hash * 33) ^ value[--i];
91
- }
92
-
93
- return (hash >>> 0).toString(36);
94
- }
95
-
96
- /** @param {Record<string, any>} obj */
97
- function lowercase_keys(obj) {
98
- /** @type {Record<string, any>} */
99
- const clone = {};
100
-
101
- for (const key in obj) {
102
- clone[key.toLowerCase()] = obj[key];
103
- }
104
-
105
- return clone;
106
- }
107
-
108
- /** @param {any} body */
109
- function is_pojo(body) {
110
- if (typeof body !== 'object') return false;
111
-
112
- if (body) {
113
- if (body instanceof Uint8Array) return false;
114
- if (body instanceof ReadableStream) return false;
115
-
116
- // if body is a node Readable, throw an error
117
- // TODO remove this for 1.0
118
- if (body._readableState && typeof body.pipe === 'function') {
119
- throw new Error('Node streams are no longer supported — use a ReadableStream instead');
120
- }
121
- }
122
-
123
- return true;
124
- }
125
-
126
- /**
127
- * Serialize an error into a JSON string, by copying its `name`, `message`
128
- * and (in dev) `stack`, plus any custom properties, plus recursively
129
- * serialized `cause` properties. This is necessary because
130
- * `JSON.stringify(error) === '{}'`
131
- * @param {Error} error
132
- * @param {(error: Error) => string | undefined} get_stack
133
- */
134
- function serialize_error(error, get_stack) {
135
- return JSON.stringify(clone_error(error, get_stack));
136
- }
137
-
138
- /**
139
- * @param {Error} error
140
- * @param {(error: Error) => string | undefined} get_stack
141
- */
142
- function clone_error(error, get_stack) {
143
- const {
144
- name,
145
- message,
146
- stack,
147
- // @ts-expect-error i guess typescript doesn't know about error.cause yet
148
- cause,
149
- ...custom
150
- } = error;
151
-
152
- /** @type {Record<string, any>} */
153
- const object = { name, message, stack: get_stack(error) };
154
-
155
- if (cause) object.cause = clone_error(cause, get_stack);
156
-
157
- for (const key in custom) {
158
- // @ts-expect-error
159
- object[key] = custom[key];
160
- }
161
-
162
- return object;
163
- }
164
-
165
- // TODO: Remove for 1.0
166
- /** @param {Record<string, any>} mod */
167
- function check_method_names(mod) {
168
- ['get', 'post', 'put', 'patch', 'del'].forEach((m) => {
169
- if (m in mod) {
170
- const replacement = m === 'del' ? 'DELETE' : m.toUpperCase();
171
- throw Error(
172
- `Endpoint method "${m}" has changed to "${replacement}". See https://github.com/sveltejs/kit/discussions/5359 for more information.`
173
- );
174
- }
175
- });
176
- }
177
-
178
- /** @type {import('types').SSRErrorPage} */
179
- const GENERIC_ERROR = {
180
- id: '__error'
181
- };
182
-
183
- /** @param {string} body */
184
- function error(body) {
185
- return new Response(body, {
186
- status: 500
187
- });
188
- }
189
-
190
- /** @param {unknown} s */
191
- function is_string(s) {
192
- return typeof s === 'string' || s instanceof String;
193
- }
194
-
195
- const text_types = new Set([
196
- 'application/xml',
197
- 'application/json',
198
- 'application/x-www-form-urlencoded',
199
- 'multipart/form-data'
200
- ]);
201
-
202
- const bodyless_status_codes = new Set([101, 204, 205, 304]);
203
-
204
- /**
205
- * Decides how the body should be parsed based on its mime type
206
- *
207
- * @param {string | undefined | null} content_type The `content-type` header of a request/response.
208
- * @returns {boolean}
209
- */
210
- function is_text(content_type) {
211
- if (!content_type) return true; // defaults to json
212
- const type = content_type.split(';')[0].toLowerCase(); // get the mime type
213
-
214
- return type.startsWith('text/') || type.endsWith('+xml') || text_types.has(type);
215
- }
216
-
217
- /**
218
- * @param {import('types').RequestEvent} event
219
- * @param {{ [method: string]: import('types').RequestHandler }} mod
220
- * @param {import('types').SSROptions} options
221
- * @returns {Promise<Response>}
222
- */
223
- async function render_endpoint(event, mod, options) {
224
- const { method } = event.request;
225
-
226
- check_method_names(mod);
227
-
228
- /** @type {import('types').RequestHandler} */
229
- let handler = mod[method];
230
-
231
- if (!handler && method === 'HEAD') {
232
- handler = mod.GET;
233
- }
234
-
235
- if (!handler) {
236
- const allowed = [];
237
-
238
- for (const method in ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']) {
239
- if (mod[method]) allowed.push(method);
240
- }
241
-
242
- if (mod.GET || mod.HEAD) allowed.push('HEAD');
243
-
244
- return event.request.headers.get('x-sveltekit-load')
245
- ? // TODO would be nice to avoid these requests altogether,
246
- // by noting whether or not page endpoints export `get`
247
- new Response(undefined, {
248
- status: 204
249
- })
250
- : new Response(`${method} method not allowed`, {
251
- status: 405,
252
- headers: {
253
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
254
- // "The server must generate an Allow header field in a 405 status code response"
255
- allow: allowed.join(', ')
256
- }
257
- });
258
- }
259
-
260
- const response = await handler(event);
261
- const preface = `Invalid response from route ${event.url.pathname}`;
262
-
263
- if (typeof response !== 'object') {
264
- return error(`${preface}: expected an object, got ${typeof response}`);
265
- }
266
-
267
- // TODO remove for 1.0
268
- // @ts-expect-error
269
- if (response.fallthrough) {
270
- throw new Error(
271
- 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
272
- );
273
- }
274
-
275
- const { status = 200, body = {} } = response;
276
- const headers =
277
- response.headers instanceof Headers
278
- ? new Headers(response.headers)
279
- : to_headers(response.headers);
280
-
281
- const type = headers.get('content-type');
282
-
283
- if (
284
- !is_text(type) &&
285
- !(body instanceof Uint8Array || body instanceof ReadableStream || is_string(body))
286
- ) {
287
- return error(
288
- `${preface}: body must be an instance of string, Uint8Array or ReadableStream if content-type is not a supported textual content-type`
289
- );
290
- }
291
-
292
- /** @type {import('types').StrictBody} */
293
- let normalized_body;
294
-
295
- if (is_pojo(body) && (!type || type.startsWith('application/json'))) {
296
- headers.set('content-type', 'application/json; charset=utf-8');
297
- normalized_body =
298
- body instanceof Error ? serialize_error(body, options.get_stack) : JSON.stringify(body);
299
- } else {
300
- normalized_body = /** @type {import('types').StrictBody} */ (body);
301
- }
302
-
303
- if (
304
- (typeof normalized_body === 'string' || normalized_body instanceof Uint8Array) &&
305
- !headers.has('etag')
306
- ) {
307
- const cache_control = headers.get('cache-control');
308
- if (!cache_control || !/(no-store|immutable)/.test(cache_control)) {
309
- headers.set('etag', `"${hash(normalized_body)}"`);
310
- }
311
- }
312
-
313
- return new Response(
314
- method !== 'HEAD' && !bodyless_status_codes.has(status) ? normalized_body : undefined,
315
- {
316
- status,
317
- headers
318
- }
319
- );
320
- }
321
-
322
- var chars$1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
323
- var unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
324
- var reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
325
- var escaped = {
326
- '<': '\\u003C',
327
- '>': '\\u003E',
328
- '/': '\\u002F',
329
- '\\': '\\\\',
330
- '\b': '\\b',
331
- '\f': '\\f',
332
- '\n': '\\n',
333
- '\r': '\\r',
334
- '\t': '\\t',
335
- '\0': '\\0',
336
- '\u2028': '\\u2028',
337
- '\u2029': '\\u2029'
338
- };
339
- var objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join('\0');
340
- function devalue(value) {
341
- var counts = new Map();
342
- function walk(thing) {
343
- if (typeof thing === 'function') {
344
- throw new Error("Cannot stringify a function");
345
- }
346
- if (counts.has(thing)) {
347
- counts.set(thing, counts.get(thing) + 1);
348
- return;
349
- }
350
- counts.set(thing, 1);
351
- if (!isPrimitive(thing)) {
352
- var type = getType(thing);
353
- switch (type) {
354
- case 'Number':
355
- case 'String':
356
- case 'Boolean':
357
- case 'Date':
358
- case 'RegExp':
359
- return;
360
- case 'Array':
361
- thing.forEach(walk);
362
- break;
363
- case 'Set':
364
- case 'Map':
365
- Array.from(thing).forEach(walk);
366
- break;
367
- default:
368
- var proto = Object.getPrototypeOf(thing);
369
- if (proto !== Object.prototype &&
370
- proto !== null &&
371
- Object.getOwnPropertyNames(proto).sort().join('\0') !== objectProtoOwnPropertyNames) {
372
- throw new Error("Cannot stringify arbitrary non-POJOs");
373
- }
374
- if (Object.getOwnPropertySymbols(thing).length > 0) {
375
- throw new Error("Cannot stringify POJOs with symbolic keys");
376
- }
377
- Object.keys(thing).forEach(function (key) { return walk(thing[key]); });
378
- }
379
- }
380
- }
381
- walk(value);
382
- var names = new Map();
383
- Array.from(counts)
384
- .filter(function (entry) { return entry[1] > 1; })
385
- .sort(function (a, b) { return b[1] - a[1]; })
386
- .forEach(function (entry, i) {
387
- names.set(entry[0], getName(i));
388
- });
389
- function stringify(thing) {
390
- if (names.has(thing)) {
391
- return names.get(thing);
392
- }
393
- if (isPrimitive(thing)) {
394
- return stringifyPrimitive(thing);
395
- }
396
- var type = getType(thing);
397
- switch (type) {
398
- case 'Number':
399
- case 'String':
400
- case 'Boolean':
401
- return "Object(" + stringify(thing.valueOf()) + ")";
402
- case 'RegExp':
403
- return "new RegExp(" + stringifyString(thing.source) + ", \"" + thing.flags + "\")";
404
- case 'Date':
405
- return "new Date(" + thing.getTime() + ")";
406
- case 'Array':
407
- var members = thing.map(function (v, i) { return i in thing ? stringify(v) : ''; });
408
- var tail = thing.length === 0 || (thing.length - 1 in thing) ? '' : ',';
409
- return "[" + members.join(',') + tail + "]";
410
- case 'Set':
411
- case 'Map':
412
- return "new " + type + "([" + Array.from(thing).map(stringify).join(',') + "])";
413
- default:
414
- var obj = "{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":" + stringify(thing[key]); }).join(',') + "}";
415
- var proto = Object.getPrototypeOf(thing);
416
- if (proto === null) {
417
- return Object.keys(thing).length > 0
418
- ? "Object.assign(Object.create(null)," + obj + ")"
419
- : "Object.create(null)";
420
- }
421
- return obj;
422
- }
423
- }
424
- var str = stringify(value);
425
- if (names.size) {
426
- var params_1 = [];
427
- var statements_1 = [];
428
- var values_1 = [];
429
- names.forEach(function (name, thing) {
430
- params_1.push(name);
431
- if (isPrimitive(thing)) {
432
- values_1.push(stringifyPrimitive(thing));
433
- return;
434
- }
435
- var type = getType(thing);
436
- switch (type) {
437
- case 'Number':
438
- case 'String':
439
- case 'Boolean':
440
- values_1.push("Object(" + stringify(thing.valueOf()) + ")");
441
- break;
442
- case 'RegExp':
443
- values_1.push(thing.toString());
444
- break;
445
- case 'Date':
446
- values_1.push("new Date(" + thing.getTime() + ")");
447
- break;
448
- case 'Array':
449
- values_1.push("Array(" + thing.length + ")");
450
- thing.forEach(function (v, i) {
451
- statements_1.push(name + "[" + i + "]=" + stringify(v));
452
- });
453
- break;
454
- case 'Set':
455
- values_1.push("new Set");
456
- statements_1.push(name + "." + Array.from(thing).map(function (v) { return "add(" + stringify(v) + ")"; }).join('.'));
457
- break;
458
- case 'Map':
459
- values_1.push("new Map");
460
- statements_1.push(name + "." + Array.from(thing).map(function (_a) {
461
- var k = _a[0], v = _a[1];
462
- return "set(" + stringify(k) + ", " + stringify(v) + ")";
463
- }).join('.'));
464
- break;
465
- default:
466
- values_1.push(Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}');
467
- Object.keys(thing).forEach(function (key) {
468
- statements_1.push("" + name + safeProp(key) + "=" + stringify(thing[key]));
469
- });
470
- }
471
- });
472
- statements_1.push("return " + str);
473
- return "(function(" + params_1.join(',') + "){" + statements_1.join(';') + "}(" + values_1.join(',') + "))";
474
- }
475
- else {
476
- return str;
477
- }
478
- }
479
- function getName(num) {
480
- var name = '';
481
- do {
482
- name = chars$1[num % chars$1.length] + name;
483
- num = ~~(num / chars$1.length) - 1;
484
- } while (num >= 0);
485
- return reserved.test(name) ? name + "_" : name;
486
- }
487
- function isPrimitive(thing) {
488
- return Object(thing) !== thing;
489
- }
490
- function stringifyPrimitive(thing) {
491
- if (typeof thing === 'string')
492
- return stringifyString(thing);
493
- if (thing === void 0)
494
- return 'void 0';
495
- if (thing === 0 && 1 / thing < 0)
496
- return '-0';
497
- var str = String(thing);
498
- if (typeof thing === 'number')
499
- return str.replace(/^(-)?0\./, '$1.');
500
- return str;
501
- }
502
- function getType(thing) {
503
- return Object.prototype.toString.call(thing).slice(8, -1);
504
- }
505
- function escapeUnsafeChar(c) {
506
- return escaped[c] || c;
507
- }
508
- function escapeUnsafeChars(str) {
509
- return str.replace(unsafeChars, escapeUnsafeChar);
510
- }
511
- function safeKey(key) {
512
- return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
513
- }
514
- function safeProp(key) {
515
- return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? "." + key : "[" + escapeUnsafeChars(JSON.stringify(key)) + "]";
516
- }
517
- function stringifyString(str) {
518
- var result = '"';
519
- for (var i = 0; i < str.length; i += 1) {
520
- var char = str.charAt(i);
521
- var code = char.charCodeAt(0);
522
- if (char === '"') {
523
- result += '\\"';
524
- }
525
- else if (char in escaped) {
526
- result += escaped[char];
527
- }
528
- else if (code >= 0xd800 && code <= 0xdfff) {
529
- var next = str.charCodeAt(i + 1);
530
- // If this is the beginning of a [high, low] surrogate pair,
531
- // add the next two characters, otherwise escape
532
- if (code <= 0xdbff && (next >= 0xdc00 && next <= 0xdfff)) {
533
- result += char + str[++i];
534
- }
535
- else {
536
- result += "\\u" + code.toString(16).toUpperCase();
537
- }
538
- }
539
- else {
540
- result += char;
541
- }
542
- }
543
- result += '"';
544
- return result;
545
- }
546
-
547
- function noop() { }
548
- function safe_not_equal(a, b) {
549
- return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
550
- }
551
- Promise.resolve();
552
-
553
- const subscriber_queue = [];
554
- /**
555
- * Creates a `Readable` store that allows reading by subscription.
556
- * @param value initial value
557
- * @param {StartStopNotifier}start start and stop notifications for subscriptions
558
- */
559
- function readable(value, start) {
560
- return {
561
- subscribe: writable(value, start).subscribe
562
- };
563
- }
564
- /**
565
- * Create a `Writable` store that allows both updating and reading by subscription.
566
- * @param {*=}value initial value
567
- * @param {StartStopNotifier=}start start and stop notifications for subscriptions
568
- */
569
- function writable(value, start = noop) {
570
- let stop;
571
- const subscribers = new Set();
572
- function set(new_value) {
573
- if (safe_not_equal(value, new_value)) {
574
- value = new_value;
575
- if (stop) { // store is ready
576
- const run_queue = !subscriber_queue.length;
577
- for (const subscriber of subscribers) {
578
- subscriber[1]();
579
- subscriber_queue.push(subscriber, value);
580
- }
581
- if (run_queue) {
582
- for (let i = 0; i < subscriber_queue.length; i += 2) {
583
- subscriber_queue[i][0](subscriber_queue[i + 1]);
584
- }
585
- subscriber_queue.length = 0;
586
- }
587
- }
588
- }
589
- }
590
- function update(fn) {
591
- set(fn(value));
592
- }
593
- function subscribe(run, invalidate = noop) {
594
- const subscriber = [run, invalidate];
595
- subscribers.add(subscriber);
596
- if (subscribers.size === 1) {
597
- stop = start(set) || noop;
598
- }
599
- run(value);
600
- return () => {
601
- subscribers.delete(subscriber);
602
- if (subscribers.size === 0) {
603
- stop();
604
- stop = null;
605
- }
606
- };
607
- }
608
- return { set, update, subscribe };
609
- }
610
-
611
- /**
612
- * @param {unknown} err
613
- * @return {Error}
614
- */
615
- function coalesce_to_error(err) {
616
- return err instanceof Error ||
617
- (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message)
618
- ? /** @type {Error} */ (err)
619
- : new Error(JSON.stringify(err));
620
- }
621
-
622
- /**
623
- * Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
624
- *
625
- * The first closes the script element, so everything after is treated as raw HTML.
626
- * The second disables further parsing until `-->`, so the script element might be unexpectedly
627
- * kept open until until an unrelated HTML comment in the page.
628
- *
629
- * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
630
- * browsers.
631
- *
632
- * @see tests for unsafe parsing examples.
633
- * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
634
- * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
635
- * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
636
- * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
637
- * @see https://github.com/tc39/proposal-json-superset
638
- * @type {Record<string, string>}
639
- */
640
- const render_json_payload_script_dict = {
641
- '<': '\\u003C',
642
- '\u2028': '\\u2028',
643
- '\u2029': '\\u2029'
644
- };
645
-
646
- const render_json_payload_script_regex = new RegExp(
647
- `[${Object.keys(render_json_payload_script_dict).join('')}]`,
648
- 'g'
649
- );
650
-
651
- /**
652
- * Generates a raw HTML string containing a safe script element carrying JSON data and associated attributes.
653
- *
654
- * It escapes all the special characters needed to guarantee the element is unbroken, but care must
655
- * be taken to ensure it is inserted in the document at an acceptable position for a script element,
656
- * and that the resulting string isn't further modified.
657
- *
658
- * Attribute names must be type-checked so we don't need to escape them.
659
- *
660
- * @param {import('types').PayloadScriptAttributes} attrs A list of attributes to be added to the element.
661
- * @param {import('types').JSONValue} payload The data to be carried by the element. Must be serializable to JSON.
662
- * @returns {string} The raw HTML of a script element carrying the JSON payload.
663
- * @example const html = render_json_payload_script({ type: 'data', url: '/data.json' }, { foo: 'bar' });
664
- */
665
- function render_json_payload_script(attrs, payload) {
666
- const safe_payload = JSON.stringify(payload).replace(
667
- render_json_payload_script_regex,
668
- (match) => render_json_payload_script_dict[match]
669
- );
670
-
671
- let safe_attrs = '';
672
- for (const [key, value] of Object.entries(attrs)) {
673
- if (value === undefined) continue;
674
- safe_attrs += ` sveltekit:data-${key}=${escape_html_attr(value)}`;
675
- }
676
-
677
- return `<script type="application/json"${safe_attrs}>${safe_payload}</script>`;
678
- }
679
-
680
- /**
681
- * When inside a double-quoted attribute value, only `&` and `"` hold special meaning.
682
- * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state
683
- * @type {Record<string, string>}
684
- */
685
- const escape_html_attr_dict = {
686
- '&': '&amp;',
687
- '"': '&quot;'
688
- };
689
-
690
- const escape_html_attr_regex = new RegExp(
691
- // special characters
692
- `[${Object.keys(escape_html_attr_dict).join('')}]|` +
693
- // high surrogate without paired low surrogate
694
- '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' +
695
- // a valid surrogate pair, the only match with 2 code units
696
- // we match it so that we can match unpaired low surrogates in the same pass
697
- // TODO: use lookbehind assertions once they are widely supported: (?<![\ud800-udbff])[\udc00-\udfff]
698
- '[\\ud800-\\udbff][\\udc00-\\udfff]|' +
699
- // unpaired low surrogate (see previous match)
700
- '[\\udc00-\\udfff]',
701
- 'g'
702
- );
703
-
704
- /**
705
- * Formats a string to be used as an attribute's value in raw HTML.
706
- *
707
- * It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes
708
- * characters that are special in attributes, and surrounds the whole string in double-quotes.
709
- *
710
- * @param {string} str
711
- * @returns {string} Escaped string surrounded by double-quotes.
712
- * @example const html = `<tag data-value=${escape_html_attr('value')}>...</tag>`;
713
- */
714
- function escape_html_attr(str) {
715
- const escaped_str = str.replace(escape_html_attr_regex, (match) => {
716
- if (match.length === 2) {
717
- // valid surrogate pair
718
- return match;
719
- }
720
-
721
- return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`;
722
- });
723
-
724
- return `"${escaped_str}"`;
725
- }
726
-
727
- const s = JSON.stringify;
728
-
729
- const encoder = new TextEncoder();
730
-
731
- /**
732
- * SHA-256 hashing function adapted from https://bitwiseshiftleft.github.io/sjcl
733
- * modified and redistributed under BSD license
734
- * @param {string} data
735
- */
736
- function sha256(data) {
737
- if (!key[0]) precompute();
738
-
739
- const out = init.slice(0);
740
- const array = encode$1(data);
741
-
742
- for (let i = 0; i < array.length; i += 16) {
743
- const w = array.subarray(i, i + 16);
744
-
745
- let tmp;
746
- let a;
747
- let b;
748
-
749
- let out0 = out[0];
750
- let out1 = out[1];
751
- let out2 = out[2];
752
- let out3 = out[3];
753
- let out4 = out[4];
754
- let out5 = out[5];
755
- let out6 = out[6];
756
- let out7 = out[7];
757
-
758
- /* Rationale for placement of |0 :
759
- * If a value can overflow is original 32 bits by a factor of more than a few
760
- * million (2^23 ish), there is a possibility that it might overflow the
761
- * 53-bit mantissa and lose precision.
762
- *
763
- * To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that
764
- * propagates around the loop, and on the hash state out[]. I don't believe
765
- * that the clamps on out4 and on out0 are strictly necessary, but it's close
766
- * (for out4 anyway), and better safe than sorry.
767
- *
768
- * The clamps on out[] are necessary for the output to be correct even in the
769
- * common case and for short inputs.
770
- */
771
-
772
- for (let i = 0; i < 64; i++) {
773
- // load up the input word for this round
774
-
775
- if (i < 16) {
776
- tmp = w[i];
777
- } else {
778
- a = w[(i + 1) & 15];
779
-
780
- b = w[(i + 14) & 15];
781
-
782
- tmp = w[i & 15] =
783
- (((a >>> 7) ^ (a >>> 18) ^ (a >>> 3) ^ (a << 25) ^ (a << 14)) +
784
- ((b >>> 17) ^ (b >>> 19) ^ (b >>> 10) ^ (b << 15) ^ (b << 13)) +
785
- w[i & 15] +
786
- w[(i + 9) & 15]) |
787
- 0;
788
- }
789
-
790
- tmp =
791
- tmp +
792
- out7 +
793
- ((out4 >>> 6) ^ (out4 >>> 11) ^ (out4 >>> 25) ^ (out4 << 26) ^ (out4 << 21) ^ (out4 << 7)) +
794
- (out6 ^ (out4 & (out5 ^ out6))) +
795
- key[i]; // | 0;
796
-
797
- // shift register
798
- out7 = out6;
799
- out6 = out5;
800
- out5 = out4;
801
-
802
- out4 = (out3 + tmp) | 0;
803
-
804
- out3 = out2;
805
- out2 = out1;
806
- out1 = out0;
807
-
808
- out0 =
809
- (tmp +
810
- ((out1 & out2) ^ (out3 & (out1 ^ out2))) +
811
- ((out1 >>> 2) ^
812
- (out1 >>> 13) ^
813
- (out1 >>> 22) ^
814
- (out1 << 30) ^
815
- (out1 << 19) ^
816
- (out1 << 10))) |
817
- 0;
818
- }
819
-
820
- out[0] = (out[0] + out0) | 0;
821
- out[1] = (out[1] + out1) | 0;
822
- out[2] = (out[2] + out2) | 0;
823
- out[3] = (out[3] + out3) | 0;
824
- out[4] = (out[4] + out4) | 0;
825
- out[5] = (out[5] + out5) | 0;
826
- out[6] = (out[6] + out6) | 0;
827
- out[7] = (out[7] + out7) | 0;
828
- }
829
-
830
- const bytes = new Uint8Array(out.buffer);
831
- reverse_endianness(bytes);
832
-
833
- return base64(bytes);
834
- }
835
-
836
- /** The SHA-256 initialization vector */
837
- const init = new Uint32Array(8);
838
-
839
- /** The SHA-256 hash key */
840
- const key = new Uint32Array(64);
841
-
842
- /** Function to precompute init and key. */
843
- function precompute() {
844
- /** @param {number} x */
845
- function frac(x) {
846
- return (x - Math.floor(x)) * 0x100000000;
847
- }
848
-
849
- let prime = 2;
850
-
851
- for (let i = 0; i < 64; prime++) {
852
- let is_prime = true;
853
-
854
- for (let factor = 2; factor * factor <= prime; factor++) {
855
- if (prime % factor === 0) {
856
- is_prime = false;
857
-
858
- break;
859
- }
860
- }
861
-
862
- if (is_prime) {
863
- if (i < 8) {
864
- init[i] = frac(prime ** (1 / 2));
865
- }
866
-
867
- key[i] = frac(prime ** (1 / 3));
868
-
869
- i++;
870
- }
871
- }
872
- }
873
-
874
- /** @param {Uint8Array} bytes */
875
- function reverse_endianness(bytes) {
876
- for (let i = 0; i < bytes.length; i += 4) {
877
- const a = bytes[i + 0];
878
- const b = bytes[i + 1];
879
- const c = bytes[i + 2];
880
- const d = bytes[i + 3];
881
-
882
- bytes[i + 0] = d;
883
- bytes[i + 1] = c;
884
- bytes[i + 2] = b;
885
- bytes[i + 3] = a;
886
- }
887
- }
888
-
889
- /** @param {string} str */
890
- function encode$1(str) {
891
- const encoded = encoder.encode(str);
892
- const length = encoded.length * 8;
893
-
894
- // result should be a multiple of 512 bits in length,
895
- // with room for a 1 (after the data) and two 32-bit
896
- // words containing the original input bit length
897
- const size = 512 * Math.ceil((length + 65) / 512);
898
- const bytes = new Uint8Array(size / 8);
899
- bytes.set(encoded);
900
-
901
- // append a 1
902
- bytes[encoded.length] = 0b10000000;
903
-
904
- reverse_endianness(bytes);
905
-
906
- // add the input bit length
907
- const words = new Uint32Array(bytes.buffer);
908
- words[words.length - 2] = Math.floor(length / 0x100000000); // this will always be zero for us
909
- words[words.length - 1] = length;
910
-
911
- return words;
912
- }
913
-
914
- /*
915
- Based on https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
916
-
917
- MIT License
918
- Copyright (c) 2020 Egor Nepomnyaschih
919
- Permission is hereby granted, free of charge, to any person obtaining a copy
920
- of this software and associated documentation files (the "Software"), to deal
921
- in the Software without restriction, including without limitation the rights
922
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
923
- copies of the Software, and to permit persons to whom the Software is
924
- furnished to do so, subject to the following conditions:
925
- The above copyright notice and this permission notice shall be included in all
926
- copies or substantial portions of the Software.
927
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
928
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
929
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
930
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
931
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
932
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
933
- SOFTWARE.
934
- */
935
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
936
-
937
- /** @param {Uint8Array} bytes */
938
- function base64(bytes) {
939
- const l = bytes.length;
940
-
941
- let result = '';
942
- let i;
943
-
944
- for (i = 2; i < l; i += 3) {
945
- result += chars[bytes[i - 2] >> 2];
946
- result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
947
- result += chars[((bytes[i - 1] & 0x0f) << 2) | (bytes[i] >> 6)];
948
- result += chars[bytes[i] & 0x3f];
949
- }
950
-
951
- if (i === l + 1) {
952
- // 1 octet yet to write
953
- result += chars[bytes[i - 2] >> 2];
954
- result += chars[(bytes[i - 2] & 0x03) << 4];
955
- result += '==';
956
- }
957
-
958
- if (i === l) {
959
- // 2 octets yet to write
960
- result += chars[bytes[i - 2] >> 2];
961
- result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
962
- result += chars[(bytes[i - 1] & 0x0f) << 2];
963
- result += '=';
964
- }
965
-
966
- return result;
967
- }
968
-
969
- const array = new Uint8Array(16);
970
-
971
- function generate_nonce() {
972
- crypto.getRandomValues(array);
973
- return base64(array);
974
- }
975
-
976
- const quoted = new Set([
977
- 'self',
978
- 'unsafe-eval',
979
- 'unsafe-hashes',
980
- 'unsafe-inline',
981
- 'none',
982
- 'strict-dynamic',
983
- 'report-sample'
984
- ]);
985
-
986
- const crypto_pattern = /^(nonce|sha\d\d\d)-/;
987
-
988
- // CSP and CSP Report Only are extremely similar with a few caveats
989
- // the easiest/DRYest way to express this is with some private encapsulation
990
- class BaseProvider {
991
- /** @type {boolean} */
992
- #use_hashes;
993
-
994
- /** @type {boolean} */
995
- #script_needs_csp;
996
-
997
- /** @type {boolean} */
998
- #style_needs_csp;
999
-
1000
- /** @type {import('types').CspDirectives} */
1001
- #directives;
1002
-
1003
- /** @type {import('types').Csp.Source[]} */
1004
- #script_src;
1005
-
1006
- /** @type {import('types').Csp.Source[]} */
1007
- #style_src;
1008
-
1009
- /** @type {string} */
1010
- #nonce;
1011
-
1012
- /**
1013
- * @param {boolean} use_hashes
1014
- * @param {import('types').CspDirectives} directives
1015
- * @param {string} nonce
1016
- * @param {boolean} dev
1017
- */
1018
- constructor(use_hashes, directives, nonce, dev) {
1019
- this.#use_hashes = use_hashes;
1020
- this.#directives = dev ? { ...directives } : directives; // clone in dev so we can safely mutate
1021
-
1022
- const d = this.#directives;
1023
-
1024
- if (dev) {
1025
- // remove strict-dynamic in dev...
1026
- // TODO reinstate this if we can figure out how to make strict-dynamic work
1027
- // if (d['default-src']) {
1028
- // d['default-src'] = d['default-src'].filter((name) => name !== 'strict-dynamic');
1029
- // if (d['default-src'].length === 0) delete d['default-src'];
1030
- // }
1031
-
1032
- // if (d['script-src']) {
1033
- // d['script-src'] = d['script-src'].filter((name) => name !== 'strict-dynamic');
1034
- // if (d['script-src'].length === 0) delete d['script-src'];
1035
- // }
1036
-
1037
- const effective_style_src = d['style-src'] || d['default-src'];
1038
-
1039
- // ...and add unsafe-inline so we can inject <style> elements
1040
- if (effective_style_src && !effective_style_src.includes('unsafe-inline')) {
1041
- d['style-src'] = [...effective_style_src, 'unsafe-inline'];
1042
- }
1043
- }
1044
-
1045
- this.#script_src = [];
1046
- this.#style_src = [];
1047
-
1048
- const effective_script_src = d['script-src'] || d['default-src'];
1049
- const effective_style_src = d['style-src'] || d['default-src'];
1050
-
1051
- this.#script_needs_csp =
1052
- !!effective_script_src &&
1053
- effective_script_src.filter((value) => value !== 'unsafe-inline').length > 0;
1054
-
1055
- this.#style_needs_csp =
1056
- !dev &&
1057
- !!effective_style_src &&
1058
- effective_style_src.filter((value) => value !== 'unsafe-inline').length > 0;
1059
-
1060
- this.script_needs_nonce = this.#script_needs_csp && !this.#use_hashes;
1061
- this.style_needs_nonce = this.#style_needs_csp && !this.#use_hashes;
1062
- this.#nonce = nonce;
1063
- }
1064
-
1065
- /** @param {string} content */
1066
- add_script(content) {
1067
- if (this.#script_needs_csp) {
1068
- if (this.#use_hashes) {
1069
- this.#script_src.push(`sha256-${sha256(content)}`);
1070
- } else if (this.#script_src.length === 0) {
1071
- this.#script_src.push(`nonce-${this.#nonce}`);
1072
- }
1073
- }
1074
- }
1075
-
1076
- /** @param {string} content */
1077
- add_style(content) {
1078
- if (this.#style_needs_csp) {
1079
- if (this.#use_hashes) {
1080
- this.#style_src.push(`sha256-${sha256(content)}`);
1081
- } else if (this.#style_src.length === 0) {
1082
- this.#style_src.push(`nonce-${this.#nonce}`);
1083
- }
1084
- }
1085
- }
1086
-
1087
- /**
1088
- * @param {boolean} [is_meta]
1089
- */
1090
- get_header(is_meta = false) {
1091
- const header = [];
1092
-
1093
- // due to browser inconsistencies, we can't append sources to default-src
1094
- // (specifically, Firefox appears to not ignore nonce-{nonce} directives
1095
- // on default-src), so we ensure that script-src and style-src exist
1096
-
1097
- const directives = { ...this.#directives };
1098
-
1099
- if (this.#style_src.length > 0) {
1100
- directives['style-src'] = [
1101
- ...(directives['style-src'] || directives['default-src'] || []),
1102
- ...this.#style_src
1103
- ];
1104
- }
1105
-
1106
- if (this.#script_src.length > 0) {
1107
- directives['script-src'] = [
1108
- ...(directives['script-src'] || directives['default-src'] || []),
1109
- ...this.#script_src
1110
- ];
1111
- }
1112
-
1113
- for (const key in directives) {
1114
- if (is_meta && (key === 'frame-ancestors' || key === 'report-uri' || key === 'sandbox')) {
1115
- // these values cannot be used with a <meta> tag
1116
- // TODO warn?
1117
- continue;
1118
- }
1119
-
1120
- // @ts-expect-error gimme a break typescript, `key` is obviously a member of internal_directives
1121
- const value = /** @type {string[] | true} */ (directives[key]);
1122
-
1123
- if (!value) continue;
1124
-
1125
- const directive = [key];
1126
- if (Array.isArray(value)) {
1127
- value.forEach((value) => {
1128
- if (quoted.has(value) || crypto_pattern.test(value)) {
1129
- directive.push(`'${value}'`);
1130
- } else {
1131
- directive.push(value);
1132
- }
1133
- });
1134
- }
1135
-
1136
- header.push(directive.join(' '));
1137
- }
1138
-
1139
- return header.join('; ');
1140
- }
1141
- }
1142
-
1143
- class CspProvider extends BaseProvider {
1144
- get_meta() {
1145
- const content = escape_html_attr(this.get_header(true));
1146
- return `<meta http-equiv="content-security-policy" content=${content}>`;
1147
- }
1148
- }
1149
-
1150
- class CspReportOnlyProvider extends BaseProvider {
1151
- /**
1152
- * @param {boolean} use_hashes
1153
- * @param {import('types').CspDirectives} directives
1154
- * @param {string} nonce
1155
- * @param {boolean} dev
1156
- */
1157
- constructor(use_hashes, directives, nonce, dev) {
1158
- super(use_hashes, directives, nonce, dev);
1159
-
1160
- if (Object.values(directives).filter((v) => !!v).length > 0) {
1161
- // If we're generating content-security-policy-report-only,
1162
- // if there are any directives, we need a report-uri or report-to (or both)
1163
- // else it's just an expensive noop.
1164
- const has_report_to = directives['report-to']?.length ?? 0 > 0;
1165
- const has_report_uri = directives['report-uri']?.length ?? 0 > 0;
1166
- if (!has_report_to && !has_report_uri) {
1167
- throw Error(
1168
- '`content-security-policy-report-only` must be specified with either the `report-to` or `report-uri` directives, or both'
1169
- );
1170
- }
1171
- }
1172
- }
1173
- }
1174
-
1175
- class Csp {
1176
- /** @readonly */
1177
- nonce = generate_nonce();
1178
-
1179
- /** @type {CspProvider} */
1180
- csp_provider;
1181
-
1182
- /** @type {CspReportOnlyProvider} */
1183
- report_only_provider;
1184
-
1185
- /**
1186
- * @param {import('./types').CspConfig} config
1187
- * @param {import('./types').CspOpts} opts
1188
- */
1189
- constructor({ mode, directives, reportOnly }, { prerender, dev }) {
1190
- const use_hashes = mode === 'hash' || (mode === 'auto' && prerender);
1191
- this.csp_provider = new CspProvider(use_hashes, directives, this.nonce, dev);
1192
- this.report_only_provider = new CspReportOnlyProvider(use_hashes, reportOnly, this.nonce, dev);
1193
- }
1194
-
1195
- get script_needs_nonce() {
1196
- return this.csp_provider.script_needs_nonce || this.report_only_provider.script_needs_nonce;
1197
- }
1198
-
1199
- get style_needs_nonce() {
1200
- return this.csp_provider.style_needs_nonce || this.report_only_provider.style_needs_nonce;
1201
- }
1202
-
1203
- /** @param {string} content */
1204
- add_script(content) {
1205
- this.csp_provider.add_script(content);
1206
- this.report_only_provider.add_script(content);
1207
- }
1208
-
1209
- /** @param {string} content */
1210
- add_style(content) {
1211
- this.csp_provider.add_style(content);
1212
- this.report_only_provider.add_style(content);
1213
- }
1214
- }
1215
-
1216
- const absolute = /^([a-z]+:)?\/?\//;
1217
- const scheme = /^[a-z]+:/;
1218
-
1219
- /**
1220
- * @param {string} base
1221
- * @param {string} path
1222
- */
1223
- function resolve(base, path) {
1224
- if (scheme.test(path)) return path;
1225
-
1226
- const base_match = absolute.exec(base);
1227
- const path_match = absolute.exec(path);
1228
-
1229
- if (!base_match) {
1230
- throw new Error(`bad base path: "${base}"`);
1231
- }
1232
-
1233
- const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
1234
- const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
1235
-
1236
- baseparts.pop();
1237
-
1238
- for (let i = 0; i < pathparts.length; i += 1) {
1239
- const part = pathparts[i];
1240
- if (part === '.') continue;
1241
- else if (part === '..') baseparts.pop();
1242
- else baseparts.push(part);
1243
- }
1244
-
1245
- const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
1246
-
1247
- return `${prefix}${baseparts.join('/')}`;
1248
- }
1249
-
1250
- /** @param {string} path */
1251
- function is_root_relative(path) {
1252
- return path[0] === '/' && path[1] !== '/';
1253
- }
1254
-
1255
- /**
1256
- * @param {string} path
1257
- * @param {import('types').TrailingSlash} trailing_slash
1258
- */
1259
- function normalize_path(path, trailing_slash) {
1260
- if (path === '/' || trailing_slash === 'ignore') return path;
1261
-
1262
- if (trailing_slash === 'never') {
1263
- return path.endsWith('/') ? path.slice(0, -1) : path;
1264
- } else if (trailing_slash === 'always' && !path.endsWith('/')) {
1265
- return path + '/';
1266
- }
1267
-
1268
- return path;
1269
- }
1270
-
1271
- /** @param {Record<string, string>} params */
1272
- function decode_params(params) {
1273
- for (const key in params) {
1274
- // input has already been decoded by decodeURI
1275
- // now handle the rest that decodeURIComponent would do
1276
- params[key] = params[key]
1277
- .replace(/%23/g, '#')
1278
- .replace(/%3[Bb]/g, ';')
1279
- .replace(/%2[Cc]/g, ',')
1280
- .replace(/%2[Ff]/g, '/')
1281
- .replace(/%3[Ff]/g, '?')
1282
- .replace(/%3[Aa]/g, ':')
1283
- .replace(/%40/g, '@')
1284
- .replace(/%26/g, '&')
1285
- .replace(/%3[Dd]/g, '=')
1286
- .replace(/%2[Bb]/g, '+')
1287
- .replace(/%24/g, '$');
1288
- }
1289
-
1290
- return params;
1291
- }
1292
-
1293
- class LoadURL extends URL {
1294
- /** @returns {string} */
1295
- get hash() {
1296
- throw new Error(
1297
- 'url.hash is inaccessible from load. Consider accessing hash from the page store within the script tag of your component.'
1298
- );
1299
- }
1300
- }
1301
-
1302
- class PrerenderingURL extends URL {
1303
- /** @returns {string} */
1304
- get search() {
1305
- throw new Error('Cannot access url.search on a page with prerendering enabled');
1306
- }
1307
-
1308
- /** @returns {URLSearchParams} */
1309
- get searchParams() {
1310
- throw new Error('Cannot access url.searchParams on a page with prerendering enabled');
1311
- }
1312
- }
1313
-
1314
- // TODO rename this function/module
1315
-
1316
- const updated = {
1317
- ...readable(false),
1318
- check: () => false
1319
- };
1320
-
1321
- /**
1322
- * Creates the HTML response.
1323
- * @param {{
1324
- * branch: Array<import('./types').Loaded>;
1325
- * options: import('types').SSROptions;
1326
- * state: import('types').SSRState;
1327
- * $session: any;
1328
- * page_config: { hydrate: boolean, router: boolean };
1329
- * status: number;
1330
- * error: Error | null;
1331
- * event: import('types').RequestEvent;
1332
- * resolve_opts: import('types').RequiredResolveOptions;
1333
- * stuff: Record<string, any>;
1334
- * }} opts
1335
- */
1336
- async function render_response({
1337
- branch,
1338
- options,
1339
- state,
1340
- $session,
1341
- page_config,
1342
- status,
1343
- error = null,
1344
- event,
1345
- resolve_opts,
1346
- stuff
1347
- }) {
1348
- if (state.prerendering) {
1349
- if (options.csp.mode === 'nonce') {
1350
- throw new Error('Cannot use prerendering if config.kit.csp.mode === "nonce"');
1351
- }
1352
-
1353
- if (options.template_contains_nonce) {
1354
- throw new Error('Cannot use prerendering if page template contains %sveltekit.nonce%');
1355
- }
1356
- }
1357
-
1358
- const { entry } = options.manifest._;
1359
-
1360
- const stylesheets = new Set(entry.stylesheets);
1361
- const modulepreloads = new Set(entry.imports);
1362
-
1363
- /** @type {Map<string, string>} */
1364
- // 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
1365
- const inline_styles = new Map();
1366
-
1367
- /** @type {Array<import('./types').Fetched>} */
1368
- const serialized_data = [];
1369
-
1370
- let shadow_props;
1371
-
1372
- let rendered;
1373
-
1374
- let is_private = false;
1375
- /** @type {import('types').NormalizedLoadOutputCache | undefined} */
1376
- let cache;
1377
-
1378
- const stack = error?.stack;
1379
-
1380
- if (options.dev && error) {
1381
- error.stack = options.get_stack(error);
1382
- }
1383
-
1384
- if (resolve_opts.ssr) {
1385
- const leaf = /** @type {import('./types.js').Loaded} */ (branch.at(-1));
1386
-
1387
- if (leaf.loaded.status) {
1388
- // explicit status returned from `load` or a page endpoint trumps
1389
- // initial status
1390
- status = leaf.loaded.status;
1391
- }
1392
-
1393
- for (const { node, props, loaded, fetched, uses_credentials } of branch) {
1394
- if (node.imports) {
1395
- node.imports.forEach((url) => modulepreloads.add(url));
1396
- }
1397
-
1398
- if (node.stylesheets) {
1399
- node.stylesheets.forEach((url) => stylesheets.add(url));
1400
- }
1401
-
1402
- if (node.inline_styles) {
1403
- Object.entries(await node.inline_styles()).forEach(([k, v]) => inline_styles.set(k, v));
1404
- }
1405
-
1406
- // TODO probably better if `fetched` wasn't populated unless `hydrate`
1407
- if (fetched && page_config.hydrate) serialized_data.push(...fetched);
1408
- if (props) shadow_props = props;
1409
-
1410
- cache = loaded?.cache;
1411
- is_private = cache?.private ?? uses_credentials;
1412
- }
1413
-
1414
- const session = writable($session);
1415
- // Even if $session isn't accessed, it still ends up serialized in the rendered HTML
1416
- is_private = is_private || (cache?.private ?? (!!$session && Object.keys($session).length > 0));
1417
-
1418
- /** @type {Record<string, any>} */
1419
- const props = {
1420
- stores: {
1421
- page: writable(null),
1422
- navigating: writable(null),
1423
- session,
1424
- updated
1425
- },
1426
- /** @type {import('types').Page} */
1427
- page: {
1428
- error,
1429
- params: event.params,
1430
- routeId: event.routeId,
1431
- status,
1432
- stuff,
1433
- url: state.prerendering ? new PrerenderingURL(event.url) : event.url
1434
- },
1435
- components: branch.map(({ node }) => node.module.default)
1436
- };
1437
-
1438
- // TODO remove this for 1.0
1439
- /**
1440
- * @param {string} property
1441
- * @param {string} replacement
1442
- */
1443
- const print_error = (property, replacement) => {
1444
- Object.defineProperty(props.page, property, {
1445
- get: () => {
1446
- throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
1447
- }
1448
- });
1449
- };
1450
-
1451
- print_error('origin', 'origin');
1452
- print_error('path', 'pathname');
1453
- print_error('query', 'searchParams');
1454
-
1455
- // props_n (instead of props[n]) makes it easy to avoid
1456
- // unnecessary updates for layout components
1457
- for (let i = 0; i < branch.length; i += 1) {
1458
- props[`props_${i}`] = await branch[i].loaded.props;
1459
- }
1460
-
1461
- rendered = options.root.render(props);
1462
- } else {
1463
- rendered = { head: '', html: '', css: { code: '', map: null } };
1464
- }
1465
-
1466
- let { head, html: body } = rendered;
1467
-
1468
- const csp = new Csp(options.csp, {
1469
- dev: options.dev,
1470
- prerender: !!state.prerendering
1471
- });
1472
-
1473
- const target = hash(body);
1474
-
1475
- // prettier-ignore
1476
- const init_app = `
1477
- import { set_public_env, start } from ${s(options.prefix + entry.file)};
1478
-
1479
- set_public_env(${s(options.public_env)});
1480
-
1481
- start({
1482
- target: document.querySelector('[data-sveltekit-hydrate="${target}"]').parentNode,
1483
- paths: ${s(options.paths)},
1484
- session: ${try_serialize($session, (error) => {
1485
- throw new Error(`Failed to serialize session data: ${error.message}`);
1486
- })},
1487
- route: ${!!page_config.router},
1488
- spa: ${!resolve_opts.ssr},
1489
- trailing_slash: ${s(options.trailing_slash)},
1490
- hydrate: ${resolve_opts.ssr && page_config.hydrate ? `{
1491
- status: ${status},
1492
- error: ${error && serialize_error(error, e => e.stack)},
1493
- nodes: [${branch.map(({ node }) => node.index).join(', ')}],
1494
- params: ${devalue(event.params)},
1495
- routeId: ${s(event.routeId)}
1496
- }` : 'null'}
1497
- });
1498
- `;
1499
-
1500
- // we use an anonymous function instead of an arrow function to support
1501
- // older browsers (https://github.com/sveltejs/kit/pull/5417)
1502
- const init_service_worker = `
1503
- if ('serviceWorker' in navigator) {
1504
- addEventListener('load', function () {
1505
- navigator.serviceWorker.register('${options.service_worker}');
1506
- });
1507
- }
1508
- `;
1509
-
1510
- if (inline_styles.size > 0) {
1511
- const content = Array.from(inline_styles.values()).join('\n');
1512
-
1513
- const attributes = [];
1514
- if (options.dev) attributes.push(' data-sveltekit');
1515
- if (csp.style_needs_nonce) attributes.push(` nonce="${csp.nonce}"`);
1516
-
1517
- csp.add_style(content);
1518
-
1519
- head += `\n\t<style${attributes.join('')}>${content}</style>`;
1520
- }
1521
-
1522
- // prettier-ignore
1523
- head += Array.from(stylesheets)
1524
- .map((dep) => {
1525
- const attributes = [
1526
- 'rel="stylesheet"',
1527
- `href="${options.prefix + dep}"`
1528
- ];
1529
-
1530
- if (csp.style_needs_nonce) {
1531
- attributes.push(`nonce="${csp.nonce}"`);
1532
- }
1533
-
1534
- if (inline_styles.has(dep)) {
1535
- // don't load stylesheets that are already inlined
1536
- // include them in disabled state so that Vite can detect them and doesn't try to add them
1537
- attributes.push('disabled', 'media="(max-width: 0)"');
1538
- }
1539
-
1540
- return `\n\t<link ${attributes.join(' ')}>`;
1541
- })
1542
- .join('');
1543
-
1544
- if (page_config.router || page_config.hydrate) {
1545
- head += Array.from(modulepreloads)
1546
- .map((dep) => `\n\t<link rel="modulepreload" href="${options.prefix + dep}">`)
1547
- .join('');
1548
-
1549
- const attributes = ['type="module"', `data-sveltekit-hydrate="${target}"`];
1550
-
1551
- csp.add_script(init_app);
1552
-
1553
- if (csp.script_needs_nonce) {
1554
- attributes.push(`nonce="${csp.nonce}"`);
1555
- }
1556
-
1557
- body += `\n\t\t<script ${attributes.join(' ')}>${init_app}</script>`;
1558
-
1559
- body += serialized_data
1560
- .map(({ url, body, response }) =>
1561
- render_json_payload_script(
1562
- { type: 'data', url, body: typeof body === 'string' ? hash(body) : undefined },
1563
- response
1564
- )
1565
- )
1566
- .join('\n\t');
1567
-
1568
- if (shadow_props) {
1569
- body += render_json_payload_script({ type: 'props' }, shadow_props);
1570
- }
1571
- }
1572
-
1573
- if (options.service_worker) {
1574
- // always include service worker unless it's turned off explicitly
1575
- csp.add_script(init_service_worker);
1576
-
1577
- head += `
1578
- <script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ''}>${init_service_worker}</script>`;
1579
- }
1580
-
1581
- if (state.prerendering) {
1582
- const http_equiv = [];
1583
-
1584
- const csp_headers = csp.csp_provider.get_meta();
1585
- if (csp_headers) {
1586
- http_equiv.push(csp_headers);
1587
- }
1588
-
1589
- if (cache) {
1590
- http_equiv.push(`<meta http-equiv="cache-control" content="max-age=${cache.maxage}">`);
1591
- }
1592
-
1593
- if (http_equiv.length > 0) {
1594
- head = http_equiv.join('\n') + head;
1595
- }
1596
- }
1597
-
1598
- const segments = event.url.pathname.slice(options.paths.base.length).split('/').slice(2);
1599
- const assets =
1600
- options.paths.assets || (segments.length > 0 ? segments.map(() => '..').join('/') : '.');
1601
-
1602
- // TODO flush chunks as early as we can
1603
- const html =
1604
- (await resolve_opts.transformPageChunk({
1605
- html: options.template({ head, body, assets, nonce: /** @type {string} */ (csp.nonce) }),
1606
- done: true
1607
- })) || '';
1608
-
1609
- const headers = new Headers({
1610
- 'content-type': 'text/html',
1611
- etag: `"${hash(html)}"`
1612
- });
1613
-
1614
- if (cache) {
1615
- headers.set('cache-control', `${is_private ? 'private' : 'public'}, max-age=${cache.maxage}`);
1616
- }
1617
-
1618
- if (!state.prerendering) {
1619
- const csp_header = csp.csp_provider.get_header();
1620
- if (csp_header) {
1621
- headers.set('content-security-policy', csp_header);
1622
- }
1623
- const report_only_header = csp.report_only_provider.get_header();
1624
- if (report_only_header) {
1625
- headers.set('content-security-policy-report-only', report_only_header);
1626
- }
1627
- }
1628
-
1629
- if (options.dev && error) {
1630
- // reset stack, otherwise it may be 'fixed' a second time
1631
- error.stack = stack;
1632
- }
1633
-
1634
- return new Response(html, {
1635
- status,
1636
- headers
1637
- });
1638
- }
1639
-
1640
- /**
1641
- * @param {any} data
1642
- * @param {(error: Error) => void} [fail]
1643
- */
1644
- function try_serialize(data, fail) {
1645
- try {
1646
- return devalue(data);
1647
- } catch (err) {
1648
- if (fail) fail(coalesce_to_error(err));
1649
- return null;
1650
- }
1651
- }
1652
-
1653
- /*!
1654
- * cookie
1655
- * Copyright(c) 2012-2014 Roman Shtylman
1656
- * Copyright(c) 2015 Douglas Christopher Wilson
1657
- * MIT Licensed
1658
- */
1659
-
1660
- /**
1661
- * Module exports.
1662
- * @public
1663
- */
1664
-
1665
- var parse_1 = parse$1;
1666
- var serialize_1 = serialize;
1667
-
1668
- /**
1669
- * Module variables.
1670
- * @private
1671
- */
1672
-
1673
- var __toString = Object.prototype.toString;
1674
-
1675
- /**
1676
- * RegExp to match field-content in RFC 7230 sec 3.2
1677
- *
1678
- * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
1679
- * field-vchar = VCHAR / obs-text
1680
- * obs-text = %x80-FF
1681
- */
1682
-
1683
- var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
1684
-
1685
- /**
1686
- * Parse a cookie header.
1687
- *
1688
- * Parse the given cookie header string into an object
1689
- * The object has the various cookies as keys(names) => values
1690
- *
1691
- * @param {string} str
1692
- * @param {object} [options]
1693
- * @return {object}
1694
- * @public
1695
- */
1696
-
1697
- function parse$1(str, options) {
1698
- if (typeof str !== 'string') {
1699
- throw new TypeError('argument str must be a string');
1700
- }
1701
-
1702
- var obj = {};
1703
- var opt = options || {};
1704
- var dec = opt.decode || decode;
1705
-
1706
- var index = 0;
1707
- while (index < str.length) {
1708
- var eqIdx = str.indexOf('=', index);
1709
-
1710
- // no more cookie pairs
1711
- if (eqIdx === -1) {
1712
- break
1713
- }
1714
-
1715
- var endIdx = str.indexOf(';', index);
1716
-
1717
- if (endIdx === -1) {
1718
- endIdx = str.length;
1719
- } else if (endIdx < eqIdx) {
1720
- // backtrack on prior semicolon
1721
- index = str.lastIndexOf(';', eqIdx - 1) + 1;
1722
- continue
1723
- }
1724
-
1725
- var key = str.slice(index, eqIdx).trim();
1726
-
1727
- // only assign once
1728
- if (undefined === obj[key]) {
1729
- var val = str.slice(eqIdx + 1, endIdx).trim();
1730
-
1731
- // quoted values
1732
- if (val.charCodeAt(0) === 0x22) {
1733
- val = val.slice(1, -1);
1734
- }
1735
-
1736
- obj[key] = tryDecode(val, dec);
1737
- }
1738
-
1739
- index = endIdx + 1;
1740
- }
1741
-
1742
- return obj;
1743
- }
1744
-
1745
- /**
1746
- * Serialize data into a cookie header.
1747
- *
1748
- * Serialize the a name value pair into a cookie string suitable for
1749
- * http headers. An optional options object specified cookie parameters.
1750
- *
1751
- * serialize('foo', 'bar', { httpOnly: true })
1752
- * => "foo=bar; httpOnly"
1753
- *
1754
- * @param {string} name
1755
- * @param {string} val
1756
- * @param {object} [options]
1757
- * @return {string}
1758
- * @public
1759
- */
1760
-
1761
- function serialize(name, val, options) {
1762
- var opt = options || {};
1763
- var enc = opt.encode || encode;
1764
-
1765
- if (typeof enc !== 'function') {
1766
- throw new TypeError('option encode is invalid');
1767
- }
1768
-
1769
- if (!fieldContentRegExp.test(name)) {
1770
- throw new TypeError('argument name is invalid');
1771
- }
1772
-
1773
- var value = enc(val);
1774
-
1775
- if (value && !fieldContentRegExp.test(value)) {
1776
- throw new TypeError('argument val is invalid');
1777
- }
1778
-
1779
- var str = name + '=' + value;
1780
-
1781
- if (null != opt.maxAge) {
1782
- var maxAge = opt.maxAge - 0;
1783
-
1784
- if (isNaN(maxAge) || !isFinite(maxAge)) {
1785
- throw new TypeError('option maxAge is invalid')
1786
- }
1787
-
1788
- str += '; Max-Age=' + Math.floor(maxAge);
1789
- }
1790
-
1791
- if (opt.domain) {
1792
- if (!fieldContentRegExp.test(opt.domain)) {
1793
- throw new TypeError('option domain is invalid');
1794
- }
1795
-
1796
- str += '; Domain=' + opt.domain;
1797
- }
1798
-
1799
- if (opt.path) {
1800
- if (!fieldContentRegExp.test(opt.path)) {
1801
- throw new TypeError('option path is invalid');
1802
- }
1803
-
1804
- str += '; Path=' + opt.path;
1805
- }
1806
-
1807
- if (opt.expires) {
1808
- var expires = opt.expires;
1809
-
1810
- if (!isDate(expires) || isNaN(expires.valueOf())) {
1811
- throw new TypeError('option expires is invalid');
1812
- }
1813
-
1814
- str += '; Expires=' + expires.toUTCString();
1815
- }
1816
-
1817
- if (opt.httpOnly) {
1818
- str += '; HttpOnly';
1819
- }
1820
-
1821
- if (opt.secure) {
1822
- str += '; Secure';
1823
- }
1824
-
1825
- if (opt.priority) {
1826
- var priority = typeof opt.priority === 'string'
1827
- ? opt.priority.toLowerCase()
1828
- : opt.priority;
1829
-
1830
- switch (priority) {
1831
- case 'low':
1832
- str += '; Priority=Low';
1833
- break
1834
- case 'medium':
1835
- str += '; Priority=Medium';
1836
- break
1837
- case 'high':
1838
- str += '; Priority=High';
1839
- break
1840
- default:
1841
- throw new TypeError('option priority is invalid')
1842
- }
1843
- }
1844
-
1845
- if (opt.sameSite) {
1846
- var sameSite = typeof opt.sameSite === 'string'
1847
- ? opt.sameSite.toLowerCase() : opt.sameSite;
1848
-
1849
- switch (sameSite) {
1850
- case true:
1851
- str += '; SameSite=Strict';
1852
- break;
1853
- case 'lax':
1854
- str += '; SameSite=Lax';
1855
- break;
1856
- case 'strict':
1857
- str += '; SameSite=Strict';
1858
- break;
1859
- case 'none':
1860
- str += '; SameSite=None';
1861
- break;
1862
- default:
1863
- throw new TypeError('option sameSite is invalid');
1864
- }
1865
- }
1866
-
1867
- return str;
1868
- }
1869
-
1870
- /**
1871
- * URL-decode string value. Optimized to skip native call when no %.
1872
- *
1873
- * @param {string} str
1874
- * @returns {string}
1875
- */
1876
-
1877
- function decode (str) {
1878
- return str.indexOf('%') !== -1
1879
- ? decodeURIComponent(str)
1880
- : str
1881
- }
1882
-
1883
- /**
1884
- * URL-encode value.
1885
- *
1886
- * @param {string} str
1887
- * @returns {string}
1888
- */
1889
-
1890
- function encode (val) {
1891
- return encodeURIComponent(val)
1892
- }
1893
-
1894
- /**
1895
- * Determine if value is a Date.
1896
- *
1897
- * @param {*} val
1898
- * @private
1899
- */
1900
-
1901
- function isDate (val) {
1902
- return __toString.call(val) === '[object Date]' ||
1903
- val instanceof Date
1904
- }
1905
-
1906
- /**
1907
- * Try decoding a string using a decoding function.
1908
- *
1909
- * @param {string} str
1910
- * @param {function} decode
1911
- * @private
1912
- */
1913
-
1914
- function tryDecode(str, decode) {
1915
- try {
1916
- return decode(str);
1917
- } catch (e) {
1918
- return str;
1919
- }
1920
- }
1921
-
1922
- var setCookie = {exports: {}};
1923
-
1924
- var defaultParseOptions = {
1925
- decodeValues: true,
1926
- map: false,
1927
- silent: false,
1928
- };
1929
-
1930
- function isNonEmptyString(str) {
1931
- return typeof str === "string" && !!str.trim();
1932
- }
1933
-
1934
- function parseString(setCookieValue, options) {
1935
- var parts = setCookieValue.split(";").filter(isNonEmptyString);
1936
- var nameValue = parts.shift().split("=");
1937
- var name = nameValue.shift();
1938
- var value = nameValue.join("="); // everything after the first =, joined by a "=" if there was more than one part
1939
-
1940
- options = options
1941
- ? Object.assign({}, defaultParseOptions, options)
1942
- : defaultParseOptions;
1943
-
1944
- try {
1945
- value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value
1946
- } catch (e) {
1947
- console.error(
1948
- "set-cookie-parser encountered an error while decoding a cookie with value '" +
1949
- value +
1950
- "'. Set options.decodeValues to false to disable this feature.",
1951
- e
1952
- );
1953
- }
1954
-
1955
- var cookie = {
1956
- name: name, // grab everything before the first =
1957
- value: value,
1958
- };
1959
-
1960
- parts.forEach(function (part) {
1961
- var sides = part.split("=");
1962
- var key = sides.shift().trimLeft().toLowerCase();
1963
- var value = sides.join("=");
1964
- if (key === "expires") {
1965
- cookie.expires = new Date(value);
1966
- } else if (key === "max-age") {
1967
- cookie.maxAge = parseInt(value, 10);
1968
- } else if (key === "secure") {
1969
- cookie.secure = true;
1970
- } else if (key === "httponly") {
1971
- cookie.httpOnly = true;
1972
- } else if (key === "samesite") {
1973
- cookie.sameSite = value;
1974
- } else {
1975
- cookie[key] = value;
1976
- }
1977
- });
1978
-
1979
- return cookie;
1980
- }
1981
-
1982
- function parse(input, options) {
1983
- options = options
1984
- ? Object.assign({}, defaultParseOptions, options)
1985
- : defaultParseOptions;
1986
-
1987
- if (!input) {
1988
- if (!options.map) {
1989
- return [];
1990
- } else {
1991
- return {};
1992
- }
1993
- }
1994
-
1995
- if (input.headers && input.headers["set-cookie"]) {
1996
- // fast-path for node.js (which automatically normalizes header names to lower-case
1997
- input = input.headers["set-cookie"];
1998
- } else if (input.headers) {
1999
- // slow-path for other environments - see #25
2000
- var sch =
2001
- input.headers[
2002
- Object.keys(input.headers).find(function (key) {
2003
- return key.toLowerCase() === "set-cookie";
2004
- })
2005
- ];
2006
- // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36
2007
- if (!sch && input.headers.cookie && !options.silent) {
2008
- console.warn(
2009
- "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
2010
- );
2011
- }
2012
- input = sch;
2013
- }
2014
- if (!Array.isArray(input)) {
2015
- input = [input];
2016
- }
2017
-
2018
- options = options
2019
- ? Object.assign({}, defaultParseOptions, options)
2020
- : defaultParseOptions;
2021
-
2022
- if (!options.map) {
2023
- return input.filter(isNonEmptyString).map(function (str) {
2024
- return parseString(str, options);
2025
- });
2026
- } else {
2027
- var cookies = {};
2028
- return input.filter(isNonEmptyString).reduce(function (cookies, str) {
2029
- var cookie = parseString(str, options);
2030
- cookies[cookie.name] = cookie;
2031
- return cookies;
2032
- }, cookies);
2033
- }
2034
- }
2035
-
2036
- /*
2037
- Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
2038
- that are within a single set-cookie field-value, such as in the Expires portion.
2039
-
2040
- This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
2041
- Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
2042
- React Native's fetch does this for *every* header, including set-cookie.
2043
-
2044
- Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
2045
- Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
2046
- */
2047
- function splitCookiesString(cookiesString) {
2048
- if (Array.isArray(cookiesString)) {
2049
- return cookiesString;
2050
- }
2051
- if (typeof cookiesString !== "string") {
2052
- return [];
2053
- }
2054
-
2055
- var cookiesStrings = [];
2056
- var pos = 0;
2057
- var start;
2058
- var ch;
2059
- var lastComma;
2060
- var nextStart;
2061
- var cookiesSeparatorFound;
2062
-
2063
- function skipWhitespace() {
2064
- while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
2065
- pos += 1;
2066
- }
2067
- return pos < cookiesString.length;
2068
- }
2069
-
2070
- function notSpecialChar() {
2071
- ch = cookiesString.charAt(pos);
2072
-
2073
- return ch !== "=" && ch !== ";" && ch !== ",";
2074
- }
2075
-
2076
- while (pos < cookiesString.length) {
2077
- start = pos;
2078
- cookiesSeparatorFound = false;
2079
-
2080
- while (skipWhitespace()) {
2081
- ch = cookiesString.charAt(pos);
2082
- if (ch === ",") {
2083
- // ',' is a cookie separator if we have later first '=', not ';' or ','
2084
- lastComma = pos;
2085
- pos += 1;
2086
-
2087
- skipWhitespace();
2088
- nextStart = pos;
2089
-
2090
- while (pos < cookiesString.length && notSpecialChar()) {
2091
- pos += 1;
2092
- }
2093
-
2094
- // currently special character
2095
- if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
2096
- // we found cookies separator
2097
- cookiesSeparatorFound = true;
2098
- // pos is inside the next cookie, so back up and return it.
2099
- pos = nextStart;
2100
- cookiesStrings.push(cookiesString.substring(start, lastComma));
2101
- start = pos;
2102
- } else {
2103
- // in param ',' or param separator ';',
2104
- // we continue from that comma
2105
- pos = lastComma + 1;
2106
- }
2107
- } else {
2108
- pos += 1;
2109
- }
2110
- }
2111
-
2112
- if (!cookiesSeparatorFound || pos >= cookiesString.length) {
2113
- cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
2114
- }
2115
- }
2116
-
2117
- return cookiesStrings;
2118
- }
2119
-
2120
- setCookie.exports = parse;
2121
- setCookie.exports.parse = parse;
2122
- var parseString_1 = setCookie.exports.parseString = parseString;
2123
- var splitCookiesString_1 = setCookie.exports.splitCookiesString = splitCookiesString;
2124
-
2125
- /**
2126
- * @param {import('types').LoadOutput | void} loaded
2127
- * @returns {import('types').NormalizedLoadOutput}
2128
- */
2129
- function normalize(loaded) {
2130
- if (!loaded) {
2131
- return {};
2132
- }
2133
-
2134
- // TODO remove for 1.0
2135
- // @ts-expect-error
2136
- if (loaded.fallthrough) {
2137
- throw new Error(
2138
- 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
2139
- );
2140
- }
2141
-
2142
- // TODO remove for 1.0
2143
- if ('maxage' in loaded) {
2144
- throw new Error('maxage should be replaced with cache: { maxage }');
2145
- }
2146
-
2147
- const has_error_status =
2148
- loaded.status && loaded.status >= 400 && loaded.status <= 599 && !loaded.redirect;
2149
- if (loaded.error || has_error_status) {
2150
- const status = loaded.status;
2151
-
2152
- if (!loaded.error && has_error_status) {
2153
- return {
2154
- status: status || 500,
2155
- error: new Error(`${status}`)
2156
- };
2157
- }
2158
-
2159
- const error = typeof loaded.error === 'string' ? new Error(loaded.error) : loaded.error;
2160
-
2161
- if (!(error instanceof Error)) {
2162
- return {
2163
- status: 500,
2164
- error: new Error(
2165
- `"error" property returned from load() must be a string or instance of Error, received type "${typeof error}"`
2166
- )
2167
- };
2168
- }
2169
-
2170
- if (!status || status < 400 || status > 599) {
2171
- console.warn('"error" returned from load() without a valid status code — defaulting to 500');
2172
- return { status: 500, error };
2173
- }
2174
-
2175
- return { status, error };
2176
- }
2177
-
2178
- if (loaded.redirect) {
2179
- if (!loaded.status || Math.floor(loaded.status / 100) !== 3) {
2180
- throw new Error(
2181
- '"redirect" property returned from load() must be accompanied by a 3xx status code'
2182
- );
2183
- }
2184
-
2185
- if (typeof loaded.redirect !== 'string') {
2186
- throw new Error('"redirect" property returned from load() must be a string');
2187
- }
2188
- }
2189
-
2190
- if (loaded.dependencies) {
2191
- if (
2192
- !Array.isArray(loaded.dependencies) ||
2193
- loaded.dependencies.some((dep) => typeof dep !== 'string')
2194
- ) {
2195
- throw new Error('"dependencies" property returned from load() must be of type string[]');
2196
- }
2197
- }
2198
-
2199
- // TODO remove before 1.0
2200
- if (/** @type {any} */ (loaded).context) {
2201
- throw new Error(
2202
- 'You are returning "context" from a load function. ' +
2203
- '"context" was renamed to "stuff", please adjust your code accordingly.'
2204
- );
2205
- }
2206
-
2207
- return /** @type {import('types').NormalizedLoadOutput} */ (loaded);
2208
- }
2209
-
2210
- /**
2211
- * @param {string} hostname
2212
- * @param {string} [constraint]
2213
- */
2214
- function domain_matches(hostname, constraint) {
2215
- if (!constraint) return true;
2216
-
2217
- const normalized = constraint[0] === '.' ? constraint.slice(1) : constraint;
2218
-
2219
- if (hostname === normalized) return true;
2220
- return hostname.endsWith('.' + normalized);
2221
- }
2222
-
2223
- /**
2224
- * @param {string} path
2225
- * @param {string} [constraint]
2226
- */
2227
- function path_matches(path, constraint) {
2228
- if (!constraint) return true;
2229
-
2230
- const normalized = constraint.endsWith('/') ? constraint.slice(0, -1) : constraint;
2231
-
2232
- if (path === normalized) return true;
2233
- return path.startsWith(normalized + '/');
2234
- }
2235
-
2236
- /**
2237
- * Calls the user's `load` function.
2238
- * @param {{
2239
- * event: import('types').RequestEvent;
2240
- * options: import('types').SSROptions;
2241
- * state: import('types').SSRState;
2242
- * route: import('types').SSRPage | import('types').SSRErrorPage;
2243
- * node: import('types').SSRNode;
2244
- * $session: any;
2245
- * stuff: Record<string, any>;
2246
- * is_error: boolean;
2247
- * is_leaf: boolean;
2248
- * status?: number;
2249
- * error?: Error;
2250
- * }} opts
2251
- * @returns {Promise<import('./types').Loaded>}
2252
- */
2253
- async function load_node({
2254
- event,
2255
- options,
2256
- state,
2257
- route,
2258
- node,
2259
- $session,
2260
- stuff,
2261
- is_error,
2262
- is_leaf,
2263
- status,
2264
- error
2265
- }) {
2266
- const { module } = node;
2267
-
2268
- let uses_credentials = false;
2269
-
2270
- /** @type {Array<import('./types').Fetched>} */
2271
- const fetched = [];
2272
-
2273
- const cookies = parse_1(event.request.headers.get('cookie') || '');
2274
-
2275
- /** @type {import('set-cookie-parser').Cookie[]} */
2276
- const new_cookies = [];
2277
-
2278
- /** @type {import('types').NormalizedLoadOutput} */
2279
- let loaded;
2280
-
2281
- const should_prerender = node.module.prerender ?? options.prerender.default;
2282
-
2283
- /** @type {import('types').ShadowData} */
2284
- const shadow = is_leaf
2285
- ? await load_shadow_data(
2286
- /** @type {import('types').SSRPage} */ (route),
2287
- event,
2288
- options,
2289
- should_prerender
2290
- )
2291
- : {};
2292
-
2293
- if (shadow.cookies) {
2294
- shadow.cookies.forEach((header) => {
2295
- new_cookies.push(parseString_1(header));
2296
- });
2297
- }
2298
-
2299
- if (shadow.error) {
2300
- loaded = {
2301
- error: shadow.error
2302
- };
2303
- } else if (shadow.redirect) {
2304
- loaded = {
2305
- redirect: shadow.redirect
2306
- };
2307
- } else if (module.load) {
2308
- /** @type {import('types').LoadEvent} */
2309
- const load_input = {
2310
- url: state.prerendering ? new PrerenderingURL(event.url) : new LoadURL(event.url),
2311
- params: event.params,
2312
- props: shadow.body || {},
2313
- routeId: event.routeId,
2314
- get session() {
2315
- if (node.module.prerender ?? options.prerender.default) {
2316
- throw Error(
2317
- 'Attempted to access session from a prerendered page. Session would never be populated.'
2318
- );
2319
- }
2320
- uses_credentials = true;
2321
- return $session;
2322
- },
2323
- /**
2324
- * @param {RequestInfo} resource
2325
- * @param {RequestInit} opts
2326
- */
2327
- fetch: async (resource, opts = {}) => {
2328
- /** @type {string} */
2329
- let requested;
2330
-
2331
- if (typeof resource === 'string') {
2332
- requested = resource;
2333
- } else {
2334
- requested = resource.url;
2335
-
2336
- opts = {
2337
- method: resource.method,
2338
- headers: resource.headers,
2339
- body: resource.body,
2340
- mode: resource.mode,
2341
- credentials: resource.credentials,
2342
- cache: resource.cache,
2343
- redirect: resource.redirect,
2344
- referrer: resource.referrer,
2345
- integrity: resource.integrity,
2346
- ...opts
2347
- };
2348
- }
2349
-
2350
- opts.headers = new Headers(opts.headers);
2351
-
2352
- // merge headers from request
2353
- for (const [key, value] of event.request.headers) {
2354
- if (
2355
- key !== 'authorization' &&
2356
- key !== 'connection' &&
2357
- key !== 'cookie' &&
2358
- key !== 'host' &&
2359
- key !== 'if-none-match' &&
2360
- !opts.headers.has(key)
2361
- ) {
2362
- opts.headers.set(key, value);
2363
- }
2364
- }
2365
-
2366
- const resolved = resolve(event.url.pathname, requested.split('?')[0]);
2367
-
2368
- /** @type {Response} */
2369
- let response;
2370
-
2371
- /** @type {import('types').PrerenderDependency} */
2372
- let dependency;
2373
-
2374
- // handle fetch requests for static assets. e.g. prebaked data, etc.
2375
- // we need to support everything the browser's fetch supports
2376
- const prefix = options.paths.assets || options.paths.base;
2377
- const filename = decodeURIComponent(
2378
- resolved.startsWith(prefix) ? resolved.slice(prefix.length) : resolved
2379
- ).slice(1);
2380
- const filename_html = `${filename}/index.html`; // path may also match path/index.html
2381
-
2382
- const is_asset = options.manifest.assets.has(filename);
2383
- const is_asset_html = options.manifest.assets.has(filename_html);
2384
-
2385
- if (is_asset || is_asset_html) {
2386
- const file = is_asset ? filename : filename_html;
2387
-
2388
- if (options.read) {
2389
- const type = is_asset
2390
- ? options.manifest.mimeTypes[filename.slice(filename.lastIndexOf('.'))]
2391
- : 'text/html';
2392
-
2393
- response = new Response(options.read(file), {
2394
- headers: type ? { 'content-type': type } : {}
2395
- });
2396
- } else {
2397
- response = await fetch(
2398
- `${event.url.origin}/${file}`,
2399
- /** @type {RequestInit} */ (opts)
2400
- );
2401
- }
2402
- } else if (is_root_relative(resolved)) {
2403
- if (opts.credentials !== 'omit') {
2404
- uses_credentials = true;
2405
-
2406
- const authorization = event.request.headers.get('authorization');
2407
-
2408
- // combine cookies from the initiating request with any that were
2409
- // added via set-cookie
2410
- const combined_cookies = { ...cookies };
2411
-
2412
- for (const cookie of new_cookies) {
2413
- if (!domain_matches(event.url.hostname, cookie.domain)) continue;
2414
- if (!path_matches(resolved, cookie.path)) continue;
2415
-
2416
- combined_cookies[cookie.name] = cookie.value;
2417
- }
2418
-
2419
- const cookie = Object.entries(combined_cookies)
2420
- .map(([name, value]) => `${name}=${value}`)
2421
- .join('; ');
2422
-
2423
- if (cookie) {
2424
- opts.headers.set('cookie', cookie);
2425
- }
2426
-
2427
- if (authorization && !opts.headers.has('authorization')) {
2428
- opts.headers.set('authorization', authorization);
2429
- }
2430
- }
2431
-
2432
- if (opts.body && typeof opts.body !== 'string') {
2433
- // per https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, this can be a
2434
- // Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object.
2435
- // non-string bodies are irksome to deal with, but luckily aren't particularly useful
2436
- // in this context anyway, so we take the easy route and ban them
2437
- throw new Error('Request body must be a string');
2438
- }
2439
-
2440
- response = await respond(
2441
- new Request(new URL(requested, event.url).href, { ...opts }),
2442
- options,
2443
- {
2444
- ...state,
2445
- initiator: route
2446
- }
2447
- );
2448
-
2449
- if (state.prerendering) {
2450
- dependency = { response, body: null };
2451
- state.prerendering.dependencies.set(resolved, dependency);
2452
- }
2453
- } else {
2454
- // external
2455
- if (resolved.startsWith('//')) {
2456
- requested = event.url.protocol + requested;
2457
- }
2458
-
2459
- // external fetch
2460
- // allow cookie passthrough for "same-origin"
2461
- // if SvelteKit is serving my.domain.com:
2462
- // - domain.com WILL NOT receive cookies
2463
- // - my.domain.com WILL receive cookies
2464
- // - api.domain.dom WILL NOT receive cookies
2465
- // - sub.my.domain.com WILL receive cookies
2466
- // ports do not affect the resolution
2467
- // leading dot prevents mydomain.com matching domain.com
2468
- if (
2469
- `.${new URL(requested).hostname}`.endsWith(`.${event.url.hostname}`) &&
2470
- opts.credentials !== 'omit'
2471
- ) {
2472
- uses_credentials = true;
2473
-
2474
- const cookie = event.request.headers.get('cookie');
2475
- if (cookie) opts.headers.set('cookie', cookie);
2476
- }
2477
-
2478
- // we need to delete the connection header, as explained here:
2479
- // https://github.com/nodejs/undici/issues/1470#issuecomment-1140798467
2480
- // TODO this may be a case for being selective about which headers we let through
2481
- opts.headers.delete('connection');
2482
-
2483
- const external_request = new Request(requested, /** @type {RequestInit} */ (opts));
2484
- response = await options.hooks.externalFetch.call(null, external_request);
2485
- }
2486
-
2487
- const set_cookie = response.headers.get('set-cookie');
2488
- if (set_cookie) {
2489
- new_cookies.push(
2490
- ...splitCookiesString_1(set_cookie)
2491
- .map((str) => parseString_1(str))
2492
- );
2493
- }
2494
-
2495
- const proxy = new Proxy(response, {
2496
- get(response, key, _receiver) {
2497
- async function text() {
2498
- const body = await response.text();
2499
-
2500
- /** @type {import('types').ResponseHeaders} */
2501
- const headers = {};
2502
- for (const [key, value] of response.headers) {
2503
- // TODO skip others besides set-cookie and etag?
2504
- if (key !== 'set-cookie' && key !== 'etag') {
2505
- headers[key] = value;
2506
- }
2507
- }
2508
-
2509
- if (!opts.body || typeof opts.body === 'string') {
2510
- const status_number = Number(response.status);
2511
- if (isNaN(status_number)) {
2512
- throw new Error(
2513
- `response.status is not a number. value: "${
2514
- response.status
2515
- }" type: ${typeof response.status}`
2516
- );
2517
- }
2518
-
2519
- fetched.push({
2520
- url: requested,
2521
- body: opts.body,
2522
- response: {
2523
- status: status_number,
2524
- statusText: response.statusText,
2525
- headers,
2526
- body
2527
- }
2528
- });
2529
- }
2530
-
2531
- if (dependency) {
2532
- dependency.body = body;
2533
- }
2534
-
2535
- return body;
2536
- }
2537
-
2538
- if (key === 'arrayBuffer') {
2539
- return async () => {
2540
- const buffer = await response.arrayBuffer();
2541
-
2542
- if (dependency) {
2543
- dependency.body = new Uint8Array(buffer);
2544
- }
2545
-
2546
- // TODO should buffer be inlined into the page (albeit base64'd)?
2547
- // any conditions in which it shouldn't be?
2548
-
2549
- return buffer;
2550
- };
2551
- }
2552
-
2553
- if (key === 'text') {
2554
- return text;
2555
- }
2556
-
2557
- if (key === 'json') {
2558
- return async () => {
2559
- return JSON.parse(await text());
2560
- };
2561
- }
2562
-
2563
- // TODO arrayBuffer?
2564
-
2565
- return Reflect.get(response, key, response);
2566
- }
2567
- });
2568
-
2569
- return proxy;
2570
- },
2571
- stuff: { ...stuff },
2572
- status: (is_error ? status : shadow.status) ?? null,
2573
- error: is_error ? error ?? null : null
2574
- };
2575
-
2576
- if (options.dev) {
2577
- // TODO remove this for 1.0
2578
- Object.defineProperty(load_input, 'page', {
2579
- get: () => {
2580
- throw new Error('`page` in `load` functions has been replaced by `url` and `params`');
2581
- }
2582
- });
2583
- }
2584
-
2585
- loaded = normalize(await module.load.call(null, load_input));
2586
- } else if (shadow.body) {
2587
- loaded = {
2588
- props: shadow.body
2589
- };
2590
- } else {
2591
- loaded = {};
2592
- }
2593
-
2594
- loaded.status = loaded.status ?? shadow.status;
2595
-
2596
- // generate __data.json files when prerendering
2597
- if (shadow.body && state.prerendering) {
2598
- const pathname = `${event.url.pathname.replace(/\/$/, '')}/__data.json`;
2599
-
2600
- const dependency = {
2601
- response: new Response(undefined),
2602
- body: JSON.stringify(shadow.body)
2603
- };
2604
-
2605
- state.prerendering.dependencies.set(pathname, dependency);
2606
- }
2607
-
2608
- return {
2609
- node,
2610
- props: shadow.body,
2611
- loaded,
2612
- stuff: loaded.stuff || stuff,
2613
- fetched,
2614
- set_cookie_headers: new_cookies.map((new_cookie) => {
2615
- const { name, value, ...options } = new_cookie;
2616
- // @ts-expect-error
2617
- return serialize_1(name, value, options);
2618
- }),
2619
- uses_credentials
2620
- };
2621
- }
2622
-
2623
- /**
2624
- *
2625
- * @param {import('types').SSRPage} route
2626
- * @param {import('types').RequestEvent} event
2627
- * @param {import('types').SSROptions} options
2628
- * @param {boolean} prerender
2629
- * @returns {Promise<import('types').ShadowData>}
2630
- */
2631
- async function load_shadow_data(route, event, options, prerender) {
2632
- if (!route.shadow) return {};
2633
-
2634
- try {
2635
- const mod = await route.shadow();
2636
-
2637
- check_method_names(mod);
2638
-
2639
- if (prerender && (mod.POST || mod.PUT || mod.DELETE || mod.PATCH)) {
2640
- throw new Error('Cannot prerender pages that have endpoints with mutative methods');
2641
- }
2642
-
2643
- const { method } = event.request;
2644
- const is_get = method === 'HEAD' || method === 'GET';
2645
- const handler = method === 'HEAD' ? mod.HEAD || mod.GET : mod[method];
2646
-
2647
- if (!handler && !is_get) {
2648
- return {
2649
- status: 405,
2650
- error: new Error(`${method} method not allowed`)
2651
- };
2652
- }
2653
-
2654
- /** @type {import('types').ShadowData} */
2655
- const data = {
2656
- status: undefined,
2657
- cookies: [],
2658
- body: {}
2659
- };
2660
-
2661
- if (!is_get) {
2662
- const { status, headers, body } = validate_shadow_output(await handler(event));
2663
- add_cookies(/** @type {string[]} */ (data.cookies), headers);
2664
- data.status = status;
2665
-
2666
- // explicit errors cause an error page...
2667
- if (body instanceof Error) {
2668
- if (status < 400) {
2669
- data.status = 500;
2670
- data.error = new Error('A non-error status code was returned with an error body');
2671
- } else {
2672
- data.error = body;
2673
- }
2674
-
2675
- return data;
2676
- }
2677
-
2678
- // ...redirects are respected...
2679
- if (status >= 300 && status < 400) {
2680
- data.redirect = /** @type {string} */ (
2681
- headers instanceof Headers ? headers.get('location') : headers.location
2682
- );
2683
- return data;
2684
- }
2685
-
2686
- // ...but 4xx and 5xx status codes _don't_ result in the error page
2687
- // rendering for non-GET requests — instead, we allow the page
2688
- // to render with any validation errors etc that were returned
2689
- data.body = body;
2690
- }
2691
-
2692
- const get = (method === 'HEAD' && mod.HEAD) || mod.GET;
2693
- if (get) {
2694
- const { status, headers, body } = validate_shadow_output(await get(event));
2695
- add_cookies(/** @type {string[]} */ (data.cookies), headers);
2696
-
2697
- if (body instanceof Error) {
2698
- if (status < 400) {
2699
- data.status = 500;
2700
- data.error = new Error('A non-error status code was returned with an error body');
2701
- } else {
2702
- data.status = status;
2703
- data.error = body;
2704
- }
2705
-
2706
- return data;
2707
- }
2708
-
2709
- if (status >= 400) {
2710
- data.status = status;
2711
- data.error = new Error('Failed to load data');
2712
- return data;
2713
- }
2714
-
2715
- if (status >= 300) {
2716
- data.status = status;
2717
- data.redirect = /** @type {string} */ (
2718
- headers instanceof Headers ? headers.get('location') : headers.location
2719
- );
2720
- return data;
2721
- }
2722
-
2723
- data.body = { ...body, ...data.body };
2724
- }
2725
-
2726
- return data;
2727
- } catch (e) {
2728
- const error = coalesce_to_error(e);
2729
- options.handle_error(error, event);
2730
-
2731
- return {
2732
- status: 500,
2733
- error
2734
- };
2735
- }
2736
- }
2737
-
2738
- /**
2739
- * @param {string[]} target
2740
- * @param {Partial<import('types').ResponseHeaders>} headers
2741
- */
2742
- function add_cookies(target, headers) {
2743
- const cookies = headers['set-cookie'];
2744
- if (cookies) {
2745
- if (Array.isArray(cookies)) {
2746
- target.push(...cookies);
2747
- } else {
2748
- target.push(/** @type {string} */ (cookies));
2749
- }
2750
- }
2751
- }
2752
-
2753
- /**
2754
- * @param {import('types').ShadowEndpointOutput} result
2755
- */
2756
- function validate_shadow_output(result) {
2757
- // TODO remove for 1.0
2758
- // @ts-expect-error
2759
- if (result.fallthrough) {
2760
- throw new Error(
2761
- 'fallthrough is no longer supported. Use matchers instead: https://kit.svelte.dev/docs/routing#advanced-routing-matching'
2762
- );
2763
- }
2764
-
2765
- const { status = 200, body = {} } = result;
2766
- let headers = result.headers || {};
2767
-
2768
- if (headers instanceof Headers) {
2769
- if (headers.has('set-cookie')) {
2770
- throw new Error(
2771
- 'Endpoint request handler cannot use Headers interface with Set-Cookie headers'
2772
- );
2773
- }
2774
- } else {
2775
- headers = lowercase_keys(/** @type {Record<string, string>} */ (headers));
2776
- }
2777
-
2778
- if (!is_pojo(body)) {
2779
- throw new Error(
2780
- 'Body returned from endpoint request handler must be a plain object or an Error'
2781
- );
2782
- }
2783
-
2784
- return { status, headers, body };
2785
- }
2786
-
2787
- /**
2788
- * @typedef {import('./types.js').Loaded} Loaded
2789
- * @typedef {import('types').SSROptions} SSROptions
2790
- * @typedef {import('types').SSRState} SSRState
2791
- */
2792
-
2793
- /**
2794
- * @param {{
2795
- * event: import('types').RequestEvent;
2796
- * options: SSROptions;
2797
- * state: SSRState;
2798
- * $session: any;
2799
- * status: number;
2800
- * error: Error;
2801
- * resolve_opts: import('types').RequiredResolveOptions;
2802
- * }} opts
2803
- */
2804
- async function respond_with_error({
2805
- event,
2806
- options,
2807
- state,
2808
- $session,
2809
- status,
2810
- error,
2811
- resolve_opts
2812
- }) {
2813
- try {
2814
- const branch = [];
2815
- let stuff = {};
2816
-
2817
- if (resolve_opts.ssr) {
2818
- const default_layout = await options.manifest._.nodes[0](); // 0 is always the root layout
2819
- const default_error = await options.manifest._.nodes[1](); // 1 is always the root error
2820
-
2821
- const layout_loaded = /** @type {Loaded} */ (
2822
- await load_node({
2823
- event,
2824
- options,
2825
- state,
2826
- route: GENERIC_ERROR,
2827
- node: default_layout,
2828
- $session,
2829
- stuff: {},
2830
- is_error: false,
2831
- is_leaf: false
2832
- })
2833
- );
2834
-
2835
- if (layout_loaded.loaded.error) {
2836
- throw layout_loaded.loaded.error;
2837
- }
2838
-
2839
- const error_loaded = /** @type {Loaded} */ (
2840
- await load_node({
2841
- event,
2842
- options,
2843
- state,
2844
- route: GENERIC_ERROR,
2845
- node: default_error,
2846
- $session,
2847
- stuff: layout_loaded ? layout_loaded.stuff : {},
2848
- is_error: true,
2849
- is_leaf: false,
2850
- status,
2851
- error
2852
- })
2853
- );
2854
-
2855
- branch.push(layout_loaded, error_loaded);
2856
- stuff = error_loaded.stuff;
2857
- }
2858
-
2859
- return await render_response({
2860
- options,
2861
- state,
2862
- $session,
2863
- page_config: {
2864
- hydrate: options.hydrate,
2865
- router: options.router
2866
- },
2867
- stuff,
2868
- status,
2869
- error,
2870
- branch,
2871
- event,
2872
- resolve_opts
2873
- });
2874
- } catch (err) {
2875
- const error = coalesce_to_error(err);
2876
-
2877
- options.handle_error(error, event);
2878
-
2879
- return new Response(error.stack, {
2880
- status: 500
2881
- });
2882
- }
2883
- }
2884
-
2885
- /**
2886
- * @typedef {import('./types.js').Loaded} Loaded
2887
- * @typedef {import('types').SSRNode} SSRNode
2888
- * @typedef {import('types').SSROptions} SSROptions
2889
- * @typedef {import('types').SSRState} SSRState
2890
- */
2891
-
2892
- /**
2893
- * Gets the nodes, calls `load` for each of them, and then calls render to build the HTML response.
2894
- * @param {{
2895
- * event: import('types').RequestEvent;
2896
- * options: SSROptions;
2897
- * state: SSRState;
2898
- * $session: any;
2899
- * resolve_opts: import('types').RequiredResolveOptions;
2900
- * route: import('types').SSRPage;
2901
- * }} opts
2902
- * @returns {Promise<Response>}
2903
- */
2904
- async function respond$1(opts) {
2905
- const { event, options, state, $session, route, resolve_opts } = opts;
2906
-
2907
- /** @type {Array<SSRNode | undefined>} */
2908
- let nodes;
2909
-
2910
- if (!resolve_opts.ssr) {
2911
- return await render_response({
2912
- ...opts,
2913
- branch: [],
2914
- page_config: {
2915
- hydrate: true,
2916
- router: true
2917
- },
2918
- status: 200,
2919
- error: null,
2920
- event,
2921
- stuff: {}
2922
- });
2923
- }
2924
-
2925
- try {
2926
- nodes = await Promise.all(
2927
- // we use == here rather than === because [undefined] serializes as "[null]"
2928
- route.a.map((n) => (n == undefined ? n : options.manifest._.nodes[n]()))
2929
- );
2930
- } catch (err) {
2931
- const error = coalesce_to_error(err);
2932
-
2933
- options.handle_error(error, event);
2934
-
2935
- return await respond_with_error({
2936
- event,
2937
- options,
2938
- state,
2939
- $session,
2940
- status: 500,
2941
- error,
2942
- resolve_opts
2943
- });
2944
- }
2945
-
2946
- // the leaf node will be present. only layouts may be undefined
2947
- const leaf = /** @type {SSRNode} */ (nodes[nodes.length - 1]).module;
2948
-
2949
- let page_config = get_page_config(leaf, options);
2950
-
2951
- if (state.prerendering) {
2952
- // if the page isn't marked as prerenderable (or is explicitly
2953
- // marked NOT prerenderable, if `prerender.default` is `true`),
2954
- // then bail out at this point
2955
- const should_prerender = leaf.prerender ?? options.prerender.default;
2956
- if (!should_prerender) {
2957
- return new Response(undefined, {
2958
- status: 204
2959
- });
2960
- }
2961
- }
2962
-
2963
- /** @type {Array<Loaded>} */
2964
- let branch = [];
2965
-
2966
- /** @type {number} */
2967
- let status = 200;
2968
-
2969
- /** @type {Error | null} */
2970
- let error = null;
2971
-
2972
- /** @type {string[]} */
2973
- let set_cookie_headers = [];
2974
-
2975
- let stuff = {};
2976
-
2977
- ssr: {
2978
- for (let i = 0; i < nodes.length; i += 1) {
2979
- const node = nodes[i];
2980
-
2981
- /** @type {Loaded | undefined} */
2982
- let loaded;
2983
-
2984
- if (node) {
2985
- try {
2986
- loaded = await load_node({
2987
- ...opts,
2988
- node,
2989
- stuff,
2990
- is_error: false,
2991
- is_leaf: i === nodes.length - 1
2992
- });
2993
-
2994
- set_cookie_headers = set_cookie_headers.concat(loaded.set_cookie_headers);
2995
-
2996
- if (loaded.loaded.redirect) {
2997
- return with_cookies(
2998
- new Response(undefined, {
2999
- status: loaded.loaded.status,
3000
- headers: {
3001
- location: loaded.loaded.redirect
3002
- }
3003
- }),
3004
- set_cookie_headers
3005
- );
3006
- }
3007
-
3008
- if (loaded.loaded.error) {
3009
- error = loaded.loaded.error;
3010
- status = loaded.loaded.status ?? 500;
3011
- }
3012
- } catch (err) {
3013
- const e = coalesce_to_error(err);
3014
-
3015
- options.handle_error(e, event);
3016
-
3017
- status = 500;
3018
- error = e;
3019
- }
3020
-
3021
- if (loaded && !error) {
3022
- branch.push(loaded);
3023
- }
3024
-
3025
- if (error) {
3026
- while (i--) {
3027
- if (route.b[i]) {
3028
- const index = /** @type {number} */ (route.b[i]);
3029
- const error_node = await options.manifest._.nodes[index]();
3030
-
3031
- /** @type {Loaded} */
3032
- let node_loaded;
3033
- let j = i;
3034
- while (!(node_loaded = branch[j])) {
3035
- j -= 1;
3036
- }
3037
-
3038
- try {
3039
- const error_loaded = /** @type {import('./types').Loaded} */ (
3040
- await load_node({
3041
- ...opts,
3042
- node: error_node,
3043
- stuff: node_loaded.stuff,
3044
- is_error: true,
3045
- is_leaf: false,
3046
- status,
3047
- error
3048
- })
3049
- );
3050
-
3051
- if (error_loaded.loaded.error) {
3052
- continue;
3053
- }
3054
-
3055
- page_config = get_page_config(error_node.module, options);
3056
- branch = branch.slice(0, j + 1).concat(error_loaded);
3057
- stuff = { ...node_loaded.stuff, ...error_loaded.stuff };
3058
- break ssr;
3059
- } catch (err) {
3060
- const e = coalesce_to_error(err);
3061
-
3062
- options.handle_error(e, event);
3063
-
3064
- continue;
3065
- }
3066
- }
3067
- }
3068
-
3069
- // TODO backtrack until we find an __error.svelte component
3070
- // that we can use as the leaf node
3071
- // for now just return regular error page
3072
- return with_cookies(
3073
- await respond_with_error({
3074
- event,
3075
- options,
3076
- state,
3077
- $session,
3078
- status,
3079
- error,
3080
- resolve_opts
3081
- }),
3082
- set_cookie_headers
3083
- );
3084
- }
3085
- }
3086
-
3087
- if (loaded && loaded.loaded.stuff) {
3088
- stuff = {
3089
- ...stuff,
3090
- ...loaded.loaded.stuff
3091
- };
3092
- }
3093
- }
3094
- }
3095
-
3096
- try {
3097
- return with_cookies(
3098
- await render_response({
3099
- ...opts,
3100
- stuff,
3101
- event,
3102
- page_config,
3103
- status,
3104
- error,
3105
- branch: branch.filter(Boolean)
3106
- }),
3107
- set_cookie_headers
3108
- );
3109
- } catch (err) {
3110
- const error = coalesce_to_error(err);
3111
-
3112
- options.handle_error(error, event);
3113
-
3114
- return with_cookies(
3115
- await respond_with_error({
3116
- ...opts,
3117
- status: 500,
3118
- error
3119
- }),
3120
- set_cookie_headers
3121
- );
3122
- }
3123
- }
3124
-
3125
- /**
3126
- * @param {import('types').SSRComponent} leaf
3127
- * @param {SSROptions} options
3128
- */
3129
- function get_page_config(leaf, options) {
3130
- // TODO remove for 1.0
3131
- if ('ssr' in leaf) {
3132
- throw new Error(
3133
- '`export const ssr` has been removed — use the handle hook instead: https://kit.svelte.dev/docs/hooks#handle'
3134
- );
3135
- }
3136
-
3137
- return {
3138
- router: 'router' in leaf ? !!leaf.router : options.router,
3139
- hydrate: 'hydrate' in leaf ? !!leaf.hydrate : options.hydrate
3140
- };
3141
- }
3142
-
3143
- /**
3144
- * @param {Response} response
3145
- * @param {string[]} set_cookie_headers
3146
- */
3147
- function with_cookies(response, set_cookie_headers) {
3148
- if (set_cookie_headers.length) {
3149
- set_cookie_headers.forEach((value) => {
3150
- response.headers.append('set-cookie', value);
3151
- });
3152
- }
3153
- return response;
3154
- }
3155
-
3156
- /**
3157
- * @param {import('types').RequestEvent} event
3158
- * @param {import('types').SSRPage} route
3159
- * @param {import('types').SSROptions} options
3160
- * @param {import('types').SSRState} state
3161
- * @param {import('types').RequiredResolveOptions} resolve_opts
3162
- * @returns {Promise<Response>}
3163
- */
3164
- async function render_page(event, route, options, state, resolve_opts) {
3165
- if (state.initiator === route) {
3166
- // infinite request cycle detected
3167
- return new Response(`Not found: ${event.url.pathname}`, {
3168
- status: 404
3169
- });
3170
- }
3171
-
3172
- if (route.shadow) {
3173
- const type = negotiate(event.request.headers.get('accept') || 'text/html', [
3174
- 'text/html',
3175
- 'application/json'
3176
- ]);
3177
-
3178
- if (type === 'application/json') {
3179
- return render_endpoint(event, await route.shadow(), options);
3180
- }
3181
- }
3182
-
3183
- const $session = await options.hooks.getSession(event);
3184
-
3185
- return respond$1({
3186
- event,
3187
- options,
3188
- state,
3189
- $session,
3190
- resolve_opts,
3191
- route
3192
- });
3193
- }
3194
-
3195
- /**
3196
- * @param {RegExpMatchArray} match
3197
- * @param {string[]} names
3198
- * @param {string[]} types
3199
- * @param {Record<string, import('types').ParamMatcher>} matchers
3200
- */
3201
- function exec(match, names, types, matchers) {
3202
- /** @type {Record<string, string>} */
3203
- const params = {};
3204
-
3205
- for (let i = 0; i < names.length; i += 1) {
3206
- const name = names[i];
3207
- const type = types[i];
3208
- const value = match[i + 1] || '';
3209
-
3210
- if (type) {
3211
- const matcher = matchers[type];
3212
- if (!matcher) throw new Error(`Missing "${type}" param matcher`); // TODO do this ahead of time?
3213
-
3214
- if (!matcher(value)) return;
3215
- }
3216
-
3217
- params[name] = value;
3218
- }
3219
-
3220
- return params;
3221
- }
3222
-
3223
- /* global __SVELTEKIT_ADAPTER_NAME__ */
3224
-
3225
- const DATA_SUFFIX = '/__data.json';
3226
-
3227
- /** @param {{ html: string }} opts */
3228
- const default_transform = ({ html }) => html;
3229
-
3230
- /** @type {import('types').Respond} */
3231
- async function respond(request, options, state) {
3232
- let url = new URL(request.url);
3233
-
3234
- const { parameter, allowed } = options.method_override;
3235
- const method_override = url.searchParams.get(parameter)?.toUpperCase();
3236
-
3237
- if (method_override) {
3238
- if (request.method === 'POST') {
3239
- if (allowed.includes(method_override)) {
3240
- request = new Proxy(request, {
3241
- get: (target, property, _receiver) => {
3242
- if (property === 'method') return method_override;
3243
- return Reflect.get(target, property, target);
3244
- }
3245
- });
3246
- } else {
3247
- const verb = allowed.length === 0 ? 'enabled' : 'allowed';
3248
- const body = `${parameter}=${method_override} is not ${verb}. See https://kit.svelte.dev/docs/configuration#methodoverride`;
3249
-
3250
- return new Response(body, {
3251
- status: 400
3252
- });
3253
- }
3254
- } else {
3255
- throw new Error(`${parameter}=${method_override} is only allowed with POST requests`);
3256
- }
3257
- }
3258
-
3259
- let decoded;
3260
- try {
3261
- decoded = decodeURI(url.pathname);
3262
- } catch {
3263
- return new Response('Malformed URI', { status: 400 });
3264
- }
3265
-
3266
- /** @type {import('types').SSRRoute | null} */
3267
- let route = null;
3268
-
3269
- /** @type {Record<string, string>} */
3270
- let params = {};
3271
-
3272
- if (options.paths.base && !state.prerendering?.fallback) {
3273
- if (!decoded.startsWith(options.paths.base)) {
3274
- return new Response('Not found', { status: 404 });
3275
- }
3276
- decoded = decoded.slice(options.paths.base.length) || '/';
3277
- }
3278
-
3279
- const is_data_request = decoded.endsWith(DATA_SUFFIX);
3280
-
3281
- if (is_data_request) {
3282
- const data_suffix_length = DATA_SUFFIX.length - (options.trailing_slash === 'always' ? 1 : 0);
3283
- decoded = decoded.slice(0, -data_suffix_length) || '/';
3284
- url = new URL(url.origin + url.pathname.slice(0, -data_suffix_length) + url.search);
3285
- }
3286
-
3287
- if (!state.prerendering?.fallback) {
3288
- const matchers = await options.manifest._.matchers();
3289
-
3290
- for (const candidate of options.manifest._.routes) {
3291
- const match = candidate.pattern.exec(decoded);
3292
- if (!match) continue;
3293
-
3294
- const matched = exec(match, candidate.names, candidate.types, matchers);
3295
- if (matched) {
3296
- route = candidate;
3297
- params = decode_params(matched);
3298
- break;
3299
- }
3300
- }
3301
- }
3302
-
3303
- if (route) {
3304
- if (route.type === 'page') {
3305
- const normalized = normalize_path(url.pathname, options.trailing_slash);
3306
-
3307
- if (normalized !== url.pathname && !state.prerendering?.fallback) {
3308
- return new Response(undefined, {
3309
- status: 301,
3310
- headers: {
3311
- 'x-sveltekit-normalize': '1',
3312
- location:
3313
- // ensure paths starting with '//' are not treated as protocol-relative
3314
- (normalized.startsWith('//') ? url.origin + normalized : normalized) +
3315
- (url.search === '?' ? '' : url.search)
3316
- }
3317
- });
3318
- }
3319
- } else if (is_data_request) {
3320
- // requesting /__data.json should fail for a standalone endpoint
3321
- return new Response(undefined, {
3322
- status: 404
3323
- });
3324
- }
3325
- }
3326
-
3327
- /** @type {import('types').RequestEvent} */
3328
- const event = {
3329
- get clientAddress() {
3330
- if (!state.getClientAddress) {
3331
- throw new Error(
3332
- `${__SVELTEKIT_ADAPTER_NAME__} does not specify getClientAddress. Please raise an issue`
3333
- );
3334
- }
3335
-
3336
- Object.defineProperty(event, 'clientAddress', {
3337
- value: state.getClientAddress()
3338
- });
3339
-
3340
- return event.clientAddress;
3341
- },
3342
- locals: {},
3343
- params,
3344
- platform: state.platform,
3345
- request,
3346
- routeId: route && route.id,
3347
- url
3348
- };
3349
-
3350
- // TODO remove this for 1.0
3351
- /**
3352
- * @param {string} property
3353
- * @param {string} replacement
3354
- * @param {string} suffix
3355
- */
3356
- const removed = (property, replacement, suffix = '') => ({
3357
- get: () => {
3358
- throw new Error(`event.${property} has been replaced by event.${replacement}` + suffix);
3359
- }
3360
- });
3361
-
3362
- const details = '. See https://github.com/sveltejs/kit/pull/3384 for details';
3363
-
3364
- const body_getter = {
3365
- get: () => {
3366
- throw new Error(
3367
- 'To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`' +
3368
- details
3369
- );
3370
- }
3371
- };
3372
-
3373
- Object.defineProperties(event, {
3374
- method: removed('method', 'request.method', details),
3375
- headers: removed('headers', 'request.headers', details),
3376
- origin: removed('origin', 'url.origin'),
3377
- path: removed('path', 'url.pathname'),
3378
- query: removed('query', 'url.searchParams'),
3379
- body: body_getter,
3380
- rawBody: body_getter
3381
- });
3382
-
3383
- /** @type {import('types').RequiredResolveOptions} */
3384
- let resolve_opts = {
3385
- ssr: true,
3386
- transformPageChunk: default_transform
3387
- };
3388
-
3389
- // TODO match route before calling handle?
3390
-
3391
- try {
3392
- const response = await options.hooks.handle({
3393
- event,
3394
- resolve: async (event, opts) => {
3395
- if (opts) {
3396
- // TODO remove for 1.0
3397
- // @ts-expect-error
3398
- if (opts.transformPage) {
3399
- throw new Error(
3400
- 'transformPage has been replaced by transformPageChunk — see https://github.com/sveltejs/kit/pull/5657 for more information'
3401
- );
3402
- }
3403
-
3404
- resolve_opts = {
3405
- ssr: opts.ssr !== false,
3406
- transformPageChunk: opts.transformPageChunk || default_transform
3407
- };
3408
- }
3409
-
3410
- if (state.prerendering?.fallback) {
3411
- return await render_response({
3412
- event,
3413
- options,
3414
- state,
3415
- $session: await options.hooks.getSession(event),
3416
- page_config: { router: true, hydrate: true },
3417
- stuff: {},
3418
- status: 200,
3419
- error: null,
3420
- branch: [],
3421
- resolve_opts: {
3422
- ...resolve_opts,
3423
- ssr: false
3424
- }
3425
- });
3426
- }
3427
-
3428
- if (route) {
3429
- /** @type {Response} */
3430
- let response;
3431
-
3432
- if (is_data_request && route.type === 'page' && route.shadow) {
3433
- response = await render_endpoint(event, await route.shadow(), options);
3434
-
3435
- // loading data for a client-side transition is a special case
3436
- if (request.headers.has('x-sveltekit-load')) {
3437
- // since redirects are opaque to the browser, we need to repackage
3438
- // 3xx responses as 200s with a custom header
3439
- if (response.status >= 300 && response.status < 400) {
3440
- const location = response.headers.get('location');
3441
-
3442
- if (location) {
3443
- const headers = new Headers(response.headers);
3444
- headers.set('x-sveltekit-location', location);
3445
- response = new Response(undefined, {
3446
- status: 204,
3447
- headers
3448
- });
3449
- }
3450
- }
3451
- }
3452
- } else {
3453
- response =
3454
- route.type === 'endpoint'
3455
- ? await render_endpoint(event, await route.load(), options)
3456
- : await render_page(event, route, options, state, resolve_opts);
3457
- }
3458
-
3459
- if (response) {
3460
- // respond with 304 if etag matches
3461
- if (response.status === 200 && response.headers.has('etag')) {
3462
- let if_none_match_value = request.headers.get('if-none-match');
3463
-
3464
- // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives
3465
- if (if_none_match_value?.startsWith('W/"')) {
3466
- if_none_match_value = if_none_match_value.substring(2);
3467
- }
3468
-
3469
- const etag = /** @type {string} */ (response.headers.get('etag'));
3470
-
3471
- if (if_none_match_value === etag) {
3472
- const headers = new Headers({ etag });
3473
-
3474
- // https://datatracker.ietf.org/doc/html/rfc7232#section-4.1
3475
- for (const key of [
3476
- 'cache-control',
3477
- 'content-location',
3478
- 'date',
3479
- 'expires',
3480
- 'vary'
3481
- ]) {
3482
- const value = response.headers.get(key);
3483
- if (value) headers.set(key, value);
3484
- }
3485
-
3486
- return new Response(undefined, {
3487
- status: 304,
3488
- headers
3489
- });
3490
- }
3491
- }
3492
-
3493
- return response;
3494
- }
3495
- }
3496
-
3497
- if (state.initiator === GENERIC_ERROR) {
3498
- return new Response('Internal Server Error', {
3499
- status: 500
3500
- });
3501
- }
3502
-
3503
- // if this request came direct from the user, rather than
3504
- // via a `fetch` in a `load`, render a 404 page
3505
- if (!state.initiator) {
3506
- const $session = await options.hooks.getSession(event);
3507
- return await respond_with_error({
3508
- event,
3509
- options,
3510
- state,
3511
- $session,
3512
- status: 404,
3513
- error: new Error(`Not found: ${event.url.pathname}`),
3514
- resolve_opts
3515
- });
3516
- }
3517
-
3518
- if (state.prerendering) {
3519
- return new Response('not found', { status: 404 });
3520
- }
3521
-
3522
- // we can't load the endpoint from our own manifest,
3523
- // so we need to make an actual HTTP request
3524
- return await fetch(request);
3525
- },
3526
-
3527
- // TODO remove for 1.0
3528
- // @ts-expect-error
3529
- get request() {
3530
- throw new Error('request in handle has been replaced with event' + details);
3531
- }
3532
- });
3533
-
3534
- // TODO for 1.0, change the error message to point to docs rather than PR
3535
- if (response && !(response instanceof Response)) {
3536
- throw new Error('handle must return a Response object' + details);
3537
- }
3538
-
3539
- return response;
3540
- } catch (/** @type {unknown} */ e) {
3541
- const error = coalesce_to_error(e);
3542
-
3543
- options.handle_error(error, event);
3544
-
3545
- const type = negotiate(event.request.headers.get('accept') || 'text/html', [
3546
- 'text/html',
3547
- 'application/json'
3548
- ]);
3549
-
3550
- if (is_data_request || type === 'application/json') {
3551
- return new Response(serialize_error(error, options.get_stack), {
3552
- status: 500,
3553
- headers: { 'content-type': 'application/json; charset=utf-8' }
3554
- });
3555
- }
3556
-
3557
- // TODO is this necessary? should we just return a plain 500 at this point?
3558
- try {
3559
- const $session = await options.hooks.getSession(event);
3560
- return await respond_with_error({
3561
- event,
3562
- options,
3563
- state,
3564
- $session,
3565
- status: 500,
3566
- error,
3567
- resolve_opts
3568
- });
3569
- } catch (/** @type {unknown} */ e) {
3570
- const error = coalesce_to_error(e);
3571
-
3572
- return new Response(options.dev ? error.stack : error.message, {
3573
- status: 500
3574
- });
3575
- }
3576
- }
3577
- }
3578
-
3579
- export { respond };