@sveltejs/kit 1.0.0-next.48 → 1.0.0-next.480

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 (117) hide show
  1. package/README.md +12 -9
  2. package/package.json +93 -64
  3. package/scripts/special-types/$env+dynamic+private.md +10 -0
  4. package/scripts/special-types/$env+dynamic+public.md +8 -0
  5. package/scripts/special-types/$env+static+private.md +19 -0
  6. package/scripts/special-types/$env+static+public.md +7 -0
  7. package/scripts/special-types/$lib.md +1 -0
  8. package/src/cli.js +112 -0
  9. package/src/constants.js +7 -0
  10. package/src/core/adapt/builder.js +207 -0
  11. package/src/core/adapt/index.js +31 -0
  12. package/src/core/config/default-error.html +56 -0
  13. package/src/core/config/index.js +110 -0
  14. package/src/core/config/options.js +504 -0
  15. package/src/core/config/types.d.ts +1 -0
  16. package/src/core/env.js +121 -0
  17. package/src/core/generate_manifest/index.js +92 -0
  18. package/src/core/prerender/crawl.js +194 -0
  19. package/src/core/prerender/prerender.js +431 -0
  20. package/src/core/prerender/queue.js +80 -0
  21. package/src/core/sync/create_manifest_data/index.js +472 -0
  22. package/src/core/sync/create_manifest_data/types.d.ts +37 -0
  23. package/src/core/sync/sync.js +59 -0
  24. package/src/core/sync/utils.js +33 -0
  25. package/src/core/sync/write_ambient.js +53 -0
  26. package/src/core/sync/write_client_manifest.js +106 -0
  27. package/src/core/sync/write_matchers.js +25 -0
  28. package/src/core/sync/write_root.js +91 -0
  29. package/src/core/sync/write_tsconfig.js +195 -0
  30. package/src/core/sync/write_types/index.js +673 -0
  31. package/src/core/utils.js +70 -0
  32. package/src/exports/hooks/index.js +1 -0
  33. package/src/exports/hooks/sequence.js +44 -0
  34. package/src/exports/index.js +45 -0
  35. package/src/exports/node/index.js +163 -0
  36. package/src/exports/node/polyfills.js +41 -0
  37. package/src/exports/vite/build/build_server.js +372 -0
  38. package/src/exports/vite/build/build_service_worker.js +90 -0
  39. package/src/exports/vite/build/utils.js +162 -0
  40. package/src/exports/vite/dev/index.js +576 -0
  41. package/src/exports/vite/index.js +597 -0
  42. package/src/exports/vite/preview/index.js +189 -0
  43. package/src/exports/vite/types.d.ts +3 -0
  44. package/src/exports/vite/utils.js +438 -0
  45. package/src/runtime/app/env.js +1 -0
  46. package/src/runtime/app/environment.js +11 -0
  47. package/src/runtime/app/forms.js +108 -0
  48. package/src/runtime/app/navigation.js +23 -0
  49. package/src/runtime/app/paths.js +1 -0
  50. package/src/runtime/app/stores.js +102 -0
  51. package/src/runtime/client/ambient.d.ts +26 -0
  52. package/src/runtime/client/client.js +1569 -0
  53. package/src/runtime/client/fetcher.js +107 -0
  54. package/src/runtime/client/parse.js +60 -0
  55. package/src/runtime/client/singletons.js +21 -0
  56. package/src/runtime/client/start.js +37 -0
  57. package/src/runtime/client/types.d.ts +85 -0
  58. package/src/runtime/client/utils.js +159 -0
  59. package/src/runtime/components/error.svelte +16 -0
  60. package/{assets → src/runtime}/components/layout.svelte +0 -0
  61. package/src/runtime/control.js +98 -0
  62. package/src/runtime/env/dynamic/private.js +1 -0
  63. package/src/runtime/env/dynamic/public.js +1 -0
  64. package/src/runtime/env-private.js +6 -0
  65. package/src/runtime/env-public.js +6 -0
  66. package/src/runtime/env.js +6 -0
  67. package/src/runtime/hash.js +16 -0
  68. package/src/runtime/paths.js +11 -0
  69. package/src/runtime/server/cookie.js +77 -0
  70. package/src/runtime/server/data/index.js +136 -0
  71. package/src/runtime/server/endpoint.js +66 -0
  72. package/src/runtime/server/index.js +343 -0
  73. package/src/runtime/server/page/actions.js +243 -0
  74. package/src/runtime/server/page/crypto.js +239 -0
  75. package/src/runtime/server/page/csp.js +249 -0
  76. package/src/runtime/server/page/fetch.js +286 -0
  77. package/src/runtime/server/page/index.js +304 -0
  78. package/src/runtime/server/page/load_data.js +124 -0
  79. package/src/runtime/server/page/render.js +346 -0
  80. package/src/runtime/server/page/respond_with_error.js +92 -0
  81. package/src/runtime/server/page/serialize_data.js +87 -0
  82. package/src/runtime/server/page/types.d.ts +35 -0
  83. package/src/runtime/server/utils.js +178 -0
  84. package/src/utils/array.js +9 -0
  85. package/src/utils/error.js +22 -0
  86. package/src/utils/escape.js +46 -0
  87. package/src/utils/filesystem.js +137 -0
  88. package/src/utils/functions.js +16 -0
  89. package/src/utils/http.js +55 -0
  90. package/src/utils/misc.js +1 -0
  91. package/src/utils/routing.js +117 -0
  92. package/src/utils/url.js +142 -0
  93. package/svelte-kit.js +1 -1
  94. package/types/ambient.d.ts +426 -0
  95. package/types/index.d.ts +410 -0
  96. package/types/internal.d.ts +384 -0
  97. package/types/private.d.ts +210 -0
  98. package/CHANGELOG.md +0 -469
  99. package/assets/components/error.svelte +0 -13
  100. package/assets/runtime/app/env.js +0 -5
  101. package/assets/runtime/app/navigation.js +0 -44
  102. package/assets/runtime/app/paths.js +0 -1
  103. package/assets/runtime/app/stores.js +0 -93
  104. package/assets/runtime/chunks/utils.js +0 -22
  105. package/assets/runtime/internal/singletons.js +0 -23
  106. package/assets/runtime/internal/start.js +0 -773
  107. package/assets/runtime/paths.js +0 -12
  108. package/dist/chunks/index.js +0 -3517
  109. package/dist/chunks/index2.js +0 -587
  110. package/dist/chunks/index3.js +0 -246
  111. package/dist/chunks/index4.js +0 -530
  112. package/dist/chunks/index5.js +0 -763
  113. package/dist/chunks/index6.js +0 -322
  114. package/dist/chunks/standard.js +0 -99
  115. package/dist/chunks/utils.js +0 -83
  116. package/dist/cli.js +0 -553
  117. package/dist/ssr.js +0 -2581
