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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +20 -0
  3. package/assets/app/navigation.js +79 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/{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 +2365 -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 +2690 -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 +765 -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/chunks/url.js +119 -0
  27. package/dist/cli.js +1122 -84
  28. package/dist/hooks.js +28 -0
  29. package/dist/install-fetch.js +6518 -0
  30. package/dist/node.js +95 -0
  31. package/package.json +95 -54
  32. package/svelte-kit.js +2 -0
  33. package/types/ambient-modules.d.ts +201 -0
  34. package/types/app.d.ts +35 -0
  35. package/types/config.d.ts +173 -0
  36. package/types/csp.d.ts +115 -0
  37. package/types/endpoint.d.ts +24 -0
  38. package/types/helper.d.ts +32 -0
  39. package/types/hooks.d.ts +38 -0
  40. package/types/index.d.ts +10 -0
  41. package/types/internal.d.ts +252 -0
  42. package/types/page.d.ts +85 -0
  43. package/CHANGELOG.md +0 -306
  44. package/assets/runtime/app/navigation.js +0 -23
  45. package/assets/runtime/app/navigation.js.map +0 -1
  46. package/assets/runtime/app/paths.js +0 -2
  47. package/assets/runtime/app/paths.js.map +0 -1
  48. package/assets/runtime/app/stores.js.map +0 -1
  49. package/assets/runtime/internal/singletons.js +0 -15
  50. package/assets/runtime/internal/singletons.js.map +0 -1
  51. package/assets/runtime/internal/start.js +0 -591
  52. package/assets/runtime/internal/start.js.map +0 -1
  53. package/assets/runtime/utils-85ebcc60.js +0 -18
  54. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  55. package/dist/api.js +0 -44
  56. package/dist/api.js.map +0 -1
  57. package/dist/build.js +0 -246
  58. package/dist/build.js.map +0 -1
  59. package/dist/cli.js.map +0 -1
  60. package/dist/colors.js +0 -37
  61. package/dist/colors.js.map +0 -1
  62. package/dist/create_app.js +0 -578
  63. package/dist/create_app.js.map +0 -1
  64. package/dist/index.js +0 -367
  65. package/dist/index.js.map +0 -1
  66. package/dist/index2.js +0 -12043
  67. package/dist/index2.js.map +0 -1
  68. package/dist/index3.js +0 -550
  69. package/dist/index3.js.map +0 -1
  70. package/dist/index4.js +0 -74
  71. package/dist/index4.js.map +0 -1
  72. package/dist/index5.js +0 -464
  73. package/dist/index5.js.map +0 -1
  74. package/dist/index6.js +0 -727
  75. package/dist/index6.js.map +0 -1
  76. package/dist/logging.js +0 -43
  77. package/dist/logging.js.map +0 -1
  78. package/dist/package.js +0 -432
  79. package/dist/package.js.map +0 -1
  80. package/dist/renderer.js +0 -2403
  81. package/dist/renderer.js.map +0 -1
  82. package/dist/standard.js +0 -101
  83. package/dist/standard.js.map +0 -1
  84. package/dist/utils.js +0 -54
  85. package/dist/utils.js.map +0 -1
  86. package/svelte-kit +0 -3
@@ -0,0 +1,2365 @@
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 (body[Symbol.toStringTag] === '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
+ const resolved = resolve(event.url.pathname, requested.split('?')[0]);
1539
+
1540
+ /** @type {Response} */
1541
+ let response;
1542
+
1543
+ /** @type {import('types/internal').PrerenderDependency} */
1544
+ let dependency;
1545
+
1546
+ // handle fetch requests for static assets. e.g. prebaked data, etc.
1547
+ // we need to support everything the browser's fetch supports
1548
+ const prefix = options.paths.assets || options.paths.base;
1549
+ const filename = decodeURIComponent(
1550
+ resolved.startsWith(prefix) ? resolved.slice(prefix.length) : resolved
1551
+ ).slice(1);
1552
+ const filename_html = `${filename}/index.html`; // path may also match path/index.html
1553
+
1554
+ const is_asset = options.manifest.assets.has(filename);
1555
+ const is_asset_html = options.manifest.assets.has(filename_html);
1556
+
1557
+ if (is_asset || is_asset_html) {
1558
+ const file = is_asset ? filename : filename_html;
1559
+
1560
+ if (options.read) {
1561
+ const type = is_asset
1562
+ ? options.manifest._.mime[filename.slice(filename.lastIndexOf('.'))]
1563
+ : 'text/html';
1564
+
1565
+ response = new Response(options.read(file), {
1566
+ headers: type ? { 'content-type': type } : {}
1567
+ });
1568
+ } else {
1569
+ response = await fetch(`${url.origin}/${file}`, /** @type {RequestInit} */ (opts));
1570
+ }
1571
+ } else if (is_root_relative(resolved)) {
1572
+ if (opts.credentials !== 'omit') {
1573
+ uses_credentials = true;
1574
+
1575
+ const cookie = event.request.headers.get('cookie');
1576
+ const authorization = event.request.headers.get('authorization');
1577
+
1578
+ if (cookie) {
1579
+ opts.headers.set('cookie', cookie);
1580
+ }
1581
+
1582
+ if (authorization && !opts.headers.has('authorization')) {
1583
+ opts.headers.set('authorization', authorization);
1584
+ }
1585
+ }
1586
+
1587
+ if (opts.body && typeof opts.body !== 'string') {
1588
+ // per https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, this can be a
1589
+ // Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object.
1590
+ // non-string bodies are irksome to deal with, but luckily aren't particularly useful
1591
+ // in this context anyway, so we take the easy route and ban them
1592
+ throw new Error('Request body must be a string');
1593
+ }
1594
+
1595
+ response = await respond(new Request(new URL(requested, event.url).href, opts), options, {
1596
+ fetched: requested,
1597
+ initiator: route
1598
+ });
1599
+
1600
+ if (state.prerender) {
1601
+ dependency = { response, body: null };
1602
+ state.prerender.dependencies.set(resolved, dependency);
1603
+ }
1604
+ } else {
1605
+ // external
1606
+ if (resolved.startsWith('//')) {
1607
+ throw new Error(
1608
+ `Cannot request protocol-relative URL (${requested}) in server-side fetch`
1609
+ );
1610
+ }
1611
+
1612
+ // external fetch
1613
+ // allow cookie passthrough for "same-origin"
1614
+ // if SvelteKit is serving my.domain.com:
1615
+ // - domain.com WILL NOT receive cookies
1616
+ // - my.domain.com WILL receive cookies
1617
+ // - api.domain.dom WILL NOT receive cookies
1618
+ // - sub.my.domain.com WILL receive cookies
1619
+ // ports do not affect the resolution
1620
+ // leading dot prevents mydomain.com matching domain.com
1621
+ if (
1622
+ `.${new URL(requested).hostname}`.endsWith(`.${event.url.hostname}`) &&
1623
+ opts.credentials !== 'omit'
1624
+ ) {
1625
+ uses_credentials = true;
1626
+
1627
+ const cookie = event.request.headers.get('cookie');
1628
+ if (cookie) opts.headers.set('cookie', cookie);
1629
+ }
1630
+
1631
+ const external_request = new Request(requested, /** @type {RequestInit} */ (opts));
1632
+ response = await options.hooks.externalFetch.call(null, external_request);
1633
+ }
1634
+
1635
+ const proxy = new Proxy(response, {
1636
+ get(response, key, _receiver) {
1637
+ async function text() {
1638
+ const body = await response.text();
1639
+
1640
+ /** @type {import('types/helper').ResponseHeaders} */
1641
+ const headers = {};
1642
+ for (const [key, value] of response.headers) {
1643
+ if (key === 'set-cookie') {
1644
+ set_cookie_headers = set_cookie_headers.concat(value);
1645
+ } else if (key !== 'etag') {
1646
+ headers[key] = value;
1647
+ }
1648
+ }
1649
+
1650
+ if (!opts.body || typeof opts.body === 'string') {
1651
+ // prettier-ignore
1652
+ fetched.push({
1653
+ url: requested,
1654
+ body: /** @type {string} */ (opts.body),
1655
+ json: `{"status":${response.status},"statusText":${s(response.statusText)},"headers":${s(headers)},"body":"${escape_json_string_in_html(body)}"}`
1656
+ });
1657
+ }
1658
+
1659
+ if (dependency) {
1660
+ dependency.body = body;
1661
+ }
1662
+
1663
+ return body;
1664
+ }
1665
+
1666
+ if (key === 'arrayBuffer') {
1667
+ return async () => {
1668
+ const buffer = await response.arrayBuffer();
1669
+
1670
+ if (dependency) {
1671
+ dependency.body = new Uint8Array(buffer);
1672
+ }
1673
+
1674
+ // TODO should buffer be inlined into the page (albeit base64'd)?
1675
+ // any conditions in which it shouldn't be?
1676
+
1677
+ return buffer;
1678
+ };
1679
+ }
1680
+
1681
+ if (key === 'text') {
1682
+ return text;
1683
+ }
1684
+
1685
+ if (key === 'json') {
1686
+ return async () => {
1687
+ return JSON.parse(await text());
1688
+ };
1689
+ }
1690
+
1691
+ // TODO arrayBuffer?
1692
+
1693
+ return Reflect.get(response, key, response);
1694
+ }
1695
+ });
1696
+
1697
+ return proxy;
1698
+ },
1699
+ stuff: { ...stuff }
1700
+ };
1701
+
1702
+ if (options.dev) {
1703
+ // TODO remove this for 1.0
1704
+ Object.defineProperty(load_input, 'page', {
1705
+ get: () => {
1706
+ throw new Error('`page` in `load` functions has been replaced by `url` and `params`');
1707
+ }
1708
+ });
1709
+ }
1710
+
1711
+ if (is_error) {
1712
+ /** @type {import('types/page').ErrorLoadInput} */ (load_input).status = status;
1713
+ /** @type {import('types/page').ErrorLoadInput} */ (load_input).error = error;
1714
+ }
1715
+
1716
+ loaded = await module.load.call(null, load_input);
1717
+
1718
+ if (!loaded) {
1719
+ throw new Error(`load function must return a value${options.dev ? ` (${node.entry})` : ''}`);
1720
+ }
1721
+ } else {
1722
+ loaded = {};
1723
+ }
1724
+
1725
+ if (loaded.fallthrough && !is_error) {
1726
+ return;
1727
+ }
1728
+
1729
+ return {
1730
+ node,
1731
+ loaded: normalize(loaded),
1732
+ stuff: loaded.stuff || stuff,
1733
+ fetched,
1734
+ set_cookie_headers,
1735
+ uses_credentials
1736
+ };
1737
+ }
1738
+
1739
+ /**
1740
+ * @typedef {import('./types.js').Loaded} Loaded
1741
+ * @typedef {import('types/internal').SSRRenderOptions} SSRRenderOptions
1742
+ * @typedef {import('types/internal').SSRRenderState} SSRRenderState
1743
+ */
1744
+
1745
+ /**
1746
+ * @param {{
1747
+ * event: import('types/hooks').RequestEvent;
1748
+ * options: SSRRenderOptions;
1749
+ * state: SSRRenderState;
1750
+ * $session: any;
1751
+ * status: number;
1752
+ * error: Error;
1753
+ * ssr: boolean;
1754
+ * }} opts
1755
+ */
1756
+ async function respond_with_error({ event, options, state, $session, status, error, ssr }) {
1757
+ try {
1758
+ const default_layout = await options.manifest._.nodes[0](); // 0 is always the root layout
1759
+ const default_error = await options.manifest._.nodes[1](); // 1 is always the root error
1760
+
1761
+ /** @type {Record<string, string>} */
1762
+ const params = {}; // error page has no params
1763
+
1764
+ const layout_loaded = /** @type {Loaded} */ (
1765
+ await load_node({
1766
+ event,
1767
+ options,
1768
+ state,
1769
+ route: null,
1770
+ url: event.url, // TODO this is redundant, no?
1771
+ params,
1772
+ node: default_layout,
1773
+ $session,
1774
+ stuff: {},
1775
+ is_error: false
1776
+ })
1777
+ );
1778
+
1779
+ const error_loaded = /** @type {Loaded} */ (
1780
+ await load_node({
1781
+ event,
1782
+ options,
1783
+ state,
1784
+ route: null,
1785
+ url: event.url,
1786
+ params,
1787
+ node: default_error,
1788
+ $session,
1789
+ stuff: layout_loaded ? layout_loaded.stuff : {},
1790
+ is_error: true,
1791
+ status,
1792
+ error
1793
+ })
1794
+ );
1795
+
1796
+ return await render_response({
1797
+ options,
1798
+ state,
1799
+ $session,
1800
+ page_config: {
1801
+ hydrate: options.hydrate,
1802
+ router: options.router
1803
+ },
1804
+ stuff: error_loaded.stuff,
1805
+ status,
1806
+ error,
1807
+ branch: [layout_loaded, error_loaded],
1808
+ url: event.url,
1809
+ params,
1810
+ ssr
1811
+ });
1812
+ } catch (err) {
1813
+ const error = coalesce_to_error(err);
1814
+
1815
+ options.handle_error(error, event);
1816
+
1817
+ return new Response(error.stack, {
1818
+ status: 500
1819
+ });
1820
+ }
1821
+ }
1822
+
1823
+ /**
1824
+ * @typedef {import('./types.js').Loaded} Loaded
1825
+ * @typedef {import('types/internal').SSRNode} SSRNode
1826
+ * @typedef {import('types/internal').SSRRenderOptions} SSRRenderOptions
1827
+ * @typedef {import('types/internal').SSRRenderState} SSRRenderState
1828
+ */
1829
+
1830
+ /**
1831
+ * @param {{
1832
+ * event: import('types/hooks').RequestEvent;
1833
+ * options: SSRRenderOptions;
1834
+ * state: SSRRenderState;
1835
+ * $session: any;
1836
+ * route: import('types/internal').SSRPage;
1837
+ * params: Record<string, string>;
1838
+ * ssr: boolean;
1839
+ * }} opts
1840
+ * @returns {Promise<Response | undefined>}
1841
+ */
1842
+ async function respond$1(opts) {
1843
+ const { event, options, state, $session, route, ssr } = opts;
1844
+
1845
+ /** @type {Array<SSRNode | undefined>} */
1846
+ let nodes;
1847
+
1848
+ if (!ssr) {
1849
+ return await render_response({
1850
+ ...opts,
1851
+ branch: [],
1852
+ page_config: {
1853
+ hydrate: true,
1854
+ router: true
1855
+ },
1856
+ status: 200,
1857
+ url: event.url,
1858
+ stuff: {}
1859
+ });
1860
+ }
1861
+
1862
+ try {
1863
+ nodes = await Promise.all(
1864
+ route.a.map((n) => options.manifest._.nodes[n] && options.manifest._.nodes[n]())
1865
+ );
1866
+ } catch (err) {
1867
+ const error = coalesce_to_error(err);
1868
+
1869
+ options.handle_error(error, event);
1870
+
1871
+ return await respond_with_error({
1872
+ event,
1873
+ options,
1874
+ state,
1875
+ $session,
1876
+ status: 500,
1877
+ error,
1878
+ ssr
1879
+ });
1880
+ }
1881
+
1882
+ // the leaf node will be present. only layouts may be undefined
1883
+ const leaf = /** @type {SSRNode} */ (nodes[nodes.length - 1]).module;
1884
+
1885
+ let page_config = get_page_config(leaf, options);
1886
+
1887
+ if (!leaf.prerender && state.prerender && !state.prerender.all) {
1888
+ // if the page has `export const prerender = true`, continue,
1889
+ // otherwise bail out at this point
1890
+ return new Response(undefined, {
1891
+ status: 204
1892
+ });
1893
+ }
1894
+
1895
+ /** @type {Array<Loaded>} */
1896
+ let branch = [];
1897
+
1898
+ /** @type {number} */
1899
+ let status = 200;
1900
+
1901
+ /** @type {Error|undefined} */
1902
+ let error;
1903
+
1904
+ /** @type {string[]} */
1905
+ let set_cookie_headers = [];
1906
+
1907
+ let stuff = {};
1908
+
1909
+ ssr: if (ssr) {
1910
+ for (let i = 0; i < nodes.length; i += 1) {
1911
+ const node = nodes[i];
1912
+
1913
+ /** @type {Loaded | undefined} */
1914
+ let loaded;
1915
+
1916
+ if (node) {
1917
+ try {
1918
+ loaded = await load_node({
1919
+ ...opts,
1920
+ url: event.url,
1921
+ node,
1922
+ stuff,
1923
+ is_error: false
1924
+ });
1925
+
1926
+ if (!loaded) return;
1927
+
1928
+ set_cookie_headers = set_cookie_headers.concat(loaded.set_cookie_headers);
1929
+
1930
+ if (loaded.loaded.redirect) {
1931
+ return with_cookies(
1932
+ new Response(undefined, {
1933
+ status: loaded.loaded.status,
1934
+ headers: {
1935
+ location: loaded.loaded.redirect
1936
+ }
1937
+ }),
1938
+ set_cookie_headers
1939
+ );
1940
+ }
1941
+
1942
+ if (loaded.loaded.error) {
1943
+ ({ status, error } = loaded.loaded);
1944
+ }
1945
+ } catch (err) {
1946
+ const e = coalesce_to_error(err);
1947
+
1948
+ options.handle_error(e, event);
1949
+
1950
+ status = 500;
1951
+ error = e;
1952
+ }
1953
+
1954
+ if (loaded && !error) {
1955
+ branch.push(loaded);
1956
+ }
1957
+
1958
+ if (error) {
1959
+ while (i--) {
1960
+ if (route.b[i]) {
1961
+ const error_node = await options.manifest._.nodes[route.b[i]]();
1962
+
1963
+ /** @type {Loaded} */
1964
+ let node_loaded;
1965
+ let j = i;
1966
+ while (!(node_loaded = branch[j])) {
1967
+ j -= 1;
1968
+ }
1969
+
1970
+ try {
1971
+ const error_loaded = /** @type {import('./types').Loaded} */ (
1972
+ await load_node({
1973
+ ...opts,
1974
+ url: event.url,
1975
+ node: error_node,
1976
+ stuff: node_loaded.stuff,
1977
+ is_error: true,
1978
+ status,
1979
+ error
1980
+ })
1981
+ );
1982
+
1983
+ if (error_loaded.loaded.error) {
1984
+ continue;
1985
+ }
1986
+
1987
+ page_config = get_page_config(error_node.module, options);
1988
+ branch = branch.slice(0, j + 1).concat(error_loaded);
1989
+ stuff = { ...node_loaded.stuff, ...error_loaded.stuff };
1990
+ break ssr;
1991
+ } catch (err) {
1992
+ const e = coalesce_to_error(err);
1993
+
1994
+ options.handle_error(e, event);
1995
+
1996
+ continue;
1997
+ }
1998
+ }
1999
+ }
2000
+
2001
+ // TODO backtrack until we find an __error.svelte component
2002
+ // that we can use as the leaf node
2003
+ // for now just return regular error page
2004
+ return with_cookies(
2005
+ await respond_with_error({
2006
+ event,
2007
+ options,
2008
+ state,
2009
+ $session,
2010
+ status,
2011
+ error,
2012
+ ssr
2013
+ }),
2014
+ set_cookie_headers
2015
+ );
2016
+ }
2017
+ }
2018
+
2019
+ if (loaded && loaded.loaded.stuff) {
2020
+ stuff = {
2021
+ ...stuff,
2022
+ ...loaded.loaded.stuff
2023
+ };
2024
+ }
2025
+ }
2026
+ }
2027
+
2028
+ try {
2029
+ return with_cookies(
2030
+ await render_response({
2031
+ ...opts,
2032
+ stuff,
2033
+ url: event.url,
2034
+ page_config,
2035
+ status,
2036
+ error,
2037
+ branch: branch.filter(Boolean)
2038
+ }),
2039
+ set_cookie_headers
2040
+ );
2041
+ } catch (err) {
2042
+ const error = coalesce_to_error(err);
2043
+
2044
+ options.handle_error(error, event);
2045
+
2046
+ return with_cookies(
2047
+ await respond_with_error({
2048
+ ...opts,
2049
+ status: 500,
2050
+ error
2051
+ }),
2052
+ set_cookie_headers
2053
+ );
2054
+ }
2055
+ }
2056
+
2057
+ /**
2058
+ * @param {import('types/internal').SSRComponent} leaf
2059
+ * @param {SSRRenderOptions} options
2060
+ */
2061
+ function get_page_config(leaf, options) {
2062
+ // TODO remove for 1.0
2063
+ if ('ssr' in leaf) {
2064
+ throw new Error(
2065
+ '`export const ssr` has been removed — use the handle hook instead: https://kit.svelte.dev/docs#hooks-handle'
2066
+ );
2067
+ }
2068
+
2069
+ return {
2070
+ router: 'router' in leaf ? !!leaf.router : options.router,
2071
+ hydrate: 'hydrate' in leaf ? !!leaf.hydrate : options.hydrate
2072
+ };
2073
+ }
2074
+
2075
+ /**
2076
+ * @param {Response} response
2077
+ * @param {string[]} set_cookie_headers
2078
+ */
2079
+ function with_cookies(response, set_cookie_headers) {
2080
+ if (set_cookie_headers.length) {
2081
+ set_cookie_headers.forEach((value) => {
2082
+ response.headers.append('set-cookie', value);
2083
+ });
2084
+ }
2085
+ return response;
2086
+ }
2087
+
2088
+ /**
2089
+ * @param {import('types/hooks').RequestEvent} event
2090
+ * @param {import('types/internal').SSRPage} route
2091
+ * @param {RegExpExecArray} match
2092
+ * @param {import('types/internal').SSRRenderOptions} options
2093
+ * @param {import('types/internal').SSRRenderState} state
2094
+ * @param {boolean} ssr
2095
+ * @returns {Promise<Response | undefined>}
2096
+ */
2097
+ async function render_page(event, route, match, options, state, ssr) {
2098
+ if (state.initiator === route) {
2099
+ // infinite request cycle detected
2100
+ return new Response(`Not found: ${event.url.pathname}`, {
2101
+ status: 404
2102
+ });
2103
+ }
2104
+
2105
+ const params = route.params ? decode_params(route.params(match)) : {};
2106
+
2107
+ const $session = await options.hooks.getSession(event);
2108
+
2109
+ const response = await respond$1({
2110
+ event,
2111
+ options,
2112
+ state,
2113
+ $session,
2114
+ route,
2115
+ params,
2116
+ ssr
2117
+ });
2118
+
2119
+ if (response) {
2120
+ return response;
2121
+ }
2122
+
2123
+ if (state.fetched) {
2124
+ // we came here because of a bad request in a `load` function.
2125
+ // rather than render the error page — which could lead to an
2126
+ // infinite loop, if the `load` belonged to the root layout,
2127
+ // we respond with a bare-bones 500
2128
+ return new Response(`Bad request in load function: failed to fetch ${state.fetched}`, {
2129
+ status: 500
2130
+ });
2131
+ }
2132
+ }
2133
+
2134
+ /** @type {import('types/internal').Respond} */
2135
+ async function respond(request, options, state = {}) {
2136
+ const url = new URL(request.url);
2137
+
2138
+ if (url.pathname !== '/' && options.trailing_slash !== 'ignore') {
2139
+ const has_trailing_slash = url.pathname.endsWith('/');
2140
+
2141
+ if (
2142
+ (has_trailing_slash && options.trailing_slash === 'never') ||
2143
+ (!has_trailing_slash &&
2144
+ options.trailing_slash === 'always' &&
2145
+ !(url.pathname.split('/').pop() || '').includes('.'))
2146
+ ) {
2147
+ url.pathname = has_trailing_slash ? url.pathname.slice(0, -1) : url.pathname + '/';
2148
+
2149
+ if (url.search === '?') url.search = '';
2150
+
2151
+ return new Response(undefined, {
2152
+ status: 301,
2153
+ headers: {
2154
+ location: url.pathname + url.search
2155
+ }
2156
+ });
2157
+ }
2158
+ }
2159
+
2160
+ const { parameter, allowed } = options.method_override;
2161
+ const method_override = url.searchParams.get(parameter)?.toUpperCase();
2162
+
2163
+ if (method_override) {
2164
+ if (request.method === 'POST') {
2165
+ if (allowed.includes(method_override)) {
2166
+ request = new Proxy(request, {
2167
+ get: (target, property, _receiver) => {
2168
+ if (property === 'method') return method_override;
2169
+ return Reflect.get(target, property, target);
2170
+ }
2171
+ });
2172
+ } else {
2173
+ const verb = allowed.length === 0 ? 'enabled' : 'allowed';
2174
+ const body = `${parameter}=${method_override} is not ${verb}. See https://kit.svelte.dev/docs#configuration-methodoverride`;
2175
+
2176
+ return new Response(body, {
2177
+ status: 400
2178
+ });
2179
+ }
2180
+ } else {
2181
+ throw new Error(`${parameter}=${method_override} is only allowed with POST requests`);
2182
+ }
2183
+ }
2184
+
2185
+ /** @type {import('types/hooks').RequestEvent} */
2186
+ const event = {
2187
+ request,
2188
+ url,
2189
+ params: {},
2190
+ locals: {},
2191
+ platform: state.platform
2192
+ };
2193
+
2194
+ // TODO remove this for 1.0
2195
+ /**
2196
+ * @param {string} property
2197
+ * @param {string} replacement
2198
+ * @param {string} suffix
2199
+ */
2200
+ const removed = (property, replacement, suffix = '') => ({
2201
+ get: () => {
2202
+ throw new Error(`event.${property} has been replaced by event.${replacement}` + suffix);
2203
+ }
2204
+ });
2205
+
2206
+ const details = '. See https://github.com/sveltejs/kit/pull/3384 for details';
2207
+
2208
+ const body_getter = {
2209
+ get: () => {
2210
+ throw new Error(
2211
+ 'To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`' +
2212
+ details
2213
+ );
2214
+ }
2215
+ };
2216
+
2217
+ Object.defineProperties(event, {
2218
+ method: removed('method', 'request.method', details),
2219
+ headers: removed('headers', 'request.headers', details),
2220
+ origin: removed('origin', 'url.origin'),
2221
+ path: removed('path', 'url.pathname'),
2222
+ query: removed('query', 'url.searchParams'),
2223
+ body: body_getter,
2224
+ rawBody: body_getter
2225
+ });
2226
+
2227
+ let ssr = true;
2228
+
2229
+ try {
2230
+ const response = await options.hooks.handle({
2231
+ event,
2232
+ resolve: async (event, opts) => {
2233
+ if (opts && 'ssr' in opts) ssr = /** @type {boolean} */ (opts.ssr);
2234
+
2235
+ if (state.prerender && state.prerender.fallback) {
2236
+ return await render_response({
2237
+ url: event.url,
2238
+ params: event.params,
2239
+ options,
2240
+ state,
2241
+ $session: await options.hooks.getSession(event),
2242
+ page_config: { router: true, hydrate: true },
2243
+ stuff: {},
2244
+ status: 200,
2245
+ branch: [],
2246
+ ssr: false
2247
+ });
2248
+ }
2249
+
2250
+ let decoded = decodeURI(event.url.pathname);
2251
+
2252
+ if (options.paths.base) {
2253
+ if (!decoded.startsWith(options.paths.base)) {
2254
+ return new Response(undefined, { status: 404 });
2255
+ }
2256
+ decoded = decoded.slice(options.paths.base.length) || '/';
2257
+ }
2258
+
2259
+ for (const route of options.manifest._.routes) {
2260
+ const match = route.pattern.exec(decoded);
2261
+ if (!match) continue;
2262
+
2263
+ const response =
2264
+ route.type === 'endpoint'
2265
+ ? await render_endpoint(event, route, match)
2266
+ : await render_page(event, route, match, options, state, ssr);
2267
+
2268
+ if (response) {
2269
+ // respond with 304 if etag matches
2270
+ if (response.status === 200 && response.headers.has('etag')) {
2271
+ let if_none_match_value = request.headers.get('if-none-match');
2272
+
2273
+ // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives
2274
+ if (if_none_match_value?.startsWith('W/"')) {
2275
+ if_none_match_value = if_none_match_value.substring(2);
2276
+ }
2277
+
2278
+ const etag = /** @type {string} */ (response.headers.get('etag'));
2279
+
2280
+ if (if_none_match_value === etag) {
2281
+ const headers = new Headers({ etag });
2282
+
2283
+ // https://datatracker.ietf.org/doc/html/rfc7232#section-4.1
2284
+ for (const key of [
2285
+ 'cache-control',
2286
+ 'content-location',
2287
+ 'date',
2288
+ 'expires',
2289
+ 'vary'
2290
+ ]) {
2291
+ const value = response.headers.get(key);
2292
+ if (value) headers.set(key, value);
2293
+ }
2294
+
2295
+ return new Response(undefined, {
2296
+ status: 304,
2297
+ headers
2298
+ });
2299
+ }
2300
+ }
2301
+
2302
+ return response;
2303
+ }
2304
+ }
2305
+
2306
+ // if this request came direct from the user, rather than
2307
+ // via a `fetch` in a `load`, render a 404 page
2308
+ if (!state.initiator) {
2309
+ const $session = await options.hooks.getSession(event);
2310
+ return await respond_with_error({
2311
+ event,
2312
+ options,
2313
+ state,
2314
+ $session,
2315
+ status: 404,
2316
+ error: new Error(`Not found: ${event.url.pathname}`),
2317
+ ssr
2318
+ });
2319
+ }
2320
+
2321
+ // we can't load the endpoint from our own manifest,
2322
+ // so we need to make an actual HTTP request
2323
+ return await fetch(request);
2324
+ },
2325
+
2326
+ // TODO remove for 1.0
2327
+ // @ts-expect-error
2328
+ get request() {
2329
+ throw new Error('request in handle has been replaced with event' + details);
2330
+ }
2331
+ });
2332
+
2333
+ // TODO for 1.0, change the error message to point to docs rather than PR
2334
+ if (response && !(response instanceof Response)) {
2335
+ throw new Error('handle must return a Response object' + details);
2336
+ }
2337
+
2338
+ return response;
2339
+ } catch (/** @type {unknown} */ e) {
2340
+ const error = coalesce_to_error(e);
2341
+
2342
+ options.handle_error(error, event);
2343
+
2344
+ try {
2345
+ const $session = await options.hooks.getSession(event);
2346
+ return await respond_with_error({
2347
+ event,
2348
+ options,
2349
+ state,
2350
+ $session,
2351
+ status: 500,
2352
+ error,
2353
+ ssr
2354
+ });
2355
+ } catch (/** @type {unknown} */ e) {
2356
+ const error = coalesce_to_error(e);
2357
+
2358
+ return new Response(options.dev ? error.stack : error.message, {
2359
+ status: 500
2360
+ });
2361
+ }
2362
+ }
2363
+ }
2364
+
2365
+ export { respond };