@sveltejs/kit 1.0.0-next.33 → 1.0.0-next.332

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