@@ -0,0 +1,77 @@
1
+ import * as cookie from 'cookie';
2
+
3
+ /**
4
+ * @param {Request} request
5
+ * @param {URL} url
6
+ */
7
+ export function get_cookies(request, url) {
8
+ const initial_cookies = cookie.parse(request.headers.get('cookie') ?? '');
9
+
10
+ /** @type {Array<{ name: string, value: string, options: import('cookie').CookieSerializeOptions }>} */
11
+ const new_cookies = [];
12
+
13
+ /** @type {import('types').Cookies} */
14
+ const cookies = {
15
+ get(name, opts) {
16
+ const decode = opts?.decode || decodeURIComponent;
17
+
18
+ let i = new_cookies.length;
19
+ while (i--) {
20
+ const cookie = new_cookies[i];
21
+
22
+ if (
23
+ cookie.name === name &&
24
+ domain_matches(url.hostname, cookie.options.domain) &&
25
+ path_matches(url.pathname, cookie.options.path)
26
+ ) {
27
+ return cookie.value;
28
+ }
29
+ }
30
+
31
+ return name in initial_cookies ? decode(initial_cookies[name]) : undefined;
32
+ },
33
+ set(name, value, options = {}) {
34
+ new_cookies.push({
35
+ name,
36
+ value,
37
+ options: {
38
+ httpOnly: true,
39
+ secure: true,
40
+ ...options
41
+ }
42
+ });
43
+ },
44
+ delete(name) {
45
+ new_cookies.push({ name, value: '', options: { expires: new Date(0) } });
46
+ delete initial_cookies[name];
47
+ }
48
+ };
49
+
50
+ return { cookies, new_cookies };
51
+ }
52
+
53
+ /**
54
+ * @param {string} hostname
55
+ * @param {string} [constraint]
56
+ */
57
+ export function domain_matches(hostname, constraint) {
58
+ if (!constraint) return true;
59
+
60
+ const normalized = constraint[0] === '.' ? constraint.slice(1) : constraint;
61
+
62
+ if (hostname === normalized) return true;
63
+ return hostname.endsWith('.' + normalized);
64
+ }
65
+
66
+ /**
67
+ * @param {string} path
68
+ * @param {string} [constraint]
69
+ */
70
+ export function path_matches(path, constraint) {
71
+ if (!constraint) return true;
72
+
73
+ const normalized = constraint.endsWith('/') ? constraint.slice(0, -1) : constraint;
74
+
75
+ if (path === normalized) return true;
76
+ return path.startsWith(normalized + '/');
77
+ }
@@ -0,0 +1,136 @@
1
+ import { HttpError, Redirect } from '../../control.js';
2
+ import { normalize_error } from '../../../utils/error.js';
3
+ import { once } from '../../../utils/functions.js';
4
+ import { load_server_data } from '../page/load_data.js';
5
+ import { data_response, handle_error_and_jsonify } from '../utils.js';
6
+ import { normalize_path } from '../../../utils/url.js';
7
+ import { DATA_SUFFIX } from '../../../constants.js';
8
+
9
+ /**
10
+ * @param {import('types').RequestEvent} event
11
+ * @param {import('types').SSRRoute} route
12
+ * @param {import('types').SSROptions} options
13
+ * @param {import('types').SSRState} state
14
+ * @returns {Promise<Response>}
15
+ */
16
+ export async function render_data(event, route, options, state) {
17
+ if (!route.page) {
18
+ // requesting /__data.js should fail for a +server.js
19
+ return new Response(undefined, {
20
+ status: 404
21
+ });
22
+ }
23
+
24
+ try {
25
+ const node_ids = [...route.page.layouts, route.page.leaf];
26
+
27
+ const invalidated =
28
+ event.url.searchParams
29
+ .get('__invalid')
30
+ ?.split('')
31
+ .map((x) => x === 'y') ?? node_ids.map(() => true);
32
+
33
+ let aborted = false;
34
+
35
+ const url = new URL(event.url);
36
+ url.pathname = normalize_path(
37
+ url.pathname.slice(0, -DATA_SUFFIX.length),
38
+ options.trailing_slash
39
+ );
40
+
41
+ url.searchParams.delete('__invalid');
42
+ url.searchParams.delete('__id');
43
+
44
+ const new_event = { ...event, url };
45
+
46
+ const functions = node_ids.map((n, i) => {
47
+ return once(async () => {
48
+ try {
49
+ if (aborted) {
50
+ return /** @type {import('types').ServerDataSkippedNode} */ ({
51
+ type: 'skip'
52
+ });
53
+ }
54
+
55
+ // == because it could be undefined (in dev) or null (in build, because of JSON.stringify)
56
+ const node = n == undefined ? n : await options.manifest._.nodes[n]();
57
+ return load_server_data({
58
+ event: new_event,
59
+ state,
60
+ node,
61
+ parent: async () => {
62
+ /** @type {Record<string, any>} */
63
+ const data = {};
64
+ for (let j = 0; j < i; j += 1) {
65
+ const parent = /** @type {import('types').ServerDataNode | null} */ (
66
+ await functions[j]()
67
+ );
68
+
69
+ if (parent) {
70
+ Object.assign(data, parent.data);
71
+ }
72
+ }
73
+ return data;
74
+ }
75
+ });
76
+ } catch (e) {
77
+ aborted = true;
78
+ throw e;
79
+ }
80
+ });
81
+ });
82
+
83
+ const promises = functions.map(async (fn, i) => {
84
+ if (!invalidated[i]) {
85
+ return /** @type {import('types').ServerDataSkippedNode} */ ({
86
+ type: 'skip'
87
+ });
88
+ }
89
+
90
+ return fn();
91
+ });
92
+
93
+ let length = promises.length;
94
+ const nodes = await Promise.all(
95
+ promises.map((p, i) =>
96
+ p.catch((error) => {
97
+ if (error instanceof Redirect) {
98
+ throw error;
99
+ }
100
+
101
+ // Math.min because array isn't guaranteed to resolve in order
102
+ length = Math.min(length, i + 1);
103
+
104
+ return /** @type {import('types').ServerErrorNode} */ ({
105
+ type: 'error',
106
+ error: handle_error_and_jsonify(event, options, error),
107
+ status: error instanceof HttpError ? error.status : undefined
108
+ });
109
+ })
110
+ )
111
+ );
112
+
113
+ /** @type {import('types').ServerData} */
114
+ const server_data = {
115
+ type: 'data',
116
+ nodes: nodes.slice(0, length)
117
+ };
118
+
119
+ return data_response(server_data);
120
+ } catch (e) {
121
+ const error = normalize_error(e);
122
+
123
+ if (error instanceof Redirect) {
124
+ /** @type {import('types').ServerData} */
125
+ const server_data = {
126
+ type: 'redirect',
127
+ location: error.location
128
+ };
129
+
130
+ return data_response(server_data);
131
+ } else {
132
+ // TODO make it clearer that this was an unexpected error
133
+ return data_response(handle_error_and_jsonify(event, options, error));
134
+ }
135
+ }
136
+ }
@@ -0,0 +1,66 @@
1
+ import { json } from '../../exports/index.js';
2
+ import { Redirect, ValidationError } from '../control.js';
3
+ import { check_method_names, method_not_allowed } from './utils.js';
4
+
5
+ /**
6
+ * @param {import('types').RequestEvent} event
7
+ * @param {import('types').SSREndpoint} mod
8
+ * @param {import('types').SSRState} state
9
+ * @returns {Promise<Response>}
10
+ */
11
+ export async function render_endpoint(event, mod, state) {
12
+ const method = /** @type {import('types').HttpMethod} */ (event.request.method);
13
+
14
+ // TODO: Remove for 1.0
15
+ check_method_names(mod);
16
+
17
+ let handler = mod[method];
18
+
19
+ if (!handler && method === 'HEAD') {
20
+ handler = mod.GET;
21
+ }
22
+
23
+ if (!handler) {
24
+ return method_not_allowed(mod, method);
25
+ }
26
+
27
+ const prerender = mod.prerender ?? state.prerender_default;
28
+
29
+ if (prerender && (mod.POST || mod.PATCH || mod.PUT || mod.DELETE)) {
30
+ throw new Error('Cannot prerender endpoints that have mutative methods');
31
+ }
32
+
33
+ if (state.prerendering && !prerender) {
34
+ throw new Error(`${event.routeId} is not prerenderable`);
35
+ }
36
+
37
+ try {
38
+ const response = await handler(
39
+ /** @type {import('types').RequestEvent<Record<string, any>>} */ (event)
40
+ );
41
+
42
+ if (!(response instanceof Response)) {
43
+ throw new Error(
44
+ `Invalid response from route ${event.url.pathname}: handler should return a Response object`
45
+ );
46
+ }
47
+
48
+ if (state.prerendering) {
49
+ response.headers.set('x-sveltekit-routeid', /** @type {string} */ (event.routeId));
50
+ response.headers.set('x-sveltekit-prerender', String(prerender));
51
+ }
52
+
53
+ return response;
54
+ } catch (error) {
55
+ if (error instanceof Redirect) {
56
+ return new Response(undefined, {
57
+ status: error.status,
58
+ headers: { location: error.location }
59
+ });
60
+ } else if (error instanceof ValidationError) {
61
+ return json(error.data, { status: error.status });
62
+ }
63
+
64
+ throw error;
65
+ }
66
+ }
@@ -0,0 +1,343 @@
1
+ import * as cookie from 'cookie';
2
+ import { render_endpoint } from './endpoint.js';
3
+ import { render_page } from './page/index.js';
4
+ import { render_response } from './page/render.js';
5
+ import { respond_with_error } from './page/respond_with_error.js';
6
+ import { coalesce_to_error } from '../../utils/error.js';
7
+ import { GENERIC_ERROR, handle_fatal_error } from './utils.js';
8
+ import { decode_params, disable_search, normalize_path } from '../../utils/url.js';
9
+ import { exec } from '../../utils/routing.js';
10
+ import { render_data } from './data/index.js';
11
+ import { DATA_SUFFIX } from '../../constants.js';
12
+ import { get_cookies } from './cookie.js';
13
+ import { HttpError } from '../control.js';
14
+
15
+ /* global __SVELTEKIT_ADAPTER_NAME__ */
16
+
17
+ /** @param {{ html: string }} opts */
18
+ const default_transform = ({ html }) => html;
19
+
20
+ const default_filter = () => false;
21
+
22
+ /** @type {import('types').Respond} */
23
+ export async function respond(request, options, state) {
24
+ let url = new URL(request.url);
25
+
26
+ if (options.csrf.check_origin) {
27
+ const type = request.headers.get('content-type')?.split(';')[0];
28
+
29
+ const forbidden =
30
+ request.method === 'POST' &&
31
+ request.headers.get('origin') !== url.origin &&
32
+ (type === 'application/x-www-form-urlencoded' || type === 'multipart/form-data');
33
+
34
+ if (forbidden) {
35
+ return new Response(`Cross-site ${request.method} form submissions are forbidden`, {
36
+ status: 403
37
+ });
38
+ }
39
+ }
40
+
41
+ let decoded;
42
+ try {
43
+ decoded = decodeURI(url.pathname);
44
+ } catch {
45
+ return new Response('Malformed URI', { status: 400 });
46
+ }
47
+
48
+ /** @type {import('types').SSRRoute | null} */
49
+ let route = null;
50
+
51
+ /** @type {Record<string, string>} */
52
+ let params = {};
53
+
54
+ if (options.paths.base && !state.prerendering?.fallback) {
55
+ if (!decoded.startsWith(options.paths.base)) {
56
+ return new Response('Not found', { status: 404 });
57
+ }
58
+ decoded = decoded.slice(options.paths.base.length) || '/';
59
+ }
60
+
61
+ const is_data_request = decoded.endsWith(DATA_SUFFIX);
62
+ if (is_data_request) decoded = decoded.slice(0, -DATA_SUFFIX.length) || '/';
63
+
64
+ if (!state.prerendering?.fallback) {
65
+ const matchers = await options.manifest._.matchers();
66
+
67
+ for (const candidate of options.manifest._.routes) {
68
+ const match = candidate.pattern.exec(decoded);
69
+ if (!match) continue;
70
+
71
+ const matched = exec(match, candidate.names, candidate.types, matchers);
72
+ if (matched) {
73
+ route = candidate;
74
+ params = decode_params(matched);
75
+ break;
76
+ }
77
+ }
78
+ }
79
+
80
+ if (route?.page && !is_data_request) {
81
+ const normalized = normalize_path(url.pathname, options.trailing_slash);
82
+
83
+ if (normalized !== url.pathname && !state.prerendering?.fallback) {
84
+ return new Response(undefined, {
85
+ status: 301,
86
+ headers: {
87
+ 'x-sveltekit-normalize': '1',
88
+ location:
89
+ // ensure paths starting with '//' are not treated as protocol-relative
90
+ (normalized.startsWith('//') ? url.origin + normalized : normalized) +
91
+ (url.search === '?' ? '' : url.search)
92
+ }
93
+ });
94
+ }
95
+ }
96
+
97
+ /** @type {Record<string, string>} */
98
+ const headers = {};
99
+
100
+ const { cookies, new_cookies } = get_cookies(request, url);
101
+
102
+ if (state.prerendering) disable_search(url);
103
+
104
+ /** @type {import('types').RequestEvent} */
105
+ const event = {
106
+ cookies,
107
+ getClientAddress:
108
+ state.getClientAddress ||
109
+ (() => {
110
+ throw new Error(
111
+ `${__SVELTEKIT_ADAPTER_NAME__} does not specify getClientAddress. Please raise an issue`
112
+ );
113
+ }),
114
+ locals: {},
115
+ params,
116
+ platform: state.platform,
117
+ request,
118
+ routeId: route && route.id,
119
+ setHeaders: (new_headers) => {
120
+ for (const key in new_headers) {
121
+ const lower = key.toLowerCase();
122
+ const value = new_headers[key];
123
+
124
+ if (lower === 'set-cookie') {
125
+ throw new Error(
126
+ `Use \`event.cookies.set(name, value, options)\` instead of \`event.setHeaders\` to set cookies`
127
+ );
128
+ } else if (lower in headers) {
129
+ throw new Error(`"${key}" header is already set`);
130
+ } else {
131
+ headers[lower] = value;
132
+
133
+ if (state.prerendering && lower === 'cache-control') {
134
+ state.prerendering.cache = /** @type {string} */ (value);
135
+ }
136
+ }
137
+ }
138
+ },
139
+ url
140
+ };
141
+
142
+ // TODO remove this for 1.0
143
+ /**
144
+ * @param {string} property
145
+ * @param {string} replacement
146
+ * @param {string} suffix
147
+ */
148
+ const removed = (property, replacement, suffix = '') => ({
149
+ get: () => {
150
+ throw new Error(`event.${property} has been replaced by event.${replacement}` + suffix);
151
+ }
152
+ });
153
+
154
+ const details = '. See https://github.com/sveltejs/kit/pull/3384 for details';
155
+
156
+ const body_getter = {
157
+ get: () => {
158
+ throw new Error(
159
+ 'To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`' +
160
+ details
161
+ );
162
+ }
163
+ };
164
+
165
+ Object.defineProperties(event, {
166
+ clientAddress: removed('clientAddress', 'getClientAddress'),
167
+ method: removed('method', 'request.method', details),
168
+ headers: removed('headers', 'request.headers', details),
169
+ origin: removed('origin', 'url.origin'),
170
+ path: removed('path', 'url.pathname'),
171
+ query: removed('query', 'url.searchParams'),
172
+ body: body_getter,
173
+ rawBody: body_getter
174
+ });
175
+
176
+ /** @type {import('types').RequiredResolveOptions} */
177
+ let resolve_opts = {
178
+ transformPageChunk: default_transform,
179
+ filterSerializedResponseHeaders: default_filter
180
+ };
181
+
182
+ /**
183
+ *
184
+ * @param {import('types').RequestEvent} event
185
+ * @param {import('types').ResolveOptions} [opts]
186
+ */
187
+ async function resolve(event, opts) {
188
+ try {
189
+ if (opts) {
190
+ // TODO remove for 1.0
191
+ if ('transformPage' in opts) {
192
+ throw new Error(
193
+ 'transformPage has been replaced by transformPageChunk — see https://github.com/sveltejs/kit/pull/5657 for more information'
194
+ );
195
+ }
196
+
197
+ if ('ssr' in opts) {
198
+ throw new Error(
199
+ 'ssr has been removed, set it in the appropriate +layout.js instead. See the PR for more information: https://github.com/sveltejs/kit/pull/6197'
200
+ );
201
+ }
202
+
203
+ resolve_opts = {
204
+ transformPageChunk: opts.transformPageChunk || default_transform,
205
+ filterSerializedResponseHeaders: opts.filterSerializedResponseHeaders || default_filter
206
+ };
207
+ }
208
+
209
+ if (state.prerendering?.fallback) {
210
+ return await render_response({
211
+ event,
212
+ options,
213
+ state,
214
+ page_config: { ssr: false, csr: true },
215
+ status: 200,
216
+ error: null,
217
+ branch: [],
218
+ fetched: [],
219
+ cookies: [],
220
+ resolve_opts
221
+ });
222
+ }
223
+
224
+ if (route) {
225
+ /** @type {Response} */
226
+ let response;
227
+
228
+ if (is_data_request) {
229
+ response = await render_data(event, route, options, state);
230
+ } else if (route.page) {
231
+ response = await render_page(event, route, route.page, options, state, resolve_opts);
232
+ } else if (route.endpoint) {
233
+ response = await render_endpoint(event, await route.endpoint(), state);
234
+ } else {
235
+ // a route will always have a page or an endpoint, but TypeScript
236
+ // doesn't know that
237
+ throw new Error('This should never happen');
238
+ }
239
+
240
+ if (!is_data_request) {
241
+ // we only want to set cookies on __data.js requests, we don't
242
+ // want to cache stuff erroneously etc
243
+ for (const key in headers) {
244
+ const value = headers[key];
245
+ response.headers.set(key, /** @type {string} */ (value));
246
+ }
247
+ }
248
+
249
+ for (const new_cookie of new_cookies) {
250
+ response.headers.append(
251
+ 'set-cookie',
252
+ cookie.serialize(new_cookie.name, new_cookie.value, new_cookie.options)
253
+ );
254
+ }
255
+
256
+ return response;
257
+ }
258
+
259
+ if (state.initiator === GENERIC_ERROR) {
260
+ return new Response('Internal Server Error', {
261
+ status: 500
262
+ });
263
+ }
264
+
265
+ // if this request came direct from the user, rather than
266
+ // via a `fetch` in a `load`, render a 404 page
267
+ if (!state.initiator) {
268
+ return await respond_with_error({
269
+ event,
270
+ options,
271
+ state,
272
+ status: 404,
273
+ error: new Error(`Not found: ${event.url.pathname}`),
274
+ resolve_opts
275
+ });
276
+ }
277
+
278
+ if (state.prerendering) {
279
+ return new Response('not found', { status: 404 });
280
+ }
281
+
282
+ // we can't load the endpoint from our own manifest,
283
+ // so we need to make an actual HTTP request
284
+ return await fetch(request);
285
+ } catch (e) {
286
+ // HttpError can come from endpoint - TODO should it be handled there instead?
287
+ const error = e instanceof HttpError ? e : coalesce_to_error(e);
288
+ return handle_fatal_error(event, options, error);
289
+ } finally {
290
+ event.cookies.set = () => {
291
+ throw new Error('Cannot use `cookies.set(...)` after the response has been generated');
292
+ };
293
+
294
+ event.setHeaders = () => {
295
+ throw new Error('Cannot use `setHeaders(...)` after the response has been generated');
296
+ };
297
+ }
298
+ }
299
+
300
+ try {
301
+ const response = await options.hooks.handle({
302
+ event,
303
+ resolve,
304
+ // TODO remove for 1.0
305
+ // @ts-expect-error
306
+ get request() {
307
+ throw new Error('request in handle has been replaced with event' + details);
308
+ }
309
+ });
310
+
311
+ // respond with 304 if etag matches
312
+ if (response.status === 200 && response.headers.has('etag')) {
313
+ let if_none_match_value = request.headers.get('if-none-match');
314
+
315
+ // ignore W/ prefix https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match#directives
316
+ if (if_none_match_value?.startsWith('W/"')) {
317
+ if_none_match_value = if_none_match_value.substring(2);
318
+ }
319
+
320
+ const etag = /** @type {string} */ (response.headers.get('etag'));
321
+
322
+ if (if_none_match_value === etag) {
323
+ const headers = new Headers({ etag });
324
+
325
+ // https://datatracker.ietf.org/doc/html/rfc7232#section-4.1
326
+ for (const key of ['cache-control', 'content-location', 'date', 'expires', 'vary']) {
327
+ const value = response.headers.get(key);
328
+ if (value) headers.set(key, value);
329
+ }
330
+
331
+ return new Response(undefined, {
332
+ status: 304,
333
+ headers
334
+ });
335
+ }
336
+ }
337
+
338
+ return response;
339
+ } catch (/** @type {unknown} */ e) {
340
+ const error = coalesce_to_error(e);
341
+ return handle_fatal_error(event, options, error);
342
+ }
343
+ }