@sveltejs/kit 1.0.0-next.22 → 1.0.0-next.223

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 (82) hide show
  1. package/README.md +12 -9
  2. package/assets/components/error.svelte +19 -3
  3. package/assets/kit.js +1996 -0
  4. package/assets/runtime/app/env.js +20 -0
  5. package/assets/runtime/app/navigation.js +55 -13
  6. package/assets/runtime/app/paths.js +1 -2
  7. package/assets/runtime/app/stores.js +19 -15
  8. package/assets/runtime/chunks/utils.js +13 -0
  9. package/assets/runtime/env.js +8 -0
  10. package/assets/runtime/internal/singletons.js +12 -9
  11. package/assets/runtime/internal/start.js +1015 -354
  12. package/assets/runtime/paths.js +13 -0
  13. package/dist/chunks/cert.js +29255 -0
  14. package/dist/chunks/constants.js +8 -0
  15. package/dist/chunks/error.js +12 -0
  16. package/dist/chunks/index.js +476 -0
  17. package/dist/chunks/index2.js +817 -0
  18. package/dist/chunks/index3.js +640 -0
  19. package/dist/chunks/index4.js +109 -0
  20. package/dist/chunks/index5.js +635 -0
  21. package/dist/chunks/index6.js +827 -0
  22. package/dist/chunks/index7.js +15575 -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 +62 -0
  27. package/dist/cli.js +996 -83
  28. package/dist/hooks.js +28 -0
  29. package/dist/install-fetch.js +6514 -0
  30. package/dist/node.js +51 -0
  31. package/dist/ssr.js +1926 -0
  32. package/package.json +96 -54
  33. package/svelte-kit.js +2 -0
  34. package/types/ambient-modules.d.ts +191 -0
  35. package/types/app.d.ts +45 -0
  36. package/types/config.d.ts +168 -0
  37. package/types/endpoint.d.ts +20 -0
  38. package/types/helper.d.ts +53 -0
  39. package/types/hooks.d.ts +55 -0
  40. package/types/index.d.ts +18 -0
  41. package/types/internal.d.ts +237 -0
  42. package/types/page.d.ts +73 -0
  43. package/CHANGELOG.md +0 -288
  44. package/assets/runtime/app/navigation.js.map +0 -1
  45. package/assets/runtime/app/paths.js.map +0 -1
  46. package/assets/runtime/app/stores.js.map +0 -1
  47. package/assets/runtime/internal/singletons.js.map +0 -1
  48. package/assets/runtime/internal/start.js.map +0 -1
  49. package/assets/runtime/utils-85ebcc60.js +0 -18
  50. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  51. package/dist/api.js +0 -44
  52. package/dist/api.js.map +0 -1
  53. package/dist/build.js +0 -246
  54. package/dist/build.js.map +0 -1
  55. package/dist/cli.js.map +0 -1
  56. package/dist/colors.js +0 -37
  57. package/dist/colors.js.map +0 -1
  58. package/dist/create_app.js +0 -578
  59. package/dist/create_app.js.map +0 -1
  60. package/dist/index.js +0 -12042
  61. package/dist/index.js.map +0 -1
  62. package/dist/index2.js +0 -544
  63. package/dist/index2.js.map +0 -1
  64. package/dist/index3.js +0 -71
  65. package/dist/index3.js.map +0 -1
  66. package/dist/index4.js +0 -466
  67. package/dist/index4.js.map +0 -1
  68. package/dist/index5.js +0 -729
  69. package/dist/index5.js.map +0 -1
  70. package/dist/index6.js +0 -730
  71. package/dist/index6.js.map +0 -1
  72. package/dist/logging.js +0 -43
  73. package/dist/logging.js.map +0 -1
  74. package/dist/package.js +0 -432
  75. package/dist/package.js.map +0 -1
  76. package/dist/renderer.js +0 -2391
  77. package/dist/renderer.js.map +0 -1
  78. package/dist/standard.js +0 -101
  79. package/dist/standard.js.map +0 -1
  80. package/dist/utils.js +0 -54
  81. package/dist/utils.js.map +0 -1
  82. package/svelte-kit +0 -3
