@sveltejs/kit 1.0.0-next.26 → 1.0.0-next.260

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 (86) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +20 -0
  3. package/assets/app/navigation.js +79 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/app/stores.js +97 -0
  6. package/assets/chunks/utils.js +13 -0
  7. package/assets/client/singletons.js +21 -0
  8. package/assets/client/start.js +1493 -0
  9. package/assets/components/error.svelte +18 -2
  10. package/assets/env.js +8 -0
  11. package/assets/paths.js +13 -0
  12. package/assets/server/index.js +2664 -0
  13. package/dist/chunks/amp_hook.js +56 -0
  14. package/dist/chunks/build.js +658 -0
  15. package/dist/chunks/cert.js +28154 -0
  16. package/dist/chunks/index.js +467 -0
  17. package/dist/chunks/index2.js +836 -0
  18. package/dist/chunks/index3.js +638 -0
  19. package/dist/chunks/index4.js +115 -0
  20. package/dist/chunks/index5.js +860 -0
  21. package/dist/chunks/index6.js +170 -0
  22. package/dist/chunks/index7.js +15582 -0
  23. package/dist/chunks/index8.js +4207 -0
  24. package/dist/chunks/misc.js +3 -0
  25. package/dist/chunks/multipart-parser.js +449 -0
  26. package/dist/cli.js +1128 -84
  27. package/dist/hooks.js +28 -0
  28. package/dist/install-fetch.js +6518 -0
  29. package/dist/node.js +95 -0
  30. package/package.json +95 -54
  31. package/svelte-kit.js +2 -0
  32. package/types/ambient-modules.d.ts +208 -0
  33. package/types/app.d.ts +35 -0
  34. package/types/config.d.ts +176 -0
  35. package/types/csp.d.ts +115 -0
  36. package/types/endpoint.d.ts +39 -0
  37. package/types/helper.d.ts +23 -0
  38. package/types/hooks.d.ts +34 -0
  39. package/types/index.d.ts +10 -0
  40. package/types/internal.d.ts +260 -0
  41. package/types/page.d.ts +33 -0
  42. package/CHANGELOG.md +0 -312
  43. package/assets/runtime/app/navigation.js +0 -23
  44. package/assets/runtime/app/navigation.js.map +0 -1
  45. package/assets/runtime/app/paths.js +0 -2
  46. package/assets/runtime/app/paths.js.map +0 -1
  47. package/assets/runtime/app/stores.js +0 -78
  48. package/assets/runtime/app/stores.js.map +0 -1
  49. package/assets/runtime/internal/singletons.js +0 -15
  50. package/assets/runtime/internal/singletons.js.map +0 -1
  51. package/assets/runtime/internal/start.js +0 -591
  52. package/assets/runtime/internal/start.js.map +0 -1
  53. package/assets/runtime/utils-85ebcc60.js +0 -18
  54. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  55. package/dist/api.js +0 -44
  56. package/dist/api.js.map +0 -1
  57. package/dist/build.js +0 -246
  58. package/dist/build.js.map +0 -1
  59. package/dist/cli.js.map +0 -1
  60. package/dist/colors.js +0 -37
  61. package/dist/colors.js.map +0 -1
  62. package/dist/create_app.js +0 -580
  63. package/dist/create_app.js.map +0 -1
  64. package/dist/index.js +0 -367
  65. package/dist/index.js.map +0 -1
  66. package/dist/index2.js +0 -12035
  67. package/dist/index2.js.map +0 -1
  68. package/dist/index3.js +0 -547
  69. package/dist/index3.js.map +0 -1
  70. package/dist/index4.js +0 -74
  71. package/dist/index4.js.map +0 -1
  72. package/dist/index5.js +0 -464
  73. package/dist/index5.js.map +0 -1
  74. package/dist/index6.js +0 -727
  75. package/dist/index6.js.map +0 -1
  76. package/dist/logging.js +0 -43
  77. package/dist/logging.js.map +0 -1
  78. package/dist/package.js +0 -432
  79. package/dist/package.js.map +0 -1
  80. package/dist/renderer.js +0 -2403
  81. package/dist/renderer.js.map +0 -1
  82. package/dist/standard.js +0 -101
  83. package/dist/standard.js.map +0 -1
  84. package/dist/utils.js +0 -54
  85. package/dist/utils.js.map +0 -1
  86. package/svelte-kit +0 -3
