@qwik.dev/router 2.0.0-beta.11 → 2.0.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/lib/adapters/azure-swa/vite/index.cjs +61 -5
  2. package/lib/adapters/azure-swa/vite/index.mjs +26 -205
  3. package/lib/adapters/bun-server/vite/index.cjs +27 -5
  4. package/lib/adapters/bun-server/vite/index.mjs +14 -200
  5. package/lib/adapters/cloud-run/vite/index.cjs +24 -5
  6. package/lib/adapters/cloud-run/vite/index.mjs +13 -199
  7. package/lib/adapters/cloudflare-pages/vite/index.cjs +65 -1
  8. package/lib/adapters/cloudflare-pages/vite/index.mjs +63 -4
  9. package/lib/adapters/deno-server/vite/index.cjs +39 -5
  10. package/lib/adapters/deno-server/vite/index.mjs +16 -202
  11. package/lib/adapters/netlify-edge/vite/index.cjs +88 -6
  12. package/lib/adapters/netlify-edge/vite/index.mjs +56 -244
  13. package/lib/adapters/node-server/vite/index.cjs +27 -5
  14. package/lib/adapters/node-server/vite/index.mjs +14 -200
  15. package/lib/adapters/shared/vite/index.cjs +303 -2
  16. package/lib/adapters/shared/vite/index.d.ts +4 -4
  17. package/lib/adapters/shared/vite/index.mjs +248 -147
  18. package/lib/adapters/ssg/vite/index.cjs +19 -5
  19. package/lib/adapters/ssg/vite/index.mjs +11 -197
  20. package/lib/adapters/vercel-edge/vite/index.cjs +81 -5
  21. package/lib/adapters/vercel-edge/vite/index.d.ts +1 -1
  22. package/lib/adapters/vercel-edge/vite/index.mjs +48 -233
  23. package/lib/chunks/error-handler.cjs +58 -0
  24. package/lib/chunks/error-handler.mjs +59 -0
  25. package/lib/chunks/format-error.cjs +136 -0
  26. package/lib/chunks/format-error.mjs +137 -0
  27. package/lib/chunks/fs.cjs +274 -0
  28. package/lib/chunks/fs.mjs +275 -0
  29. package/lib/chunks/index.cjs +877 -0
  30. package/lib/chunks/index.mjs +876 -0
  31. package/lib/chunks/mime-types.cjs +52 -0
  32. package/lib/chunks/mime-types.mjs +53 -0
  33. package/lib/chunks/routing.qwik.cjs +452 -0
  34. package/lib/chunks/routing.qwik.mjs +453 -0
  35. package/lib/chunks/types.qwik.cjs +24 -0
  36. package/lib/chunks/types.qwik.mjs +25 -0
  37. package/lib/index.d.ts +9 -3
  38. package/lib/index.qwik.cjs +530 -994
  39. package/lib/index.qwik.mjs +499 -965
  40. package/lib/middleware/aws-lambda/index.cjs +52 -1
  41. package/lib/middleware/aws-lambda/index.mjs +37 -26
  42. package/lib/middleware/azure-swa/index.cjs +92 -1
  43. package/lib/middleware/azure-swa/index.mjs +64 -46
  44. package/lib/middleware/bun/index.cjs +143 -1
  45. package/lib/middleware/bun/index.mjs +103 -117
  46. package/lib/middleware/cloudflare-pages/index.cjs +96 -1
  47. package/lib/middleware/cloudflare-pages/index.mjs +68 -47
  48. package/lib/middleware/deno/index.cjs +130 -1
  49. package/lib/middleware/deno/index.mjs +93 -112
  50. package/lib/middleware/firebase/index.cjs +33 -1
  51. package/lib/middleware/firebase/index.mjs +25 -16
  52. package/lib/middleware/netlify-edge/index.cjs +71 -1
  53. package/lib/middleware/netlify-edge/index.mjs +52 -36
  54. package/lib/middleware/node/index.cjs +219 -1
  55. package/lib/middleware/node/index.mjs +178 -165
  56. package/lib/middleware/request-handler/index.cjs +1488 -18
  57. package/lib/middleware/request-handler/index.d.ts +20 -2
  58. package/lib/middleware/request-handler/index.mjs +1223 -882
  59. package/lib/middleware/vercel-edge/index.cjs +98 -1
  60. package/lib/middleware/vercel-edge/index.mjs +71 -47
  61. package/lib/service-worker/index.cjs +5 -0
  62. package/lib/service-worker/index.mjs +5 -0
  63. package/lib/ssg/index.cjs +15 -1
  64. package/lib/ssg/index.mjs +12 -19
  65. package/lib/vite/index.cjs +2006 -27
  66. package/lib/vite/index.d.ts +6 -6
  67. package/lib/vite/index.mjs +1592 -1223
  68. package/package.json +9 -8
  69. package/lib/adapters/azure-swa/vite/index-BqUeglYs.cjs +0 -1
  70. package/lib/adapters/azure-swa/vite/index-CBIchDYq.js +0 -651
  71. package/lib/adapters/azure-swa/vite/index-ClHGw5z1.js +0 -6
  72. package/lib/adapters/azure-swa/vite/index-CrwlB95_.js +0 -22
  73. package/lib/adapters/azure-swa/vite/index-DTIOTwZo.cjs +0 -11
  74. package/lib/adapters/azure-swa/vite/index-vQuPcef3.cjs +0 -1
  75. package/lib/adapters/bun-server/vite/index-BqUeglYs.cjs +0 -1
  76. package/lib/adapters/bun-server/vite/index-CBIchDYq.js +0 -651
  77. package/lib/adapters/bun-server/vite/index-ClHGw5z1.js +0 -6
  78. package/lib/adapters/bun-server/vite/index-CrwlB95_.js +0 -22
  79. package/lib/adapters/bun-server/vite/index-DTIOTwZo.cjs +0 -11
  80. package/lib/adapters/bun-server/vite/index-vQuPcef3.cjs +0 -1
  81. package/lib/adapters/cloud-run/vite/index-BqUeglYs.cjs +0 -1
  82. package/lib/adapters/cloud-run/vite/index-CBIchDYq.js +0 -651
  83. package/lib/adapters/cloud-run/vite/index-ClHGw5z1.js +0 -6
  84. package/lib/adapters/cloud-run/vite/index-CrwlB95_.js +0 -22
  85. package/lib/adapters/cloud-run/vite/index-DTIOTwZo.cjs +0 -11
  86. package/lib/adapters/cloud-run/vite/index-vQuPcef3.cjs +0 -1
  87. package/lib/adapters/cloudflare-pages/vite/index-Bg_9YkM5.js +0 -22
  88. package/lib/adapters/cloudflare-pages/vite/index-C1aDmh1S.cjs +0 -1
  89. package/lib/adapters/cloudflare-pages/vite/index-CHT9Y93A.js +0 -254
  90. package/lib/adapters/cloudflare-pages/vite/index-Ck7KvpK1.cjs +0 -11
  91. package/lib/adapters/cloudflare-pages/vite/index-ClHGw5z1.js +0 -6
  92. package/lib/adapters/cloudflare-pages/vite/index-Cp1cjAds.js +0 -645
  93. package/lib/adapters/cloudflare-pages/vite/index-D9RL9dvJ.cjs +0 -5
  94. package/lib/adapters/cloudflare-pages/vite/index-vQuPcef3.cjs +0 -1
  95. package/lib/adapters/deno-server/vite/index-BqUeglYs.cjs +0 -1
  96. package/lib/adapters/deno-server/vite/index-CBIchDYq.js +0 -651
  97. package/lib/adapters/deno-server/vite/index-ClHGw5z1.js +0 -6
  98. package/lib/adapters/deno-server/vite/index-CrwlB95_.js +0 -22
  99. package/lib/adapters/deno-server/vite/index-DTIOTwZo.cjs +0 -11
  100. package/lib/adapters/deno-server/vite/index-vQuPcef3.cjs +0 -1
  101. package/lib/adapters/netlify-edge/vite/index-BqUeglYs.cjs +0 -1
  102. package/lib/adapters/netlify-edge/vite/index-CBIchDYq.js +0 -651
  103. package/lib/adapters/netlify-edge/vite/index-ClHGw5z1.js +0 -6
  104. package/lib/adapters/netlify-edge/vite/index-CrwlB95_.js +0 -22
  105. package/lib/adapters/netlify-edge/vite/index-DTIOTwZo.cjs +0 -11
  106. package/lib/adapters/netlify-edge/vite/index-vQuPcef3.cjs +0 -1
  107. package/lib/adapters/node-server/vite/index-BqUeglYs.cjs +0 -1
  108. package/lib/adapters/node-server/vite/index-CBIchDYq.js +0 -651
  109. package/lib/adapters/node-server/vite/index-ClHGw5z1.js +0 -6
  110. package/lib/adapters/node-server/vite/index-CrwlB95_.js +0 -22
  111. package/lib/adapters/node-server/vite/index-DTIOTwZo.cjs +0 -11
  112. package/lib/adapters/node-server/vite/index-vQuPcef3.cjs +0 -1
  113. package/lib/adapters/shared/vite/index-BqUeglYs.cjs +0 -1
  114. package/lib/adapters/shared/vite/index-CBIchDYq.js +0 -651
  115. package/lib/adapters/shared/vite/index-ClHGw5z1.js +0 -6
  116. package/lib/adapters/shared/vite/index-CrwlB95_.js +0 -22
  117. package/lib/adapters/shared/vite/index-DTIOTwZo.cjs +0 -11
  118. package/lib/adapters/shared/vite/index-vQuPcef3.cjs +0 -1
  119. package/lib/adapters/ssg/vite/index-BqUeglYs.cjs +0 -1
  120. package/lib/adapters/ssg/vite/index-CBIchDYq.js +0 -651
  121. package/lib/adapters/ssg/vite/index-ClHGw5z1.js +0 -6
  122. package/lib/adapters/ssg/vite/index-CrwlB95_.js +0 -22
  123. package/lib/adapters/ssg/vite/index-DTIOTwZo.cjs +0 -11
  124. package/lib/adapters/ssg/vite/index-vQuPcef3.cjs +0 -1
  125. package/lib/adapters/vercel-edge/vite/index-BqUeglYs.cjs +0 -1
  126. package/lib/adapters/vercel-edge/vite/index-CBIchDYq.js +0 -651
  127. package/lib/adapters/vercel-edge/vite/index-ClHGw5z1.js +0 -6
  128. package/lib/adapters/vercel-edge/vite/index-CrwlB95_.js +0 -22
  129. package/lib/adapters/vercel-edge/vite/index-DTIOTwZo.cjs +0 -11
  130. package/lib/adapters/vercel-edge/vite/index-vQuPcef3.cjs +0 -1
  131. package/lib/service-worker.cjs +0 -1
  132. package/lib/service-worker.mjs +0 -5
  133. package/lib/ssg/deno.cjs +0 -1
  134. package/lib/ssg/deno.mjs +0 -6
  135. package/lib/ssg/index-CBIchDYq.js +0 -651
  136. package/lib/ssg/index-ClHGw5z1.js +0 -6
  137. package/lib/ssg/index-DTIOTwZo.cjs +0 -11
  138. package/lib/ssg/index-vQuPcef3.cjs +0 -1
  139. package/lib/ssg/node.cjs +0 -11
  140. package/lib/ssg/node.mjs +0 -651
