@sveltejs/kit 1.0.0-next.31 → 1.0.0-next.310

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