@@ -0,0 +1,2664 @@
1
+ /** @param {Partial<import('types/helper').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 (typeof value === 'string') {
11
+ headers.set(key, value);
12
+ } else {
13
+ value.forEach((value) => {
14
+ headers.append(key, value);
15
+ });
16
+ }
17
+ }
18
+ }
19
+
20
+ return headers;
21
+ }
22
+
23
+ /**
24
+ * Hash using djb2
25
+ * @param {import('types/hooks').StrictBody} value
26
+ */
27
+ function hash(value) {
28
+ let hash = 5381;
29
+ let i = value.length;
30
+
31
+ if (typeof value === 'string') {
32
+ while (i) hash = (hash * 33) ^ value.charCodeAt(--i);
33
+ } else {
34
+ while (i) hash = (hash * 33) ^ value[--i];
35
+ }
36
+
37
+ return (hash >>> 0).toString(36);
38
+ }
39
+
40
+ /** @param {Record<string, any>} obj */
41
+
42
+ /** @param {Record<string, string>} params */
43
+ function decode_params(params) {
44
+ for (const key in params) {
45
+ // input has already been decoded by decodeURI
46
+ // now handle the rest that decodeURIComponent would do
47
+ params[key] = params[key]
48
+ .replace(/%23/g, '#')
49
+ .replace(/%3[Bb]/g, ';')
50
+ .replace(/%2[Cc]/g, ',')
51
+ .replace(/%2[Ff]/g, '/')
52
+ .replace(/%3[Ff]/g, '?')
53
+ .replace(/%3[Aa]/g, ':')
54
+ .replace(/%40/g, '@')
55
+ .replace(/%26/g, '&')
56
+ .replace(/%3[Dd]/g, '=')
57
+ .replace(/%2[Bb]/g, '+')
58
+ .replace(/%24/g, '$');
59
+ }
60
+
61
+ return params;
62
+ }
63
+
64
+ /** @param {any} body */
65
+ function is_pojo(body) {
66
+ if (typeof body !== 'object') return false;
67
+
68
+ if (body) {
69
+ if (body instanceof Uint8Array) return false;
70
+
71
+ // body could be a node Readable, but we don't want to import
72
+ // node built-ins, so we use duck typing
73
+ if (body._readableState && body._writableState && body._events) return false;
74
+
75
+ // similarly, it could be a web ReadableStream
76
+ if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) return false;
77
+ }
78
+
79
+ return true;
80
+ }
81
+
82
+ /** @param {string} body */
83
+ function error(body) {
84
+ return new Response(body, {
85
+ status: 500
86
+ });
87
+ }
88
+
89
+ /** @param {unknown} s */
90
+ function is_string(s) {
91
+ return typeof s === 'string' || s instanceof String;
92
+ }
93
+
94
+ const text_types = new Set([
95
+ 'application/xml',
96
+ 'application/json',
97
+ 'application/x-www-form-urlencoded',
98
+ 'multipart/form-data'
99
+ ]);
100
+
101
+ /**
102
+ * Decides how the body should be parsed based on its mime type. Should match what's in parse_body
103
+ *
104
+ * @param {string | undefined | null} content_type The `content-type` header of a request/response.
105
+ * @returns {boolean}
106
+ */
107
+ function is_text(content_type) {
108
+ if (!content_type) return true; // defaults to json
109
+ const type = content_type.split(';')[0].toLowerCase(); // get the mime type
110
+
111
+ return type.startsWith('text/') || type.endsWith('+xml') || text_types.has(type);
112
+ }
113
+
114
+ /**
115
+ * @param {import('types/hooks').RequestEvent} event
116
+ * @param {{ [method: string]: import('types/endpoint').RequestHandler }} mod
117
+ * @returns {Promise<Response | undefined>}
118
+ */
119
+ async function render_endpoint(event, mod) {
120
+ /** @type {import('types/endpoint').RequestHandler} */
121
+ const handler = mod[event.request.method.toLowerCase().replace('delete', 'del')]; // 'delete' is a reserved word
122
+
123
+ if (!handler) {
124
+ return;
125
+ }
126
+
127
+ const response = await handler(event);
128
+ const preface = `Invalid response from route ${event.url.pathname}`;
129
+
130
+ if (typeof response !== 'object') {
131
+ return error(`${preface}: expected an object, got ${typeof response}`);
132
+ }
133
+
134
+ if (response.fallthrough) {
135
+ return;
136
+ }
137
+
138
+ const { status = 200, body = {} } = response;
139
+ const headers =
140
+ response.headers instanceof Headers ? response.headers : to_headers(response.headers);
141
+
142
+ const type = headers.get('content-type');
143
+
144
+ if (!is_text(type) && !(body instanceof Uint8Array || is_string(body))) {
145
+ return error(
146
+ `${preface}: body must be an instance of string or Uint8Array if content-type is not a supported textual content-type`
147
+ );
148
+ }
149
+
150
+ /** @type {import('types/hooks').StrictBody} */
151
+ let normalized_body;
152
+
153
+ if (is_pojo(body) && (!type || type.startsWith('application/json'))) {
154
+ headers.set('content-type', 'application/json; charset=utf-8');
155
+ normalized_body = JSON.stringify(body);
156
+ } else {
157
+ normalized_body = /** @type {import('types/hooks').StrictBody} */ (body);
158
+ }
159
+
160
+ if (
161
+ (typeof normalized_body === 'string' || normalized_body instanceof Uint8Array) &&
162
+ !headers.has('etag')
163
+ ) {
164
+ const cache_control = headers.get('cache-control');
165
+ if (!cache_control || !/(no-store|immutable)/.test(cache_control)) {
166
+ headers.set('etag', `"${hash(normalized_body)}"`);
167
+ }
168
+ }
169
+
170
+ return new Response(normalized_body, {
171
+ status,
172
+ headers
173
+ });
174
+ }
175
+
176
+ var chars$1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
177
+ var unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
178
+ 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)$/;
179
+ var escaped = {
180
+ '<': '\\u003C',
181
+ '>': '\\u003E',
182
+ '/': '\\u002F',
183
+ '\\': '\\\\',
184
+ '\b': '\\b',
185
+ '\f': '\\f',
186
+ '\n': '\\n',
187
+ '\r': '\\r',
188
+ '\t': '\\t',
189
+ '\0': '\\0',
190
+ '\u2028': '\\u2028',
191
+ '\u2029': '\\u2029'
192
+ };
193
+ var objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join('\0');
194
+ function devalue(value) {
195
+ var counts = new Map();
196
+ function walk(thing) {
197
+ if (typeof thing === 'function') {
198
+ throw new Error("Cannot stringify a function");
199
+ }
200
+ if (counts.has(thing)) {
201
+ counts.set(thing, counts.get(thing) + 1);
202
+ return;
203
+ }
204
+ counts.set(thing, 1);
205
+ if (!isPrimitive(thing)) {
206
+ var type = getType(thing);
207
+ switch (type) {
208
+ case 'Number':
209
+ case 'String':
210
+ case 'Boolean':
211
+ case 'Date':
212
+ case 'RegExp':
213
+ return;
214
+ case 'Array':
215
+ thing.forEach(walk);
216
+ break;
217
+ case 'Set':
218
+ case 'Map':
219
+ Array.from(thing).forEach(walk);
220
+ break;
221
+ default:
222
+ var proto = Object.getPrototypeOf(thing);
223
+ if (proto !== Object.prototype &&
224
+ proto !== null &&
225
+ Object.getOwnPropertyNames(proto).sort().join('\0') !== objectProtoOwnPropertyNames) {
226
+ throw new Error("Cannot stringify arbitrary non-POJOs");
227
+ }
228
+ if (Object.getOwnPropertySymbols(thing).length > 0) {
229
+ throw new Error("Cannot stringify POJOs with symbolic keys");
230
+ }
231
+ Object.keys(thing).forEach(function (key) { return walk(thing[key]); });
232
+ }
233
+ }
234
+ }
235
+ walk(value);
236
+ var names = new Map();
237
+ Array.from(counts)
238
+ .filter(function (entry) { return entry[1] > 1; })
239
+ .sort(function (a, b) { return b[1] - a[1]; })
240
+ .forEach(function (entry, i) {
241
+ names.set(entry[0], getName(i));
242
+ });
243
+ function stringify(thing) {
244
+ if (names.has(thing)) {
245
+ return names.get(thing);
246
+ }
247
+ if (isPrimitive(thing)) {
248
+ return stringifyPrimitive(thing);
249
+ }
250
+ var type = getType(thing);
251
+ switch (type) {
252
+ case 'Number':
253
+ case 'String':
254
+ case 'Boolean':
255
+ return "Object(" + stringify(thing.valueOf()) + ")";
256
+ case 'RegExp':
257
+ return "new RegExp(" + stringifyString(thing.source) + ", \"" + thing.flags + "\")";
258
+ case 'Date':
259
+ return "new Date(" + thing.getTime() + ")";
260
+ case 'Array':
261
+ var members = thing.map(function (v, i) { return i in thing ? stringify(v) : ''; });
262
+ var tail = thing.length === 0 || (thing.length - 1 in thing) ? '' : ',';
263
+ return "[" + members.join(',') + tail + "]";
264
+ case 'Set':
265
+ case 'Map':
266
+ return "new " + type + "([" + Array.from(thing).map(stringify).join(',') + "])";
267
+ default:
268
+ var obj = "{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":" + stringify(thing[key]); }).join(',') + "}";
269
+ var proto = Object.getPrototypeOf(thing);
270
+ if (proto === null) {
271
+ return Object.keys(thing).length > 0
272
+ ? "Object.assign(Object.create(null)," + obj + ")"
273
+ : "Object.create(null)";
274
+ }
275
+ return obj;
276
+ }
277
+ }
278
+ var str = stringify(value);
279
+ if (names.size) {
280
+ var params_1 = [];
281
+ var statements_1 = [];
282
+ var values_1 = [];
283
+ names.forEach(function (name, thing) {
284
+ params_1.push(name);
285
+ if (isPrimitive(thing)) {
286
+ values_1.push(stringifyPrimitive(thing));
287
+ return;
288
+ }
289
+ var type = getType(thing);
290
+ switch (type) {
291
+ case 'Number':
292
+ case 'String':
293
+ case 'Boolean':
294
+ values_1.push("Object(" + stringify(thing.valueOf()) + ")");
295
+ break;
296
+ case 'RegExp':
297
+ values_1.push(thing.toString());
298
+ break;
299
+ case 'Date':
300
+ values_1.push("new Date(" + thing.getTime() + ")");
301
+ break;
302
+ case 'Array':
303
+ values_1.push("Array(" + thing.length + ")");
304
+ thing.forEach(function (v, i) {
305
+ statements_1.push(name + "[" + i + "]=" + stringify(v));
306
+ });
307
+ break;
308
+ case 'Set':
309
+ values_1.push("new Set");
310
+ statements_1.push(name + "." + Array.from(thing).map(function (v) { return "add(" + stringify(v) + ")"; }).join('.'));
311
+ break;
312
+ case 'Map':
313
+ values_1.push("new Map");
314
+ statements_1.push(name + "." + Array.from(thing).map(function (_a) {
315
+ var k = _a[0], v = _a[1];
316
+ return "set(" + stringify(k) + ", " + stringify(v) + ")";
317
+ }).join('.'));
318
+ break;
319
+ default:
320
+ values_1.push(Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}');
321
+ Object.keys(thing).forEach(function (key) {
322
+ statements_1.push("" + name + safeProp(key) + "=" + stringify(thing[key]));
323
+ });
324
+ }
325
+ });
326
+ statements_1.push("return " + str);
327
+ return "(function(" + params_1.join(',') + "){" + statements_1.join(';') + "}(" + values_1.join(',') + "))";
328
+ }
329
+ else {
330
+ return str;
331
+ }
332
+ }
333
+ function getName(num) {
334
+ var name = '';
335
+ do {
336
+ name = chars$1[num % chars$1.length] + name;
337
+ num = ~~(num / chars$1.length) - 1;
338
+ } while (num >= 0);
339
+ return reserved.test(name) ? name + "_" : name;
340
+ }
341
+ function isPrimitive(thing) {
342
+ return Object(thing) !== thing;
343
+ }
344
+ function stringifyPrimitive(thing) {
345
+ if (typeof thing === 'string')
346
+ return stringifyString(thing);
347
+ if (thing === void 0)
348
+ return 'void 0';
349
+ if (thing === 0 && 1 / thing < 0)
350
+ return '-0';
351
+ var str = String(thing);
352
+ if (typeof thing === 'number')
353
+ return str.replace(/^(-)?0\./, '$1.');
354
+ return str;
355
+ }
356
+ function getType(thing) {
357
+ return Object.prototype.toString.call(thing).slice(8, -1);
358
+ }
359
+ function escapeUnsafeChar(c) {
360
+ return escaped[c] || c;
361
+ }
362
+ function escapeUnsafeChars(str) {
363
+ return str.replace(unsafeChars, escapeUnsafeChar);
364
+ }
365
+ function safeKey(key) {
366
+ return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
367
+ }
368
+ function safeProp(key) {
369
+ return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? "." + key : "[" + escapeUnsafeChars(JSON.stringify(key)) + "]";
370
+ }
371
+ function stringifyString(str) {
372
+ var result = '"';
373
+ for (var i = 0; i < str.length; i += 1) {
374
+ var char = str.charAt(i);
375
+ var code = char.charCodeAt(0);
376
+ if (char === '"') {
377
+ result += '\\"';
378
+ }
379
+ else if (char in escaped) {
380
+ result += escaped[char];
381
+ }
382
+ else if (code >= 0xd800 && code <= 0xdfff) {
383
+ var next = str.charCodeAt(i + 1);
384
+ // If this is the beginning of a [high, low] surrogate pair,
385
+ // add the next two characters, otherwise escape
386
+ if (code <= 0xdbff && (next >= 0xdc00 && next <= 0xdfff)) {
387
+ result += char + str[++i];
388
+ }
389
+ else {
390
+ result += "\\u" + code.toString(16).toUpperCase();
391
+ }
392
+ }
393
+ else {
394
+ result += char;
395
+ }
396
+ }
397
+ result += '"';
398
+ return result;
399
+ }
400
+
401
+ function noop() { }
402
+ function safe_not_equal(a, b) {
403
+ return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
404
+ }
405
+ Promise.resolve();
406
+
407
+ const subscriber_queue = [];
408
+ /**
409
+ * Creates a `Readable` store that allows reading by subscription.
410
+ * @param value initial value
411
+ * @param {StartStopNotifier}start start and stop notifications for subscriptions
412
+ */
413
+ function readable(value, start) {
414
+ return {
415
+ subscribe: writable(value, start).subscribe
416
+ };
417
+ }
418
+ /**
419
+ * Create a `Writable` store that allows both updating and reading by subscription.
420
+ * @param {*=}value initial value
421
+ * @param {StartStopNotifier=}start start and stop notifications for subscriptions
422
+ */
423
+ function writable(value, start = noop) {
424
+ let stop;
425
+ const subscribers = new Set();
426
+ function set(new_value) {
427
+ if (safe_not_equal(value, new_value)) {
428
+ value = new_value;
429
+ if (stop) { // store is ready
430
+ const run_queue = !subscriber_queue.length;
431
+ for (const subscriber of subscribers) {
432
+ subscriber[1]();
433
+ subscriber_queue.push(subscriber, value);
434
+ }
435
+ if (run_queue) {
436
+ for (let i = 0; i < subscriber_queue.length; i += 2) {
437
+ subscriber_queue[i][0](subscriber_queue[i + 1]);
438
+ }
439
+ subscriber_queue.length = 0;
440
+ }
441
+ }
442
+ }
443
+ }
444
+ function update(fn) {
445
+ set(fn(value));
446
+ }
447
+ function subscribe(run, invalidate = noop) {
448
+ const subscriber = [run, invalidate];
449
+ subscribers.add(subscriber);
450
+ if (subscribers.size === 1) {
451
+ stop = start(set) || noop;
452
+ }
453
+ run(value);
454
+ return () => {
455
+ subscribers.delete(subscriber);
456
+ if (subscribers.size === 0) {
457
+ stop();
458
+ stop = null;
459
+ }
460
+ };
461
+ }
462
+ return { set, update, subscribe };
463
+ }
464
+
465
+ /**
466
+ * @param {unknown} err
467
+ * @return {Error}
468
+ */
469
+ function coalesce_to_error(err) {
470
+ return err instanceof Error ||
471
+ (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message)
472
+ ? /** @type {Error} */ (err)
473
+ : new Error(JSON.stringify(err));
474
+ }
475
+
476
+ /** @type {Record<string, string>} */
477
+ const escape_json_string_in_html_dict = {
478
+ '"': '\\"',
479
+ '<': '\\u003C',
480
+ '>': '\\u003E',
481
+ '/': '\\u002F',
482
+ '\\': '\\\\',
483
+ '\b': '\\b',
484
+ '\f': '\\f',
485
+ '\n': '\\n',
486
+ '\r': '\\r',
487
+ '\t': '\\t',
488
+ '\0': '\\0',
489
+ '\u2028': '\\u2028',
490
+ '\u2029': '\\u2029'
491
+ };
492
+
493
+ /** @param {string} str */
494
+ function escape_json_string_in_html(str) {
495
+ return escape(
496
+ str,
497
+ escape_json_string_in_html_dict,
498
+ (code) => `\\u${code.toString(16).toUpperCase()}`
499
+ );
500
+ }
501
+
502
+ /** @type {Record<string, string>} */
503
+ const escape_html_attr_dict = {
504
+ '<': '&lt;',
505
+ '>': '&gt;',
506
+ '"': '&quot;'
507
+ };
508
+
509
+ /**
510
+ * use for escaping string values to be used html attributes on the page
511
+ * e.g.
512
+ * <script data-url="here">
513
+ *
514
+ * @param {string} str
515
+ * @returns string escaped string
516
+ */
517
+ function escape_html_attr(str) {
518
+ return '"' + escape(str, escape_html_attr_dict, (code) => `&#${code};`) + '"';
519
+ }
520
+
521
+ /**
522
+ *
523
+ * @param str {string} string to escape
524
+ * @param dict {Record<string, string>} dictionary of character replacements
525
+ * @param unicode_encoder {function(number): string} encoder to use for high unicode characters
526
+ * @returns {string}
527
+ */
528
+ function escape(str, dict, unicode_encoder) {
529
+ let result = '';
530
+
531
+ for (let i = 0; i < str.length; i += 1) {
532
+ const char = str.charAt(i);
533
+ const code = char.charCodeAt(0);
534
+
535
+ if (char in dict) {
536
+ result += dict[char];
537
+ } else if (code >= 0xd800 && code <= 0xdfff) {
538
+ const next = str.charCodeAt(i + 1);
539
+
540
+ // If this is the beginning of a [high, low] surrogate pair,
541
+ // add the next two characters, otherwise escape
542
+ if (code <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
543
+ result += char + str[++i];
544
+ } else {
545
+ result += unicode_encoder(code);
546
+ }
547
+ } else {
548
+ result += char;
549
+ }
550
+ }
551
+
552
+ return result;
553
+ }
554
+
555
+ const s = JSON.stringify;
556
+
557
+ /** @param {URL} url */
558
+ function create_prerendering_url_proxy(url) {
559
+ return new Proxy(url, {
560
+ get: (target, prop, receiver) => {
561
+ if (prop === 'search' || prop === 'searchParams') {
562
+ throw new Error(`Cannot access url.${prop} on a page with prerendering enabled`);
563
+ }
564
+ return Reflect.get(target, prop, receiver);
565
+ }
566
+ });
567
+ }
568
+
569
+ const encoder = new TextEncoder();
570
+
571
+ /**
572
+ * SHA-256 hashing function adapted from https://bitwiseshiftleft.github.io/sjcl
573
+ * modified and redistributed under BSD license
574
+ * @param {string} data
575
+ */
576
+ function sha256(data) {
577
+ if (!key[0]) precompute();
578
+
579
+ const out = init.slice(0);
580
+ const array = encode(data);
581
+
582
+ for (let i = 0; i < array.length; i += 16) {
583
+ const w = array.subarray(i, i + 16);
584
+
585
+ let tmp;
586
+ let a;
587
+ let b;
588
+
589
+ let out0 = out[0];
590
+ let out1 = out[1];
591
+ let out2 = out[2];
592
+ let out3 = out[3];
593
+ let out4 = out[4];
594
+ let out5 = out[5];
595
+ let out6 = out[6];
596
+ let out7 = out[7];
597
+
598
+ /* Rationale for placement of |0 :
599
+ * If a value can overflow is original 32 bits by a factor of more than a few
600
+ * million (2^23 ish), there is a possibility that it might overflow the
601
+ * 53-bit mantissa and lose precision.
602
+ *
603
+ * To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that
604
+ * propagates around the loop, and on the hash state out[]. I don't believe
605
+ * that the clamps on out4 and on out0 are strictly necessary, but it's close
606
+ * (for out4 anyway), and better safe than sorry.
607
+ *
608
+ * The clamps on out[] are necessary for the output to be correct even in the
609
+ * common case and for short inputs.
610
+ */
611
+
612
+ for (let i = 0; i < 64; i++) {
613
+ // load up the input word for this round
614
+
615
+ if (i < 16) {
616
+ tmp = w[i];
617
+ } else {
618
+ a = w[(i + 1) & 15];
619
+
620
+ b = w[(i + 14) & 15];
621
+
622
+ tmp = w[i & 15] =
623
+ (((a >>> 7) ^ (a >>> 18) ^ (a >>> 3) ^ (a << 25) ^ (a << 14)) +
624
+ ((b >>> 17) ^ (b >>> 19) ^ (b >>> 10) ^ (b << 15) ^ (b << 13)) +
625
+ w[i & 15] +
626
+ w[(i + 9) & 15]) |
627
+ 0;
628
+ }
629
+
630
+ tmp =
631
+ tmp +
632
+ out7 +
633
+ ((out4 >>> 6) ^ (out4 >>> 11) ^ (out4 >>> 25) ^ (out4 << 26) ^ (out4 << 21) ^ (out4 << 7)) +
634
+ (out6 ^ (out4 & (out5 ^ out6))) +
635
+ key[i]; // | 0;
636
+
637
+ // shift register
638
+ out7 = out6;
639
+ out6 = out5;
640
+ out5 = out4;
641
+
642
+ out4 = (out3 + tmp) | 0;
643
+
644
+ out3 = out2;
645
+ out2 = out1;
646
+ out1 = out0;
647
+
648
+ out0 =
649
+ (tmp +
650
+ ((out1 & out2) ^ (out3 & (out1 ^ out2))) +
651
+ ((out1 >>> 2) ^
652
+ (out1 >>> 13) ^
653
+ (out1 >>> 22) ^
654
+ (out1 << 30) ^
655
+ (out1 << 19) ^
656
+ (out1 << 10))) |
657
+ 0;
658
+ }
659
+
660
+ out[0] = (out[0] + out0) | 0;
661
+ out[1] = (out[1] + out1) | 0;
662
+ out[2] = (out[2] + out2) | 0;
663
+ out[3] = (out[3] + out3) | 0;
664
+ out[4] = (out[4] + out4) | 0;
665
+ out[5] = (out[5] + out5) | 0;
666
+ out[6] = (out[6] + out6) | 0;
667
+ out[7] = (out[7] + out7) | 0;
668
+ }
669
+
670
+ const bytes = new Uint8Array(out.buffer);
671
+ reverse_endianness(bytes);
672
+
673
+ return base64(bytes);
674
+ }
675
+
676
+ /** The SHA-256 initialization vector */
677
+ const init = new Uint32Array(8);
678
+
679
+ /** The SHA-256 hash key */
680
+ const key = new Uint32Array(64);
681
+
682
+ /** Function to precompute init and key. */
683
+ function precompute() {
684
+ /** @param {number} x */
685
+ function frac(x) {
686
+ return (x - Math.floor(x)) * 0x100000000;
687
+ }
688
+
689
+ let prime = 2;
690
+
691
+ for (let i = 0; i < 64; prime++) {
692
+ let is_prime = true;
693
+
694
+ for (let factor = 2; factor * factor <= prime; factor++) {
695
+ if (prime % factor === 0) {
696
+ is_prime = false;
697
+
698
+ break;
699
+ }
700
+ }
701
+
702
+ if (is_prime) {
703
+ if (i < 8) {
704
+ init[i] = frac(prime ** (1 / 2));
705
+ }
706
+
707
+ key[i] = frac(prime ** (1 / 3));
708
+
709
+ i++;
710
+ }
711
+ }
712
+ }
713
+
714
+ /** @param {Uint8Array} bytes */
715
+ function reverse_endianness(bytes) {
716
+ for (let i = 0; i < bytes.length; i += 4) {
717
+ const a = bytes[i + 0];
718
+ const b = bytes[i + 1];
719
+ const c = bytes[i + 2];
720
+ const d = bytes[i + 3];
721
+
722
+ bytes[i + 0] = d;
723
+ bytes[i + 1] = c;
724
+ bytes[i + 2] = b;
725
+ bytes[i + 3] = a;
726
+ }
727
+ }
728
+
729
+ /** @param {string} str */
730
+ function encode(str) {
731
+ const encoded = encoder.encode(str);
732
+ const length = encoded.length * 8;
733
+
734
+ // result should be a multiple of 512 bits in length,
735
+ // with room for a 1 (after the data) and two 32-bit
736
+ // words containing the original input bit length
737
+ const size = 512 * Math.ceil((length + 65) / 512);
738
+ const bytes = new Uint8Array(size / 8);
739
+ bytes.set(encoded);
740
+
741
+ // append a 1
742
+ bytes[encoded.length] = 0b10000000;
743
+
744
+ reverse_endianness(bytes);
745
+
746
+ // add the input bit length
747
+ const words = new Uint32Array(bytes.buffer);
748
+ words[words.length - 2] = Math.floor(length / 0x100000000); // this will always be zero for us
749
+ words[words.length - 1] = length;
750
+
751
+ return words;
752
+ }
753
+
754
+ /*
755
+ Based on https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
756
+
757
+ MIT License
758
+ Copyright (c) 2020 Egor Nepomnyaschih
759
+ Permission is hereby granted, free of charge, to any person obtaining a copy
760
+ of this software and associated documentation files (the "Software"), to deal
761
+ in the Software without restriction, including without limitation the rights
762
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
763
+ copies of the Software, and to permit persons to whom the Software is
764
+ furnished to do so, subject to the following conditions:
765
+ The above copyright notice and this permission notice shall be included in all
766
+ copies or substantial portions of the Software.
767
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
768
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
769
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
770
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
771
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
772
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
773
+ SOFTWARE.
774
+ */
775
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
776
+
777
+ /** @param {Uint8Array} bytes */
778
+ function base64(bytes) {
779
+ const l = bytes.length;
780
+
781
+ let result = '';
782
+ let i;
783
+
784
+ for (i = 2; i < l; i += 3) {
785
+ result += chars[bytes[i - 2] >> 2];
786
+ result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
787
+ result += chars[((bytes[i - 1] & 0x0f) << 2) | (bytes[i] >> 6)];
788
+ result += chars[bytes[i] & 0x3f];
789
+ }
790
+
791
+ if (i === l + 1) {
792
+ // 1 octet yet to write
793
+ result += chars[bytes[i - 2] >> 2];
794
+ result += chars[(bytes[i - 2] & 0x03) << 4];
795
+ result += '==';
796
+ }
797
+
798
+ if (i === l) {
799
+ // 2 octets yet to write
800
+ result += chars[bytes[i - 2] >> 2];
801
+ result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
802
+ result += chars[(bytes[i - 1] & 0x0f) << 2];
803
+ result += '=';
804
+ }
805
+
806
+ return result;
807
+ }
808
+
809
+ /** @type {Promise<void>} */
810
+ let csp_ready;
811
+
812
+ /** @type {() => string} */
813
+ let generate_nonce;
814
+
815
+ /** @type {(input: string) => string} */
816
+ let generate_hash;
817
+
818
+ if (typeof crypto !== 'undefined') {
819
+ const array = new Uint8Array(16);
820
+
821
+ generate_nonce = () => {
822
+ crypto.getRandomValues(array);
823
+ return base64(array);
824
+ };
825
+
826
+ generate_hash = sha256;
827
+ } else {
828
+ // TODO: remove this in favor of web crypto API once we no longer support Node 14
829
+ const name = 'crypto'; // store in a variable to fool esbuild when adapters bundle kit
830
+ csp_ready = import(name).then((crypto) => {
831
+ generate_nonce = () => {
832
+ return crypto.randomBytes(16).toString('base64');
833
+ };
834
+
835
+ generate_hash = (input) => {
836
+ return crypto.createHash('sha256').update(input, 'utf-8').digest().toString('base64');
837
+ };
838
+ });
839
+ }
840
+
841
+ const quoted = new Set([
842
+ 'self',
843
+ 'unsafe-eval',
844
+ 'unsafe-hashes',
845
+ 'unsafe-inline',
846
+ 'none',
847
+ 'strict-dynamic',
848
+ 'report-sample'
849
+ ]);
850
+
851
+ const crypto_pattern = /^(nonce|sha\d\d\d)-/;
852
+
853
+ class Csp {
854
+ /** @type {boolean} */
855
+ #use_hashes;
856
+
857
+ /** @type {boolean} */
858
+ #dev;
859
+
860
+ /** @type {boolean} */
861
+ #script_needs_csp;
862
+
863
+ /** @type {boolean} */
864
+ #style_needs_csp;
865
+
866
+ /** @type {import('types/csp').CspDirectives} */
867
+ #directives;
868
+
869
+ /** @type {import('types/csp').Source[]} */
870
+ #script_src;
871
+
872
+ /** @type {import('types/csp').Source[]} */
873
+ #style_src;
874
+
875
+ /**
876
+ * @param {{
877
+ * mode: string,
878
+ * directives: import('types/csp').CspDirectives
879
+ * }} config
880
+ * @param {{
881
+ * dev: boolean;
882
+ * prerender: boolean;
883
+ * needs_nonce: boolean;
884
+ * }} opts
885
+ */
886
+ constructor({ mode, directives }, { dev, prerender, needs_nonce }) {
887
+ this.#use_hashes = mode === 'hash' || (mode === 'auto' && prerender);
888
+ this.#directives = dev ? { ...directives } : directives; // clone in dev so we can safely mutate
889
+ this.#dev = dev;
890
+
891
+ const d = this.#directives;
892
+
893
+ if (dev) {
894
+ // remove strict-dynamic in dev...
895
+ // TODO reinstate this if we can figure out how to make strict-dynamic work
896
+ // if (d['default-src']) {
897
+ // d['default-src'] = d['default-src'].filter((name) => name !== 'strict-dynamic');
898
+ // if (d['default-src'].length === 0) delete d['default-src'];
899
+ // }
900
+
901
+ // if (d['script-src']) {
902
+ // d['script-src'] = d['script-src'].filter((name) => name !== 'strict-dynamic');
903
+ // if (d['script-src'].length === 0) delete d['script-src'];
904
+ // }
905
+
906
+ const effective_style_src = d['style-src'] || d['default-src'];
907
+
908
+ // ...and add unsafe-inline so we can inject <style> elements
909
+ if (effective_style_src && !effective_style_src.includes('unsafe-inline')) {
910
+ d['style-src'] = [...effective_style_src, 'unsafe-inline'];
911
+ }
912
+ }
913
+
914
+ this.#script_src = [];
915
+ this.#style_src = [];
916
+
917
+ const effective_script_src = d['script-src'] || d['default-src'];
918
+ const effective_style_src = d['style-src'] || d['default-src'];
919
+
920
+ this.#script_needs_csp =
921
+ !!effective_script_src &&
922
+ effective_script_src.filter((value) => value !== 'unsafe-inline').length > 0;
923
+
924
+ this.#style_needs_csp =
925
+ !dev &&
926
+ !!effective_style_src &&
927
+ effective_style_src.filter((value) => value !== 'unsafe-inline').length > 0;
928
+
929
+ this.script_needs_nonce = this.#script_needs_csp && !this.#use_hashes;
930
+ this.style_needs_nonce = this.#style_needs_csp && !this.#use_hashes;
931
+
932
+ if (this.script_needs_nonce || this.style_needs_nonce || needs_nonce) {
933
+ this.nonce = generate_nonce();
934
+ }
935
+ }
936
+
937
+ /** @param {string} content */
938
+ add_script(content) {
939
+ if (this.#script_needs_csp) {
940
+ if (this.#use_hashes) {
941
+ this.#script_src.push(`sha256-${generate_hash(content)}`);
942
+ } else if (this.#script_src.length === 0) {
943
+ this.#script_src.push(`nonce-${this.nonce}`);
944
+ }
945
+ }
946
+ }
947
+
948
+ /** @param {string} content */
949
+ add_style(content) {
950
+ if (this.#style_needs_csp) {
951
+ if (this.#use_hashes) {
952
+ this.#style_src.push(`sha256-${generate_hash(content)}`);
953
+ } else if (this.#style_src.length === 0) {
954
+ this.#style_src.push(`nonce-${this.nonce}`);
955
+ }
956
+ }
957
+ }
958
+
959
+ /** @param {boolean} [is_meta] */
960
+ get_header(is_meta = false) {
961
+ const header = [];
962
+
963
+ // due to browser inconsistencies, we can't append sources to default-src
964
+ // (specifically, Firefox appears to not ignore nonce-{nonce} directives
965
+ // on default-src), so we ensure that script-src and style-src exist
966
+
967
+ const directives = { ...this.#directives };
968
+
969
+ if (this.#style_src.length > 0) {
970
+ directives['style-src'] = [
971
+ ...(directives['style-src'] || directives['default-src'] || []),
972
+ ...this.#style_src
973
+ ];
974
+ }
975
+
976
+ if (this.#script_src.length > 0) {
977
+ directives['script-src'] = [
978
+ ...(directives['script-src'] || directives['default-src'] || []),
979
+ ...this.#script_src
980
+ ];
981
+ }
982
+
983
+ for (const key in directives) {
984
+ if (is_meta && (key === 'frame-ancestors' || key === 'report-uri' || key === 'sandbox')) {
985
+ // these values cannot be used with a <meta> tag
986
+ // TODO warn?
987
+ continue;
988
+ }
989
+
990
+ // @ts-expect-error gimme a break typescript, `key` is obviously a member of directives
991
+ const value = /** @type {string[] | true} */ (directives[key]);
992
+
993
+ if (!value) continue;
994
+
995
+ const directive = [key];
996
+ if (Array.isArray(value)) {
997
+ value.forEach((value) => {
998
+ if (quoted.has(value) || crypto_pattern.test(value)) {
999
+ directive.push(`'${value}'`);
1000
+ } else {
1001
+ directive.push(value);
1002
+ }
1003
+ });
1004
+ }
1005
+
1006
+ header.push(directive.join(' '));
1007
+ }
1008
+
1009
+ return header.join('; ');
1010
+ }
1011
+
1012
+ get_meta() {
1013
+ const content = escape_html_attr(this.get_header(true));
1014
+ return `<meta http-equiv="content-security-policy" content=${content}>`;
1015
+ }
1016
+ }
1017
+
1018
+ // TODO rename this function/module
1019
+
1020
+ const updated = {
1021
+ ...readable(false),
1022
+ check: () => false
1023
+ };
1024
+
1025
+ /**
1026
+ * @param {{
1027
+ * branch: Array<import('./types').Loaded>;
1028
+ * options: import('types/internal').SSROptions;
1029
+ * state: import('types/internal').SSRState;
1030
+ * $session: any;
1031
+ * page_config: { hydrate: boolean, router: boolean };
1032
+ * status: number;
1033
+ * error?: Error;
1034
+ * url: URL;
1035
+ * params: Record<string, string>;
1036
+ * ssr: boolean;
1037
+ * stuff: Record<string, any>;
1038
+ * }} opts
1039
+ */
1040
+ async function render_response({
1041
+ branch,
1042
+ options,
1043
+ state,
1044
+ $session,
1045
+ page_config,
1046
+ status,
1047
+ error,
1048
+ url,
1049
+ params,
1050
+ ssr,
1051
+ stuff
1052
+ }) {
1053
+ if (state.prerender) {
1054
+ if (options.csp.mode === 'nonce') {
1055
+ throw new Error('Cannot use prerendering if config.kit.csp.mode === "nonce"');
1056
+ }
1057
+
1058
+ if (options.template_contains_nonce) {
1059
+ throw new Error('Cannot use prerendering if page template contains %svelte.nonce%');
1060
+ }
1061
+ }
1062
+
1063
+ const stylesheets = new Set(options.manifest._.entry.css);
1064
+ const modulepreloads = new Set(options.manifest._.entry.js);
1065
+ /** @type {Map<string, string>} */
1066
+ const styles = new Map();
1067
+
1068
+ /** @type {Array<{ url: string, body: string, json: string }>} */
1069
+ const serialized_data = [];
1070
+
1071
+ let shadow_props;
1072
+
1073
+ let rendered;
1074
+
1075
+ let is_private = false;
1076
+ let maxage;
1077
+
1078
+ if (error) {
1079
+ error.stack = options.get_stack(error);
1080
+ }
1081
+
1082
+ if (ssr) {
1083
+ branch.forEach(({ node, props, loaded, fetched, uses_credentials }) => {
1084
+ if (node.css) node.css.forEach((url) => stylesheets.add(url));
1085
+ if (node.js) node.js.forEach((url) => modulepreloads.add(url));
1086
+ if (node.styles) Object.entries(node.styles).forEach(([k, v]) => styles.set(k, v));
1087
+
1088
+ // TODO probably better if `fetched` wasn't populated unless `hydrate`
1089
+ if (fetched && page_config.hydrate) serialized_data.push(...fetched);
1090
+ if (props) shadow_props = props;
1091
+
1092
+ if (uses_credentials) is_private = true;
1093
+
1094
+ maxage = loaded.maxage;
1095
+ });
1096
+
1097
+ const session = writable($session);
1098
+
1099
+ /** @type {Record<string, any>} */
1100
+ const props = {
1101
+ stores: {
1102
+ page: writable(null),
1103
+ navigating: writable(null),
1104
+ session,
1105
+ updated
1106
+ },
1107
+ page: {
1108
+ url: state.prerender ? create_prerendering_url_proxy(url) : url,
1109
+ params,
1110
+ status,
1111
+ error,
1112
+ stuff
1113
+ },
1114
+ components: branch.map(({ node }) => node.module.default)
1115
+ };
1116
+
1117
+ // TODO remove this for 1.0
1118
+ /**
1119
+ * @param {string} property
1120
+ * @param {string} replacement
1121
+ */
1122
+ const print_error = (property, replacement) => {
1123
+ Object.defineProperty(props.page, property, {
1124
+ get: () => {
1125
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
1126
+ }
1127
+ });
1128
+ };
1129
+
1130
+ print_error('origin', 'origin');
1131
+ print_error('path', 'pathname');
1132
+ print_error('query', 'searchParams');
1133
+
1134
+ // props_n (instead of props[n]) makes it easy to avoid
1135
+ // unnecessary updates for layout components
1136
+ for (let i = 0; i < branch.length; i += 1) {
1137
+ props[`props_${i}`] = await branch[i].loaded.props;
1138
+ }
1139
+
1140
+ let session_tracking_active = false;
1141
+ const unsubscribe = session.subscribe(() => {
1142
+ if (session_tracking_active) is_private = true;
1143
+ });
1144
+ session_tracking_active = true;
1145
+
1146
+ try {
1147
+ rendered = options.root.render(props);
1148
+ } finally {
1149
+ unsubscribe();
1150
+ }
1151
+ } else {
1152
+ rendered = { head: '', html: '', css: { code: '', map: null } };
1153
+ }
1154
+
1155
+ let { head, html: body } = rendered;
1156
+
1157
+ const inlined_style = Array.from(styles.values()).join('\n');
1158
+
1159
+ await csp_ready;
1160
+ const csp = new Csp(options.csp, {
1161
+ dev: options.dev,
1162
+ prerender: !!state.prerender,
1163
+ needs_nonce: options.template_contains_nonce
1164
+ });
1165
+
1166
+ const target = hash(body);
1167
+
1168
+ // prettier-ignore
1169
+ const init_app = `
1170
+ import { start } from ${s(options.prefix + options.manifest._.entry.file)};
1171
+ start({
1172
+ target: document.querySelector('[data-hydrate="${target}"]').parentNode,
1173
+ paths: ${s(options.paths)},
1174
+ session: ${try_serialize($session, (error) => {
1175
+ throw new Error(`Failed to serialize session data: ${error.message}`);
1176
+ })},
1177
+ route: ${!!page_config.router},
1178
+ spa: ${!ssr},
1179
+ trailing_slash: ${s(options.trailing_slash)},
1180
+ hydrate: ${ssr && page_config.hydrate ? `{
1181
+ status: ${status},
1182
+ error: ${serialize_error(error)},
1183
+ nodes: [
1184
+ ${(branch || [])
1185
+ .map(({ node }) => `import(${s(options.prefix + node.entry)})`)
1186
+ .join(',\n\t\t\t\t\t\t')}
1187
+ ],
1188
+ url: new URL(${s(url.href)}),
1189
+ params: ${devalue(params)}
1190
+ }` : 'null'}
1191
+ });
1192
+ `;
1193
+
1194
+ const init_service_worker = `
1195
+ if ('serviceWorker' in navigator) {
1196
+ navigator.serviceWorker.register('${options.service_worker}');
1197
+ }
1198
+ `;
1199
+
1200
+ if (options.amp) {
1201
+ head += `
1202
+ <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style>
1203
+ <noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
1204
+ <script async src="https://cdn.ampproject.org/v0.js"></script>
1205
+
1206
+ <style amp-custom>${inlined_style}\n${rendered.css.code}</style>`;
1207
+
1208
+ if (options.service_worker) {
1209
+ head +=
1210
+ '<script async custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js"></script>';
1211
+
1212
+ body += `<amp-install-serviceworker src="${options.service_worker}" layout="nodisplay"></amp-install-serviceworker>`;
1213
+ }
1214
+ } else {
1215
+ if (inlined_style) {
1216
+ const attributes = [];
1217
+ if (options.dev) attributes.push(' data-svelte');
1218
+ if (csp.style_needs_nonce) attributes.push(` nonce="${csp.nonce}"`);
1219
+
1220
+ csp.add_style(inlined_style);
1221
+
1222
+ head += `\n\t<style${attributes.join('')}>${inlined_style}</style>`;
1223
+ }
1224
+
1225
+ // prettier-ignore
1226
+ head += Array.from(stylesheets)
1227
+ .map((dep) => {
1228
+ const attributes = [
1229
+ 'rel="stylesheet"',
1230
+ `href="${options.prefix + dep}"`
1231
+ ];
1232
+
1233
+ if (csp.style_needs_nonce) {
1234
+ attributes.push(`nonce="${csp.nonce}"`);
1235
+ }
1236
+
1237
+ if (styles.has(dep)) {
1238
+ attributes.push('disabled', 'media="(max-width: 0)"');
1239
+ }
1240
+
1241
+ return `\n\t<link ${attributes.join(' ')}>`;
1242
+ })
1243
+ .join('');
1244
+
1245
+ if (page_config.router || page_config.hydrate) {
1246
+ head += Array.from(modulepreloads)
1247
+ .map((dep) => `\n\t<link rel="modulepreload" href="${options.prefix + dep}">`)
1248
+ .join('');
1249
+
1250
+ const attributes = ['type="module"', `data-hydrate="${target}"`];
1251
+
1252
+ csp.add_script(init_app);
1253
+
1254
+ if (csp.script_needs_nonce) {
1255
+ attributes.push(`nonce="${csp.nonce}"`);
1256
+ }
1257
+
1258
+ body += `\n\t\t<script ${attributes.join(' ')}>${init_app}</script>`;
1259
+
1260
+ // prettier-ignore
1261
+ body += serialized_data
1262
+ .map(({ url, body, json }) => {
1263
+ let attributes = `type="application/json" data-type="svelte-data" data-url=${escape_html_attr(url)}`;
1264
+ if (body) attributes += ` data-body="${hash(body)}"`;
1265
+
1266
+ return `<script ${attributes}>${json}</script>`;
1267
+ })
1268
+ .join('\n\t');
1269
+
1270
+ if (shadow_props) {
1271
+ // prettier-ignore
1272
+ body += `<script type="application/json" data-type="svelte-props">${s(shadow_props)}</script>`;
1273
+ }
1274
+ }
1275
+
1276
+ if (options.service_worker) {
1277
+ // always include service worker unless it's turned off explicitly
1278
+ csp.add_script(init_service_worker);
1279
+
1280
+ head += `
1281
+ <script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ''}>${init_service_worker}</script>`;
1282
+ }
1283
+ }
1284
+
1285
+ if (state.prerender) {
1286
+ const http_equiv = [];
1287
+
1288
+ const csp_headers = csp.get_meta();
1289
+ if (csp_headers) {
1290
+ http_equiv.push(csp_headers);
1291
+ }
1292
+
1293
+ if (maxage) {
1294
+ http_equiv.push(`<meta http-equiv="cache-control" content="max-age=${maxage}">`);
1295
+ }
1296
+
1297
+ if (http_equiv.length > 0) {
1298
+ head = http_equiv.join('\n') + head;
1299
+ }
1300
+ }
1301
+
1302
+ const segments = url.pathname.slice(options.paths.base.length).split('/').slice(2);
1303
+ const assets =
1304
+ options.paths.assets || (segments.length > 0 ? segments.map(() => '..').join('/') : '.');
1305
+
1306
+ const html = options.template({ head, body, assets, nonce: /** @type {string} */ (csp.nonce) });
1307
+
1308
+ const headers = new Headers({
1309
+ 'content-type': 'text/html',
1310
+ etag: `"${hash(html)}"`
1311
+ });
1312
+
1313
+ if (maxage) {
1314
+ headers.set('cache-control', `${is_private ? 'private' : 'public'}, max-age=${maxage}`);
1315
+ }
1316
+
1317
+ if (!options.floc) {
1318
+ headers.set('permissions-policy', 'interest-cohort=()');
1319
+ }
1320
+
1321
+ if (!state.prerender) {
1322
+ const csp_header = csp.get_header();
1323
+ if (csp_header) {
1324
+ headers.set('content-security-policy', csp_header);
1325
+ }
1326
+ }
1327
+
1328
+ return new Response(html, {
1329
+ status,
1330
+ headers
1331
+ });
1332
+ }
1333
+
1334
+ /**
1335
+ * @param {any} data
1336
+ * @param {(error: Error) => void} [fail]
1337
+ */
1338
+ function try_serialize(data, fail) {
1339
+ try {
1340
+ return devalue(data);
1341
+ } catch (err) {
1342
+ if (fail) fail(coalesce_to_error(err));
1343
+ return null;
1344
+ }
1345
+ }
1346
+
1347
+ // Ensure we return something truthy so the client will not re-render the page over the error
1348
+
1349
+ /** @param {(Error & {frame?: string} & {loc?: object}) | undefined | null} error */
1350
+ function serialize_error(error) {
1351
+ if (!error) return null;
1352
+ let serialized = try_serialize(error);
1353
+ if (!serialized) {
1354
+ const { name, message, stack } = error;
1355
+ serialized = try_serialize({ ...error, name, message, stack });
1356
+ }
1357
+ if (!serialized) {
1358
+ serialized = '{}';
1359
+ }
1360
+ return serialized;
1361
+ }
1362
+
1363
+ /**
1364
+ * @param {import('types/page').LoadOutput} loaded
1365
+ * @returns {import('types/internal').NormalizedLoadOutput}
1366
+ */
1367
+ function normalize(loaded) {
1368
+ const has_error_status =
1369
+ loaded.status && loaded.status >= 400 && loaded.status <= 599 && !loaded.redirect;
1370
+ if (loaded.error || has_error_status) {
1371
+ const status = loaded.status;
1372
+
1373
+ if (!loaded.error && has_error_status) {
1374
+ return {
1375
+ status: status || 500,
1376
+ error: new Error()
1377
+ };
1378
+ }
1379
+
1380
+ const error = typeof loaded.error === 'string' ? new Error(loaded.error) : loaded.error;
1381
+
1382
+ if (!(error instanceof Error)) {
1383
+ return {
1384
+ status: 500,
1385
+ error: new Error(
1386
+ `"error" property returned from load() must be a string or instance of Error, received type "${typeof error}"`
1387
+ )
1388
+ };
1389
+ }
1390
+
1391
+ if (!status || status < 400 || status > 599) {
1392
+ console.warn('"error" returned from load() without a valid status code — defaulting to 500');
1393
+ return { status: 500, error };
1394
+ }
1395
+
1396
+ return { status, error };
1397
+ }
1398
+
1399
+ if (loaded.redirect) {
1400
+ if (!loaded.status || Math.floor(loaded.status / 100) !== 3) {
1401
+ return {
1402
+ status: 500,
1403
+ error: new Error(
1404
+ '"redirect" property returned from load() must be accompanied by a 3xx status code'
1405
+ )
1406
+ };
1407
+ }
1408
+
1409
+ if (typeof loaded.redirect !== 'string') {
1410
+ return {
1411
+ status: 500,
1412
+ error: new Error('"redirect" property returned from load() must be a string')
1413
+ };
1414
+ }
1415
+ }
1416
+
1417
+ // TODO remove before 1.0
1418
+ if (/** @type {any} */ (loaded).context) {
1419
+ throw new Error(
1420
+ 'You are returning "context" from a load function. ' +
1421
+ '"context" was renamed to "stuff", please adjust your code accordingly.'
1422
+ );
1423
+ }
1424
+
1425
+ return /** @type {import('types/internal').NormalizedLoadOutput} */ (loaded);
1426
+ }
1427
+
1428
+ const absolute = /^([a-z]+:)?\/?\//;
1429
+ const scheme = /^[a-z]+:/;
1430
+
1431
+ /**
1432
+ * @param {string} base
1433
+ * @param {string} path
1434
+ */
1435
+ function resolve(base, path) {
1436
+ if (scheme.test(path)) return path;
1437
+
1438
+ const base_match = absolute.exec(base);
1439
+ const path_match = absolute.exec(path);
1440
+
1441
+ if (!base_match) {
1442
+ throw new Error(`bad base path: "${base}"`);
1443
+ }
1444
+
1445
+ const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
1446
+ const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
1447
+
1448
+ baseparts.pop();
1449
+
1450
+ for (let i = 0; i < pathparts.length; i += 1) {
1451
+ const part = pathparts[i];
1452
+ if (part === '.') continue;
1453
+ else if (part === '..') baseparts.pop();
1454
+ else baseparts.push(part);
1455
+ }
1456
+
1457
+ const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
1458
+
1459
+ return `${prefix}${baseparts.join('/')}`;
1460
+ }
1461
+
1462
+ /** @param {string} path */
1463
+ function is_root_relative(path) {
1464
+ return path[0] === '/' && path[1] !== '/';
1465
+ }
1466
+
1467
+ /**
1468
+ * @param {{
1469
+ * event: import('types/hooks').RequestEvent;
1470
+ * options: import('types/internal').SSROptions;
1471
+ * state: import('types/internal').SSRState;
1472
+ * route: import('types/internal').SSRPage | null;
1473
+ * url: URL;
1474
+ * params: Record<string, string>;
1475
+ * node: import('types/internal').SSRNode;
1476
+ * $session: any;
1477
+ * stuff: Record<string, any>;
1478
+ * is_error: boolean;
1479
+ * is_leaf: boolean;
1480
+ * status?: number;
1481
+ * error?: Error;
1482
+ * }} opts
1483
+ * @returns {Promise<import('./types').Loaded | undefined>} undefined for fallthrough
1484
+ */
1485
+ async function load_node({
1486
+ event,
1487
+ options,
1488
+ state,
1489
+ route,
1490
+ url,
1491
+ params,
1492
+ node,
1493
+ $session,
1494
+ stuff,
1495
+ is_error,
1496
+ is_leaf,
1497
+ status,
1498
+ error
1499
+ }) {
1500
+ const { module } = node;
1501
+
1502
+ let uses_credentials = false;
1503
+
1504
+ /**
1505
+ * @type {Array<{
1506
+ * url: string;
1507
+ * body: string;
1508
+ * json: string;
1509
+ * }>}
1510
+ */
1511
+ const fetched = [];
1512
+
1513
+ /**
1514
+ * @type {string[]}
1515
+ */
1516
+ let set_cookie_headers = [];
1517
+
1518
+ /** @type {import('types/helper').Either<import('types/endpoint').Fallthrough, import('types/page').LoadOutput>} */
1519
+ let loaded;
1520
+
1521
+ /** @type {import('types/endpoint').ShadowData} */
1522
+ const shadow = is_leaf
1523
+ ? await load_shadow_data(
1524
+ /** @type {import('types/internal').SSRPage} */ (route),
1525
+ event,
1526
+ !!state.prerender
1527
+ )
1528
+ : {};
1529
+
1530
+ if (shadow.fallthrough) return;
1531
+
1532
+ if (shadow.cookies) {
1533
+ set_cookie_headers.push(...shadow.cookies);
1534
+ }
1535
+
1536
+ if (shadow.error) {
1537
+ loaded = {
1538
+ status: shadow.status,
1539
+ error: shadow.error
1540
+ };
1541
+ } else if (shadow.redirect) {
1542
+ loaded = {
1543
+ status: shadow.status,
1544
+ redirect: shadow.redirect
1545
+ };
1546
+ } else if (module.load) {
1547
+ /** @type {import('types/page').LoadInput | import('types/page').ErrorLoadInput} */
1548
+ const load_input = {
1549
+ url: state.prerender ? create_prerendering_url_proxy(url) : url,
1550
+ params,
1551
+ props: shadow.body || {},
1552
+ get session() {
1553
+ uses_credentials = true;
1554
+ return $session;
1555
+ },
1556
+ /**
1557
+ * @param {RequestInfo} resource
1558
+ * @param {RequestInit} opts
1559
+ */
1560
+ fetch: async (resource, opts = {}) => {
1561
+ /** @type {string} */
1562
+ let requested;
1563
+
1564
+ if (typeof resource === 'string') {
1565
+ requested = resource;
1566
+ } else {
1567
+ requested = resource.url;
1568
+
1569
+ opts = {
1570
+ method: resource.method,
1571
+ headers: resource.headers,
1572
+ body: resource.body,
1573
+ mode: resource.mode,
1574
+ credentials: resource.credentials,
1575
+ cache: resource.cache,
1576
+ redirect: resource.redirect,
1577
+ referrer: resource.referrer,
1578
+ integrity: resource.integrity,
1579
+ ...opts
1580
+ };
1581
+ }
1582
+
1583
+ opts.headers = new Headers(opts.headers);
1584
+
1585
+ // merge headers from request
1586
+ for (const [key, value] of event.request.headers) {
1587
+ if (
1588
+ key !== 'authorization' &&
1589
+ key !== 'cookie' &&
1590
+ key !== 'host' &&
1591
+ key !== 'if-none-match' &&
1592
+ !opts.headers.has(key)
1593
+ ) {
1594
+ opts.headers.set(key, value);
1595
+ }
1596
+ }
1597
+
1598
+ opts.headers.set('referer', event.url.href);
1599
+
1600
+ const resolved = resolve(event.url.pathname, requested.split('?')[0]);
1601
+
1602
+ /** @type {Response} */
1603
+ let response;
1604
+
1605
+ /** @type {import('types/internal').PrerenderDependency} */
1606
+ let dependency;
1607
+
1608
+ // handle fetch requests for static assets. e.g. prebaked data, etc.
1609
+ // we need to support everything the browser's fetch supports
1610
+ const prefix = options.paths.assets || options.paths.base;
1611
+ const filename = decodeURIComponent(
1612
+ resolved.startsWith(prefix) ? resolved.slice(prefix.length) : resolved
1613
+ ).slice(1);
1614
+ const filename_html = `${filename}/index.html`; // path may also match path/index.html
1615
+
1616
+ const is_asset = options.manifest.assets.has(filename);
1617
+ const is_asset_html = options.manifest.assets.has(filename_html);
1618
+
1619
+ if (is_asset || is_asset_html) {
1620
+ const file = is_asset ? filename : filename_html;
1621
+
1622
+ if (options.read) {
1623
+ const type = is_asset
1624
+ ? options.manifest._.mime[filename.slice(filename.lastIndexOf('.'))]
1625
+ : 'text/html';
1626
+
1627
+ response = new Response(options.read(file), {
1628
+ headers: type ? { 'content-type': type } : {}
1629
+ });
1630
+ } else {
1631
+ response = await fetch(`${url.origin}/${file}`, /** @type {RequestInit} */ (opts));
1632
+ }
1633
+ } else if (is_root_relative(resolved)) {
1634
+ if (opts.credentials !== 'omit') {
1635
+ uses_credentials = true;
1636
+
1637
+ const cookie = event.request.headers.get('cookie');
1638
+ const authorization = event.request.headers.get('authorization');
1639
+
1640
+ if (cookie) {
1641
+ opts.headers.set('cookie', cookie);
1642
+ }
1643
+
1644
+ if (authorization && !opts.headers.has('authorization')) {
1645
+ opts.headers.set('authorization', authorization);
1646
+ }
1647
+ }
1648
+
1649
+ if (opts.body && typeof opts.body !== 'string') {
1650
+ // per https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, this can be a
1651
+ // Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object.
1652
+ // non-string bodies are irksome to deal with, but luckily aren't particularly useful
1653
+ // in this context anyway, so we take the easy route and ban them
1654
+ throw new Error('Request body must be a string');
1655
+ }
1656
+
1657
+ response = await respond(new Request(new URL(requested, event.url).href, opts), options, {
1658
+ fetched: requested,
1659
+ initiator: route
1660
+ });
1661
+
1662
+ if (state.prerender) {
1663
+ dependency = { response, body: null };
1664
+ state.prerender.dependencies.set(resolved, dependency);
1665
+ }
1666
+ } else {
1667
+ // external
1668
+ if (resolved.startsWith('//')) {
1669
+ throw new Error(
1670
+ `Cannot request protocol-relative URL (${requested}) in server-side fetch`
1671
+ );
1672
+ }
1673
+
1674
+ // external fetch
1675
+ // allow cookie passthrough for "same-origin"
1676
+ // if SvelteKit is serving my.domain.com:
1677
+ // - domain.com WILL NOT receive cookies
1678
+ // - my.domain.com WILL receive cookies
1679
+ // - api.domain.dom WILL NOT receive cookies
1680
+ // - sub.my.domain.com WILL receive cookies
1681
+ // ports do not affect the resolution
1682
+ // leading dot prevents mydomain.com matching domain.com
1683
+ if (
1684
+ `.${new URL(requested).hostname}`.endsWith(`.${event.url.hostname}`) &&
1685
+ opts.credentials !== 'omit'
1686
+ ) {
1687
+ uses_credentials = true;
1688
+
1689
+ const cookie = event.request.headers.get('cookie');
1690
+ if (cookie) opts.headers.set('cookie', cookie);
1691
+ }
1692
+
1693
+ const external_request = new Request(requested, /** @type {RequestInit} */ (opts));
1694
+ response = await options.hooks.externalFetch.call(null, external_request);
1695
+ }
1696
+
1697
+ const proxy = new Proxy(response, {
1698
+ get(response, key, _receiver) {
1699
+ async function text() {
1700
+ const body = await response.text();
1701
+
1702
+ /** @type {import('types/helper').ResponseHeaders} */
1703
+ const headers = {};
1704
+ for (const [key, value] of response.headers) {
1705
+ if (key === 'set-cookie') {
1706
+ set_cookie_headers = set_cookie_headers.concat(value);
1707
+ } else if (key !== 'etag') {
1708
+ headers[key] = value;
1709
+ }
1710
+ }
1711
+
1712
+ if (!opts.body || typeof opts.body === 'string') {
1713
+ // prettier-ignore
1714
+ fetched.push({
1715
+ url: requested,
1716
+ body: /** @type {string} */ (opts.body),
1717
+ json: `{"status":${response.status},"statusText":${s(response.statusText)},"headers":${s(headers)},"body":"${escape_json_string_in_html(body)}"}`
1718
+ });
1719
+ }
1720
+
1721
+ if (dependency) {
1722
+ dependency.body = body;
1723
+ }
1724
+
1725
+ return body;
1726
+ }
1727
+
1728
+ if (key === 'arrayBuffer') {
1729
+ return async () => {
1730
+ const buffer = await response.arrayBuffer();
1731
+
1732
+ if (dependency) {
1733
+ dependency.body = new Uint8Array(buffer);
1734
+ }
1735
+
1736
+ // TODO should buffer be inlined into the page (albeit base64'd)?
1737
+ // any conditions in which it shouldn't be?
1738
+
1739
+ return buffer;
1740
+ };
1741
+ }
1742
+
1743
+ if (key === 'text') {
1744
+ return text;
1745
+ }
1746
+
1747
+ if (key === 'json') {
1748
+ return async () => {
1749
+ return JSON.parse(await text());
1750
+ };
1751
+ }
1752
+
1753
+ // TODO arrayBuffer?
1754
+
1755
+ return Reflect.get(response, key, response);
1756
+ }
1757
+ });
1758
+
1759
+ return proxy;
1760
+ },
1761
+ stuff: { ...stuff }
1762
+ };
1763
+
1764
+ if (options.dev) {
1765
+ // TODO remove this for 1.0
1766
+ Object.defineProperty(load_input, 'page', {
1767
+ get: () => {
1768
+ throw new Error('`page` in `load` functions has been replaced by `url` and `params`');
1769
+ }
1770
+ });
1771
+ }
1772
+
1773
+ if (is_error) {
1774
+ /** @type {import('types/page').ErrorLoadInput} */ (load_input).status = status;
1775
+ /** @type {import('types/page').ErrorLoadInput} */ (load_input).error = error;
1776
+ }
1777
+
1778
+ loaded = await module.load.call(null, load_input);
1779
+
1780
+ if (!loaded) {
1781
+ throw new Error(`load function must return a value${options.dev ? ` (${node.entry})` : ''}`);
1782
+ }
1783
+ } else if (shadow.body) {
1784
+ loaded = {
1785
+ props: shadow.body
1786
+ };
1787
+ } else {
1788
+ loaded = {};
1789
+ }
1790
+
1791
+ if (loaded.fallthrough && !is_error) {
1792
+ return;
1793
+ }
1794
+
1795
+ // generate __data.json files when prerendering
1796
+ if (shadow.body && state.prerender) {
1797
+ const pathname = `${event.url.pathname}/__data.json`;
1798
+
1799
+ const dependency = {
1800
+ response: new Response(undefined),
1801
+ body: JSON.stringify(shadow.body)
1802
+ };
1803
+
1804
+ state.prerender.dependencies.set(pathname, dependency);
1805
+ }
1806
+
1807
+ return {
1808
+ node,
1809
+ props: shadow.body,
1810
+ loaded: normalize(loaded),
1811
+ stuff: loaded.stuff || stuff,
1812
+ fetched,
1813
+ set_cookie_headers,
1814
+ uses_credentials
1815
+ };
1816
+ }
1817
+
1818
+ /**
1819
+ *
1820
+ * @param {import('types/internal').SSRPage} route
1821
+ * @param {import('types/hooks').RequestEvent} event
1822
+ * @param {boolean} prerender
1823
+ * @returns {Promise<import('types/endpoint').ShadowData>}
1824
+ */
1825
+ async function load_shadow_data(route, event, prerender) {
1826
+ if (!route.shadow) return {};
1827
+
1828
+ try {
1829
+ const mod = await route.shadow();
1830
+
1831
+ if (prerender && (mod.post || mod.put || mod.del || mod.patch)) {
1832
+ throw new Error('Cannot prerender pages that have shadow endpoints with mutative methods');
1833
+ }
1834
+
1835
+ const method = event.request.method.toLowerCase().replace('delete', 'del');
1836
+ const handler = mod[method];
1837
+
1838
+ if (!handler) {
1839
+ return {
1840
+ status: 405,
1841
+ error: new Error(`${method} method not allowed`)
1842
+ };
1843
+ }
1844
+
1845
+ /** @type {import('types/endpoint').ShadowData} */
1846
+ const data = {
1847
+ status: 200,
1848
+ cookies: [],
1849
+ body: {}
1850
+ };
1851
+
1852
+ if (method !== 'get') {
1853
+ const result = await handler(event);
1854
+
1855
+ if (result.fallthrough) return result;
1856
+
1857
+ const { status = 200, headers = {}, body = {} } = result;
1858
+
1859
+ validate_shadow_output(headers, body);
1860
+
1861
+ if (headers['set-cookie']) {
1862
+ /** @type {string[]} */ (data.cookies).push(...headers['set-cookie']);
1863
+ }
1864
+
1865
+ // Redirects are respected...
1866
+ if (status >= 300 && status < 400) {
1867
+ return {
1868
+ status,
1869
+ redirect: /** @type {string} */ (
1870
+ headers instanceof Headers ? headers.get('location') : headers.location
1871
+ )
1872
+ };
1873
+ }
1874
+
1875
+ // ...but 4xx and 5xx status codes _don't_ result in the error page
1876
+ // rendering for non-GET requests — instead, we allow the page
1877
+ // to render with any validation errors etc that were returned
1878
+ data.status = status;
1879
+ data.body = body;
1880
+ }
1881
+
1882
+ if (mod.get) {
1883
+ const result = await mod.get.call(null, event);
1884
+
1885
+ if (result.fallthrough) return result;
1886
+
1887
+ const { status = 200, headers = {}, body = {} } = result;
1888
+
1889
+ validate_shadow_output(headers, body);
1890
+
1891
+ if (headers['set-cookie']) {
1892
+ /** @type {string[]} */ (data.cookies).push(...headers['set-cookie']);
1893
+ }
1894
+
1895
+ if (status >= 400) {
1896
+ return {
1897
+ status,
1898
+ error: new Error('Failed to load data')
1899
+ };
1900
+ }
1901
+
1902
+ if (status >= 300) {
1903
+ return {
1904
+ status,
1905
+ redirect: /** @type {string} */ (
1906
+ headers instanceof Headers ? headers.get('location') : headers.location
1907
+ )
1908
+ };
1909
+ }
1910
+
1911
+ data.body = { ...body, ...data.body };
1912
+ }
1913
+
1914
+ return data;
1915
+ } catch (e) {
1916
+ return {
1917
+ status: 500,
1918
+ error: coalesce_to_error(e)
1919
+ };
1920
+ }
1921
+ }
1922
+
1923
+ /**
1924
+ * @param {Headers | Partial<import('types/helper').ResponseHeaders>} headers
1925
+ * @param {import('types/helper').JSONValue} body
1926
+ */
1927
+ function validate_shadow_output(headers, body) {
1928
+ if (headers instanceof Headers && headers.has('set-cookie')) {
1929
+ throw new Error(
1930
+ 'Shadow endpoint request handler cannot use Headers interface with Set-Cookie headers'
1931
+ );
1932
+ }
1933
+
1934
+ if (!is_pojo(body)) {
1935
+ throw new Error('Body returned from shadow endpoint request handler must be a plain object');
1936
+ }
1937
+ }
1938
+
1939
+ /**
1940
+ * @typedef {import('./types.js').Loaded} Loaded
1941
+ * @typedef {import('types/internal').SSROptions} SSROptions
1942
+ * @typedef {import('types/internal').SSRState} SSRState
1943
+ */
1944
+
1945
+ /**
1946
+ * @param {{
1947
+ * event: import('types/hooks').RequestEvent;
1948
+ * options: SSROptions;
1949
+ * state: SSRState;
1950
+ * $session: any;
1951
+ * status: number;
1952
+ * error: Error;
1953
+ * ssr: boolean;
1954
+ * }} opts
1955
+ */
1956
+ async function respond_with_error({ event, options, state, $session, status, error, ssr }) {
1957
+ try {
1958
+ const default_layout = await options.manifest._.nodes[0](); // 0 is always the root layout
1959
+ const default_error = await options.manifest._.nodes[1](); // 1 is always the root error
1960
+
1961
+ /** @type {Record<string, string>} */
1962
+ const params = {}; // error page has no params
1963
+
1964
+ const layout_loaded = /** @type {Loaded} */ (
1965
+ await load_node({
1966
+ event,
1967
+ options,
1968
+ state,
1969
+ route: null,
1970
+ url: event.url, // TODO this is redundant, no?
1971
+ params,
1972
+ node: default_layout,
1973
+ $session,
1974
+ stuff: {},
1975
+ is_error: false,
1976
+ is_leaf: false
1977
+ })
1978
+ );
1979
+
1980
+ const error_loaded = /** @type {Loaded} */ (
1981
+ await load_node({
1982
+ event,
1983
+ options,
1984
+ state,
1985
+ route: null,
1986
+ url: event.url,
1987
+ params,
1988
+ node: default_error,
1989
+ $session,
1990
+ stuff: layout_loaded ? layout_loaded.stuff : {},
1991
+ is_error: true,
1992
+ is_leaf: false,
1993
+ status,
1994
+ error
1995
+ })
1996
+ );
1997
+
1998
+ return await render_response({
1999
+ options,
2000
+ state,
2001
+ $session,
2002
+ page_config: {
2003
+ hydrate: options.hydrate,
2004
+ router: options.router
2005
+ },
2006
+ stuff: error_loaded.stuff,
2007
+ status,
2008
+ error,
2009
+ branch: [layout_loaded, error_loaded],
2010
+ url: event.url,
2011
+ params,
2012
+ ssr
2013
+ });
2014
+ } catch (err) {
2015
+ const error = coalesce_to_error(err);
2016
+
2017
+ options.handle_error(error, event);
2018
+
2019
+ return new Response(error.stack, {
2020
+ status: 500
2021
+ });
2022
+ }
2023
+ }
2024
+
2025
+ /**
2026
+ * @typedef {import('./types.js').Loaded} Loaded
2027
+ * @typedef {import('types/internal').SSRNode} SSRNode
2028
+ * @typedef {import('types/internal').SSROptions} SSROptions
2029
+ * @typedef {import('types/internal').SSRState} SSRState
2030
+ */
2031
+
2032
+ /**
2033
+ * @param {{
2034
+ * event: import('types/hooks').RequestEvent;
2035
+ * options: SSROptions;
2036
+ * state: SSRState;
2037
+ * $session: any;
2038
+ * route: import('types/internal').SSRPage;
2039
+ * params: Record<string, string>;
2040
+ * ssr: boolean;
2041
+ * }} opts
2042
+ * @returns {Promise<Response | undefined>}
2043
+ */
2044
+ async function respond$1(opts) {
2045
+ const { event, options, state, $session, route, ssr } = opts;
2046
+
2047
+ /** @type {Array<SSRNode | undefined>} */
2048
+ let nodes;
2049
+
2050
+ if (!ssr) {
2051
+ return await render_response({
2052
+ ...opts,
2053
+ branch: [],
2054
+ page_config: {
2055
+ hydrate: true,
2056
+ router: true
2057
+ },
2058
+ status: 200,
2059
+ url: event.url,
2060
+ stuff: {}
2061
+ });
2062
+ }
2063
+
2064
+ try {
2065
+ nodes = await Promise.all(
2066
+ route.a.map((n) => options.manifest._.nodes[n] && options.manifest._.nodes[n]())
2067
+ );
2068
+ } catch (err) {
2069
+ const error = coalesce_to_error(err);
2070
+
2071
+ options.handle_error(error, event);
2072
+
2073
+ return await respond_with_error({
2074
+ event,
2075
+ options,
2076
+ state,
2077
+ $session,
2078
+ status: 500,
2079
+ error,
2080
+ ssr
2081
+ });
2082
+ }
2083
+
2084
+ // the leaf node will be present. only layouts may be undefined
2085
+ const leaf = /** @type {SSRNode} */ (nodes[nodes.length - 1]).module;
2086
+
2087
+ let page_config = get_page_config(leaf, options);
2088
+
2089
+ if (!leaf.prerender && state.prerender && !state.prerender.all) {
2090
+ // if the page has `export const prerender = true`, continue,
2091
+ // otherwise bail out at this point
2092
+ return new Response(undefined, {
2093
+ status: 204
2094
+ });
2095
+ }
2096
+
2097
+ /** @type {Array<Loaded>} */
2098
+ let branch = [];
2099
+
2100
+ /** @type {number} */
2101
+ let status = 200;
2102
+
2103
+ /** @type {Error|undefined} */
2104
+ let error;
2105
+
2106
+ /** @type {string[]} */
2107
+ let set_cookie_headers = [];
2108
+
2109
+ let stuff = {};
2110
+
2111
+ ssr: if (ssr) {
2112
+ for (let i = 0; i < nodes.length; i += 1) {
2113
+ const node = nodes[i];
2114
+
2115
+ /** @type {Loaded | undefined} */
2116
+ let loaded;
2117
+
2118
+ if (node) {
2119
+ try {
2120
+ loaded = await load_node({
2121
+ ...opts,
2122
+ url: event.url,
2123
+ node,
2124
+ stuff,
2125
+ is_error: false,
2126
+ is_leaf: i === nodes.length - 1
2127
+ });
2128
+
2129
+ if (!loaded) return;
2130
+
2131
+ set_cookie_headers = set_cookie_headers.concat(loaded.set_cookie_headers);
2132
+
2133
+ if (loaded.loaded.redirect) {
2134
+ return with_cookies(
2135
+ new Response(undefined, {
2136
+ status: loaded.loaded.status,
2137
+ headers: {
2138
+ location: loaded.loaded.redirect
2139
+ }
2140
+ }),
2141
+ set_cookie_headers
2142
+ );
2143
+ }
2144
+
2145
+ if (loaded.loaded.error) {
2146
+ ({ status, error } = loaded.loaded);
2147
+ }
2148
+ } catch (err) {
2149
+ const e = coalesce_to_error(err);
2150
+
2151
+ options.handle_error(e, event);
2152
+
2153
+ status = 500;
2154
+ error = e;
2155
+ }
2156
+
2157
+ if (loaded && !error) {
2158
+ branch.push(loaded);
2159
+ }
2160
+
2161
+ if (error) {
2162
+ while (i--) {
2163
+ if (route.b[i]) {
2164
+ const error_node = await options.manifest._.nodes[route.b[i]]();
2165
+
2166
+ /** @type {Loaded} */
2167
+ let node_loaded;
2168
+ let j = i;
2169
+ while (!(node_loaded = branch[j])) {
2170
+ j -= 1;
2171
+ }
2172
+
2173
+ try {
2174
+ const error_loaded = /** @type {import('./types').Loaded} */ (
2175
+ await load_node({
2176
+ ...opts,
2177
+ url: event.url,
2178
+ node: error_node,
2179
+ stuff: node_loaded.stuff,
2180
+ is_error: true,
2181
+ is_leaf: false,
2182
+ status,
2183
+ error
2184
+ })
2185
+ );
2186
+
2187
+ if (error_loaded.loaded.error) {
2188
+ continue;
2189
+ }
2190
+
2191
+ page_config = get_page_config(error_node.module, options);
2192
+ branch = branch.slice(0, j + 1).concat(error_loaded);
2193
+ stuff = { ...node_loaded.stuff, ...error_loaded.stuff };
2194
+ break ssr;
2195
+ } catch (err) {
2196
+ const e = coalesce_to_error(err);
2197
+
2198
+ options.handle_error(e, event);
2199
+
2200
+ continue;
2201
+ }
2202
+ }
2203
+ }
2204
+
2205
+ // TODO backtrack until we find an __error.svelte component
2206
+ // that we can use as the leaf node
2207
+ // for now just return regular error page
2208
+ return with_cookies(
2209
+ await respond_with_error({
2210
+ event,
2211
+ options,
2212
+ state,
2213
+ $session,
2214
+ status,
2215
+ error,
2216
+ ssr
2217
+ }),
2218
+ set_cookie_headers
2219
+ );
2220
+ }
2221
+ }
2222
+
2223
+ if (loaded && loaded.loaded.stuff) {
2224
+ stuff = {
2225
+ ...stuff,
2226
+ ...loaded.loaded.stuff
2227
+ };
2228
+ }
2229
+ }
2230
+ }
2231
+
2232
+ try {
2233
+ return with_cookies(
2234
+ await render_response({
2235
+ ...opts,
2236
+ stuff,
2237
+ url: event.url,
2238
+ page_config,
2239
+ status,
2240
+ error,
2241
+ branch: branch.filter(Boolean)
2242
+ }),
2243
+ set_cookie_headers
2244
+ );
2245
+ } catch (err) {
2246
+ const error = coalesce_to_error(err);
2247
+
2248
+ options.handle_error(error, event);
2249
+
2250
+ return with_cookies(
2251
+ await respond_with_error({
2252
+ ...opts,
2253
+ status: 500,
2254
+ error
2255
+ }),
2256
+ set_cookie_headers
2257
+ );
2258
+ }
2259
+ }
2260
+
2261
+ /**
2262
+ * @param {import('types/internal').SSRComponent} leaf
2263
+ * @param {SSROptions} options
2264
+ */
2265
+ function get_page_config(leaf, options) {
2266
+ // TODO remove for 1.0
2267
+ if ('ssr' in leaf) {
2268
+ throw new Error(
2269
+ '`export const ssr` has been removed — use the handle hook instead: https://kit.svelte.dev/docs#hooks-handle'
2270
+ );
2271
+ }
2272
+
2273
+ return {
2274
+ router: 'router' in leaf ? !!leaf.router : options.router,
2275
+ hydrate: 'hydrate' in leaf ? !!leaf.hydrate : options.hydrate
2276
+ };
2277
+ }
2278
+
2279
+ /**
2280
+ * @param {Response} response
2281
+ * @param {string[]} set_cookie_headers
2282
+ */
2283
+ function with_cookies(response, set_cookie_headers) {
2284
+ if (set_cookie_headers.length) {
2285
+ set_cookie_headers.forEach((value) => {
2286
+ response.headers.append('set-cookie', value);
2287
+ });
2288
+ }
2289
+ return response;
2290
+ }
2291
+
2292
+ /**
2293
+ * @param {import('types/hooks').RequestEvent} event
2294
+ * @param {import('types/internal').SSRPage} route
2295
+ * @param {import('types/internal').SSROptions} options
2296
+ * @param {import('types/internal').SSRState} state
2297
+ * @param {boolean} ssr
2298
+ * @returns {Promise<Response | undefined>}
2299
+ */
2300
+ async function render_page(event, route, options, state, ssr) {
2301
+ if (state.initiator === route) {
2302
+ // infinite request cycle detected
2303
+ return new Response(`Not found: ${event.url.pathname}`, {
2304
+ status: 404
2305
+ });
2306
+ }
2307
+
2308
+ if (route.shadow) {
2309
+ const type = negotiate(event.request.headers.get('accept') || 'text/html', [
2310
+ 'text/html',
2311
+ 'application/json'
2312
+ ]);
2313
+
2314
+ if (type === 'application/json') {
2315
+ return render_endpoint(event, await route.shadow());
2316
+ }
2317
+ }
2318
+
2319
+ const $session = await options.hooks.getSession(event);
2320
+
2321
+ const response = await respond$1({
2322
+ event,
2323
+ options,
2324
+ state,
2325
+ $session,
2326
+ route,
2327
+ params: event.params, // TODO this is redundant
2328
+ ssr
2329
+ });
2330
+
2331
+ if (response) {
2332
+ return response;
2333
+ }
2334
+
2335
+ if (state.fetched) {
2336
+ // we came here because of a bad request in a `load` function.
2337
+ // rather than render the error page — which could lead to an
2338
+ // infinite loop, if the `load` belonged to the root layout,
2339
+ // we respond with a bare-bones 500
2340
+ return new Response(`Bad request in load function: failed to fetch ${state.fetched}`, {
2341
+ status: 500
2342
+ });
2343
+ }
2344
+ }
2345
+
2346
+ /**
2347
+ * @param {string} accept
2348
+ * @param {string[]} types
2349
+ */
2350
+ function negotiate(accept, types) {
2351
+ const parts = accept
2352
+ .split(',')
2353
+ .map((str, i) => {
2354
+ const match = /([^/]+)\/([^;]+)(?:;q=([0-9.]+))?/.exec(str);
2355
+ if (match) {
2356
+ const [, type, subtype, q = '1'] = match;
2357
+ return { type, subtype, q: +q, i };
2358
+ }
2359
+
2360
+ throw new Error(`Invalid Accept header: ${accept}`);
2361
+ })
2362
+ .sort((a, b) => {
2363
+ if (a.q !== b.q) {
2364
+ return b.q - a.q;
2365
+ }
2366
+
2367
+ if ((a.subtype === '*') !== (b.subtype === '*')) {
2368
+ return a.subtype === '*' ? 1 : -1;
2369
+ }
2370
+
2371
+ if ((a.type === '*') !== (b.type === '*')) {
2372
+ return a.type === '*' ? 1 : -1;
2373
+ }
2374
+
2375
+ return a.i - b.i;
2376
+ });
2377
+
2378
+ let accepted;
2379
+ let min_priority = Infinity;
2380
+
2381
+ for (const mimetype of types) {
2382
+ const [type, subtype] = mimetype.split('/');
2383
+ const priority = parts.findIndex(
2384
+ (part) =>
2385
+ (part.type === type || part.type === '*') &&
2386
+ (part.subtype === subtype || part.subtype === '*')
2387
+ );
2388
+
2389
+ if (priority !== -1 && priority < min_priority) {
2390
+ accepted = mimetype;
2391
+ min_priority = priority;
2392
+ }
2393
+ }
2394
+
2395
+ return accepted;
2396
+ }
2397
+
2398
+ const DATA_SUFFIX = '/__data.json';
2399
+
2400
+ /** @type {import('types/internal').Respond} */
2401
+ async function respond(request, options, state = {}) {
2402
+ const url = new URL(request.url);
2403
+
2404
+ if (url.pathname !== '/' && options.trailing_slash !== 'ignore') {
2405
+ const has_trailing_slash = url.pathname.endsWith('/');
2406
+
2407
+ if (
2408
+ (has_trailing_slash && options.trailing_slash === 'never') ||
2409
+ (!has_trailing_slash &&
2410
+ options.trailing_slash === 'always' &&
2411
+ !(url.pathname.split('/').pop() || '').includes('.'))
2412
+ ) {
2413
+ url.pathname = has_trailing_slash ? url.pathname.slice(0, -1) : url.pathname + '/';
2414
+
2415
+ if (url.search === '?') url.search = '';
2416
+
2417
+ return new Response(undefined, {
2418
+ status: 301,
2419
+ headers: {
2420
+ location: url.pathname + url.search
2421
+ }
2422
+ });
2423
+ }
2424
+ }
2425
+
2426
+ const { parameter, allowed } = options.method_override;
2427
+ const method_override = url.searchParams.get(parameter)?.toUpperCase();
2428
+
2429
+ if (method_override) {
2430
+ if (request.method === 'POST') {
2431
+ if (allowed.includes(method_override)) {
2432
+ request = new Proxy(request, {
2433
+ get: (target, property, _receiver) => {
2434
+ if (property === 'method') return method_override;
2435
+ return Reflect.get(target, property, target);
2436
+ }
2437
+ });
2438
+ } else {
2439
+ const verb = allowed.length === 0 ? 'enabled' : 'allowed';
2440
+ const body = `${parameter}=${method_override} is not ${verb}. See https://kit.svelte.dev/docs#configuration-methodoverride`;
2441
+
2442
+ return new Response(body, {
2443
+ status: 400
2444
+ });
2445
+ }
2446
+ } else {
2447
+ throw new Error(`${parameter}=${method_override} is only allowed with POST requests`);
2448
+ }
2449
+ }
2450
+
2451
+ /** @type {import('types/hooks').RequestEvent} */
2452
+ const event = {
2453
+ request,
2454
+ url,
2455
+ params: {},
2456
+ // @ts-expect-error this picks up types that belong to the tests
2457
+ locals: {},
2458
+ platform: state.platform
2459
+ };
2460
+
2461
+ // TODO remove this for 1.0
2462
+ /**
2463
+ * @param {string} property
2464
+ * @param {string} replacement
2465
+ * @param {string} suffix
2466
+ */
2467
+ const removed = (property, replacement, suffix = '') => ({
2468
+ get: () => {
2469
+ throw new Error(`event.${property} has been replaced by event.${replacement}` + suffix);
2470
+ }
2471
+ });
2472
+
2473
+ const details = '. See https://github.com/sveltejs/kit/pull/3384 for details';
2474
+
2475
+ const body_getter = {
2476
+ get: () => {
2477
+ throw new Error(
2478
+ 'To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`' +
2479
+ details
2480
+ );
2481
+ }
2482
+ };
2483
+
2484
+ Object.defineProperties(event, {
2485
+ method: removed('method', 'request.method', details),
2486
+ headers: removed('headers', 'request.headers', details),
2487
+ origin: removed('origin', 'url.origin'),
2488
+ path: removed('path', 'url.pathname'),
2489
+ query: removed('query', 'url.searchParams'),
2490
+ body: body_getter,
2491
+ rawBody: body_getter
2492
+ });
2493
+
2494
+ let ssr = true;
2495
+
2496
+ try {
2497
+ const response = await options.hooks.handle({
2498
+ event,
2499
+ resolve: async (event, opts) => {
2500
+ if (opts && 'ssr' in opts) ssr = /** @type {boolean} */ (opts.ssr);
2501
+
2502
+ if (state.prerender && state.prerender.fallback) {
2503
+ return await render_response({
2504
+ url: event.url,
2505
+ params: event.params,
2506
+ options,
2507
+ state,
2508
+ $session: await options.hooks.getSession(event),
2509
+ page_config: { router: true, hydrate: true },
2510
+ stuff: {},
2511
+ status: 200,
2512
+ branch: [],
2513
+ ssr: false
2514
+ });
2515
+ }
2516
+
2517
+ let decoded = decodeURI(event.url.pathname);
2518
+
2519
+ if (options.paths.base) {
2520
+ if (!decoded.startsWith(options.paths.base)) {
2521
+ return new Response(undefined, { status: 404 });
2522
+ }
2523
+ decoded = decoded.slice(options.paths.base.length) || '/';
2524
+ }
2525
+
2526
+ const is_data_request = decoded.endsWith(DATA_SUFFIX);
2527
+ if (is_data_request) decoded = decoded.slice(0, -DATA_SUFFIX.length) || '/';
2528
+
2529
+ for (const route of options.manifest._.routes) {
2530
+ const match = route.pattern.exec(decoded);
2531
+ if (!match) continue;
2532
+
2533
+ event.params = route.params ? decode_params(route.params(match)) : {};
2534
+
2535
+ /** @type {Response | undefined} */
2536
+ let response;
2537
+
2538
+ if (is_data_request && route.type === 'page' && route.shadow) {
2539
+ response = await render_endpoint(event, await route.shadow());
2540
+
2541
+ // since redirects are opaque to the browser, we need to repackage
2542
+ // 3xx responses as 200s with a custom header
2543
+ if (
2544
+ response &&
2545
+ response.status >= 300 &&
2546
+ response.status < 400 &&
2547
+ request.headers.get('x-sveltekit-noredirect') === 'true'
2548
+ ) {
2549
+ const location = response.headers.get('location');
2550
+
2551
+ if (location) {
2552
+ response = new Response(undefined, {
2553
+ status: 204,
2554
+ headers: {
2555
+ 'x-sveltekit-location': location
2556
+ }
2557
+ });
2558
+ }
2559
+ }
2560
+ } else {
2561
+ response =
2562
+ route.type === 'endpoint'
2563
+ ? await render_endpoint(event, await route.load())
2564
+ : await render_page(event, route, options, state, ssr);
2565
+ }
2566
+
2567
+ if (response) {
2568
+ // respond with 304 if etag matches
2569
+ if (response.status === 200 && response.headers.has('etag')) {
2570
+ let if_none_match_value = request.headers.get('if-none-match');
2571
+
2572
+ // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives
2573
+ if (if_none_match_value?.startsWith('W/"')) {
2574
+ if_none_match_value = if_none_match_value.substring(2);
2575
+ }
2576
+
2577
+ const etag = /** @type {string} */ (response.headers.get('etag'));
2578
+
2579
+ if (if_none_match_value === etag) {
2580
+ const headers = new Headers({ etag });
2581
+
2582
+ // https://datatracker.ietf.org/doc/html/rfc7232#section-4.1
2583
+ for (const key of [
2584
+ 'cache-control',
2585
+ 'content-location',
2586
+ 'date',
2587
+ 'expires',
2588
+ 'vary'
2589
+ ]) {
2590
+ const value = response.headers.get(key);
2591
+ if (value) headers.set(key, value);
2592
+ }
2593
+
2594
+ return new Response(undefined, {
2595
+ status: 304,
2596
+ headers
2597
+ });
2598
+ }
2599
+ }
2600
+
2601
+ return response;
2602
+ }
2603
+ }
2604
+
2605
+ // if this request came direct from the user, rather than
2606
+ // via a `fetch` in a `load`, render a 404 page
2607
+ if (!state.initiator) {
2608
+ const $session = await options.hooks.getSession(event);
2609
+ return await respond_with_error({
2610
+ event,
2611
+ options,
2612
+ state,
2613
+ $session,
2614
+ status: 404,
2615
+ error: new Error(`Not found: ${event.url.pathname}`),
2616
+ ssr
2617
+ });
2618
+ }
2619
+
2620
+ // we can't load the endpoint from our own manifest,
2621
+ // so we need to make an actual HTTP request
2622
+ return await fetch(request);
2623
+ },
2624
+
2625
+ // TODO remove for 1.0
2626
+ // @ts-expect-error
2627
+ get request() {
2628
+ throw new Error('request in handle has been replaced with event' + details);
2629
+ }
2630
+ });
2631
+
2632
+ // TODO for 1.0, change the error message to point to docs rather than PR
2633
+ if (response && !(response instanceof Response)) {
2634
+ throw new Error('handle must return a Response object' + details);
2635
+ }
2636
+
2637
+ return response;
2638
+ } catch (/** @type {unknown} */ e) {
2639
+ const error = coalesce_to_error(e);
2640
+
2641
+ options.handle_error(error, event);
2642
+
2643
+ try {
2644
+ const $session = await options.hooks.getSession(event);
2645
+ return await respond_with_error({
2646
+ event,
2647
+ options,
2648
+ state,
2649
+ $session,
2650
+ status: 500,
2651
+ error,
2652
+ ssr
2653
+ });
2654
+ } catch (/** @type {unknown} */ e) {
2655
+ const error = coalesce_to_error(e);
2656
+
2657
+ return new Response(options.dev ? error.stack : error.message, {
2658
+ status: 500
2659
+ });
2660
+ }
2661
+ }
2662
+ }
2663
+
2664
+ export { respond };