@@ -1,1127 +1,1468 @@
1
- import { _serialize as q, _UNINITIALIZED as ye, _deserialize as te, _verifySerializable as Qe } from "@qwik.dev/core/internal";
2
- import "@qwik.dev/core";
3
- import { ServerError as D, RedirectMessage as H, RewriteMessage as we, AbortMessage as pe } from "@qwik.dev/router/middleware/request-handler";
4
- const re = /* @__PURE__ */ new WeakMap(), ie = "qaction", J = "qloaders", Ee = "qfunc", oe = "qdata", je = "q:route";
5
- function ze(e, n) {
6
- const t = ce(e), r = ae(e), i = ce(n), o = ae(n);
7
- return Re(e, t, r, n, i, o);
8
- }
9
- function Re(e, n, t, r, i, o) {
10
- if (r.startsWith("/build/"))
11
- return null;
12
- let a = null;
13
- for (; n < t; ) {
14
- const c = e.charCodeAt(n++), s = r.charCodeAt(i++);
15
- if (c === 91) {
16
- const l = be(e, n), f = n + (l ? 3 : 0), u = z(
17
- e,
18
- f,
19
- t,
20
- 93
21
- /* CLOSE_BRACKET */
22
- ), m = e.substring(f, u), p = z(
23
- e,
24
- u + 1,
25
- t,
26
- 47
27
- /* SLASH */
28
- ), g = e.substring(u + 1, p);
29
- n = u + 1;
30
- const w = i - 1;
31
- if (l) {
32
- const R = Be(
33
- m,
34
- g,
35
- r,
36
- w,
37
- o,
38
- e,
39
- n + g.length + 1,
40
- t
41
- );
42
- if (R)
43
- return Object.assign(a || (a = {}), R);
44
- }
45
- const b = z(r, w, o, 47, g);
46
- if (b == -1)
47
- return null;
48
- const M = r.substring(w, b);
49
- if (!l && !g && !M)
50
- return null;
51
- i = b, (a || (a = {}))[m] = decodeURIComponent(M);
52
- } else if (c !== s && !(isNaN(s) && Ge(e, n)))
53
- return null;
1
+ var __defProp = Object.defineProperty;
2
+ var __typeError = (msg) => {
3
+ throw TypeError(msg);
4
+ };
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
8
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
9
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
10
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
11
+ var _a, _b, _c, _pendingHighSurrogate, _handle, _transform;
12
+ import { isServer } from "@qwik.dev/core/build";
13
+ import { i as isPromise, k as QDATA_KEY, Q as Q_ROUTE, h as QFN_KEY, m as QLOADER_KEY, j as QACTION_KEY, d as loadRoute } from "../../chunks/routing.qwik.mjs";
14
+ import { inlinedQrl } from "@qwik.dev/core";
15
+ import { _serialize, _UNINITIALIZED, _deserialize, _verifySerializable } from "@qwik.dev/core/internal";
16
+ import { L as LoadedRouteProp } from "../../chunks/types.qwik.mjs";
17
+ import { _asyncRequestStore as _asyncRequestStore$1, ServerError as ServerError$1, RedirectMessage as RedirectMessage$1, RewriteMessage as RewriteMessage$1, AbortMessage as AbortMessage$1 } from "@qwik.dev/router/middleware/request-handler";
18
+ import { g as getErrorHtml, m as minimalHtmlResponse } from "../../chunks/error-handler.mjs";
19
+ import "@qwik.dev/core/preloader";
20
+ var HttpStatus = /* @__PURE__ */ ((HttpStatus2) => {
21
+ HttpStatus2[HttpStatus2["Continue"] = 100] = "Continue";
22
+ HttpStatus2[HttpStatus2["SwitchingProtocols"] = 101] = "SwitchingProtocols";
23
+ HttpStatus2[HttpStatus2["Processing"] = 102] = "Processing";
24
+ HttpStatus2[HttpStatus2["Ok"] = 200] = "Ok";
25
+ HttpStatus2[HttpStatus2["Created"] = 201] = "Created";
26
+ HttpStatus2[HttpStatus2["Accepted"] = 202] = "Accepted";
27
+ HttpStatus2[HttpStatus2["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
28
+ HttpStatus2[HttpStatus2["NoContent"] = 204] = "NoContent";
29
+ HttpStatus2[HttpStatus2["ResetContent"] = 205] = "ResetContent";
30
+ HttpStatus2[HttpStatus2["PartialContent"] = 206] = "PartialContent";
31
+ HttpStatus2[HttpStatus2["MultiStatus"] = 207] = "MultiStatus";
32
+ HttpStatus2[HttpStatus2["AlreadyReported"] = 208] = "AlreadyReported";
33
+ HttpStatus2[HttpStatus2["ImUsed"] = 226] = "ImUsed";
34
+ HttpStatus2[HttpStatus2["MultipleChoices"] = 300] = "MultipleChoices";
35
+ HttpStatus2[HttpStatus2["MovedPermanently"] = 301] = "MovedPermanently";
36
+ HttpStatus2[HttpStatus2["Found"] = 302] = "Found";
37
+ HttpStatus2[HttpStatus2["SeeOther"] = 303] = "SeeOther";
38
+ HttpStatus2[HttpStatus2["NotModified"] = 304] = "NotModified";
39
+ HttpStatus2[HttpStatus2["UseProxy"] = 305] = "UseProxy";
40
+ HttpStatus2[HttpStatus2["SwitchProxy"] = 306] = "SwitchProxy";
41
+ HttpStatus2[HttpStatus2["TemporaryRedirect"] = 307] = "TemporaryRedirect";
42
+ HttpStatus2[HttpStatus2["PermanentRedirect"] = 308] = "PermanentRedirect";
43
+ HttpStatus2[HttpStatus2["BadRequest"] = 400] = "BadRequest";
44
+ HttpStatus2[HttpStatus2["Unauthorized"] = 401] = "Unauthorized";
45
+ HttpStatus2[HttpStatus2["PaymentRequired"] = 402] = "PaymentRequired";
46
+ HttpStatus2[HttpStatus2["Forbidden"] = 403] = "Forbidden";
47
+ HttpStatus2[HttpStatus2["NotFound"] = 404] = "NotFound";
48
+ HttpStatus2[HttpStatus2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
49
+ HttpStatus2[HttpStatus2["NotAcceptable"] = 406] = "NotAcceptable";
50
+ HttpStatus2[HttpStatus2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
51
+ HttpStatus2[HttpStatus2["RequestTimeout"] = 408] = "RequestTimeout";
52
+ HttpStatus2[HttpStatus2["Conflict"] = 409] = "Conflict";
53
+ HttpStatus2[HttpStatus2["Gone"] = 410] = "Gone";
54
+ HttpStatus2[HttpStatus2["LengthRequired"] = 411] = "LengthRequired";
55
+ HttpStatus2[HttpStatus2["PreconditionFailed"] = 412] = "PreconditionFailed";
56
+ HttpStatus2[HttpStatus2["PayloadTooLarge"] = 413] = "PayloadTooLarge";
57
+ HttpStatus2[HttpStatus2["UriTooLong"] = 414] = "UriTooLong";
58
+ HttpStatus2[HttpStatus2["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
59
+ HttpStatus2[HttpStatus2["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
60
+ HttpStatus2[HttpStatus2["ExpectationFailed"] = 417] = "ExpectationFailed";
61
+ HttpStatus2[HttpStatus2["IAmATeapot"] = 418] = "IAmATeapot";
62
+ HttpStatus2[HttpStatus2["MisdirectedRequest"] = 421] = "MisdirectedRequest";
63
+ HttpStatus2[HttpStatus2["UnprocessableEntity"] = 422] = "UnprocessableEntity";
64
+ HttpStatus2[HttpStatus2["Locked"] = 423] = "Locked";
65
+ HttpStatus2[HttpStatus2["FailedDependency"] = 424] = "FailedDependency";
66
+ HttpStatus2[HttpStatus2["UpgradeRequired"] = 426] = "UpgradeRequired";
67
+ HttpStatus2[HttpStatus2["PreconditionRequired"] = 428] = "PreconditionRequired";
68
+ HttpStatus2[HttpStatus2["TooManyRequests"] = 429] = "TooManyRequests";
69
+ HttpStatus2[HttpStatus2["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
70
+ HttpStatus2[HttpStatus2["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
71
+ HttpStatus2[HttpStatus2["InternalServerError"] = 500] = "InternalServerError";
72
+ HttpStatus2[HttpStatus2["NotImplemented"] = 501] = "NotImplemented";
73
+ HttpStatus2[HttpStatus2["BadGateway"] = 502] = "BadGateway";
74
+ HttpStatus2[HttpStatus2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
75
+ HttpStatus2[HttpStatus2["GatewayTimeout"] = 504] = "GatewayTimeout";
76
+ HttpStatus2[HttpStatus2["HttpVersionNotSupported"] = 505] = "HttpVersionNotSupported";
77
+ HttpStatus2[HttpStatus2["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
78
+ HttpStatus2[HttpStatus2["InsufficientStorage"] = 507] = "InsufficientStorage";
79
+ HttpStatus2[HttpStatus2["LoopDetected"] = 508] = "LoopDetected";
80
+ HttpStatus2[HttpStatus2["NotExtended"] = 510] = "NotExtended";
81
+ HttpStatus2[HttpStatus2["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
82
+ return HttpStatus2;
83
+ })(HttpStatus || {});
84
+ function createCacheControl(cacheControl) {
85
+ const controls = [];
86
+ if (cacheControl === "day") {
87
+ cacheControl = 60 * 60 * 24;
88
+ } else if (cacheControl === "week") {
89
+ cacheControl = 60 * 60 * 24 * 7;
90
+ } else if (cacheControl === "month") {
91
+ cacheControl = 60 * 60 * 24 * 30;
92
+ } else if (cacheControl === "year") {
93
+ cacheControl = 60 * 60 * 24 * 365;
94
+ } else if (cacheControl === "private") {
95
+ cacheControl = {
96
+ private: true,
97
+ noCache: true
98
+ };
99
+ } else if (cacheControl === "immutable") {
100
+ cacheControl = {
101
+ public: true,
102
+ immutable: true,
103
+ maxAge: 60 * 60 * 24 * 365
104
+ };
105
+ } else if (cacheControl === "no-cache") {
106
+ cacheControl = {
107
+ noCache: true
108
+ };
54
109
  }
55
- return se(e, n) && se(r, i) ? a || {} : null;
56
- }
57
- function Ge(e, n) {
58
- return e.charCodeAt(n) === 91 && be(e, n + 1);
59
- }
60
- function ae(e) {
61
- const n = e.length;
62
- return n > 1 && e.charCodeAt(n - 1) === 47 ? n - 1 : n;
63
- }
64
- function se(e, n) {
65
- const t = e.length;
66
- return n >= t || n == t - 1 && e.charCodeAt(n) === 47;
67
- }
68
- function ce(e) {
69
- return e.charCodeAt(0) === 47 ? 1 : 0;
70
- }
71
- function be(e, n) {
72
- return e.charCodeAt(n) === 46 && e.charCodeAt(n + 1) === 46 && e.charCodeAt(n + 2) === 46;
73
- }
74
- function z(e, n, t, r, i = "") {
75
- for (; n < t && e.charCodeAt(n) !== r; )
76
- n++;
77
- const o = i.length;
78
- for (let a = 0; a < o; a++)
79
- if (e.charCodeAt(n - o + a) !== i.charCodeAt(a))
80
- return -1;
81
- return n - o;
82
- }
83
- function Be(e, n, t, r, i, o, a, c) {
84
- t.charCodeAt(r) === 47 && r++;
85
- let s = i;
86
- const l = n + "/";
87
- for (; s >= r; ) {
88
- const f = Re(o, a, c, t, s, i);
89
- if (f) {
90
- let m = t.substring(r, Math.min(s, i));
91
- return m.endsWith(l) && (m = m.substring(0, m.length - l.length)), f[e] = decodeURIComponent(m), f;
92
- }
93
- const u = Ke(t, r, l, s, r - 1) + l.length;
94
- if (s === u)
95
- break;
96
- s = u;
110
+ if (typeof cacheControl === "number") {
111
+ cacheControl = {
112
+ maxAge: cacheControl,
113
+ sMaxAge: cacheControl
114
+ };
97
115
  }
98
- return null;
99
- }
100
- function Ke(e, n, t, r, i) {
101
- let o = e.lastIndexOf(t, r);
102
- return o == r - t.length && (o = e.lastIndexOf(t, r - t.length - 1)), o > n ? o : i;
103
- }
104
- var W = /* @__PURE__ */ ((e) => (e[e.RouteName = 0] = "RouteName", e[e.Loaders = 1] = "Loaders", e[e.OriginalPathname = 2] = "OriginalPathname", e[e.RouteBundleNames = 3] = "RouteBundleNames", e))(W || {}), $ = /* @__PURE__ */ ((e) => (e[e.Pathname = 0] = "Pathname", e[e.MenuLoader = 1] = "MenuLoader", e))($ || {}), L = /* @__PURE__ */ ((e) => (e[e.RouteName = 0] = "RouteName", e[e.Params = 1] = "Params", e[e.Mods = 2] = "Mods", e[e.Menu = 3] = "Menu", e[e.RouteBundleNames = 4] = "RouteBundleNames", e))(L || {});
105
- const Ae = (e) => e == null ? e : (Object.getOwnPropertyNames(e).forEach((n) => {
106
- const t = e[n];
107
- t && typeof t == "object" && !Object.isFrozen(t) && Ae(t);
108
- }), Object.freeze(e)), ve = async (e, n, t, r, i) => {
109
- if (!Array.isArray(e))
110
- return null;
111
- for (const o of e) {
112
- const a = o[W.RouteName], c = ze(a, r);
113
- if (!c)
114
- continue;
115
- const s = o[W.Loaders], l = o[W.RouteBundleNames], f = new Array(s.length), u = [];
116
- s.forEach((p, g) => {
117
- le(
118
- p,
119
- u,
120
- (w) => f[g] = w,
121
- t
122
- );
123
- });
124
- let m;
125
- if (!i) {
126
- const p = Je(n, r);
127
- le(
128
- p,
129
- u,
130
- (g) => m = g?.default,
131
- t
132
- );
133
- }
134
- return u.length > 0 && await Promise.all(u), [a, c, f, Ae(m), l];
116
+ if (cacheControl.immutable) {
117
+ controls.push("immutable");
135
118
  }
136
- return null;
137
- }, le = (e, n, t, r) => {
138
- if (typeof e == "function") {
139
- const i = re.get(e);
140
- if (i)
141
- t(i);
142
- else {
143
- const o = e();
144
- typeof o.then == "function" ? n.push(
145
- o.then((a) => {
146
- r !== !1 && re.set(e, a), t(a);
147
- })
148
- ) : o && t(o);
149
- }
119
+ if (cacheControl.maxAge) {
120
+ controls.push(`max-age=${cacheControl.maxAge}`);
150
121
  }
151
- }, Je = (e, n) => {
152
- if (e) {
153
- n = n.endsWith("/") ? n : n + "/";
154
- const t = e.find(
155
- (r) => r[$.Pathname] === n || n.startsWith(r[$.Pathname])
156
- );
157
- if (t)
158
- return t[$.MenuLoader];
122
+ if (cacheControl.sMaxAge) {
123
+ controls.push(`s-maxage=${cacheControl.sMaxAge}`);
159
124
  }
160
- };
161
- var Y = /* @__PURE__ */ ((e) => (e[e.Continue = 100] = "Continue", e[e.SwitchingProtocols = 101] = "SwitchingProtocols", e[e.Processing = 102] = "Processing", e[e.Ok = 200] = "Ok", e[e.Created = 201] = "Created", e[e.Accepted = 202] = "Accepted", e[e.NonAuthoritativeInformation = 203] = "NonAuthoritativeInformation", e[e.NoContent = 204] = "NoContent", e[e.ResetContent = 205] = "ResetContent", e[e.PartialContent = 206] = "PartialContent", e[e.MultiStatus = 207] = "MultiStatus", e[e.AlreadyReported = 208] = "AlreadyReported", e[e.ImUsed = 226] = "ImUsed", e[e.MultipleChoices = 300] = "MultipleChoices", e[e.MovedPermanently = 301] = "MovedPermanently", e[e.Found = 302] = "Found", e[e.SeeOther = 303] = "SeeOther", e[e.NotModified = 304] = "NotModified", e[e.UseProxy = 305] = "UseProxy", e[e.SwitchProxy = 306] = "SwitchProxy", e[e.TemporaryRedirect = 307] = "TemporaryRedirect", e[e.PermanentRedirect = 308] = "PermanentRedirect", e[e.BadRequest = 400] = "BadRequest", e[e.Unauthorized = 401] = "Unauthorized", e[e.PaymentRequired = 402] = "PaymentRequired", e[e.Forbidden = 403] = "Forbidden", e[e.NotFound = 404] = "NotFound", e[e.MethodNotAllowed = 405] = "MethodNotAllowed", e[e.NotAcceptable = 406] = "NotAcceptable", e[e.ProxyAuthenticationRequired = 407] = "ProxyAuthenticationRequired", e[e.RequestTimeout = 408] = "RequestTimeout", e[e.Conflict = 409] = "Conflict", e[e.Gone = 410] = "Gone", e[e.LengthRequired = 411] = "LengthRequired", e[e.PreconditionFailed = 412] = "PreconditionFailed", e[e.PayloadTooLarge = 413] = "PayloadTooLarge", e[e.UriTooLong = 414] = "UriTooLong", e[e.UnsupportedMediaType = 415] = "UnsupportedMediaType", e[e.RangeNotSatisfiable = 416] = "RangeNotSatisfiable", e[e.ExpectationFailed = 417] = "ExpectationFailed", e[e.IAmATeapot = 418] = "IAmATeapot", e[e.MisdirectedRequest = 421] = "MisdirectedRequest", e[e.UnprocessableEntity = 422] = "UnprocessableEntity", e[e.Locked = 423] = "Locked", e[e.FailedDependency = 424] = "FailedDependency", e[e.UpgradeRequired = 426] = "UpgradeRequired", e[e.PreconditionRequired = 428] = "PreconditionRequired", e[e.TooManyRequests = 429] = "TooManyRequests", e[e.RequestHeaderFieldsTooLarge = 431] = "RequestHeaderFieldsTooLarge", e[e.UnavailableForLegalReasons = 451] = "UnavailableForLegalReasons", e[e.InternalServerError = 500] = "InternalServerError", e[e.NotImplemented = 501] = "NotImplemented", e[e.BadGateway = 502] = "BadGateway", e[e.ServiceUnavailable = 503] = "ServiceUnavailable", e[e.GatewayTimeout = 504] = "GatewayTimeout", e[e.HttpVersionNotSupported = 505] = "HttpVersionNotSupported", e[e.VariantAlsoNegotiates = 506] = "VariantAlsoNegotiates", e[e.InsufficientStorage = 507] = "InsufficientStorage", e[e.LoopDetected = 508] = "LoopDetected", e[e.NotExtended = 510] = "NotExtended", e[e.NetworkAuthenticationRequired = 511] = "NetworkAuthenticationRequired", e))(Y || {});
162
- const Ye = (e) => e && typeof e.then == "function";
163
- function Ve(e) {
164
- const n = [];
165
- return e === "day" ? e = 3600 * 24 : e === "week" ? e = 3600 * 24 * 7 : e === "month" ? e = 3600 * 24 * 30 : e === "year" ? e = 3600 * 24 * 365 : e === "private" ? e = {
166
- private: !0,
167
- noCache: !0
168
- } : e === "immutable" ? e = {
169
- public: !0,
170
- immutable: !0,
171
- maxAge: 3600 * 24 * 365
172
- } : e === "no-cache" && (e = {
173
- noCache: !0
174
- }), typeof e == "number" && (e = {
175
- maxAge: e,
176
- sMaxAge: e
177
- }), e.immutable && n.push("immutable"), e.maxAge && n.push(`max-age=${e.maxAge}`), e.sMaxAge && n.push(`s-maxage=${e.sMaxAge}`), e.noStore && n.push("no-store"), e.noCache && n.push("no-cache"), e.private && n.push("private"), e.public && n.push("public"), e.staleWhileRevalidate && n.push(`stale-while-revalidate=${e.staleWhileRevalidate}`), e.staleIfError && n.push(`stale-if-error=${e.staleIfError}`), n.join(", ");
125
+ if (cacheControl.noStore) {
126
+ controls.push("no-store");
127
+ }
128
+ if (cacheControl.noCache) {
129
+ controls.push("no-cache");
130
+ }
131
+ if (cacheControl.private) {
132
+ controls.push("private");
133
+ }
134
+ if (cacheControl.public) {
135
+ controls.push("public");
136
+ }
137
+ if (cacheControl.staleWhileRevalidate) {
138
+ controls.push(`stale-while-revalidate=${cacheControl.staleWhileRevalidate}`);
139
+ }
140
+ if (cacheControl.staleIfError) {
141
+ controls.push(`stale-if-error=${cacheControl.staleIfError}`);
142
+ }
143
+ return controls.join(", ");
178
144
  }
179
- const Xe = {
145
+ const SAMESITE = {
180
146
  lax: "Lax",
181
147
  Lax: "Lax",
182
148
  None: "None",
183
149
  none: "None",
184
150
  strict: "Strict",
185
151
  Strict: "Strict"
186
- }, Ze = {
152
+ };
153
+ const UNIT = {
187
154
  seconds: 1,
188
- minutes: 60,
189
- hours: 3600,
190
- days: 3600 * 24,
191
- weeks: 3600 * 24 * 7
192
- }, de = (e, n, t) => {
193
- const r = [`${e}=${n}`];
194
- typeof t.domain == "string" && r.push(`Domain=${t.domain}`), typeof t.maxAge == "number" ? r.push(`Max-Age=${t.maxAge}`) : Array.isArray(t.maxAge) ? r.push(`Max-Age=${t.maxAge[0] * Ze[t.maxAge[1]]}`) : typeof t.expires == "number" || typeof t.expires == "string" ? r.push(`Expires=${t.expires}`) : t.expires instanceof Date && r.push(`Expires=${t.expires.toUTCString()}`), t.httpOnly && r.push("HttpOnly"), typeof t.path == "string" && r.push(`Path=${t.path}`);
195
- const i = en(t.sameSite);
196
- return i && r.push(`SameSite=${i}`), t.secure && r.push("Secure"), r.join("; ");
155
+ minutes: 1 * 60,
156
+ hours: 1 * 60 * 60,
157
+ days: 1 * 60 * 60 * 24,
158
+ weeks: 1 * 60 * 60 * 24 * 7
197
159
  };
198
- function fe(e) {
160
+ const createSetCookieValue = (cookieName, cookieValue, options) => {
161
+ const c = [`${cookieName}=${cookieValue}`];
162
+ if (typeof options.domain === "string") {
163
+ c.push(`Domain=${options.domain}`);
164
+ }
165
+ if (typeof options.maxAge === "number") {
166
+ c.push(`Max-Age=${options.maxAge}`);
167
+ } else if (Array.isArray(options.maxAge)) {
168
+ c.push(`Max-Age=${options.maxAge[0] * UNIT[options.maxAge[1]]}`);
169
+ } else if (typeof options.expires === "number" || typeof options.expires == "string") {
170
+ c.push(`Expires=${options.expires}`);
171
+ } else if (options.expires instanceof Date) {
172
+ c.push(`Expires=${options.expires.toUTCString()}`);
173
+ }
174
+ if (options.httpOnly) {
175
+ c.push("HttpOnly");
176
+ }
177
+ if (typeof options.path === "string") {
178
+ c.push(`Path=${options.path}`);
179
+ }
180
+ const sameSite = resolveSameSite(options.sameSite);
181
+ if (sameSite) {
182
+ c.push(`SameSite=${sameSite}`);
183
+ }
184
+ if (options.secure) {
185
+ c.push("Secure");
186
+ }
187
+ return c.join("; ");
188
+ };
189
+ function tryDecodeUriComponent(str) {
199
190
  try {
200
- return decodeURIComponent(e);
191
+ return decodeURIComponent(str);
201
192
  } catch {
202
- return e;
193
+ return str;
203
194
  }
204
195
  }
205
- const He = (e) => {
206
- const n = {};
207
- if (typeof e == "string" && e !== "") {
208
- const t = e.split(";");
209
- for (const r of t) {
210
- const i = r.indexOf("=");
211
- i !== -1 && (n[fe(r.slice(0, i).trim())] = fe(r.slice(i + 1).trim()));
196
+ const parseCookieString = (cookieString) => {
197
+ const cookie = {};
198
+ if (typeof cookieString === "string" && cookieString !== "") {
199
+ const cookieSegments = cookieString.split(";");
200
+ for (const cookieSegment of cookieSegments) {
201
+ const separatorIndex = cookieSegment.indexOf("=");
202
+ if (separatorIndex !== -1) {
203
+ cookie[tryDecodeUriComponent(cookieSegment.slice(0, separatorIndex).trim())] = tryDecodeUriComponent(cookieSegment.slice(separatorIndex + 1).trim());
204
+ }
212
205
  }
213
206
  }
214
- return n;
207
+ return cookie;
215
208
  };
216
- function en(e) {
217
- if (e === !0)
209
+ function resolveSameSite(sameSite) {
210
+ if (sameSite === true) {
218
211
  return "Strict";
219
- if (e === !1)
212
+ }
213
+ if (sameSite === false) {
220
214
  return "None";
221
- if (e)
222
- return Xe[e];
215
+ }
216
+ if (sameSite) {
217
+ return SAMESITE[sameSite];
218
+ }
219
+ return void 0;
223
220
  }
224
- const x = Symbol("request-cookies"), k = Symbol("response-cookies"), T = Symbol("live-cookies");
225
- class nn {
226
- [x];
227
- [k] = {};
228
- [T] = {};
229
- appendCounter = 0;
230
- constructor(n) {
231
- this[x] = He(n), this[T] = { ...this[x] };
232
- }
233
- get(n, t = !0) {
234
- const r = this[t ? T : x][n];
235
- return r ? {
236
- value: r,
221
+ const REQ_COOKIE = Symbol("request-cookies");
222
+ const RES_COOKIE = Symbol("response-cookies");
223
+ const LIVE_COOKIE = Symbol("live-cookies");
224
+ _c = REQ_COOKIE, _b = RES_COOKIE, _a = LIVE_COOKIE;
225
+ class Cookie {
226
+ constructor(cookieString) {
227
+ __publicField(this, _c);
228
+ __publicField(this, _b, {});
229
+ __publicField(this, _a, {});
230
+ __publicField(this, "appendCounter", 0);
231
+ this[REQ_COOKIE] = parseCookieString(cookieString);
232
+ this[LIVE_COOKIE] = { ...this[REQ_COOKIE] };
233
+ }
234
+ get(cookieName, live = true) {
235
+ const value = this[live ? LIVE_COOKIE : REQ_COOKIE][cookieName];
236
+ if (!value) {
237
+ return null;
238
+ }
239
+ return {
240
+ value,
237
241
  json() {
238
- return JSON.parse(r);
242
+ return JSON.parse(value);
239
243
  },
240
244
  number() {
241
- return Number(r);
245
+ return Number(value);
242
246
  }
243
- } : null;
247
+ };
244
248
  }
245
- getAll(n = !0) {
246
- return Object.keys(this[n ? T : x]).reduce(
247
- (t, r) => (t[r] = this.get(r), t),
249
+ getAll(live = true) {
250
+ return Object.keys(this[live ? LIVE_COOKIE : REQ_COOKIE]).reduce(
251
+ (cookies, cookieName) => {
252
+ cookies[cookieName] = this.get(cookieName);
253
+ return cookies;
254
+ },
248
255
  {}
249
256
  );
250
257
  }
251
- has(n, t = !0) {
252
- return !!this[t ? T : x][n];
253
- }
254
- set(n, t, r = {}) {
255
- this[T][n] = typeof t == "string" ? t : JSON.stringify(t);
256
- const i = typeof t == "string" ? t : encodeURIComponent(JSON.stringify(t));
257
- this[k][n] = de(n, i, r);
258
- }
259
- append(n, t, r = {}) {
260
- this[T][n] = typeof t == "string" ? t : JSON.stringify(t);
261
- const i = typeof t == "string" ? t : encodeURIComponent(JSON.stringify(t));
262
- this[k][++this.appendCounter] = de(
263
- n,
264
- i,
265
- r
258
+ has(cookieName, live = true) {
259
+ return !!this[live ? LIVE_COOKIE : REQ_COOKIE][cookieName];
260
+ }
261
+ set(cookieName, cookieValue, options = {}) {
262
+ this[LIVE_COOKIE][cookieName] = typeof cookieValue === "string" ? cookieValue : JSON.stringify(cookieValue);
263
+ const resolvedValue = typeof cookieValue === "string" ? cookieValue : encodeURIComponent(JSON.stringify(cookieValue));
264
+ this[RES_COOKIE][cookieName] = createSetCookieValue(cookieName, resolvedValue, options);
265
+ }
266
+ append(cookieName, cookieValue, options = {}) {
267
+ this[LIVE_COOKIE][cookieName] = typeof cookieValue === "string" ? cookieValue : JSON.stringify(cookieValue);
268
+ const resolvedValue = typeof cookieValue === "string" ? cookieValue : encodeURIComponent(JSON.stringify(cookieValue));
269
+ this[RES_COOKIE][++this.appendCounter] = createSetCookieValue(
270
+ cookieName,
271
+ resolvedValue,
272
+ options
266
273
  );
267
274
  }
268
- delete(n, t) {
269
- this.set(n, "deleted", { ...t, maxAge: 0 }), this[T][n] = null;
275
+ delete(name, options) {
276
+ this.set(name, "deleted", { ...options, maxAge: 0 });
277
+ this[LIVE_COOKIE][name] = null;
270
278
  }
271
279
  headers() {
272
- return Object.values(this[k]);
280
+ return Object.values(this[RES_COOKIE]);
273
281
  }
274
282
  }
275
- const kn = (e, n) => {
276
- const t = n.headers();
277
- if (t.length > 0) {
278
- const r = new Headers(e);
279
- for (const i of t)
280
- r.append("Set-Cookie", i);
281
- return r;
282
- }
283
- return e;
283
+ const mergeHeadersCookies = (headers, cookies) => {
284
+ const cookieHeaders = cookies.headers();
285
+ if (cookieHeaders.length > 0) {
286
+ const newHeaders = new Headers(headers);
287
+ for (const cookie of cookieHeaders) {
288
+ newHeaders.append("Set-Cookie", cookie);
289
+ }
290
+ return newHeaders;
291
+ }
292
+ return headers;
284
293
  };
285
- function G(e, n) {
286
- let t = "Server Error";
287
- return n != null && (typeof n.message == "string" ? t = n.message : t = String(n)), "<html>" + _e(e, t) + "</html>";
288
- }
289
- function _e(e, n) {
290
- typeof e != "number" && (e = 500), typeof n == "string" ? n = rn(n) : n = "";
291
- const t = typeof n == "string" ? "600px" : "300px", r = e >= 500 ? an : on;
292
- return `
293
- <head>
294
- <meta charset="utf-8">
295
- <meta http-equiv="Status" content="${e}">
296
- <title>${e} ${n}</title>
297
- <meta name="viewport" content="width=device-width,initial-scale=1">
298
- <style>
299
- body { color: ${r}; background-color: #fafafa; padding: 30px; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Roboto, sans-serif; }
300
- p { max-width: ${t}; margin: 60px auto 30px auto; background: white; border-radius: 4px; box-shadow: 0px 0px 50px -20px ${r}; overflow: hidden; }
301
- strong { display: inline-block; padding: 15px; background: ${r}; color: white; }
302
- span { display: inline-block; padding: 15px; }
303
- </style>
304
- </head>
305
- <body><p><strong>${e}</strong> <span>${n}</span></p></body>
306
- `;
307
- }
308
- const tn = /[&<>]/g, rn = (e) => e.replace(tn, (n) => {
309
- switch (n) {
310
- case "&":
311
- return "&amp;";
312
- case "<":
313
- return "&lt;";
314
- case ">":
315
- return "&gt;";
316
- default:
317
- return "";
318
- }
319
- }), on = "#006ce9", an = "#713fc2";
320
- let F;
321
- import("node:async_hooks").then((e) => {
322
- const n = e.AsyncLocalStorage;
323
- F = new n(), globalThis.qcAsyncRequestStore = F;
324
- }).catch((e) => {
325
- console.warn(
326
- "AsyncLocalStorage not available, continuing without it. This might impact concurrent server calls.",
327
- e
328
- );
329
- });
330
- function sn(e, n, t, r, i = "/") {
331
- let o;
332
- const a = new Promise((s) => o = s), c = ln(
333
- e,
334
- n,
335
- t,
336
- i,
337
- o
294
+ function runQwikRouter(serverRequestEv, loadedRoute, requestHandlers, rebuildRouteInfo, basePathname = "/") {
295
+ let resolve;
296
+ const responsePromise = new Promise((r) => resolve = r);
297
+ const requestEv = createRequestEvent(
298
+ serverRequestEv,
299
+ loadedRoute,
300
+ requestHandlers,
301
+ basePathname,
302
+ resolve
338
303
  );
339
304
  return {
340
- response: a,
341
- requestEv: c,
342
- completion: F ? F.run(c, ue, c, r, o) : ue(c, r, o)
305
+ response: responsePromise,
306
+ requestEv,
307
+ completion: _asyncRequestStore$1 ? _asyncRequestStore$1.run(requestEv, runNext, requestEv, rebuildRouteInfo, resolve) : runNext(requestEv, rebuildRouteInfo, resolve)
343
308
  };
344
309
  }
345
- async function ue(e, n, t) {
310
+ async function runNext(requestEv, rebuildRouteInfo, resolve) {
346
311
  try {
347
- ((a) => new URL(a.pathname + a.search, a))(e.originalUrl);
312
+ const isValidURL = (url) => new URL(url.pathname + url.search, url);
313
+ isValidURL(requestEv.originalUrl);
348
314
  } catch {
349
- const a = "Resource Not Found";
350
- e.status(404);
351
- const c = G(404, a);
352
- return e.html(404, c), new D(404, a);
315
+ const status = 404;
316
+ const message = "Resource Not Found";
317
+ requestEv.status(status);
318
+ const html = getErrorHtml(status, message);
319
+ requestEv.html(status, html);
320
+ return new ServerError$1(status, message);
353
321
  }
354
- let r = 1;
355
- async function i() {
322
+ let rewriteAttempt = 1;
323
+ async function _runNext() {
356
324
  try {
357
- await e.next();
358
- } catch (o) {
359
- if (o instanceof H)
360
- await e.getWritableStream().close();
361
- else if (o instanceof we) {
362
- if (r > 50)
363
- throw new Error("Infinite rewrite loop");
364
- r += 1;
365
- const a = new URL(e.url);
366
- a.pathname = o.pathname;
367
- const { loadedRoute: c, requestHandlers: s } = await n(a);
368
- return e.resetRoute(c, s, a), await i();
369
- } else if (o instanceof D) {
370
- if (!e.headersSent) {
371
- const a = o.status, c = e.request.headers.get("Accept");
372
- if (c && !c.includes("text/html"))
373
- e.headers.set("Content-Type", "application/qwik-json"), e.send(a, await q([o.data]));
374
- else {
375
- const s = G(o.status, o.data);
376
- e.html(a, s);
377
- }
325
+ await requestEv.next();
326
+ } catch (e) {
327
+ if (e instanceof RedirectMessage$1) {
328
+ const stream = requestEv.getWritableStream();
329
+ await stream.close();
330
+ return e;
331
+ } else if (e instanceof RewriteMessage$1) {
332
+ if (rewriteAttempt > 50) {
333
+ return new Error(`Infinite rewrite loop`);
378
334
  }
379
- } else if (!(o instanceof pe)) {
380
- if (I(e) !== "dev")
381
- try {
382
- e.headersSent || (e.headers.set("content-type", "text/html; charset=utf-8"), e.cacheControl({ noCache: !0 }), e.status(500));
383
- const a = e.getWritableStream();
384
- if (!a.locked) {
385
- const c = a.getWriter();
386
- await c.write(E.encode(G(500, "Internal Server Error"))), await c.close();
387
- }
388
- } catch {
389
- console.error("Unable to render error page");
335
+ rewriteAttempt += 1;
336
+ const url = new URL(requestEv.url);
337
+ url.pathname = e.pathname;
338
+ const { loadedRoute, requestHandlers } = await rebuildRouteInfo(url);
339
+ requestEv.resetRoute(loadedRoute, requestHandlers, url);
340
+ return await _runNext();
341
+ } else if (e instanceof AbortMessage$1) {
342
+ return;
343
+ } else if (e instanceof ServerError$1 && !requestEv.headersSent) {
344
+ const status = e.status;
345
+ const accept = requestEv.request.headers.get("Accept");
346
+ if (accept && !accept.includes("text/html")) {
347
+ requestEv.headers.set("Content-Type", "application/qwik-json");
348
+ requestEv.send(status, await _serialize([e.data]));
349
+ } else {
350
+ requestEv.html(status, getErrorHtml(status, e.data));
351
+ }
352
+ return e;
353
+ }
354
+ if (getRequestMode(requestEv) !== "dev") {
355
+ try {
356
+ if (!requestEv.headersSent) {
357
+ requestEv.headers.set("content-type", "text/html; charset=utf-8");
358
+ requestEv.cacheControl({ noCache: true });
359
+ requestEv.status(500);
390
360
  }
391
- return o;
361
+ const stream = requestEv.getWritableStream();
362
+ if (!stream.locked) {
363
+ const writer = stream.getWriter();
364
+ await writer.write(encoder.encode(getErrorHtml(500, "Internal Server Error")));
365
+ await writer.close();
366
+ }
367
+ } catch {
368
+ console.error("Unable to render error page");
369
+ }
392
370
  }
371
+ return e;
393
372
  }
394
373
  }
395
374
  try {
396
- return await i();
375
+ return await _runNext();
397
376
  } finally {
398
- e.isDirty() || t(null);
377
+ if (!requestEv.isDirty()) {
378
+ resolve(null);
379
+ }
399
380
  }
400
381
  }
401
- function V(e) {
402
- const n = e.endsWith(C);
403
- if (n) {
404
- const t = e.length - C.length + (globalThis.__NO_TRAILING_SLASH__ ? 0 : 1);
405
- e = e.slice(0, t), e === "" && (e = "/");
382
+ function getRouteMatchPathname(pathname) {
383
+ const isInternal = pathname.endsWith(QDATA_JSON);
384
+ if (isInternal) {
385
+ const trimEnd = pathname.length - QDATA_JSON.length + (globalThis.__NO_TRAILING_SLASH__ ? 0 : 1);
386
+ pathname = pathname.slice(0, trimEnd);
387
+ if (pathname === "") {
388
+ pathname = "/";
389
+ }
406
390
  }
407
- return { pathname: e, isInternal: n };
391
+ return { pathname, isInternal };
408
392
  }
409
- const ee = "@isQData", C = "/q-data.json", Te = Symbol("RequestEvLoaders"), Me = Symbol("RequestEvMode"), Ne = Symbol("RequestEvRoute"), xe = Symbol(
393
+ const IsQData = "@isQData";
394
+ const QDATA_JSON = "/q-data.json";
395
+ const RequestEvLoaders = Symbol("RequestEvLoaders");
396
+ const RequestEvMode = Symbol("RequestEvMode");
397
+ const RequestEvRoute = Symbol("RequestEvRoute");
398
+ const RequestEvLoaderSerializationStrategyMap = Symbol(
410
399
  "RequestEvLoaderSerializationStrategyMap"
411
- ), Ce = "@routeName", Q = "@actionId", Ie = "@actionFormData", cn = "@nonce", Pe = "@rewrite", X = "@serverTiming", Le = "qData";
412
- function ln(e, n, t, r, i) {
413
- const { request: o, platform: a, env: c } = e, s = /* @__PURE__ */ new Map(), l = new nn(o.headers.get("cookie")), f = new Headers(), u = new URL(o.url), { pathname: m, isInternal: p } = V(u.pathname);
414
- p && (u.pathname = m, s.set(ee, !0));
415
- let g = -1, w = null, b, M = e.locale, R = 200;
416
- const qe = async () => {
417
- for (g++; g < t.length; ) {
418
- const d = t[g], h = d(A);
419
- Ye(h) && await h, g++;
400
+ );
401
+ const RequestRouteName = "@routeName";
402
+ const RequestEvSharedActionId = "@actionId";
403
+ const RequestEvSharedActionFormData = "@actionFormData";
404
+ const RequestEvSharedNonce = "@nonce";
405
+ const RequestEvIsRewrite = "@rewrite";
406
+ const RequestEvShareServerTiming = "@serverTiming";
407
+ const RequestEvShareQData = "qData";
408
+ function createRequestEvent(serverRequestEv, loadedRoute, requestHandlers, basePathname, resolved) {
409
+ const { request, platform, env } = serverRequestEv;
410
+ const sharedMap = /* @__PURE__ */ new Map();
411
+ const cookie = new Cookie(request.headers.get("cookie"));
412
+ const headers = new Headers();
413
+ const url = new URL(request.url);
414
+ const { pathname, isInternal } = getRouteMatchPathname(url.pathname);
415
+ if (isInternal) {
416
+ url.pathname = pathname;
417
+ sharedMap.set(IsQData, true);
418
+ }
419
+ let routeModuleIndex = -1;
420
+ let writableStream = null;
421
+ let requestData = void 0;
422
+ let locale = serverRequestEv.locale;
423
+ let status = 200;
424
+ const next = async () => {
425
+ routeModuleIndex++;
426
+ while (routeModuleIndex < requestHandlers.length) {
427
+ const moduleRequestHandler = requestHandlers[routeModuleIndex];
428
+ const result = moduleRequestHandler(requestEv);
429
+ if (isPromise(result)) {
430
+ await result;
431
+ }
432
+ routeModuleIndex++;
420
433
  }
421
- }, De = (d, h, y = u) => {
422
- n = d, t = h, u.pathname = y.pathname, u.search = y.search, g = -1;
423
- }, N = () => {
424
- if (w !== null)
434
+ };
435
+ const resetRoute = (_loadedRoute, _requestHandlers, _url = url) => {
436
+ loadedRoute = _loadedRoute;
437
+ requestHandlers = _requestHandlers;
438
+ url.pathname = _url.pathname;
439
+ url.search = _url.search;
440
+ routeModuleIndex = -1;
441
+ };
442
+ const check = () => {
443
+ if (writableStream !== null) {
425
444
  throw new Error("Response already sent");
426
- }, U = (d, h) => {
427
- if (N(), typeof d == "number") {
428
- R = d;
429
- const _ = A.getWritableStream().getWriter();
430
- _.write(typeof h == "string" ? E.encode(h) : h), _.close();
431
- } else if (R = d.status, d.headers.forEach((y, _) => {
432
- _.toLowerCase() !== "set-cookie" && f.append(_, y);
433
- }), d.headers.getSetCookie().forEach((y) => {
434
- const _ = y.indexOf("=");
435
- if (_ === -1)
436
- return;
437
- const Fe = y.slice(0, _).trim(), Se = y.slice(_ + 1).trim();
438
- l.set(Fe, Se);
439
- }), d.body) {
440
- const y = A.getWritableStream();
441
- d.body.pipeTo(y);
442
- } else
443
- A.getWritableStream().getWriter().close();
444
- return ne();
445
- }, ne = () => (g = B, new pe()), P = {}, A = {
446
- [Te]: P,
447
- [xe]: /* @__PURE__ */ new Map(),
448
- [Me]: e.mode,
449
- get [Ne]() {
450
- return n;
445
+ }
446
+ };
447
+ const send = (statusOrResponse, body) => {
448
+ check();
449
+ if (typeof statusOrResponse === "number") {
450
+ status = statusOrResponse;
451
+ const writableStream2 = requestEv.getWritableStream();
452
+ const writer = writableStream2.getWriter();
453
+ writer.write(typeof body === "string" ? encoder.encode(body) : body);
454
+ writer.close();
455
+ } else {
456
+ status = statusOrResponse.status;
457
+ statusOrResponse.headers.forEach((value, key) => {
458
+ if (key.toLowerCase() === "set-cookie") {
459
+ return;
460
+ }
461
+ headers.append(key, value);
462
+ });
463
+ statusOrResponse.headers.getSetCookie().forEach((ck) => {
464
+ const index = ck.indexOf("=");
465
+ if (index === -1) {
466
+ return;
467
+ }
468
+ const key = ck.slice(0, index).trim();
469
+ const value = ck.slice(index + 1).trim();
470
+ cookie.set(key, value);
471
+ });
472
+ if (statusOrResponse.body) {
473
+ const writableStream2 = requestEv.getWritableStream();
474
+ statusOrResponse.body.pipeTo(writableStream2);
475
+ } else {
476
+ requestEv.getWritableStream().getWriter().close();
477
+ }
478
+ }
479
+ return exit();
480
+ };
481
+ const exit = (message = new AbortMessage$1()) => {
482
+ routeModuleIndex = ABORT_INDEX;
483
+ return message;
484
+ };
485
+ const loaders = {};
486
+ const requestEv = {
487
+ [RequestEvLoaders]: loaders,
488
+ [RequestEvLoaderSerializationStrategyMap]: /* @__PURE__ */ new Map(),
489
+ [RequestEvMode]: serverRequestEv.mode,
490
+ get [RequestEvRoute]() {
491
+ return loadedRoute;
451
492
  },
452
- cookie: l,
453
- headers: f,
454
- env: c,
455
- method: o.method,
456
- signal: o.signal,
457
- originalUrl: new URL(u),
493
+ cookie,
494
+ headers,
495
+ env,
496
+ method: request.method,
497
+ signal: request.signal,
498
+ originalUrl: new URL(url),
458
499
  get params() {
459
- return n?.[L.Params] ?? {};
500
+ return loadedRoute?.[LoadedRouteProp.Params] ?? {};
460
501
  },
461
502
  get pathname() {
462
- return u.pathname;
503
+ return url.pathname;
463
504
  },
464
- platform: a,
505
+ platform,
465
506
  get query() {
466
- return u.searchParams;
507
+ return url.searchParams;
467
508
  },
468
- request: o,
469
- url: u,
470
- basePathname: r,
471
- sharedMap: s,
509
+ request,
510
+ url,
511
+ basePathname,
512
+ sharedMap,
472
513
  get headersSent() {
473
- return w !== null;
514
+ return writableStream !== null;
474
515
  },
475
516
  get exited() {
476
- return g >= B;
517
+ return routeModuleIndex >= ABORT_INDEX;
477
518
  },
478
519
  get clientConn() {
479
- return e.getClientConn();
520
+ return serverRequestEv.getClientConn();
480
521
  },
481
- next: qe,
482
- resetRoute: De,
483
- exit: ne,
484
- cacheControl: (d, h = "Cache-Control") => {
485
- N(), f.set(h, Ve(d));
522
+ next,
523
+ resetRoute,
524
+ exit,
525
+ cacheControl: (cacheControl, target = "Cache-Control") => {
526
+ check();
527
+ headers.set(target, createCacheControl(cacheControl));
486
528
  },
487
- resolveValue: (async (d) => {
488
- const h = d.__id;
489
- if (d.__brand === "server_loader") {
490
- if (!(h in P))
529
+ resolveValue: (async (loaderOrAction) => {
530
+ const id = loaderOrAction.__id;
531
+ if (loaderOrAction.__brand === "server_loader") {
532
+ if (!(id in loaders)) {
491
533
  throw new Error(
492
534
  "You can not get the returned data of a loader that has not been executed for this request."
493
535
  );
494
- if (P[h] === ye) {
495
- const y = I(A) === "dev";
496
- await Ue(d, P, A, y);
536
+ }
537
+ if (loaders[id] === _UNINITIALIZED) {
538
+ const isDev = getRequestMode(requestEv) === "dev";
539
+ await getRouteLoaderPromise(loaderOrAction, loaders, requestEv, isDev);
497
540
  }
498
541
  }
499
- return P[h];
542
+ return loaders[id];
500
543
  }),
501
- status: (d) => typeof d == "number" ? (N(), R = d, d) : R,
502
- locale: (d) => (typeof d == "string" && (M = d), M || ""),
503
- error: (d, h) => (R = d, f.delete("Cache-Control"), new D(d, h)),
504
- redirect: (d, h) => {
505
- if (N(), R = d, h) {
506
- if (/([^:])\/{2,}/.test(h)) {
507
- const y = h.replace(/([^:])\/{2,}/g, "$1/");
508
- console.warn(`Redirect URL ${h} is invalid, fixing to ${y}`), h = y;
544
+ status: (statusCode) => {
545
+ if (typeof statusCode === "number") {
546
+ check();
547
+ status = statusCode;
548
+ return statusCode;
549
+ }
550
+ return status;
551
+ },
552
+ locale: (_locale) => {
553
+ if (typeof _locale === "string") {
554
+ locale = _locale;
555
+ }
556
+ return locale || "";
557
+ },
558
+ error: (statusCode, message) => {
559
+ status = statusCode;
560
+ headers.delete("Cache-Control");
561
+ return new ServerError$1(statusCode, message);
562
+ },
563
+ redirect: (statusCode, url2) => {
564
+ check();
565
+ status = statusCode;
566
+ if (url2) {
567
+ if (/([^:])\/{2,}/.test(url2)) {
568
+ const fixedURL = url2.replace(/([^:])\/{2,}/g, "$1/");
569
+ console.warn(`Redirect URL ${url2} is invalid, fixing to ${fixedURL}`);
570
+ url2 = fixedURL;
509
571
  }
510
- f.set("Location", h);
572
+ headers.set("Location", url2);
511
573
  }
512
- return f.delete("Cache-Control"), d > 301 && f.set("Cache-Control", "no-store"), g = B, new H();
574
+ headers.delete("Cache-Control");
575
+ if (statusCode > 301) {
576
+ headers.set("Cache-Control", "no-store");
577
+ }
578
+ return exit(new RedirectMessage$1());
513
579
  },
514
- rewrite: (d) => {
515
- if (N(), d.startsWith("http"))
580
+ rewrite: (pathname2) => {
581
+ check();
582
+ if (pathname2.startsWith("http")) {
516
583
  throw new Error("Rewrite does not support absolute urls");
517
- return s.set(Pe, !0), new we(d.replace(/\/+/g, "/"));
584
+ }
585
+ sharedMap.set(RequestEvIsRewrite, true);
586
+ return exit(new RewriteMessage$1(pathname2.replace(/\/+/g, "/")));
587
+ },
588
+ defer: (returnData) => {
589
+ return typeof returnData === "function" ? returnData : () => returnData;
590
+ },
591
+ fail: (statusCode, data) => {
592
+ check();
593
+ status = statusCode;
594
+ headers.delete("Cache-Control");
595
+ return {
596
+ failed: true,
597
+ ...data
598
+ };
599
+ },
600
+ text: (statusCode, text) => {
601
+ headers.set("Content-Type", "text/plain; charset=utf-8");
602
+ return send(statusCode, text);
603
+ },
604
+ html: (statusCode, html) => {
605
+ headers.set("Content-Type", "text/html; charset=utf-8");
606
+ return send(statusCode, html);
607
+ },
608
+ parseBody: async () => {
609
+ if (requestData !== void 0) {
610
+ return requestData;
611
+ }
612
+ return requestData = parseRequest(requestEv, sharedMap);
613
+ },
614
+ json: (statusCode, data) => {
615
+ headers.set("Content-Type", "application/json; charset=utf-8");
616
+ return send(statusCode, JSON.stringify(data));
617
+ },
618
+ send,
619
+ isDirty: () => {
620
+ return writableStream !== null;
518
621
  },
519
- defer: (d) => typeof d == "function" ? d : () => d,
520
- fail: (d, h) => (N(), R = d, f.delete("Cache-Control"), {
521
- failed: !0,
522
- ...h
523
- }),
524
- text: (d, h) => (f.set("Content-Type", "text/plain; charset=utf-8"), U(d, h)),
525
- html: (d, h) => (f.set("Content-Type", "text/html; charset=utf-8"), U(d, h)),
526
- parseBody: async () => b !== void 0 ? b : b = fn(A, s),
527
- json: (d, h) => (f.set("Content-Type", "application/json; charset=utf-8"), U(d, JSON.stringify(h))),
528
- send: U,
529
- isDirty: () => w !== null,
530
622
  getWritableStream: () => {
531
- if (w === null) {
532
- if (e.mode === "dev") {
533
- const d = s.get(X);
534
- d && f.set(
535
- "Server-Timing",
536
- d.map(([h, y]) => `${h};dur=${y}`).join(",")
537
- );
623
+ if (writableStream === null) {
624
+ if (serverRequestEv.mode === "dev") {
625
+ const serverTiming = sharedMap.get(RequestEvShareServerTiming);
626
+ if (serverTiming) {
627
+ headers.set(
628
+ "Server-Timing",
629
+ serverTiming.map(([name, duration]) => `${name};dur=${duration}`).join(",")
630
+ );
631
+ }
538
632
  }
539
- w = e.getWritableStream(
540
- R,
541
- f,
542
- l,
543
- i,
544
- A
633
+ writableStream = serverRequestEv.getWritableStream(
634
+ status,
635
+ headers,
636
+ cookie,
637
+ resolved,
638
+ requestEv
545
639
  );
546
640
  }
547
- return w;
641
+ return writableStream;
548
642
  }
549
643
  };
550
- return Object.freeze(A);
644
+ return Object.freeze(requestEv);
551
645
  }
552
- function O(e) {
553
- return e[Te];
646
+ function getRequestLoaders(requestEv) {
647
+ return requestEv[RequestEvLoaders];
554
648
  }
555
- function Oe(e) {
556
- return e[xe];
649
+ function getRequestLoaderSerializationStrategyMap(requestEv) {
650
+ return requestEv[RequestEvLoaderSerializationStrategyMap];
557
651
  }
558
- function dn(e) {
559
- return e[Ne];
652
+ function getRequestRoute(requestEv) {
653
+ return requestEv[RequestEvRoute];
560
654
  }
561
- function I(e) {
562
- return e[Me];
655
+ function getRequestMode(requestEv) {
656
+ return requestEv[RequestEvMode];
563
657
  }
564
- const B = Number.MAX_SAFE_INTEGER, fn = async ({ request: e, method: n, query: t }, r) => {
565
- const i = e.headers.get("content-type")?.split(/[;,]/, 1)[0].trim() ?? "";
566
- if (i === "application/x-www-form-urlencoded" || i === "multipart/form-data") {
567
- const o = await e.formData();
568
- return r.set(Ie, o), un(o);
569
- } else {
570
- if (i === "application/json")
571
- return await e.json();
572
- if (i === "application/qwik-json") {
573
- if (n === "GET" && t.has(oe)) {
574
- const o = t.get(oe);
575
- if (o)
576
- try {
577
- return te(decodeURIComponent(o));
578
- } catch {
579
- }
658
+ const ABORT_INDEX = Number.MAX_SAFE_INTEGER;
659
+ const parseRequest = async ({ request, method, query }, sharedMap) => {
660
+ const type = request.headers.get("content-type")?.split(/[;,]/, 1)[0].trim() ?? "";
661
+ if (type === "application/x-www-form-urlencoded" || type === "multipart/form-data") {
662
+ const formData = await request.formData();
663
+ sharedMap.set(RequestEvSharedActionFormData, formData);
664
+ return formToObj(formData);
665
+ } else if (type === "application/json") {
666
+ const data = await request.json();
667
+ return data;
668
+ } else if (type === "application/qwik-json") {
669
+ if (method === "GET" && query.has(QDATA_KEY)) {
670
+ const data = query.get(QDATA_KEY);
671
+ if (data) {
672
+ try {
673
+ return _deserialize(decodeURIComponent(data));
674
+ } catch {
675
+ }
580
676
  }
581
- return te(await e.text());
582
677
  }
678
+ return _deserialize(await request.text());
679
+ }
680
+ return void 0;
681
+ };
682
+ const formToObj = (formData) => {
683
+ const values = [...formData.entries()].reduce((values2, [name, value]) => {
684
+ name.split(".").reduce((object, key, index, keys) => {
685
+ if (key.endsWith("[]")) {
686
+ const arrayKey = key.slice(0, -2);
687
+ object[arrayKey] = object[arrayKey] || [];
688
+ return object[arrayKey] = [...object[arrayKey], value];
689
+ }
690
+ if (index < keys.length - 1) {
691
+ return object[key] = object[key] || (Number.isNaN(+keys[index + 1]) ? {} : []);
692
+ }
693
+ return object[key] = value;
694
+ }, values2);
695
+ return values2;
696
+ }, {});
697
+ return values;
698
+ };
699
+ function getQwikRouterServerData(requestEv) {
700
+ const { params, request, status, locale, originalUrl } = requestEv;
701
+ const requestHeaders = {};
702
+ request.headers.forEach((value, key) => requestHeaders[key] = value);
703
+ const action = requestEv.sharedMap.get(RequestEvSharedActionId);
704
+ const formData = requestEv.sharedMap.get(RequestEvSharedActionFormData);
705
+ const routeName = requestEv.sharedMap.get(RequestRouteName);
706
+ const nonce = requestEv.sharedMap.get(RequestEvSharedNonce);
707
+ const headers = requestEv.request.headers;
708
+ const reconstructedUrl = new URL(originalUrl.pathname + originalUrl.search, originalUrl);
709
+ const host = headers.get("X-Forwarded-Host");
710
+ const protocol = headers.get("X-Forwarded-Proto");
711
+ if (host) {
712
+ reconstructedUrl.port = "";
713
+ reconstructedUrl.host = host;
583
714
  }
584
- }, un = (e) => [...e.entries()].reduce((t, [r, i]) => (r.split(".").reduce((o, a, c, s) => {
585
- if (a.endsWith("[]")) {
586
- const l = a.slice(0, -2);
587
- return o[l] = o[l] || [], o[l] = [...o[l], i];
588
- }
589
- return c < s.length - 1 ? o[a] = o[a] || (Number.isNaN(+s[c + 1]) ? {} : []) : o[a] = i;
590
- }, t), t), {});
591
- function hn(e) {
592
- const { params: n, request: t, status: r, locale: i, originalUrl: o } = e, a = {};
593
- t.headers.forEach((M, R) => a[R] = M);
594
- const c = e.sharedMap.get(Q), s = e.sharedMap.get(Ie), l = e.sharedMap.get(Ce), f = e.sharedMap.get(cn), u = e.request.headers, m = new URL(o.pathname + o.search, o), p = u.get("X-Forwarded-Host"), g = u.get("X-Forwarded-Proto");
595
- p && (m.port = "", m.host = p), g && (m.protocol = g);
596
- const w = O(e), b = Oe(e);
715
+ if (protocol) {
716
+ reconstructedUrl.protocol = protocol;
717
+ }
718
+ const loaders = getRequestLoaders(requestEv);
719
+ const loadersSerializationStrategy = getRequestLoaderSerializationStrategyMap(requestEv);
597
720
  return {
598
- url: m.href,
599
- requestHeaders: a,
600
- locale: i(),
601
- nonce: f,
721
+ url: reconstructedUrl.href,
722
+ requestHeaders,
723
+ locale: locale(),
724
+ nonce,
602
725
  containerAttributes: {
603
- [je]: l
726
+ [Q_ROUTE]: routeName
604
727
  },
605
728
  qwikrouter: {
606
- routeName: l,
607
- ev: e,
608
- params: { ...n },
609
- loadedRoute: dn(e),
729
+ routeName,
730
+ ev: requestEv,
731
+ params: { ...params },
732
+ loadedRoute: getRequestRoute(requestEv),
610
733
  response: {
611
- status: r(),
612
- loaders: w,
613
- loadersSerializationStrategy: b,
614
- action: c,
615
- formData: s
734
+ status: status(),
735
+ loaders,
736
+ loadersSerializationStrategy,
737
+ action,
738
+ formData
616
739
  }
617
740
  }
618
741
  };
619
742
  }
620
- const mn = (e, n, t, r, i, o) => {
621
- const a = [], c = [], s = [], l = !!(n && An(n[L.Mods]));
622
- if (o && s.push(Nn), e && he(
623
- a,
624
- c,
625
- s,
626
- e,
627
- l,
628
- t
629
- ), n) {
630
- const f = n[L.RouteName];
631
- r && (t === "POST" || t === "PUT" || t === "PATCH" || t === "DELETE") && (r === "lax-proto" ? s.unshift(_n) : s.unshift(Tn)), l && ((t === "POST" || t === "GET") && s.push(pn), s.push(Rn), o && s.push(xn));
632
- const u = n[L.Mods];
633
- he(
634
- a,
635
- c,
636
- s,
637
- u,
638
- l,
639
- t
640
- ), l && (s.push((m) => {
641
- m.sharedMap.set(Ce, f);
642
- }), s.push(gn(c)), s.push(yn(a)), s.push(i));
643
- }
644
- return s;
645
- }, he = (e, n, t, r, i, o) => {
646
- for (const a of r) {
647
- typeof a.onRequest == "function" ? t.push(a.onRequest) : Array.isArray(a.onRequest) && t.push(...a.onRequest);
648
- let c;
649
- switch (o) {
743
+ const resolveRequestHandlers = (serverPlugins, route, method, checkOrigin, renderHandler, isInternal) => {
744
+ const routeLoaders = [];
745
+ const routeActions = [];
746
+ const requestHandlers = [];
747
+ const isPageRoute = !!(route && isLastModulePageRoute(route[LoadedRouteProp.Mods]));
748
+ if (isInternal) {
749
+ requestHandlers.push(handleQDataRedirect);
750
+ }
751
+ if (serverPlugins) {
752
+ _resolveRequestHandlers(
753
+ routeLoaders,
754
+ routeActions,
755
+ requestHandlers,
756
+ serverPlugins,
757
+ isPageRoute,
758
+ method
759
+ );
760
+ }
761
+ if (route) {
762
+ const routeModules = route[LoadedRouteProp.Mods];
763
+ _resolveRequestHandlers(
764
+ routeLoaders,
765
+ routeActions,
766
+ requestHandlers,
767
+ routeModules,
768
+ isPageRoute,
769
+ method
770
+ );
771
+ const routeName = route[LoadedRouteProp.RouteName];
772
+ if (checkOrigin && (method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE")) {
773
+ if (checkOrigin === "lax-proto") {
774
+ requestHandlers.unshift(csrfLaxProtoCheckMiddleware);
775
+ } else {
776
+ requestHandlers.unshift(csrfCheckMiddleware);
777
+ }
778
+ }
779
+ if (isPageRoute) {
780
+ if (method === "POST" || method === "GET") {
781
+ requestHandlers.push(runServerFunction);
782
+ }
783
+ requestHandlers.push(fixTrailingSlash);
784
+ if (isInternal) {
785
+ requestHandlers.push(renderQData);
786
+ }
787
+ }
788
+ if (isPageRoute) {
789
+ requestHandlers.push((ev) => {
790
+ ev.sharedMap.set(RequestRouteName, routeName);
791
+ });
792
+ requestHandlers.push(actionsMiddleware(routeActions));
793
+ requestHandlers.push(loadersMiddleware(routeLoaders));
794
+ requestHandlers.push(renderHandler);
795
+ }
796
+ }
797
+ return requestHandlers;
798
+ };
799
+ const _resolveRequestHandlers = (routeLoaders, routeActions, requestHandlers, routeModules, collectActions, method) => {
800
+ for (const routeModule of routeModules) {
801
+ if (typeof routeModule.onRequest === "function") {
802
+ requestHandlers.push(routeModule.onRequest);
803
+ } else if (Array.isArray(routeModule.onRequest)) {
804
+ requestHandlers.push(...routeModule.onRequest);
805
+ }
806
+ let methodReqHandler;
807
+ switch (method) {
650
808
  case "GET": {
651
- c = a.onGet;
809
+ methodReqHandler = routeModule.onGet;
652
810
  break;
653
811
  }
654
812
  case "POST": {
655
- c = a.onPost;
813
+ methodReqHandler = routeModule.onPost;
656
814
  break;
657
815
  }
658
816
  case "PUT": {
659
- c = a.onPut;
817
+ methodReqHandler = routeModule.onPut;
660
818
  break;
661
819
  }
662
820
  case "PATCH": {
663
- c = a.onPatch;
821
+ methodReqHandler = routeModule.onPatch;
664
822
  break;
665
823
  }
666
824
  case "DELETE": {
667
- c = a.onDelete;
825
+ methodReqHandler = routeModule.onDelete;
668
826
  break;
669
827
  }
670
828
  case "OPTIONS": {
671
- c = a.onOptions;
829
+ methodReqHandler = routeModule.onOptions;
672
830
  break;
673
831
  }
674
832
  case "HEAD": {
675
- c = a.onHead;
833
+ methodReqHandler = routeModule.onHead;
676
834
  break;
677
835
  }
678
836
  }
679
- if (typeof c == "function" ? t.push(c) : Array.isArray(c) && t.push(...c), i)
680
- for (const s of Object.values(a))
681
- typeof s == "function" && (s.__brand === "server_loader" ? e.push(s) : s.__brand === "server_action" && n.push(s));
837
+ if (typeof methodReqHandler === "function") {
838
+ requestHandlers.push(methodReqHandler);
839
+ } else if (Array.isArray(methodReqHandler)) {
840
+ requestHandlers.push(...methodReqHandler);
841
+ }
842
+ if (collectActions) {
843
+ for (const module of Object.values(routeModule)) {
844
+ if (typeof module === "function") {
845
+ if (module.__brand === "server_loader") {
846
+ routeLoaders.push(module);
847
+ } else if (module.__brand === "server_action") {
848
+ routeActions.push(module);
849
+ }
850
+ }
851
+ }
852
+ }
682
853
  }
683
854
  };
684
- function gn(e) {
685
- return async (n) => {
686
- const t = n;
687
- if (t.headersSent) {
688
- t.exit();
855
+ function actionsMiddleware(routeActions) {
856
+ return async (requestEvent) => {
857
+ const requestEv = requestEvent;
858
+ if (requestEv.headersSent) {
859
+ requestEv.exit();
689
860
  return;
690
861
  }
691
- const { method: r } = t, i = O(t), o = I(t) === "dev";
692
- if (o && r === "GET" && t.query.has(ie) && console.warn(
693
- `Seems like you are submitting a Qwik Action via GET request. Qwik Actions should be submitted via POST request.
694
- Make sure your <form> has method="POST" attribute, like this: <form method="POST">`
695
- ), r === "POST") {
696
- const a = t.query.get(ie);
697
- if (a) {
698
- const c = globalThis._qwikActionsMap, s = e.find((l) => l.__id === a) ?? c?.get(a);
699
- if (s) {
700
- t.sharedMap.set(Q, a);
701
- const l = await t.parseBody();
702
- if (!l || typeof l != "object")
862
+ const { method } = requestEv;
863
+ const loaders = getRequestLoaders(requestEv);
864
+ const isDev = getRequestMode(requestEv) === "dev";
865
+ if (isDev && method === "GET") {
866
+ if (requestEv.query.has(QACTION_KEY)) {
867
+ console.warn(
868
+ 'Seems like you are submitting a Qwik Action via GET request. Qwik Actions should be submitted via POST request.\nMake sure your <form> has method="POST" attribute, like this: <form method="POST">'
869
+ );
870
+ }
871
+ }
872
+ if (method === "POST") {
873
+ const selectedActionId = requestEv.query.get(QACTION_KEY);
874
+ if (selectedActionId) {
875
+ const serverActionsMap = globalThis._qwikActionsMap;
876
+ const action = routeActions.find((action2) => action2.__id === selectedActionId) ?? serverActionsMap?.get(selectedActionId);
877
+ if (action) {
878
+ requestEv.sharedMap.set(RequestEvSharedActionId, selectedActionId);
879
+ const data = await requestEv.parseBody();
880
+ if (!data || typeof data !== "object") {
703
881
  throw new Error(
704
- `Expected request data for the action id ${a} to be an object`
882
+ `Expected request data for the action id ${selectedActionId} to be an object`
705
883
  );
706
- const f = await ke(t, s.__validators, l, o);
707
- if (!f.success)
708
- i[a] = t.fail(f.status ?? 500, f.error);
709
- else {
710
- const u = o ? await j(
711
- t,
712
- s.__qrl.getHash(),
713
- () => s.__qrl.call(t, f.data, t)
714
- ) : await s.__qrl.call(t, f.data, t);
715
- o && S(u, s.__qrl), i[a] = u;
884
+ }
885
+ const result = await runValidators(requestEv, action.__validators, data, isDev);
886
+ if (!result.success) {
887
+ loaders[selectedActionId] = requestEv.fail(result.status ?? 500, result.error);
888
+ } else {
889
+ const actionResolved = isDev ? await measure(
890
+ requestEv,
891
+ action.__qrl.getHash(),
892
+ () => action.__qrl.call(requestEv, result.data, requestEv)
893
+ ) : await action.__qrl.call(requestEv, result.data, requestEv);
894
+ if (isDev) {
895
+ verifySerializable(actionResolved, action.__qrl);
896
+ }
897
+ loaders[selectedActionId] = actionResolved;
716
898
  }
717
899
  }
718
900
  }
719
901
  }
720
902
  };
721
903
  }
722
- function yn(e) {
723
- return async (n) => {
724
- const t = n;
725
- if (t.headersSent) {
726
- t.exit();
904
+ function loadersMiddleware(routeLoaders) {
905
+ return async (requestEvent) => {
906
+ const requestEv = requestEvent;
907
+ if (requestEv.headersSent) {
908
+ requestEv.exit();
727
909
  return;
728
910
  }
729
- const r = O(t), i = I(t) === "dev";
730
- if (e.length > 0) {
731
- let o = [];
732
- if (t.query.has(J)) {
733
- const c = t.query.getAll(J);
734
- for (const s of e)
735
- c.includes(s.__id) ? o.push(s) : r[s.__id] = ye;
736
- } else
737
- o = e;
738
- const a = o.map(
739
- (c) => Ue(c, r, t, i)
911
+ const loaders = getRequestLoaders(requestEv);
912
+ const isDev = getRequestMode(requestEv) === "dev";
913
+ if (routeLoaders.length > 0) {
914
+ const resolvedLoadersPromises = routeLoaders.map(
915
+ (loader) => getRouteLoaderPromise(loader, loaders, requestEv, isDev)
740
916
  );
741
- await Promise.all(a);
917
+ await Promise.all(resolvedLoadersPromises);
742
918
  }
743
919
  };
744
920
  }
745
- async function Ue(e, n, t, r) {
746
- const i = e.__id;
747
- return n[i] = ke(
748
- t,
749
- e.__validators,
921
+ async function getRouteLoaderPromise(loader, loaders, requestEv, isDev) {
922
+ const loaderId = loader.__id;
923
+ loaders[loaderId] = runValidators(
924
+ requestEv,
925
+ loader.__validators,
750
926
  void 0,
751
927
  // data
752
- r
753
- ).then((a) => a.success ? r ? j(
754
- t,
755
- e.__qrl.getHash(),
756
- () => e.__qrl.call(t, t)
757
- ) : e.__qrl.call(t, t) : t.fail(a.status ?? 500, a.error)).then((a) => (typeof a == "function" ? n[i] = a() : (r && S(a, e.__qrl), n[i] = a), a)), Oe(t).set(i, e.__serializationStrategy), n[i];
928
+ isDev
929
+ ).then((res) => {
930
+ if (res.success) {
931
+ if (isDev) {
932
+ return measure(
933
+ requestEv,
934
+ loader.__qrl.getHash(),
935
+ () => loader.__qrl.call(requestEv, requestEv)
936
+ );
937
+ } else {
938
+ return loader.__qrl.call(requestEv, requestEv);
939
+ }
940
+ } else {
941
+ return requestEv.fail(res.status ?? 500, res.error);
942
+ }
943
+ }).then((resolvedLoader) => {
944
+ if (typeof resolvedLoader === "function") {
945
+ loaders[loaderId] = resolvedLoader();
946
+ } else {
947
+ if (isDev) {
948
+ verifySerializable(resolvedLoader, loader.__qrl);
949
+ }
950
+ loaders[loaderId] = resolvedLoader;
951
+ }
952
+ return resolvedLoader;
953
+ });
954
+ const loadersSerializationStrategy = getRequestLoaderSerializationStrategyMap(requestEv);
955
+ loadersSerializationStrategy.set(loaderId, loader.__serializationStrategy);
956
+ return loaders[loaderId];
758
957
  }
759
- async function ke(e, n, t, r) {
760
- let i = {
761
- success: !0,
762
- data: t
958
+ async function runValidators(requestEv, validators, data, isDev) {
959
+ let lastResult = {
960
+ success: true,
961
+ data
763
962
  };
764
- if (n)
765
- for (const o of n)
766
- if (r ? i = await j(
767
- e,
768
- "validator$",
769
- () => o.validate(e, t)
770
- ) : i = await o.validate(e, t), i.success)
771
- t = i.data;
772
- else
773
- return i;
774
- return i;
963
+ if (validators) {
964
+ for (const validator of validators) {
965
+ if (isDev) {
966
+ lastResult = await measure(
967
+ requestEv,
968
+ `validator$`,
969
+ () => validator.validate(requestEv, data)
970
+ );
971
+ } else {
972
+ lastResult = await validator.validate(requestEv, data);
973
+ }
974
+ if (!lastResult.success) {
975
+ return lastResult;
976
+ } else {
977
+ data = lastResult.data;
978
+ }
979
+ }
980
+ }
981
+ return lastResult;
775
982
  }
776
- function wn(e) {
777
- return e ? typeof e == "object" && Symbol.asyncIterator in e : !1;
983
+ function isAsyncIterator(obj) {
984
+ return obj ? typeof obj === "object" && Symbol.asyncIterator in obj : false;
778
985
  }
779
- async function pn(e) {
780
- const n = e.query.get(Ee);
781
- if (n && e.request.headers.get("X-QRL") === n && e.request.headers.get("Content-Type") === "application/qwik-json") {
782
- e.exit();
783
- const t = I(e) === "dev", r = await e.parseBody();
784
- if (Array.isArray(r)) {
785
- const [i, ...o] = r;
786
- if (bn(i) && i.getHash() === n) {
787
- let a;
788
- try {
789
- t ? a = await j(
790
- e,
791
- `server_${i.getSymbol()}`,
792
- () => i.apply(e, o)
793
- ) : a = await i.apply(e, o);
794
- } catch (c) {
795
- throw c instanceof D ? e.error(c.status, c.data) : e.error(500, "Invalid request");
986
+ async function runServerFunction(ev) {
987
+ const serverFnHash = ev.query.get(QFN_KEY);
988
+ if (serverFnHash && ev.request.headers.get("X-QRL") === serverFnHash && ev.request.headers.get("Content-Type") === "application/qwik-json") {
989
+ ev.exit();
990
+ const isDev = getRequestMode(ev) === "dev";
991
+ const data = await ev.parseBody();
992
+ if (Array.isArray(data)) {
993
+ const qrl = inlinedQrl(null, serverFnHash, data[1]);
994
+ let result;
995
+ try {
996
+ if (isDev) {
997
+ result = await measure(
998
+ ev,
999
+ `server_${serverFnHash}`,
1000
+ () => qrl.apply(ev, data[0])
1001
+ );
1002
+ } else {
1003
+ result = await qrl.apply(ev, data[0]);
796
1004
  }
797
- if (wn(a)) {
798
- e.headers.set("Content-Type", "text/qwik-json-stream");
799
- const s = e.getWritableStream().getWriter();
800
- for await (const l of a) {
801
- t && S(l, i);
802
- const f = await q([l]);
803
- if (e.signal.aborted)
804
- break;
805
- await s.write(E.encode(`${f}
806
- `));
1005
+ } catch (err) {
1006
+ if (err instanceof ServerError$1) {
1007
+ throw ev.error(err.status, err.data);
1008
+ }
1009
+ console.error(`Server function ${serverFnHash} failed:`, err);
1010
+ throw ev.error(500, "Invalid request");
1011
+ }
1012
+ if (isAsyncIterator(result)) {
1013
+ ev.headers.set("Content-Type", "text/qwik-json-stream");
1014
+ const writable = ev.getWritableStream();
1015
+ const stream = writable.getWriter();
1016
+ for await (const item of result) {
1017
+ if (isDev) {
1018
+ verifySerializable(item, qrl);
807
1019
  }
808
- s.close();
809
- } else {
810
- S(a, i), e.headers.set("Content-Type", "application/qwik-json");
811
- const c = await q([a]);
812
- e.send(200, c);
1020
+ const message = await _serialize([item]);
1021
+ if (ev.signal.aborted) {
1022
+ break;
1023
+ }
1024
+ await stream.write(encoder.encode(`${message}
1025
+ `));
813
1026
  }
814
- return;
1027
+ stream.close();
1028
+ } else {
1029
+ verifySerializable(result, qrl);
1030
+ ev.headers.set("Content-Type", "application/qwik-json");
1031
+ const message = await _serialize([result]);
1032
+ ev.send(200, message);
815
1033
  }
1034
+ return;
816
1035
  }
817
- throw e.error(500, "Invalid request");
1036
+ throw ev.error(500, "Invalid request");
818
1037
  }
819
1038
  }
820
- function Rn(e) {
821
- const { basePathname: n, originalUrl: t, sharedMap: r } = e, { pathname: i, search: o } = t;
822
- if (!r.has(ee) && i !== n && !i.endsWith(".html")) {
823
- if (globalThis.__NO_TRAILING_SLASH__) {
824
- if (i.endsWith("/"))
825
- throw e.redirect(
826
- Y.MovedPermanently,
827
- i.slice(0, i.length - 1) + o
1039
+ function fixTrailingSlash(ev) {
1040
+ const { basePathname, originalUrl, sharedMap } = ev;
1041
+ const { pathname, search } = originalUrl;
1042
+ const isQData = sharedMap.has(IsQData);
1043
+ if (!isQData && pathname !== basePathname && !pathname.endsWith(".html")) {
1044
+ if (!globalThis.__NO_TRAILING_SLASH__) {
1045
+ if (!pathname.endsWith("/")) {
1046
+ throw ev.redirect(HttpStatus.MovedPermanently, pathname + "/" + search);
1047
+ }
1048
+ } else {
1049
+ if (pathname.endsWith("/")) {
1050
+ throw ev.redirect(
1051
+ HttpStatus.MovedPermanently,
1052
+ pathname.slice(0, pathname.length - 1) + search
828
1053
  );
829
- } else if (!i.endsWith("/"))
830
- throw e.redirect(Y.MovedPermanently, i + "/" + o);
1054
+ }
1055
+ }
831
1056
  }
832
1057
  }
833
- function S(e, n) {
1058
+ function verifySerializable(data, qrl) {
834
1059
  try {
835
- Qe(e, void 0);
836
- } catch (t) {
837
- throw t instanceof Error && n.dev && (t.loc = n.dev), t;
1060
+ _verifySerializable(data, void 0);
1061
+ } catch (e) {
1062
+ if (e instanceof Error && qrl.dev) {
1063
+ e.loc = qrl.dev;
1064
+ }
1065
+ throw e;
838
1066
  }
839
1067
  }
840
- const bn = (e) => typeof e == "function" && typeof e.getSymbol == "function";
841
- function An(e) {
842
- const n = e[e.length - 1];
843
- return n && typeof n.default == "function";
1068
+ function isLastModulePageRoute(routeModules) {
1069
+ const lastRouteModule = routeModules[routeModules.length - 1];
1070
+ return lastRouteModule && typeof lastRouteModule.default === "function";
844
1071
  }
845
- function Z(e) {
846
- e = new URL(e), e.pathname.endsWith(C) && (e.pathname = e.pathname.slice(0, -C.length)), globalThis.__NO_TRAILING_SLASH__ ? e.pathname.endsWith("/") && (e.pathname = e.pathname.slice(0, -1)) : e.pathname.endsWith("/") || (e.pathname += "/");
847
- const n = e.search.slice(1).replaceAll(/&?q(action|data|func|loaders)=[^&]+/g, "");
848
- return `${e.pathname}${n ? `?${n}` : ""}${e.hash}`;
1072
+ function getPathname(url) {
1073
+ url = new URL(url);
1074
+ if (url.pathname.endsWith(QDATA_JSON)) {
1075
+ url.pathname = url.pathname.slice(0, -QDATA_JSON.length);
1076
+ }
1077
+ if (!globalThis.__NO_TRAILING_SLASH__) {
1078
+ if (!url.pathname.endsWith("/")) {
1079
+ url.pathname += "/";
1080
+ }
1081
+ } else {
1082
+ if (url.pathname.endsWith("/")) {
1083
+ url.pathname = url.pathname.slice(0, -1);
1084
+ }
1085
+ }
1086
+ const search = url.search.slice(1).replaceAll(/&?q(action|data|func|loaders)=[^&]+/g, "");
1087
+ return `${url.pathname}${search ? `?${search}` : ""}${url.hash}`;
849
1088
  }
850
- const E = /* @__PURE__ */ new TextEncoder();
851
- function _n(e) {
852
- We(e, "lax-proto");
1089
+ const encoder = /* @__PURE__ */ new TextEncoder();
1090
+ function csrfLaxProtoCheckMiddleware(requestEv) {
1091
+ checkCSRF(requestEv, "lax-proto");
853
1092
  }
854
- function Tn(e) {
855
- We(e);
1093
+ function csrfCheckMiddleware(requestEv) {
1094
+ checkCSRF(requestEv);
856
1095
  }
857
- function We(e, n) {
858
- if (In(
859
- e.request.headers,
1096
+ function checkCSRF(requestEv, laxProto) {
1097
+ const isForm = isContentType(
1098
+ requestEv.request.headers,
860
1099
  "application/x-www-form-urlencoded",
861
1100
  "multipart/form-data",
862
1101
  "text/plain"
863
- )) {
864
- const r = e.request.headers.get("origin"), i = e.url.origin;
865
- let o = r !== i;
866
- if (o && n && r?.replace(/^http(s)?/g, "") === i.replace(/^http(s)?/g, "") && (o = !1), o)
867
- throw e.error(
1102
+ );
1103
+ if (isForm) {
1104
+ const inputOrigin = requestEv.request.headers.get("origin");
1105
+ const origin = requestEv.url.origin;
1106
+ let forbidden = inputOrigin !== origin;
1107
+ if (forbidden && laxProto && inputOrigin?.replace(/^http(s)?/g, "") === origin.replace(/^http(s)?/g, "")) {
1108
+ forbidden = false;
1109
+ }
1110
+ if (forbidden) {
1111
+ throw requestEv.error(
868
1112
  403,
869
- `CSRF check failed. Cross-site ${e.method} form submissions are forbidden.
870
- The request origin "${r}" does not match the server origin "${i}".`
1113
+ `CSRF check failed. Cross-site ${requestEv.method} form submissions are forbidden.
1114
+ The request origin "${inputOrigin}" does not match the server origin "${origin}".`
871
1115
  );
1116
+ }
872
1117
  }
873
1118
  }
874
- function Mn(e) {
875
- return async (n) => {
876
- if (n.headersSent || n.sharedMap.has(ee))
1119
+ function renderQwikMiddleware(render) {
1120
+ return async (requestEv) => {
1121
+ if (requestEv.headersSent) {
1122
+ return;
1123
+ }
1124
+ const isPageDataReq = requestEv.sharedMap.has(IsQData);
1125
+ if (isPageDataReq) {
877
1126
  return;
878
- n.request.headers.forEach((f, u) => f);
879
- const r = n.headers;
880
- r.has("Content-Type") || r.set("Content-Type", "text/html; charset=utf-8");
881
- const { readable: i, writable: o } = new TextEncoderStream(), a = n.getWritableStream(), c = i.pipeTo(a, { preventClose: !0 }), s = o.getWriter(), l = n.status();
1127
+ }
1128
+ requestEv.request.headers.forEach((value, key) => value);
1129
+ const responseHeaders = requestEv.headers;
1130
+ if (!responseHeaders.has("Content-Type")) {
1131
+ responseHeaders.set("Content-Type", "text/html; charset=utf-8");
1132
+ }
1133
+ const { readable, writable } = new TextEncoderStream();
1134
+ const writableStream = requestEv.getWritableStream();
1135
+ const pipe = readable.pipeTo(writableStream, { preventClose: true });
1136
+ const stream = writable.getWriter();
1137
+ const status = requestEv.status();
882
1138
  try {
883
- const f = I(n) === "static", u = hn(n), m = await e({
884
- base: n.basePathname + "build/",
885
- stream: s,
886
- serverData: u,
1139
+ const isStatic = getRequestMode(requestEv) === "static";
1140
+ const serverData = getQwikRouterServerData(requestEv);
1141
+ const result = await render({
1142
+ base: requestEv.basePathname + "build/",
1143
+ stream,
1144
+ serverData,
887
1145
  containerAttributes: {
888
- "q:render": f ? "static" : "",
889
- ...u.containerAttributes
1146
+ ["q:render"]: isStatic ? "static" : "",
1147
+ ...serverData.containerAttributes
890
1148
  }
891
- }), p = {
892
- loaders: O(n),
893
- action: n.sharedMap.get(Q),
894
- status: l !== 200 ? l : 200,
895
- href: Z(n.url)
1149
+ });
1150
+ const qData = {
1151
+ loaders: getRequestLoaders(requestEv),
1152
+ action: requestEv.sharedMap.get(RequestEvSharedActionId),
1153
+ status: status !== 200 ? status : 200,
1154
+ href: getPathname(requestEv.url)
896
1155
  };
897
- typeof m.html == "string" && await s.write(m.html), n.sharedMap.set(Le, p);
1156
+ if (typeof result.html === "string") {
1157
+ await stream.write(result.html);
1158
+ }
1159
+ requestEv.sharedMap.set(RequestEvShareQData, qData);
898
1160
  } finally {
899
- await s.ready, await s.close(), await c;
1161
+ await stream.ready;
1162
+ await stream.close();
1163
+ await pipe;
900
1164
  }
901
- await a.close();
1165
+ await writableStream.close();
902
1166
  };
903
1167
  }
904
- async function Nn(e) {
1168
+ async function handleQDataRedirect(requestEv) {
905
1169
  try {
906
- await e.next();
907
- } catch (i) {
908
- if (!(i instanceof H))
909
- throw i;
1170
+ await requestEv.next();
1171
+ } catch (err) {
1172
+ if (!(err instanceof RedirectMessage$1)) {
1173
+ throw err;
1174
+ }
910
1175
  }
911
- if (e.headersSent)
1176
+ if (requestEv.headersSent) {
912
1177
  return;
913
- const n = e.status(), t = e.headers.get("Location");
914
- if (n >= 301 && n <= 308 && t) {
915
- const i = Cn(t);
916
- if (i) {
917
- e.headers.set("Location", i), e.getWritableStream().close();
1178
+ }
1179
+ const status = requestEv.status();
1180
+ const location = requestEv.headers.get("Location");
1181
+ const isRedirect = status >= 301 && status <= 308 && location;
1182
+ if (isRedirect) {
1183
+ const adaptedLocation = makeQDataPath(location);
1184
+ if (adaptedLocation) {
1185
+ requestEv.headers.set("Location", adaptedLocation);
1186
+ requestEv.getWritableStream().close();
918
1187
  return;
919
- } else
920
- e.status(200), e.headers.delete("Location");
1188
+ } else {
1189
+ requestEv.status(200);
1190
+ requestEv.headers.delete("Location");
1191
+ }
921
1192
  }
922
1193
  }
923
- async function xn(e) {
924
- if (await e.next(), e.headersSent || e.exited)
1194
+ async function renderQData(requestEv) {
1195
+ await requestEv.next();
1196
+ if (requestEv.headersSent || requestEv.exited) {
925
1197
  return;
926
- const n = e.status(), t = e.headers.get("Location");
927
- e.request.headers.forEach((l, f) => l), e.headers.set("Content-Type", "application/json; charset=utf-8");
928
- let r = O(e);
929
- const i = e.query.getAll(J), o = i.length > 0;
930
- if (o) {
931
- const l = {};
932
- for (const f of i) {
933
- const u = r[f];
934
- l[f] = u;
1198
+ }
1199
+ const status = requestEv.status();
1200
+ const redirectLocation = requestEv.headers.get("Location");
1201
+ requestEv.request.headers.forEach((value, key) => value);
1202
+ requestEv.headers.set("Content-Type", "application/json; charset=utf-8");
1203
+ let loaders = getRequestLoaders(requestEv);
1204
+ const selectedLoaderIds = requestEv.query.getAll(QLOADER_KEY);
1205
+ const hasCustomLoaders = selectedLoaderIds.length > 0;
1206
+ if (hasCustomLoaders) {
1207
+ const selectedLoaders = {};
1208
+ for (const loaderId of selectedLoaderIds) {
1209
+ const loader = loaders[loaderId];
1210
+ selectedLoaders[loaderId] = loader;
935
1211
  }
936
- r = l;
1212
+ loaders = selectedLoaders;
937
1213
  }
938
- const a = o ? {
1214
+ const qData = hasCustomLoaders ? {
939
1215
  // send minimal data to the client
940
- loaders: r,
941
- status: n !== 200 ? n : 200,
942
- href: Z(e.url)
1216
+ loaders,
1217
+ status: status !== 200 ? status : 200,
1218
+ href: getPathname(requestEv.url)
943
1219
  } : {
944
- loaders: r,
945
- action: e.sharedMap.get(Q),
946
- status: n !== 200 ? n : 200,
947
- href: Z(e.url),
948
- redirect: t ?? void 0,
949
- isRewrite: e.sharedMap.get(Pe)
950
- }, c = e.getWritableStream().getWriter(), s = await q([a]);
951
- c.write(E.encode(s)), e.sharedMap.set(Le, a), c.close();
1220
+ loaders,
1221
+ action: requestEv.sharedMap.get(RequestEvSharedActionId),
1222
+ status: status !== 200 ? status : 200,
1223
+ href: getPathname(requestEv.url),
1224
+ redirect: redirectLocation ?? void 0,
1225
+ isRewrite: requestEv.sharedMap.get(RequestEvIsRewrite)
1226
+ };
1227
+ const writer = requestEv.getWritableStream().getWriter();
1228
+ const data = await _serialize([qData]);
1229
+ writer.write(encoder.encode(data));
1230
+ requestEv.sharedMap.set(RequestEvShareQData, qData);
1231
+ writer.close();
952
1232
  }
953
- function Cn(e) {
954
- if (e.startsWith("/")) {
955
- if (!e.includes(C)) {
956
- const n = new URL(e, "http://localhost");
957
- return (n.pathname.endsWith("/") ? n.pathname.slice(0, -1) : n.pathname) + C + n.search;
1233
+ function makeQDataPath(href) {
1234
+ if (href.startsWith("/")) {
1235
+ if (!href.includes(QDATA_JSON)) {
1236
+ const url = new URL(href, "http://localhost");
1237
+ const pathname = url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname;
1238
+ return pathname + QDATA_JSON + url.search;
958
1239
  }
959
- return e;
960
- } else
961
- return;
1240
+ return href;
1241
+ } else {
1242
+ return void 0;
1243
+ }
962
1244
  }
963
- function me() {
964
- return typeof performance < "u" ? performance.now() : 0;
1245
+ function now() {
1246
+ return typeof performance !== "undefined" ? performance.now() : 0;
965
1247
  }
966
- async function j(e, n, t) {
967
- const r = me();
1248
+ async function measure(requestEv, name, fn) {
1249
+ const start = now();
968
1250
  try {
969
- return await t();
1251
+ return await fn();
970
1252
  } finally {
971
- const i = me() - r;
972
- let o = e.sharedMap.get(X);
973
- o || e.sharedMap.set(X, o = []), o.push([n, i]);
1253
+ const duration = now() - start;
1254
+ let measurements = requestEv.sharedMap.get(RequestEvShareServerTiming);
1255
+ if (!measurements) {
1256
+ requestEv.sharedMap.set(RequestEvShareServerTiming, measurements = []);
1257
+ }
1258
+ measurements.push([name, duration]);
974
1259
  }
975
1260
  }
976
- function In(e, ...n) {
977
- const t = e.get("content-type")?.split(/;/, 1)[0].trim() ?? "";
978
- return n.includes(t);
1261
+ function isContentType(headers, ...types) {
1262
+ const type = headers.get("content-type")?.split(/;/, 1)[0].trim() ?? "";
1263
+ return types.includes(type);
1264
+ }
1265
+ let _asyncRequestStore;
1266
+ if (isServer) {
1267
+ import("node:async_hooks").then((module) => {
1268
+ _asyncRequestStore = new module.AsyncLocalStorage();
1269
+ }).catch((err) => {
1270
+ console.warn(
1271
+ "\n=====================\n Qwik Router Warning:\n AsyncLocalStorage is not available, continuing without it.\n This impacts concurrent async server calls, where they lose access to the ServerRequestEv object.\n=====================\n\n",
1272
+ err
1273
+ );
1274
+ });
979
1275
  }
980
- let K;
981
- async function Wn(e, n) {
982
- const { render: t, checkOrigin: r } = n;
983
- let { qwikRouterConfig: i } = n;
984
- if (i || (K || (K = await import("@qwik-router-config")), i = K), !i)
1276
+ let qwikRouterConfigActual;
1277
+ async function requestHandler(serverRequestEv, opts) {
1278
+ const { render, checkOrigin } = opts;
1279
+ let { qwikRouterConfig } = opts;
1280
+ if (!qwikRouterConfig) {
1281
+ if (!qwikRouterConfigActual) {
1282
+ qwikRouterConfigActual = await import("@qwik-router-config");
1283
+ }
1284
+ qwikRouterConfig = qwikRouterConfigActual;
1285
+ }
1286
+ if (!qwikRouterConfig) {
985
1287
  throw new Error("qwikRouterConfig is required.");
986
- const { pathname: o, isInternal: a } = V(e.url.pathname), c = await ge(
987
- i,
988
- o,
989
- e.request.method,
990
- r ?? !0,
991
- t,
992
- a
1288
+ }
1289
+ const { pathname, isInternal } = getRouteMatchPathname(serverRequestEv.url.pathname);
1290
+ const routeAndHandlers = await loadRequestHandlers(
1291
+ qwikRouterConfig,
1292
+ pathname,
1293
+ serverRequestEv.request.method,
1294
+ checkOrigin ?? true,
1295
+ render,
1296
+ isInternal
993
1297
  );
994
- if (c) {
995
- const [s, l] = c;
996
- return sn(
997
- e,
998
- s,
999
- l,
1000
- async (u) => {
1001
- const { pathname: m } = V(u.pathname), p = await ge(
1002
- i,
1003
- m,
1004
- e.request.method,
1005
- r ?? !0,
1006
- t,
1007
- a
1008
- );
1009
- if (p) {
1010
- const [g, w] = p;
1011
- return { loadedRoute: g, requestHandlers: w };
1012
- } else
1013
- return { loadedRoute: null, requestHandlers: [] };
1014
- },
1015
- i.basePathname
1298
+ if (routeAndHandlers) {
1299
+ const [route, requestHandlers] = routeAndHandlers;
1300
+ const rebuildRouteInfo = async (url) => {
1301
+ const { pathname: pathname2 } = getRouteMatchPathname(url.pathname);
1302
+ const routeAndHandlers2 = await loadRequestHandlers(
1303
+ qwikRouterConfig,
1304
+ pathname2,
1305
+ serverRequestEv.request.method,
1306
+ checkOrigin ?? true,
1307
+ render,
1308
+ isInternal
1309
+ );
1310
+ if (routeAndHandlers2) {
1311
+ const [loadedRoute, requestHandlers2] = routeAndHandlers2;
1312
+ return { loadedRoute, requestHandlers: requestHandlers2 };
1313
+ } else {
1314
+ return { loadedRoute: null, requestHandlers: [] };
1315
+ }
1316
+ };
1317
+ return runQwikRouter(
1318
+ serverRequestEv,
1319
+ route,
1320
+ requestHandlers,
1321
+ rebuildRouteInfo,
1322
+ qwikRouterConfig.basePathname
1016
1323
  );
1017
1324
  }
1018
1325
  return null;
1019
1326
  }
1020
- async function ge(e, n, t, r, i, o) {
1021
- const { routes: a, serverPlugins: c, menus: s, cacheModules: l } = e, f = await ve(a, s, l, n, o), u = mn(
1022
- c,
1023
- f,
1024
- t,
1025
- r,
1026
- Mn(i),
1027
- o
1327
+ async function loadRequestHandlers(qwikRouterConfig, pathname, method, checkOrigin, renderFn, isInternal) {
1328
+ const { routes, serverPlugins, menus, cacheModules } = qwikRouterConfig;
1329
+ const route = await loadRoute(routes, menus, cacheModules, pathname, isInternal);
1330
+ const requestHandlers = resolveRequestHandlers(
1331
+ serverPlugins,
1332
+ route,
1333
+ method,
1334
+ checkOrigin,
1335
+ renderQwikMiddleware(renderFn),
1336
+ isInternal
1028
1337
  );
1029
- return u.length > 0 ? [f, u] : null;
1338
+ if (requestHandlers.length > 0) {
1339
+ return [route, requestHandlers];
1340
+ }
1341
+ return null;
1030
1342
  }
1031
- const Pn = [
1343
+ const notFounds = [
1032
1344
  // Will be replaced in post-build with the 404s generated by SSG
1033
1345
  "__QWIK_ROUTER_NOT_FOUND_ARRAY__"
1034
1346
  ];
1035
- function $n(e) {
1036
- for (const [n, t] of Pn)
1037
- if (e.startsWith(n))
1038
- return t;
1039
- return _e(404, "Resource Not Found");
1347
+ function getNotFound(prefix) {
1348
+ for (const [path, html] of notFounds) {
1349
+ if (prefix.startsWith(path)) {
1350
+ return html;
1351
+ }
1352
+ }
1353
+ return minimalHtmlResponse(404, "Resource Not Found");
1040
1354
  }
1041
- const v = /* @__PURE__ */ new Set(["__QWIK_ROUTER_STATIC_PATHS_ARRAY__"]);
1042
- function qn(e, n) {
1043
- if (e.toUpperCase() !== "GET")
1044
- return !1;
1045
- const t = n.pathname;
1046
- if (t.startsWith("/" + (globalThis.__QWIK_BUILD_DIR__ || "build") + "/") || t.startsWith("/" + (globalThis.__QWIK_ASSETS_DIR__ || "assets") + "/") || v.has(t))
1047
- return !0;
1048
- if (t.endsWith("/q-data.json")) {
1049
- const r = t.replace(/\/q-data.json$/, "");
1050
- if (v.has(r + "/") || v.has(r))
1051
- return !0;
1052
- }
1053
- return !1;
1355
+ const staticPaths = /* @__PURE__ */ new Set(["__QWIK_ROUTER_STATIC_PATHS_ARRAY__"]);
1356
+ function isStaticPath(method, url) {
1357
+ if (method.toUpperCase() !== "GET") {
1358
+ return false;
1359
+ }
1360
+ const p = url.pathname;
1361
+ if (p.startsWith("/" + (globalThis.__QWIK_BUILD_DIR__ || "build") + "/")) {
1362
+ return true;
1363
+ }
1364
+ if (p.startsWith("/" + (globalThis.__QWIK_ASSETS_DIR__ || "assets") + "/")) {
1365
+ return true;
1366
+ }
1367
+ if (staticPaths.has(p)) {
1368
+ return true;
1369
+ }
1370
+ if (p.endsWith("/q-data.json")) {
1371
+ const pWithoutQdata = p.replace(/\/q-data.json$/, "");
1372
+ if (staticPaths.has(pWithoutQdata + "/")) {
1373
+ return true;
1374
+ }
1375
+ if (staticPaths.has(pWithoutQdata)) {
1376
+ return true;
1377
+ }
1378
+ }
1379
+ return false;
1054
1380
  }
1055
- class Dn extends Error {
1056
- constructor(n, t) {
1057
- super(typeof t == "string" ? t : void 0), this.status = n, this.data = t;
1381
+ class ServerError extends Error {
1382
+ constructor(status, data) {
1383
+ super(typeof data === "string" ? data : void 0);
1384
+ this.status = status;
1385
+ this.data = data;
1058
1386
  }
1059
1387
  }
1060
- class $e {
1388
+ class AbortMessage {
1061
1389
  }
1062
- class Fn extends $e {
1390
+ class RedirectMessage extends AbortMessage {
1063
1391
  }
1064
- class Sn extends $e {
1065
- constructor(n) {
1066
- super(), this.pathname = n;
1392
+ class RewriteMessage extends AbortMessage {
1393
+ constructor(pathname) {
1394
+ super();
1395
+ this.pathname = pathname;
1067
1396
  }
1068
1397
  }
1069
- class Qn {
1070
- #e = null;
1071
- #n = new TextEncoder();
1072
- #t = new TransformStream({
1073
- transform: (n, t) => {
1074
- n = String(n);
1075
- let r = "";
1076
- for (let i = 0; i < n.length; i++) {
1077
- const o = n[i], a = o.charCodeAt(0);
1078
- if (this.#e !== null) {
1079
- const c = this.#e;
1080
- if (this.#e = null, 56320 <= a && a <= 57343) {
1081
- r += c + o;
1398
+ class _TextEncoderStream_polyfill {
1399
+ constructor() {
1400
+ __privateAdd(this, _pendingHighSurrogate, null);
1401
+ __privateAdd(this, _handle, new TextEncoder());
1402
+ __privateAdd(this, _transform, new TransformStream({
1403
+ transform: (chunk, controller) => {
1404
+ chunk = String(chunk);
1405
+ let finalChunk = "";
1406
+ for (let i = 0; i < chunk.length; i++) {
1407
+ const item = chunk[i];
1408
+ const codeUnit = item.charCodeAt(0);
1409
+ if (__privateGet(this, _pendingHighSurrogate) !== null) {
1410
+ const highSurrogate = __privateGet(this, _pendingHighSurrogate);
1411
+ __privateSet(this, _pendingHighSurrogate, null);
1412
+ if (56320 <= codeUnit && codeUnit <= 57343) {
1413
+ finalChunk += highSurrogate + item;
1414
+ continue;
1415
+ }
1416
+ finalChunk += "�";
1417
+ }
1418
+ if (55296 <= codeUnit && codeUnit <= 56319) {
1419
+ __privateSet(this, _pendingHighSurrogate, item);
1082
1420
  continue;
1083
1421
  }
1084
- r += "�";
1422
+ if (56320 <= codeUnit && codeUnit <= 57343) {
1423
+ finalChunk += "�";
1424
+ continue;
1425
+ }
1426
+ finalChunk += item;
1085
1427
  }
1086
- if (55296 <= a && a <= 56319) {
1087
- this.#e = o;
1088
- continue;
1428
+ if (finalChunk) {
1429
+ controller.enqueue(__privateGet(this, _handle).encode(finalChunk));
1089
1430
  }
1090
- if (56320 <= a && a <= 57343) {
1091
- r += "�";
1092
- continue;
1431
+ },
1432
+ flush: (controller) => {
1433
+ if (__privateGet(this, _pendingHighSurrogate) !== null) {
1434
+ controller.enqueue(new Uint8Array([239, 191, 189]));
1093
1435
  }
1094
- r += o;
1095
1436
  }
1096
- r && t.enqueue(this.#n.encode(r));
1097
- },
1098
- flush: (n) => {
1099
- this.#e !== null && n.enqueue(new Uint8Array([239, 191, 189]));
1100
- }
1101
- });
1437
+ }));
1438
+ }
1102
1439
  get encoding() {
1103
- return this.#n.encoding;
1440
+ return __privateGet(this, _handle).encoding;
1104
1441
  }
1105
1442
  get readable() {
1106
- return this.#t.readable;
1443
+ return __privateGet(this, _transform).readable;
1107
1444
  }
1108
1445
  get writable() {
1109
- return this.#t.writable;
1446
+ return __privateGet(this, _transform).writable;
1110
1447
  }
1111
1448
  get [Symbol.toStringTag]() {
1112
1449
  return "TextEncoderStream";
1113
1450
  }
1114
1451
  }
1452
+ _pendingHighSurrogate = new WeakMap();
1453
+ _handle = new WeakMap();
1454
+ _transform = new WeakMap();
1115
1455
  export {
1116
- $e as AbortMessage,
1117
- Fn as RedirectMessage,
1118
- Le as RequestEvShareQData,
1119
- Sn as RewriteMessage,
1120
- Dn as ServerError,
1121
- Qn as _TextEncoderStream_polyfill,
1122
- G as getErrorHtml,
1123
- $n as getNotFound,
1124
- qn as isStaticPath,
1125
- kn as mergeHeadersCookies,
1126
- Wn as requestHandler
1456
+ AbortMessage,
1457
+ RedirectMessage,
1458
+ RequestEvShareQData,
1459
+ RewriteMessage,
1460
+ ServerError,
1461
+ _TextEncoderStream_polyfill,
1462
+ _asyncRequestStore,
1463
+ getErrorHtml,
1464
+ getNotFound,
1465
+ isStaticPath,
1466
+ mergeHeadersCookies,
1467
+ requestHandler
1127
1468
  };