index.js 124 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864
  1. import { B as BROWSER } from "./chunks/false.js";
  2. import { json, text, isRedirect, 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 split_remote_key, q as has_prerendered_path, T as TRAILING_SLASH_PARAM, I as INVALIDATED_PARAM, t as handle_fatal_error, u 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, w as writable, r as readable, 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, f as resolve, g as decode_pathname, h 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 "clsx";
  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. const s = JSON.stringify;
  26. async function render_endpoint(event, event_state, mod, state) {
  27. const method = (
  28. /** @type {import('types').HttpMethod} */
  29. event.request.method
  30. );
  31. let handler = mod[method] || mod.fallback;
  32. if (method === "HEAD" && !mod.HEAD && mod.GET) {
  33. handler = mod.GET;
  34. }
  35. if (!handler) {
  36. return method_not_allowed(mod, method);
  37. }
  38. const prerender = mod.prerender ?? state.prerender_default;
  39. if (prerender && (mod.POST || mod.PATCH || mod.PUT || mod.DELETE)) {
  40. throw new Error("Cannot prerender endpoints that have mutative methods");
  41. }
  42. if (state.prerendering && !state.prerendering.inside_reroute && !prerender) {
  43. if (state.depth > 0) {
  44. throw new Error(`${event.route.id} is not prerenderable`);
  45. } else {
  46. return new Response(void 0, { status: 204 });
  47. }
  48. }
  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. { cause: e }
  416. );
  417. }
  418. if ("path" in error2) {
  419. let message = `Data returned from action inside ${route_id} is not serializable: ${error2.message}`;
  420. if (error2.path !== "") message += ` (data.${error2.path})`;
  421. throw new Error(message, { cause: e });
  422. }
  423. throw error2;
  424. }
  425. }
  426. function create_async_iterator() {
  427. let resolved = -1;
  428. let returned = -1;
  429. const deferred = [];
  430. return {
  431. iterate: (transform = (x) => x) => {
  432. return {
  433. [Symbol.asyncIterator]() {
  434. return {
  435. next: async () => {
  436. const next = deferred[++returned];
  437. if (!next) return { value: null, done: true };
  438. const value = await next.promise;
  439. return { value: transform(value), done: false };
  440. }
  441. };
  442. }
  443. };
  444. },
  445. add: (promise) => {
  446. deferred.push(with_resolvers());
  447. void promise.then((value) => {
  448. deferred[++resolved].resolve(value);
  449. });
  450. }
  451. };
  452. }
  453. function server_data_serializer(event, event_state, options2) {
  454. let promise_id = 1;
  455. let max_nodes = -1;
  456. const iterator = create_async_iterator();
  457. const global = get_global_name(options2);
  458. function get_replacer(index) {
  459. return function replacer(thing) {
  460. if (typeof thing?.then === "function") {
  461. const id = promise_id++;
  462. const promise = thing.then(
  463. /** @param {any} data */
  464. (data) => ({ data })
  465. ).catch(
  466. /** @param {any} error */
  467. async (error2) => ({
  468. error: await handle_error_and_jsonify(event, event_state, options2, error2)
  469. })
  470. ).then(
  471. /**
  472. * @param {{data: any; error: any}} result
  473. */
  474. async ({ data, error: error2 }) => {
  475. let str;
  476. try {
  477. str = devalue.uneval(error2 ? [, error2] : [data], replacer);
  478. } catch {
  479. error2 = await handle_error_and_jsonify(
  480. event,
  481. event_state,
  482. options2,
  483. new Error(`Failed to serialize promise while rendering ${event.route.id}`)
  484. );
  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. ), { cause: e });
  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. ), { cause: e });
  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. const child_state = { ...event_state, is_in_universal_load: true };
  764. return await with_request_store(
  765. { event: traced_event, state: child_state },
  766. () => load.call(null, {
  767. url: event.url,
  768. params: event.params,
  769. data: server_data_node?.data ?? null,
  770. route: event.route,
  771. fetch: create_universal_fetch(event, state, fetched, csr, resolve_opts),
  772. setHeaders: event.setHeaders,
  773. depends: () => {
  774. },
  775. parent,
  776. untrack: (fn) => fn(),
  777. tracing: traced_event.tracing
  778. })
  779. );
  780. }
  781. });
  782. return result ?? null;
  783. }
  784. function create_universal_fetch(event, state, fetched, csr, resolve_opts) {
  785. const universal_fetch = async (input, init2) => {
  786. const cloned_body = input instanceof Request && input.body ? input.clone().body : null;
  787. const cloned_headers = input instanceof Request && [...input.headers].length ? new Headers(input.headers) : init2?.headers;
  788. let response = await event.fetch(input, init2);
  789. const url = new URL(input instanceof Request ? input.url : input, event.url);
  790. const same_origin = url.origin === event.url.origin;
  791. let dependency;
  792. if (same_origin) {
  793. if (state.prerendering) {
  794. dependency = { response, body: null };
  795. state.prerendering.dependencies.set(url.pathname, dependency);
  796. }
  797. } else if (url.protocol === "https:" || url.protocol === "http:") {
  798. const mode = input instanceof Request ? input.mode : init2?.mode ?? "cors";
  799. if (mode === "no-cors") {
  800. response = new Response("", {
  801. status: response.status,
  802. statusText: response.statusText,
  803. headers: response.headers
  804. });
  805. } else {
  806. const acao = response.headers.get("access-control-allow-origin");
  807. if (!acao || acao !== event.url.origin && acao !== "*") {
  808. throw new Error(
  809. `CORS error: ${acao ? "Incorrect" : "No"} 'Access-Control-Allow-Origin' header is present on the requested resource`
  810. );
  811. }
  812. }
  813. }
  814. let teed_body;
  815. const proxy = new Proxy(response, {
  816. get(response2, key2, receiver) {
  817. async function push_fetched(body2, is_b64) {
  818. const status_number = Number(response2.status);
  819. if (isNaN(status_number)) {
  820. throw new Error(
  821. `response.status is not a number. value: "${response2.status}" type: ${typeof response2.status}`
  822. );
  823. }
  824. fetched.push({
  825. url: same_origin ? url.href.slice(event.url.origin.length) : url.href,
  826. method: event.request.method,
  827. request_body: (
  828. /** @type {string | ArrayBufferView | undefined} */
  829. input instanceof Request && cloned_body ? await stream_to_string(cloned_body) : init2?.body
  830. ),
  831. request_headers: cloned_headers,
  832. response_body: body2,
  833. response: response2,
  834. is_b64
  835. });
  836. }
  837. if (key2 === "body") {
  838. if (response2.body === null) {
  839. return null;
  840. }
  841. if (teed_body) {
  842. return teed_body;
  843. }
  844. const [a, b] = response2.body.tee();
  845. void (async () => {
  846. let result = new Uint8Array();
  847. for await (const chunk of a) {
  848. const combined = new Uint8Array(result.length + chunk.length);
  849. combined.set(result, 0);
  850. combined.set(chunk, result.length);
  851. result = combined;
  852. }
  853. if (dependency) {
  854. dependency.body = new Uint8Array(result);
  855. }
  856. void push_fetched(base64_encode(result), true);
  857. })();
  858. return teed_body = b;
  859. }
  860. if (key2 === "arrayBuffer") {
  861. return async () => {
  862. const buffer = await response2.arrayBuffer();
  863. const bytes = new Uint8Array(buffer);
  864. if (dependency) {
  865. dependency.body = bytes;
  866. }
  867. if (buffer instanceof ArrayBuffer) {
  868. await push_fetched(base64_encode(bytes), true);
  869. }
  870. return buffer;
  871. };
  872. }
  873. async function text2() {
  874. const body2 = await response2.text();
  875. if (body2 === "" && NULL_BODY_STATUS.includes(response2.status)) {
  876. await push_fetched(void 0, false);
  877. return void 0;
  878. }
  879. if (!body2 || typeof body2 === "string") {
  880. await push_fetched(body2, false);
  881. }
  882. if (dependency) {
  883. dependency.body = body2;
  884. }
  885. return body2;
  886. }
  887. if (key2 === "text") {
  888. return text2;
  889. }
  890. if (key2 === "json") {
  891. return async () => {
  892. const body2 = await text2();
  893. return body2 ? JSON.parse(body2) : void 0;
  894. };
  895. }
  896. const value = Reflect.get(response2, key2, response2);
  897. if (value instanceof Function) {
  898. return Object.defineProperties(
  899. /**
  900. * @this {any}
  901. */
  902. function() {
  903. return Reflect.apply(value, this === receiver ? response2 : this, arguments);
  904. },
  905. {
  906. name: { value: value.name },
  907. length: { value: value.length }
  908. }
  909. );
  910. }
  911. return value;
  912. }
  913. });
  914. if (csr) {
  915. const get = response.headers.get;
  916. response.headers.get = (key2) => {
  917. const lower = key2.toLowerCase();
  918. const value = get.call(response.headers, lower);
  919. if (value && !lower.startsWith("x-sveltekit-")) {
  920. const included = resolve_opts.filterSerializedResponseHeaders(lower, value);
  921. if (!included) {
  922. throw new Error(
  923. `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})`
  924. );
  925. }
  926. }
  927. return value;
  928. };
  929. }
  930. return proxy;
  931. };
  932. return (input, init2) => {
  933. const response = universal_fetch(input, init2);
  934. response.catch(() => {
  935. });
  936. return response;
  937. };
  938. }
  939. async function stream_to_string(stream) {
  940. let result = "";
  941. const reader = stream.getReader();
  942. while (true) {
  943. const { done, value } = await reader.read();
  944. if (done) {
  945. break;
  946. }
  947. result += text_decoder.decode(value);
  948. }
  949. return result;
  950. }
  951. function hash(...values) {
  952. let hash2 = 5381;
  953. for (const value of values) {
  954. if (typeof value === "string") {
  955. let i = value.length;
  956. while (i) hash2 = hash2 * 33 ^ value.charCodeAt(--i);
  957. } else if (ArrayBuffer.isView(value)) {
  958. const buffer = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
  959. let i = buffer.length;
  960. while (i) hash2 = hash2 * 33 ^ buffer[--i];
  961. } else {
  962. throw new TypeError("value must be a string or TypedArray");
  963. }
  964. }
  965. return (hash2 >>> 0).toString(36);
  966. }
  967. const replacements = {
  968. "<": "\\u003C",
  969. "\u2028": "\\u2028",
  970. "\u2029": "\\u2029"
  971. };
  972. const pattern = new RegExp(`[${Object.keys(replacements).join("")}]`, "g");
  973. function serialize_data(fetched, filter, prerendering = false) {
  974. const headers2 = {};
  975. let cache_control = null;
  976. let age = null;
  977. let varyAny = false;
  978. for (const [key2, value] of fetched.response.headers) {
  979. if (filter(key2, value)) {
  980. headers2[key2] = value;
  981. }
  982. if (key2 === "cache-control") cache_control = value;
  983. else if (key2 === "age") age = value;
  984. else if (key2 === "vary" && value.trim() === "*") varyAny = true;
  985. }
  986. const payload = {
  987. status: fetched.response.status,
  988. statusText: fetched.response.statusText,
  989. headers: headers2,
  990. body: fetched.response_body
  991. };
  992. const safe_payload = JSON.stringify(payload).replace(pattern, (match) => replacements[match]);
  993. const attrs = [
  994. 'type="application/json"',
  995. "data-sveltekit-fetched",
  996. `data-url="${escape_html(fetched.url, true)}"`
  997. ];
  998. if (fetched.is_b64) {
  999. attrs.push("data-b64");
  1000. }
  1001. if (fetched.request_headers || fetched.request_body) {
  1002. const values = [];
  1003. if (fetched.request_headers) {
  1004. values.push([...new Headers(fetched.request_headers)].join(","));
  1005. }
  1006. if (fetched.request_body) {
  1007. values.push(fetched.request_body);
  1008. }
  1009. attrs.push(`data-hash="${hash(...values)}"`);
  1010. }
  1011. if (!prerendering && fetched.method === "GET" && cache_control && !varyAny) {
  1012. const match = /s-maxage=(\d+)/g.exec(cache_control) ?? /max-age=(\d+)/g.exec(cache_control);
  1013. if (match) {
  1014. const ttl = +match[1] - +(age ?? "0");
  1015. attrs.push(`data-ttl="${ttl}"`);
  1016. }
  1017. }
  1018. return `<script ${attrs.join(" ")}>${safe_payload}<\/script>`;
  1019. }
  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 find_route(path, routes, matchers) {
  1417. for (const route of routes) {
  1418. const match = route.pattern.exec(path);
  1419. if (!match) continue;
  1420. const matched = exec(match, route.params, matchers);
  1421. if (matched) {
  1422. return {
  1423. route,
  1424. params: decode_params(matched)
  1425. };
  1426. }
  1427. }
  1428. return null;
  1429. }
  1430. function generate_route_object(route, url, manifest) {
  1431. const { errors, layouts, leaf } = route;
  1432. 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 ");
  1433. return [
  1434. `{
  1435. id: ${s(route.id)}`,
  1436. `errors: ${s(route.errors)}`,
  1437. `layouts: ${s(route.layouts)}`,
  1438. `leaf: ${s(route.leaf)}`,
  1439. `nodes: {
  1440. ${nodes}
  1441. }
  1442. }`
  1443. ].join(",\n ");
  1444. }
  1445. function create_client_import(import_path, url) {
  1446. if (!import_path) return "Promise.resolve({})";
  1447. if (import_path[0] === "/") {
  1448. return `import('${import_path}')`;
  1449. }
  1450. if (assets !== "") {
  1451. return `import('${assets}/${import_path}')`;
  1452. }
  1453. let path = get_relative_path(url.pathname, `${base}/${import_path}`);
  1454. if (path[0] !== ".") path = `./${path}`;
  1455. return `import('${path}')`;
  1456. }
  1457. async function resolve_route(resolved_path, url, manifest) {
  1458. if (!manifest._.client.routes) {
  1459. return text("Server-side route resolution disabled", { status: 400 });
  1460. }
  1461. const matchers = await manifest._.matchers();
  1462. const result = find_route(resolved_path, manifest._.client.routes, matchers);
  1463. return create_server_routing_response(result?.route ?? null, result?.params ?? {}, url, manifest).response;
  1464. }
  1465. function create_server_routing_response(route, params, url, manifest) {
  1466. const headers2 = new Headers({
  1467. "content-type": "application/javascript; charset=utf-8"
  1468. });
  1469. if (route) {
  1470. const csr_route = generate_route_object(route, url, manifest);
  1471. const body2 = `${create_css_import(route, url, manifest)}
  1472. export const route = ${csr_route}; export const params = ${JSON.stringify(params)};`;
  1473. return { response: text(body2, { headers: headers2 }), body: body2 };
  1474. } else {
  1475. return { response: text("", { headers: headers2 }), body: "" };
  1476. }
  1477. }
  1478. function create_css_import(route, url, manifest) {
  1479. const { errors, layouts, leaf } = route;
  1480. let css = "";
  1481. for (const node of [...errors, ...layouts.map((l) => l?.[1]), leaf[1]]) {
  1482. if (typeof node !== "number") continue;
  1483. const node_css = manifest._.client.css?.[node];
  1484. for (const css_path of node_css ?? []) {
  1485. css += `'${assets || base}/${css_path}',`;
  1486. }
  1487. }
  1488. if (!css) return "";
  1489. return `${create_client_import(
  1490. /** @type {string} */
  1491. manifest._.client.start,
  1492. url
  1493. )}.then(x => x.load_css([${css}]));`;
  1494. }
  1495. const updated = {
  1496. ...readable(false),
  1497. check: () => false
  1498. };
  1499. async function render_response({
  1500. branch,
  1501. fetched,
  1502. options: options2,
  1503. manifest,
  1504. state,
  1505. page_config,
  1506. status,
  1507. error: error2 = null,
  1508. event,
  1509. event_state,
  1510. resolve_opts,
  1511. action_result,
  1512. data_serializer,
  1513. error_components
  1514. }) {
  1515. if (state.prerendering) {
  1516. if (options2.csp.mode === "nonce") {
  1517. throw new Error('Cannot use prerendering if config.kit.csp.mode === "nonce"');
  1518. }
  1519. if (options2.app_template_contains_nonce) {
  1520. throw new Error("Cannot use prerendering if page template contains %sveltekit.nonce%");
  1521. }
  1522. }
  1523. const { client } = manifest._;
  1524. const modulepreloads = new Set(client.imports);
  1525. const stylesheets = new Set(client.stylesheets);
  1526. const fonts = new Set(client.fonts);
  1527. const link_headers = /* @__PURE__ */ new Set();
  1528. const inline_styles = /* @__PURE__ */ new Map();
  1529. let rendered;
  1530. const form_value = action_result?.type === "success" || action_result?.type === "failure" ? action_result.data ?? null : null;
  1531. let base$1 = base;
  1532. let assets$1 = assets;
  1533. let base_expression = s(base);
  1534. const csp = new Csp(options2.csp, {
  1535. prerender: !!state.prerendering
  1536. });
  1537. {
  1538. if (!state.prerendering?.fallback) {
  1539. const segments = event.url.pathname.slice(base.length).split("/").slice(2);
  1540. base$1 = segments.map(() => "..").join("/") || ".";
  1541. base_expression = `new URL(${s(base$1)}, location).pathname.slice(0, -1)`;
  1542. if (!assets || assets[0] === "/" && assets !== SVELTE_KIT_ASSETS) {
  1543. assets$1 = base$1;
  1544. }
  1545. } else if (options2.hash_routing) {
  1546. base_expression = "new URL('.', location).pathname.slice(0, -1)";
  1547. }
  1548. }
  1549. if (page_config.ssr) {
  1550. const props = {
  1551. stores: {
  1552. page: writable(null),
  1553. navigating: writable(null),
  1554. updated
  1555. },
  1556. constructors: await Promise.all(
  1557. branch.map(({ node }) => {
  1558. if (!node.component) {
  1559. throw new Error(`Missing +page.svelte component for route ${event.route.id}`);
  1560. }
  1561. return node.component();
  1562. })
  1563. ),
  1564. form: form_value
  1565. };
  1566. if (error_components) {
  1567. if (error2) {
  1568. props.error = error2;
  1569. }
  1570. props.errors = error_components;
  1571. }
  1572. let data2 = {};
  1573. for (let i = 0; i < branch.length; i += 1) {
  1574. data2 = { ...data2, ...branch[i].data };
  1575. props[`data_${i}`] = data2;
  1576. }
  1577. props.page = {
  1578. error: error2,
  1579. params: (
  1580. /** @type {Record<string, any>} */
  1581. event.params
  1582. ),
  1583. route: event.route,
  1584. status,
  1585. url: event.url,
  1586. data: data2,
  1587. form: form_value,
  1588. state: {}
  1589. };
  1590. const render_opts = {
  1591. context: /* @__PURE__ */ new Map([
  1592. [
  1593. "__request__",
  1594. {
  1595. page: props.page
  1596. }
  1597. ]
  1598. ]),
  1599. csp: csp.script_needs_nonce ? { nonce: csp.nonce } : { hash: csp.script_needs_hash },
  1600. transformError: error_components ? (
  1601. /** @param {unknown} e */
  1602. async (e) => {
  1603. if (isRedirect(e)) {
  1604. throw e;
  1605. }
  1606. const transformed2 = await handle_error_and_jsonify(event, event_state, options2, e);
  1607. props.page.error = props.error = error2 = transformed2;
  1608. props.page.status = status = get_status(e);
  1609. return transformed2;
  1610. }
  1611. ) : void 0
  1612. };
  1613. const fetch2 = globalThis.fetch;
  1614. try {
  1615. if (BROWSER) ;
  1616. const state2 = { ...event_state, is_in_render: true };
  1617. rendered = await with_request_store({ event, state: state2 }, async () => {
  1618. if (relative) override({ base: base$1, assets: assets$1 });
  1619. const maybe_promise = options2.root.render(props, render_opts);
  1620. const rendered2 = options2.async && "then" in maybe_promise ? (
  1621. /** @type {ReturnType<typeof options.root.render> & Promise<any>} */
  1622. maybe_promise.then((r) => r)
  1623. ) : maybe_promise;
  1624. if (options2.async) {
  1625. reset();
  1626. }
  1627. const { head: head2, html: html2, css, hashes } = (
  1628. /** @type {ReturnType<typeof options.root.render>} */
  1629. options2.async ? await rendered2 : rendered2
  1630. );
  1631. if (hashes) {
  1632. csp.add_script_hashes(hashes.script);
  1633. }
  1634. return { head: head2, html: html2, css, hashes };
  1635. });
  1636. } finally {
  1637. reset();
  1638. }
  1639. for (const { node } of branch) {
  1640. for (const url of node.imports) modulepreloads.add(url);
  1641. for (const url of node.stylesheets) stylesheets.add(url);
  1642. for (const url of node.fonts) fonts.add(url);
  1643. if (node.inline_styles && !client.inline) {
  1644. Object.entries(await node.inline_styles()).forEach(([filename, css]) => {
  1645. if (typeof css === "string") {
  1646. inline_styles.set(filename, css);
  1647. return;
  1648. }
  1649. inline_styles.set(filename, css(`${assets$1}/${app_dir}/immutable/assets`, assets$1));
  1650. });
  1651. }
  1652. }
  1653. } else {
  1654. rendered = { head: "", html: "", css: { code: "", map: null }, hashes: { script: [] } };
  1655. }
  1656. const head = new Head(rendered.head, !!state.prerendering);
  1657. let body2 = rendered.html;
  1658. const prefixed = (path) => {
  1659. if (path.startsWith("/")) {
  1660. return base + path;
  1661. }
  1662. return `${assets$1}/${path}`;
  1663. };
  1664. const style = client.inline ? client.inline?.style : Array.from(inline_styles.values()).join("\n");
  1665. if (style) {
  1666. const attributes = [];
  1667. if (csp.style_needs_nonce) attributes.push(`nonce="${csp.nonce}"`);
  1668. csp.add_style(style);
  1669. head.add_style(style, attributes);
  1670. }
  1671. for (const dep of stylesheets) {
  1672. const path = prefixed(dep);
  1673. const attributes = ['rel="stylesheet"'];
  1674. if (inline_styles.has(dep)) {
  1675. attributes.push("disabled", 'media="(max-width: 0)"');
  1676. } else {
  1677. if (resolve_opts.preload({ type: "css", path })) {
  1678. link_headers.add(`<${encodeURI(path)}>; rel="preload"; as="style"; nopush`);
  1679. }
  1680. }
  1681. head.add_stylesheet(path, attributes);
  1682. }
  1683. for (const dep of fonts) {
  1684. const path = prefixed(dep);
  1685. if (resolve_opts.preload({ type: "font", path })) {
  1686. const ext = dep.slice(dep.lastIndexOf(".") + 1);
  1687. head.add_link_tag(path, ['rel="preload"', 'as="font"', `type="font/${ext}"`, "crossorigin"]);
  1688. link_headers.add(
  1689. `<${encodeURI(path)}>; rel="preload"; as="font"; type="font/${ext}"; crossorigin; nopush`
  1690. );
  1691. }
  1692. }
  1693. const global = get_global_name(options2);
  1694. const { data, chunks } = data_serializer.get_data(csp);
  1695. if (page_config.ssr && page_config.csr) {
  1696. body2 += `
  1697. ${fetched.map(
  1698. (item) => serialize_data(item, resolve_opts.filterSerializedResponseHeaders, !!state.prerendering)
  1699. ).join("\n ")}`;
  1700. }
  1701. if (page_config.csr) {
  1702. const route = manifest._.client.routes?.find((r) => r.id === event.route.id) ?? null;
  1703. if (client.uses_env_dynamic_public && state.prerendering) {
  1704. modulepreloads.add(`${app_dir}/env.js`);
  1705. }
  1706. if (!client.inline) {
  1707. const included_modulepreloads = Array.from(modulepreloads, (dep) => prefixed(dep)).filter(
  1708. (path) => resolve_opts.preload({ type: "js", path })
  1709. );
  1710. for (const path of included_modulepreloads) {
  1711. link_headers.add(`<${encodeURI(path)}>; rel="modulepreload"; nopush`);
  1712. if (options2.preload_strategy !== "modulepreload") {
  1713. head.add_script_preload(path);
  1714. } else {
  1715. head.add_link_tag(path, ['rel="modulepreload"']);
  1716. }
  1717. }
  1718. }
  1719. if (manifest._.client.routes && state.prerendering && !state.prerendering.fallback) {
  1720. const pathname = add_resolution_suffix(event.url.pathname);
  1721. state.prerendering.dependencies.set(
  1722. pathname,
  1723. create_server_routing_response(route, event.params, new URL(pathname, event.url), manifest)
  1724. );
  1725. }
  1726. const blocks = [];
  1727. const load_env_eagerly = client.uses_env_dynamic_public && state.prerendering;
  1728. const properties = [`base: ${base_expression}`];
  1729. if (assets) {
  1730. properties.push(`assets: ${s(assets)}`);
  1731. }
  1732. if (client.uses_env_dynamic_public) {
  1733. properties.push(`env: ${load_env_eagerly ? "null" : s(public_env)}`);
  1734. }
  1735. if (chunks) {
  1736. blocks.push("const deferred = new Map();");
  1737. properties.push(`defer: (id) => new Promise((fulfil, reject) => {
  1738. deferred.set(id, { fulfil, reject });
  1739. })`);
  1740. let app_declaration = "";
  1741. if (Object.keys(options2.hooks.transport).length > 0) {
  1742. if (client.inline) {
  1743. app_declaration = `const app = __sveltekit_${options2.version_hash}.app.app;`;
  1744. } else if (client.app) {
  1745. app_declaration = `const app = await import(${s(prefixed(client.app))});`;
  1746. } else {
  1747. app_declaration = `const { app } = await import(${s(prefixed(client.start))});`;
  1748. }
  1749. }
  1750. const prelude = app_declaration ? `${app_declaration}
  1751. const [data, error] = fn(app);` : `const [data, error] = fn();`;
  1752. properties.push(`resolve: async (id, fn) => {
  1753. ${prelude}
  1754. const try_to_resolve = () => {
  1755. if (!deferred.has(id)) {
  1756. setTimeout(try_to_resolve, 0);
  1757. return;
  1758. }
  1759. const { fulfil, reject } = deferred.get(id);
  1760. deferred.delete(id);
  1761. if (error) reject(error);
  1762. else fulfil(data);
  1763. }
  1764. try_to_resolve();
  1765. }`);
  1766. }
  1767. blocks.push(`${global} = {
  1768. ${properties.join(",\n ")}
  1769. };`);
  1770. const args = ["element"];
  1771. blocks.push("const element = document.currentScript.parentElement;");
  1772. if (page_config.ssr) {
  1773. const serialized = { form: "null", error: "null" };
  1774. if (form_value) {
  1775. serialized.form = uneval_action_response(
  1776. form_value,
  1777. /** @type {string} */
  1778. event.route.id,
  1779. options2.hooks.transport
  1780. );
  1781. }
  1782. if (error2) {
  1783. serialized.error = devalue.uneval(error2);
  1784. }
  1785. const hydrate = [
  1786. `node_ids: [${branch.map(({ node }) => node.index).join(", ")}]`,
  1787. `data: ${data}`,
  1788. `form: ${serialized.form}`,
  1789. `error: ${serialized.error}`
  1790. ];
  1791. if (status !== 200) {
  1792. hydrate.push(`status: ${status}`);
  1793. }
  1794. if (manifest._.client.routes) {
  1795. if (route) {
  1796. const stringified = generate_route_object(route, event.url, manifest).replaceAll(
  1797. "\n",
  1798. "\n "
  1799. );
  1800. hydrate.push(`params: ${devalue.uneval(event.params)}`, `server_route: ${stringified}`);
  1801. }
  1802. } else if (options2.embedded) {
  1803. hydrate.push(`params: ${devalue.uneval(event.params)}`, `route: ${s(event.route)}`);
  1804. }
  1805. const indent = " ".repeat(load_env_eagerly ? 7 : 6);
  1806. args.push(`{
  1807. ${indent} ${hydrate.join(`,
  1808. ${indent} `)}
  1809. ${indent}}`);
  1810. }
  1811. const { remote } = event_state;
  1812. let serialized_query_data = "";
  1813. let serialized_prerender_data = "";
  1814. if (remote.data) {
  1815. const query = {};
  1816. const prerender = {};
  1817. for (const [internals, cache] of remote.data) {
  1818. if (!internals.id) continue;
  1819. for (const key2 in cache) {
  1820. const entry = cache[key2];
  1821. if (!entry.serialize) continue;
  1822. const remote_key = create_remote_key(internals.id, key2);
  1823. const store = internals.type === "prerender" ? prerender : query;
  1824. if (event_state.remote.refreshes?.[remote_key] !== void 0) {
  1825. store[remote_key] = await entry.data;
  1826. } else {
  1827. const result = await Promise.race([
  1828. Promise.resolve(entry.data).then(
  1829. (v) => (
  1830. /** @type {const} */
  1831. { settled: true, value: v }
  1832. ),
  1833. (e) => (
  1834. /** @type {const} */
  1835. { settled: true, error: e }
  1836. )
  1837. ),
  1838. new Promise((resolve2) => {
  1839. queueMicrotask(() => resolve2(
  1840. /** @type {const} */
  1841. { settled: false }
  1842. ));
  1843. })
  1844. ]);
  1845. if (result.settled) {
  1846. if ("error" in result) throw result.error;
  1847. store[remote_key] = result.value;
  1848. }
  1849. }
  1850. }
  1851. }
  1852. const replacer = (thing) => {
  1853. for (const key2 in options2.hooks.transport) {
  1854. const encoded = options2.hooks.transport[key2].encode(thing);
  1855. if (encoded) {
  1856. return `app.decode('${key2}', ${devalue.uneval(encoded, replacer)})`;
  1857. }
  1858. }
  1859. };
  1860. if (Object.keys(query).length > 0) {
  1861. serialized_query_data = `${global}.query = ${devalue.uneval(query, replacer)};
  1862. `;
  1863. }
  1864. if (Object.keys(prerender).length > 0) {
  1865. serialized_prerender_data = `${global}.prerender = ${devalue.uneval(prerender, replacer)};
  1866. `;
  1867. }
  1868. }
  1869. const serialized_remote_data = `${serialized_query_data}${serialized_prerender_data}`;
  1870. const boot = client.inline ? `${client.inline.script}
  1871. ${serialized_remote_data}${global}.app.start(${args.join(", ")});` : client.app ? `Promise.all([
  1872. import(${s(prefixed(client.start))}),
  1873. import(${s(prefixed(client.app))})
  1874. ]).then(([kit, app]) => {
  1875. ${serialized_remote_data}kit.start(app, ${args.join(", ")});
  1876. });` : `import(${s(prefixed(client.start))}).then((app) => {
  1877. ${serialized_remote_data}app.start(${args.join(", ")})
  1878. });`;
  1879. if (load_env_eagerly) {
  1880. blocks.push(`import(${s(`${base$1}/${app_dir}/env.js`)}).then(({ env }) => {
  1881. ${global}.env = env;
  1882. ${boot.replace(/\n/g, "\n ")}
  1883. });`);
  1884. } else {
  1885. blocks.push(boot);
  1886. }
  1887. if (options2.service_worker) {
  1888. let opts = "";
  1889. if (options2.service_worker_options != null) {
  1890. const service_worker_options = { ...options2.service_worker_options };
  1891. opts = `, ${s(service_worker_options)}`;
  1892. }
  1893. blocks.push(`if ('serviceWorker' in navigator) {
  1894. addEventListener('load', function () {
  1895. navigator.serviceWorker.register('${prefixed("service-worker.js")}'${opts});
  1896. });
  1897. }`);
  1898. }
  1899. const init_app = `
  1900. {
  1901. ${blocks.join("\n\n ")}
  1902. }
  1903. `;
  1904. csp.add_script(init_app);
  1905. body2 += `
  1906. <script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ""}>${init_app}<\/script>
  1907. `;
  1908. }
  1909. const headers2 = new Headers({
  1910. "x-sveltekit-page": "true",
  1911. "content-type": "text/html"
  1912. });
  1913. if (state.prerendering) {
  1914. const csp_headers = csp.csp_provider.get_meta();
  1915. if (csp_headers) {
  1916. head.add_http_equiv(csp_headers);
  1917. }
  1918. if (state.prerendering.cache) {
  1919. head.add_http_equiv(
  1920. `<meta http-equiv="cache-control" content="${state.prerendering.cache}">`
  1921. );
  1922. }
  1923. } else {
  1924. const csp_header = csp.csp_provider.get_header();
  1925. if (csp_header) {
  1926. headers2.set("content-security-policy", csp_header);
  1927. }
  1928. const report_only_header = csp.report_only_provider.get_header();
  1929. if (report_only_header) {
  1930. headers2.set("content-security-policy-report-only", report_only_header);
  1931. }
  1932. if (link_headers.size) {
  1933. headers2.set("link", Array.from(link_headers).join(", "));
  1934. }
  1935. }
  1936. const html = options2.templates.app({
  1937. head: head.build(),
  1938. body: body2,
  1939. assets: assets$1,
  1940. nonce: (
  1941. /** @type {string} */
  1942. csp.nonce
  1943. ),
  1944. env: public_env
  1945. });
  1946. const transformed = await resolve_opts.transformPageChunk({
  1947. html,
  1948. done: true
  1949. }) || "";
  1950. if (!chunks) {
  1951. headers2.set("etag", `"${hash(transformed)}"`);
  1952. }
  1953. return !chunks ? text(transformed, {
  1954. status,
  1955. headers: headers2
  1956. }) : new Response(
  1957. new ReadableStream({
  1958. async start(controller) {
  1959. controller.enqueue(text_encoder.encode(transformed + "\n"));
  1960. for await (const chunk of chunks) {
  1961. if (chunk.length) controller.enqueue(text_encoder.encode(chunk));
  1962. }
  1963. controller.close();
  1964. },
  1965. type: "bytes"
  1966. }),
  1967. {
  1968. headers: headers2
  1969. }
  1970. );
  1971. }
  1972. class Head {
  1973. #rendered;
  1974. #prerendering;
  1975. /** @type {string[]} */
  1976. #http_equiv = [];
  1977. /** @type {string[]} */
  1978. #link_tags = [];
  1979. /** @type {string[]} */
  1980. #script_preloads = [];
  1981. /** @type {string[]} */
  1982. #style_tags = [];
  1983. /** @type {string[]} */
  1984. #stylesheet_links = [];
  1985. /**
  1986. * @param {string} rendered
  1987. * @param {boolean} prerendering
  1988. */
  1989. constructor(rendered, prerendering) {
  1990. this.#rendered = rendered;
  1991. this.#prerendering = prerendering;
  1992. }
  1993. build() {
  1994. return [
  1995. ...this.#http_equiv,
  1996. ...this.#link_tags,
  1997. ...this.#script_preloads,
  1998. this.#rendered,
  1999. ...this.#style_tags,
  2000. ...this.#stylesheet_links
  2001. ].join("\n ");
  2002. }
  2003. /**
  2004. * @param {string} style
  2005. * @param {string[]} attributes
  2006. */
  2007. add_style(style, attributes) {
  2008. this.#style_tags.push(
  2009. `<style${attributes.length ? " " + attributes.join(" ") : ""}>${style}</style>`
  2010. );
  2011. }
  2012. /**
  2013. * @param {string} href
  2014. * @param {string[]} attributes
  2015. */
  2016. add_stylesheet(href, attributes) {
  2017. this.#stylesheet_links.push(`<link href="${href}" ${attributes.join(" ")}>`);
  2018. }
  2019. /** @param {string} href */
  2020. add_script_preload(href) {
  2021. this.#script_preloads.push(
  2022. `<link rel="preload" as="script" crossorigin="anonymous" href="${href}">`
  2023. );
  2024. }
  2025. /**
  2026. * @param {string} href
  2027. * @param {string[]} attributes
  2028. */
  2029. add_link_tag(href, attributes) {
  2030. if (!this.#prerendering) return;
  2031. this.#link_tags.push(`<link href="${href}" ${attributes.join(" ")}>`);
  2032. }
  2033. /** @param {string} tag */
  2034. add_http_equiv(tag) {
  2035. if (!this.#prerendering) return;
  2036. this.#http_equiv.push(tag);
  2037. }
  2038. }
  2039. class PageNodes {
  2040. data;
  2041. /**
  2042. * @param {Array<import('types').SSRNode | undefined>} nodes
  2043. */
  2044. constructor(nodes) {
  2045. this.data = nodes;
  2046. }
  2047. layouts() {
  2048. return this.data.slice(0, -1);
  2049. }
  2050. page() {
  2051. return this.data.at(-1);
  2052. }
  2053. validate() {
  2054. for (const layout of this.layouts()) {
  2055. if (layout) {
  2056. validate_layout_server_exports(
  2057. layout.server,
  2058. /** @type {string} */
  2059. layout.server_id
  2060. );
  2061. validate_layout_exports(
  2062. layout.universal,
  2063. /** @type {string} */
  2064. layout.universal_id
  2065. );
  2066. }
  2067. }
  2068. const page = this.page();
  2069. if (page) {
  2070. validate_page_server_exports(
  2071. page.server,
  2072. /** @type {string} */
  2073. page.server_id
  2074. );
  2075. validate_page_exports(
  2076. page.universal,
  2077. /** @type {string} */
  2078. page.universal_id
  2079. );
  2080. }
  2081. }
  2082. /**
  2083. * @template {'prerender' | 'ssr' | 'csr' | 'trailingSlash'} Option
  2084. * @param {Option} option
  2085. * @returns {Value | undefined}
  2086. */
  2087. #get_option(option) {
  2088. return this.data.reduce(
  2089. (value, node) => {
  2090. return node?.universal?.[option] ?? node?.server?.[option] ?? value;
  2091. },
  2092. /** @type {Value | undefined} */
  2093. void 0
  2094. );
  2095. }
  2096. csr() {
  2097. return this.#get_option("csr") ?? true;
  2098. }
  2099. ssr() {
  2100. return this.#get_option("ssr") ?? true;
  2101. }
  2102. prerender() {
  2103. return this.#get_option("prerender") ?? false;
  2104. }
  2105. trailing_slash() {
  2106. return this.#get_option("trailingSlash") ?? "never";
  2107. }
  2108. get_config() {
  2109. let current2 = {};
  2110. for (const node of this.data) {
  2111. if (!node?.universal?.config && !node?.server?.config) continue;
  2112. current2 = {
  2113. ...current2,
  2114. // TODO: should we override the server config value with the universal value similar to other page options?
  2115. ...node?.universal?.config,
  2116. ...node?.server?.config
  2117. };
  2118. }
  2119. return Object.keys(current2).length ? current2 : void 0;
  2120. }
  2121. should_prerender_data() {
  2122. return this.data.some(
  2123. // prerender in case of trailingSlash because the client retrieves that value from the server
  2124. (node) => node?.server?.load || node?.server?.trailingSlash !== void 0
  2125. );
  2126. }
  2127. }
  2128. async function respond_with_error({
  2129. event,
  2130. event_state,
  2131. options: options2,
  2132. manifest,
  2133. state,
  2134. status,
  2135. error: error2,
  2136. resolve_opts
  2137. }) {
  2138. if (event.request.headers.get("x-sveltekit-error")) {
  2139. return static_error_page(
  2140. options2,
  2141. status,
  2142. /** @type {Error} */
  2143. error2.message
  2144. );
  2145. }
  2146. const fetched = [];
  2147. try {
  2148. const branch = [];
  2149. const default_layout = await manifest._.nodes[0]();
  2150. const nodes = new PageNodes([default_layout]);
  2151. const ssr = nodes.ssr();
  2152. const csr = nodes.csr();
  2153. const data_serializer = server_data_serializer(event, event_state, options2);
  2154. if (ssr) {
  2155. state.error = true;
  2156. const server_data_promise = load_server_data({
  2157. event,
  2158. event_state,
  2159. state,
  2160. node: default_layout,
  2161. // eslint-disable-next-line @typescript-eslint/require-await
  2162. parent: async () => ({})
  2163. });
  2164. const server_data = await server_data_promise;
  2165. data_serializer.add_node(0, server_data);
  2166. const data = await load_data({
  2167. event,
  2168. event_state,
  2169. fetched,
  2170. node: default_layout,
  2171. // eslint-disable-next-line @typescript-eslint/require-await
  2172. parent: async () => ({}),
  2173. resolve_opts,
  2174. server_data_promise,
  2175. state,
  2176. csr
  2177. });
  2178. branch.push(
  2179. {
  2180. node: default_layout,
  2181. server_data,
  2182. data
  2183. },
  2184. {
  2185. node: await manifest._.nodes[1](),
  2186. // 1 is always the root error
  2187. data: null,
  2188. server_data: null
  2189. }
  2190. );
  2191. }
  2192. return await render_response({
  2193. options: options2,
  2194. manifest,
  2195. state,
  2196. page_config: {
  2197. ssr,
  2198. csr
  2199. },
  2200. status,
  2201. error: await handle_error_and_jsonify(event, event_state, options2, error2),
  2202. branch,
  2203. error_components: [],
  2204. fetched,
  2205. event,
  2206. event_state,
  2207. resolve_opts,
  2208. data_serializer
  2209. });
  2210. } catch (e) {
  2211. if (e instanceof Redirect) {
  2212. return redirect_response(e.status, e.location);
  2213. }
  2214. return static_error_page(
  2215. options2,
  2216. get_status(e),
  2217. (await handle_error_and_jsonify(event, event_state, options2, e)).message
  2218. );
  2219. }
  2220. }
  2221. async function handle_remote_call(event, state, options2, manifest, id) {
  2222. return record_span({
  2223. name: "sveltekit.remote.call",
  2224. attributes: {},
  2225. fn: (current2) => {
  2226. const traced_event = merge_tracing(event, current2);
  2227. return with_request_store(
  2228. { event: traced_event, state },
  2229. () => handle_remote_call_internal(traced_event, state, options2, manifest, id)
  2230. );
  2231. }
  2232. });
  2233. }
  2234. async function handle_remote_call_internal(event, state, options2, manifest, id) {
  2235. const [hash2, name, additional_args] = id.split("/");
  2236. const remotes = manifest._.remotes;
  2237. if (!remotes[hash2]) error(404);
  2238. const module = await remotes[hash2]();
  2239. const fn = module.default[name];
  2240. if (!fn) error(404);
  2241. const internals = fn.__;
  2242. const transport = options2.hooks.transport;
  2243. event.tracing.current.setAttributes({
  2244. "sveltekit.remote.call.type": internals.type,
  2245. "sveltekit.remote.call.name": internals.name
  2246. });
  2247. try {
  2248. if (internals.type === "query_batch") {
  2249. if (event.request.method !== "POST") {
  2250. throw new SvelteKitError(
  2251. 405,
  2252. "Method Not Allowed",
  2253. `\`query.batch\` functions must be invoked via POST request, not ${event.request.method}`
  2254. );
  2255. }
  2256. const { payloads } = await event.request.json();
  2257. const args = await Promise.all(
  2258. payloads.map((payload2) => parse_remote_arg(payload2, transport))
  2259. );
  2260. const results = await with_request_store(
  2261. { event, state },
  2262. () => internals.run(args, options2)
  2263. );
  2264. return json(
  2265. /** @type {RemoteFunctionResponse} */
  2266. {
  2267. type: "result",
  2268. result: stringify(results, transport)
  2269. }
  2270. );
  2271. }
  2272. if (internals.type === "form") {
  2273. if (event.request.method !== "POST") {
  2274. throw new SvelteKitError(
  2275. 405,
  2276. "Method Not Allowed",
  2277. `\`form\` functions must be invoked via POST request, not ${event.request.method}`
  2278. );
  2279. }
  2280. if (!is_form_content_type(event.request)) {
  2281. throw new SvelteKitError(
  2282. 415,
  2283. "Unsupported Media Type",
  2284. `\`form\` functions expect form-encoded data — received ${event.request.headers.get(
  2285. "content-type"
  2286. )}`
  2287. );
  2288. }
  2289. const { data: data2, meta, form_data } = await deserialize_binary_form(event.request);
  2290. state.remote.requested = create_requested_map(meta.remote_refreshes);
  2291. if (additional_args && !("id" in data2)) {
  2292. data2.id = JSON.parse(decodeURIComponent(additional_args));
  2293. }
  2294. const fn2 = internals.fn;
  2295. const result = await with_request_store({ event, state }, () => fn2(data2, meta, form_data));
  2296. return json(
  2297. /** @type {RemoteFunctionResponse} */
  2298. {
  2299. type: "result",
  2300. result: stringify(result, transport),
  2301. refreshes: result.issues ? void 0 : await serialize_refreshes()
  2302. }
  2303. );
  2304. }
  2305. if (internals.type === "command") {
  2306. const { payload: payload2, refreshes } = await event.request.json();
  2307. state.remote.requested = create_requested_map(refreshes);
  2308. const arg = parse_remote_arg(payload2, transport);
  2309. const data2 = await with_request_store({ event, state }, () => fn(arg));
  2310. return json(
  2311. /** @type {RemoteFunctionResponse} */
  2312. {
  2313. type: "result",
  2314. result: stringify(data2, transport),
  2315. refreshes: await serialize_refreshes()
  2316. }
  2317. );
  2318. }
  2319. const payload = internals.type === "prerender" ? additional_args : (
  2320. /** @type {string} */
  2321. // new URL(...) necessary because we're hiding the URL from the user in the event object
  2322. new URL(event.request.url).searchParams.get("payload")
  2323. );
  2324. const data = await with_request_store(
  2325. { event, state },
  2326. () => fn(parse_remote_arg(payload, transport))
  2327. );
  2328. return json(
  2329. /** @type {RemoteFunctionResponse} */
  2330. {
  2331. type: "result",
  2332. result: stringify(data, transport)
  2333. }
  2334. );
  2335. } catch (error2) {
  2336. if (error2 instanceof Redirect) {
  2337. return json(
  2338. /** @type {RemoteFunctionResponse} */
  2339. {
  2340. type: "redirect",
  2341. location: error2.location,
  2342. refreshes: await serialize_refreshes()
  2343. }
  2344. );
  2345. }
  2346. const status = error2 instanceof HttpError || error2 instanceof SvelteKitError ? error2.status : 500;
  2347. return json(
  2348. /** @type {RemoteFunctionResponse} */
  2349. {
  2350. type: "error",
  2351. error: await handle_error_and_jsonify(event, state, options2, error2),
  2352. status
  2353. },
  2354. {
  2355. // By setting a non-200 during prerendering we fail the prerender process (unless handleHttpError handles it).
  2356. // Errors at runtime will be passed to the client and are handled there
  2357. status: state.prerendering ? status : void 0,
  2358. headers: {
  2359. "cache-control": "private, no-store"
  2360. }
  2361. }
  2362. );
  2363. }
  2364. async function serialize_refreshes() {
  2365. const refreshes = state.remote.refreshes ?? {};
  2366. const entries = Object.entries(refreshes);
  2367. if (entries.length === 0) {
  2368. return void 0;
  2369. }
  2370. const results = await Promise.all(
  2371. entries.map(async ([key2, promise]) => {
  2372. try {
  2373. return [key2, { type: "result", data: await promise }];
  2374. } catch (error2) {
  2375. const status = error2 instanceof HttpError || error2 instanceof SvelteKitError ? error2.status : 500;
  2376. return [
  2377. key2,
  2378. {
  2379. type: "error",
  2380. status,
  2381. error: await handle_error_and_jsonify(event, state, options2, error2)
  2382. }
  2383. ];
  2384. }
  2385. })
  2386. );
  2387. return stringify(Object.fromEntries(results), transport);
  2388. }
  2389. }
  2390. function create_requested_map(refreshes) {
  2391. const requested = /* @__PURE__ */ new Map();
  2392. for (const key2 of refreshes ?? []) {
  2393. const parts = split_remote_key(key2);
  2394. const existing = requested.get(parts.id);
  2395. if (existing) {
  2396. existing.push(parts.payload);
  2397. } else {
  2398. requested.set(parts.id, [parts.payload]);
  2399. }
  2400. }
  2401. return requested;
  2402. }
  2403. async function handle_remote_form_post(event, state, manifest, id) {
  2404. return record_span({
  2405. name: "sveltekit.remote.form.post",
  2406. attributes: {},
  2407. fn: (current2) => {
  2408. const traced_event = merge_tracing(event, current2);
  2409. return with_request_store(
  2410. { event: traced_event, state },
  2411. () => handle_remote_form_post_internal(traced_event, state, manifest, id)
  2412. );
  2413. }
  2414. });
  2415. }
  2416. async function handle_remote_form_post_internal(event, state, manifest, id) {
  2417. const [hash2, name, action_id] = id.split("/");
  2418. const remotes = manifest._.remotes;
  2419. const module = await remotes[hash2]?.();
  2420. let form = (
  2421. /** @type {RemoteForm<any, any>} */
  2422. module?.default[name]
  2423. );
  2424. if (!form) {
  2425. event.setHeaders({
  2426. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
  2427. // "The server must generate an Allow header field in a 405 status code response"
  2428. allow: "GET"
  2429. });
  2430. return {
  2431. type: "error",
  2432. error: new SvelteKitError(
  2433. 405,
  2434. "Method Not Allowed",
  2435. `POST method not allowed. No form actions exist for ${"this page"}`
  2436. )
  2437. };
  2438. }
  2439. if (action_id) {
  2440. form = with_request_store({ event, state }, () => form.for(JSON.parse(action_id)));
  2441. }
  2442. try {
  2443. const fn = (
  2444. /** @type {RemoteFormInternals} */
  2445. /** @type {any} */
  2446. form.__.fn
  2447. );
  2448. const { data, meta, form_data } = await deserialize_binary_form(event.request);
  2449. if (action_id && !("id" in data)) {
  2450. data.id = JSON.parse(decodeURIComponent(action_id));
  2451. }
  2452. await with_request_store({ event, state }, () => fn(data, meta, form_data));
  2453. return {
  2454. type: "success",
  2455. status: 200
  2456. };
  2457. } catch (e) {
  2458. const err = normalize_error(e);
  2459. if (err instanceof Redirect) {
  2460. return {
  2461. type: "redirect",
  2462. status: err.status,
  2463. location: err.location
  2464. };
  2465. }
  2466. return {
  2467. type: "error",
  2468. error: check_incorrect_fail_use(err)
  2469. };
  2470. }
  2471. }
  2472. function get_remote_id(url) {
  2473. return url.pathname.startsWith(`${base}/${app_dir}/remote/`) && url.pathname.replace(`${base}/${app_dir}/remote/`, "");
  2474. }
  2475. function get_remote_action(url) {
  2476. return url.searchParams.get("/remote");
  2477. }
  2478. const MAX_DEPTH = 10;
  2479. async function render_page(event, event_state, page, options2, manifest, state, nodes, resolve_opts) {
  2480. if (state.depth > MAX_DEPTH) {
  2481. return text(`Not found: ${event.url.pathname}`, {
  2482. status: 404
  2483. // TODO in some cases this should be 500. not sure how to differentiate
  2484. });
  2485. }
  2486. if (is_action_json_request(event)) {
  2487. const node = await manifest._.nodes[page.leaf]();
  2488. return handle_action_json_request(event, event_state, options2, node?.server);
  2489. }
  2490. try {
  2491. const leaf_node = (
  2492. /** @type {import('types').SSRNode} */
  2493. nodes.page()
  2494. );
  2495. let status = 200;
  2496. let action_result = void 0;
  2497. if (is_action_request(event)) {
  2498. const remote_id = get_remote_action(event.url);
  2499. if (remote_id) {
  2500. action_result = await handle_remote_form_post(event, event_state, manifest, remote_id);
  2501. } else {
  2502. action_result = await handle_action_request(event, event_state, leaf_node.server);
  2503. }
  2504. if (action_result?.type === "redirect") {
  2505. return redirect_response(action_result.status, action_result.location);
  2506. }
  2507. if (action_result?.type === "error") {
  2508. status = get_status(action_result.error);
  2509. }
  2510. if (action_result?.type === "failure") {
  2511. status = action_result.status;
  2512. }
  2513. }
  2514. const should_prerender = nodes.prerender();
  2515. if (should_prerender) {
  2516. const mod = leaf_node.server;
  2517. if (mod?.actions) {
  2518. throw new Error("Cannot prerender pages with actions");
  2519. }
  2520. } else if (state.prerendering) {
  2521. return new Response(void 0, {
  2522. status: 204
  2523. });
  2524. }
  2525. state.prerender_default = should_prerender;
  2526. const should_prerender_data = nodes.should_prerender_data();
  2527. const data_pathname = add_data_suffix(event.url.pathname);
  2528. const fetched = [];
  2529. const ssr = nodes.ssr();
  2530. const csr = nodes.csr();
  2531. if (ssr === false && !(state.prerendering && should_prerender_data)) {
  2532. if (BROWSER && action_result && !event.request.headers.has("x-sveltekit-action")) ;
  2533. return await render_response({
  2534. branch: [],
  2535. fetched,
  2536. page_config: {
  2537. ssr: false,
  2538. csr
  2539. },
  2540. status,
  2541. error: null,
  2542. event,
  2543. event_state,
  2544. options: options2,
  2545. manifest,
  2546. state,
  2547. resolve_opts,
  2548. data_serializer: server_data_serializer(event, event_state, options2)
  2549. });
  2550. }
  2551. const branch = [];
  2552. let load_error = null;
  2553. const data_serializer = server_data_serializer(event, event_state, options2);
  2554. const data_serializer_json = state.prerendering && should_prerender_data ? server_data_serializer_json(event, event_state, options2) : null;
  2555. const server_promises = nodes.data.map((node, i) => {
  2556. if (load_error) {
  2557. throw load_error;
  2558. }
  2559. return Promise.resolve().then(async () => {
  2560. try {
  2561. if (node === leaf_node && action_result?.type === "error") {
  2562. throw action_result.error;
  2563. }
  2564. const server_data = await load_server_data({
  2565. event,
  2566. event_state,
  2567. state,
  2568. node,
  2569. parent: async () => {
  2570. const data = {};
  2571. for (let j = 0; j < i; j += 1) {
  2572. const parent = await server_promises[j];
  2573. if (parent) Object.assign(data, parent.data);
  2574. }
  2575. return data;
  2576. }
  2577. });
  2578. if (node) {
  2579. data_serializer.add_node(i, server_data);
  2580. }
  2581. data_serializer_json?.add_node(i, server_data);
  2582. return server_data;
  2583. } catch (e) {
  2584. load_error = /** @type {Error} */
  2585. e;
  2586. throw load_error;
  2587. }
  2588. });
  2589. });
  2590. const load_promises = nodes.data.map((node, i) => {
  2591. if (load_error) throw load_error;
  2592. return Promise.resolve().then(async () => {
  2593. try {
  2594. return await load_data({
  2595. event,
  2596. event_state,
  2597. fetched,
  2598. node,
  2599. parent: async () => {
  2600. const data = {};
  2601. for (let j = 0; j < i; j += 1) {
  2602. Object.assign(data, await load_promises[j]);
  2603. }
  2604. return data;
  2605. },
  2606. resolve_opts,
  2607. server_data_promise: server_promises[i],
  2608. state,
  2609. csr
  2610. });
  2611. } catch (e) {
  2612. load_error = /** @type {Error} */
  2613. e;
  2614. throw load_error;
  2615. }
  2616. });
  2617. });
  2618. for (const p of server_promises) p.catch(() => {
  2619. });
  2620. for (const p of load_promises) p.catch(() => {
  2621. });
  2622. for (let i = 0; i < nodes.data.length; i += 1) {
  2623. const node = nodes.data[i];
  2624. if (node) {
  2625. try {
  2626. const server_data = await server_promises[i];
  2627. const data = await load_promises[i];
  2628. branch.push({ node, server_data, data });
  2629. } catch (e) {
  2630. const err = normalize_error(e);
  2631. if (err instanceof Redirect) {
  2632. if (state.prerendering && should_prerender_data) {
  2633. const body2 = JSON.stringify({
  2634. type: "redirect",
  2635. location: err.location
  2636. });
  2637. state.prerendering.dependencies.set(data_pathname, {
  2638. response: text(body2),
  2639. body: body2
  2640. });
  2641. }
  2642. return redirect_response(err.status, err.location);
  2643. }
  2644. const status2 = get_status(err);
  2645. const error2 = await handle_error_and_jsonify(event, event_state, options2, err);
  2646. while (i--) {
  2647. if (page.errors[i]) {
  2648. const index = (
  2649. /** @type {number} */
  2650. page.errors[i]
  2651. );
  2652. const node2 = await manifest._.nodes[index]();
  2653. let j = i;
  2654. while (!branch[j]) j -= 1;
  2655. data_serializer.set_max_nodes(j + 1);
  2656. const layouts = compact(branch.slice(0, j + 1));
  2657. const nodes2 = new PageNodes(layouts.map((layout) => layout.node));
  2658. const error_branch = layouts.concat({
  2659. node: node2,
  2660. data: null,
  2661. server_data: null
  2662. });
  2663. return await render_response({
  2664. event,
  2665. event_state,
  2666. options: options2,
  2667. manifest,
  2668. state,
  2669. resolve_opts,
  2670. page_config: {
  2671. ssr: nodes2.ssr(),
  2672. csr: nodes2.csr()
  2673. },
  2674. status: status2,
  2675. error: error2,
  2676. error_components: await load_error_components(
  2677. options2,
  2678. ssr,
  2679. error_branch,
  2680. page,
  2681. manifest
  2682. ),
  2683. branch: error_branch,
  2684. fetched,
  2685. data_serializer
  2686. });
  2687. }
  2688. }
  2689. return static_error_page(options2, status2, error2.message);
  2690. }
  2691. } else {
  2692. branch.push(null);
  2693. }
  2694. }
  2695. if (state.prerendering && data_serializer_json) {
  2696. let { data, chunks } = data_serializer_json.get_data();
  2697. if (chunks) {
  2698. for await (const chunk of chunks) {
  2699. data += chunk;
  2700. }
  2701. }
  2702. state.prerendering.dependencies.set(data_pathname, {
  2703. response: text(data),
  2704. body: data
  2705. });
  2706. }
  2707. return await render_response({
  2708. event,
  2709. event_state,
  2710. options: options2,
  2711. manifest,
  2712. state,
  2713. resolve_opts,
  2714. page_config: {
  2715. csr,
  2716. ssr
  2717. },
  2718. status,
  2719. error: null,
  2720. branch: !ssr ? [] : compact(branch),
  2721. action_result,
  2722. fetched,
  2723. data_serializer: !ssr ? server_data_serializer(event, event_state, options2) : data_serializer,
  2724. error_components: await load_error_components(options2, ssr, branch, page, manifest)
  2725. });
  2726. } catch (e) {
  2727. if (e instanceof Redirect) {
  2728. return redirect_response(e.status, e.location);
  2729. }
  2730. return await respond_with_error({
  2731. event,
  2732. event_state,
  2733. options: options2,
  2734. manifest,
  2735. state,
  2736. status: e instanceof HttpError ? e.status : 500,
  2737. error: e,
  2738. resolve_opts
  2739. });
  2740. }
  2741. }
  2742. async function load_error_components(options2, ssr, branch, page, manifest) {
  2743. let error_components;
  2744. if (options2.server_error_boundaries && ssr) {
  2745. let last_idx = -1;
  2746. error_components = await Promise.all(
  2747. // eslint-disable-next-line @typescript-eslint/await-thenable
  2748. branch.map((b, i) => {
  2749. if (i === 0) return void 0;
  2750. if (!b) return null;
  2751. i--;
  2752. while (i > last_idx + 1 && page.errors[i] === void 0) i -= 1;
  2753. last_idx = i;
  2754. const idx = page.errors[i];
  2755. if (idx == null) return void 0;
  2756. return manifest._.nodes[idx]?.().then((e) => e.component?.()).catch(() => void 0);
  2757. }).filter((e) => e !== null)
  2758. );
  2759. }
  2760. return error_components;
  2761. }
  2762. function once(fn) {
  2763. let done = false;
  2764. let result;
  2765. return () => {
  2766. if (done) return result;
  2767. done = true;
  2768. return result = fn();
  2769. };
  2770. }
  2771. async function render_data(event, event_state, route, options2, manifest, state, invalidated_data_nodes, trailing_slash) {
  2772. if (!route.page) {
  2773. return new Response(void 0, {
  2774. status: 404
  2775. });
  2776. }
  2777. try {
  2778. const node_ids = [...route.page.layouts, route.page.leaf];
  2779. const invalidated = invalidated_data_nodes ?? node_ids.map(() => true);
  2780. let aborted = false;
  2781. const url = new URL(event.url);
  2782. url.pathname = normalize_path(url.pathname, trailing_slash);
  2783. const new_event = { ...event, url };
  2784. const functions = node_ids.map((n, i) => {
  2785. return once(async () => {
  2786. try {
  2787. if (aborted) {
  2788. return (
  2789. /** @type {import('types').ServerDataSkippedNode} */
  2790. {
  2791. type: "skip"
  2792. }
  2793. );
  2794. }
  2795. const node = n == void 0 ? n : await manifest._.nodes[n]();
  2796. return load_server_data({
  2797. event: new_event,
  2798. event_state,
  2799. state,
  2800. node,
  2801. parent: async () => {
  2802. const data2 = {};
  2803. for (let j = 0; j < i; j += 1) {
  2804. const parent = (
  2805. /** @type {import('types').ServerDataNode | null} */
  2806. await functions[j]()
  2807. );
  2808. if (parent) {
  2809. Object.assign(data2, parent.data);
  2810. }
  2811. }
  2812. return data2;
  2813. }
  2814. });
  2815. } catch (e) {
  2816. aborted = true;
  2817. throw e;
  2818. }
  2819. });
  2820. });
  2821. const promises = functions.map(async (fn, i) => {
  2822. if (!invalidated[i]) {
  2823. return (
  2824. /** @type {import('types').ServerDataSkippedNode} */
  2825. {
  2826. type: "skip"
  2827. }
  2828. );
  2829. }
  2830. return fn();
  2831. });
  2832. let length = promises.length;
  2833. const nodes = await Promise.all(
  2834. promises.map(
  2835. (p, i) => p.catch(async (error2) => {
  2836. if (error2 instanceof Redirect) {
  2837. throw error2;
  2838. }
  2839. length = Math.min(length, i + 1);
  2840. return (
  2841. /** @type {import('types').ServerErrorNode} */
  2842. {
  2843. type: "error",
  2844. error: await handle_error_and_jsonify(event, event_state, options2, error2),
  2845. status: error2 instanceof HttpError || error2 instanceof SvelteKitError ? error2.status : void 0
  2846. }
  2847. );
  2848. })
  2849. )
  2850. );
  2851. const data_serializer = server_data_serializer_json(event, event_state, options2);
  2852. for (let i = 0; i < nodes.length; i++) data_serializer.add_node(i, nodes[i]);
  2853. const { data, chunks } = data_serializer.get_data();
  2854. if (!chunks) {
  2855. return json_response(data);
  2856. }
  2857. return new Response(
  2858. new ReadableStream({
  2859. async start(controller) {
  2860. controller.enqueue(text_encoder.encode(data));
  2861. for await (const chunk of chunks) {
  2862. controller.enqueue(text_encoder.encode(chunk));
  2863. }
  2864. controller.close();
  2865. },
  2866. type: "bytes"
  2867. }),
  2868. {
  2869. headers: {
  2870. // we use a proprietary content type to prevent buffering.
  2871. // the `text` prefix makes it inspectable
  2872. "content-type": "text/sveltekit-data",
  2873. "cache-control": "private, no-store"
  2874. }
  2875. }
  2876. );
  2877. } catch (e) {
  2878. const error2 = normalize_error(e);
  2879. if (error2 instanceof Redirect) {
  2880. return redirect_json_response(error2);
  2881. } else {
  2882. return json_response(await handle_error_and_jsonify(event, event_state, options2, error2), 500);
  2883. }
  2884. }
  2885. }
  2886. function json_response(json2, status = 200) {
  2887. return text(typeof json2 === "string" ? json2 : JSON.stringify(json2), {
  2888. status,
  2889. headers: {
  2890. "content-type": "application/json",
  2891. "cache-control": "private, no-store"
  2892. }
  2893. });
  2894. }
  2895. function redirect_json_response(redirect) {
  2896. return json_response(
  2897. /** @type {import('types').ServerRedirectNode} */
  2898. {
  2899. type: "redirect",
  2900. location: redirect.location
  2901. }
  2902. );
  2903. }
  2904. const INVALID_COOKIE_CHARACTER_REGEX = /[\x00-\x1F\x7F()<>@,;:"/[\]?={} \t]/;
  2905. function validate_options(options2) {
  2906. if (options2?.path === void 0) {
  2907. throw new Error("You must specify a `path` when setting, deleting or serializing cookies");
  2908. }
  2909. }
  2910. function generate_cookie_key(domain, path, name) {
  2911. return `${domain || ""}${path}?${encodeURIComponent(name)}`;
  2912. }
  2913. function get_cookies(request, url) {
  2914. const header = request.headers.get("cookie") ?? "";
  2915. const initial_cookies = parse(header, { decode: (value) => value });
  2916. let normalized_url;
  2917. const new_cookies = /* @__PURE__ */ new Map();
  2918. const defaults = {
  2919. httpOnly: true,
  2920. sameSite: "lax",
  2921. secure: url.hostname === "localhost" && url.protocol === "http:" ? false : true
  2922. };
  2923. const cookies = {
  2924. // The JSDoc param annotations appearing below for get, set and delete
  2925. // are necessary to expose the `cookie` library types to
  2926. // typescript users. `@type {import('@sveltejs/kit').Cookies}` above is not
  2927. // sufficient to do so.
  2928. /**
  2929. * @param {string} name
  2930. * @param {import('cookie').CookieParseOptions} [opts]
  2931. */
  2932. get(name, opts) {
  2933. const best_match = Array.from(new_cookies.values()).filter((c) => {
  2934. return c.name === name && domain_matches(url.hostname, c.options.domain) && path_matches(url.pathname, c.options.path);
  2935. }).sort((a, b) => b.options.path.length - a.options.path.length)[0];
  2936. if (best_match) {
  2937. return best_match.options.maxAge === 0 ? void 0 : best_match.value;
  2938. }
  2939. const req_cookies = parse(header, { decode: opts?.decode });
  2940. const cookie = req_cookies[name];
  2941. return cookie;
  2942. },
  2943. /**
  2944. * @param {import('cookie').CookieParseOptions} [opts]
  2945. */
  2946. getAll(opts) {
  2947. const cookies2 = parse(header, { decode: opts?.decode });
  2948. const lookup = /* @__PURE__ */ new Map();
  2949. for (const c of new_cookies.values()) {
  2950. if (domain_matches(url.hostname, c.options.domain) && path_matches(url.pathname, c.options.path)) {
  2951. const existing = lookup.get(c.name);
  2952. if (!existing || c.options.path.length > existing.options.path.length) {
  2953. lookup.set(c.name, c);
  2954. }
  2955. }
  2956. }
  2957. for (const c of lookup.values()) {
  2958. cookies2[c.name] = c.value;
  2959. }
  2960. return Object.entries(cookies2).map(([name, value]) => ({ name, value }));
  2961. },
  2962. /**
  2963. * @param {string} name
  2964. * @param {string} value
  2965. * @param {import('./page/types.js').Cookie['options']} options
  2966. */
  2967. set(name, value, options2) {
  2968. const illegal_characters = name.match(INVALID_COOKIE_CHARACTER_REGEX);
  2969. if (illegal_characters) {
  2970. console.warn(
  2971. `The cookie name "${name}" will be invalid in SvelteKit 3.0 as it contains ${illegal_characters.join(
  2972. " and "
  2973. )}. See RFC 2616 for more details https://datatracker.ietf.org/doc/html/rfc2616#section-2.2`
  2974. );
  2975. }
  2976. validate_options(options2);
  2977. set_internal(name, value, { ...defaults, ...options2 });
  2978. },
  2979. /**
  2980. * @param {string} name
  2981. * @param {import('./page/types.js').Cookie['options']} options
  2982. */
  2983. delete(name, options2) {
  2984. validate_options(options2);
  2985. cookies.set(name, "", { ...options2, maxAge: 0 });
  2986. },
  2987. /**
  2988. * @param {string} name
  2989. * @param {string} value
  2990. * @param {import('./page/types.js').Cookie['options']} options
  2991. */
  2992. serialize(name, value, options2) {
  2993. validate_options(options2);
  2994. let path = options2.path;
  2995. if (!options2.domain || options2.domain === url.hostname) {
  2996. if (!normalized_url) {
  2997. throw new Error("Cannot serialize cookies until after the route is determined");
  2998. }
  2999. path = resolve(normalized_url, path);
  3000. }
  3001. return serialize(name, value, { ...defaults, ...options2, path });
  3002. }
  3003. };
  3004. function get_cookie_header(destination, header2) {
  3005. const combined_cookies = {
  3006. // cookies sent by the user agent have lowest precedence
  3007. ...initial_cookies
  3008. };
  3009. for (const cookie of new_cookies.values()) {
  3010. if (!domain_matches(destination.hostname, cookie.options.domain)) continue;
  3011. if (!path_matches(destination.pathname, cookie.options.path)) continue;
  3012. const encoder = cookie.options.encode || encodeURIComponent;
  3013. combined_cookies[cookie.name] = encoder(cookie.value);
  3014. }
  3015. if (header2) {
  3016. const parsed = parse(header2, { decode: (value) => value });
  3017. for (const name in parsed) {
  3018. combined_cookies[name] = parsed[name];
  3019. }
  3020. }
  3021. return Object.entries(combined_cookies).map(([name, value]) => `${name}=${value}`).join("; ");
  3022. }
  3023. const internal_queue = [];
  3024. function set_internal(name, value, options2) {
  3025. if (!normalized_url) {
  3026. internal_queue.push(() => set_internal(name, value, options2));
  3027. return;
  3028. }
  3029. let path = options2.path;
  3030. if (!options2.domain || options2.domain === url.hostname) {
  3031. path = resolve(normalized_url, path);
  3032. }
  3033. const cookie_key = generate_cookie_key(options2.domain, path, name);
  3034. const cookie = { name, value, options: { ...options2, path } };
  3035. new_cookies.set(cookie_key, cookie);
  3036. }
  3037. function set_trailing_slash(trailing_slash) {
  3038. normalized_url = normalize_path(url.pathname, trailing_slash);
  3039. internal_queue.forEach((fn) => fn());
  3040. }
  3041. return { cookies, new_cookies, get_cookie_header, set_internal, set_trailing_slash };
  3042. }
  3043. function domain_matches(hostname, constraint) {
  3044. if (!constraint) return true;
  3045. const normalized = constraint[0] === "." ? constraint.slice(1) : constraint;
  3046. if (hostname === normalized) return true;
  3047. return hostname.endsWith("." + normalized);
  3048. }
  3049. function path_matches(path, constraint) {
  3050. if (!constraint) return true;
  3051. const normalized = constraint.endsWith("/") ? constraint.slice(0, -1) : constraint;
  3052. if (path === normalized) return true;
  3053. return path.startsWith(normalized + "/");
  3054. }
  3055. function add_cookies_to_headers(headers2, cookies) {
  3056. for (const new_cookie of cookies) {
  3057. const { name, value, options: options2 } = new_cookie;
  3058. headers2.append("set-cookie", serialize(name, value, options2));
  3059. if (options2.path.endsWith(".html")) {
  3060. const path = add_data_suffix(options2.path);
  3061. headers2.append("set-cookie", serialize(name, value, { ...options2, path }));
  3062. }
  3063. }
  3064. }
  3065. function create_fetch({ event, options: options2, manifest, state, get_cookie_header, set_internal }) {
  3066. const server_fetch = async (info, init2) => {
  3067. const original_request = normalize_fetch_input(info, init2, event.url);
  3068. let mode = (info instanceof Request ? info.mode : init2?.mode) ?? "cors";
  3069. let credentials = (info instanceof Request ? info.credentials : init2?.credentials) ?? "same-origin";
  3070. return options2.hooks.handleFetch({
  3071. event,
  3072. request: original_request,
  3073. fetch: async (info2, init3) => {
  3074. const request = normalize_fetch_input(info2, init3, event.url);
  3075. const url = new URL(request.url);
  3076. if (!request.headers.has("origin")) {
  3077. request.headers.set("origin", event.url.origin);
  3078. }
  3079. if (info2 !== original_request) {
  3080. mode = (info2 instanceof Request ? info2.mode : init3?.mode) ?? "cors";
  3081. credentials = (info2 instanceof Request ? info2.credentials : init3?.credentials) ?? "same-origin";
  3082. }
  3083. if ((request.method === "GET" || request.method === "HEAD") && (mode === "no-cors" && url.origin !== event.url.origin || url.origin === event.url.origin)) {
  3084. request.headers.delete("origin");
  3085. }
  3086. const decoded = decodeURIComponent(url.pathname);
  3087. if (url.origin !== event.url.origin || base && decoded !== base && !decoded.startsWith(`${base}/`)) {
  3088. if (`.${url.hostname}`.endsWith(`.${event.url.hostname}`) && credentials !== "omit") {
  3089. const cookie = get_cookie_header(url, request.headers.get("cookie"));
  3090. if (cookie) request.headers.set("cookie", cookie);
  3091. }
  3092. return fetch(request);
  3093. }
  3094. const prefix = assets || base;
  3095. const filename = (decoded.startsWith(prefix) ? decoded.slice(prefix.length) : decoded).slice(1);
  3096. const filename_html = `${filename}/index.html`;
  3097. const is_asset = manifest.assets.has(filename) || filename in manifest._.server_assets;
  3098. const is_asset_html = manifest.assets.has(filename_html) || filename_html in manifest._.server_assets;
  3099. if (is_asset || is_asset_html) {
  3100. const file = is_asset ? filename : filename_html;
  3101. if (state.read) {
  3102. const type = is_asset ? manifest.mimeTypes[filename.slice(filename.lastIndexOf("."))] : "text/html";
  3103. return new Response(state.read(file), {
  3104. headers: type ? { "content-type": type } : {}
  3105. });
  3106. } else if (read_implementation && file in manifest._.server_assets) {
  3107. const length = manifest._.server_assets[file];
  3108. const type = manifest.mimeTypes[file.slice(file.lastIndexOf("."))];
  3109. return new Response(read_implementation(file), {
  3110. headers: {
  3111. "Content-Length": "" + length,
  3112. "Content-Type": type
  3113. }
  3114. });
  3115. }
  3116. return await fetch(request);
  3117. }
  3118. if (has_prerendered_path(manifest, base + decoded)) {
  3119. return await fetch(request);
  3120. }
  3121. if (credentials !== "omit") {
  3122. const cookie = get_cookie_header(url, request.headers.get("cookie"));
  3123. if (cookie) {
  3124. request.headers.set("cookie", cookie);
  3125. }
  3126. const authorization = event.request.headers.get("authorization");
  3127. if (authorization && !request.headers.has("authorization")) {
  3128. request.headers.set("authorization", authorization);
  3129. }
  3130. }
  3131. if (!request.headers.has("accept")) {
  3132. request.headers.set("accept", "*/*");
  3133. }
  3134. if (!request.headers.has("accept-language")) {
  3135. request.headers.set(
  3136. "accept-language",
  3137. /** @type {string} */
  3138. event.request.headers.get("accept-language")
  3139. );
  3140. }
  3141. const response = await internal_fetch(request, options2, manifest, state);
  3142. const set_cookie = response.headers.get("set-cookie");
  3143. if (set_cookie) {
  3144. for (const str of set_cookie_parser.splitCookiesString(set_cookie)) {
  3145. const { name, value, ...options3 } = set_cookie_parser.parseString(str, {
  3146. decodeValues: false
  3147. });
  3148. const path = options3.path ?? (url.pathname.split("/").slice(0, -1).join("/") || "/");
  3149. set_internal(name, value, {
  3150. path,
  3151. encode: (value2) => value2,
  3152. .../** @type {import('cookie').CookieSerializeOptions} */
  3153. options3
  3154. });
  3155. }
  3156. }
  3157. return response;
  3158. }
  3159. });
  3160. };
  3161. return (input, init2) => {
  3162. const response = server_fetch(input, init2);
  3163. response.catch(() => {
  3164. });
  3165. return response;
  3166. };
  3167. }
  3168. function normalize_fetch_input(info, init2, url) {
  3169. if (info instanceof Request) {
  3170. return info;
  3171. }
  3172. return new Request(typeof info === "string" ? new URL(info, url) : info, init2);
  3173. }
  3174. async function internal_fetch(request, options2, manifest, state) {
  3175. if (request.signal) {
  3176. if (request.signal.aborted) {
  3177. throw new DOMException("The operation was aborted.", "AbortError");
  3178. }
  3179. let remove_abort_listener = () => {
  3180. };
  3181. const abort_promise = new Promise((_, reject) => {
  3182. const on_abort = () => {
  3183. reject(new DOMException("The operation was aborted.", "AbortError"));
  3184. };
  3185. request.signal.addEventListener("abort", on_abort, { once: true });
  3186. remove_abort_listener = () => request.signal.removeEventListener("abort", on_abort);
  3187. });
  3188. const result = await Promise.race([
  3189. respond(request, options2, manifest, {
  3190. ...state,
  3191. depth: state.depth + 1
  3192. }),
  3193. abort_promise
  3194. ]);
  3195. remove_abort_listener();
  3196. return result;
  3197. } else {
  3198. return await respond(request, options2, manifest, {
  3199. ...state,
  3200. depth: state.depth + 1
  3201. });
  3202. }
  3203. }
  3204. let body;
  3205. let etag;
  3206. let headers;
  3207. function get_public_env(request) {
  3208. body ??= `export const env=${JSON.stringify(public_env)}`;
  3209. etag ??= `W/${Date.now()}`;
  3210. headers ??= new Headers({
  3211. "content-type": "application/javascript; charset=utf-8",
  3212. etag
  3213. });
  3214. if (request.headers.get("if-none-match") === etag) {
  3215. return new Response(void 0, { status: 304, headers });
  3216. }
  3217. return new Response(body, { headers });
  3218. }
  3219. const default_transform = ({ html }) => html;
  3220. const default_filter = () => false;
  3221. const default_preload = ({ type }) => type === "js" || type === "css";
  3222. const page_methods = /* @__PURE__ */ new Set(["GET", "HEAD", "POST"]);
  3223. const allowed_page_methods = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
  3224. let warned_on_devtools_json_request = false;
  3225. const respond = propagate_context(internal_respond);
  3226. async function internal_respond(request, options2, manifest, state) {
  3227. const url = new URL(request.url);
  3228. const is_route_resolution_request = has_resolution_suffix(url.pathname);
  3229. const is_data_request = has_data_suffix(url.pathname);
  3230. const remote_id = get_remote_id(url);
  3231. {
  3232. const request_origin = request.headers.get("origin");
  3233. if (remote_id) {
  3234. if (request.method !== "GET" && request_origin !== url.origin) {
  3235. const message = "Cross-site remote requests are forbidden";
  3236. return json({ message }, { status: 403 });
  3237. }
  3238. } else if (options2.csrf_check_origin) {
  3239. 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));
  3240. if (forbidden) {
  3241. const message = `Cross-site ${request.method} form submissions are forbidden`;
  3242. const opts = { status: 403 };
  3243. if (request.headers.get("accept") === "application/json") {
  3244. return json({ message }, opts);
  3245. }
  3246. return text(message, opts);
  3247. }
  3248. }
  3249. }
  3250. if (options2.hash_routing && url.pathname !== base + "/" && url.pathname !== "/[fallback]") {
  3251. return text("Not found", { status: 404 });
  3252. }
  3253. let invalidated_data_nodes;
  3254. if (is_route_resolution_request) {
  3255. url.pathname = strip_resolution_suffix(url.pathname);
  3256. } else if (is_data_request) {
  3257. url.pathname = strip_data_suffix(url.pathname) + (url.searchParams.get(TRAILING_SLASH_PARAM) === "1" ? "/" : "") || "/";
  3258. url.searchParams.delete(TRAILING_SLASH_PARAM);
  3259. invalidated_data_nodes = url.searchParams.get(INVALIDATED_PARAM)?.split("").map((node) => node === "1");
  3260. url.searchParams.delete(INVALIDATED_PARAM);
  3261. } else if (remote_id) {
  3262. url.pathname = request.headers.get("x-sveltekit-pathname") ?? base;
  3263. url.search = request.headers.get("x-sveltekit-search") ?? "";
  3264. }
  3265. const headers2 = {};
  3266. const { cookies, new_cookies, get_cookie_header, set_internal, set_trailing_slash } = get_cookies(
  3267. request,
  3268. url
  3269. );
  3270. const event_state = {
  3271. prerendering: state.prerendering,
  3272. transport: options2.hooks.transport,
  3273. handleValidationError: options2.hooks.handleValidationError,
  3274. tracing: {
  3275. record_span
  3276. },
  3277. remote: {
  3278. data: null,
  3279. forms: null,
  3280. /** A map of remote function key to corresponding single-flight-mutation promise */
  3281. refreshes: null,
  3282. /** A map of remote function ID to payloads requested for refreshing by the client */
  3283. requested: null,
  3284. /**
  3285. * A map of remote function ID to objects that have passed validation;
  3286. * used to prevent revalidating parameters returned from `requested`
  3287. */
  3288. validated: null
  3289. },
  3290. is_in_remote_function: false,
  3291. is_in_render: false,
  3292. is_in_universal_load: false
  3293. };
  3294. const event = {
  3295. cookies,
  3296. // @ts-expect-error `fetch` needs to be created after the `event` itself
  3297. fetch: null,
  3298. getClientAddress: state.getClientAddress || (() => {
  3299. throw new Error(
  3300. `${"@sveltejs/adapter-static"} does not specify getClientAddress. Please raise an issue`
  3301. );
  3302. }),
  3303. locals: {},
  3304. params: {},
  3305. platform: state.platform,
  3306. request,
  3307. route: { id: null },
  3308. setHeaders: (new_headers) => {
  3309. for (const key2 in new_headers) {
  3310. const lower = key2.toLowerCase();
  3311. const value = new_headers[key2];
  3312. if (lower === "set-cookie") {
  3313. throw new Error(
  3314. "Use `event.cookies.set(name, value, options)` instead of `event.setHeaders` to set cookies"
  3315. );
  3316. } else if (lower in headers2) {
  3317. if (lower === "server-timing") {
  3318. headers2[lower] += ", " + value;
  3319. } else {
  3320. throw new Error(`"${key2}" header is already set`);
  3321. }
  3322. } else {
  3323. headers2[lower] = value;
  3324. if (state.prerendering && lower === "cache-control") {
  3325. state.prerendering.cache = /** @type {string} */
  3326. value;
  3327. }
  3328. }
  3329. }
  3330. },
  3331. url,
  3332. isDataRequest: is_data_request,
  3333. isSubRequest: state.depth > 0,
  3334. isRemoteRequest: !!remote_id
  3335. };
  3336. event.fetch = create_fetch({
  3337. event,
  3338. options: options2,
  3339. manifest,
  3340. state,
  3341. get_cookie_header,
  3342. set_internal
  3343. });
  3344. if (state.emulator?.platform) {
  3345. event.platform = await state.emulator.platform({
  3346. config: {},
  3347. prerender: !!state.prerendering?.fallback
  3348. });
  3349. }
  3350. let resolved_path = url.pathname;
  3351. if (!remote_id) {
  3352. const prerendering_reroute_state = state.prerendering?.inside_reroute;
  3353. try {
  3354. if (state.prerendering) state.prerendering.inside_reroute = true;
  3355. resolved_path = await options2.hooks.reroute({ url: new URL(url), fetch: event.fetch }) ?? url.pathname;
  3356. } catch {
  3357. return text("Internal Server Error", {
  3358. status: 500
  3359. });
  3360. } finally {
  3361. if (state.prerendering) state.prerendering.inside_reroute = prerendering_reroute_state;
  3362. }
  3363. }
  3364. try {
  3365. resolved_path = decode_pathname(resolved_path);
  3366. } catch {
  3367. return text("Malformed URI", { status: 400 });
  3368. }
  3369. if (
  3370. // the resolved path has been decoded so it should be compared to the decoded url pathname
  3371. resolved_path !== decode_pathname(url.pathname) && !state.prerendering?.fallback && has_prerendered_path(manifest, resolved_path)
  3372. ) {
  3373. const url2 = new URL(request.url);
  3374. url2.pathname = is_data_request ? add_data_suffix(resolved_path) : is_route_resolution_request ? add_resolution_suffix(resolved_path) : resolved_path;
  3375. try {
  3376. const response = await fetch(url2, request);
  3377. const headers22 = new Headers(response.headers);
  3378. if (headers22.has("content-encoding")) {
  3379. headers22.delete("content-encoding");
  3380. headers22.delete("content-length");
  3381. }
  3382. return new Response(response.body, {
  3383. headers: headers22,
  3384. status: response.status,
  3385. statusText: response.statusText
  3386. });
  3387. } catch (error2) {
  3388. return await handle_fatal_error(event, event_state, options2, error2);
  3389. }
  3390. }
  3391. let route = null;
  3392. if (base && !state.prerendering?.fallback) {
  3393. if (!resolved_path.startsWith(base)) {
  3394. return text("Not found", { status: 404 });
  3395. }
  3396. resolved_path = resolved_path.slice(base.length) || "/";
  3397. }
  3398. if (is_route_resolution_request) {
  3399. return resolve_route(resolved_path, new URL(request.url), manifest);
  3400. }
  3401. if (resolved_path === `/${app_dir}/env.js`) {
  3402. return get_public_env(request);
  3403. }
  3404. if (!remote_id && resolved_path.startsWith(`/${app_dir}`)) {
  3405. const headers22 = new Headers();
  3406. headers22.set("cache-control", "public, max-age=0, must-revalidate");
  3407. return text("Not found", { status: 404, headers: headers22 });
  3408. }
  3409. if (!state.prerendering?.fallback) {
  3410. const matchers = await manifest._.matchers();
  3411. const result = find_route(resolved_path, manifest._.routes, matchers);
  3412. if (result) {
  3413. route = result.route;
  3414. event.route = { id: route.id };
  3415. event.params = result.params;
  3416. }
  3417. }
  3418. let resolve_opts = {
  3419. transformPageChunk: default_transform,
  3420. filterSerializedResponseHeaders: default_filter,
  3421. preload: default_preload
  3422. };
  3423. let trailing_slash = "never";
  3424. try {
  3425. const page_nodes = route?.page ? new PageNodes(await load_page_nodes(route.page, manifest)) : void 0;
  3426. if (route && !remote_id) {
  3427. if (url.pathname === base || url.pathname === base + "/") {
  3428. trailing_slash = "always";
  3429. } else if (page_nodes) {
  3430. if (BROWSER) ;
  3431. trailing_slash = page_nodes.trailing_slash();
  3432. } else if (route.endpoint) {
  3433. const node = await route.endpoint();
  3434. trailing_slash = node.trailingSlash ?? "never";
  3435. if (BROWSER) ;
  3436. }
  3437. if (!is_data_request) {
  3438. const normalized = normalize_path(url.pathname, trailing_slash);
  3439. if (normalized !== url.pathname && !state.prerendering?.fallback) {
  3440. return new Response(void 0, {
  3441. status: 308,
  3442. headers: {
  3443. "x-sveltekit-normalize": "1",
  3444. location: (
  3445. // ensure paths starting with '//' are not treated as protocol-relative
  3446. (normalized.startsWith("//") ? url.origin + normalized : normalized) + (url.search === "?" ? "" : url.search)
  3447. )
  3448. }
  3449. });
  3450. }
  3451. }
  3452. if (state.before_handle || state.emulator?.platform) {
  3453. let config = {};
  3454. let prerender = false;
  3455. if (route.endpoint) {
  3456. const node = await route.endpoint();
  3457. config = node.config ?? config;
  3458. prerender = node.prerender ?? prerender;
  3459. } else if (page_nodes) {
  3460. config = page_nodes.get_config() ?? config;
  3461. prerender = page_nodes.prerender();
  3462. }
  3463. if (state.before_handle) {
  3464. state.before_handle(event, config, prerender);
  3465. }
  3466. if (state.emulator?.platform) {
  3467. event.platform = await state.emulator.platform({ config, prerender });
  3468. }
  3469. }
  3470. }
  3471. set_trailing_slash(trailing_slash);
  3472. if (state.prerendering && !state.prerendering.fallback && !state.prerendering.inside_reroute) {
  3473. disable_search(url);
  3474. }
  3475. const response = await record_span({
  3476. name: "sveltekit.handle.root",
  3477. attributes: {
  3478. "http.route": event.route.id || "unknown",
  3479. "http.method": event.request.method,
  3480. "http.url": event.url.href,
  3481. "sveltekit.is_data_request": is_data_request,
  3482. "sveltekit.is_sub_request": event.isSubRequest
  3483. },
  3484. fn: async (root_span) => {
  3485. const traced_event = {
  3486. ...event,
  3487. tracing: {
  3488. enabled: false,
  3489. root: root_span,
  3490. current: root_span
  3491. }
  3492. };
  3493. return await with_request_store(
  3494. { event: traced_event, state: event_state },
  3495. () => options2.hooks.handle({
  3496. event: traced_event,
  3497. resolve: (event2, opts) => {
  3498. return record_span({
  3499. name: "sveltekit.resolve",
  3500. attributes: {
  3501. "http.route": event2.route.id || "unknown"
  3502. },
  3503. fn: (resolve_span) => {
  3504. return with_request_store(
  3505. null,
  3506. () => resolve2(merge_tracing(event2, resolve_span), page_nodes, opts).then(
  3507. (response2) => {
  3508. for (const key2 in headers2) {
  3509. const value = headers2[key2];
  3510. response2.headers.set(
  3511. key2,
  3512. /** @type {string} */
  3513. value
  3514. );
  3515. }
  3516. add_cookies_to_headers(response2.headers, new_cookies.values());
  3517. if (state.prerendering && event2.route.id !== null) {
  3518. response2.headers.set("x-sveltekit-routeid", encodeURI(event2.route.id));
  3519. }
  3520. resolve_span.setAttributes({
  3521. "http.response.status_code": response2.status,
  3522. "http.response.body.size": response2.headers.get("content-length") || "unknown"
  3523. });
  3524. return response2;
  3525. }
  3526. )
  3527. );
  3528. }
  3529. });
  3530. }
  3531. })
  3532. );
  3533. }
  3534. });
  3535. if (response.status === 200 && response.headers.has("etag")) {
  3536. let if_none_match_value = request.headers.get("if-none-match");
  3537. if (if_none_match_value?.startsWith('W/"')) {
  3538. if_none_match_value = if_none_match_value.substring(2);
  3539. }
  3540. const etag2 = (
  3541. /** @type {string} */
  3542. response.headers.get("etag")
  3543. );
  3544. if (if_none_match_value === etag2) {
  3545. const headers22 = new Headers({ etag: etag2 });
  3546. for (const key2 of [
  3547. "cache-control",
  3548. "content-location",
  3549. "date",
  3550. "expires",
  3551. "vary",
  3552. "set-cookie"
  3553. ]) {
  3554. const value = response.headers.get(key2);
  3555. if (value) headers22.set(key2, value);
  3556. }
  3557. return new Response(void 0, {
  3558. status: 304,
  3559. headers: headers22
  3560. });
  3561. }
  3562. }
  3563. if (is_data_request && response.status >= 300 && response.status <= 308) {
  3564. const location = response.headers.get("location");
  3565. if (location) {
  3566. return redirect_json_response(new Redirect(
  3567. /** @type {any} */
  3568. response.status,
  3569. location
  3570. ));
  3571. }
  3572. }
  3573. return response;
  3574. } catch (e) {
  3575. if (e instanceof Redirect) {
  3576. 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);
  3577. add_cookies_to_headers(response.headers, new_cookies.values());
  3578. return response;
  3579. }
  3580. return await handle_fatal_error(event, event_state, options2, e);
  3581. }
  3582. async function resolve2(event2, page_nodes, opts) {
  3583. try {
  3584. if (opts) {
  3585. resolve_opts = {
  3586. transformPageChunk: opts.transformPageChunk || default_transform,
  3587. filterSerializedResponseHeaders: opts.filterSerializedResponseHeaders || default_filter,
  3588. preload: opts.preload || default_preload
  3589. };
  3590. }
  3591. if (options2.hash_routing || state.prerendering?.fallback) {
  3592. return await render_response({
  3593. event: event2,
  3594. event_state,
  3595. options: options2,
  3596. manifest,
  3597. state,
  3598. page_config: { ssr: false, csr: true },
  3599. status: 200,
  3600. error: null,
  3601. branch: [],
  3602. fetched: [],
  3603. resolve_opts,
  3604. data_serializer: server_data_serializer(event2, event_state, options2)
  3605. });
  3606. }
  3607. if (remote_id) {
  3608. return await handle_remote_call(event2, event_state, options2, manifest, remote_id);
  3609. }
  3610. if (route) {
  3611. const method = (
  3612. /** @type {import('types').HttpMethod} */
  3613. event2.request.method
  3614. );
  3615. let response2;
  3616. if (is_data_request) {
  3617. response2 = await render_data(
  3618. event2,
  3619. event_state,
  3620. route,
  3621. options2,
  3622. manifest,
  3623. state,
  3624. invalidated_data_nodes,
  3625. trailing_slash
  3626. );
  3627. } else if (route.endpoint && (!route.page || is_endpoint_request(event2))) {
  3628. response2 = await render_endpoint(event2, event_state, await route.endpoint(), state);
  3629. } else if (route.page) {
  3630. if (!page_nodes) {
  3631. throw new Error("page_nodes not found. This should never happen");
  3632. } else if (page_methods.has(method)) {
  3633. response2 = await render_page(
  3634. event2,
  3635. event_state,
  3636. route.page,
  3637. options2,
  3638. manifest,
  3639. state,
  3640. page_nodes,
  3641. resolve_opts
  3642. );
  3643. } else {
  3644. const allowed_methods = new Set(allowed_page_methods);
  3645. const node = await manifest._.nodes[route.page.leaf]();
  3646. if (node?.server?.actions) {
  3647. allowed_methods.add("POST");
  3648. }
  3649. if (method === "OPTIONS") {
  3650. response2 = new Response(null, {
  3651. status: 204,
  3652. headers: {
  3653. allow: Array.from(allowed_methods.values()).join(", ")
  3654. }
  3655. });
  3656. } else {
  3657. const mod = [...allowed_methods].reduce(
  3658. (acc, curr) => {
  3659. acc[curr] = true;
  3660. return acc;
  3661. },
  3662. /** @type {Record<string, any>} */
  3663. {}
  3664. );
  3665. response2 = method_not_allowed(mod, method);
  3666. }
  3667. }
  3668. } else {
  3669. throw new Error("Route is neither page nor endpoint. This should never happen");
  3670. }
  3671. if (request.method === "GET" && route.page && route.endpoint) {
  3672. const vary = response2.headers.get("vary")?.split(",")?.map((v) => v.trim().toLowerCase());
  3673. if (!(vary?.includes("accept") || vary?.includes("*"))) {
  3674. response2 = new Response(response2.body, {
  3675. status: response2.status,
  3676. statusText: response2.statusText,
  3677. headers: new Headers(response2.headers)
  3678. });
  3679. response2.headers.append("Vary", "Accept");
  3680. }
  3681. }
  3682. return response2;
  3683. }
  3684. if (state.error && event2.isSubRequest) {
  3685. const headers22 = new Headers(request.headers);
  3686. headers22.set("x-sveltekit-error", "true");
  3687. return await fetch(request, { headers: headers22 });
  3688. }
  3689. if (state.error) {
  3690. return text("Internal Server Error", {
  3691. status: 500
  3692. });
  3693. }
  3694. if (state.depth === 0) {
  3695. if (BROWSER && event2.url.pathname === "/.well-known/appspecific/com.chrome.devtools.json") ;
  3696. return await respond_with_error({
  3697. event: event2,
  3698. event_state,
  3699. options: options2,
  3700. manifest,
  3701. state,
  3702. status: 404,
  3703. error: new SvelteKitError(404, "Not Found", `Not found: ${event2.url.pathname}`),
  3704. resolve_opts
  3705. });
  3706. }
  3707. if (state.prerendering) {
  3708. return text("not found", { status: 404 });
  3709. }
  3710. const response = await fetch(request);
  3711. return new Response(response.body, response);
  3712. } catch (e) {
  3713. return await handle_fatal_error(event2, event_state, options2, e);
  3714. } finally {
  3715. event2.cookies.set = () => {
  3716. throw new Error("Cannot use `cookies.set(...)` after the response has been generated");
  3717. };
  3718. event2.setHeaders = () => {
  3719. throw new Error("Cannot use `setHeaders(...)` after the response has been generated");
  3720. };
  3721. }
  3722. }
  3723. }
  3724. function load_page_nodes(page, manifest) {
  3725. return Promise.all([
  3726. // we use == here rather than === because [undefined] serializes as "[null]"
  3727. ...page.layouts.map((n) => n == void 0 ? n : manifest._.nodes[n]()),
  3728. manifest._.nodes[page.leaf]()
  3729. ]);
  3730. }
  3731. function propagate_context(fn) {
  3732. return async (req, ...rest) => {
  3733. {
  3734. return fn(req, ...rest);
  3735. }
  3736. };
  3737. }
  3738. function filter_env(env, allowed, disallowed) {
  3739. return Object.fromEntries(
  3740. Object.entries(env).filter(
  3741. ([k]) => k.startsWith(allowed) && (disallowed === "" || !k.startsWith(disallowed))
  3742. )
  3743. );
  3744. }
  3745. function set_app(value) {
  3746. }
  3747. let init_promise;
  3748. let current = null;
  3749. class Server {
  3750. /** @type {import('types').SSROptions} */
  3751. #options;
  3752. /** @type {import('@sveltejs/kit').SSRManifest} */
  3753. #manifest;
  3754. /** @param {import('@sveltejs/kit').SSRManifest} manifest */
  3755. constructor(manifest) {
  3756. this.#options = options;
  3757. this.#manifest = manifest;
  3758. if (IN_WEBCONTAINER) {
  3759. const respond2 = this.respond.bind(this);
  3760. this.respond = async (...args) => {
  3761. const { promise, resolve: resolve2 } = (
  3762. /** @type {PromiseWithResolvers<void>} */
  3763. with_resolvers()
  3764. );
  3765. const previous = current;
  3766. current = promise;
  3767. await previous;
  3768. return respond2(...args).finally(resolve2);
  3769. };
  3770. }
  3771. }
  3772. /**
  3773. * @param {import('@sveltejs/kit').ServerInitOptions} opts
  3774. */
  3775. async init({ env, read }) {
  3776. const { env_public_prefix, env_private_prefix } = this.#options;
  3777. set_private_env(filter_env(env, env_private_prefix, env_public_prefix));
  3778. set_public_env(filter_env(env, env_public_prefix, env_private_prefix));
  3779. if (read) {
  3780. const wrapped_read = (file) => {
  3781. const result = read(file);
  3782. if (result instanceof ReadableStream) {
  3783. return result;
  3784. } else {
  3785. return new ReadableStream({
  3786. async start(controller) {
  3787. try {
  3788. const stream = await Promise.resolve(result);
  3789. if (!stream) {
  3790. controller.close();
  3791. return;
  3792. }
  3793. const reader = stream.getReader();
  3794. while (true) {
  3795. const { done, value } = await reader.read();
  3796. if (done) break;
  3797. controller.enqueue(value);
  3798. }
  3799. controller.close();
  3800. } catch (error2) {
  3801. controller.error(error2);
  3802. }
  3803. }
  3804. });
  3805. }
  3806. };
  3807. set_read_implementation(wrapped_read);
  3808. }
  3809. await (init_promise ??= (async () => {
  3810. try {
  3811. const module = await get_hooks();
  3812. this.#options.hooks = {
  3813. handle: module.handle || (({ event, resolve: resolve2 }) => resolve2(event)),
  3814. handleError: module.handleError || (({ status, error: error2, event }) => {
  3815. const error_message = format_server_error(
  3816. status,
  3817. /** @type {Error} */
  3818. error2,
  3819. event
  3820. );
  3821. console.error(error_message);
  3822. }),
  3823. handleFetch: module.handleFetch || (({ request, fetch: fetch2 }) => fetch2(request)),
  3824. handleValidationError: module.handleValidationError || (({ issues }) => {
  3825. console.error("Remote function schema validation failed:", issues);
  3826. return { message: "Bad Request" };
  3827. }),
  3828. reroute: module.reroute || (() => {
  3829. }),
  3830. transport: module.transport || {}
  3831. };
  3832. set_app({
  3833. decoders: module.transport ? Object.fromEntries(Object.entries(module.transport).map(([k, v]) => [k, v.decode])) : {}
  3834. });
  3835. if (module.init) {
  3836. await module.init();
  3837. }
  3838. } catch (e) {
  3839. {
  3840. throw e;
  3841. }
  3842. }
  3843. })());
  3844. }
  3845. /**
  3846. * @param {Request} request
  3847. * @param {import('types').RequestOptions} options
  3848. */
  3849. async respond(request, options2) {
  3850. return respond(request, this.#options, this.#manifest, {
  3851. ...options2,
  3852. error: false,
  3853. depth: 0
  3854. });
  3855. }
  3856. }
  3857. export {
  3858. Server
  3859. };