@sveltejs/kit 1.0.0-next.25 → 1.0.0-next.253

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