package/assets/kit.js ADDED
@@ -0,0 +1,1996 @@
1
+ /**
2
+ * @param {Record<string, string | string[] | undefined>} headers
3
+ * @param {string} key
4
+ * @returns {string | undefined}
5
+ * @throws {Error}
6
+ */
7
+ function get_single_valued_header(headers, key) {
8
+ const value = headers[key];
9
+ if (Array.isArray(value)) {
10
+ if (value.length === 0) {
11
+ return undefined;
12
+ }
13
+ if (value.length > 1) {
14
+ throw new Error(
15
+ `Multiple headers provided for ${key}. Multiple may be provided only for set-cookie`
16
+ );
17
+ }
18
+ return value[0];
19
+ }
20
+ return value;
21
+ }
22
+
23
+ /** @param {Record<string, any>} obj */
24
+ function lowercase_keys(obj) {
25
+ /** @type {Record<string, any>} */
26
+ const clone = {};
27
+
28
+ for (const key in obj) {
29
+ clone[key.toLowerCase()] = obj[key];
30
+ }
31
+
32
+ return clone;
33
+ }
34
+
35
+ /** @param {Record<string, string>} params */
36
+ function decode_params(params) {
37
+ for (const key in params) {
38
+ // input has already been decoded by decodeURI
39
+ // now handle the rest that decodeURIComponent would do
40
+ params[key] = params[key]
41
+ .replace(/%23/g, '#')
42
+ .replace(/%3[Bb]/g, ';')
43
+ .replace(/%2[Cc]/g, ',')
44
+ .replace(/%2[Ff]/g, '/')
45
+ .replace(/%3[Ff]/g, '?')
46
+ .replace(/%3[Aa]/g, ':')
47
+ .replace(/%40/g, '@')
48
+ .replace(/%26/g, '&')
49
+ .replace(/%3[Dd]/g, '=')
50
+ .replace(/%2[Bb]/g, '+')
51
+ .replace(/%24/g, '$');
52
+ }
53
+
54
+ return params;
55
+ }
56
+
57
+ /** @param {string} body */
58
+ function error(body) {
59
+ return {
60
+ status: 500,
61
+ body,
62
+ headers: {}
63
+ };
64
+ }
65
+
66
+ /** @param {unknown} s */
67
+ function is_string(s) {
68
+ return typeof s === 'string' || s instanceof String;
69
+ }
70
+
71
+ const text_types = new Set([
72
+ 'application/xml',
73
+ 'application/json',
74
+ 'application/x-www-form-urlencoded',
75
+ 'multipart/form-data'
76
+ ]);
77
+
78
+ /**
79
+ * Decides how the body should be parsed based on its mime type. Should match what's in parse_body
80
+ *
81
+ * @param {string | undefined | null} content_type The `content-type` header of a request/response.
82
+ * @returns {boolean}
83
+ */
84
+ function is_text(content_type) {
85
+ if (!content_type) return true; // defaults to json
86
+ const type = content_type.split(';')[0].toLowerCase(); // get the mime type
87
+
88
+ return type.startsWith('text/') || type.endsWith('+xml') || text_types.has(type);
89
+ }
90
+
91
+ /**
92
+ * @param {import('types/hooks').ServerRequest} request
93
+ * @param {import('types/internal').SSREndpoint} route
94
+ * @param {RegExpExecArray} match
95
+ * @returns {Promise<import('types/hooks').ServerResponse | undefined>}
96
+ */
97
+ async function render_endpoint(request, route, match) {
98
+ const mod = await route.load();
99
+
100
+ /** @type {import('types/endpoint').RequestHandler} */
101
+ const handler = mod[request.method.toLowerCase().replace('delete', 'del')]; // 'delete' is a reserved word
102
+
103
+ if (!handler) {
104
+ return;
105
+ }
106
+
107
+ // we're mutating `request` so that we don't have to do { ...request, params }
108
+ // on the next line, since that breaks the getters that replace path, query and
109
+ // origin. We could revert that once we remove the getters
110
+ request.params = route.params ? decode_params(route.params(match)) : {};
111
+
112
+ const response = await handler(request);
113
+ const preface = `Invalid response from route ${request.url.pathname}`;
114
+
115
+ if (typeof response !== 'object') {
116
+ return error(`${preface}: expected an object, got ${typeof response}`);
117
+ }
118
+
119
+ if (response.fallthrough) {
120
+ return;
121
+ }
122
+
123
+ let { status = 200, body, headers = {} } = response;
124
+
125
+ headers = lowercase_keys(headers);
126
+ const type = get_single_valued_header(headers, 'content-type');
127
+
128
+ if (!is_text(type) && !(body instanceof Uint8Array || is_string(body))) {
129
+ return error(
130
+ `${preface}: body must be an instance of string or Uint8Array if content-type is not a supported textual content-type`
131
+ );
132
+ }
133
+
134
+ /** @type {import('types/hooks').StrictBody} */
135
+ let normalized_body;
136
+
137
+ // ensure the body is an object
138
+ if (
139
+ (typeof body === 'object' || typeof body === 'undefined') &&
140
+ !(body instanceof Uint8Array) &&
141
+ (!type || type.startsWith('application/json'))
142
+ ) {
143
+ headers = { ...headers, 'content-type': 'application/json; charset=utf-8' };
144
+ normalized_body = JSON.stringify(typeof body === 'undefined' ? {} : body);
145
+ } else {
146
+ normalized_body = /** @type {import('types/hooks').StrictBody} */ (body);
147
+ }
148
+
149
+ return { status, body: normalized_body, headers };
150
+ }
151
+
152
+ var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
153
+ var unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
154
+ 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)$/;
155
+ var escaped = {
156
+ '<': '\\u003C',
157
+ '>': '\\u003E',
158
+ '/': '\\u002F',
159
+ '\\': '\\\\',
160
+ '\b': '\\b',
161
+ '\f': '\\f',
162
+ '\n': '\\n',
163
+ '\r': '\\r',
164
+ '\t': '\\t',
165
+ '\0': '\\0',
166
+ '\u2028': '\\u2028',
167
+ '\u2029': '\\u2029'
168
+ };
169
+ var objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join('\0');
170
+ function devalue(value) {
171
+ var counts = new Map();
172
+ function walk(thing) {
173
+ if (typeof thing === 'function') {
174
+ throw new Error("Cannot stringify a function");
175
+ }
176
+ if (counts.has(thing)) {
177
+ counts.set(thing, counts.get(thing) + 1);
178
+ return;
179
+ }
180
+ counts.set(thing, 1);
181
+ if (!isPrimitive(thing)) {
182
+ var type = getType(thing);
183
+ switch (type) {
184
+ case 'Number':
185
+ case 'String':
186
+ case 'Boolean':
187
+ case 'Date':
188
+ case 'RegExp':
189
+ return;
190
+ case 'Array':
191
+ thing.forEach(walk);
192
+ break;
193
+ case 'Set':
194
+ case 'Map':
195
+ Array.from(thing).forEach(walk);
196
+ break;
197
+ default:
198
+ var proto = Object.getPrototypeOf(thing);
199
+ if (proto !== Object.prototype &&
200
+ proto !== null &&
201
+ Object.getOwnPropertyNames(proto).sort().join('\0') !== objectProtoOwnPropertyNames) {
202
+ throw new Error("Cannot stringify arbitrary non-POJOs");
203
+ }
204
+ if (Object.getOwnPropertySymbols(thing).length > 0) {
205
+ throw new Error("Cannot stringify POJOs with symbolic keys");
206
+ }
207
+ Object.keys(thing).forEach(function (key) { return walk(thing[key]); });
208
+ }
209
+ }
210
+ }
211
+ walk(value);
212
+ var names = new Map();
213
+ Array.from(counts)
214
+ .filter(function (entry) { return entry[1] > 1; })
215
+ .sort(function (a, b) { return b[1] - a[1]; })
216
+ .forEach(function (entry, i) {
217
+ names.set(entry[0], getName(i));
218
+ });
219
+ function stringify(thing) {
220
+ if (names.has(thing)) {
221
+ return names.get(thing);
222
+ }
223
+ if (isPrimitive(thing)) {
224
+ return stringifyPrimitive(thing);
225
+ }
226
+ var type = getType(thing);
227
+ switch (type) {
228
+ case 'Number':
229
+ case 'String':
230
+ case 'Boolean':
231
+ return "Object(" + stringify(thing.valueOf()) + ")";
232
+ case 'RegExp':
233
+ return "new RegExp(" + stringifyString(thing.source) + ", \"" + thing.flags + "\")";
234
+ case 'Date':
235
+ return "new Date(" + thing.getTime() + ")";
236
+ case 'Array':
237
+ var members = thing.map(function (v, i) { return i in thing ? stringify(v) : ''; });
238
+ var tail = thing.length === 0 || (thing.length - 1 in thing) ? '' : ',';
239
+ return "[" + members.join(',') + tail + "]";
240
+ case 'Set':
241
+ case 'Map':
242
+ return "new " + type + "([" + Array.from(thing).map(stringify).join(',') + "])";
243
+ default:
244
+ var obj = "{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":" + stringify(thing[key]); }).join(',') + "}";
245
+ var proto = Object.getPrototypeOf(thing);
246
+ if (proto === null) {
247
+ return Object.keys(thing).length > 0
248
+ ? "Object.assign(Object.create(null)," + obj + ")"
249
+ : "Object.create(null)";
250
+ }
251
+ return obj;
252
+ }
253
+ }
254
+ var str = stringify(value);
255
+ if (names.size) {
256
+ var params_1 = [];
257
+ var statements_1 = [];
258
+ var values_1 = [];
259
+ names.forEach(function (name, thing) {
260
+ params_1.push(name);
261
+ if (isPrimitive(thing)) {
262
+ values_1.push(stringifyPrimitive(thing));
263
+ return;
264
+ }
265
+ var type = getType(thing);
266
+ switch (type) {
267
+ case 'Number':
268
+ case 'String':
269
+ case 'Boolean':
270
+ values_1.push("Object(" + stringify(thing.valueOf()) + ")");
271
+ break;
272
+ case 'RegExp':
273
+ values_1.push(thing.toString());
274
+ break;
275
+ case 'Date':
276
+ values_1.push("new Date(" + thing.getTime() + ")");
277
+ break;
278
+ case 'Array':
279
+ values_1.push("Array(" + thing.length + ")");
280
+ thing.forEach(function (v, i) {
281
+ statements_1.push(name + "[" + i + "]=" + stringify(v));
282
+ });
283
+ break;
284
+ case 'Set':
285
+ values_1.push("new Set");
286
+ statements_1.push(name + "." + Array.from(thing).map(function (v) { return "add(" + stringify(v) + ")"; }).join('.'));
287
+ break;
288
+ case 'Map':
289
+ values_1.push("new Map");
290
+ statements_1.push(name + "." + Array.from(thing).map(function (_a) {
291
+ var k = _a[0], v = _a[1];
292
+ return "set(" + stringify(k) + ", " + stringify(v) + ")";
293
+ }).join('.'));
294
+ break;
295
+ default:
296
+ values_1.push(Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}');
297
+ Object.keys(thing).forEach(function (key) {
298
+ statements_1.push("" + name + safeProp(key) + "=" + stringify(thing[key]));
299
+ });
300
+ }
301
+ });
302
+ statements_1.push("return " + str);
303
+ return "(function(" + params_1.join(',') + "){" + statements_1.join(';') + "}(" + values_1.join(',') + "))";
304
+ }
305
+ else {
306
+ return str;
307
+ }
308
+ }
309
+ function getName(num) {
310
+ var name = '';
311
+ do {
312
+ name = chars[num % chars.length] + name;
313
+ num = ~~(num / chars.length) - 1;
314
+ } while (num >= 0);
315
+ return reserved.test(name) ? name + "_" : name;
316
+ }
317
+ function isPrimitive(thing) {
318
+ return Object(thing) !== thing;
319
+ }
320
+ function stringifyPrimitive(thing) {
321
+ if (typeof thing === 'string')
322
+ return stringifyString(thing);
323
+ if (thing === void 0)
324
+ return 'void 0';
325
+ if (thing === 0 && 1 / thing < 0)
326
+ return '-0';
327
+ var str = String(thing);
328
+ if (typeof thing === 'number')
329
+ return str.replace(/^(-)?0\./, '$1.');
330
+ return str;
331
+ }
332
+ function getType(thing) {
333
+ return Object.prototype.toString.call(thing).slice(8, -1);
334
+ }
335
+ function escapeUnsafeChar(c) {
336
+ return escaped[c] || c;
337
+ }
338
+ function escapeUnsafeChars(str) {
339
+ return str.replace(unsafeChars, escapeUnsafeChar);
340
+ }
341
+ function safeKey(key) {
342
+ return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
343
+ }
344
+ function safeProp(key) {
345
+ return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? "." + key : "[" + escapeUnsafeChars(JSON.stringify(key)) + "]";
346
+ }
347
+ function stringifyString(str) {
348
+ var result = '"';
349
+ for (var i = 0; i < str.length; i += 1) {
350
+ var char = str.charAt(i);
351
+ var code = char.charCodeAt(0);
352
+ if (char === '"') {
353
+ result += '\\"';
354
+ }
355
+ else if (char in escaped) {
356
+ result += escaped[char];
357
+ }
358
+ else if (code >= 0xd800 && code <= 0xdfff) {
359
+ var next = str.charCodeAt(i + 1);
360
+ // If this is the beginning of a [high, low] surrogate pair,
361
+ // add the next two characters, otherwise escape
362
+ if (code <= 0xdbff && (next >= 0xdc00 && next <= 0xdfff)) {
363
+ result += char + str[++i];
364
+ }
365
+ else {
366
+ result += "\\u" + code.toString(16).toUpperCase();
367
+ }
368
+ }
369
+ else {
370
+ result += char;
371
+ }
372
+ }
373
+ result += '"';
374
+ return result;
375
+ }
376
+
377
+ function noop() { }
378
+ function safe_not_equal(a, b) {
379
+ return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
380
+ }
381
+ Promise.resolve();
382
+
383
+ const subscriber_queue = [];
384
+ /**
385
+ * Create a `Writable` store that allows both updating and reading by subscription.
386
+ * @param {*=}value initial value
387
+ * @param {StartStopNotifier=}start start and stop notifications for subscriptions
388
+ */
389
+ function writable(value, start = noop) {
390
+ let stop;
391
+ const subscribers = new Set();
392
+ function set(new_value) {
393
+ if (safe_not_equal(value, new_value)) {
394
+ value = new_value;
395
+ if (stop) { // store is ready
396
+ const run_queue = !subscriber_queue.length;
397
+ for (const subscriber of subscribers) {
398
+ subscriber[1]();
399
+ subscriber_queue.push(subscriber, value);
400
+ }
401
+ if (run_queue) {
402
+ for (let i = 0; i < subscriber_queue.length; i += 2) {
403
+ subscriber_queue[i][0](subscriber_queue[i + 1]);
404
+ }
405
+ subscriber_queue.length = 0;
406
+ }
407
+ }
408
+ }
409
+ }
410
+ function update(fn) {
411
+ set(fn(value));
412
+ }
413
+ function subscribe(run, invalidate = noop) {
414
+ const subscriber = [run, invalidate];
415
+ subscribers.add(subscriber);
416
+ if (subscribers.size === 1) {
417
+ stop = start(set) || noop;
418
+ }
419
+ run(value);
420
+ return () => {
421
+ subscribers.delete(subscriber);
422
+ if (subscribers.size === 0) {
423
+ stop();
424
+ stop = null;
425
+ }
426
+ };
427
+ }
428
+ return { set, update, subscribe };
429
+ }
430
+
431
+ /**
432
+ * @param {unknown} err
433
+ * @return {Error}
434
+ */
435
+ function coalesce_to_error(err) {
436
+ return err instanceof Error ||
437
+ (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message)
438
+ ? /** @type {Error} */ (err)
439
+ : new Error(JSON.stringify(err));
440
+ }
441
+
442
+ /**
443
+ * Hash using djb2
444
+ * @param {import('types/hooks').StrictBody} value
445
+ */
446
+ function hash(value) {
447
+ let hash = 5381;
448
+ let i = value.length;
449
+
450
+ if (typeof value === 'string') {
451
+ while (i) hash = (hash * 33) ^ value.charCodeAt(--i);
452
+ } else {
453
+ while (i) hash = (hash * 33) ^ value[--i];
454
+ }
455
+
456
+ return (hash >>> 0).toString(36);
457
+ }
458
+
459
+ /** @type {Record<string, string>} */
460
+ const escape_json_string_in_html_dict = {
461
+ '"': '\\"',
462
+ '<': '\\u003C',
463
+ '>': '\\u003E',
464
+ '/': '\\u002F',
465
+ '\\': '\\\\',
466
+ '\b': '\\b',
467
+ '\f': '\\f',
468
+ '\n': '\\n',
469
+ '\r': '\\r',
470
+ '\t': '\\t',
471
+ '\0': '\\0',
472
+ '\u2028': '\\u2028',
473
+ '\u2029': '\\u2029'
474
+ };
475
+
476
+ /** @param {string} str */
477
+ function escape_json_string_in_html(str) {
478
+ return escape(
479
+ str,
480
+ escape_json_string_in_html_dict,
481
+ (code) => `\\u${code.toString(16).toUpperCase()}`
482
+ );
483
+ }
484
+
485
+ /** @type {Record<string, string>} */
486
+ const escape_html_attr_dict = {
487
+ '<': '&lt;',
488
+ '>': '&gt;',
489
+ '"': '&quot;'
490
+ };
491
+
492
+ /**
493
+ * use for escaping string values to be used html attributes on the page
494
+ * e.g.
495
+ * <script data-url="here">
496
+ *
497
+ * @param {string} str
498
+ * @returns string escaped string
499
+ */
500
+ function escape_html_attr(str) {
501
+ return '"' + escape(str, escape_html_attr_dict, (code) => `&#${code};`) + '"';
502
+ }
503
+
504
+ /**
505
+ *
506
+ * @param str {string} string to escape
507
+ * @param dict {Record<string, string>} dictionary of character replacements
508
+ * @param unicode_encoder {function(number): string} encoder to use for high unicode characters
509
+ * @returns {string}
510
+ */
511
+ function escape(str, dict, unicode_encoder) {
512
+ let result = '';
513
+
514
+ for (let i = 0; i < str.length; i += 1) {
515
+ const char = str.charAt(i);
516
+ const code = char.charCodeAt(0);
517
+
518
+ if (char in dict) {
519
+ result += dict[char];
520
+ } else if (code >= 0xd800 && code <= 0xdfff) {
521
+ const next = str.charCodeAt(i + 1);
522
+
523
+ // If this is the beginning of a [high, low] surrogate pair,
524
+ // add the next two characters, otherwise escape
525
+ if (code <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
526
+ result += char + str[++i];
527
+ } else {
528
+ result += unicode_encoder(code);
529
+ }
530
+ } else {
531
+ result += char;
532
+ }
533
+ }
534
+
535
+ return result;
536
+ }
537
+
538
+ const s = JSON.stringify;
539
+
540
+ // TODO rename this function/module
541
+
542
+ /**
543
+ * @param {{
544
+ * branch: Array<import('./types').Loaded>;
545
+ * options: import('types/internal').SSRRenderOptions;
546
+ * $session: any;
547
+ * page_config: { hydrate: boolean, router: boolean };
548
+ * status: number;
549
+ * error?: Error;
550
+ * url: URL;
551
+ * params: Record<string, string>;
552
+ * ssr: boolean;
553
+ * stuff: Record<string, any>;
554
+ * }} opts
555
+ */
556
+ async function render_response({
557
+ branch,
558
+ options,
559
+ $session,
560
+ page_config,
561
+ status,
562
+ error,
563
+ url,
564
+ params,
565
+ ssr,
566
+ stuff
567
+ }) {
568
+ const css = new Set(options.manifest._.entry.css);
569
+ const js = new Set(options.manifest._.entry.js);
570
+ const styles = new Set();
571
+
572
+ /** @type {Array<{ url: string, body: string, json: string }>} */
573
+ const serialized_data = [];
574
+
575
+ let rendered;
576
+
577
+ let is_private = false;
578
+ let maxage;
579
+
580
+ if (error) {
581
+ error.stack = options.get_stack(error);
582
+ }
583
+
584
+ if (ssr) {
585
+ branch.forEach(({ node, loaded, fetched, uses_credentials }) => {
586
+ if (node.css) node.css.forEach((url) => css.add(url));
587
+ if (node.js) node.js.forEach((url) => js.add(url));
588
+ if (node.styles) node.styles.forEach((content) => styles.add(content));
589
+
590
+ // TODO probably better if `fetched` wasn't populated unless `hydrate`
591
+ if (fetched && page_config.hydrate) serialized_data.push(...fetched);
592
+
593
+ if (uses_credentials) is_private = true;
594
+
595
+ maxage = loaded.maxage;
596
+ });
597
+
598
+ const session = writable($session);
599
+
600
+ /** @type {Record<string, any>} */
601
+ const props = {
602
+ stores: {
603
+ page: writable(null),
604
+ navigating: writable(null),
605
+ session
606
+ },
607
+ page: { url, params, status, error, stuff },
608
+ components: branch.map(({ node }) => node.module.default)
609
+ };
610
+
611
+ // TODO remove this for 1.0
612
+ /**
613
+ * @param {string} property
614
+ * @param {string} replacement
615
+ */
616
+ const print_error = (property, replacement) => {
617
+ Object.defineProperty(props.page, property, {
618
+ get: () => {
619
+ throw new Error(`$page.${property} has been replaced by $page.url.${replacement}`);
620
+ }
621
+ });
622
+ };
623
+
624
+ print_error('origin', 'origin');
625
+ print_error('path', 'pathname');
626
+ print_error('query', 'searchParams');
627
+
628
+ // props_n (instead of props[n]) makes it easy to avoid
629
+ // unnecessary updates for layout components
630
+ for (let i = 0; i < branch.length; i += 1) {
631
+ props[`props_${i}`] = await branch[i].loaded.props;
632
+ }
633
+
634
+ let session_tracking_active = false;
635
+ const unsubscribe = session.subscribe(() => {
636
+ if (session_tracking_active) is_private = true;
637
+ });
638
+ session_tracking_active = true;
639
+
640
+ try {
641
+ rendered = options.root.render(props);
642
+ } finally {
643
+ unsubscribe();
644
+ }
645
+ } else {
646
+ rendered = { head: '', html: '', css: { code: '', map: null } };
647
+ }
648
+
649
+ const include_js = page_config.router || page_config.hydrate;
650
+ if (!include_js) js.clear();
651
+
652
+ // TODO strip the AMP stuff out of the build if not relevant
653
+ const links = options.amp
654
+ ? styles.size > 0 || rendered.css.code.length > 0
655
+ ? `<style amp-custom>${Array.from(styles).concat(rendered.css.code).join('\n')}</style>`
656
+ : ''
657
+ : [
658
+ // From https://web.dev/priority-hints/:
659
+ // Generally, preloads will load in the order the parser gets to them for anything above "Medium" priority
660
+ // Thus, we should list CSS first
661
+ ...Array.from(css).map((dep) => `<link rel="stylesheet" href="${options.prefix}${dep}">`),
662
+ ...Array.from(js).map((dep) => `<link rel="modulepreload" href="${options.prefix}${dep}">`)
663
+ ].join('\n\t\t');
664
+
665
+ /** @type {string} */
666
+ let init = '';
667
+
668
+ if (options.amp) {
669
+ init = `
670
+ <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>
671
+ <noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
672
+ <script async src="https://cdn.ampproject.org/v0.js"></script>`;
673
+ init += options.service_worker
674
+ ? '<script async custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js"></script>'
675
+ : '';
676
+ } else if (include_js) {
677
+ // prettier-ignore
678
+ init = `<script type="module">
679
+ import { start } from ${s(options.prefix + options.manifest._.entry.file)};
680
+ start({
681
+ target: ${options.target ? `document.querySelector(${s(options.target)})` : 'document.body'},
682
+ paths: ${s(options.paths)},
683
+ session: ${try_serialize($session, (error) => {
684
+ throw new Error(`Failed to serialize session data: ${error.message}`);
685
+ })},
686
+ route: ${!!page_config.router},
687
+ spa: ${!ssr},
688
+ trailing_slash: ${s(options.trailing_slash)},
689
+ hydrate: ${ssr && page_config.hydrate ? `{
690
+ status: ${status},
691
+ error: ${serialize_error(error)},
692
+ nodes: [
693
+ ${(branch || [])
694
+ .map(({ node }) => `import(${s(options.prefix + node.entry)})`)
695
+ .join(',\n\t\t\t\t\t\t')}
696
+ ],
697
+ url: new URL(${s(url.href)}),
698
+ params: ${devalue(params)}
699
+ }` : 'null'}
700
+ });
701
+ </script>`;
702
+ }
703
+
704
+ if (options.service_worker && !options.amp) {
705
+ init += `<script>
706
+ if ('serviceWorker' in navigator) {
707
+ navigator.serviceWorker.register('${options.service_worker}');
708
+ }
709
+ </script>`;
710
+ }
711
+
712
+ const head = [
713
+ rendered.head,
714
+ styles.size && !options.amp
715
+ ? `<style data-svelte>${Array.from(styles).join('\n')}</style>`
716
+ : '',
717
+ links,
718
+ init
719
+ ].join('\n\n\t\t');
720
+
721
+ let body = rendered.html;
722
+ if (options.amp) {
723
+ if (options.service_worker) {
724
+ body += `<amp-install-serviceworker src="${options.service_worker}" layout="nodisplay"></amp-install-serviceworker>`;
725
+ }
726
+ } else {
727
+ body += serialized_data
728
+ .map(({ url, body, json }) => {
729
+ let attributes = `type="application/json" data-type="svelte-data" data-url=${escape_html_attr(
730
+ url
731
+ )}`;
732
+ if (body) attributes += ` data-body="${hash(body)}"`;
733
+
734
+ return `<script ${attributes}>${json}</script>`;
735
+ })
736
+ .join('\n\n\t');
737
+ }
738
+
739
+ /** @type {import('types/helper').ResponseHeaders} */
740
+ const headers = {
741
+ 'content-type': 'text/html'
742
+ };
743
+
744
+ if (maxage) {
745
+ headers['cache-control'] = `${is_private ? 'private' : 'public'}, max-age=${maxage}`;
746
+ }
747
+
748
+ if (!options.floc) {
749
+ headers['permissions-policy'] = 'interest-cohort=()';
750
+ }
751
+
752
+ const segments = url.pathname.slice(options.paths.base.length).split('/').slice(2);
753
+ const assets =
754
+ options.paths.assets || (segments.length > 0 ? segments.map(() => '..').join('/') : '.');
755
+
756
+ return {
757
+ status,
758
+ headers,
759
+ body: options.template({
760
+ head,
761
+ body,
762
+ assets
763
+ })
764
+ };
765
+ }
766
+
767
+ /**
768
+ * @param {any} data
769
+ * @param {(error: Error) => void} [fail]
770
+ */
771
+ function try_serialize(data, fail) {
772
+ try {
773
+ return devalue(data);
774
+ } catch (err) {
775
+ if (fail) fail(coalesce_to_error(err));
776
+ return null;
777
+ }
778
+ }
779
+
780
+ // Ensure we return something truthy so the client will not re-render the page over the error
781
+
782
+ /** @param {(Error & {frame?: string} & {loc?: object}) | undefined | null} error */
783
+ function serialize_error(error) {
784
+ if (!error) return null;
785
+ let serialized = try_serialize(error);
786
+ if (!serialized) {
787
+ const { name, message, stack } = error;
788
+ serialized = try_serialize({ ...error, name, message, stack });
789
+ }
790
+ if (!serialized) {
791
+ serialized = '{}';
792
+ }
793
+ return serialized;
794
+ }
795
+
796
+ /**
797
+ * @param {import('types/page').LoadOutput} loaded
798
+ * @returns {import('types/internal').NormalizedLoadOutput}
799
+ */
800
+ function normalize(loaded) {
801
+ const has_error_status =
802
+ loaded.status && loaded.status >= 400 && loaded.status <= 599 && !loaded.redirect;
803
+ if (loaded.error || has_error_status) {
804
+ const status = loaded.status;
805
+
806
+ if (!loaded.error && has_error_status) {
807
+ return {
808
+ status: status || 500,
809
+ error: new Error()
810
+ };
811
+ }
812
+
813
+ const error = typeof loaded.error === 'string' ? new Error(loaded.error) : loaded.error;
814
+
815
+ if (!(error instanceof Error)) {
816
+ return {
817
+ status: 500,
818
+ error: new Error(
819
+ `"error" property returned from load() must be a string or instance of Error, received type "${typeof error}"`
820
+ )
821
+ };
822
+ }
823
+
824
+ if (!status || status < 400 || status > 599) {
825
+ console.warn('"error" returned from load() without a valid status code — defaulting to 500');
826
+ return { status: 500, error };
827
+ }
828
+
829
+ return { status, error };
830
+ }
831
+
832
+ if (loaded.redirect) {
833
+ if (!loaded.status || Math.floor(loaded.status / 100) !== 3) {
834
+ return {
835
+ status: 500,
836
+ error: new Error(
837
+ '"redirect" property returned from load() must be accompanied by a 3xx status code'
838
+ )
839
+ };
840
+ }
841
+
842
+ if (typeof loaded.redirect !== 'string') {
843
+ return {
844
+ status: 500,
845
+ error: new Error('"redirect" property returned from load() must be a string')
846
+ };
847
+ }
848
+ }
849
+
850
+ // TODO remove before 1.0
851
+ if (/** @type {any} */ (loaded).context) {
852
+ throw new Error(
853
+ 'You are returning "context" from a load function. ' +
854
+ '"context" was renamed to "stuff", please adjust your code accordingly.'
855
+ );
856
+ }
857
+
858
+ return /** @type {import('types/internal').NormalizedLoadOutput} */ (loaded);
859
+ }
860
+
861
+ const absolute = /^([a-z]+:)?\/?\//;
862
+ const scheme = /^[a-z]+:/;
863
+
864
+ /**
865
+ * @param {string} base
866
+ * @param {string} path
867
+ */
868
+ function resolve(base, path) {
869
+ if (scheme.test(path)) return path;
870
+
871
+ const base_match = absolute.exec(base);
872
+ const path_match = absolute.exec(path);
873
+
874
+ if (!base_match) {
875
+ throw new Error(`bad base path: "${base}"`);
876
+ }
877
+
878
+ const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
879
+ const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
880
+
881
+ baseparts.pop();
882
+
883
+ for (let i = 0; i < pathparts.length; i += 1) {
884
+ const part = pathparts[i];
885
+ if (part === '.') continue;
886
+ else if (part === '..') baseparts.pop();
887
+ else baseparts.push(part);
888
+ }
889
+
890
+ const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
891
+
892
+ return `${prefix}${baseparts.join('/')}`;
893
+ }
894
+
895
+ /** @param {string} path */
896
+ function is_root_relative(path) {
897
+ return path[0] === '/' && path[1] !== '/';
898
+ }
899
+
900
+ /**
901
+ * @param {{
902
+ * request: import('types/hooks').ServerRequest;
903
+ * options: import('types/internal').SSRRenderOptions;
904
+ * state: import('types/internal').SSRRenderState;
905
+ * route: import('types/internal').SSRPage | null;
906
+ * url: URL;
907
+ * params: Record<string, string>;
908
+ * node: import('types/internal').SSRNode;
909
+ * $session: any;
910
+ * stuff: Record<string, any>;
911
+ * prerender_enabled: boolean;
912
+ * is_error: boolean;
913
+ * status?: number;
914
+ * error?: Error;
915
+ * }} opts
916
+ * @returns {Promise<import('./types').Loaded | undefined>} undefined for fallthrough
917
+ */
918
+ async function load_node({
919
+ request,
920
+ options,
921
+ state,
922
+ route,
923
+ url,
924
+ params,
925
+ node,
926
+ $session,
927
+ stuff,
928
+ prerender_enabled,
929
+ is_error,
930
+ status,
931
+ error
932
+ }) {
933
+ const { module } = node;
934
+
935
+ let uses_credentials = false;
936
+
937
+ /**
938
+ * @type {Array<{
939
+ * url: string;
940
+ * body: string;
941
+ * json: string;
942
+ * }>}
943
+ */
944
+ const fetched = [];
945
+
946
+ /**
947
+ * @type {string[]}
948
+ */
949
+ let set_cookie_headers = [];
950
+
951
+ let loaded;
952
+
953
+ const url_proxy = new Proxy(url, {
954
+ get: (target, prop, receiver) => {
955
+ if (prerender_enabled && (prop === 'search' || prop === 'searchParams')) {
956
+ throw new Error('Cannot access query on a page with prerendering enabled');
957
+ }
958
+ return Reflect.get(target, prop, receiver);
959
+ }
960
+ });
961
+
962
+ if (module.load) {
963
+ /** @type {import('types/page').LoadInput | import('types/page').ErrorLoadInput} */
964
+ const load_input = {
965
+ url: url_proxy,
966
+ params,
967
+ get session() {
968
+ uses_credentials = true;
969
+ return $session;
970
+ },
971
+ /**
972
+ * @param {RequestInfo} resource
973
+ * @param {RequestInit} opts
974
+ */
975
+ fetch: async (resource, opts = {}) => {
976
+ /** @type {string} */
977
+ let requested;
978
+
979
+ if (typeof resource === 'string') {
980
+ requested = resource;
981
+ } else {
982
+ requested = resource.url;
983
+
984
+ opts = {
985
+ method: resource.method,
986
+ headers: resource.headers,
987
+ body: resource.body,
988
+ mode: resource.mode,
989
+ credentials: resource.credentials,
990
+ cache: resource.cache,
991
+ redirect: resource.redirect,
992
+ referrer: resource.referrer,
993
+ integrity: resource.integrity,
994
+ ...opts
995
+ };
996
+ }
997
+
998
+ opts.headers = new Headers(opts.headers);
999
+
1000
+ const resolved = resolve(request.url.pathname, requested.split('?')[0]);
1001
+
1002
+ let response;
1003
+
1004
+ // handle fetch requests for static assets. e.g. prebaked data, etc.
1005
+ // we need to support everything the browser's fetch supports
1006
+ const prefix = options.paths.assets || options.paths.base;
1007
+ const filename = (
1008
+ resolved.startsWith(prefix) ? resolved.slice(prefix.length) : resolved
1009
+ ).slice(1);
1010
+ const filename_html = `${filename}/index.html`; // path may also match path/index.html
1011
+
1012
+ const is_asset = options.manifest.assets.has(filename);
1013
+ const is_asset_html = options.manifest.assets.has(filename_html);
1014
+
1015
+ if (is_asset || is_asset_html) {
1016
+ const file = is_asset ? filename : filename_html;
1017
+
1018
+ if (options.read) {
1019
+ const type = is_asset
1020
+ ? options.manifest._.mime[filename.slice(filename.lastIndexOf('.'))]
1021
+ : 'text/html';
1022
+
1023
+ response = new Response(options.read(file), {
1024
+ headers: type ? { 'content-type': type } : {}
1025
+ });
1026
+ } else {
1027
+ response = await fetch(`${url.origin}/${file}`, /** @type {RequestInit} */ (opts));
1028
+ }
1029
+ } else if (is_root_relative(resolved)) {
1030
+ const relative = resolved;
1031
+
1032
+ // TODO: fix type https://github.com/node-fetch/node-fetch/issues/1113
1033
+ if (opts.credentials !== 'omit') {
1034
+ uses_credentials = true;
1035
+
1036
+ if (request.headers.cookie) {
1037
+ opts.headers.set('cookie', request.headers.cookie);
1038
+ }
1039
+
1040
+ if (request.headers.authorization && !opts.headers.has('authorization')) {
1041
+ opts.headers.set('authorization', request.headers.authorization);
1042
+ }
1043
+ }
1044
+
1045
+ if (opts.body && typeof opts.body !== 'string') {
1046
+ // per https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, this can be a
1047
+ // Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object.
1048
+ // non-string bodies are irksome to deal with, but luckily aren't particularly useful
1049
+ // in this context anyway, so we take the easy route and ban them
1050
+ throw new Error('Request body must be a string');
1051
+ }
1052
+
1053
+ const rendered = await respond(
1054
+ {
1055
+ url: new URL(requested, request.url),
1056
+ method: opts.method || 'GET',
1057
+ headers: Object.fromEntries(opts.headers),
1058
+ rawBody: opts.body == null ? null : new TextEncoder().encode(opts.body)
1059
+ },
1060
+ options,
1061
+ {
1062
+ fetched: requested,
1063
+ initiator: route
1064
+ }
1065
+ );
1066
+
1067
+ if (rendered) {
1068
+ if (state.prerender) {
1069
+ state.prerender.dependencies.set(relative, rendered);
1070
+ }
1071
+
1072
+ // Set-Cookie must be filtered out (done below) and that's the only header value that
1073
+ // can be an array so we know we have only simple values
1074
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
1075
+ response = new Response(rendered.body, {
1076
+ status: rendered.status,
1077
+ headers: /** @type {Record<string, string>} */ (rendered.headers)
1078
+ });
1079
+ } else {
1080
+ // we can't load the endpoint from our own manifest,
1081
+ // so we need to make an actual HTTP request
1082
+ return fetch(new URL(requested, request.url).href, {
1083
+ method: opts.method || 'GET',
1084
+ headers: opts.headers
1085
+ });
1086
+ }
1087
+ } else {
1088
+ // external
1089
+ if (resolved.startsWith('//')) {
1090
+ throw new Error(
1091
+ `Cannot request protocol-relative URL (${requested}) in server-side fetch`
1092
+ );
1093
+ }
1094
+
1095
+ // external fetch
1096
+ // allow cookie passthrough for "same-origin"
1097
+ // if SvelteKit is serving my.domain.com:
1098
+ // - domain.com WILL NOT receive cookies
1099
+ // - my.domain.com WILL receive cookies
1100
+ // - api.domain.dom WILL NOT receive cookies
1101
+ // - sub.my.domain.com WILL receive cookies
1102
+ // ports do not affect the resolution
1103
+ // leading dot prevents mydomain.com matching domain.com
1104
+ if (
1105
+ `.${new URL(requested).hostname}`.endsWith(`.${request.url.hostname}`) &&
1106
+ opts.credentials !== 'omit'
1107
+ ) {
1108
+ uses_credentials = true;
1109
+ opts.headers.set('cookie', request.headers.cookie);
1110
+ }
1111
+
1112
+ const external_request = new Request(requested, /** @type {RequestInit} */ (opts));
1113
+ response = await options.hooks.externalFetch.call(null, external_request);
1114
+ }
1115
+
1116
+ if (response) {
1117
+ const proxy = new Proxy(response, {
1118
+ get(response, key, _receiver) {
1119
+ async function text() {
1120
+ const body = await response.text();
1121
+
1122
+ /** @type {import('types/helper').ResponseHeaders} */
1123
+ const headers = {};
1124
+ for (const [key, value] of response.headers) {
1125
+ if (key === 'set-cookie') {
1126
+ set_cookie_headers = set_cookie_headers.concat(value);
1127
+ } else if (key !== 'etag') {
1128
+ headers[key] = value;
1129
+ }
1130
+ }
1131
+
1132
+ if (!opts.body || typeof opts.body === 'string') {
1133
+ // prettier-ignore
1134
+ fetched.push({
1135
+ url: requested,
1136
+ body: /** @type {string} */ (opts.body),
1137
+ json: `{"status":${response.status},"statusText":${s(response.statusText)},"headers":${s(headers)},"body":"${escape_json_string_in_html(body)}"}`
1138
+ });
1139
+ }
1140
+
1141
+ return body;
1142
+ }
1143
+
1144
+ if (key === 'text') {
1145
+ return text;
1146
+ }
1147
+
1148
+ if (key === 'json') {
1149
+ return async () => {
1150
+ return JSON.parse(await text());
1151
+ };
1152
+ }
1153
+
1154
+ // TODO arrayBuffer?
1155
+
1156
+ return Reflect.get(response, key, response);
1157
+ }
1158
+ });
1159
+
1160
+ return proxy;
1161
+ }
1162
+
1163
+ return (
1164
+ response ||
1165
+ new Response('Not found', {
1166
+ status: 404
1167
+ })
1168
+ );
1169
+ },
1170
+ stuff: { ...stuff }
1171
+ };
1172
+
1173
+ if (options.dev) {
1174
+ // TODO remove this for 1.0
1175
+ Object.defineProperty(load_input, 'page', {
1176
+ get: () => {
1177
+ throw new Error('`page` in `load` functions has been replaced by `url` and `params`');
1178
+ }
1179
+ });
1180
+ }
1181
+
1182
+ if (is_error) {
1183
+ /** @type {import('types/page').ErrorLoadInput} */ (load_input).status = status;
1184
+ /** @type {import('types/page').ErrorLoadInput} */ (load_input).error = error;
1185
+ }
1186
+
1187
+ loaded = await module.load.call(null, load_input);
1188
+
1189
+ if (!loaded) {
1190
+ throw new Error(`load function must return a value${options.dev ? ` (${node.entry})` : ''}`);
1191
+ }
1192
+ } else {
1193
+ loaded = {};
1194
+ }
1195
+
1196
+ if (loaded.fallthrough && !is_error) {
1197
+ return;
1198
+ }
1199
+
1200
+ return {
1201
+ node,
1202
+ loaded: normalize(loaded),
1203
+ stuff: loaded.stuff || stuff,
1204
+ fetched,
1205
+ set_cookie_headers,
1206
+ uses_credentials
1207
+ };
1208
+ }
1209
+
1210
+ /**
1211
+ * @typedef {import('./types.js').Loaded} Loaded
1212
+ * @typedef {import('types/internal').SSRNode} SSRNode
1213
+ * @typedef {import('types/internal').SSRRenderOptions} SSRRenderOptions
1214
+ * @typedef {import('types/internal').SSRRenderState} SSRRenderState
1215
+ */
1216
+
1217
+ /**
1218
+ * @param {{
1219
+ * request: import('types/hooks').ServerRequest;
1220
+ * options: SSRRenderOptions;
1221
+ * state: SSRRenderState;
1222
+ * $session: any;
1223
+ * status: number;
1224
+ * error: Error;
1225
+ * ssr: boolean;
1226
+ * }} opts
1227
+ */
1228
+ async function respond_with_error({
1229
+ request,
1230
+ options,
1231
+ state,
1232
+ $session,
1233
+ status,
1234
+ error,
1235
+ ssr
1236
+ }) {
1237
+ try {
1238
+ const default_layout = await options.manifest._.nodes[0](); // 0 is always the root layout
1239
+ const default_error = await options.manifest._.nodes[1](); // 1 is always the root error
1240
+
1241
+ /** @type {Record<string, string>} */
1242
+ const params = {}; // error page has no params
1243
+
1244
+ const layout_loaded = /** @type {Loaded} */ (
1245
+ await load_node({
1246
+ request,
1247
+ options,
1248
+ state,
1249
+ route: null,
1250
+ url: request.url, // TODO this is redundant, no?
1251
+ params,
1252
+ node: default_layout,
1253
+ $session,
1254
+ stuff: {},
1255
+ prerender_enabled: is_prerender_enabled(options, default_error, state),
1256
+ is_error: false
1257
+ })
1258
+ );
1259
+
1260
+ const error_loaded = /** @type {Loaded} */ (
1261
+ await load_node({
1262
+ request,
1263
+ options,
1264
+ state,
1265
+ route: null,
1266
+ url: request.url,
1267
+ params,
1268
+ node: default_error,
1269
+ $session,
1270
+ stuff: layout_loaded ? layout_loaded.stuff : {},
1271
+ prerender_enabled: is_prerender_enabled(options, default_error, state),
1272
+ is_error: true,
1273
+ status,
1274
+ error
1275
+ })
1276
+ );
1277
+
1278
+ return await render_response({
1279
+ options,
1280
+ $session,
1281
+ page_config: {
1282
+ hydrate: options.hydrate,
1283
+ router: options.router
1284
+ },
1285
+ stuff: error_loaded.stuff,
1286
+ status,
1287
+ error,
1288
+ branch: [layout_loaded, error_loaded],
1289
+ url: request.url,
1290
+ params,
1291
+ ssr
1292
+ });
1293
+ } catch (err) {
1294
+ const error = coalesce_to_error(err);
1295
+
1296
+ options.handle_error(error, request);
1297
+
1298
+ return {
1299
+ status: 500,
1300
+ headers: {},
1301
+ body: error.stack
1302
+ };
1303
+ }
1304
+ }
1305
+
1306
+ /**
1307
+ * @param {SSRRenderOptions} options
1308
+ * @param {SSRNode} node
1309
+ * @param {SSRRenderState} state
1310
+ */
1311
+ function is_prerender_enabled(options, node, state) {
1312
+ return (
1313
+ options.prerender && (!!node.module.prerender || (!!state.prerender && state.prerender.all))
1314
+ );
1315
+ }
1316
+
1317
+ /**
1318
+ * @typedef {import('./types.js').Loaded} Loaded
1319
+ * @typedef {import('types/hooks').ServerResponse} ServerResponse
1320
+ * @typedef {import('types/internal').SSRNode} SSRNode
1321
+ * @typedef {import('types/internal').SSRRenderOptions} SSRRenderOptions
1322
+ * @typedef {import('types/internal').SSRRenderState} SSRRenderState
1323
+ */
1324
+
1325
+ /**
1326
+ * @param {{
1327
+ * request: import('types/hooks').ServerRequest;
1328
+ * options: SSRRenderOptions;
1329
+ * state: SSRRenderState;
1330
+ * $session: any;
1331
+ * route: import('types/internal').SSRPage;
1332
+ * params: Record<string, string>;
1333
+ * ssr: boolean;
1334
+ * }} opts
1335
+ * @returns {Promise<ServerResponse | undefined>}
1336
+ */
1337
+ async function respond$1(opts) {
1338
+ const { request, options, state, $session, route, ssr } = opts;
1339
+
1340
+ /** @type {Array<SSRNode | undefined>} */
1341
+ let nodes;
1342
+
1343
+ if (!ssr) {
1344
+ return await render_response({
1345
+ ...opts,
1346
+ branch: [],
1347
+ page_config: {
1348
+ hydrate: true,
1349
+ router: true
1350
+ },
1351
+ status: 200,
1352
+ url: request.url,
1353
+ stuff: {}
1354
+ });
1355
+ }
1356
+
1357
+ try {
1358
+ nodes = await Promise.all(
1359
+ route.a.map((n) => options.manifest._.nodes[n] && options.manifest._.nodes[n]())
1360
+ );
1361
+ } catch (err) {
1362
+ const error = coalesce_to_error(err);
1363
+
1364
+ options.handle_error(error, request);
1365
+
1366
+ return await respond_with_error({
1367
+ request,
1368
+ options,
1369
+ state,
1370
+ $session,
1371
+ status: 500,
1372
+ error,
1373
+ ssr
1374
+ });
1375
+ }
1376
+
1377
+ // the leaf node will be present. only layouts may be undefined
1378
+ const leaf = /** @type {SSRNode} */ (nodes[nodes.length - 1]).module;
1379
+
1380
+ let page_config = get_page_config(leaf, options);
1381
+
1382
+ if (!leaf.prerender && state.prerender && !state.prerender.all) {
1383
+ // if the page has `export const prerender = true`, continue,
1384
+ // otherwise bail out at this point
1385
+ return {
1386
+ status: 204,
1387
+ headers: {}
1388
+ };
1389
+ }
1390
+
1391
+ /** @type {Array<Loaded>} */
1392
+ let branch = [];
1393
+
1394
+ /** @type {number} */
1395
+ let status = 200;
1396
+
1397
+ /** @type {Error|undefined} */
1398
+ let error;
1399
+
1400
+ /** @type {string[]} */
1401
+ let set_cookie_headers = [];
1402
+
1403
+ let stuff = {};
1404
+
1405
+ ssr: if (ssr) {
1406
+ for (let i = 0; i < nodes.length; i += 1) {
1407
+ const node = nodes[i];
1408
+
1409
+ /** @type {Loaded | undefined} */
1410
+ let loaded;
1411
+
1412
+ if (node) {
1413
+ try {
1414
+ loaded = await load_node({
1415
+ ...opts,
1416
+ url: request.url,
1417
+ node,
1418
+ stuff,
1419
+ prerender_enabled: is_prerender_enabled(options, node, state),
1420
+ is_error: false
1421
+ });
1422
+
1423
+ if (!loaded) return;
1424
+
1425
+ set_cookie_headers = set_cookie_headers.concat(loaded.set_cookie_headers);
1426
+
1427
+ if (loaded.loaded.redirect) {
1428
+ return with_cookies(
1429
+ {
1430
+ status: loaded.loaded.status,
1431
+ headers: {
1432
+ location: encodeURI(loaded.loaded.redirect)
1433
+ }
1434
+ },
1435
+ set_cookie_headers
1436
+ );
1437
+ }
1438
+
1439
+ if (loaded.loaded.error) {
1440
+ ({ status, error } = loaded.loaded);
1441
+ }
1442
+ } catch (err) {
1443
+ const e = coalesce_to_error(err);
1444
+
1445
+ options.handle_error(e, request);
1446
+
1447
+ status = 500;
1448
+ error = e;
1449
+ }
1450
+
1451
+ if (loaded && !error) {
1452
+ branch.push(loaded);
1453
+ }
1454
+
1455
+ if (error) {
1456
+ while (i--) {
1457
+ if (route.b[i]) {
1458
+ const error_node = await options.manifest._.nodes[route.b[i]]();
1459
+
1460
+ /** @type {Loaded} */
1461
+ let node_loaded;
1462
+ let j = i;
1463
+ while (!(node_loaded = branch[j])) {
1464
+ j -= 1;
1465
+ }
1466
+
1467
+ try {
1468
+ const error_loaded = /** @type {import('./types').Loaded} */ (
1469
+ await load_node({
1470
+ ...opts,
1471
+ url: request.url,
1472
+ node: error_node,
1473
+ stuff: node_loaded.stuff,
1474
+ prerender_enabled: is_prerender_enabled(options, error_node, state),
1475
+ is_error: true,
1476
+ status,
1477
+ error
1478
+ })
1479
+ );
1480
+
1481
+ if (error_loaded.loaded.error) {
1482
+ continue;
1483
+ }
1484
+
1485
+ page_config = get_page_config(error_node.module, options);
1486
+ branch = branch.slice(0, j + 1).concat(error_loaded);
1487
+ stuff = { ...node_loaded.stuff, ...error_loaded.stuff };
1488
+ break ssr;
1489
+ } catch (err) {
1490
+ const e = coalesce_to_error(err);
1491
+
1492
+ options.handle_error(e, request);
1493
+
1494
+ continue;
1495
+ }
1496
+ }
1497
+ }
1498
+
1499
+ // TODO backtrack until we find an __error.svelte component
1500
+ // that we can use as the leaf node
1501
+ // for now just return regular error page
1502
+ return with_cookies(
1503
+ await respond_with_error({
1504
+ request,
1505
+ options,
1506
+ state,
1507
+ $session,
1508
+ status,
1509
+ error,
1510
+ ssr
1511
+ }),
1512
+ set_cookie_headers
1513
+ );
1514
+ }
1515
+ }
1516
+
1517
+ if (loaded && loaded.loaded.stuff) {
1518
+ stuff = {
1519
+ ...stuff,
1520
+ ...loaded.loaded.stuff
1521
+ };
1522
+ }
1523
+ }
1524
+ }
1525
+
1526
+ try {
1527
+ return with_cookies(
1528
+ await render_response({
1529
+ ...opts,
1530
+ stuff,
1531
+ url: request.url,
1532
+ page_config,
1533
+ status,
1534
+ error,
1535
+ branch: branch.filter(Boolean)
1536
+ }),
1537
+ set_cookie_headers
1538
+ );
1539
+ } catch (err) {
1540
+ const error = coalesce_to_error(err);
1541
+
1542
+ options.handle_error(error, request);
1543
+
1544
+ return with_cookies(
1545
+ await respond_with_error({
1546
+ ...opts,
1547
+ status: 500,
1548
+ error
1549
+ }),
1550
+ set_cookie_headers
1551
+ );
1552
+ }
1553
+ }
1554
+
1555
+ /**
1556
+ * @param {import('types/internal').SSRComponent} leaf
1557
+ * @param {SSRRenderOptions} options
1558
+ */
1559
+ function get_page_config(leaf, options) {
1560
+ // TODO remove for 1.0
1561
+ if ('ssr' in leaf) {
1562
+ throw new Error(
1563
+ '`export const ssr` has been removed — use the handle hook instead: https://kit.svelte.dev/docs#hooks-handle'
1564
+ );
1565
+ }
1566
+
1567
+ return {
1568
+ router: 'router' in leaf ? !!leaf.router : options.router,
1569
+ hydrate: 'hydrate' in leaf ? !!leaf.hydrate : options.hydrate
1570
+ };
1571
+ }
1572
+
1573
+ /**
1574
+ * @param {ServerResponse} response
1575
+ * @param {string[]} set_cookie_headers
1576
+ */
1577
+ function with_cookies(response, set_cookie_headers) {
1578
+ if (set_cookie_headers.length) {
1579
+ response.headers['set-cookie'] = set_cookie_headers;
1580
+ }
1581
+ return response;
1582
+ }
1583
+
1584
+ /**
1585
+ * @param {import('types/hooks').ServerRequest} request
1586
+ * @param {import('types/internal').SSRPage} route
1587
+ * @param {RegExpExecArray} match
1588
+ * @param {import('types/internal').SSRRenderOptions} options
1589
+ * @param {import('types/internal').SSRRenderState} state
1590
+ * @param {boolean} ssr
1591
+ * @returns {Promise<import('types/hooks').ServerResponse | undefined>}
1592
+ */
1593
+ async function render_page(request, route, match, options, state, ssr) {
1594
+ if (state.initiator === route) {
1595
+ // infinite request cycle detected
1596
+ return {
1597
+ status: 404,
1598
+ headers: {},
1599
+ body: `Not found: ${request.url.pathname}`
1600
+ };
1601
+ }
1602
+
1603
+ const params = route.params ? decode_params(route.params(match)) : {};
1604
+
1605
+ const $session = await options.hooks.getSession(request);
1606
+
1607
+ const response = await respond$1({
1608
+ request,
1609
+ options,
1610
+ state,
1611
+ $session,
1612
+ route,
1613
+ params,
1614
+ ssr
1615
+ });
1616
+
1617
+ if (response) {
1618
+ return response;
1619
+ }
1620
+
1621
+ if (state.fetched) {
1622
+ // we came here because of a bad request in a `load` function.
1623
+ // rather than render the error page — which could lead to an
1624
+ // infinite loop, if the `load` belonged to the root layout,
1625
+ // we respond with a bare-bones 500
1626
+ return {
1627
+ status: 500,
1628
+ headers: {},
1629
+ body: `Bad request in load function: failed to fetch ${state.fetched}`
1630
+ };
1631
+ }
1632
+ }
1633
+
1634
+ function read_only_form_data() {
1635
+ /** @type {Map<string, string[]>} */
1636
+ const map = new Map();
1637
+
1638
+ return {
1639
+ /**
1640
+ * @param {string} key
1641
+ * @param {string} value
1642
+ */
1643
+ append(key, value) {
1644
+ if (map.has(key)) {
1645
+ (map.get(key) || []).push(value);
1646
+ } else {
1647
+ map.set(key, [value]);
1648
+ }
1649
+ },
1650
+
1651
+ data: new ReadOnlyFormData(map)
1652
+ };
1653
+ }
1654
+
1655
+ class ReadOnlyFormData {
1656
+ /** @type {Map<string, string[]>} */
1657
+ #map;
1658
+
1659
+ /** @param {Map<string, string[]>} map */
1660
+ constructor(map) {
1661
+ this.#map = map;
1662
+ }
1663
+
1664
+ /** @param {string} key */
1665
+ get(key) {
1666
+ const value = this.#map.get(key);
1667
+ return value && value[0];
1668
+ }
1669
+
1670
+ /** @param {string} key */
1671
+ getAll(key) {
1672
+ return this.#map.get(key);
1673
+ }
1674
+
1675
+ /** @param {string} key */
1676
+ has(key) {
1677
+ return this.#map.has(key);
1678
+ }
1679
+
1680
+ *[Symbol.iterator]() {
1681
+ for (const [key, value] of this.#map) {
1682
+ for (let i = 0; i < value.length; i += 1) {
1683
+ yield [key, value[i]];
1684
+ }
1685
+ }
1686
+ }
1687
+
1688
+ *entries() {
1689
+ for (const [key, value] of this.#map) {
1690
+ for (let i = 0; i < value.length; i += 1) {
1691
+ yield [key, value[i]];
1692
+ }
1693
+ }
1694
+ }
1695
+
1696
+ *keys() {
1697
+ for (const [key] of this.#map) yield key;
1698
+ }
1699
+
1700
+ *values() {
1701
+ for (const [, value] of this.#map) {
1702
+ for (let i = 0; i < value.length; i += 1) {
1703
+ yield value[i];
1704
+ }
1705
+ }
1706
+ }
1707
+ }
1708
+
1709
+ /**
1710
+ * @param {import('types/app').RawBody} raw
1711
+ * @param {import('types/helper').RequestHeaders} headers
1712
+ */
1713
+ function parse_body(raw, headers) {
1714
+ if (!raw) return raw;
1715
+
1716
+ const content_type = headers['content-type'];
1717
+ const [type, ...directives] = content_type ? content_type.split(/;\s*/) : [];
1718
+
1719
+ const text = () => new TextDecoder(headers['content-encoding'] || 'utf-8').decode(raw);
1720
+
1721
+ switch (type) {
1722
+ case 'text/plain':
1723
+ return text();
1724
+
1725
+ case 'application/json':
1726
+ return JSON.parse(text());
1727
+
1728
+ case 'application/x-www-form-urlencoded':
1729
+ return get_urlencoded(text());
1730
+
1731
+ case 'multipart/form-data': {
1732
+ const boundary = directives.find((directive) => directive.startsWith('boundary='));
1733
+ if (!boundary) throw new Error('Missing boundary');
1734
+ return get_multipart(text(), boundary.slice('boundary='.length));
1735
+ }
1736
+ default:
1737
+ return raw;
1738
+ }
1739
+ }
1740
+
1741
+ /** @param {string} text */
1742
+ function get_urlencoded(text) {
1743
+ const { data, append } = read_only_form_data();
1744
+
1745
+ text
1746
+ .replace(/\+/g, ' ')
1747
+ .split('&')
1748
+ .forEach((str) => {
1749
+ const [key, value] = str.split('=');
1750
+ append(decodeURIComponent(key), decodeURIComponent(value));
1751
+ });
1752
+
1753
+ return data;
1754
+ }
1755
+
1756
+ /**
1757
+ * @param {string} text
1758
+ * @param {string} boundary
1759
+ */
1760
+ function get_multipart(text, boundary) {
1761
+ const parts = text.split(`--${boundary}`);
1762
+
1763
+ if (parts[0] !== '' || parts[parts.length - 1].trim() !== '--') {
1764
+ throw new Error('Malformed form data');
1765
+ }
1766
+
1767
+ const { data, append } = read_only_form_data();
1768
+
1769
+ parts.slice(1, -1).forEach((part) => {
1770
+ const match = /\s*([\s\S]+?)\r\n\r\n([\s\S]*)\s*/.exec(part);
1771
+ if (!match) {
1772
+ throw new Error('Malformed form data');
1773
+ }
1774
+ const raw_headers = match[1];
1775
+ const body = match[2].trim();
1776
+
1777
+ let key;
1778
+
1779
+ /** @type {Record<string, string>} */
1780
+ const headers = {};
1781
+ raw_headers.split('\r\n').forEach((str) => {
1782
+ const [raw_header, ...raw_directives] = str.split('; ');
1783
+ let [name, value] = raw_header.split(': ');
1784
+
1785
+ name = name.toLowerCase();
1786
+ headers[name] = value;
1787
+
1788
+ /** @type {Record<string, string>} */
1789
+ const directives = {};
1790
+ raw_directives.forEach((raw_directive) => {
1791
+ const [name, value] = raw_directive.split('=');
1792
+ directives[name] = JSON.parse(value); // TODO is this right?
1793
+ });
1794
+
1795
+ if (name === 'content-disposition') {
1796
+ if (value !== 'form-data') throw new Error('Malformed form data');
1797
+
1798
+ if (directives.filename) {
1799
+ // TODO we probably don't want to do this automatically
1800
+ throw new Error('File upload is not yet implemented');
1801
+ }
1802
+
1803
+ if (directives.name) {
1804
+ key = directives.name;
1805
+ }
1806
+ }
1807
+ });
1808
+
1809
+ if (!key) throw new Error('Malformed form data');
1810
+
1811
+ append(key, body);
1812
+ });
1813
+
1814
+ return data;
1815
+ }
1816
+
1817
+ /** @type {import('@sveltejs/kit/ssr').Respond} */
1818
+ async function respond(incoming, options, state = {}) {
1819
+ if (incoming.url.pathname !== '/' && options.trailing_slash !== 'ignore') {
1820
+ const has_trailing_slash = incoming.url.pathname.endsWith('/');
1821
+
1822
+ if (
1823
+ (has_trailing_slash && options.trailing_slash === 'never') ||
1824
+ (!has_trailing_slash &&
1825
+ options.trailing_slash === 'always' &&
1826
+ !(incoming.url.pathname.split('/').pop() || '').includes('.'))
1827
+ ) {
1828
+ incoming.url.pathname = has_trailing_slash
1829
+ ? incoming.url.pathname.slice(0, -1)
1830
+ : incoming.url.pathname + '/';
1831
+
1832
+ if (incoming.url.search === '?') incoming.url.search = '';
1833
+
1834
+ return {
1835
+ status: 301,
1836
+ headers: {
1837
+ location: incoming.url.pathname + incoming.url.search
1838
+ }
1839
+ };
1840
+ }
1841
+ }
1842
+
1843
+ const headers = lowercase_keys(incoming.headers);
1844
+ const request = {
1845
+ ...incoming,
1846
+ headers,
1847
+ body: parse_body(incoming.rawBody, headers),
1848
+ params: {},
1849
+ locals: {}
1850
+ };
1851
+
1852
+ const { parameter, allowed } = options.method_override;
1853
+ const method_override = incoming.url.searchParams.get(parameter)?.toUpperCase();
1854
+
1855
+ if (method_override) {
1856
+ if (request.method.toUpperCase() === 'POST') {
1857
+ if (allowed.includes(method_override)) {
1858
+ request.method = method_override;
1859
+ } else {
1860
+ const verb = allowed.length === 0 ? 'enabled' : 'allowed';
1861
+ const body = `${parameter}=${method_override} is not ${verb}. See https://kit.svelte.dev/docs#configuration-methodoverride`;
1862
+
1863
+ return {
1864
+ status: 400,
1865
+ headers: {},
1866
+ body
1867
+ };
1868
+ }
1869
+ } else {
1870
+ throw new Error(`${parameter}=${method_override} is only allowed with POST requests`);
1871
+ }
1872
+ }
1873
+
1874
+ // TODO remove this for 1.0
1875
+ /**
1876
+ * @param {string} property
1877
+ * @param {string} replacement
1878
+ */
1879
+ const print_error = (property, replacement) => {
1880
+ Object.defineProperty(request, property, {
1881
+ get: () => {
1882
+ throw new Error(`request.${property} has been replaced by request.url.${replacement}`);
1883
+ }
1884
+ });
1885
+ };
1886
+
1887
+ print_error('origin', 'origin');
1888
+ print_error('path', 'pathname');
1889
+ print_error('query', 'searchParams');
1890
+
1891
+ let ssr = true;
1892
+
1893
+ try {
1894
+ return await options.hooks.handle({
1895
+ request,
1896
+ resolve: async (request, opts) => {
1897
+ if (opts && 'ssr' in opts) ssr = /** @type {boolean} */ (opts.ssr);
1898
+
1899
+ if (state.prerender && state.prerender.fallback) {
1900
+ return await render_response({
1901
+ url: request.url,
1902
+ params: request.params,
1903
+ options,
1904
+ $session: await options.hooks.getSession(request),
1905
+ page_config: { router: true, hydrate: true },
1906
+ stuff: {},
1907
+ status: 200,
1908
+ branch: [],
1909
+ ssr: false
1910
+ });
1911
+ }
1912
+
1913
+ const decoded = decodeURI(request.url.pathname).replace(options.paths.base, '');
1914
+
1915
+ for (const route of options.manifest._.routes) {
1916
+ const match = route.pattern.exec(decoded);
1917
+ if (!match) continue;
1918
+
1919
+ const response =
1920
+ route.type === 'endpoint'
1921
+ ? await render_endpoint(request, route, match)
1922
+ : await render_page(request, route, match, options, state, ssr);
1923
+
1924
+ if (response) {
1925
+ // inject ETags for 200 responses
1926
+ if (response.status === 200) {
1927
+ const cache_control = get_single_valued_header(response.headers, 'cache-control');
1928
+ if (!cache_control || !/(no-store|immutable)/.test(cache_control)) {
1929
+ let if_none_match_value = request.headers['if-none-match'];
1930
+ // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives
1931
+ if (if_none_match_value?.startsWith('W/"')) {
1932
+ if_none_match_value = if_none_match_value.substring(2);
1933
+ }
1934
+
1935
+ const etag = `"${hash(response.body || '')}"`;
1936
+
1937
+ if (if_none_match_value === etag) {
1938
+ return {
1939
+ status: 304,
1940
+ headers: {}
1941
+ };
1942
+ }
1943
+
1944
+ response.headers['etag'] = etag;
1945
+ }
1946
+ }
1947
+
1948
+ return response;
1949
+ }
1950
+ }
1951
+
1952
+ // if this request came direct from the user, rather than
1953
+ // via a `fetch` in a `load`, render a 404 page
1954
+ if (!state.initiator) {
1955
+ const $session = await options.hooks.getSession(request);
1956
+ return await respond_with_error({
1957
+ request,
1958
+ options,
1959
+ state,
1960
+ $session,
1961
+ status: 404,
1962
+ error: new Error(`Not found: ${request.url.pathname}`),
1963
+ ssr
1964
+ });
1965
+ }
1966
+ }
1967
+ });
1968
+ } catch (/** @type {unknown} */ e) {
1969
+ const error = coalesce_to_error(e);
1970
+
1971
+ options.handle_error(error, request);
1972
+
1973
+ try {
1974
+ const $session = await options.hooks.getSession(request);
1975
+ return await respond_with_error({
1976
+ request,
1977
+ options,
1978
+ state,
1979
+ $session,
1980
+ status: 500,
1981
+ error,
1982
+ ssr
1983
+ });
1984
+ } catch (/** @type {unknown} */ e) {
1985
+ const error = coalesce_to_error(e);
1986
+
1987
+ return {
1988
+ status: 500,
1989
+ headers: {},
1990
+ body: options.dev ? error.stack : error.message
1991
+ };
1992
+ }
1993
+ }
1994
+ }
1995
+
1996
+ export { respond };