@k-4u/resource-mapper-core 0.0.1

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 (250) hide show
  1. package/.aws-icons-last-updated +1 -0
  2. package/.svelte-kit/ambient.d.ts +263 -0
  3. package/.svelte-kit/generated/client/app.js +31 -0
  4. package/.svelte-kit/generated/client/matchers.js +1 -0
  5. package/.svelte-kit/generated/client/nodes/0.js +1 -0
  6. package/.svelte-kit/generated/client/nodes/1.js +1 -0
  7. package/.svelte-kit/generated/client/nodes/2.js +3 -0
  8. package/.svelte-kit/generated/client/nodes/3.js +3 -0
  9. package/.svelte-kit/generated/client-optimized/app.js +31 -0
  10. package/.svelte-kit/generated/client-optimized/matchers.js +1 -0
  11. package/.svelte-kit/generated/client-optimized/nodes/0.js +1 -0
  12. package/.svelte-kit/generated/client-optimized/nodes/1.js +1 -0
  13. package/.svelte-kit/generated/client-optimized/nodes/2.js +3 -0
  14. package/.svelte-kit/generated/client-optimized/nodes/3.js +3 -0
  15. package/.svelte-kit/generated/root.js +3 -0
  16. package/.svelte-kit/generated/root.svelte +68 -0
  17. package/.svelte-kit/generated/server/internal.js +53 -0
  18. package/.svelte-kit/non-ambient.d.ts +43 -0
  19. package/.svelte-kit/output/client/.vite/manifest.json +175 -0
  20. package/.svelte-kit/output/client/_app/immutable/assets/0.Czt_67iE.css +1 -0
  21. package/.svelte-kit/output/client/_app/immutable/assets/TeamContactCard.Dxj5nUCr.css +1 -0
  22. package/.svelte-kit/output/client/_app/immutable/assets/helpers.ysDrpaDf.css +1 -0
  23. package/.svelte-kit/output/client/_app/immutable/assets/libavoid.DQJapW5w.wasm +0 -0
  24. package/.svelte-kit/output/client/_app/immutable/chunks/BlLuv0eP.js +46 -0
  25. package/.svelte-kit/output/client/_app/immutable/chunks/CSBHmwYv.js +1 -0
  26. package/.svelte-kit/output/client/_app/immutable/chunks/CTCi5ueQ.js +1 -0
  27. package/.svelte-kit/output/client/_app/immutable/chunks/CfOzjaik.js +2 -0
  28. package/.svelte-kit/output/client/_app/immutable/chunks/D4PdvFNs.js +1 -0
  29. package/.svelte-kit/output/client/_app/immutable/chunks/DXgP-QUS.js +2 -0
  30. package/.svelte-kit/output/client/_app/immutable/chunks/DlbDC5An.js +1 -0
  31. package/.svelte-kit/output/client/_app/immutable/chunks/wRWe7aK9.js +1 -0
  32. package/.svelte-kit/output/client/_app/immutable/entry/app.ConrMuHl.js +2 -0
  33. package/.svelte-kit/output/client/_app/immutable/entry/start.Bm6FyGme.js +1 -0
  34. package/.svelte-kit/output/client/_app/immutable/nodes/0.d3cL-ETU.js +1 -0
  35. package/.svelte-kit/output/client/_app/immutable/nodes/1.D6z9rPGv.js +1 -0
  36. package/.svelte-kit/output/client/_app/immutable/nodes/2.CLD-8chl.js +1 -0
  37. package/.svelte-kit/output/client/_app/immutable/nodes/3.DXYeBoel.js +1 -0
  38. package/.svelte-kit/output/client/_app/version.json +1 -0
  39. package/.svelte-kit/output/client/libavoid.wasm +0 -0
  40. package/.svelte-kit/output/client/static/robots.txt +3 -0
  41. package/.svelte-kit/output/prerendered/dependencies/_app/env.js +1 -0
  42. package/.svelte-kit/output/server/.vite/manifest.json +224 -0
  43. package/.svelte-kit/output/server/_app/immutable/assets/LoadingOverlay.DBbe6V8W.css +1 -0
  44. package/.svelte-kit/output/server/_app/immutable/assets/_layout.Czt_67iE.css +1 -0
  45. package/.svelte-kit/output/server/_app/immutable/assets/_page.D9P41uDZ.css +1 -0
  46. package/.svelte-kit/output/server/chunks/ErrorDisplay.js +59 -0
  47. package/.svelte-kit/output/server/chunks/LoadingOverlay.js +12 -0
  48. package/.svelte-kit/output/server/chunks/LoadingOverlay.svelte_svelte_type_style_lang.js +1671 -0
  49. package/.svelte-kit/output/server/chunks/connections.js +33 -0
  50. package/.svelte-kit/output/server/chunks/diagram.js +7 -0
  51. package/.svelte-kit/output/server/chunks/environment.js +34 -0
  52. package/.svelte-kit/output/server/chunks/equality.js +57 -0
  53. package/.svelte-kit/output/server/chunks/exports.js +174 -0
  54. package/.svelte-kit/output/server/chunks/false.js +4 -0
  55. package/.svelte-kit/output/server/chunks/index.js +59 -0
  56. package/.svelte-kit/output/server/chunks/index2.js +2939 -0
  57. package/.svelte-kit/output/server/chunks/index3.js +20 -0
  58. package/.svelte-kit/output/server/chunks/internal.js +1017 -0
  59. package/.svelte-kit/output/server/chunks/shared.js +770 -0
  60. package/.svelte-kit/output/server/chunks/utils.js +43 -0
  61. package/.svelte-kit/output/server/entries/pages/_error.svelte.js +64 -0
  62. package/.svelte-kit/output/server/entries/pages/_layout.svelte.js +65 -0
  63. package/.svelte-kit/output/server/entries/pages/_page.svelte.js +3991 -0
  64. package/.svelte-kit/output/server/entries/pages/_page.ts.js +30 -0
  65. package/.svelte-kit/output/server/entries/pages/group/_groupId_/_page.svelte.js +67 -0
  66. package/.svelte-kit/output/server/entries/pages/group/_groupId_/_page.ts.js +47 -0
  67. package/.svelte-kit/output/server/index.js +3747 -0
  68. package/.svelte-kit/output/server/internal.js +13 -0
  69. package/.svelte-kit/output/server/manifest-full.js +47 -0
  70. package/.svelte-kit/output/server/manifest.js +47 -0
  71. package/.svelte-kit/output/server/nodes/0.js +8 -0
  72. package/.svelte-kit/output/server/nodes/1.js +8 -0
  73. package/.svelte-kit/output/server/nodes/2.js +10 -0
  74. package/.svelte-kit/output/server/nodes/3.js +10 -0
  75. package/.svelte-kit/output/server/remote-entry.js +557 -0
  76. package/.svelte-kit/tsconfig.json +61 -0
  77. package/.svelte-kit/types/route_meta_data.json +8 -0
  78. package/.svelte-kit/types/src/routes/$types.d.ts +26 -0
  79. package/.svelte-kit/types/src/routes/group/[groupId]/$types.d.ts +21 -0
  80. package/.svelte-kit/types/src/routes/group/[groupId]/proxy+page.ts +49 -0
  81. package/.svelte-kit/types/src/routes/proxy+page.ts +33 -0
  82. package/build/_app/env.js +1 -0
  83. package/build/_app/env.js.br +1 -0
  84. package/build/_app/env.js.gz +0 -0
  85. package/build/_app/immutable/assets/0.Czt_67iE.css +1 -0
  86. package/build/_app/immutable/assets/0.Czt_67iE.css.br +0 -0
  87. package/build/_app/immutable/assets/0.Czt_67iE.css.gz +0 -0
  88. package/build/_app/immutable/assets/TeamContactCard.Dxj5nUCr.css +1 -0
  89. package/build/_app/immutable/assets/TeamContactCard.Dxj5nUCr.css.br +0 -0
  90. package/build/_app/immutable/assets/TeamContactCard.Dxj5nUCr.css.gz +0 -0
  91. package/build/_app/immutable/assets/helpers.ysDrpaDf.css +1 -0
  92. package/build/_app/immutable/assets/helpers.ysDrpaDf.css.br +0 -0
  93. package/build/_app/immutable/assets/helpers.ysDrpaDf.css.gz +0 -0
  94. package/build/_app/immutable/assets/libavoid.DQJapW5w.wasm +0 -0
  95. package/build/_app/immutable/assets/libavoid.DQJapW5w.wasm.br +0 -0
  96. package/build/_app/immutable/assets/libavoid.DQJapW5w.wasm.gz +0 -0
  97. package/build/_app/immutable/chunks/BlLuv0eP.js +46 -0
  98. package/build/_app/immutable/chunks/BlLuv0eP.js.br +0 -0
  99. package/build/_app/immutable/chunks/BlLuv0eP.js.gz +0 -0
  100. package/build/_app/immutable/chunks/CSBHmwYv.js +1 -0
  101. package/build/_app/immutable/chunks/CSBHmwYv.js.br +0 -0
  102. package/build/_app/immutable/chunks/CSBHmwYv.js.gz +0 -0
  103. package/build/_app/immutable/chunks/CTCi5ueQ.js +1 -0
  104. package/build/_app/immutable/chunks/CTCi5ueQ.js.br +0 -0
  105. package/build/_app/immutable/chunks/CTCi5ueQ.js.gz +0 -0
  106. package/build/_app/immutable/chunks/CfOzjaik.js +2 -0
  107. package/build/_app/immutable/chunks/CfOzjaik.js.br +0 -0
  108. package/build/_app/immutable/chunks/CfOzjaik.js.gz +0 -0
  109. package/build/_app/immutable/chunks/D4PdvFNs.js +1 -0
  110. package/build/_app/immutable/chunks/D4PdvFNs.js.br +0 -0
  111. package/build/_app/immutable/chunks/D4PdvFNs.js.gz +0 -0
  112. package/build/_app/immutable/chunks/DXgP-QUS.js +2 -0
  113. package/build/_app/immutable/chunks/DXgP-QUS.js.br +0 -0
  114. package/build/_app/immutable/chunks/DXgP-QUS.js.gz +0 -0
  115. package/build/_app/immutable/chunks/DlbDC5An.js +1 -0
  116. package/build/_app/immutable/chunks/DlbDC5An.js.br +0 -0
  117. package/build/_app/immutable/chunks/DlbDC5An.js.gz +0 -0
  118. package/build/_app/immutable/chunks/wRWe7aK9.js +1 -0
  119. package/build/_app/immutable/chunks/wRWe7aK9.js.br +0 -0
  120. package/build/_app/immutable/chunks/wRWe7aK9.js.gz +0 -0
  121. package/build/_app/immutable/entry/app.ConrMuHl.js +2 -0
  122. package/build/_app/immutable/entry/app.ConrMuHl.js.br +0 -0
  123. package/build/_app/immutable/entry/app.ConrMuHl.js.gz +0 -0
  124. package/build/_app/immutable/entry/start.Bm6FyGme.js +1 -0
  125. package/build/_app/immutable/entry/start.Bm6FyGme.js.br +2 -0
  126. package/build/_app/immutable/entry/start.Bm6FyGme.js.gz +0 -0
  127. package/build/_app/immutable/nodes/0.d3cL-ETU.js +1 -0
  128. package/build/_app/immutable/nodes/0.d3cL-ETU.js.br +0 -0
  129. package/build/_app/immutable/nodes/0.d3cL-ETU.js.gz +0 -0
  130. package/build/_app/immutable/nodes/1.D6z9rPGv.js +1 -0
  131. package/build/_app/immutable/nodes/1.D6z9rPGv.js.br +0 -0
  132. package/build/_app/immutable/nodes/1.D6z9rPGv.js.gz +0 -0
  133. package/build/_app/immutable/nodes/2.CLD-8chl.js +1 -0
  134. package/build/_app/immutable/nodes/2.CLD-8chl.js.br +0 -0
  135. package/build/_app/immutable/nodes/2.CLD-8chl.js.gz +0 -0
  136. package/build/_app/immutable/nodes/3.DXYeBoel.js +1 -0
  137. package/build/_app/immutable/nodes/3.DXYeBoel.js.br +0 -0
  138. package/build/_app/immutable/nodes/3.DXYeBoel.js.gz +0 -0
  139. package/build/_app/version.json +1 -0
  140. package/build/_app/version.json.br +0 -0
  141. package/build/_app/version.json.gz +0 -0
  142. package/build/index.html +34 -0
  143. package/build/index.html.br +0 -0
  144. package/build/index.html.gz +0 -0
  145. package/build/libavoid.wasm +0 -0
  146. package/build/libavoid.wasm.br +0 -0
  147. package/build/libavoid.wasm.gz +0 -0
  148. package/build/static/robots.txt +3 -0
  149. package/coverage/coverage-final.json +6 -0
  150. package/coverage/coverage-summary.json +7 -0
  151. package/coverage/junit.xml +57 -0
  152. package/coverage/lcov-report/base.css +224 -0
  153. package/coverage/lcov-report/block-navigation.js +87 -0
  154. package/coverage/lcov-report/favicon.png +0 -0
  155. package/coverage/lcov-report/index.html +131 -0
  156. package/coverage/lcov-report/prettify.css +1 -0
  157. package/coverage/lcov-report/prettify.js +2 -0
  158. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  159. package/coverage/lcov-report/sorter.js +210 -0
  160. package/coverage/lcov-report/stores/index.html +116 -0
  161. package/coverage/lcov-report/stores/routingStore.ts.html +781 -0
  162. package/coverage/lcov-report/utils/flow/helpers.ts.html +127 -0
  163. package/coverage/lcov-report/utils/flow/index.html +161 -0
  164. package/coverage/lcov-report/utils/flow/layout.ts.html +805 -0
  165. package/coverage/lcov-report/utils/flow/serviceIds.ts.html +97 -0
  166. package/coverage/lcov-report/utils/flow/servicesGraph.ts.html +859 -0
  167. package/coverage/lcov.info +646 -0
  168. package/coverage/test-results.json +1 -0
  169. package/data/services/api/api-gateway.yaml +18 -0
  170. package/data/services/api/group-info.yaml +7 -0
  171. package/data/services/api/lambda-orders.yaml +21 -0
  172. package/data/services/api/lambda-products.yaml +15 -0
  173. package/data/services/api/lambda-users.yaml +15 -0
  174. package/data/services/compute/alb.yaml +15 -0
  175. package/data/services/compute/ecs-inventory.yaml +16 -0
  176. package/data/services/compute/ecs-notification.yaml +15 -0
  177. package/data/services/compute/group-info.yaml +7 -0
  178. package/data/services/data/dynamodb-notifications.yaml +12 -0
  179. package/data/services/data/dynamodb-orders.yaml +9 -0
  180. package/data/services/data/dynamodb-products.yaml +9 -0
  181. package/data/services/data/dynamodb-users.yaml +9 -0
  182. package/data/services/data/group-info.yaml +7 -0
  183. package/data/services/data/rds-postgres.yaml +9 -0
  184. package/data/services/data/redis.yaml +10 -0
  185. package/data/services/frontend/cloudfront.yaml +12 -0
  186. package/data/services/frontend/group-info.yaml +7 -0
  187. package/data/services/frontend/route53.yaml +15 -0
  188. package/data/services/frontend/s3-website.yaml +9 -0
  189. package/data/teams/cloud-shepherds.yaml +15 -0
  190. package/data/teams/data-wizards.yaml +15 -0
  191. package/data/teams/interface-architects.yaml +19 -0
  192. package/e2e/demo.test.ts +54 -0
  193. package/e2e/header-toolbar.simple.spec.ts +0 -0
  194. package/e2e/header-toolbar.spec.ts +53 -0
  195. package/e2e/layout.spec.ts +30 -0
  196. package/package.json +69 -0
  197. package/playwright.config.ts +10 -0
  198. package/plugins/mapper-data-plugin.ts +32 -0
  199. package/project.json +23 -0
  200. package/src/app.css +125 -0
  201. package/src/app.d.ts +31 -0
  202. package/src/app.html +11 -0
  203. package/src/lib/assets/favicon.svg +19 -0
  204. package/src/lib/components/EmptyState.svelte +37 -0
  205. package/src/lib/components/ErrorDisplay.svelte +82 -0
  206. package/src/lib/components/FlowCanvas.svelte +223 -0
  207. package/src/lib/components/GenericSidebarCard.svelte +44 -0
  208. package/src/lib/components/GroupDetailSidebar.svelte +31 -0
  209. package/src/lib/components/Header.svelte +57 -0
  210. package/src/lib/components/Legend.svelte +25 -0
  211. package/src/lib/components/LoadingOverlay.svelte +42 -0
  212. package/src/lib/components/LoadingSpinner.svelte +10 -0
  213. package/src/lib/components/ServiceDetailSidebar.svelte +90 -0
  214. package/src/lib/components/TeamContactCard.svelte +166 -0
  215. package/src/lib/components/flow/ExternalNode.svelte +45 -0
  216. package/src/lib/components/flow/MainGroupNode.svelte +24 -0
  217. package/src/lib/components/flow/ServiceGroupNode.svelte +17 -0
  218. package/src/lib/components/flow/ServiceNode.svelte +40 -0
  219. package/src/lib/components/flow/SnakeEdge.svelte +206 -0
  220. package/src/lib/components/flow/index.ts +6 -0
  221. package/src/lib/components/index.ts +12 -0
  222. package/src/lib/data/connections.ts +26 -0
  223. package/src/lib/data/groups.ts +11 -0
  224. package/src/lib/data/services.ts +12 -0
  225. package/src/lib/data/teams.ts +11 -0
  226. package/src/lib/index.ts +1 -0
  227. package/src/lib/state/theme.svelte.ts +21 -0
  228. package/src/lib/stores/diagram.ts +6 -0
  229. package/src/lib/stores/routingStore.test.ts +133 -0
  230. package/src/lib/stores/routingStore.ts +232 -0
  231. package/src/lib/utils/awsIcons.ts +117 -0
  232. package/src/lib/utils/flow/groupOverviewGraph.ts +73 -0
  233. package/src/lib/utils/flow/helpers.ts +14 -0
  234. package/src/lib/utils/flow/layout.test.ts +271 -0
  235. package/src/lib/utils/flow/layout.ts +240 -0
  236. package/src/lib/utils/flow/serviceIds.ts +5 -0
  237. package/src/lib/utils/flow/servicesGraph.test.ts +119 -0
  238. package/src/lib/utils/flow/servicesGraph.ts +258 -0
  239. package/src/routes/+error.svelte +36 -0
  240. package/src/routes/+layout.svelte +27 -0
  241. package/src/routes/+page.svelte +81 -0
  242. package/src/routes/+page.ts +31 -0
  243. package/src/routes/group/[groupId]/+page.svelte +102 -0
  244. package/src/routes/group/[groupId]/+page.ts +48 -0
  245. package/src/routes/layout.css +0 -0
  246. package/static/static/robots.txt +3 -0
  247. package/svelte.config.js +28 -0
  248. package/tailwind.config.js +12 -0
  249. package/tsconfig.json +22 -0
  250. package/vite.config.ts +81 -0
@@ -0,0 +1,3747 @@
1
+ import { B as BROWSER } from "./chunks/false.js";
2
+ import { json, text, error } from "@sveltejs/kit";
3
+ import { Redirect, SvelteKitError, ActionFailure, HttpError } from "@sveltejs/kit/internal";
4
+ import { with_request_store, merge_tracing, try_get_request_store } from "@sveltejs/kit/internal/server";
5
+ import { a as assets, b as base, c as app_dir, r as relative, o as override, d as reset } from "./chunks/environment.js";
6
+ import { E as ENDPOINT_METHODS, P as PAGE_METHODS, n as negotiate, m as method_not_allowed, h as handle_error_and_jsonify, g as get_status, i as is_form_content_type, a as normalize_error, b as get_global_name, s as serialize_uses, c as clarify_devalue_error, d as get_node_type, e as escape_html, S as SVELTE_KIT_ASSETS, f as create_remote_key, j as static_error_page, r as redirect_response, p as parse_remote_arg, k as stringify, l as deserialize_binary_form, o as has_prerendered_path, T as TRAILING_SLASH_PARAM, I as INVALIDATED_PARAM, q as handle_fatal_error, t as format_server_error } from "./chunks/shared.js";
7
+ import * as devalue from "devalue";
8
+ import { m as make_trackable, d as disable_search, a as decode_params, S as SCHEME, v as validate_layout_server_exports, b as validate_layout_exports, c as validate_page_server_exports, e as validate_page_exports, n as normalize_path, r as resolve, f as decode_pathname, g as validate_server_exports } from "./chunks/exports.js";
9
+ import { b as base64_encode, t as text_decoder, a as text_encoder, g as get_relative_path } from "./chunks/utils.js";
10
+ import { r as readable, w as writable } from "./chunks/index.js";
11
+ import { p as public_env, r as read_implementation, o as options, s as set_private_env, a as set_public_env, g as get_hooks, b as set_read_implementation } from "./chunks/internal.js";
12
+ import { parse, serialize } from "cookie";
13
+ import * as set_cookie_parser from "set-cookie-parser";
14
+ function with_resolvers() {
15
+ let resolve2;
16
+ let reject;
17
+ const promise = new Promise((res, rej) => {
18
+ resolve2 = res;
19
+ reject = rej;
20
+ });
21
+ return { promise, resolve: resolve2, reject };
22
+ }
23
+ const NULL_BODY_STATUS = [101, 103, 204, 205, 304];
24
+ const IN_WEBCONTAINER = !!globalThis.process?.versions?.webcontainer;
25
+ async function render_endpoint(event, event_state, mod, state) {
26
+ const method = (
27
+ /** @type {import('types').HttpMethod} */
28
+ event.request.method
29
+ );
30
+ let handler = mod[method] || mod.fallback;
31
+ if (method === "HEAD" && !mod.HEAD && mod.GET) {
32
+ handler = mod.GET;
33
+ }
34
+ if (!handler) {
35
+ return method_not_allowed(mod, method);
36
+ }
37
+ const prerender = mod.prerender ?? state.prerender_default;
38
+ if (prerender && (mod.POST || mod.PATCH || mod.PUT || mod.DELETE)) {
39
+ throw new Error("Cannot prerender endpoints that have mutative methods");
40
+ }
41
+ if (state.prerendering && !state.prerendering.inside_reroute && !prerender) {
42
+ if (state.depth > 0) {
43
+ throw new Error(`${event.route.id} is not prerenderable`);
44
+ } else {
45
+ return new Response(void 0, { status: 204 });
46
+ }
47
+ }
48
+ event_state.is_endpoint_request = true;
49
+ try {
50
+ const response = await with_request_store(
51
+ { event, state: event_state },
52
+ () => handler(
53
+ /** @type {import('@sveltejs/kit').RequestEvent<Record<string, any>>} */
54
+ event
55
+ )
56
+ );
57
+ if (!(response instanceof Response)) {
58
+ throw new Error(
59
+ `Invalid response from route ${event.url.pathname}: handler should return a Response object`
60
+ );
61
+ }
62
+ if (state.prerendering && (!state.prerendering.inside_reroute || prerender)) {
63
+ const cloned = new Response(response.clone().body, {
64
+ status: response.status,
65
+ statusText: response.statusText,
66
+ headers: new Headers(response.headers)
67
+ });
68
+ cloned.headers.set("x-sveltekit-prerender", String(prerender));
69
+ if (state.prerendering.inside_reroute && prerender) {
70
+ cloned.headers.set(
71
+ "x-sveltekit-routeid",
72
+ encodeURI(
73
+ /** @type {string} */
74
+ event.route.id
75
+ )
76
+ );
77
+ state.prerendering.dependencies.set(event.url.pathname, { response: cloned, body: null });
78
+ } else {
79
+ return cloned;
80
+ }
81
+ }
82
+ return response;
83
+ } catch (e) {
84
+ if (e instanceof Redirect) {
85
+ return new Response(void 0, {
86
+ status: e.status,
87
+ headers: { location: e.location }
88
+ });
89
+ }
90
+ throw e;
91
+ }
92
+ }
93
+ function is_endpoint_request(event) {
94
+ const { method, headers: headers2 } = event.request;
95
+ if (ENDPOINT_METHODS.includes(method) && !PAGE_METHODS.includes(method)) {
96
+ return true;
97
+ }
98
+ if (method === "POST" && headers2.get("x-sveltekit-action") === "true") return false;
99
+ const accept = event.request.headers.get("accept") ?? "*/*";
100
+ return negotiate(accept, ["*", "text/html"]) !== "text/html";
101
+ }
102
+ function compact(arr) {
103
+ return arr.filter(
104
+ /** @returns {val is NonNullable<T>} */
105
+ (val) => val != null
106
+ );
107
+ }
108
+ const DATA_SUFFIX = "/__data.json";
109
+ const HTML_DATA_SUFFIX = ".html__data.json";
110
+ function has_data_suffix(pathname) {
111
+ return pathname.endsWith(DATA_SUFFIX) || pathname.endsWith(HTML_DATA_SUFFIX);
112
+ }
113
+ function add_data_suffix(pathname) {
114
+ if (pathname.endsWith(".html")) return pathname.replace(/\.html$/, HTML_DATA_SUFFIX);
115
+ return pathname.replace(/\/$/, "") + DATA_SUFFIX;
116
+ }
117
+ function strip_data_suffix(pathname) {
118
+ if (pathname.endsWith(HTML_DATA_SUFFIX)) {
119
+ return pathname.slice(0, -HTML_DATA_SUFFIX.length) + ".html";
120
+ }
121
+ return pathname.slice(0, -DATA_SUFFIX.length);
122
+ }
123
+ const ROUTE_SUFFIX = "/__route.js";
124
+ function has_resolution_suffix(pathname) {
125
+ return pathname.endsWith(ROUTE_SUFFIX);
126
+ }
127
+ function add_resolution_suffix(pathname) {
128
+ return pathname.replace(/\/$/, "") + ROUTE_SUFFIX;
129
+ }
130
+ function strip_resolution_suffix(pathname) {
131
+ return pathname.slice(0, -ROUTE_SUFFIX.length);
132
+ }
133
+ const noop_span = {
134
+ spanContext() {
135
+ return noop_span_context;
136
+ },
137
+ setAttribute() {
138
+ return this;
139
+ },
140
+ setAttributes() {
141
+ return this;
142
+ },
143
+ addEvent() {
144
+ return this;
145
+ },
146
+ setStatus() {
147
+ return this;
148
+ },
149
+ updateName() {
150
+ return this;
151
+ },
152
+ end() {
153
+ return this;
154
+ },
155
+ isRecording() {
156
+ return false;
157
+ },
158
+ recordException() {
159
+ return this;
160
+ },
161
+ addLink() {
162
+ return this;
163
+ },
164
+ addLinks() {
165
+ return this;
166
+ }
167
+ };
168
+ const noop_span_context = {
169
+ traceId: "",
170
+ spanId: "",
171
+ traceFlags: 0
172
+ };
173
+ async function record_span({ name, attributes, fn }) {
174
+ {
175
+ return fn(noop_span);
176
+ }
177
+ }
178
+ function is_action_json_request(event) {
179
+ const accept = negotiate(event.request.headers.get("accept") ?? "*/*", [
180
+ "application/json",
181
+ "text/html"
182
+ ]);
183
+ return accept === "application/json" && event.request.method === "POST";
184
+ }
185
+ async function handle_action_json_request(event, event_state, options2, server) {
186
+ const actions = server?.actions;
187
+ if (!actions) {
188
+ const no_actions_error = new SvelteKitError(
189
+ 405,
190
+ "Method Not Allowed",
191
+ `POST method not allowed. No form actions exist for ${"this page"}`
192
+ );
193
+ return action_json(
194
+ {
195
+ type: "error",
196
+ error: await handle_error_and_jsonify(event, event_state, options2, no_actions_error)
197
+ },
198
+ {
199
+ status: no_actions_error.status,
200
+ headers: {
201
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
202
+ // "The server must generate an Allow header field in a 405 status code response"
203
+ allow: "GET"
204
+ }
205
+ }
206
+ );
207
+ }
208
+ check_named_default_separate(actions);
209
+ try {
210
+ const data = await call_action(event, event_state, actions);
211
+ if (BROWSER) ;
212
+ if (data instanceof ActionFailure) {
213
+ return action_json({
214
+ type: "failure",
215
+ status: data.status,
216
+ // @ts-expect-error we assign a string to what is supposed to be an object. That's ok
217
+ // because we don't use the object outside, and this way we have better code navigation
218
+ // through knowing where the related interface is used.
219
+ data: stringify_action_response(
220
+ data.data,
221
+ /** @type {string} */
222
+ event.route.id,
223
+ options2.hooks.transport
224
+ )
225
+ });
226
+ } else {
227
+ return action_json({
228
+ type: "success",
229
+ status: data ? 200 : 204,
230
+ // @ts-expect-error see comment above
231
+ data: stringify_action_response(
232
+ data,
233
+ /** @type {string} */
234
+ event.route.id,
235
+ options2.hooks.transport
236
+ )
237
+ });
238
+ }
239
+ } catch (e) {
240
+ const err = normalize_error(e);
241
+ if (err instanceof Redirect) {
242
+ return action_json_redirect(err);
243
+ }
244
+ return action_json(
245
+ {
246
+ type: "error",
247
+ error: await handle_error_and_jsonify(
248
+ event,
249
+ event_state,
250
+ options2,
251
+ check_incorrect_fail_use(err)
252
+ )
253
+ },
254
+ {
255
+ status: get_status(err)
256
+ }
257
+ );
258
+ }
259
+ }
260
+ function check_incorrect_fail_use(error2) {
261
+ return error2 instanceof ActionFailure ? new Error('Cannot "throw fail()". Use "return fail()"') : error2;
262
+ }
263
+ function action_json_redirect(redirect) {
264
+ return action_json({
265
+ type: "redirect",
266
+ status: redirect.status,
267
+ location: redirect.location
268
+ });
269
+ }
270
+ function action_json(data, init2) {
271
+ return json(data, init2);
272
+ }
273
+ function is_action_request(event) {
274
+ return event.request.method === "POST";
275
+ }
276
+ async function handle_action_request(event, event_state, server) {
277
+ const actions = server?.actions;
278
+ if (!actions) {
279
+ event.setHeaders({
280
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
281
+ // "The server must generate an Allow header field in a 405 status code response"
282
+ allow: "GET"
283
+ });
284
+ return {
285
+ type: "error",
286
+ error: new SvelteKitError(
287
+ 405,
288
+ "Method Not Allowed",
289
+ `POST method not allowed. No form actions exist for ${"this page"}`
290
+ )
291
+ };
292
+ }
293
+ check_named_default_separate(actions);
294
+ try {
295
+ const data = await call_action(event, event_state, actions);
296
+ if (BROWSER) ;
297
+ if (data instanceof ActionFailure) {
298
+ return {
299
+ type: "failure",
300
+ status: data.status,
301
+ data: data.data
302
+ };
303
+ } else {
304
+ return {
305
+ type: "success",
306
+ status: 200,
307
+ // @ts-expect-error this will be removed upon serialization, so `undefined` is the same as omission
308
+ data
309
+ };
310
+ }
311
+ } catch (e) {
312
+ const err = normalize_error(e);
313
+ if (err instanceof Redirect) {
314
+ return {
315
+ type: "redirect",
316
+ status: err.status,
317
+ location: err.location
318
+ };
319
+ }
320
+ return {
321
+ type: "error",
322
+ error: check_incorrect_fail_use(err)
323
+ };
324
+ }
325
+ }
326
+ function check_named_default_separate(actions) {
327
+ if (actions.default && Object.keys(actions).length > 1) {
328
+ throw new Error(
329
+ "When using named actions, the default action cannot be used. See the docs for more info: https://svelte.dev/docs/kit/form-actions#named-actions"
330
+ );
331
+ }
332
+ }
333
+ async function call_action(event, event_state, actions) {
334
+ const url = new URL(event.request.url);
335
+ let name = "default";
336
+ for (const param of url.searchParams) {
337
+ if (param[0].startsWith("/")) {
338
+ name = param[0].slice(1);
339
+ if (name === "default") {
340
+ throw new Error('Cannot use reserved action name "default"');
341
+ }
342
+ break;
343
+ }
344
+ }
345
+ const action = actions[name];
346
+ if (!action) {
347
+ throw new SvelteKitError(404, "Not Found", `No action with name '${name}' found`);
348
+ }
349
+ if (!is_form_content_type(event.request)) {
350
+ throw new SvelteKitError(
351
+ 415,
352
+ "Unsupported Media Type",
353
+ `Form actions expect form-encoded data — received ${event.request.headers.get(
354
+ "content-type"
355
+ )}`
356
+ );
357
+ }
358
+ return record_span({
359
+ name: "sveltekit.form_action",
360
+ attributes: {
361
+ "http.route": event.route.id || "unknown"
362
+ },
363
+ fn: async (current2) => {
364
+ const traced_event = merge_tracing(event, current2);
365
+ const result = await with_request_store(
366
+ { event: traced_event, state: event_state },
367
+ () => action(traced_event)
368
+ );
369
+ if (result instanceof ActionFailure) {
370
+ current2.setAttributes({
371
+ "sveltekit.form_action.result.type": "failure",
372
+ "sveltekit.form_action.result.status": result.status
373
+ });
374
+ }
375
+ return result;
376
+ }
377
+ });
378
+ }
379
+ function validate_action_return(data) {
380
+ if (data instanceof Redirect) {
381
+ throw new Error("Cannot `return redirect(...)` — use `redirect(...)` instead");
382
+ }
383
+ if (data instanceof HttpError) {
384
+ throw new Error("Cannot `return error(...)` — use `error(...)` or `return fail(...)` instead");
385
+ }
386
+ }
387
+ function uneval_action_response(data, route_id, transport) {
388
+ const replacer = (thing) => {
389
+ for (const key2 in transport) {
390
+ const encoded = transport[key2].encode(thing);
391
+ if (encoded) {
392
+ return `app.decode('${key2}', ${devalue.uneval(encoded, replacer)})`;
393
+ }
394
+ }
395
+ };
396
+ return try_serialize(data, (value) => devalue.uneval(value, replacer), route_id);
397
+ }
398
+ function stringify_action_response(data, route_id, transport) {
399
+ const encoders = Object.fromEntries(
400
+ Object.entries(transport).map(([key2, value]) => [key2, value.encode])
401
+ );
402
+ return try_serialize(data, (value) => devalue.stringify(value, encoders), route_id);
403
+ }
404
+ function try_serialize(data, fn, route_id) {
405
+ try {
406
+ return fn(data);
407
+ } catch (e) {
408
+ const error2 = (
409
+ /** @type {any} */
410
+ e
411
+ );
412
+ if (data instanceof Response) {
413
+ throw new Error(
414
+ `Data returned from action inside ${route_id} is not serializable. Form actions need to return plain objects or fail(). E.g. return { success: true } or return fail(400, { message: "invalid" });`
415
+ );
416
+ }
417
+ if ("path" in error2) {
418
+ let message = `Data returned from action inside ${route_id} is not serializable: ${error2.message}`;
419
+ if (error2.path !== "") message += ` (data.${error2.path})`;
420
+ throw new Error(message);
421
+ }
422
+ throw error2;
423
+ }
424
+ }
425
+ function create_async_iterator() {
426
+ let resolved = -1;
427
+ let returned = -1;
428
+ const deferred = [];
429
+ return {
430
+ iterate: (transform = (x) => x) => {
431
+ return {
432
+ [Symbol.asyncIterator]() {
433
+ return {
434
+ next: async () => {
435
+ const next = deferred[++returned];
436
+ if (!next) return { value: null, done: true };
437
+ const value = await next.promise;
438
+ return { value: transform(value), done: false };
439
+ }
440
+ };
441
+ }
442
+ };
443
+ },
444
+ add: (promise) => {
445
+ deferred.push(with_resolvers());
446
+ void promise.then((value) => {
447
+ deferred[++resolved].resolve(value);
448
+ });
449
+ }
450
+ };
451
+ }
452
+ function server_data_serializer(event, event_state, options2) {
453
+ let promise_id = 1;
454
+ let max_nodes = -1;
455
+ const iterator = create_async_iterator();
456
+ const global = get_global_name(options2);
457
+ function get_replacer(index) {
458
+ return function replacer(thing) {
459
+ if (typeof thing?.then === "function") {
460
+ const id = promise_id++;
461
+ const promise = thing.then(
462
+ /** @param {any} data */
463
+ (data) => ({ data })
464
+ ).catch(
465
+ /** @param {any} error */
466
+ async (error2) => ({
467
+ error: await handle_error_and_jsonify(event, event_state, options2, error2)
468
+ })
469
+ ).then(
470
+ /**
471
+ * @param {{data: any; error: any}} result
472
+ */
473
+ async ({ data, error: error2 }) => {
474
+ let str;
475
+ try {
476
+ str = devalue.uneval(error2 ? [, error2] : [data], replacer);
477
+ } catch {
478
+ error2 = await handle_error_and_jsonify(
479
+ event,
480
+ event_state,
481
+ options2,
482
+ new Error(`Failed to serialize promise while rendering ${event.route.id}`)
483
+ );
484
+ data = void 0;
485
+ str = devalue.uneval([, error2], replacer);
486
+ }
487
+ return {
488
+ index,
489
+ str: `${global}.resolve(${id}, ${str.includes("app.decode") ? `(app) => ${str}` : `() => ${str}`})`
490
+ };
491
+ }
492
+ );
493
+ iterator.add(promise);
494
+ return `${global}.defer(${id})`;
495
+ } else {
496
+ for (const key2 in options2.hooks.transport) {
497
+ const encoded = options2.hooks.transport[key2].encode(thing);
498
+ if (encoded) {
499
+ return `app.decode('${key2}', ${devalue.uneval(encoded, replacer)})`;
500
+ }
501
+ }
502
+ }
503
+ };
504
+ }
505
+ const strings = (
506
+ /** @type {string[]} */
507
+ []
508
+ );
509
+ return {
510
+ set_max_nodes(i) {
511
+ max_nodes = i;
512
+ },
513
+ add_node(i, node) {
514
+ try {
515
+ if (!node) {
516
+ strings[i] = "null";
517
+ return;
518
+ }
519
+ const payload = { type: "data", data: node.data, uses: serialize_uses(node) };
520
+ if (node.slash) payload.slash = node.slash;
521
+ strings[i] = devalue.uneval(payload, get_replacer(i));
522
+ } catch (e) {
523
+ e.path = e.path.slice(1);
524
+ throw new Error(clarify_devalue_error(
525
+ event,
526
+ /** @type {any} */
527
+ e
528
+ ));
529
+ }
530
+ },
531
+ get_data(csp) {
532
+ const open = `<script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ""}>`;
533
+ const close = `<\/script>
534
+ `;
535
+ return {
536
+ data: `[${compact(max_nodes > -1 ? strings.slice(0, max_nodes) : strings).join(",")}]`,
537
+ chunks: promise_id > 1 ? iterator.iterate(({ index, str }) => {
538
+ if (max_nodes > -1 && index >= max_nodes) {
539
+ return "";
540
+ }
541
+ return open + str + close;
542
+ }) : null
543
+ };
544
+ }
545
+ };
546
+ }
547
+ function server_data_serializer_json(event, event_state, options2) {
548
+ let promise_id = 1;
549
+ const iterator = create_async_iterator();
550
+ const reducers = {
551
+ ...Object.fromEntries(
552
+ Object.entries(options2.hooks.transport).map(([key2, value]) => [key2, value.encode])
553
+ ),
554
+ /** @param {any} thing */
555
+ Promise: (thing) => {
556
+ if (typeof thing?.then !== "function") {
557
+ return;
558
+ }
559
+ const id = promise_id++;
560
+ let key2 = "data";
561
+ const promise = thing.catch(
562
+ /** @param {any} e */
563
+ async (e) => {
564
+ key2 = "error";
565
+ return handle_error_and_jsonify(
566
+ event,
567
+ event_state,
568
+ options2,
569
+ /** @type {any} */
570
+ e
571
+ );
572
+ }
573
+ ).then(
574
+ /** @param {any} value */
575
+ async (value) => {
576
+ let str;
577
+ try {
578
+ str = devalue.stringify(value, reducers);
579
+ } catch {
580
+ const error2 = await handle_error_and_jsonify(
581
+ event,
582
+ event_state,
583
+ options2,
584
+ new Error(`Failed to serialize promise while rendering ${event.route.id}`)
585
+ );
586
+ key2 = "error";
587
+ str = devalue.stringify(error2, reducers);
588
+ }
589
+ return `{"type":"chunk","id":${id},"${key2}":${str}}
590
+ `;
591
+ }
592
+ );
593
+ iterator.add(promise);
594
+ return id;
595
+ }
596
+ };
597
+ const strings = (
598
+ /** @type {string[]} */
599
+ []
600
+ );
601
+ return {
602
+ add_node(i, node) {
603
+ try {
604
+ if (!node) {
605
+ strings[i] = "null";
606
+ return;
607
+ }
608
+ if (node.type === "error" || node.type === "skip") {
609
+ strings[i] = JSON.stringify(node);
610
+ return;
611
+ }
612
+ strings[i] = `{"type":"data","data":${devalue.stringify(node.data, reducers)},"uses":${JSON.stringify(
613
+ serialize_uses(node)
614
+ )}${node.slash ? `,"slash":${JSON.stringify(node.slash)}` : ""}}`;
615
+ } catch (e) {
616
+ e.path = "data" + e.path;
617
+ throw new Error(clarify_devalue_error(
618
+ event,
619
+ /** @type {any} */
620
+ e
621
+ ));
622
+ }
623
+ },
624
+ get_data() {
625
+ return {
626
+ data: `{"type":"data","nodes":[${strings.join(",")}]}
627
+ `,
628
+ chunks: promise_id > 1 ? iterator.iterate() : null
629
+ };
630
+ }
631
+ };
632
+ }
633
+ async function load_server_data({ event, event_state, state, node, parent }) {
634
+ if (!node?.server) return null;
635
+ let is_tracking = true;
636
+ const uses = {
637
+ dependencies: /* @__PURE__ */ new Set(),
638
+ params: /* @__PURE__ */ new Set(),
639
+ parent: false,
640
+ route: false,
641
+ url: false,
642
+ search_params: /* @__PURE__ */ new Set()
643
+ };
644
+ const load = node.server.load;
645
+ const slash = node.server.trailingSlash;
646
+ if (!load) {
647
+ return { type: "data", data: null, uses, slash };
648
+ }
649
+ const url = make_trackable(
650
+ event.url,
651
+ () => {
652
+ if (is_tracking) {
653
+ uses.url = true;
654
+ }
655
+ },
656
+ (param) => {
657
+ if (is_tracking) {
658
+ uses.search_params.add(param);
659
+ }
660
+ }
661
+ );
662
+ if (state.prerendering) {
663
+ disable_search(url);
664
+ }
665
+ const result = await record_span({
666
+ name: "sveltekit.load",
667
+ attributes: {
668
+ "sveltekit.load.node_id": node.server_id || "unknown",
669
+ "sveltekit.load.node_type": get_node_type(node.server_id),
670
+ "http.route": event.route.id || "unknown"
671
+ },
672
+ fn: async (current2) => {
673
+ const traced_event = merge_tracing(event, current2);
674
+ const result2 = await with_request_store(
675
+ { event: traced_event, state: event_state },
676
+ () => load.call(null, {
677
+ ...traced_event,
678
+ fetch: (info, init2) => {
679
+ new URL(info instanceof Request ? info.url : info, event.url);
680
+ return event.fetch(info, init2);
681
+ },
682
+ /** @param {string[]} deps */
683
+ depends: (...deps) => {
684
+ for (const dep of deps) {
685
+ const { href } = new URL(dep, event.url);
686
+ uses.dependencies.add(href);
687
+ }
688
+ },
689
+ params: new Proxy(event.params, {
690
+ get: (target, key2) => {
691
+ if (is_tracking) {
692
+ uses.params.add(key2);
693
+ }
694
+ return target[
695
+ /** @type {string} */
696
+ key2
697
+ ];
698
+ }
699
+ }),
700
+ parent: async () => {
701
+ if (is_tracking) {
702
+ uses.parent = true;
703
+ }
704
+ return parent();
705
+ },
706
+ route: new Proxy(event.route, {
707
+ get: (target, key2) => {
708
+ if (is_tracking) {
709
+ uses.route = true;
710
+ }
711
+ return target[
712
+ /** @type {'id'} */
713
+ key2
714
+ ];
715
+ }
716
+ }),
717
+ url,
718
+ untrack(fn) {
719
+ is_tracking = false;
720
+ try {
721
+ return fn();
722
+ } finally {
723
+ is_tracking = true;
724
+ }
725
+ }
726
+ })
727
+ );
728
+ return result2;
729
+ }
730
+ });
731
+ return {
732
+ type: "data",
733
+ data: result ?? null,
734
+ uses,
735
+ slash
736
+ };
737
+ }
738
+ async function load_data({
739
+ event,
740
+ event_state,
741
+ fetched,
742
+ node,
743
+ parent,
744
+ server_data_promise,
745
+ state,
746
+ resolve_opts,
747
+ csr
748
+ }) {
749
+ const server_data_node = await server_data_promise;
750
+ const load = node?.universal?.load;
751
+ if (!load) {
752
+ return server_data_node?.data ?? null;
753
+ }
754
+ const result = await record_span({
755
+ name: "sveltekit.load",
756
+ attributes: {
757
+ "sveltekit.load.node_id": node.universal_id || "unknown",
758
+ "sveltekit.load.node_type": get_node_type(node.universal_id),
759
+ "http.route": event.route.id || "unknown"
760
+ },
761
+ fn: async (current2) => {
762
+ const traced_event = merge_tracing(event, current2);
763
+ return await with_request_store(
764
+ { event: traced_event, state: event_state },
765
+ () => load.call(null, {
766
+ url: event.url,
767
+ params: event.params,
768
+ data: server_data_node?.data ?? null,
769
+ route: event.route,
770
+ fetch: create_universal_fetch(event, state, fetched, csr, resolve_opts),
771
+ setHeaders: event.setHeaders,
772
+ depends: () => {
773
+ },
774
+ parent,
775
+ untrack: (fn) => fn(),
776
+ tracing: traced_event.tracing
777
+ })
778
+ );
779
+ }
780
+ });
781
+ return result ?? null;
782
+ }
783
+ function create_universal_fetch(event, state, fetched, csr, resolve_opts) {
784
+ const universal_fetch = async (input, init2) => {
785
+ const cloned_body = input instanceof Request && input.body ? input.clone().body : null;
786
+ const cloned_headers = input instanceof Request && [...input.headers].length ? new Headers(input.headers) : init2?.headers;
787
+ let response = await event.fetch(input, init2);
788
+ const url = new URL(input instanceof Request ? input.url : input, event.url);
789
+ const same_origin = url.origin === event.url.origin;
790
+ let dependency;
791
+ if (same_origin) {
792
+ if (state.prerendering) {
793
+ dependency = { response, body: null };
794
+ state.prerendering.dependencies.set(url.pathname, dependency);
795
+ }
796
+ } else if (url.protocol === "https:" || url.protocol === "http:") {
797
+ const mode = input instanceof Request ? input.mode : init2?.mode ?? "cors";
798
+ if (mode === "no-cors") {
799
+ response = new Response("", {
800
+ status: response.status,
801
+ statusText: response.statusText,
802
+ headers: response.headers
803
+ });
804
+ } else {
805
+ const acao = response.headers.get("access-control-allow-origin");
806
+ if (!acao || acao !== event.url.origin && acao !== "*") {
807
+ throw new Error(
808
+ `CORS error: ${acao ? "Incorrect" : "No"} 'Access-Control-Allow-Origin' header is present on the requested resource`
809
+ );
810
+ }
811
+ }
812
+ }
813
+ let teed_body;
814
+ const proxy = new Proxy(response, {
815
+ get(response2, key2, receiver) {
816
+ async function push_fetched(body2, is_b64) {
817
+ const status_number = Number(response2.status);
818
+ if (isNaN(status_number)) {
819
+ throw new Error(
820
+ `response.status is not a number. value: "${response2.status}" type: ${typeof response2.status}`
821
+ );
822
+ }
823
+ fetched.push({
824
+ url: same_origin ? url.href.slice(event.url.origin.length) : url.href,
825
+ method: event.request.method,
826
+ request_body: (
827
+ /** @type {string | ArrayBufferView | undefined} */
828
+ input instanceof Request && cloned_body ? await stream_to_string(cloned_body) : init2?.body
829
+ ),
830
+ request_headers: cloned_headers,
831
+ response_body: body2,
832
+ response: response2,
833
+ is_b64
834
+ });
835
+ }
836
+ if (key2 === "body") {
837
+ if (response2.body === null) {
838
+ return null;
839
+ }
840
+ if (teed_body) {
841
+ return teed_body;
842
+ }
843
+ const [a, b] = response2.body.tee();
844
+ void (async () => {
845
+ let result = new Uint8Array();
846
+ for await (const chunk of a) {
847
+ const combined = new Uint8Array(result.length + chunk.length);
848
+ combined.set(result, 0);
849
+ combined.set(chunk, result.length);
850
+ result = combined;
851
+ }
852
+ if (dependency) {
853
+ dependency.body = new Uint8Array(result);
854
+ }
855
+ void push_fetched(base64_encode(result), true);
856
+ })();
857
+ return teed_body = b;
858
+ }
859
+ if (key2 === "arrayBuffer") {
860
+ return async () => {
861
+ const buffer = await response2.arrayBuffer();
862
+ const bytes = new Uint8Array(buffer);
863
+ if (dependency) {
864
+ dependency.body = bytes;
865
+ }
866
+ if (buffer instanceof ArrayBuffer) {
867
+ await push_fetched(base64_encode(bytes), true);
868
+ }
869
+ return buffer;
870
+ };
871
+ }
872
+ async function text2() {
873
+ const body2 = await response2.text();
874
+ if (body2 === "" && NULL_BODY_STATUS.includes(response2.status)) {
875
+ await push_fetched(void 0, false);
876
+ return void 0;
877
+ }
878
+ if (!body2 || typeof body2 === "string") {
879
+ await push_fetched(body2, false);
880
+ }
881
+ if (dependency) {
882
+ dependency.body = body2;
883
+ }
884
+ return body2;
885
+ }
886
+ if (key2 === "text") {
887
+ return text2;
888
+ }
889
+ if (key2 === "json") {
890
+ return async () => {
891
+ const body2 = await text2();
892
+ return body2 ? JSON.parse(body2) : void 0;
893
+ };
894
+ }
895
+ const value = Reflect.get(response2, key2, response2);
896
+ if (value instanceof Function) {
897
+ return Object.defineProperties(
898
+ /**
899
+ * @this {any}
900
+ */
901
+ function() {
902
+ return Reflect.apply(value, this === receiver ? response2 : this, arguments);
903
+ },
904
+ {
905
+ name: { value: value.name },
906
+ length: { value: value.length }
907
+ }
908
+ );
909
+ }
910
+ return value;
911
+ }
912
+ });
913
+ if (csr) {
914
+ const get = response.headers.get;
915
+ response.headers.get = (key2) => {
916
+ const lower = key2.toLowerCase();
917
+ const value = get.call(response.headers, lower);
918
+ if (value && !lower.startsWith("x-sveltekit-")) {
919
+ const included = resolve_opts.filterSerializedResponseHeaders(lower, value);
920
+ if (!included) {
921
+ throw new Error(
922
+ `Failed to get response header "${lower}" — it must be included by the \`filterSerializedResponseHeaders\` option: https://svelte.dev/docs/kit/hooks#Server-hooks-handle (at ${event.route.id})`
923
+ );
924
+ }
925
+ }
926
+ return value;
927
+ };
928
+ }
929
+ return proxy;
930
+ };
931
+ return (input, init2) => {
932
+ const response = universal_fetch(input, init2);
933
+ response.catch(() => {
934
+ });
935
+ return response;
936
+ };
937
+ }
938
+ async function stream_to_string(stream) {
939
+ let result = "";
940
+ const reader = stream.getReader();
941
+ while (true) {
942
+ const { done, value } = await reader.read();
943
+ if (done) {
944
+ break;
945
+ }
946
+ result += text_decoder.decode(value);
947
+ }
948
+ return result;
949
+ }
950
+ function hash(...values) {
951
+ let hash2 = 5381;
952
+ for (const value of values) {
953
+ if (typeof value === "string") {
954
+ let i = value.length;
955
+ while (i) hash2 = hash2 * 33 ^ value.charCodeAt(--i);
956
+ } else if (ArrayBuffer.isView(value)) {
957
+ const buffer = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
958
+ let i = buffer.length;
959
+ while (i) hash2 = hash2 * 33 ^ buffer[--i];
960
+ } else {
961
+ throw new TypeError("value must be a string or TypedArray");
962
+ }
963
+ }
964
+ return (hash2 >>> 0).toString(36);
965
+ }
966
+ const replacements = {
967
+ "<": "\\u003C",
968
+ "\u2028": "\\u2028",
969
+ "\u2029": "\\u2029"
970
+ };
971
+ const pattern = new RegExp(`[${Object.keys(replacements).join("")}]`, "g");
972
+ function serialize_data(fetched, filter, prerendering = false) {
973
+ const headers2 = {};
974
+ let cache_control = null;
975
+ let age = null;
976
+ let varyAny = false;
977
+ for (const [key2, value] of fetched.response.headers) {
978
+ if (filter(key2, value)) {
979
+ headers2[key2] = value;
980
+ }
981
+ if (key2 === "cache-control") cache_control = value;
982
+ else if (key2 === "age") age = value;
983
+ else if (key2 === "vary" && value.trim() === "*") varyAny = true;
984
+ }
985
+ const payload = {
986
+ status: fetched.response.status,
987
+ statusText: fetched.response.statusText,
988
+ headers: headers2,
989
+ body: fetched.response_body
990
+ };
991
+ const safe_payload = JSON.stringify(payload).replace(pattern, (match) => replacements[match]);
992
+ const attrs = [
993
+ 'type="application/json"',
994
+ "data-sveltekit-fetched",
995
+ `data-url="${escape_html(fetched.url, true)}"`
996
+ ];
997
+ if (fetched.is_b64) {
998
+ attrs.push("data-b64");
999
+ }
1000
+ if (fetched.request_headers || fetched.request_body) {
1001
+ const values = [];
1002
+ if (fetched.request_headers) {
1003
+ values.push([...new Headers(fetched.request_headers)].join(","));
1004
+ }
1005
+ if (fetched.request_body) {
1006
+ values.push(fetched.request_body);
1007
+ }
1008
+ attrs.push(`data-hash="${hash(...values)}"`);
1009
+ }
1010
+ if (!prerendering && fetched.method === "GET" && cache_control && !varyAny) {
1011
+ const match = /s-maxage=(\d+)/g.exec(cache_control) ?? /max-age=(\d+)/g.exec(cache_control);
1012
+ if (match) {
1013
+ const ttl = +match[1] - +(age ?? "0");
1014
+ attrs.push(`data-ttl="${ttl}"`);
1015
+ }
1016
+ }
1017
+ return `<script ${attrs.join(" ")}>${safe_payload}<\/script>`;
1018
+ }
1019
+ const s = JSON.stringify;
1020
+ function sha256(data) {
1021
+ if (!key[0]) precompute();
1022
+ const out = init.slice(0);
1023
+ const array2 = encode(data);
1024
+ for (let i = 0; i < array2.length; i += 16) {
1025
+ const w = array2.subarray(i, i + 16);
1026
+ let tmp;
1027
+ let a;
1028
+ let b;
1029
+ let out0 = out[0];
1030
+ let out1 = out[1];
1031
+ let out2 = out[2];
1032
+ let out3 = out[3];
1033
+ let out4 = out[4];
1034
+ let out5 = out[5];
1035
+ let out6 = out[6];
1036
+ let out7 = out[7];
1037
+ for (let i2 = 0; i2 < 64; i2++) {
1038
+ if (i2 < 16) {
1039
+ tmp = w[i2];
1040
+ } else {
1041
+ a = w[i2 + 1 & 15];
1042
+ b = w[i2 + 14 & 15];
1043
+ tmp = w[i2 & 15] = (a >>> 7 ^ a >>> 18 ^ a >>> 3 ^ a << 25 ^ a << 14) + (b >>> 17 ^ b >>> 19 ^ b >>> 10 ^ b << 15 ^ b << 13) + w[i2 & 15] + w[i2 + 9 & 15] | 0;
1044
+ }
1045
+ tmp = tmp + out7 + (out4 >>> 6 ^ out4 >>> 11 ^ out4 >>> 25 ^ out4 << 26 ^ out4 << 21 ^ out4 << 7) + (out6 ^ out4 & (out5 ^ out6)) + key[i2];
1046
+ out7 = out6;
1047
+ out6 = out5;
1048
+ out5 = out4;
1049
+ out4 = out3 + tmp | 0;
1050
+ out3 = out2;
1051
+ out2 = out1;
1052
+ out1 = out0;
1053
+ out0 = tmp + (out1 & out2 ^ out3 & (out1 ^ out2)) + (out1 >>> 2 ^ out1 >>> 13 ^ out1 >>> 22 ^ out1 << 30 ^ out1 << 19 ^ out1 << 10) | 0;
1054
+ }
1055
+ out[0] = out[0] + out0 | 0;
1056
+ out[1] = out[1] + out1 | 0;
1057
+ out[2] = out[2] + out2 | 0;
1058
+ out[3] = out[3] + out3 | 0;
1059
+ out[4] = out[4] + out4 | 0;
1060
+ out[5] = out[5] + out5 | 0;
1061
+ out[6] = out[6] + out6 | 0;
1062
+ out[7] = out[7] + out7 | 0;
1063
+ }
1064
+ const bytes = new Uint8Array(out.buffer);
1065
+ reverse_endianness(bytes);
1066
+ return btoa(String.fromCharCode(...bytes));
1067
+ }
1068
+ const init = new Uint32Array(8);
1069
+ const key = new Uint32Array(64);
1070
+ function precompute() {
1071
+ function frac(x) {
1072
+ return (x - Math.floor(x)) * 4294967296;
1073
+ }
1074
+ let prime = 2;
1075
+ for (let i = 0; i < 64; prime++) {
1076
+ let is_prime = true;
1077
+ for (let factor = 2; factor * factor <= prime; factor++) {
1078
+ if (prime % factor === 0) {
1079
+ is_prime = false;
1080
+ break;
1081
+ }
1082
+ }
1083
+ if (is_prime) {
1084
+ if (i < 8) {
1085
+ init[i] = frac(prime ** (1 / 2));
1086
+ }
1087
+ key[i] = frac(prime ** (1 / 3));
1088
+ i++;
1089
+ }
1090
+ }
1091
+ }
1092
+ function reverse_endianness(bytes) {
1093
+ for (let i = 0; i < bytes.length; i += 4) {
1094
+ const a = bytes[i + 0];
1095
+ const b = bytes[i + 1];
1096
+ const c = bytes[i + 2];
1097
+ const d = bytes[i + 3];
1098
+ bytes[i + 0] = d;
1099
+ bytes[i + 1] = c;
1100
+ bytes[i + 2] = b;
1101
+ bytes[i + 3] = a;
1102
+ }
1103
+ }
1104
+ function encode(str) {
1105
+ const encoded = text_encoder.encode(str);
1106
+ const length = encoded.length * 8;
1107
+ const size = 512 * Math.ceil((length + 65) / 512);
1108
+ const bytes = new Uint8Array(size / 8);
1109
+ bytes.set(encoded);
1110
+ bytes[encoded.length] = 128;
1111
+ reverse_endianness(bytes);
1112
+ const words = new Uint32Array(bytes.buffer);
1113
+ words[words.length - 2] = Math.floor(length / 4294967296);
1114
+ words[words.length - 1] = length;
1115
+ return words;
1116
+ }
1117
+ const array = new Uint8Array(16);
1118
+ function generate_nonce() {
1119
+ crypto.getRandomValues(array);
1120
+ return btoa(String.fromCharCode(...array));
1121
+ }
1122
+ const quoted = /* @__PURE__ */ new Set([
1123
+ "self",
1124
+ "unsafe-eval",
1125
+ "unsafe-hashes",
1126
+ "unsafe-inline",
1127
+ "none",
1128
+ "strict-dynamic",
1129
+ "report-sample",
1130
+ "wasm-unsafe-eval",
1131
+ "script"
1132
+ ]);
1133
+ const crypto_pattern = /^(nonce|sha\d\d\d)-/;
1134
+ class BaseProvider {
1135
+ /** @type {boolean} */
1136
+ #use_hashes;
1137
+ /** @type {boolean} */
1138
+ #script_needs_csp;
1139
+ /** @type {boolean} */
1140
+ #script_src_needs_csp;
1141
+ /** @type {boolean} */
1142
+ #script_src_elem_needs_csp;
1143
+ /** @type {boolean} */
1144
+ #style_needs_csp;
1145
+ /** @type {boolean} */
1146
+ #style_src_needs_csp;
1147
+ /** @type {boolean} */
1148
+ #style_src_attr_needs_csp;
1149
+ /** @type {boolean} */
1150
+ #style_src_elem_needs_csp;
1151
+ /** @type {import('types').CspDirectives} */
1152
+ #directives;
1153
+ /** @type {Set<import('types').Csp.Source>} */
1154
+ #script_src;
1155
+ /** @type {Set<import('types').Csp.Source>} */
1156
+ #script_src_elem;
1157
+ /** @type {Set<import('types').Csp.Source>} */
1158
+ #style_src;
1159
+ /** @type {Set<import('types').Csp.Source>} */
1160
+ #style_src_attr;
1161
+ /** @type {Set<import('types').Csp.Source>} */
1162
+ #style_src_elem;
1163
+ /** @type {boolean} */
1164
+ script_needs_nonce;
1165
+ /** @type {boolean} */
1166
+ style_needs_nonce;
1167
+ /** @type {boolean} */
1168
+ script_needs_hash;
1169
+ /** @type {string} */
1170
+ #nonce;
1171
+ /**
1172
+ * @param {boolean} use_hashes
1173
+ * @param {import('types').CspDirectives} directives
1174
+ * @param {string} nonce
1175
+ */
1176
+ constructor(use_hashes, directives, nonce) {
1177
+ this.#use_hashes = use_hashes;
1178
+ this.#directives = directives;
1179
+ const d = this.#directives;
1180
+ this.#script_src = /* @__PURE__ */ new Set();
1181
+ this.#script_src_elem = /* @__PURE__ */ new Set();
1182
+ this.#style_src = /* @__PURE__ */ new Set();
1183
+ this.#style_src_attr = /* @__PURE__ */ new Set();
1184
+ this.#style_src_elem = /* @__PURE__ */ new Set();
1185
+ const effective_script_src = d["script-src"] || d["default-src"];
1186
+ const script_src_elem = d["script-src-elem"];
1187
+ const effective_style_src = d["style-src"] || d["default-src"];
1188
+ const style_src_attr = d["style-src-attr"];
1189
+ const style_src_elem = d["style-src-elem"];
1190
+ const style_needs_csp = (directive) => !!directive && !directive.some((value) => value === "unsafe-inline");
1191
+ const script_needs_csp = (directive) => !!directive && (!directive.some((value) => value === "unsafe-inline") || directive.some((value) => value === "strict-dynamic"));
1192
+ this.#script_src_needs_csp = script_needs_csp(effective_script_src);
1193
+ this.#script_src_elem_needs_csp = script_needs_csp(script_src_elem);
1194
+ this.#style_src_needs_csp = style_needs_csp(effective_style_src);
1195
+ this.#style_src_attr_needs_csp = style_needs_csp(style_src_attr);
1196
+ this.#style_src_elem_needs_csp = style_needs_csp(style_src_elem);
1197
+ this.#script_needs_csp = this.#script_src_needs_csp || this.#script_src_elem_needs_csp;
1198
+ this.#style_needs_csp = this.#style_src_needs_csp || this.#style_src_attr_needs_csp || this.#style_src_elem_needs_csp;
1199
+ this.script_needs_nonce = this.#script_needs_csp && !this.#use_hashes;
1200
+ this.style_needs_nonce = this.#style_needs_csp && !this.#use_hashes;
1201
+ this.script_needs_hash = this.#script_needs_csp && this.#use_hashes;
1202
+ this.#nonce = nonce;
1203
+ }
1204
+ /** @param {string} content */
1205
+ add_script(content) {
1206
+ if (!this.#script_needs_csp) return;
1207
+ const source = this.#use_hashes ? `sha256-${sha256(content)}` : `nonce-${this.#nonce}`;
1208
+ if (this.#script_src_needs_csp) {
1209
+ this.#script_src.add(source);
1210
+ }
1211
+ if (this.#script_src_elem_needs_csp) {
1212
+ this.#script_src_elem.add(source);
1213
+ }
1214
+ }
1215
+ /** @param {`sha256-${string}`[]} hashes */
1216
+ add_script_hashes(hashes) {
1217
+ for (const hash2 of hashes) {
1218
+ if (this.#script_src_needs_csp) {
1219
+ this.#script_src.add(hash2);
1220
+ }
1221
+ if (this.#script_src_elem_needs_csp) {
1222
+ this.#script_src_elem.add(hash2);
1223
+ }
1224
+ }
1225
+ }
1226
+ /** @param {string} content */
1227
+ add_style(content) {
1228
+ if (!this.#style_needs_csp) return;
1229
+ const source = this.#use_hashes ? `sha256-${sha256(content)}` : `nonce-${this.#nonce}`;
1230
+ if (this.#style_src_needs_csp) {
1231
+ this.#style_src.add(source);
1232
+ }
1233
+ if (this.#style_src_attr_needs_csp) {
1234
+ this.#style_src_attr.add(source);
1235
+ }
1236
+ if (this.#style_src_elem_needs_csp) {
1237
+ const sha256_empty_comment_hash = "sha256-9OlNO0DNEeaVzHL4RZwCLsBHA8WBQ8toBp/4F5XV2nc=";
1238
+ const d = this.#directives;
1239
+ if (d["style-src-elem"] && !d["style-src-elem"].includes(sha256_empty_comment_hash) && !this.#style_src_elem.has(sha256_empty_comment_hash)) {
1240
+ this.#style_src_elem.add(sha256_empty_comment_hash);
1241
+ }
1242
+ if (source !== sha256_empty_comment_hash) {
1243
+ this.#style_src_elem.add(source);
1244
+ }
1245
+ }
1246
+ }
1247
+ /**
1248
+ * @param {boolean} [is_meta]
1249
+ */
1250
+ get_header(is_meta = false) {
1251
+ const header = [];
1252
+ const directives = { ...this.#directives };
1253
+ if (this.#style_src.size > 0) {
1254
+ directives["style-src"] = [
1255
+ ...directives["style-src"] || directives["default-src"] || [],
1256
+ ...this.#style_src
1257
+ ];
1258
+ }
1259
+ if (this.#style_src_attr.size > 0) {
1260
+ directives["style-src-attr"] = [
1261
+ ...directives["style-src-attr"] || [],
1262
+ ...this.#style_src_attr
1263
+ ];
1264
+ }
1265
+ if (this.#style_src_elem.size > 0) {
1266
+ directives["style-src-elem"] = [
1267
+ ...directives["style-src-elem"] || [],
1268
+ ...this.#style_src_elem
1269
+ ];
1270
+ }
1271
+ if (this.#script_src.size > 0) {
1272
+ directives["script-src"] = [
1273
+ ...directives["script-src"] || directives["default-src"] || [],
1274
+ ...this.#script_src
1275
+ ];
1276
+ }
1277
+ if (this.#script_src_elem.size > 0) {
1278
+ directives["script-src-elem"] = [
1279
+ ...directives["script-src-elem"] || [],
1280
+ ...this.#script_src_elem
1281
+ ];
1282
+ }
1283
+ for (const key2 in directives) {
1284
+ if (is_meta && (key2 === "frame-ancestors" || key2 === "report-uri" || key2 === "sandbox")) {
1285
+ continue;
1286
+ }
1287
+ const value = (
1288
+ /** @type {string[] | true} */
1289
+ directives[key2]
1290
+ );
1291
+ if (!value) continue;
1292
+ const directive = [key2];
1293
+ if (Array.isArray(value)) {
1294
+ value.forEach((value2) => {
1295
+ if (quoted.has(value2) || crypto_pattern.test(value2)) {
1296
+ directive.push(`'${value2}'`);
1297
+ } else {
1298
+ directive.push(value2);
1299
+ }
1300
+ });
1301
+ }
1302
+ header.push(directive.join(" "));
1303
+ }
1304
+ return header.join("; ");
1305
+ }
1306
+ }
1307
+ class CspProvider extends BaseProvider {
1308
+ get_meta() {
1309
+ const content = this.get_header(true);
1310
+ if (!content) {
1311
+ return;
1312
+ }
1313
+ return `<meta http-equiv="content-security-policy" content="${escape_html(content, true)}">`;
1314
+ }
1315
+ }
1316
+ class CspReportOnlyProvider extends BaseProvider {
1317
+ /**
1318
+ * @param {boolean} use_hashes
1319
+ * @param {import('types').CspDirectives} directives
1320
+ * @param {string} nonce
1321
+ */
1322
+ constructor(use_hashes, directives, nonce) {
1323
+ super(use_hashes, directives, nonce);
1324
+ if (Object.values(directives).filter((v) => !!v).length > 0) {
1325
+ const has_report_to = directives["report-to"]?.length ?? 0 > 0;
1326
+ const has_report_uri = directives["report-uri"]?.length ?? 0 > 0;
1327
+ if (!has_report_to && !has_report_uri) {
1328
+ throw Error(
1329
+ "`content-security-policy-report-only` must be specified with either the `report-to` or `report-uri` directives, or both"
1330
+ );
1331
+ }
1332
+ }
1333
+ }
1334
+ }
1335
+ class Csp {
1336
+ /** @readonly */
1337
+ nonce = generate_nonce();
1338
+ /** @type {CspProvider} */
1339
+ csp_provider;
1340
+ /** @type {CspReportOnlyProvider} */
1341
+ report_only_provider;
1342
+ /**
1343
+ * @param {import('./types.js').CspConfig} config
1344
+ * @param {import('./types.js').CspOpts} opts
1345
+ */
1346
+ constructor({ mode, directives, reportOnly }, { prerender }) {
1347
+ const use_hashes = mode === "hash" || mode === "auto" && prerender;
1348
+ this.csp_provider = new CspProvider(use_hashes, directives, this.nonce);
1349
+ this.report_only_provider = new CspReportOnlyProvider(use_hashes, reportOnly, this.nonce);
1350
+ }
1351
+ get script_needs_hash() {
1352
+ return this.csp_provider.script_needs_hash || this.report_only_provider.script_needs_hash;
1353
+ }
1354
+ get script_needs_nonce() {
1355
+ return this.csp_provider.script_needs_nonce || this.report_only_provider.script_needs_nonce;
1356
+ }
1357
+ get style_needs_nonce() {
1358
+ return this.csp_provider.style_needs_nonce || this.report_only_provider.style_needs_nonce;
1359
+ }
1360
+ /** @param {string} content */
1361
+ add_script(content) {
1362
+ this.csp_provider.add_script(content);
1363
+ this.report_only_provider.add_script(content);
1364
+ }
1365
+ /** @param {`sha256-${string}`[]} hashes */
1366
+ add_script_hashes(hashes) {
1367
+ this.csp_provider.add_script_hashes(hashes);
1368
+ this.report_only_provider.add_script_hashes(hashes);
1369
+ }
1370
+ /** @param {string} content */
1371
+ add_style(content) {
1372
+ this.csp_provider.add_style(content);
1373
+ this.report_only_provider.add_style(content);
1374
+ }
1375
+ }
1376
+ function exec(match, params, matchers) {
1377
+ const result = {};
1378
+ const values = match.slice(1);
1379
+ const values_needing_match = values.filter((value) => value !== void 0);
1380
+ let buffered = 0;
1381
+ for (let i = 0; i < params.length; i += 1) {
1382
+ const param = params[i];
1383
+ let value = values[i - buffered];
1384
+ if (param.chained && param.rest && buffered) {
1385
+ value = values.slice(i - buffered, i + 1).filter((s2) => s2).join("/");
1386
+ buffered = 0;
1387
+ }
1388
+ if (value === void 0) {
1389
+ if (param.rest) {
1390
+ value = "";
1391
+ } else {
1392
+ continue;
1393
+ }
1394
+ }
1395
+ if (!param.matcher || matchers[param.matcher](value)) {
1396
+ result[param.name] = value;
1397
+ const next_param = params[i + 1];
1398
+ const next_value = values[i + 1];
1399
+ if (next_param && !next_param.rest && next_param.optional && next_value && param.chained) {
1400
+ buffered = 0;
1401
+ }
1402
+ if (!next_param && !next_value && Object.keys(result).length === values_needing_match.length) {
1403
+ buffered = 0;
1404
+ }
1405
+ continue;
1406
+ }
1407
+ if (param.optional && param.chained) {
1408
+ buffered++;
1409
+ continue;
1410
+ }
1411
+ return;
1412
+ }
1413
+ if (buffered) return;
1414
+ return result;
1415
+ }
1416
+ function generate_route_object(route, url, manifest) {
1417
+ const { errors, layouts, leaf } = route;
1418
+ const nodes = [...errors, ...layouts.map((l) => l?.[1]), leaf[1]].filter((n) => typeof n === "number").map((n) => `'${n}': () => ${create_client_import(manifest._.client.nodes?.[n], url)}`).join(",\n ");
1419
+ return [
1420
+ `{
1421
+ id: ${s(route.id)}`,
1422
+ `errors: ${s(route.errors)}`,
1423
+ `layouts: ${s(route.layouts)}`,
1424
+ `leaf: ${s(route.leaf)}`,
1425
+ `nodes: {
1426
+ ${nodes}
1427
+ }
1428
+ }`
1429
+ ].join(",\n ");
1430
+ }
1431
+ function create_client_import(import_path, url) {
1432
+ if (!import_path) return "Promise.resolve({})";
1433
+ if (import_path[0] === "/") {
1434
+ return `import('${import_path}')`;
1435
+ }
1436
+ if (assets !== "") {
1437
+ return `import('${assets}/${import_path}')`;
1438
+ }
1439
+ let path = get_relative_path(url.pathname, `${base}/${import_path}`);
1440
+ if (path[0] !== ".") path = `./${path}`;
1441
+ return `import('${path}')`;
1442
+ }
1443
+ async function resolve_route(resolved_path, url, manifest) {
1444
+ if (!manifest._.client.routes) {
1445
+ return text("Server-side route resolution disabled", { status: 400 });
1446
+ }
1447
+ let route = null;
1448
+ let params = {};
1449
+ const matchers = await manifest._.matchers();
1450
+ for (const candidate of manifest._.client.routes) {
1451
+ const match = candidate.pattern.exec(resolved_path);
1452
+ if (!match) continue;
1453
+ const matched = exec(match, candidate.params, matchers);
1454
+ if (matched) {
1455
+ route = candidate;
1456
+ params = decode_params(matched);
1457
+ break;
1458
+ }
1459
+ }
1460
+ return create_server_routing_response(route, params, url, manifest).response;
1461
+ }
1462
+ function create_server_routing_response(route, params, url, manifest) {
1463
+ const headers2 = new Headers({
1464
+ "content-type": "application/javascript; charset=utf-8"
1465
+ });
1466
+ if (route) {
1467
+ const csr_route = generate_route_object(route, url, manifest);
1468
+ const body2 = `${create_css_import(route, url, manifest)}
1469
+ export const route = ${csr_route}; export const params = ${JSON.stringify(params)};`;
1470
+ return { response: text(body2, { headers: headers2 }), body: body2 };
1471
+ } else {
1472
+ return { response: text("", { headers: headers2 }), body: "" };
1473
+ }
1474
+ }
1475
+ function create_css_import(route, url, manifest) {
1476
+ const { errors, layouts, leaf } = route;
1477
+ let css = "";
1478
+ for (const node of [...errors, ...layouts.map((l) => l?.[1]), leaf[1]]) {
1479
+ if (typeof node !== "number") continue;
1480
+ const node_css = manifest._.client.css?.[node];
1481
+ for (const css_path of node_css ?? []) {
1482
+ css += `'${assets || base}/${css_path}',`;
1483
+ }
1484
+ }
1485
+ if (!css) return "";
1486
+ return `${create_client_import(
1487
+ /** @type {string} */
1488
+ manifest._.client.start,
1489
+ url
1490
+ )}.then(x => x.load_css([${css}]));`;
1491
+ }
1492
+ const updated = {
1493
+ ...readable(false),
1494
+ check: () => false
1495
+ };
1496
+ async function render_response({
1497
+ branch,
1498
+ fetched,
1499
+ options: options2,
1500
+ manifest,
1501
+ state,
1502
+ page_config,
1503
+ status,
1504
+ error: error2 = null,
1505
+ event,
1506
+ event_state,
1507
+ resolve_opts,
1508
+ action_result,
1509
+ data_serializer
1510
+ }) {
1511
+ if (state.prerendering) {
1512
+ if (options2.csp.mode === "nonce") {
1513
+ throw new Error('Cannot use prerendering if config.kit.csp.mode === "nonce"');
1514
+ }
1515
+ if (options2.app_template_contains_nonce) {
1516
+ throw new Error("Cannot use prerendering if page template contains %sveltekit.nonce%");
1517
+ }
1518
+ }
1519
+ const { client } = manifest._;
1520
+ const modulepreloads = new Set(client.imports);
1521
+ const stylesheets = new Set(client.stylesheets);
1522
+ const fonts = new Set(client.fonts);
1523
+ const link_headers = /* @__PURE__ */ new Set();
1524
+ const inline_styles = /* @__PURE__ */ new Map();
1525
+ let rendered;
1526
+ const form_value = action_result?.type === "success" || action_result?.type === "failure" ? action_result.data ?? null : null;
1527
+ let base$1 = base;
1528
+ let assets$1 = assets;
1529
+ let base_expression = s(base);
1530
+ const csp = new Csp(options2.csp, {
1531
+ prerender: !!state.prerendering
1532
+ });
1533
+ {
1534
+ if (!state.prerendering?.fallback) {
1535
+ const segments = event.url.pathname.slice(base.length).split("/").slice(2);
1536
+ base$1 = segments.map(() => "..").join("/") || ".";
1537
+ base_expression = `new URL(${s(base$1)}, location).pathname.slice(0, -1)`;
1538
+ if (!assets || assets[0] === "/" && assets !== SVELTE_KIT_ASSETS) {
1539
+ assets$1 = base$1;
1540
+ }
1541
+ } else if (options2.hash_routing) {
1542
+ base_expression = "new URL('.', location).pathname.slice(0, -1)";
1543
+ }
1544
+ }
1545
+ if (page_config.ssr) {
1546
+ const props = {
1547
+ stores: {
1548
+ page: writable(null),
1549
+ navigating: writable(null),
1550
+ updated
1551
+ },
1552
+ constructors: await Promise.all(
1553
+ branch.map(({ node }) => {
1554
+ if (!node.component) {
1555
+ throw new Error(`Missing +page.svelte component for route ${event.route.id}`);
1556
+ }
1557
+ return node.component();
1558
+ })
1559
+ ),
1560
+ form: form_value
1561
+ };
1562
+ let data2 = {};
1563
+ for (let i = 0; i < branch.length; i += 1) {
1564
+ data2 = { ...data2, ...branch[i].data };
1565
+ props[`data_${i}`] = data2;
1566
+ }
1567
+ props.page = {
1568
+ error: error2,
1569
+ params: (
1570
+ /** @type {Record<string, any>} */
1571
+ event.params
1572
+ ),
1573
+ route: event.route,
1574
+ status,
1575
+ url: event.url,
1576
+ data: data2,
1577
+ form: form_value,
1578
+ state: {}
1579
+ };
1580
+ const render_opts = {
1581
+ context: /* @__PURE__ */ new Map([
1582
+ [
1583
+ "__request__",
1584
+ {
1585
+ page: props.page
1586
+ }
1587
+ ]
1588
+ ]),
1589
+ csp: csp.script_needs_nonce ? { nonce: csp.nonce } : { hash: csp.script_needs_hash }
1590
+ };
1591
+ const fetch2 = globalThis.fetch;
1592
+ try {
1593
+ if (BROWSER) ;
1594
+ rendered = await with_request_store({ event, state: event_state }, async () => {
1595
+ if (relative) override({ base: base$1, assets: assets$1 });
1596
+ const maybe_promise = options2.root.render(props, render_opts);
1597
+ const rendered2 = options2.async && "then" in maybe_promise ? (
1598
+ /** @type {ReturnType<typeof options.root.render> & Promise<any>} */
1599
+ maybe_promise.then((r) => r)
1600
+ ) : maybe_promise;
1601
+ if (options2.async) {
1602
+ reset();
1603
+ }
1604
+ const { head: head2, html: html2, css, hashes } = (
1605
+ /** @type {ReturnType<typeof options.root.render>} */
1606
+ options2.async ? await rendered2 : rendered2
1607
+ );
1608
+ if (hashes) {
1609
+ csp.add_script_hashes(hashes.script);
1610
+ }
1611
+ return { head: head2, html: html2, css, hashes };
1612
+ });
1613
+ } finally {
1614
+ reset();
1615
+ }
1616
+ for (const { node } of branch) {
1617
+ for (const url of node.imports) modulepreloads.add(url);
1618
+ for (const url of node.stylesheets) stylesheets.add(url);
1619
+ for (const url of node.fonts) fonts.add(url);
1620
+ if (node.inline_styles && !client.inline) {
1621
+ Object.entries(await node.inline_styles()).forEach(([filename, css]) => {
1622
+ if (typeof css === "string") {
1623
+ inline_styles.set(filename, css);
1624
+ return;
1625
+ }
1626
+ inline_styles.set(filename, css(`${assets$1}/${app_dir}/immutable/assets`, assets$1));
1627
+ });
1628
+ }
1629
+ }
1630
+ } else {
1631
+ rendered = { head: "", html: "", css: { code: "", map: null }, hashes: { script: [] } };
1632
+ }
1633
+ const head = new Head(rendered.head, !!state.prerendering);
1634
+ let body2 = rendered.html;
1635
+ const prefixed = (path) => {
1636
+ if (path.startsWith("/")) {
1637
+ return base + path;
1638
+ }
1639
+ return `${assets$1}/${path}`;
1640
+ };
1641
+ const style = client.inline ? client.inline?.style : Array.from(inline_styles.values()).join("\n");
1642
+ if (style) {
1643
+ const attributes = [];
1644
+ if (csp.style_needs_nonce) attributes.push(`nonce="${csp.nonce}"`);
1645
+ csp.add_style(style);
1646
+ head.add_style(style, attributes);
1647
+ }
1648
+ for (const dep of stylesheets) {
1649
+ const path = prefixed(dep);
1650
+ const attributes = ['rel="stylesheet"'];
1651
+ if (inline_styles.has(dep)) {
1652
+ attributes.push("disabled", 'media="(max-width: 0)"');
1653
+ } else {
1654
+ if (resolve_opts.preload({ type: "css", path })) {
1655
+ link_headers.add(`<${encodeURI(path)}>; rel="preload"; as="style"; nopush`);
1656
+ }
1657
+ }
1658
+ head.add_stylesheet(path, attributes);
1659
+ }
1660
+ for (const dep of fonts) {
1661
+ const path = prefixed(dep);
1662
+ if (resolve_opts.preload({ type: "font", path })) {
1663
+ const ext = dep.slice(dep.lastIndexOf(".") + 1);
1664
+ head.add_link_tag(path, ['rel="preload"', 'as="font"', `type="font/${ext}"`, "crossorigin"]);
1665
+ link_headers.add(
1666
+ `<${encodeURI(path)}>; rel="preload"; as="font"; type="font/${ext}"; crossorigin; nopush`
1667
+ );
1668
+ }
1669
+ }
1670
+ const global = get_global_name(options2);
1671
+ const { data, chunks } = data_serializer.get_data(csp);
1672
+ if (page_config.ssr && page_config.csr) {
1673
+ body2 += `
1674
+ ${fetched.map(
1675
+ (item) => serialize_data(item, resolve_opts.filterSerializedResponseHeaders, !!state.prerendering)
1676
+ ).join("\n ")}`;
1677
+ }
1678
+ if (page_config.csr) {
1679
+ const route = manifest._.client.routes?.find((r) => r.id === event.route.id) ?? null;
1680
+ if (client.uses_env_dynamic_public && state.prerendering) {
1681
+ modulepreloads.add(`${app_dir}/env.js`);
1682
+ }
1683
+ if (!client.inline) {
1684
+ const included_modulepreloads = Array.from(modulepreloads, (dep) => prefixed(dep)).filter(
1685
+ (path) => resolve_opts.preload({ type: "js", path })
1686
+ );
1687
+ for (const path of included_modulepreloads) {
1688
+ link_headers.add(`<${encodeURI(path)}>; rel="modulepreload"; nopush`);
1689
+ if (options2.preload_strategy !== "modulepreload") {
1690
+ head.add_script_preload(path);
1691
+ } else {
1692
+ head.add_link_tag(path, ['rel="modulepreload"']);
1693
+ }
1694
+ }
1695
+ }
1696
+ if (manifest._.client.routes && state.prerendering && !state.prerendering.fallback) {
1697
+ const pathname = add_resolution_suffix(event.url.pathname);
1698
+ state.prerendering.dependencies.set(
1699
+ pathname,
1700
+ create_server_routing_response(route, event.params, new URL(pathname, event.url), manifest)
1701
+ );
1702
+ }
1703
+ const blocks = [];
1704
+ const load_env_eagerly = client.uses_env_dynamic_public && state.prerendering;
1705
+ const properties = [`base: ${base_expression}`];
1706
+ if (assets) {
1707
+ properties.push(`assets: ${s(assets)}`);
1708
+ }
1709
+ if (client.uses_env_dynamic_public) {
1710
+ properties.push(`env: ${load_env_eagerly ? "null" : s(public_env)}`);
1711
+ }
1712
+ if (chunks) {
1713
+ blocks.push("const deferred = new Map();");
1714
+ properties.push(`defer: (id) => new Promise((fulfil, reject) => {
1715
+ deferred.set(id, { fulfil, reject });
1716
+ })`);
1717
+ let app_declaration = "";
1718
+ if (Object.keys(options2.hooks.transport).length > 0) {
1719
+ if (client.inline) {
1720
+ app_declaration = `const app = __sveltekit_${options2.version_hash}.app.app;`;
1721
+ } else if (client.app) {
1722
+ app_declaration = `const app = await import(${s(prefixed(client.app))});`;
1723
+ } else {
1724
+ app_declaration = `const { app } = await import(${s(prefixed(client.start))});`;
1725
+ }
1726
+ }
1727
+ const prelude = app_declaration ? `${app_declaration}
1728
+ const [data, error] = fn(app);` : `const [data, error] = fn();`;
1729
+ properties.push(`resolve: async (id, fn) => {
1730
+ ${prelude}
1731
+
1732
+ const try_to_resolve = () => {
1733
+ if (!deferred.has(id)) {
1734
+ setTimeout(try_to_resolve, 0);
1735
+ return;
1736
+ }
1737
+ const { fulfil, reject } = deferred.get(id);
1738
+ deferred.delete(id);
1739
+ if (error) reject(error);
1740
+ else fulfil(data);
1741
+ }
1742
+ try_to_resolve();
1743
+ }`);
1744
+ }
1745
+ blocks.push(`${global} = {
1746
+ ${properties.join(",\n ")}
1747
+ };`);
1748
+ const args = ["element"];
1749
+ blocks.push("const element = document.currentScript.parentElement;");
1750
+ if (page_config.ssr) {
1751
+ const serialized = { form: "null", error: "null" };
1752
+ if (form_value) {
1753
+ serialized.form = uneval_action_response(
1754
+ form_value,
1755
+ /** @type {string} */
1756
+ event.route.id,
1757
+ options2.hooks.transport
1758
+ );
1759
+ }
1760
+ if (error2) {
1761
+ serialized.error = devalue.uneval(error2);
1762
+ }
1763
+ const hydrate = [
1764
+ `node_ids: [${branch.map(({ node }) => node.index).join(", ")}]`,
1765
+ `data: ${data}`,
1766
+ `form: ${serialized.form}`,
1767
+ `error: ${serialized.error}`
1768
+ ];
1769
+ if (status !== 200) {
1770
+ hydrate.push(`status: ${status}`);
1771
+ }
1772
+ if (manifest._.client.routes) {
1773
+ if (route) {
1774
+ const stringified = generate_route_object(route, event.url, manifest).replaceAll(
1775
+ "\n",
1776
+ "\n "
1777
+ );
1778
+ hydrate.push(`params: ${devalue.uneval(event.params)}`, `server_route: ${stringified}`);
1779
+ }
1780
+ } else if (options2.embedded) {
1781
+ hydrate.push(`params: ${devalue.uneval(event.params)}`, `route: ${s(event.route)}`);
1782
+ }
1783
+ const indent = " ".repeat(load_env_eagerly ? 7 : 6);
1784
+ args.push(`{
1785
+ ${indent} ${hydrate.join(`,
1786
+ ${indent} `)}
1787
+ ${indent}}`);
1788
+ }
1789
+ const { remote_data: remote_cache } = event_state;
1790
+ let serialized_remote_data = "";
1791
+ if (remote_cache) {
1792
+ const remote = {};
1793
+ for (const [info, cache] of remote_cache) {
1794
+ if (!info.id) continue;
1795
+ for (const key2 in cache) {
1796
+ remote[create_remote_key(info.id, key2)] = await cache[key2];
1797
+ }
1798
+ }
1799
+ const replacer = (thing) => {
1800
+ for (const key2 in options2.hooks.transport) {
1801
+ const encoded = options2.hooks.transport[key2].encode(thing);
1802
+ if (encoded) {
1803
+ return `app.decode('${key2}', ${devalue.uneval(encoded, replacer)})`;
1804
+ }
1805
+ }
1806
+ };
1807
+ serialized_remote_data = `${global}.data = ${devalue.uneval(remote, replacer)};
1808
+
1809
+ `;
1810
+ }
1811
+ const boot = client.inline ? `${client.inline.script}
1812
+
1813
+ ${serialized_remote_data}${global}.app.start(${args.join(", ")});` : client.app ? `Promise.all([
1814
+ import(${s(prefixed(client.start))}),
1815
+ import(${s(prefixed(client.app))})
1816
+ ]).then(([kit, app]) => {
1817
+ ${serialized_remote_data}kit.start(app, ${args.join(", ")});
1818
+ });` : `import(${s(prefixed(client.start))}).then((app) => {
1819
+ ${serialized_remote_data}app.start(${args.join(", ")})
1820
+ });`;
1821
+ if (load_env_eagerly) {
1822
+ blocks.push(`import(${s(`${base$1}/${app_dir}/env.js`)}).then(({ env }) => {
1823
+ ${global}.env = env;
1824
+
1825
+ ${boot.replace(/\n/g, "\n ")}
1826
+ });`);
1827
+ } else {
1828
+ blocks.push(boot);
1829
+ }
1830
+ if (options2.service_worker) {
1831
+ let opts = "";
1832
+ if (options2.service_worker_options != null) {
1833
+ const service_worker_options = { ...options2.service_worker_options };
1834
+ opts = `, ${s(service_worker_options)}`;
1835
+ }
1836
+ blocks.push(`if ('serviceWorker' in navigator) {
1837
+ addEventListener('load', function () {
1838
+ navigator.serviceWorker.register('${prefixed("service-worker.js")}'${opts});
1839
+ });
1840
+ }`);
1841
+ }
1842
+ const init_app = `
1843
+ {
1844
+ ${blocks.join("\n\n ")}
1845
+ }
1846
+ `;
1847
+ csp.add_script(init_app);
1848
+ body2 += `
1849
+ <script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ""}>${init_app}<\/script>
1850
+ `;
1851
+ }
1852
+ const headers2 = new Headers({
1853
+ "x-sveltekit-page": "true",
1854
+ "content-type": "text/html"
1855
+ });
1856
+ if (state.prerendering) {
1857
+ const csp_headers = csp.csp_provider.get_meta();
1858
+ if (csp_headers) {
1859
+ head.add_http_equiv(csp_headers);
1860
+ }
1861
+ if (state.prerendering.cache) {
1862
+ head.add_http_equiv(
1863
+ `<meta http-equiv="cache-control" content="${state.prerendering.cache}">`
1864
+ );
1865
+ }
1866
+ } else {
1867
+ const csp_header = csp.csp_provider.get_header();
1868
+ if (csp_header) {
1869
+ headers2.set("content-security-policy", csp_header);
1870
+ }
1871
+ const report_only_header = csp.report_only_provider.get_header();
1872
+ if (report_only_header) {
1873
+ headers2.set("content-security-policy-report-only", report_only_header);
1874
+ }
1875
+ if (link_headers.size) {
1876
+ headers2.set("link", Array.from(link_headers).join(", "));
1877
+ }
1878
+ }
1879
+ const html = options2.templates.app({
1880
+ head: head.build(),
1881
+ body: body2,
1882
+ assets: assets$1,
1883
+ nonce: (
1884
+ /** @type {string} */
1885
+ csp.nonce
1886
+ ),
1887
+ env: public_env
1888
+ });
1889
+ const transformed = await resolve_opts.transformPageChunk({
1890
+ html,
1891
+ done: true
1892
+ }) || "";
1893
+ if (!chunks) {
1894
+ headers2.set("etag", `"${hash(transformed)}"`);
1895
+ }
1896
+ return !chunks ? text(transformed, {
1897
+ status,
1898
+ headers: headers2
1899
+ }) : new Response(
1900
+ new ReadableStream({
1901
+ async start(controller) {
1902
+ controller.enqueue(text_encoder.encode(transformed + "\n"));
1903
+ for await (const chunk of chunks) {
1904
+ if (chunk.length) controller.enqueue(text_encoder.encode(chunk));
1905
+ }
1906
+ controller.close();
1907
+ },
1908
+ type: "bytes"
1909
+ }),
1910
+ {
1911
+ headers: headers2
1912
+ }
1913
+ );
1914
+ }
1915
+ class Head {
1916
+ #rendered;
1917
+ #prerendering;
1918
+ /** @type {string[]} */
1919
+ #http_equiv = [];
1920
+ /** @type {string[]} */
1921
+ #link_tags = [];
1922
+ /** @type {string[]} */
1923
+ #script_preloads = [];
1924
+ /** @type {string[]} */
1925
+ #style_tags = [];
1926
+ /** @type {string[]} */
1927
+ #stylesheet_links = [];
1928
+ /**
1929
+ * @param {string} rendered
1930
+ * @param {boolean} prerendering
1931
+ */
1932
+ constructor(rendered, prerendering) {
1933
+ this.#rendered = rendered;
1934
+ this.#prerendering = prerendering;
1935
+ }
1936
+ build() {
1937
+ return [
1938
+ ...this.#http_equiv,
1939
+ ...this.#link_tags,
1940
+ ...this.#script_preloads,
1941
+ this.#rendered,
1942
+ ...this.#style_tags,
1943
+ ...this.#stylesheet_links
1944
+ ].join("\n ");
1945
+ }
1946
+ /**
1947
+ * @param {string} style
1948
+ * @param {string[]} attributes
1949
+ */
1950
+ add_style(style, attributes) {
1951
+ this.#style_tags.push(
1952
+ `<style${attributes.length ? " " + attributes.join(" ") : ""}>${style}</style>`
1953
+ );
1954
+ }
1955
+ /**
1956
+ * @param {string} href
1957
+ * @param {string[]} attributes
1958
+ */
1959
+ add_stylesheet(href, attributes) {
1960
+ this.#stylesheet_links.push(`<link href="${href}" ${attributes.join(" ")}>`);
1961
+ }
1962
+ /** @param {string} href */
1963
+ add_script_preload(href) {
1964
+ this.#script_preloads.push(
1965
+ `<link rel="preload" as="script" crossorigin="anonymous" href="${href}">`
1966
+ );
1967
+ }
1968
+ /**
1969
+ * @param {string} href
1970
+ * @param {string[]} attributes
1971
+ */
1972
+ add_link_tag(href, attributes) {
1973
+ if (!this.#prerendering) return;
1974
+ this.#link_tags.push(`<link href="${href}" ${attributes.join(" ")}>`);
1975
+ }
1976
+ /** @param {string} tag */
1977
+ add_http_equiv(tag) {
1978
+ if (!this.#prerendering) return;
1979
+ this.#http_equiv.push(tag);
1980
+ }
1981
+ }
1982
+ class PageNodes {
1983
+ data;
1984
+ /**
1985
+ * @param {Array<import('types').SSRNode | undefined>} nodes
1986
+ */
1987
+ constructor(nodes) {
1988
+ this.data = nodes;
1989
+ }
1990
+ layouts() {
1991
+ return this.data.slice(0, -1);
1992
+ }
1993
+ page() {
1994
+ return this.data.at(-1);
1995
+ }
1996
+ validate() {
1997
+ for (const layout of this.layouts()) {
1998
+ if (layout) {
1999
+ validate_layout_server_exports(
2000
+ layout.server,
2001
+ /** @type {string} */
2002
+ layout.server_id
2003
+ );
2004
+ validate_layout_exports(
2005
+ layout.universal,
2006
+ /** @type {string} */
2007
+ layout.universal_id
2008
+ );
2009
+ }
2010
+ }
2011
+ const page = this.page();
2012
+ if (page) {
2013
+ validate_page_server_exports(
2014
+ page.server,
2015
+ /** @type {string} */
2016
+ page.server_id
2017
+ );
2018
+ validate_page_exports(
2019
+ page.universal,
2020
+ /** @type {string} */
2021
+ page.universal_id
2022
+ );
2023
+ }
2024
+ }
2025
+ /**
2026
+ * @template {'prerender' | 'ssr' | 'csr' | 'trailingSlash'} Option
2027
+ * @param {Option} option
2028
+ * @returns {Value | undefined}
2029
+ */
2030
+ #get_option(option) {
2031
+ return this.data.reduce(
2032
+ (value, node) => {
2033
+ return node?.universal?.[option] ?? node?.server?.[option] ?? value;
2034
+ },
2035
+ /** @type {Value | undefined} */
2036
+ void 0
2037
+ );
2038
+ }
2039
+ csr() {
2040
+ return this.#get_option("csr") ?? true;
2041
+ }
2042
+ ssr() {
2043
+ return this.#get_option("ssr") ?? true;
2044
+ }
2045
+ prerender() {
2046
+ return this.#get_option("prerender") ?? false;
2047
+ }
2048
+ trailing_slash() {
2049
+ return this.#get_option("trailingSlash") ?? "never";
2050
+ }
2051
+ get_config() {
2052
+ let current2 = {};
2053
+ for (const node of this.data) {
2054
+ if (!node?.universal?.config && !node?.server?.config) continue;
2055
+ current2 = {
2056
+ ...current2,
2057
+ // TODO: should we override the server config value with the universal value similar to other page options?
2058
+ ...node?.universal?.config,
2059
+ ...node?.server?.config
2060
+ };
2061
+ }
2062
+ return Object.keys(current2).length ? current2 : void 0;
2063
+ }
2064
+ should_prerender_data() {
2065
+ return this.data.some(
2066
+ // prerender in case of trailingSlash because the client retrieves that value from the server
2067
+ (node) => node?.server?.load || node?.server?.trailingSlash !== void 0
2068
+ );
2069
+ }
2070
+ }
2071
+ async function respond_with_error({
2072
+ event,
2073
+ event_state,
2074
+ options: options2,
2075
+ manifest,
2076
+ state,
2077
+ status,
2078
+ error: error2,
2079
+ resolve_opts
2080
+ }) {
2081
+ if (event.request.headers.get("x-sveltekit-error")) {
2082
+ return static_error_page(
2083
+ options2,
2084
+ status,
2085
+ /** @type {Error} */
2086
+ error2.message
2087
+ );
2088
+ }
2089
+ const fetched = [];
2090
+ try {
2091
+ const branch = [];
2092
+ const default_layout = await manifest._.nodes[0]();
2093
+ const nodes = new PageNodes([default_layout]);
2094
+ const ssr = nodes.ssr();
2095
+ const csr = nodes.csr();
2096
+ const data_serializer = server_data_serializer(event, event_state, options2);
2097
+ if (ssr) {
2098
+ state.error = true;
2099
+ const server_data_promise = load_server_data({
2100
+ event,
2101
+ event_state,
2102
+ state,
2103
+ node: default_layout,
2104
+ // eslint-disable-next-line @typescript-eslint/require-await
2105
+ parent: async () => ({})
2106
+ });
2107
+ const server_data = await server_data_promise;
2108
+ data_serializer.add_node(0, server_data);
2109
+ const data = await load_data({
2110
+ event,
2111
+ event_state,
2112
+ fetched,
2113
+ node: default_layout,
2114
+ // eslint-disable-next-line @typescript-eslint/require-await
2115
+ parent: async () => ({}),
2116
+ resolve_opts,
2117
+ server_data_promise,
2118
+ state,
2119
+ csr
2120
+ });
2121
+ branch.push(
2122
+ {
2123
+ node: default_layout,
2124
+ server_data,
2125
+ data
2126
+ },
2127
+ {
2128
+ node: await manifest._.nodes[1](),
2129
+ // 1 is always the root error
2130
+ data: null,
2131
+ server_data: null
2132
+ }
2133
+ );
2134
+ }
2135
+ return await render_response({
2136
+ options: options2,
2137
+ manifest,
2138
+ state,
2139
+ page_config: {
2140
+ ssr,
2141
+ csr
2142
+ },
2143
+ status,
2144
+ error: await handle_error_and_jsonify(event, event_state, options2, error2),
2145
+ branch,
2146
+ fetched,
2147
+ event,
2148
+ event_state,
2149
+ resolve_opts,
2150
+ data_serializer
2151
+ });
2152
+ } catch (e) {
2153
+ if (e instanceof Redirect) {
2154
+ return redirect_response(e.status, e.location);
2155
+ }
2156
+ return static_error_page(
2157
+ options2,
2158
+ get_status(e),
2159
+ (await handle_error_and_jsonify(event, event_state, options2, e)).message
2160
+ );
2161
+ }
2162
+ }
2163
+ async function handle_remote_call(event, state, options2, manifest, id) {
2164
+ return record_span({
2165
+ name: "sveltekit.remote.call",
2166
+ attributes: {},
2167
+ fn: (current2) => {
2168
+ const traced_event = merge_tracing(event, current2);
2169
+ return with_request_store(
2170
+ { event: traced_event, state },
2171
+ () => handle_remote_call_internal(traced_event, state, options2, manifest, id)
2172
+ );
2173
+ }
2174
+ });
2175
+ }
2176
+ async function handle_remote_call_internal(event, state, options2, manifest, id) {
2177
+ const [hash2, name, additional_args] = id.split("/");
2178
+ const remotes = manifest._.remotes;
2179
+ if (!remotes[hash2]) error(404);
2180
+ const module = await remotes[hash2]();
2181
+ const fn = module.default[name];
2182
+ if (!fn) error(404);
2183
+ const info = fn.__;
2184
+ const transport = options2.hooks.transport;
2185
+ event.tracing.current.setAttributes({
2186
+ "sveltekit.remote.call.type": info.type,
2187
+ "sveltekit.remote.call.name": info.name
2188
+ });
2189
+ let form_client_refreshes;
2190
+ try {
2191
+ if (info.type === "query_batch") {
2192
+ if (event.request.method !== "POST") {
2193
+ throw new SvelteKitError(
2194
+ 405,
2195
+ "Method Not Allowed",
2196
+ `\`query.batch\` functions must be invoked via POST request, not ${event.request.method}`
2197
+ );
2198
+ }
2199
+ const { payloads } = await event.request.json();
2200
+ const args = await Promise.all(
2201
+ payloads.map((payload2) => parse_remote_arg(payload2, transport))
2202
+ );
2203
+ const results = await with_request_store({ event, state }, () => info.run(args, options2));
2204
+ return json(
2205
+ /** @type {RemoteFunctionResponse} */
2206
+ {
2207
+ type: "result",
2208
+ result: stringify(results, transport)
2209
+ }
2210
+ );
2211
+ }
2212
+ if (info.type === "form") {
2213
+ if (event.request.method !== "POST") {
2214
+ throw new SvelteKitError(
2215
+ 405,
2216
+ "Method Not Allowed",
2217
+ `\`form\` functions must be invoked via POST request, not ${event.request.method}`
2218
+ );
2219
+ }
2220
+ if (!is_form_content_type(event.request)) {
2221
+ throw new SvelteKitError(
2222
+ 415,
2223
+ "Unsupported Media Type",
2224
+ `\`form\` functions expect form-encoded data — received ${event.request.headers.get(
2225
+ "content-type"
2226
+ )}`
2227
+ );
2228
+ }
2229
+ const { data: data2, meta, form_data } = await deserialize_binary_form(event.request);
2230
+ if (additional_args && !("id" in data2)) {
2231
+ data2.id = JSON.parse(decodeURIComponent(additional_args));
2232
+ }
2233
+ const fn2 = info.fn;
2234
+ const result = await with_request_store({ event, state }, () => fn2(data2, meta, form_data));
2235
+ return json(
2236
+ /** @type {RemoteFunctionResponse} */
2237
+ {
2238
+ type: "result",
2239
+ result: stringify(result, transport),
2240
+ refreshes: result.issues ? void 0 : await serialize_refreshes(meta.remote_refreshes)
2241
+ }
2242
+ );
2243
+ }
2244
+ if (info.type === "command") {
2245
+ const { payload: payload2, refreshes } = await event.request.json();
2246
+ const arg = parse_remote_arg(payload2, transport);
2247
+ const data2 = await with_request_store({ event, state }, () => fn(arg));
2248
+ return json(
2249
+ /** @type {RemoteFunctionResponse} */
2250
+ {
2251
+ type: "result",
2252
+ result: stringify(data2, transport),
2253
+ refreshes: await serialize_refreshes(refreshes)
2254
+ }
2255
+ );
2256
+ }
2257
+ const payload = info.type === "prerender" ? additional_args : (
2258
+ /** @type {string} */
2259
+ // new URL(...) necessary because we're hiding the URL from the user in the event object
2260
+ new URL(event.request.url).searchParams.get("payload")
2261
+ );
2262
+ const data = await with_request_store(
2263
+ { event, state },
2264
+ () => fn(parse_remote_arg(payload, transport))
2265
+ );
2266
+ return json(
2267
+ /** @type {RemoteFunctionResponse} */
2268
+ {
2269
+ type: "result",
2270
+ result: stringify(data, transport)
2271
+ }
2272
+ );
2273
+ } catch (error2) {
2274
+ if (error2 instanceof Redirect) {
2275
+ return json(
2276
+ /** @type {RemoteFunctionResponse} */
2277
+ {
2278
+ type: "redirect",
2279
+ location: error2.location,
2280
+ refreshes: await serialize_refreshes(form_client_refreshes)
2281
+ }
2282
+ );
2283
+ }
2284
+ const status = error2 instanceof HttpError || error2 instanceof SvelteKitError ? error2.status : 500;
2285
+ return json(
2286
+ /** @type {RemoteFunctionResponse} */
2287
+ {
2288
+ type: "error",
2289
+ error: await handle_error_and_jsonify(event, state, options2, error2),
2290
+ status
2291
+ },
2292
+ {
2293
+ // By setting a non-200 during prerendering we fail the prerender process (unless handleHttpError handles it).
2294
+ // Errors at runtime will be passed to the client and are handled there
2295
+ status: state.prerendering ? status : void 0,
2296
+ headers: {
2297
+ "cache-control": "private, no-store"
2298
+ }
2299
+ }
2300
+ );
2301
+ }
2302
+ async function serialize_refreshes(client_refreshes) {
2303
+ const refreshes = state.refreshes ?? {};
2304
+ if (client_refreshes) {
2305
+ for (const key2 of client_refreshes) {
2306
+ if (refreshes[key2] !== void 0) continue;
2307
+ const [hash3, name2, payload] = key2.split("/");
2308
+ const loader = manifest._.remotes[hash3];
2309
+ const fn2 = (await loader?.())?.default?.[name2];
2310
+ if (!fn2) error(400, "Bad Request");
2311
+ refreshes[key2] = with_request_store(
2312
+ { event, state },
2313
+ () => fn2(parse_remote_arg(payload, transport))
2314
+ );
2315
+ }
2316
+ }
2317
+ if (Object.keys(refreshes).length === 0) {
2318
+ return void 0;
2319
+ }
2320
+ return stringify(
2321
+ Object.fromEntries(
2322
+ await Promise.all(
2323
+ Object.entries(refreshes).map(async ([key2, promise]) => [key2, await promise])
2324
+ )
2325
+ ),
2326
+ transport
2327
+ );
2328
+ }
2329
+ }
2330
+ async function handle_remote_form_post(event, state, manifest, id) {
2331
+ return record_span({
2332
+ name: "sveltekit.remote.form.post",
2333
+ attributes: {},
2334
+ fn: (current2) => {
2335
+ const traced_event = merge_tracing(event, current2);
2336
+ return with_request_store(
2337
+ { event: traced_event, state },
2338
+ () => handle_remote_form_post_internal(traced_event, state, manifest, id)
2339
+ );
2340
+ }
2341
+ });
2342
+ }
2343
+ async function handle_remote_form_post_internal(event, state, manifest, id) {
2344
+ const [hash2, name, action_id] = id.split("/");
2345
+ const remotes = manifest._.remotes;
2346
+ const module = await remotes[hash2]?.();
2347
+ let form = (
2348
+ /** @type {RemoteForm<any, any>} */
2349
+ module?.default[name]
2350
+ );
2351
+ if (!form) {
2352
+ event.setHeaders({
2353
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
2354
+ // "The server must generate an Allow header field in a 405 status code response"
2355
+ allow: "GET"
2356
+ });
2357
+ return {
2358
+ type: "error",
2359
+ error: new SvelteKitError(
2360
+ 405,
2361
+ "Method Not Allowed",
2362
+ `POST method not allowed. No form actions exist for ${"this page"}`
2363
+ )
2364
+ };
2365
+ }
2366
+ if (action_id) {
2367
+ form = with_request_store({ event, state }, () => form.for(JSON.parse(action_id)));
2368
+ }
2369
+ try {
2370
+ const fn = (
2371
+ /** @type {RemoteInfo & { type: 'form' }} */
2372
+ /** @type {any} */
2373
+ form.__.fn
2374
+ );
2375
+ const { data, meta, form_data } = await deserialize_binary_form(event.request);
2376
+ if (action_id && !("id" in data)) {
2377
+ data.id = JSON.parse(decodeURIComponent(action_id));
2378
+ }
2379
+ await with_request_store({ event, state }, () => fn(data, meta, form_data));
2380
+ return {
2381
+ type: "success",
2382
+ status: 200
2383
+ };
2384
+ } catch (e) {
2385
+ const err = normalize_error(e);
2386
+ if (err instanceof Redirect) {
2387
+ return {
2388
+ type: "redirect",
2389
+ status: err.status,
2390
+ location: err.location
2391
+ };
2392
+ }
2393
+ return {
2394
+ type: "error",
2395
+ error: check_incorrect_fail_use(err)
2396
+ };
2397
+ }
2398
+ }
2399
+ function get_remote_id(url) {
2400
+ return url.pathname.startsWith(`${base}/${app_dir}/remote/`) && url.pathname.replace(`${base}/${app_dir}/remote/`, "");
2401
+ }
2402
+ function get_remote_action(url) {
2403
+ return url.searchParams.get("/remote");
2404
+ }
2405
+ const MAX_DEPTH = 10;
2406
+ async function render_page(event, event_state, page, options2, manifest, state, nodes, resolve_opts) {
2407
+ if (state.depth > MAX_DEPTH) {
2408
+ return text(`Not found: ${event.url.pathname}`, {
2409
+ status: 404
2410
+ // TODO in some cases this should be 500. not sure how to differentiate
2411
+ });
2412
+ }
2413
+ if (is_action_json_request(event)) {
2414
+ const node = await manifest._.nodes[page.leaf]();
2415
+ return handle_action_json_request(event, event_state, options2, node?.server);
2416
+ }
2417
+ try {
2418
+ const leaf_node = (
2419
+ /** @type {import('types').SSRNode} */
2420
+ nodes.page()
2421
+ );
2422
+ let status = 200;
2423
+ let action_result = void 0;
2424
+ if (is_action_request(event)) {
2425
+ const remote_id = get_remote_action(event.url);
2426
+ if (remote_id) {
2427
+ action_result = await handle_remote_form_post(event, event_state, manifest, remote_id);
2428
+ } else {
2429
+ action_result = await handle_action_request(event, event_state, leaf_node.server);
2430
+ }
2431
+ if (action_result?.type === "redirect") {
2432
+ return redirect_response(action_result.status, action_result.location);
2433
+ }
2434
+ if (action_result?.type === "error") {
2435
+ status = get_status(action_result.error);
2436
+ }
2437
+ if (action_result?.type === "failure") {
2438
+ status = action_result.status;
2439
+ }
2440
+ }
2441
+ const should_prerender = nodes.prerender();
2442
+ if (should_prerender) {
2443
+ const mod = leaf_node.server;
2444
+ if (mod?.actions) {
2445
+ throw new Error("Cannot prerender pages with actions");
2446
+ }
2447
+ } else if (state.prerendering) {
2448
+ return new Response(void 0, {
2449
+ status: 204
2450
+ });
2451
+ }
2452
+ state.prerender_default = should_prerender;
2453
+ const should_prerender_data = nodes.should_prerender_data();
2454
+ const data_pathname = add_data_suffix(event.url.pathname);
2455
+ const fetched = [];
2456
+ const ssr = nodes.ssr();
2457
+ const csr = nodes.csr();
2458
+ if (ssr === false && !(state.prerendering && should_prerender_data)) {
2459
+ if (BROWSER && action_result && !event.request.headers.has("x-sveltekit-action")) ;
2460
+ return await render_response({
2461
+ branch: [],
2462
+ fetched,
2463
+ page_config: {
2464
+ ssr: false,
2465
+ csr
2466
+ },
2467
+ status,
2468
+ error: null,
2469
+ event,
2470
+ event_state,
2471
+ options: options2,
2472
+ manifest,
2473
+ state,
2474
+ resolve_opts,
2475
+ data_serializer: server_data_serializer(event, event_state, options2)
2476
+ });
2477
+ }
2478
+ const branch = [];
2479
+ let load_error = null;
2480
+ const data_serializer = server_data_serializer(event, event_state, options2);
2481
+ const data_serializer_json = state.prerendering && should_prerender_data ? server_data_serializer_json(event, event_state, options2) : null;
2482
+ const server_promises = nodes.data.map((node, i) => {
2483
+ if (load_error) {
2484
+ throw load_error;
2485
+ }
2486
+ return Promise.resolve().then(async () => {
2487
+ try {
2488
+ if (node === leaf_node && action_result?.type === "error") {
2489
+ throw action_result.error;
2490
+ }
2491
+ const server_data = await load_server_data({
2492
+ event,
2493
+ event_state,
2494
+ state,
2495
+ node,
2496
+ parent: async () => {
2497
+ const data = {};
2498
+ for (let j = 0; j < i; j += 1) {
2499
+ const parent = await server_promises[j];
2500
+ if (parent) Object.assign(data, parent.data);
2501
+ }
2502
+ return data;
2503
+ }
2504
+ });
2505
+ if (node) {
2506
+ data_serializer.add_node(i, server_data);
2507
+ }
2508
+ data_serializer_json?.add_node(i, server_data);
2509
+ return server_data;
2510
+ } catch (e) {
2511
+ load_error = /** @type {Error} */
2512
+ e;
2513
+ throw load_error;
2514
+ }
2515
+ });
2516
+ });
2517
+ const load_promises = nodes.data.map((node, i) => {
2518
+ if (load_error) throw load_error;
2519
+ return Promise.resolve().then(async () => {
2520
+ try {
2521
+ return await load_data({
2522
+ event,
2523
+ event_state,
2524
+ fetched,
2525
+ node,
2526
+ parent: async () => {
2527
+ const data = {};
2528
+ for (let j = 0; j < i; j += 1) {
2529
+ Object.assign(data, await load_promises[j]);
2530
+ }
2531
+ return data;
2532
+ },
2533
+ resolve_opts,
2534
+ server_data_promise: server_promises[i],
2535
+ state,
2536
+ csr
2537
+ });
2538
+ } catch (e) {
2539
+ load_error = /** @type {Error} */
2540
+ e;
2541
+ throw load_error;
2542
+ }
2543
+ });
2544
+ });
2545
+ for (const p of server_promises) p.catch(() => {
2546
+ });
2547
+ for (const p of load_promises) p.catch(() => {
2548
+ });
2549
+ for (let i = 0; i < nodes.data.length; i += 1) {
2550
+ const node = nodes.data[i];
2551
+ if (node) {
2552
+ try {
2553
+ const server_data = await server_promises[i];
2554
+ const data = await load_promises[i];
2555
+ branch.push({ node, server_data, data });
2556
+ } catch (e) {
2557
+ const err = normalize_error(e);
2558
+ if (err instanceof Redirect) {
2559
+ if (state.prerendering && should_prerender_data) {
2560
+ const body2 = JSON.stringify({
2561
+ type: "redirect",
2562
+ location: err.location
2563
+ });
2564
+ state.prerendering.dependencies.set(data_pathname, {
2565
+ response: text(body2),
2566
+ body: body2
2567
+ });
2568
+ }
2569
+ return redirect_response(err.status, err.location);
2570
+ }
2571
+ const status2 = get_status(err);
2572
+ const error2 = await handle_error_and_jsonify(event, event_state, options2, err);
2573
+ while (i--) {
2574
+ if (page.errors[i]) {
2575
+ const index = (
2576
+ /** @type {number} */
2577
+ page.errors[i]
2578
+ );
2579
+ const node2 = await manifest._.nodes[index]();
2580
+ let j = i;
2581
+ while (!branch[j]) j -= 1;
2582
+ data_serializer.set_max_nodes(j + 1);
2583
+ const layouts = compact(branch.slice(0, j + 1));
2584
+ const nodes2 = new PageNodes(layouts.map((layout) => layout.node));
2585
+ return await render_response({
2586
+ event,
2587
+ event_state,
2588
+ options: options2,
2589
+ manifest,
2590
+ state,
2591
+ resolve_opts,
2592
+ page_config: {
2593
+ ssr: nodes2.ssr(),
2594
+ csr: nodes2.csr()
2595
+ },
2596
+ status: status2,
2597
+ error: error2,
2598
+ branch: layouts.concat({
2599
+ node: node2,
2600
+ data: null,
2601
+ server_data: null
2602
+ }),
2603
+ fetched,
2604
+ data_serializer
2605
+ });
2606
+ }
2607
+ }
2608
+ return static_error_page(options2, status2, error2.message);
2609
+ }
2610
+ } else {
2611
+ branch.push(null);
2612
+ }
2613
+ }
2614
+ if (state.prerendering && data_serializer_json) {
2615
+ let { data, chunks } = data_serializer_json.get_data();
2616
+ if (chunks) {
2617
+ for await (const chunk of chunks) {
2618
+ data += chunk;
2619
+ }
2620
+ }
2621
+ state.prerendering.dependencies.set(data_pathname, {
2622
+ response: text(data),
2623
+ body: data
2624
+ });
2625
+ }
2626
+ return await render_response({
2627
+ event,
2628
+ event_state,
2629
+ options: options2,
2630
+ manifest,
2631
+ state,
2632
+ resolve_opts,
2633
+ page_config: {
2634
+ csr,
2635
+ ssr
2636
+ },
2637
+ status,
2638
+ error: null,
2639
+ branch: ssr === false ? [] : compact(branch),
2640
+ action_result,
2641
+ fetched,
2642
+ data_serializer: ssr === false ? server_data_serializer(event, event_state, options2) : data_serializer
2643
+ });
2644
+ } catch (e) {
2645
+ if (e instanceof Redirect) {
2646
+ return redirect_response(e.status, e.location);
2647
+ }
2648
+ return await respond_with_error({
2649
+ event,
2650
+ event_state,
2651
+ options: options2,
2652
+ manifest,
2653
+ state,
2654
+ status: e instanceof HttpError ? e.status : 500,
2655
+ error: e,
2656
+ resolve_opts
2657
+ });
2658
+ }
2659
+ }
2660
+ function once(fn) {
2661
+ let done = false;
2662
+ let result;
2663
+ return () => {
2664
+ if (done) return result;
2665
+ done = true;
2666
+ return result = fn();
2667
+ };
2668
+ }
2669
+ async function render_data(event, event_state, route, options2, manifest, state, invalidated_data_nodes, trailing_slash) {
2670
+ if (!route.page) {
2671
+ return new Response(void 0, {
2672
+ status: 404
2673
+ });
2674
+ }
2675
+ try {
2676
+ const node_ids = [...route.page.layouts, route.page.leaf];
2677
+ const invalidated = invalidated_data_nodes ?? node_ids.map(() => true);
2678
+ let aborted = false;
2679
+ const url = new URL(event.url);
2680
+ url.pathname = normalize_path(url.pathname, trailing_slash);
2681
+ const new_event = { ...event, url };
2682
+ const functions = node_ids.map((n, i) => {
2683
+ return once(async () => {
2684
+ try {
2685
+ if (aborted) {
2686
+ return (
2687
+ /** @type {import('types').ServerDataSkippedNode} */
2688
+ {
2689
+ type: "skip"
2690
+ }
2691
+ );
2692
+ }
2693
+ const node = n == void 0 ? n : await manifest._.nodes[n]();
2694
+ return load_server_data({
2695
+ event: new_event,
2696
+ event_state,
2697
+ state,
2698
+ node,
2699
+ parent: async () => {
2700
+ const data2 = {};
2701
+ for (let j = 0; j < i; j += 1) {
2702
+ const parent = (
2703
+ /** @type {import('types').ServerDataNode | null} */
2704
+ await functions[j]()
2705
+ );
2706
+ if (parent) {
2707
+ Object.assign(data2, parent.data);
2708
+ }
2709
+ }
2710
+ return data2;
2711
+ }
2712
+ });
2713
+ } catch (e) {
2714
+ aborted = true;
2715
+ throw e;
2716
+ }
2717
+ });
2718
+ });
2719
+ const promises = functions.map(async (fn, i) => {
2720
+ if (!invalidated[i]) {
2721
+ return (
2722
+ /** @type {import('types').ServerDataSkippedNode} */
2723
+ {
2724
+ type: "skip"
2725
+ }
2726
+ );
2727
+ }
2728
+ return fn();
2729
+ });
2730
+ let length = promises.length;
2731
+ const nodes = await Promise.all(
2732
+ promises.map(
2733
+ (p, i) => p.catch(async (error2) => {
2734
+ if (error2 instanceof Redirect) {
2735
+ throw error2;
2736
+ }
2737
+ length = Math.min(length, i + 1);
2738
+ return (
2739
+ /** @type {import('types').ServerErrorNode} */
2740
+ {
2741
+ type: "error",
2742
+ error: await handle_error_and_jsonify(event, event_state, options2, error2),
2743
+ status: error2 instanceof HttpError || error2 instanceof SvelteKitError ? error2.status : void 0
2744
+ }
2745
+ );
2746
+ })
2747
+ )
2748
+ );
2749
+ const data_serializer = server_data_serializer_json(event, event_state, options2);
2750
+ for (let i = 0; i < nodes.length; i++) data_serializer.add_node(i, nodes[i]);
2751
+ const { data, chunks } = data_serializer.get_data();
2752
+ if (!chunks) {
2753
+ return json_response(data);
2754
+ }
2755
+ return new Response(
2756
+ new ReadableStream({
2757
+ async start(controller) {
2758
+ controller.enqueue(text_encoder.encode(data));
2759
+ for await (const chunk of chunks) {
2760
+ controller.enqueue(text_encoder.encode(chunk));
2761
+ }
2762
+ controller.close();
2763
+ },
2764
+ type: "bytes"
2765
+ }),
2766
+ {
2767
+ headers: {
2768
+ // we use a proprietary content type to prevent buffering.
2769
+ // the `text` prefix makes it inspectable
2770
+ "content-type": "text/sveltekit-data",
2771
+ "cache-control": "private, no-store"
2772
+ }
2773
+ }
2774
+ );
2775
+ } catch (e) {
2776
+ const error2 = normalize_error(e);
2777
+ if (error2 instanceof Redirect) {
2778
+ return redirect_json_response(error2);
2779
+ } else {
2780
+ return json_response(await handle_error_and_jsonify(event, event_state, options2, error2), 500);
2781
+ }
2782
+ }
2783
+ }
2784
+ function json_response(json2, status = 200) {
2785
+ return text(typeof json2 === "string" ? json2 : JSON.stringify(json2), {
2786
+ status,
2787
+ headers: {
2788
+ "content-type": "application/json",
2789
+ "cache-control": "private, no-store"
2790
+ }
2791
+ });
2792
+ }
2793
+ function redirect_json_response(redirect) {
2794
+ return json_response(
2795
+ /** @type {import('types').ServerRedirectNode} */
2796
+ {
2797
+ type: "redirect",
2798
+ location: redirect.location
2799
+ }
2800
+ );
2801
+ }
2802
+ const INVALID_COOKIE_CHARACTER_REGEX = /[\x00-\x1F\x7F()<>@,;:"/[\]?={} \t]/;
2803
+ function validate_options(options2) {
2804
+ if (options2?.path === void 0) {
2805
+ throw new Error("You must specify a `path` when setting, deleting or serializing cookies");
2806
+ }
2807
+ }
2808
+ function generate_cookie_key(domain, path, name) {
2809
+ return `${domain || ""}${path}?${encodeURIComponent(name)}`;
2810
+ }
2811
+ function get_cookies(request, url) {
2812
+ const header = request.headers.get("cookie") ?? "";
2813
+ const initial_cookies = parse(header, { decode: (value) => value });
2814
+ let normalized_url;
2815
+ const new_cookies = /* @__PURE__ */ new Map();
2816
+ const defaults = {
2817
+ httpOnly: true,
2818
+ sameSite: "lax",
2819
+ secure: url.hostname === "localhost" && url.protocol === "http:" ? false : true
2820
+ };
2821
+ const cookies = {
2822
+ // The JSDoc param annotations appearing below for get, set and delete
2823
+ // are necessary to expose the `cookie` library types to
2824
+ // typescript users. `@type {import('@sveltejs/kit').Cookies}` above is not
2825
+ // sufficient to do so.
2826
+ /**
2827
+ * @param {string} name
2828
+ * @param {import('cookie').CookieParseOptions} [opts]
2829
+ */
2830
+ get(name, opts) {
2831
+ const best_match = Array.from(new_cookies.values()).filter((c) => {
2832
+ return c.name === name && domain_matches(url.hostname, c.options.domain) && path_matches(url.pathname, c.options.path);
2833
+ }).sort((a, b) => b.options.path.length - a.options.path.length)[0];
2834
+ if (best_match) {
2835
+ return best_match.options.maxAge === 0 ? void 0 : best_match.value;
2836
+ }
2837
+ const req_cookies = parse(header, { decode: opts?.decode });
2838
+ const cookie = req_cookies[name];
2839
+ return cookie;
2840
+ },
2841
+ /**
2842
+ * @param {import('cookie').CookieParseOptions} [opts]
2843
+ */
2844
+ getAll(opts) {
2845
+ const cookies2 = parse(header, { decode: opts?.decode });
2846
+ const lookup = /* @__PURE__ */ new Map();
2847
+ for (const c of new_cookies.values()) {
2848
+ if (domain_matches(url.hostname, c.options.domain) && path_matches(url.pathname, c.options.path)) {
2849
+ const existing = lookup.get(c.name);
2850
+ if (!existing || c.options.path.length > existing.options.path.length) {
2851
+ lookup.set(c.name, c);
2852
+ }
2853
+ }
2854
+ }
2855
+ for (const c of lookup.values()) {
2856
+ cookies2[c.name] = c.value;
2857
+ }
2858
+ return Object.entries(cookies2).map(([name, value]) => ({ name, value }));
2859
+ },
2860
+ /**
2861
+ * @param {string} name
2862
+ * @param {string} value
2863
+ * @param {import('./page/types.js').Cookie['options']} options
2864
+ */
2865
+ set(name, value, options2) {
2866
+ const illegal_characters = name.match(INVALID_COOKIE_CHARACTER_REGEX);
2867
+ if (illegal_characters) {
2868
+ console.warn(
2869
+ `The cookie name "${name}" will be invalid in SvelteKit 3.0 as it contains ${illegal_characters.join(
2870
+ " and "
2871
+ )}. See RFC 2616 for more details https://datatracker.ietf.org/doc/html/rfc2616#section-2.2`
2872
+ );
2873
+ }
2874
+ validate_options(options2);
2875
+ set_internal(name, value, { ...defaults, ...options2 });
2876
+ },
2877
+ /**
2878
+ * @param {string} name
2879
+ * @param {import('./page/types.js').Cookie['options']} options
2880
+ */
2881
+ delete(name, options2) {
2882
+ validate_options(options2);
2883
+ cookies.set(name, "", { ...options2, maxAge: 0 });
2884
+ },
2885
+ /**
2886
+ * @param {string} name
2887
+ * @param {string} value
2888
+ * @param {import('./page/types.js').Cookie['options']} options
2889
+ */
2890
+ serialize(name, value, options2) {
2891
+ validate_options(options2);
2892
+ let path = options2.path;
2893
+ if (!options2.domain || options2.domain === url.hostname) {
2894
+ if (!normalized_url) {
2895
+ throw new Error("Cannot serialize cookies until after the route is determined");
2896
+ }
2897
+ path = resolve(normalized_url, path);
2898
+ }
2899
+ return serialize(name, value, { ...defaults, ...options2, path });
2900
+ }
2901
+ };
2902
+ function get_cookie_header(destination, header2) {
2903
+ const combined_cookies = {
2904
+ // cookies sent by the user agent have lowest precedence
2905
+ ...initial_cookies
2906
+ };
2907
+ for (const cookie of new_cookies.values()) {
2908
+ if (!domain_matches(destination.hostname, cookie.options.domain)) continue;
2909
+ if (!path_matches(destination.pathname, cookie.options.path)) continue;
2910
+ const encoder = cookie.options.encode || encodeURIComponent;
2911
+ combined_cookies[cookie.name] = encoder(cookie.value);
2912
+ }
2913
+ if (header2) {
2914
+ const parsed = parse(header2, { decode: (value) => value });
2915
+ for (const name in parsed) {
2916
+ combined_cookies[name] = parsed[name];
2917
+ }
2918
+ }
2919
+ return Object.entries(combined_cookies).map(([name, value]) => `${name}=${value}`).join("; ");
2920
+ }
2921
+ const internal_queue = [];
2922
+ function set_internal(name, value, options2) {
2923
+ if (!normalized_url) {
2924
+ internal_queue.push(() => set_internal(name, value, options2));
2925
+ return;
2926
+ }
2927
+ let path = options2.path;
2928
+ if (!options2.domain || options2.domain === url.hostname) {
2929
+ path = resolve(normalized_url, path);
2930
+ }
2931
+ const cookie_key = generate_cookie_key(options2.domain, path, name);
2932
+ const cookie = { name, value, options: { ...options2, path } };
2933
+ new_cookies.set(cookie_key, cookie);
2934
+ }
2935
+ function set_trailing_slash(trailing_slash) {
2936
+ normalized_url = normalize_path(url.pathname, trailing_slash);
2937
+ internal_queue.forEach((fn) => fn());
2938
+ }
2939
+ return { cookies, new_cookies, get_cookie_header, set_internal, set_trailing_slash };
2940
+ }
2941
+ function domain_matches(hostname, constraint) {
2942
+ if (!constraint) return true;
2943
+ const normalized = constraint[0] === "." ? constraint.slice(1) : constraint;
2944
+ if (hostname === normalized) return true;
2945
+ return hostname.endsWith("." + normalized);
2946
+ }
2947
+ function path_matches(path, constraint) {
2948
+ if (!constraint) return true;
2949
+ const normalized = constraint.endsWith("/") ? constraint.slice(0, -1) : constraint;
2950
+ if (path === normalized) return true;
2951
+ return path.startsWith(normalized + "/");
2952
+ }
2953
+ function add_cookies_to_headers(headers2, cookies) {
2954
+ for (const new_cookie of cookies) {
2955
+ const { name, value, options: options2 } = new_cookie;
2956
+ headers2.append("set-cookie", serialize(name, value, options2));
2957
+ if (options2.path.endsWith(".html")) {
2958
+ const path = add_data_suffix(options2.path);
2959
+ headers2.append("set-cookie", serialize(name, value, { ...options2, path }));
2960
+ }
2961
+ }
2962
+ }
2963
+ function create_fetch({ event, options: options2, manifest, state, get_cookie_header, set_internal }) {
2964
+ const server_fetch = async (info, init2) => {
2965
+ const original_request = normalize_fetch_input(info, init2, event.url);
2966
+ let mode = (info instanceof Request ? info.mode : init2?.mode) ?? "cors";
2967
+ let credentials = (info instanceof Request ? info.credentials : init2?.credentials) ?? "same-origin";
2968
+ return options2.hooks.handleFetch({
2969
+ event,
2970
+ request: original_request,
2971
+ fetch: async (info2, init3) => {
2972
+ const request = normalize_fetch_input(info2, init3, event.url);
2973
+ const url = new URL(request.url);
2974
+ if (!request.headers.has("origin")) {
2975
+ request.headers.set("origin", event.url.origin);
2976
+ }
2977
+ if (info2 !== original_request) {
2978
+ mode = (info2 instanceof Request ? info2.mode : init3?.mode) ?? "cors";
2979
+ credentials = (info2 instanceof Request ? info2.credentials : init3?.credentials) ?? "same-origin";
2980
+ }
2981
+ if ((request.method === "GET" || request.method === "HEAD") && (mode === "no-cors" && url.origin !== event.url.origin || url.origin === event.url.origin)) {
2982
+ request.headers.delete("origin");
2983
+ }
2984
+ const decoded = decodeURIComponent(url.pathname);
2985
+ if (url.origin !== event.url.origin || base && decoded !== base && !decoded.startsWith(`${base}/`)) {
2986
+ if (`.${url.hostname}`.endsWith(`.${event.url.hostname}`) && credentials !== "omit") {
2987
+ const cookie = get_cookie_header(url, request.headers.get("cookie"));
2988
+ if (cookie) request.headers.set("cookie", cookie);
2989
+ }
2990
+ return fetch(request);
2991
+ }
2992
+ const prefix = assets || base;
2993
+ const filename = (decoded.startsWith(prefix) ? decoded.slice(prefix.length) : decoded).slice(1);
2994
+ const filename_html = `${filename}/index.html`;
2995
+ const is_asset = manifest.assets.has(filename) || filename in manifest._.server_assets;
2996
+ const is_asset_html = manifest.assets.has(filename_html) || filename_html in manifest._.server_assets;
2997
+ if (is_asset || is_asset_html) {
2998
+ const file = is_asset ? filename : filename_html;
2999
+ if (state.read) {
3000
+ const type = is_asset ? manifest.mimeTypes[filename.slice(filename.lastIndexOf("."))] : "text/html";
3001
+ return new Response(state.read(file), {
3002
+ headers: type ? { "content-type": type } : {}
3003
+ });
3004
+ } else if (read_implementation && file in manifest._.server_assets) {
3005
+ const length = manifest._.server_assets[file];
3006
+ const type = manifest.mimeTypes[file.slice(file.lastIndexOf("."))];
3007
+ return new Response(read_implementation(file), {
3008
+ headers: {
3009
+ "Content-Length": "" + length,
3010
+ "Content-Type": type
3011
+ }
3012
+ });
3013
+ }
3014
+ return await fetch(request);
3015
+ }
3016
+ if (has_prerendered_path(manifest, base + decoded)) {
3017
+ return await fetch(request);
3018
+ }
3019
+ if (credentials !== "omit") {
3020
+ const cookie = get_cookie_header(url, request.headers.get("cookie"));
3021
+ if (cookie) {
3022
+ request.headers.set("cookie", cookie);
3023
+ }
3024
+ const authorization = event.request.headers.get("authorization");
3025
+ if (authorization && !request.headers.has("authorization")) {
3026
+ request.headers.set("authorization", authorization);
3027
+ }
3028
+ }
3029
+ if (!request.headers.has("accept")) {
3030
+ request.headers.set("accept", "*/*");
3031
+ }
3032
+ if (!request.headers.has("accept-language")) {
3033
+ request.headers.set(
3034
+ "accept-language",
3035
+ /** @type {string} */
3036
+ event.request.headers.get("accept-language")
3037
+ );
3038
+ }
3039
+ const response = await internal_fetch(request, options2, manifest, state);
3040
+ const set_cookie = response.headers.get("set-cookie");
3041
+ if (set_cookie) {
3042
+ for (const str of set_cookie_parser.splitCookiesString(set_cookie)) {
3043
+ const { name, value, ...options3 } = set_cookie_parser.parseString(str, {
3044
+ decodeValues: false
3045
+ });
3046
+ const path = options3.path ?? (url.pathname.split("/").slice(0, -1).join("/") || "/");
3047
+ set_internal(name, value, {
3048
+ path,
3049
+ encode: (value2) => value2,
3050
+ .../** @type {import('cookie').CookieSerializeOptions} */
3051
+ options3
3052
+ });
3053
+ }
3054
+ }
3055
+ return response;
3056
+ }
3057
+ });
3058
+ };
3059
+ return (input, init2) => {
3060
+ const response = server_fetch(input, init2);
3061
+ response.catch(() => {
3062
+ });
3063
+ return response;
3064
+ };
3065
+ }
3066
+ function normalize_fetch_input(info, init2, url) {
3067
+ if (info instanceof Request) {
3068
+ return info;
3069
+ }
3070
+ return new Request(typeof info === "string" ? new URL(info, url) : info, init2);
3071
+ }
3072
+ async function internal_fetch(request, options2, manifest, state) {
3073
+ if (request.signal) {
3074
+ if (request.signal.aborted) {
3075
+ throw new DOMException("The operation was aborted.", "AbortError");
3076
+ }
3077
+ let remove_abort_listener = () => {
3078
+ };
3079
+ const abort_promise = new Promise((_, reject) => {
3080
+ const on_abort = () => {
3081
+ reject(new DOMException("The operation was aborted.", "AbortError"));
3082
+ };
3083
+ request.signal.addEventListener("abort", on_abort, { once: true });
3084
+ remove_abort_listener = () => request.signal.removeEventListener("abort", on_abort);
3085
+ });
3086
+ const result = await Promise.race([
3087
+ respond(request, options2, manifest, {
3088
+ ...state,
3089
+ depth: state.depth + 1
3090
+ }),
3091
+ abort_promise
3092
+ ]);
3093
+ remove_abort_listener();
3094
+ return result;
3095
+ } else {
3096
+ return await respond(request, options2, manifest, {
3097
+ ...state,
3098
+ depth: state.depth + 1
3099
+ });
3100
+ }
3101
+ }
3102
+ let body;
3103
+ let etag;
3104
+ let headers;
3105
+ function get_public_env(request) {
3106
+ body ??= `export const env=${JSON.stringify(public_env)}`;
3107
+ etag ??= `W/${Date.now()}`;
3108
+ headers ??= new Headers({
3109
+ "content-type": "application/javascript; charset=utf-8",
3110
+ etag
3111
+ });
3112
+ if (request.headers.get("if-none-match") === etag) {
3113
+ return new Response(void 0, { status: 304, headers });
3114
+ }
3115
+ return new Response(body, { headers });
3116
+ }
3117
+ const default_transform = ({ html }) => html;
3118
+ const default_filter = () => false;
3119
+ const default_preload = ({ type }) => type === "js" || type === "css";
3120
+ const page_methods = /* @__PURE__ */ new Set(["GET", "HEAD", "POST"]);
3121
+ const allowed_page_methods = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
3122
+ let warned_on_devtools_json_request = false;
3123
+ const respond = propagate_context(internal_respond);
3124
+ async function internal_respond(request, options2, manifest, state) {
3125
+ const url = new URL(request.url);
3126
+ const is_route_resolution_request = has_resolution_suffix(url.pathname);
3127
+ const is_data_request = has_data_suffix(url.pathname);
3128
+ const remote_id = get_remote_id(url);
3129
+ {
3130
+ const request_origin = request.headers.get("origin");
3131
+ if (remote_id) {
3132
+ if (request.method !== "GET" && request_origin !== url.origin) {
3133
+ const message = "Cross-site remote requests are forbidden";
3134
+ return json({ message }, { status: 403 });
3135
+ }
3136
+ } else if (options2.csrf_check_origin) {
3137
+ const forbidden = is_form_content_type(request) && (request.method === "POST" || request.method === "PUT" || request.method === "PATCH" || request.method === "DELETE") && request_origin !== url.origin && (!request_origin || !options2.csrf_trusted_origins.includes(request_origin));
3138
+ if (forbidden) {
3139
+ const message = `Cross-site ${request.method} form submissions are forbidden`;
3140
+ const opts = { status: 403 };
3141
+ if (request.headers.get("accept") === "application/json") {
3142
+ return json({ message }, opts);
3143
+ }
3144
+ return text(message, opts);
3145
+ }
3146
+ }
3147
+ }
3148
+ if (options2.hash_routing && url.pathname !== base + "/" && url.pathname !== "/[fallback]") {
3149
+ return text("Not found", { status: 404 });
3150
+ }
3151
+ let invalidated_data_nodes;
3152
+ if (is_route_resolution_request) {
3153
+ url.pathname = strip_resolution_suffix(url.pathname);
3154
+ } else if (is_data_request) {
3155
+ url.pathname = strip_data_suffix(url.pathname) + (url.searchParams.get(TRAILING_SLASH_PARAM) === "1" ? "/" : "") || "/";
3156
+ url.searchParams.delete(TRAILING_SLASH_PARAM);
3157
+ invalidated_data_nodes = url.searchParams.get(INVALIDATED_PARAM)?.split("").map((node) => node === "1");
3158
+ url.searchParams.delete(INVALIDATED_PARAM);
3159
+ } else if (remote_id) {
3160
+ url.pathname = request.headers.get("x-sveltekit-pathname") ?? base;
3161
+ url.search = request.headers.get("x-sveltekit-search") ?? "";
3162
+ }
3163
+ const headers2 = {};
3164
+ const { cookies, new_cookies, get_cookie_header, set_internal, set_trailing_slash } = get_cookies(
3165
+ request,
3166
+ url
3167
+ );
3168
+ const event_state = {
3169
+ prerendering: state.prerendering,
3170
+ transport: options2.hooks.transport,
3171
+ handleValidationError: options2.hooks.handleValidationError,
3172
+ tracing: {
3173
+ record_span
3174
+ },
3175
+ is_in_remote_function: false
3176
+ };
3177
+ const event = {
3178
+ cookies,
3179
+ // @ts-expect-error `fetch` needs to be created after the `event` itself
3180
+ fetch: null,
3181
+ getClientAddress: state.getClientAddress || (() => {
3182
+ throw new Error(
3183
+ `${"@sveltejs/adapter-static"} does not specify getClientAddress. Please raise an issue`
3184
+ );
3185
+ }),
3186
+ locals: {},
3187
+ params: {},
3188
+ platform: state.platform,
3189
+ request,
3190
+ route: { id: null },
3191
+ setHeaders: (new_headers) => {
3192
+ for (const key2 in new_headers) {
3193
+ const lower = key2.toLowerCase();
3194
+ const value = new_headers[key2];
3195
+ if (lower === "set-cookie") {
3196
+ throw new Error(
3197
+ "Use `event.cookies.set(name, value, options)` instead of `event.setHeaders` to set cookies"
3198
+ );
3199
+ } else if (lower in headers2) {
3200
+ if (lower === "server-timing") {
3201
+ headers2[lower] += ", " + value;
3202
+ } else {
3203
+ throw new Error(`"${key2}" header is already set`);
3204
+ }
3205
+ } else {
3206
+ headers2[lower] = value;
3207
+ if (state.prerendering && lower === "cache-control") {
3208
+ state.prerendering.cache = /** @type {string} */
3209
+ value;
3210
+ }
3211
+ }
3212
+ }
3213
+ },
3214
+ url,
3215
+ isDataRequest: is_data_request,
3216
+ isSubRequest: state.depth > 0,
3217
+ isRemoteRequest: !!remote_id
3218
+ };
3219
+ event.fetch = create_fetch({
3220
+ event,
3221
+ options: options2,
3222
+ manifest,
3223
+ state,
3224
+ get_cookie_header,
3225
+ set_internal
3226
+ });
3227
+ if (state.emulator?.platform) {
3228
+ event.platform = await state.emulator.platform({
3229
+ config: {},
3230
+ prerender: !!state.prerendering?.fallback
3231
+ });
3232
+ }
3233
+ let resolved_path = url.pathname;
3234
+ if (!remote_id) {
3235
+ const prerendering_reroute_state = state.prerendering?.inside_reroute;
3236
+ try {
3237
+ if (state.prerendering) state.prerendering.inside_reroute = true;
3238
+ resolved_path = await options2.hooks.reroute({ url: new URL(url), fetch: event.fetch }) ?? url.pathname;
3239
+ } catch {
3240
+ return text("Internal Server Error", {
3241
+ status: 500
3242
+ });
3243
+ } finally {
3244
+ if (state.prerendering) state.prerendering.inside_reroute = prerendering_reroute_state;
3245
+ }
3246
+ }
3247
+ try {
3248
+ resolved_path = decode_pathname(resolved_path);
3249
+ } catch {
3250
+ return text("Malformed URI", { status: 400 });
3251
+ }
3252
+ if (
3253
+ // the resolved path has been decoded so it should be compared to the decoded url pathname
3254
+ resolved_path !== decode_pathname(url.pathname) && !state.prerendering?.fallback && has_prerendered_path(manifest, resolved_path)
3255
+ ) {
3256
+ const url2 = new URL(request.url);
3257
+ url2.pathname = is_data_request ? add_data_suffix(resolved_path) : is_route_resolution_request ? add_resolution_suffix(resolved_path) : resolved_path;
3258
+ try {
3259
+ const response = await fetch(url2, request);
3260
+ const headers22 = new Headers(response.headers);
3261
+ if (headers22.has("content-encoding")) {
3262
+ headers22.delete("content-encoding");
3263
+ headers22.delete("content-length");
3264
+ }
3265
+ return new Response(response.body, {
3266
+ headers: headers22,
3267
+ status: response.status,
3268
+ statusText: response.statusText
3269
+ });
3270
+ } catch (error2) {
3271
+ return await handle_fatal_error(event, event_state, options2, error2);
3272
+ }
3273
+ }
3274
+ let route = null;
3275
+ if (base && !state.prerendering?.fallback) {
3276
+ if (!resolved_path.startsWith(base)) {
3277
+ return text("Not found", { status: 404 });
3278
+ }
3279
+ resolved_path = resolved_path.slice(base.length) || "/";
3280
+ }
3281
+ if (is_route_resolution_request) {
3282
+ return resolve_route(resolved_path, new URL(request.url), manifest);
3283
+ }
3284
+ if (resolved_path === `/${app_dir}/env.js`) {
3285
+ return get_public_env(request);
3286
+ }
3287
+ if (!remote_id && resolved_path.startsWith(`/${app_dir}`)) {
3288
+ const headers22 = new Headers();
3289
+ headers22.set("cache-control", "public, max-age=0, must-revalidate");
3290
+ return text("Not found", { status: 404, headers: headers22 });
3291
+ }
3292
+ if (!state.prerendering?.fallback) {
3293
+ const matchers = await manifest._.matchers();
3294
+ for (const candidate of manifest._.routes) {
3295
+ const match = candidate.pattern.exec(resolved_path);
3296
+ if (!match) continue;
3297
+ const matched = exec(match, candidate.params, matchers);
3298
+ if (matched) {
3299
+ route = candidate;
3300
+ event.route = { id: route.id };
3301
+ event.params = decode_params(matched);
3302
+ break;
3303
+ }
3304
+ }
3305
+ }
3306
+ let resolve_opts = {
3307
+ transformPageChunk: default_transform,
3308
+ filterSerializedResponseHeaders: default_filter,
3309
+ preload: default_preload
3310
+ };
3311
+ let trailing_slash = "never";
3312
+ try {
3313
+ const page_nodes = route?.page ? new PageNodes(await load_page_nodes(route.page, manifest)) : void 0;
3314
+ if (route && !remote_id) {
3315
+ if (url.pathname === base || url.pathname === base + "/") {
3316
+ trailing_slash = "always";
3317
+ } else if (page_nodes) {
3318
+ if (BROWSER) ;
3319
+ trailing_slash = page_nodes.trailing_slash();
3320
+ } else if (route.endpoint) {
3321
+ const node = await route.endpoint();
3322
+ trailing_slash = node.trailingSlash ?? "never";
3323
+ if (BROWSER) ;
3324
+ }
3325
+ if (!is_data_request) {
3326
+ const normalized = normalize_path(url.pathname, trailing_slash);
3327
+ if (normalized !== url.pathname && !state.prerendering?.fallback) {
3328
+ return new Response(void 0, {
3329
+ status: 308,
3330
+ headers: {
3331
+ "x-sveltekit-normalize": "1",
3332
+ location: (
3333
+ // ensure paths starting with '//' are not treated as protocol-relative
3334
+ (normalized.startsWith("//") ? url.origin + normalized : normalized) + (url.search === "?" ? "" : url.search)
3335
+ )
3336
+ }
3337
+ });
3338
+ }
3339
+ }
3340
+ if (state.before_handle || state.emulator?.platform) {
3341
+ let config = {};
3342
+ let prerender = false;
3343
+ if (route.endpoint) {
3344
+ const node = await route.endpoint();
3345
+ config = node.config ?? config;
3346
+ prerender = node.prerender ?? prerender;
3347
+ } else if (page_nodes) {
3348
+ config = page_nodes.get_config() ?? config;
3349
+ prerender = page_nodes.prerender();
3350
+ }
3351
+ if (state.before_handle) {
3352
+ state.before_handle(event, config, prerender);
3353
+ }
3354
+ if (state.emulator?.platform) {
3355
+ event.platform = await state.emulator.platform({ config, prerender });
3356
+ }
3357
+ }
3358
+ }
3359
+ set_trailing_slash(trailing_slash);
3360
+ if (state.prerendering && !state.prerendering.fallback && !state.prerendering.inside_reroute) {
3361
+ disable_search(url);
3362
+ }
3363
+ const response = await record_span({
3364
+ name: "sveltekit.handle.root",
3365
+ attributes: {
3366
+ "http.route": event.route.id || "unknown",
3367
+ "http.method": event.request.method,
3368
+ "http.url": event.url.href,
3369
+ "sveltekit.is_data_request": is_data_request,
3370
+ "sveltekit.is_sub_request": event.isSubRequest
3371
+ },
3372
+ fn: async (root_span) => {
3373
+ const traced_event = {
3374
+ ...event,
3375
+ tracing: {
3376
+ enabled: false,
3377
+ root: root_span,
3378
+ current: root_span
3379
+ }
3380
+ };
3381
+ return await with_request_store(
3382
+ { event: traced_event, state: event_state },
3383
+ () => options2.hooks.handle({
3384
+ event: traced_event,
3385
+ resolve: (event2, opts) => {
3386
+ return record_span({
3387
+ name: "sveltekit.resolve",
3388
+ attributes: {
3389
+ "http.route": event2.route.id || "unknown"
3390
+ },
3391
+ fn: (resolve_span) => {
3392
+ return with_request_store(
3393
+ null,
3394
+ () => resolve2(merge_tracing(event2, resolve_span), page_nodes, opts).then(
3395
+ (response2) => {
3396
+ for (const key2 in headers2) {
3397
+ const value = headers2[key2];
3398
+ response2.headers.set(
3399
+ key2,
3400
+ /** @type {string} */
3401
+ value
3402
+ );
3403
+ }
3404
+ add_cookies_to_headers(response2.headers, new_cookies.values());
3405
+ if (state.prerendering && event2.route.id !== null) {
3406
+ response2.headers.set("x-sveltekit-routeid", encodeURI(event2.route.id));
3407
+ }
3408
+ resolve_span.setAttributes({
3409
+ "http.response.status_code": response2.status,
3410
+ "http.response.body.size": response2.headers.get("content-length") || "unknown"
3411
+ });
3412
+ return response2;
3413
+ }
3414
+ )
3415
+ );
3416
+ }
3417
+ });
3418
+ }
3419
+ })
3420
+ );
3421
+ }
3422
+ });
3423
+ if (response.status === 200 && response.headers.has("etag")) {
3424
+ let if_none_match_value = request.headers.get("if-none-match");
3425
+ if (if_none_match_value?.startsWith('W/"')) {
3426
+ if_none_match_value = if_none_match_value.substring(2);
3427
+ }
3428
+ const etag2 = (
3429
+ /** @type {string} */
3430
+ response.headers.get("etag")
3431
+ );
3432
+ if (if_none_match_value === etag2) {
3433
+ const headers22 = new Headers({ etag: etag2 });
3434
+ for (const key2 of [
3435
+ "cache-control",
3436
+ "content-location",
3437
+ "date",
3438
+ "expires",
3439
+ "vary",
3440
+ "set-cookie"
3441
+ ]) {
3442
+ const value = response.headers.get(key2);
3443
+ if (value) headers22.set(key2, value);
3444
+ }
3445
+ return new Response(void 0, {
3446
+ status: 304,
3447
+ headers: headers22
3448
+ });
3449
+ }
3450
+ }
3451
+ if (is_data_request && response.status >= 300 && response.status <= 308) {
3452
+ const location = response.headers.get("location");
3453
+ if (location) {
3454
+ return redirect_json_response(new Redirect(
3455
+ /** @type {any} */
3456
+ response.status,
3457
+ location
3458
+ ));
3459
+ }
3460
+ }
3461
+ return response;
3462
+ } catch (e) {
3463
+ if (e instanceof Redirect) {
3464
+ const response = is_data_request || remote_id ? redirect_json_response(e) : route?.page && is_action_json_request(event) ? action_json_redirect(e) : redirect_response(e.status, e.location);
3465
+ add_cookies_to_headers(response.headers, new_cookies.values());
3466
+ return response;
3467
+ }
3468
+ return await handle_fatal_error(event, event_state, options2, e);
3469
+ }
3470
+ async function resolve2(event2, page_nodes, opts) {
3471
+ try {
3472
+ if (opts) {
3473
+ resolve_opts = {
3474
+ transformPageChunk: opts.transformPageChunk || default_transform,
3475
+ filterSerializedResponseHeaders: opts.filterSerializedResponseHeaders || default_filter,
3476
+ preload: opts.preload || default_preload
3477
+ };
3478
+ }
3479
+ if (options2.hash_routing || state.prerendering?.fallback) {
3480
+ return await render_response({
3481
+ event: event2,
3482
+ event_state,
3483
+ options: options2,
3484
+ manifest,
3485
+ state,
3486
+ page_config: { ssr: false, csr: true },
3487
+ status: 200,
3488
+ error: null,
3489
+ branch: [],
3490
+ fetched: [],
3491
+ resolve_opts,
3492
+ data_serializer: server_data_serializer(event2, event_state, options2)
3493
+ });
3494
+ }
3495
+ if (remote_id) {
3496
+ return await handle_remote_call(event2, event_state, options2, manifest, remote_id);
3497
+ }
3498
+ if (route) {
3499
+ const method = (
3500
+ /** @type {import('types').HttpMethod} */
3501
+ event2.request.method
3502
+ );
3503
+ let response2;
3504
+ if (is_data_request) {
3505
+ response2 = await render_data(
3506
+ event2,
3507
+ event_state,
3508
+ route,
3509
+ options2,
3510
+ manifest,
3511
+ state,
3512
+ invalidated_data_nodes,
3513
+ trailing_slash
3514
+ );
3515
+ } else if (route.endpoint && (!route.page || is_endpoint_request(event2))) {
3516
+ response2 = await render_endpoint(event2, event_state, await route.endpoint(), state);
3517
+ } else if (route.page) {
3518
+ if (!page_nodes) {
3519
+ throw new Error("page_nodes not found. This should never happen");
3520
+ } else if (page_methods.has(method)) {
3521
+ response2 = await render_page(
3522
+ event2,
3523
+ event_state,
3524
+ route.page,
3525
+ options2,
3526
+ manifest,
3527
+ state,
3528
+ page_nodes,
3529
+ resolve_opts
3530
+ );
3531
+ } else {
3532
+ const allowed_methods = new Set(allowed_page_methods);
3533
+ const node = await manifest._.nodes[route.page.leaf]();
3534
+ if (node?.server?.actions) {
3535
+ allowed_methods.add("POST");
3536
+ }
3537
+ if (method === "OPTIONS") {
3538
+ response2 = new Response(null, {
3539
+ status: 204,
3540
+ headers: {
3541
+ allow: Array.from(allowed_methods.values()).join(", ")
3542
+ }
3543
+ });
3544
+ } else {
3545
+ const mod = [...allowed_methods].reduce(
3546
+ (acc, curr) => {
3547
+ acc[curr] = true;
3548
+ return acc;
3549
+ },
3550
+ /** @type {Record<string, any>} */
3551
+ {}
3552
+ );
3553
+ response2 = method_not_allowed(mod, method);
3554
+ }
3555
+ }
3556
+ } else {
3557
+ throw new Error("Route is neither page nor endpoint. This should never happen");
3558
+ }
3559
+ if (request.method === "GET" && route.page && route.endpoint) {
3560
+ const vary = response2.headers.get("vary")?.split(",")?.map((v) => v.trim().toLowerCase());
3561
+ if (!(vary?.includes("accept") || vary?.includes("*"))) {
3562
+ response2 = new Response(response2.body, {
3563
+ status: response2.status,
3564
+ statusText: response2.statusText,
3565
+ headers: new Headers(response2.headers)
3566
+ });
3567
+ response2.headers.append("Vary", "Accept");
3568
+ }
3569
+ }
3570
+ return response2;
3571
+ }
3572
+ if (state.error && event2.isSubRequest) {
3573
+ const headers22 = new Headers(request.headers);
3574
+ headers22.set("x-sveltekit-error", "true");
3575
+ return await fetch(request, { headers: headers22 });
3576
+ }
3577
+ if (state.error) {
3578
+ return text("Internal Server Error", {
3579
+ status: 500
3580
+ });
3581
+ }
3582
+ if (state.depth === 0) {
3583
+ if (BROWSER && event2.url.pathname === "/.well-known/appspecific/com.chrome.devtools.json") ;
3584
+ return await respond_with_error({
3585
+ event: event2,
3586
+ event_state,
3587
+ options: options2,
3588
+ manifest,
3589
+ state,
3590
+ status: 404,
3591
+ error: new SvelteKitError(404, "Not Found", `Not found: ${event2.url.pathname}`),
3592
+ resolve_opts
3593
+ });
3594
+ }
3595
+ if (state.prerendering) {
3596
+ return text("not found", { status: 404 });
3597
+ }
3598
+ const response = await fetch(request);
3599
+ return new Response(response.body, response);
3600
+ } catch (e) {
3601
+ return await handle_fatal_error(event2, event_state, options2, e);
3602
+ } finally {
3603
+ event2.cookies.set = () => {
3604
+ throw new Error("Cannot use `cookies.set(...)` after the response has been generated");
3605
+ };
3606
+ event2.setHeaders = () => {
3607
+ throw new Error("Cannot use `setHeaders(...)` after the response has been generated");
3608
+ };
3609
+ }
3610
+ }
3611
+ }
3612
+ function load_page_nodes(page, manifest) {
3613
+ return Promise.all([
3614
+ // we use == here rather than === because [undefined] serializes as "[null]"
3615
+ ...page.layouts.map((n) => n == void 0 ? n : manifest._.nodes[n]()),
3616
+ manifest._.nodes[page.leaf]()
3617
+ ]);
3618
+ }
3619
+ function propagate_context(fn) {
3620
+ return async (req, ...rest) => {
3621
+ {
3622
+ return fn(req, ...rest);
3623
+ }
3624
+ };
3625
+ }
3626
+ function filter_env(env, allowed, disallowed) {
3627
+ return Object.fromEntries(
3628
+ Object.entries(env).filter(
3629
+ ([k]) => k.startsWith(allowed) && (disallowed === "" || !k.startsWith(disallowed))
3630
+ )
3631
+ );
3632
+ }
3633
+ function set_app(value) {
3634
+ }
3635
+ let init_promise;
3636
+ let current = null;
3637
+ class Server {
3638
+ /** @type {import('types').SSROptions} */
3639
+ #options;
3640
+ /** @type {import('@sveltejs/kit').SSRManifest} */
3641
+ #manifest;
3642
+ /** @param {import('@sveltejs/kit').SSRManifest} manifest */
3643
+ constructor(manifest) {
3644
+ this.#options = options;
3645
+ this.#manifest = manifest;
3646
+ if (IN_WEBCONTAINER) {
3647
+ const respond2 = this.respond.bind(this);
3648
+ this.respond = async (...args) => {
3649
+ const { promise, resolve: resolve2 } = (
3650
+ /** @type {PromiseWithResolvers<void>} */
3651
+ with_resolvers()
3652
+ );
3653
+ const previous = current;
3654
+ current = promise;
3655
+ await previous;
3656
+ return respond2(...args).finally(resolve2);
3657
+ };
3658
+ }
3659
+ }
3660
+ /**
3661
+ * @param {import('@sveltejs/kit').ServerInitOptions} opts
3662
+ */
3663
+ async init({ env, read }) {
3664
+ const { env_public_prefix, env_private_prefix } = this.#options;
3665
+ set_private_env(filter_env(env, env_private_prefix, env_public_prefix));
3666
+ set_public_env(filter_env(env, env_public_prefix, env_private_prefix));
3667
+ if (read) {
3668
+ const wrapped_read = (file) => {
3669
+ const result = read(file);
3670
+ if (result instanceof ReadableStream) {
3671
+ return result;
3672
+ } else {
3673
+ return new ReadableStream({
3674
+ async start(controller) {
3675
+ try {
3676
+ const stream = await Promise.resolve(result);
3677
+ if (!stream) {
3678
+ controller.close();
3679
+ return;
3680
+ }
3681
+ const reader = stream.getReader();
3682
+ while (true) {
3683
+ const { done, value } = await reader.read();
3684
+ if (done) break;
3685
+ controller.enqueue(value);
3686
+ }
3687
+ controller.close();
3688
+ } catch (error2) {
3689
+ controller.error(error2);
3690
+ }
3691
+ }
3692
+ });
3693
+ }
3694
+ };
3695
+ set_read_implementation(wrapped_read);
3696
+ }
3697
+ await (init_promise ??= (async () => {
3698
+ try {
3699
+ const module = await get_hooks();
3700
+ this.#options.hooks = {
3701
+ handle: module.handle || (({ event, resolve: resolve2 }) => resolve2(event)),
3702
+ handleError: module.handleError || (({ status, error: error2, event }) => {
3703
+ const error_message = format_server_error(
3704
+ status,
3705
+ /** @type {Error} */
3706
+ error2,
3707
+ event
3708
+ );
3709
+ console.error(error_message);
3710
+ }),
3711
+ handleFetch: module.handleFetch || (({ request, fetch: fetch2 }) => fetch2(request)),
3712
+ handleValidationError: module.handleValidationError || (({ issues }) => {
3713
+ console.error("Remote function schema validation failed:", issues);
3714
+ return { message: "Bad Request" };
3715
+ }),
3716
+ reroute: module.reroute || (() => {
3717
+ }),
3718
+ transport: module.transport || {}
3719
+ };
3720
+ set_app({
3721
+ decoders: module.transport ? Object.fromEntries(Object.entries(module.transport).map(([k, v]) => [k, v.decode])) : {}
3722
+ });
3723
+ if (module.init) {
3724
+ await module.init();
3725
+ }
3726
+ } catch (e) {
3727
+ {
3728
+ throw e;
3729
+ }
3730
+ }
3731
+ })());
3732
+ }
3733
+ /**
3734
+ * @param {Request} request
3735
+ * @param {import('types').RequestOptions} options
3736
+ */
3737
+ async respond(request, options2) {
3738
+ return respond(request, this.#options, this.#manifest, {
3739
+ ...options2,
3740
+ error: false,
3741
+ depth: 0
3742
+ });
3743
+ }
3744
+ }
3745
+ export {
3746
+ Server
3747
+ };