gemi 0.207.2 → 0.209.0

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 (253) hide show
  1. package/dist/ai/Agent.d.ts +83 -1
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentController.d.ts +7 -1
  4. package/dist/ai/AgentController.d.ts.map +1 -1
  5. package/dist/ai/AgentProvider.d.ts +20 -2
  6. package/dist/ai/AgentProvider.d.ts.map +1 -1
  7. package/dist/ai/FallbackProvider.d.ts.map +1 -1
  8. package/dist/ai/index.d.ts +4 -4
  9. package/dist/ai/index.d.ts.map +1 -1
  10. package/dist/ai/index.js +38 -38
  11. package/dist/ai/index.js.map +4 -4
  12. package/dist/ai/providers/call.d.ts +3 -1
  13. package/dist/ai/providers/call.d.ts.map +1 -1
  14. package/dist/ai/providers/capabilities.d.ts.map +1 -1
  15. package/dist/ai/providers/endpoints.d.ts +9 -0
  16. package/dist/ai/providers/endpoints.d.ts.map +1 -1
  17. package/dist/ai/providers/errors.d.ts +4 -2
  18. package/dist/ai/providers/errors.d.ts.map +1 -1
  19. package/dist/ai/providers/http.d.ts +33 -0
  20. package/dist/ai/providers/http.d.ts.map +1 -1
  21. package/dist/ai/providers/request.d.ts.map +1 -1
  22. package/dist/ai/store/stubAgentRun.d.ts +2 -1
  23. package/dist/ai/store/stubAgentRun.d.ts.map +1 -1
  24. package/dist/ai/testing/index.js +2 -2
  25. package/dist/ai/testing/index.js.map +1 -1
  26. package/dist/ai/types.d.ts +31 -2
  27. package/dist/ai/types.d.ts.map +1 -1
  28. package/dist/app/index.js +1 -1
  29. package/dist/bun/plugin.js +1 -1
  30. package/dist/bun/preload.js +1 -1
  31. package/dist/{chunk-24tj4dzx.js → chunk-094hbhc8.js} +2 -2
  32. package/dist/{chunk-24tj4dzx.js.map → chunk-094hbhc8.js.map} +1 -1
  33. package/dist/{chunk-1em8t2x1.js → chunk-101rvvje.js} +3 -3
  34. package/dist/{chunk-1em8t2x1.js.map → chunk-101rvvje.js.map} +1 -1
  35. package/dist/{chunk-qc0e278w.js → chunk-12gthjxx.js} +1 -1
  36. package/dist/{chunk-8ar7180x.js → chunk-1agwddws.js} +2 -2
  37. package/dist/{chunk-8ar7180x.js.map → chunk-1agwddws.js.map} +1 -1
  38. package/dist/{chunk-nfher0gz.js → chunk-1vnbw1d8.js} +2 -2
  39. package/dist/{chunk-nfher0gz.js.map → chunk-1vnbw1d8.js.map} +1 -1
  40. package/dist/{chunk-53fv4c39.js → chunk-24z18t5q.js} +4 -4
  41. package/dist/{chunk-53fv4c39.js.map → chunk-24z18t5q.js.map} +1 -1
  42. package/dist/{chunk-6ge27ygx.js → chunk-2jbdbvd8.js} +2 -2
  43. package/dist/{chunk-6ge27ygx.js.map → chunk-2jbdbvd8.js.map} +1 -1
  44. package/dist/{chunk-fhn92are.js → chunk-2k438dp6.js} +2 -2
  45. package/dist/{chunk-fhn92are.js.map → chunk-2k438dp6.js.map} +1 -1
  46. package/dist/{chunk-rjtge67x.js → chunk-3raywsbj.js} +2 -2
  47. package/dist/{chunk-rjtge67x.js.map → chunk-3raywsbj.js.map} +1 -1
  48. package/dist/{chunk-k8peybx0.js → chunk-3rgf7rsy.js} +3 -3
  49. package/dist/{chunk-k8peybx0.js.map → chunk-3rgf7rsy.js.map} +1 -1
  50. package/dist/{chunk-hthyn5pj.js → chunk-3wsmgdcr.js} +3 -3
  51. package/dist/{chunk-hthyn5pj.js.map → chunk-3wsmgdcr.js.map} +1 -1
  52. package/dist/{chunk-3830ee5d.js → chunk-5399t8zm.js} +2 -2
  53. package/dist/{chunk-3830ee5d.js.map → chunk-5399t8zm.js.map} +1 -1
  54. package/dist/{chunk-ndcqbwsj.js → chunk-641fns6j.js} +2 -2
  55. package/dist/{chunk-ndcqbwsj.js.map → chunk-641fns6j.js.map} +1 -1
  56. package/dist/{chunk-wrfz0jsw.js → chunk-6zcqa5fz.js} +2 -2
  57. package/dist/{chunk-wrfz0jsw.js.map → chunk-6zcqa5fz.js.map} +1 -1
  58. package/dist/{chunk-6zpf257t.js → chunk-716832vw.js} +2 -2
  59. package/dist/{chunk-6zpf257t.js.map → chunk-716832vw.js.map} +1 -1
  60. package/dist/{chunk-092magz7.js → chunk-7fr265wp.js} +2 -2
  61. package/dist/{chunk-092magz7.js.map → chunk-7fr265wp.js.map} +1 -1
  62. package/dist/{chunk-e0scxs81.js → chunk-8gyq2etb.js} +3 -3
  63. package/dist/{chunk-e0scxs81.js.map → chunk-8gyq2etb.js.map} +3 -3
  64. package/dist/{chunk-8q5kxzxn.js → chunk-8ty6yp6r.js} +3 -3
  65. package/dist/{chunk-8q5kxzxn.js.map → chunk-8ty6yp6r.js.map} +1 -1
  66. package/dist/{chunk-8ncqxja2.js → chunk-9d8tz60r.js} +1 -1
  67. package/dist/{chunk-xgc5tj8k.js → chunk-9qyedsvw.js} +3 -3
  68. package/dist/{chunk-xgc5tj8k.js.map → chunk-9qyedsvw.js.map} +1 -1
  69. package/dist/{chunk-zf1eqgzt.js → chunk-a76a7869.js} +2 -2
  70. package/dist/{chunk-72e857nw.js.map → chunk-a76a7869.js.map} +1 -1
  71. package/dist/{chunk-djnn8vvp.js → chunk-achvynaf.js} +2 -2
  72. package/dist/{chunk-djnn8vvp.js.map → chunk-achvynaf.js.map} +1 -1
  73. package/dist/{chunk-0eq7am78.js → chunk-ad0dx73f.js} +2 -2
  74. package/dist/{chunk-0eq7am78.js.map → chunk-ad0dx73f.js.map} +1 -1
  75. package/dist/{chunk-emt36pxm.js → chunk-agrr8f8y.js} +2 -2
  76. package/dist/{chunk-emt36pxm.js.map → chunk-agrr8f8y.js.map} +1 -1
  77. package/dist/{chunk-znw55n6g.js → chunk-arzp5dne.js} +2 -2
  78. package/dist/{chunk-znw55n6g.js.map → chunk-arzp5dne.js.map} +1 -1
  79. package/dist/{chunk-jn1h76sa.js → chunk-b1y54j6v.js} +2 -2
  80. package/dist/{chunk-jn1h76sa.js.map → chunk-b1y54j6v.js.map} +1 -1
  81. package/dist/{chunk-te4vz0rw.js → chunk-b51a77kv.js} +2 -2
  82. package/dist/{chunk-te4vz0rw.js.map → chunk-b51a77kv.js.map} +1 -1
  83. package/dist/{chunk-wfees83q.js → chunk-bdzj9znx.js} +3 -3
  84. package/dist/{chunk-wfees83q.js.map → chunk-bdzj9znx.js.map} +1 -1
  85. package/dist/{chunk-39dz1abf.js → chunk-bhc9vk13.js} +1 -1
  86. package/dist/{chunk-460c8k50.js → chunk-cfbhhfkv.js} +3 -3
  87. package/dist/{chunk-460c8k50.js.map → chunk-cfbhhfkv.js.map} +1 -1
  88. package/dist/{chunk-78g1cngk.js → chunk-dje6exhs.js} +2 -2
  89. package/dist/{chunk-78g1cngk.js.map → chunk-dje6exhs.js.map} +1 -1
  90. package/dist/{chunk-bpqkzpkt.js → chunk-dm6tkkwv.js} +2 -2
  91. package/dist/{chunk-bpqkzpkt.js.map → chunk-dm6tkkwv.js.map} +1 -1
  92. package/dist/{chunk-8gyanh1b.js → chunk-efskg8cp.js} +2 -2
  93. package/dist/{chunk-8gyanh1b.js.map → chunk-efskg8cp.js.map} +1 -1
  94. package/dist/{chunk-bxznwntw.js → chunk-enq03rgh.js} +2 -2
  95. package/dist/{chunk-bxznwntw.js.map → chunk-enq03rgh.js.map} +1 -1
  96. package/dist/{chunk-34vvev4a.js → chunk-ewhgsw1n.js} +2 -2
  97. package/dist/{chunk-34vvev4a.js.map → chunk-ewhgsw1n.js.map} +1 -1
  98. package/dist/{chunk-a7zqp5m7.js → chunk-fsae9dgb.js} +2 -2
  99. package/dist/{chunk-a7zqp5m7.js.map → chunk-fsae9dgb.js.map} +1 -1
  100. package/dist/{chunk-hqg4dfca.js → chunk-fv6ncgbc.js} +2 -2
  101. package/dist/{chunk-hqg4dfca.js.map → chunk-fv6ncgbc.js.map} +1 -1
  102. package/dist/{chunk-etcds9w3.js → chunk-h1f4f9wx.js} +2 -2
  103. package/dist/{chunk-etcds9w3.js.map → chunk-h1f4f9wx.js.map} +1 -1
  104. package/dist/{chunk-m3v661b3.js → chunk-h4byt0x3.js} +2 -2
  105. package/dist/{chunk-m3v661b3.js.map → chunk-h4byt0x3.js.map} +1 -1
  106. package/dist/{chunk-c8bvpkr2.js → chunk-hbdqv48k.js} +2 -2
  107. package/dist/{chunk-c8bvpkr2.js.map → chunk-hbdqv48k.js.map} +1 -1
  108. package/dist/{chunk-9m6mkaqb.js → chunk-hcysexst.js} +2 -2
  109. package/dist/{chunk-9m6mkaqb.js.map → chunk-hcysexst.js.map} +1 -1
  110. package/dist/{chunk-wpfempaj.js → chunk-hmccxtd3.js} +2 -2
  111. package/dist/{chunk-wpfempaj.js.map → chunk-hmccxtd3.js.map} +1 -1
  112. package/dist/{chunk-tx5zrdmb.js → chunk-jggtz103.js} +2 -2
  113. package/dist/{chunk-tx5zrdmb.js.map → chunk-jggtz103.js.map} +1 -1
  114. package/dist/{chunk-sjve1yvv.js → chunk-jr9y6k90.js} +1 -1
  115. package/dist/{chunk-6x2zbh1q.js → chunk-kax9ghny.js} +2 -2
  116. package/dist/{chunk-6x2zbh1q.js.map → chunk-kax9ghny.js.map} +1 -1
  117. package/dist/{chunk-q1t9gvm1.js → chunk-kbkyde5f.js} +2 -2
  118. package/dist/{chunk-q1t9gvm1.js.map → chunk-kbkyde5f.js.map} +1 -1
  119. package/dist/{chunk-77dt2tap.js → chunk-mtf5kzza.js} +2 -2
  120. package/dist/{chunk-77dt2tap.js.map → chunk-mtf5kzza.js.map} +1 -1
  121. package/dist/{chunk-3z8d8v8q.js → chunk-mxedsqbe.js} +3 -3
  122. package/dist/{chunk-3z8d8v8q.js.map → chunk-mxedsqbe.js.map} +1 -1
  123. package/dist/{chunk-jy61580r.js → chunk-n0sbg84n.js} +2 -2
  124. package/dist/{chunk-jy61580r.js.map → chunk-n0sbg84n.js.map} +1 -1
  125. package/dist/{chunk-06w8hhnk.js → chunk-n65hk6bq.js} +2 -2
  126. package/dist/{chunk-06w8hhnk.js.map → chunk-n65hk6bq.js.map} +1 -1
  127. package/dist/{chunk-4ksnhx8x.js → chunk-ntcj2sgv.js} +3 -3
  128. package/dist/{chunk-4ksnhx8x.js.map → chunk-ntcj2sgv.js.map} +1 -1
  129. package/dist/{chunk-scw0vknj.js → chunk-p27ft91c.js} +1 -1
  130. package/dist/{chunk-vyaedzr8.js → chunk-p608rrfc.js} +3 -3
  131. package/dist/{chunk-vyaedzr8.js.map → chunk-p608rrfc.js.map} +1 -1
  132. package/dist/chunk-pag82mxh.js +5 -0
  133. package/dist/{chunk-4q59y78y.js.map → chunk-pag82mxh.js.map} +1 -1
  134. package/dist/{chunk-yj1h4rzn.js → chunk-q634cwbc.js} +3 -3
  135. package/dist/{chunk-yj1h4rzn.js.map → chunk-q634cwbc.js.map} +1 -1
  136. package/dist/{chunk-09hzyf9g.js → chunk-q7x7ddw0.js} +3 -3
  137. package/dist/{chunk-09hzyf9g.js.map → chunk-q7x7ddw0.js.map} +1 -1
  138. package/dist/{chunk-65btke6p.js → chunk-qc7x8q1q.js} +2 -2
  139. package/dist/{chunk-65btke6p.js.map → chunk-qc7x8q1q.js.map} +1 -1
  140. package/dist/{chunk-wdrmzjtq.js → chunk-r5ggnywk.js} +2 -2
  141. package/dist/{chunk-wdrmzjtq.js.map → chunk-r5ggnywk.js.map} +1 -1
  142. package/dist/{chunk-72e857nw.js → chunk-raejxs3y.js} +2 -2
  143. package/dist/{chunk-zf1eqgzt.js.map → chunk-raejxs3y.js.map} +1 -1
  144. package/dist/{chunk-k8a41gkt.js → chunk-rffpqhn8.js} +2 -2
  145. package/dist/{chunk-k8a41gkt.js.map → chunk-rffpqhn8.js.map} +1 -1
  146. package/dist/{chunk-p9c5rc1z.js → chunk-rhyhxgxg.js} +3 -3
  147. package/dist/{chunk-p9c5rc1z.js.map → chunk-rhyhxgxg.js.map} +1 -1
  148. package/dist/chunk-szaq0f6n.js +24 -0
  149. package/dist/{chunk-e05rbjn2.js.map → chunk-szaq0f6n.js.map} +6 -5
  150. package/dist/{chunk-eeq9ty68.js → chunk-t0xfzpfa.js} +2 -2
  151. package/dist/{chunk-eeq9ty68.js.map → chunk-t0xfzpfa.js.map} +1 -1
  152. package/dist/chunk-t9gc6mhq.js +11 -0
  153. package/dist/{chunk-2e40rx0p.js.map → chunk-t9gc6mhq.js.map} +8 -8
  154. package/dist/{chunk-9qyet3nb.js → chunk-tj8wbxyz.js} +2 -2
  155. package/dist/{chunk-9qyet3nb.js.map → chunk-tj8wbxyz.js.map} +1 -1
  156. package/dist/{chunk-q751b0jx.js → chunk-tjfvkzq8.js} +1 -1
  157. package/dist/{chunk-njnng5ew.js → chunk-v10kckwp.js} +4 -4
  158. package/dist/{chunk-njnng5ew.js.map → chunk-v10kckwp.js.map} +1 -1
  159. package/dist/{chunk-ne51fxg2.js → chunk-vrpsgq3x.js} +2 -2
  160. package/dist/{chunk-ne51fxg2.js.map → chunk-vrpsgq3x.js.map} +1 -1
  161. package/dist/{chunk-jy26hy7z.js → chunk-w92n83g2.js} +2 -2
  162. package/dist/{chunk-jy26hy7z.js.map → chunk-w92n83g2.js.map} +1 -1
  163. package/dist/{chunk-dwya9z8p.js → chunk-wcpqn1pg.js} +2 -2
  164. package/dist/{chunk-dwya9z8p.js.map → chunk-wcpqn1pg.js.map} +1 -1
  165. package/dist/{chunk-zvk6dydb.js → chunk-wkh9xcdq.js} +2 -2
  166. package/dist/{chunk-zvk6dydb.js.map → chunk-wkh9xcdq.js.map} +1 -1
  167. package/dist/{chunk-7wzhdq1x.js → chunk-wy87gc0b.js} +3 -3
  168. package/dist/{chunk-7wzhdq1x.js.map → chunk-wy87gc0b.js.map} +1 -1
  169. package/dist/{chunk-aed0vv5g.js → chunk-xt90xbes.js} +2 -2
  170. package/dist/{chunk-aed0vv5g.js.map → chunk-xt90xbes.js.map} +1 -1
  171. package/dist/{chunk-6cx6kh04.js → chunk-y16vp7yf.js} +2 -2
  172. package/dist/{chunk-6cx6kh04.js.map → chunk-y16vp7yf.js.map} +1 -1
  173. package/dist/{chunk-cffx7wqp.js → chunk-yn3pf1fp.js} +2 -2
  174. package/dist/{chunk-cffx7wqp.js.map → chunk-yn3pf1fp.js.map} +1 -1
  175. package/dist/{chunk-s1fa5f8b.js → chunk-yzbj11dd.js} +2 -2
  176. package/dist/{chunk-s1fa5f8b.js.map → chunk-yzbj11dd.js.map} +1 -1
  177. package/dist/{chunk-vebstesm.js → chunk-zcx8n3mk.js} +3 -3
  178. package/dist/{chunk-vebstesm.js.map → chunk-zcx8n3mk.js.map} +1 -1
  179. package/dist/chunk-zrqzxc50.js +48 -0
  180. package/dist/chunk-zrqzxc50.js.map +27 -0
  181. package/dist/{chunk-8d2g78vc.js → chunk-zv6a6w1v.js} +2 -2
  182. package/dist/{chunk-8d2g78vc.js.map → chunk-zv6a6w1v.js.map} +1 -1
  183. package/dist/{chunk-1tc6j8bn.js → chunk-zzs96hc8.js} +2 -2
  184. package/dist/{chunk-1tc6j8bn.js.map → chunk-zzs96hc8.js.map} +1 -1
  185. package/dist/chunks/{RealtimeClient-DIxu38Vp.js → RealtimeClient-CmGMu3vA.js} +2 -2
  186. package/dist/chunks/{RealtimeClient-DIxu38Vp.js.map → RealtimeClient-CmGMu3vA.js.map} +1 -1
  187. package/dist/chunks/{ThemeProvider-DwBG9z7t.js → ThemeProvider-Cd7Ioorg.js} +30 -5
  188. package/dist/chunks/{ThemeProvider-DwBG9z7t.js.map → ThemeProvider-Cd7Ioorg.js.map} +1 -1
  189. package/dist/chunks/{fetchFileRequest-DbtCribY.js → fetchFileRequest-VDh0ivL-.js} +2 -2
  190. package/dist/chunks/{fetchFileRequest-DbtCribY.js.map → fetchFileRequest-VDh0ivL-.js.map} +1 -1
  191. package/dist/chunks/{live-Dw8WcP_Q.js → live-DAt2MPE2.js} +3 -3
  192. package/dist/chunks/{live-Dw8WcP_Q.js.map → live-DAt2MPE2.js.map} +1 -1
  193. package/dist/chunks/{mutationExtras-BHBySXVs.js → mutationExtras-CodkSO_f.js} +2 -2
  194. package/dist/chunks/{mutationExtras-BHBySXVs.js.map → mutationExtras-CodkSO_f.js.map} +1 -1
  195. package/dist/chunks/{subscriptionStream-CdYxY-Q6.js → subscriptionStream-CotXoVnq.js} +2 -2
  196. package/dist/chunks/{subscriptionStream-CdYxY-Q6.js.map → subscriptionStream-CotXoVnq.js.map} +1 -1
  197. package/dist/client/ClientRouter.d.ts.map +1 -1
  198. package/dist/client/ComponentContext.d.ts.map +1 -1
  199. package/dist/client/chunkLoadRecovery.d.ts +24 -1
  200. package/dist/client/chunkLoadRecovery.d.ts.map +1 -1
  201. package/dist/client/index.js +36 -7
  202. package/dist/client/index.js.map +1 -1
  203. package/dist/config/index.js +1 -1
  204. package/dist/console/run.js +2 -2
  205. package/dist/console/run.js.map +1 -1
  206. package/dist/container/index.js +2 -2
  207. package/dist/container/index.js.map +1 -1
  208. package/dist/database/index.js +2 -2
  209. package/dist/database/index.js.map +1 -1
  210. package/dist/email/index.js +2 -2
  211. package/dist/email/index.js.map +1 -1
  212. package/dist/facades/index.js +2 -2
  213. package/dist/facades/index.js.map +1 -1
  214. package/dist/foundation/index.js +2 -2
  215. package/dist/foundation/index.js.map +1 -1
  216. package/dist/http/index.js +2 -2
  217. package/dist/http/index.js.map +1 -1
  218. package/dist/i18n/dictionaryRuntime.js +2 -2
  219. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  220. package/dist/i18n/index.js +2 -2
  221. package/dist/i18n/index.js.map +1 -1
  222. package/dist/kernel/index.js +2 -2
  223. package/dist/kernel/index.js.map +1 -1
  224. package/dist/orm/index.js +2 -2
  225. package/dist/orm/index.js.map +1 -1
  226. package/dist/probe/index.js +2 -2
  227. package/dist/probe/index.js.map +1 -1
  228. package/dist/server/assetFallback.d.ts +46 -0
  229. package/dist/server/assetFallback.d.ts.map +1 -0
  230. package/dist/server/httpProd.d.ts.map +1 -1
  231. package/dist/server/index.js +2 -2
  232. package/dist/server/index.js.map +1 -1
  233. package/dist/services/index.js +2 -2
  234. package/dist/services/index.js.map +1 -1
  235. package/dist/services/queue/work.js +2 -2
  236. package/dist/services/queue/work.js.map +1 -1
  237. package/dist/stats/route-table.js +1 -1
  238. package/dist/support/index.js +2 -2
  239. package/dist/support/index.js.map +1 -1
  240. package/dist/testing/index.js +2 -2
  241. package/dist/vitest/index.js +1 -1
  242. package/package.json +1 -1
  243. package/dist/chunk-2e40rx0p.js +0 -11
  244. package/dist/chunk-4q59y78y.js +0 -5
  245. package/dist/chunk-e05rbjn2.js +0 -24
  246. package/dist/chunk-v1d7xya8.js +0 -46
  247. package/dist/chunk-v1d7xya8.js.map +0 -27
  248. /package/dist/{chunk-qc0e278w.js.map → chunk-12gthjxx.js.map} +0 -0
  249. /package/dist/{chunk-8ncqxja2.js.map → chunk-9d8tz60r.js.map} +0 -0
  250. /package/dist/{chunk-39dz1abf.js.map → chunk-bhc9vk13.js.map} +0 -0
  251. /package/dist/{chunk-sjve1yvv.js.map → chunk-jr9y6k90.js.map} +0 -0
  252. /package/dist/{chunk-scw0vknj.js.map → chunk-p27ft91c.js.map} +0 -0
  253. /package/dist/{chunk-q751b0jx.js.map → chunk-tjfvkzq8.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Th as TV}from"./chunk-hthyn5pj.js";import{li as KV}from"./chunk-1em8t2x1.js";import{Ai as pW,Aj as GZ,Ci as Z3,Cj as oB,Di as Z8,Ei as tW,Ej as aB,Fi as C2,Gi as u,Ii as S8,Ji as R$,Ki as m2,Li as A2,Mi as S2,Ni as X6,Oi as A,Pi as IW,Qi as o8,Ri as LZ,Si as E8,Ti as O6,Vi as w$,Wi as h,Xi as n4,ej as D6,kj as L6,mi as B3,qi as MB,ri as j9,si as z9,sj as k1,ti as A8,ui as _8,xi as I8,yi as x8,yj as nG,zi as DB,zj as XZ}from"./chunk-7wzhdq1x.js";import{Hj as e1,Ij as q0,Jj as Z$,Kj as G9}from"./chunk-aed0vv5g.js";import{Lj as WZ,Mj as eW,Qj as t9,Rj as J8,Sj as P}from"./chunk-jy26hy7z.js";import{Zj as gG,ak as i3}from"./chunk-yj1h4rzn.js";import{ek as BY,hk as dB}from"./chunk-3z8d8v8q.js";import{Ek as $$,zk as k$}from"./chunk-wdrmzjtq.js";import{Sk as HG}from"./chunk-6cx6kh04.js";import{Tk as QZ,Wk as hB}from"./chunk-06w8hhnk.js";import{Xk as _1}from"./chunk-24tj4dzx.js";import{$k as H8,Yk as B6,Zk as s0,_k as f1,al as DV,cl as iZ,dl as sB,ml as K8,ol as LV,pl as MV,ql as HV}from"./chunk-xgc5tj8k.js";import{Fl as q1}from"./chunk-etcds9w3.js";import{Kl as cW,Pl as uW}from"./chunk-nfher0gz.js";import{$l as c,Wl as dW}from"./chunk-65btke6p.js";import{am as $3,dm as H}from"./chunk-vyaedzr8.js";import{lm as qW}from"./chunk-tx5zrdmb.js";import{mm as tB}from"./chunk-0eq7am78.js";import{Am as EW}from"./chunk-77dt2tap.js";import{Bm as B8,Dm as HB}from"./chunk-ne51fxg2.js";import{Im as W8}from"./chunk-zf1eqgzt.js";function Y6($){return typeof $==="function"&&$.prototype!==void 0}var N2=Symbol.for("gemi.HttpResponse"),AV=new Set([301,302,303,307,308]);class U1{kind;body;status;headers;[N2]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return P2(J,"json"),new U1("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return U1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!AV.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new U1("empty",void 0,J,Y)}static noContent($={}){return new U1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return P2(J,"text"),new U1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function P2($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function a1($){return typeof $==="object"&&$!==null&&$[N2]===!0}function SV($,Z,J={}){return U1.error($,Z,J)}function e0($){return typeof $==="string"?[$]:$}function j6($,Z){let J=$.split(/[\\/]/).pop()??"",W=Z?"attachment":"inline",Y=J.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${W}; filename="${Y}"; filename*=UTF-8''${encodeURIComponent(J)}`}function EV($){return"total"in $&&"partial"in $&&"body"in $}function _2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function X3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":x8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function bV($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(EV($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function C8($,Z){if($ instanceof Response)return $;if(!$)return _2();let J=await bV($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return _2()}let{range:G}=Z;if(G){if(z<=0)return X3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=_8(G,z);if(!B)return X3(z);W=W.slice(B.start,B.end+1),Y=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,V=Q?206:J.status,F=new Headers;if(F.set("Accept-Ranges","bytes"),F.set("Content-Type",J.type||"application/octet-stream"),F.set("X-Content-Type-Options","nosniff"),Q)F.set("Content-Range",I8(Y,j,z)),F.set("Content-Length",String(j-Y+1));else if(z>=0)F.set("Content-Length",String(z));if(J.name)F.set("Content-Disposition",j6(J.name,J.download));if(J.etag)F.set("ETag",J.etag);if(J.lastModified)F.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))F.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:V,headers:F})}return new Response(W,{status:V,headers:F})}function RV($){return Y6($)}function I2($,Z){if($.length===0)return $();return $(Z??new A)}class n{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];__internal_bodyLimitDefault;constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!RV(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(this.source){let Z=new this.source.controller;return I2(Z[this.methodName].bind(Z),$)}return I2(this.handler,$)}middleware($){return this.middlewares=e0($),this}}class E2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=e0($),this}async run(){let $=new A,Z=$.headers.toJSON();for(let J of C2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(S2($.rawRequest))throw new S8(A2($.rawRequest));throw J}}}class b2{constructor(...$){return new n(...$)}}class R2 extends n{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),J=Z?.req?.rawRequest,W=A8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(a1(Y))return Y;return await C8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof E8)return X3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class k2{constructor(...$){return new R2(...$)}}class w2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new n("GET",$,"list"),post:new n("POST",$,"store")},this.second={get:new n("GET",$,"show"),put:new n("PUT",$,"update"),delete:new n("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class x0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new n("GET",$,Z)}post($,Z){return new n("POST",$,Z)}put($,Z){return new n("PUT",$,Z)}patch($,Z){return new n("PATCH",$,Z)}delete($,Z){return new n("DELETE",$,Z)}resource($){return new w2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${x2($)}.`);return kV($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${x2($)}.`);return wV($)}file($,Z){return new b2("GET",$,Z)}stream($,Z){return new k2("GET",$,Z)}proxy($,Z={}){return new E2($,Z)}}function x2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function kV($){let Z={stream:new n("POST",$,"stream"),attach:new n("POST",$,"attach"),watch:new n("POST",$,"watch"),stop:new n("POST",$,"stop"),upload:new n("POST",$,"upload")};return Z.stream.__internal_bodyLimitDefault="none",Z.upload.__internal_bodyLimitDefault="upload",class extends x0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/watch":Z.watch,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach),Z.watch.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function wV($){let Z={start:new n("POST",$,"voiceStart"),update:new n("PATCH",$,"voiceUpdate"),end:new n("DELETE",$,"voiceEnd")};return class extends x0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var t1="access_token";function b$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function z6($,Z){let J=b$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var fV=/^[A-Za-z0-9_-]+$/,qV=/^:[A-Za-z_][A-Za-z0-9_]*$/,f2=/^[A-Za-z0-9_-]{1,128}$/,vV=/^[A-Za-z0-9_.:-]+$/;class i extends Error{constructor($){super($);this.name="InvalidChannelError"}}function q2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function FZ($){if(typeof $!=="string"||$.length===0)throw new i("A channel pattern must be a non-empty string.");if($.length>255)throw new i(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(qV.test(W)){let Y=W.slice(1);if(J.has(Y))throw new i(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new i(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!fV.test(W))throw new i(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function G3($,Z={}){let J=FZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new i(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!f2.test(G))throw new i(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new i(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new i(`The topic built from "${$}" is longer than 255 characters.`);return Y}function b8($){if(FZ($).some((J)=>J.startsWith(":")))throw new i(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function v2($){if(typeof $!=="string"||$.length===0||$.length>64||!vV.test($))throw new i(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function g2($,Z){if($===Z)return!0;if($===U0)return Z.startsWith(`${U0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&f2.test(W[j]))}var U0="user";function UZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return G3(`${U0}.:id`,{id:Z})}class Z0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class G6 extends Z0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');let J=Z==="upload"?this.config.uploadLimit??R$("50mb"):R$(Z);return X6(this.req.rawRequest,J),{}}}function gV($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}function yV($){return{"body-limit":G6.configure({uploadLimit:$})}}class r1{config;static token="middleware";defaultBodyLimit;uploadBodyLimit;builtinAliases;constructor($){this.config=$;let Z=$.bodyLimit===null||$.bodyLimit===void 0?null:R$($.bodyLimit);this.defaultBodyLimit=Z===1/0?null:Z,this.uploadBodyLimit=R$($.uploadBodyLimit??"50mb"),this.builtinAliases=yV(this.uploadBodyLimit)}get aliases(){return{...this.builtinAliases,...this.config.aliases}}applyDefaultBodyLimit($,Z){if(this.defaultBodyLimit===null||Z==="none"||m2($))return;let J=Z==="upload"?Math.max(this.defaultBodyLimit,this.uploadBodyLimit):this.defaultBodyLimit;X6($,J,{checkDeclared:!1,uploadLimit:this.uploadBodyLimit})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new A,J=this.aliases,W=[];for(let[Y,j]of gV($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:y2(z)})}}else if(Y6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:y2(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await mV(W.slice(j+1)),z}return Y})()}}function y2($){return $?.runsOnRefusal===!0}async function mV($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class Q6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...e0($)],this}events(...$){return this}}class c2{static __brand="ChannelRouter";channels={};public(){return new Q6("public")}private($){return new Q6("private",$)}async authorize($,Z,J={},W={}){try{cV(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!u2(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===U0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=G3(Z,J??{})}catch(G){if(G instanceof i)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new A($,z,"api",Z);return P.exit(()=>B6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(Y.middlewares.length>0)await H(r1).runMiddleware(Y.middlewares);if(Z===U0){let Q=await h2(X);if(!Q)return{ok:!1,code:"denied"};if(j=UZ(Q),Y.visibility==="private"&&Y.authorizer){if(await p2(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await p2(Y.authorizer,X,z):await h2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(dV(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function hV($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;l2(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function u2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function h2($){if(!P.getStore().user&&b$($)===null)return null;try{return await f0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function p2($,Z,J){if(pV($))return new $().authorize(Z,J);return $(Z,J)}function pV($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function dV($){return $?.kind===e1||$$($)||k$($)}var d2=new WeakSet;function cV($){if(d2.has($))return;l2($),d2.add($)}function l2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!u2(Y))throw new i(`The channel "${W}" is not declared with this.public() or this.private().`);let j=FZ(W);if(j[0].startsWith(":"))throw new i(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==U0&&j.length===2&&j[0]===U0)throw new i(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==U0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new i(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===U0?[U0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(uV(J[W].segments,J[Y].segments))throw new i(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function uV($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class R8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class V6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class k8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function lV($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function iV($,Z){let J=lV($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class i2{static __brand="McpRouter";routes={};scopes;param($){return new R8($.as,$.input,$.bind)}fromTool($,Z={}){return new k8($,Z)}fromApiRoute($,Z,J){return new V6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,V=Object.keys(Y??{});if(V.length===0)throw Error(`${Q}: declare at least one audience.`);let F={},B=new Map;for(let U of V){let{name:D,casing:O,description:L,params:M,files:T,...K}=Y[U],N=D??(O?iV(W,O):W);if(B.has(N))throw Error(`${Q}: the audiences "${B.get(N)}" and "${U}" are both named "${N}". Give one its own name or casing.`);B.set(N,U);let R=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof R!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let C={...G,...K,description:R};if(z||M)C.params={...z,...M};if(X||T)C.files={...X,...T};F[N]=new V6($,Z,C)}return F}}function O0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class w8 extends q0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class b1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new w8([O0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new w8($,Z)}}class s2{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return b1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function f8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",j6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class n2{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function o2($,Z){if(a1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class a2{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=o2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=e0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class t2{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends R1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends R1{routes=J??{}}}else this.children=class extends R1{routes=Z},this.handler=()=>({})}async run($,Z){let J=o2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class R1{middlewares=[];featureGates=[];routes={};view($,Z){return new a2($,Z)}file($){return new n2($)}redirect($){return new s2($)}layout($,Z,J){return new t2($,Z,J)}}function sV($){return $}function nV(){return{aliases:{},global:[],bodyLimit:"1mb",uploadBodyLimit:"50mb"}}var l0="redirect";function O1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function OZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function q8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function oV($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(c).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function aV($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function F6($,Z){let J=Z||H(b).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=oV($,!W);if(W||!aV(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class r2 extends Z0{async run($){let Z=P.getStore(),J=Z.req;if(Z.user)return{};let W=await z6(H(b),J);if(!W)throw new w$({redirectTo:F6(J,$)});return Z.setUser(W),{}}}var g8="gemi_same_site",v8="private, no-cache, no-store, max-age=0, must-revalidate";class U6 extends Z0{run(){let $=P.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(g8))return{};if(b$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(g8,"1"),new e2(`${W.pathname}${W.search}`)}}class e2 extends q0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=tV($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":v8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":v8}},viewData:{status:200,data:{},headers:{"Cache-Control":v8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function tV($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class $9 extends Z0{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var Z9={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class J9 extends Z0{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...Z9,...this.config.origins[Z]};for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...Z9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var rV="Rate limit exceeded";class J$ extends q0{result;retryAfter;constructor($,Z=rV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?y8($):{}};this.payload={api:{status:429,data:{error:{...Z$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function y8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class D1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(W9("window",W),W9("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new J$(W,typeof J==="function"?J(W):J);return W}}function W9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as m8}from"net";function f$($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return m8(j)===6?j:null}if(m8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&m8(J[1])===4?J[1]:null}class X9 extends Z0{async run($,Z){let J=eV();if(!J)return{};let W=await J.consume(this.key(),{limit:Y9($)??this.config.limit,window:Y9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(y8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new J$(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=j9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${DZ(this.req)}:${this.req.routePath??"*"}`}}function eV(){try{let $=H();return $.bound(D1)?$.make(D1):null}catch{return null}}function DZ($){let Z=z9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return f$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function Y9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class Q9 extends Z0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new h8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new h8;return{}}}class h8 extends q0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:G9("csrf","Invalid CSRF token",403)}},view:{}}}class B9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class V9{all($,Z){return!0}}class p8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new LZ:new O6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new A,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends Z0{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof LZ:$ instanceof O6}}function $F($){return new p8($)}async function M6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await UF($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return FF(z,Z,J,$.url)}async function FF($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:V}=await Y.read();if(Q)break;if(z+V.byteLength>Z){if(!J)throw new L6(W,Z);j.push(V.subarray(0,Z-z)),z=Z;break}j.push(V),z+=V.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function UF($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function H6($){return new TextDecoder("utf-8").decode($)}var OF={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function q$($){return $.replace(/[&<>"']/g,(Z)=>OF[Z])}var DF={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function d8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return DF[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function c8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function F9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(d8($.slice(W)));return}if(Y>W)Z.text(d8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(c8($.slice(Y+2,j).trim())),W=j+1}else{let j=LF($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=c8(z.slice(0,G));if(Q){if(Z.open(Q,MF(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function LF($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function MF($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[c8(W[1])]=d8(W[2]??W[3]??"");return Z}class j0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var M9="http://www.sitemaps.org/schemas/sitemap/0.9",HF="http://www.w3.org/1999/xhtml",i8=`<?xml version="1.0" encoding="UTF-8"?>
2
+ import{Uh as TV}from"./chunk-3wsmgdcr.js";import{mi as KV}from"./chunk-101rvvje.js";import{Ai as DB,Aj as XZ,Bi as pW,Bj as GZ,Di as Z3,Dj as oB,Ei as Z8,Fi as tW,Fj as aB,Gi as C2,Hi as u,Ji as S8,Ki as R$,Li as m2,Mi as A2,Ni as S2,Oi as X6,Pi as A,Qi as IW,Ri as o8,Si as LZ,Ti as E8,Ui as O6,Wi as w$,Xi as h,Yi as n4,fj as D6,lj as L6,ni as B3,ri as MB,si as j9,ti as z9,tj as k1,ui as A8,vi as _8,yi as I8,zi as x8,zj as nG}from"./chunk-wy87gc0b.js";import{Ij as e1,Jj as q0,Kj as Z$,Lj as G9}from"./chunk-xt90xbes.js";import{Mj as WZ,Nj as eW,Rj as t9,Sj as J8,Tj as P}from"./chunk-w92n83g2.js";import{_j as gG,bk as i3}from"./chunk-q634cwbc.js";import{fk as BY,ik as dB}from"./chunk-mxedsqbe.js";import{Ak as k$,Fk as $$}from"./chunk-r5ggnywk.js";import{Tk as HG}from"./chunk-y16vp7yf.js";import{Uk as QZ,Xk as hB}from"./chunk-n65hk6bq.js";import{Yk as _1}from"./chunk-094hbhc8.js";import{$k as f1,Zk as B6,_k as s0,al as H8,bl as DV,dl as iZ,el as sB,nl as K8,pl as LV,ql as MV,rl as HV}from"./chunk-9qyedsvw.js";import{Gl as q1}from"./chunk-h1f4f9wx.js";import{Ll as cW,Ql as uW}from"./chunk-1vnbw1d8.js";import{Xl as dW,am as c}from"./chunk-qc7x8q1q.js";import{bm as $3,em as H}from"./chunk-p608rrfc.js";import{mm as qW}from"./chunk-jggtz103.js";import{nm as tB}from"./chunk-ad0dx73f.js";import{Bm as EW}from"./chunk-mtf5kzza.js";import{Cm as B8,Em as HB}from"./chunk-vrpsgq3x.js";import{Jm as W8}from"./chunk-a76a7869.js";function Y6($){return typeof $==="function"&&$.prototype!==void 0}var N2=Symbol.for("gemi.HttpResponse"),AV=new Set([301,302,303,307,308]);class U1{kind;body;status;headers;[N2]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return P2(J,"json"),new U1("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return U1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!AV.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new U1("empty",void 0,J,Y)}static noContent($={}){return new U1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return P2(J,"text"),new U1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function P2($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function a1($){return typeof $==="object"&&$!==null&&$[N2]===!0}function SV($,Z,J={}){return U1.error($,Z,J)}function e0($){return typeof $==="string"?[$]:$}function j6($,Z){let J=$.split(/[\\/]/).pop()??"",W=Z?"attachment":"inline",Y=J.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${W}; filename="${Y}"; filename*=UTF-8''${encodeURIComponent(J)}`}function EV($){return"total"in $&&"partial"in $&&"body"in $}function _2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function X3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":x8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function bV($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(EV($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function C8($,Z){if($ instanceof Response)return $;if(!$)return _2();let J=await bV($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return _2()}let{range:G}=Z;if(G){if(z<=0)return X3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=_8(G,z);if(!B)return X3(z);W=W.slice(B.start,B.end+1),Y=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,V=Q?206:J.status,F=new Headers;if(F.set("Accept-Ranges","bytes"),F.set("Content-Type",J.type||"application/octet-stream"),F.set("X-Content-Type-Options","nosniff"),Q)F.set("Content-Range",I8(Y,j,z)),F.set("Content-Length",String(j-Y+1));else if(z>=0)F.set("Content-Length",String(z));if(J.name)F.set("Content-Disposition",j6(J.name,J.download));if(J.etag)F.set("ETag",J.etag);if(J.lastModified)F.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))F.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:V,headers:F})}return new Response(W,{status:V,headers:F})}function RV($){return Y6($)}function I2($,Z){if($.length===0)return $();return $(Z??new A)}class n{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];__internal_bodyLimitDefault;constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!RV(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(this.source){let Z=new this.source.controller;return I2(Z[this.methodName].bind(Z),$)}return I2(this.handler,$)}middleware($){return this.middlewares=e0($),this}}class E2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=e0($),this}async run(){let $=new A,Z=$.headers.toJSON();for(let J of C2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(S2($.rawRequest))throw new S8(A2($.rawRequest));throw J}}}class b2{constructor(...$){return new n(...$)}}class R2 extends n{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),J=Z?.req?.rawRequest,W=A8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(a1(Y))return Y;return await C8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof E8)return X3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class k2{constructor(...$){return new R2(...$)}}class w2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new n("GET",$,"list"),post:new n("POST",$,"store")},this.second={get:new n("GET",$,"show"),put:new n("PUT",$,"update"),delete:new n("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class x0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new n("GET",$,Z)}post($,Z){return new n("POST",$,Z)}put($,Z){return new n("PUT",$,Z)}patch($,Z){return new n("PATCH",$,Z)}delete($,Z){return new n("DELETE",$,Z)}resource($){return new w2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${x2($)}.`);return kV($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${x2($)}.`);return wV($)}file($,Z){return new b2("GET",$,Z)}stream($,Z){return new k2("GET",$,Z)}proxy($,Z={}){return new E2($,Z)}}function x2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function kV($){let Z={stream:new n("POST",$,"stream"),attach:new n("POST",$,"attach"),watch:new n("POST",$,"watch"),stop:new n("POST",$,"stop"),upload:new n("POST",$,"upload")};return Z.stream.__internal_bodyLimitDefault="none",Z.upload.__internal_bodyLimitDefault="upload",class extends x0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/watch":Z.watch,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach),Z.watch.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function wV($){let Z={start:new n("POST",$,"voiceStart"),update:new n("PATCH",$,"voiceUpdate"),end:new n("DELETE",$,"voiceEnd")};return class extends x0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var t1="access_token";function b$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function z6($,Z){let J=b$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var fV=/^[A-Za-z0-9_-]+$/,qV=/^:[A-Za-z_][A-Za-z0-9_]*$/,f2=/^[A-Za-z0-9_-]{1,128}$/,vV=/^[A-Za-z0-9_.:-]+$/;class i extends Error{constructor($){super($);this.name="InvalidChannelError"}}function q2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function FZ($){if(typeof $!=="string"||$.length===0)throw new i("A channel pattern must be a non-empty string.");if($.length>255)throw new i(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(qV.test(W)){let Y=W.slice(1);if(J.has(Y))throw new i(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new i(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!fV.test(W))throw new i(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function G3($,Z={}){let J=FZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new i(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!f2.test(G))throw new i(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new i(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new i(`The topic built from "${$}" is longer than 255 characters.`);return Y}function b8($){if(FZ($).some((J)=>J.startsWith(":")))throw new i(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function v2($){if(typeof $!=="string"||$.length===0||$.length>64||!vV.test($))throw new i(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function g2($,Z){if($===Z)return!0;if($===U0)return Z.startsWith(`${U0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&f2.test(W[j]))}var U0="user";function UZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return G3(`${U0}.:id`,{id:Z})}class Z0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class G6 extends Z0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');let J=Z==="upload"?this.config.uploadLimit??R$("50mb"):R$(Z);return X6(this.req.rawRequest,J),{}}}function gV($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}function yV($){return{"body-limit":G6.configure({uploadLimit:$})}}class r1{config;static token="middleware";defaultBodyLimit;uploadBodyLimit;builtinAliases;constructor($){this.config=$;let Z=$.bodyLimit===null||$.bodyLimit===void 0?null:R$($.bodyLimit);this.defaultBodyLimit=Z===1/0?null:Z,this.uploadBodyLimit=R$($.uploadBodyLimit??"50mb"),this.builtinAliases=yV(this.uploadBodyLimit)}get aliases(){return{...this.builtinAliases,...this.config.aliases}}applyDefaultBodyLimit($,Z){if(this.defaultBodyLimit===null||Z==="none"||m2($))return;let J=Z==="upload"?Math.max(this.defaultBodyLimit,this.uploadBodyLimit):this.defaultBodyLimit;X6($,J,{checkDeclared:!1,uploadLimit:this.uploadBodyLimit})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new A,J=this.aliases,W=[];for(let[Y,j]of gV($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:y2(z)})}}else if(Y6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:y2(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await mV(W.slice(j+1)),z}return Y})()}}function y2($){return $?.runsOnRefusal===!0}async function mV($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class Q6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...e0($)],this}events(...$){return this}}class c2{static __brand="ChannelRouter";channels={};public(){return new Q6("public")}private($){return new Q6("private",$)}async authorize($,Z,J={},W={}){try{cV(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!u2(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===U0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=G3(Z,J??{})}catch(G){if(G instanceof i)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new A($,z,"api",Z);return P.exit(()=>B6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(Y.middlewares.length>0)await H(r1).runMiddleware(Y.middlewares);if(Z===U0){let Q=await h2(X);if(!Q)return{ok:!1,code:"denied"};if(j=UZ(Q),Y.visibility==="private"&&Y.authorizer){if(await p2(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await p2(Y.authorizer,X,z):await h2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(dV(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function hV($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;l2(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function u2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function h2($){if(!P.getStore().user&&b$($)===null)return null;try{return await f0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function p2($,Z,J){if(pV($))return new $().authorize(Z,J);return $(Z,J)}function pV($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function dV($){return $?.kind===e1||$$($)||k$($)}var d2=new WeakSet;function cV($){if(d2.has($))return;l2($),d2.add($)}function l2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!u2(Y))throw new i(`The channel "${W}" is not declared with this.public() or this.private().`);let j=FZ(W);if(j[0].startsWith(":"))throw new i(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==U0&&j.length===2&&j[0]===U0)throw new i(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==U0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new i(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===U0?[U0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(uV(J[W].segments,J[Y].segments))throw new i(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function uV($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class R8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class V6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class k8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function lV($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function iV($,Z){let J=lV($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class i2{static __brand="McpRouter";routes={};scopes;param($){return new R8($.as,$.input,$.bind)}fromTool($,Z={}){return new k8($,Z)}fromApiRoute($,Z,J){return new V6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,V=Object.keys(Y??{});if(V.length===0)throw Error(`${Q}: declare at least one audience.`);let F={},B=new Map;for(let U of V){let{name:D,casing:O,description:L,params:M,files:T,...K}=Y[U],N=D??(O?iV(W,O):W);if(B.has(N))throw Error(`${Q}: the audiences "${B.get(N)}" and "${U}" are both named "${N}". Give one its own name or casing.`);B.set(N,U);let R=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof R!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let C={...G,...K,description:R};if(z||M)C.params={...z,...M};if(X||T)C.files={...X,...T};F[N]=new V6($,Z,C)}return F}}function O0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class w8 extends q0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class b1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new w8([O0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new w8($,Z)}}class s2{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return b1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function f8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",j6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class n2{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function o2($,Z){if(a1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class a2{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=o2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=e0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class t2{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends R1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends R1{routes=J??{}}}else this.children=class extends R1{routes=Z},this.handler=()=>({})}async run($,Z){let J=o2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class R1{middlewares=[];featureGates=[];routes={};view($,Z){return new a2($,Z)}file($){return new n2($)}redirect($){return new s2($)}layout($,Z,J){return new t2($,Z,J)}}function sV($){return $}function nV(){return{aliases:{},global:[],bodyLimit:"1mb",uploadBodyLimit:"50mb"}}var l0="redirect";function O1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function OZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function q8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function oV($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(c).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function aV($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function F6($,Z){let J=Z||H(b).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=oV($,!W);if(W||!aV(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class r2 extends Z0{async run($){let Z=P.getStore(),J=Z.req;if(Z.user)return{};let W=await z6(H(b),J);if(!W)throw new w$({redirectTo:F6(J,$)});return Z.setUser(W),{}}}var g8="gemi_same_site",v8="private, no-cache, no-store, max-age=0, must-revalidate";class U6 extends Z0{run(){let $=P.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(g8))return{};if(b$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(g8,"1"),new e2(`${W.pathname}${W.search}`)}}class e2 extends q0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=tV($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":v8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":v8}},viewData:{status:200,data:{},headers:{"Cache-Control":v8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function tV($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class $9 extends Z0{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var Z9={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class J9 extends Z0{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...Z9,...this.config.origins[Z]};for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...Z9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var rV="Rate limit exceeded";class J$ extends q0{result;retryAfter;constructor($,Z=rV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?y8($):{}};this.payload={api:{status:429,data:{error:{...Z$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function y8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class D1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(W9("window",W),W9("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new J$(W,typeof J==="function"?J(W):J);return W}}function W9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as m8}from"net";function f$($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return m8(j)===6?j:null}if(m8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&m8(J[1])===4?J[1]:null}class X9 extends Z0{async run($,Z){let J=eV();if(!J)return{};let W=await J.consume(this.key(),{limit:Y9($)??this.config.limit,window:Y9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(y8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new J$(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=j9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${DZ(this.req)}:${this.req.routePath??"*"}`}}function eV(){try{let $=H();return $.bound(D1)?$.make(D1):null}catch{return null}}function DZ($){let Z=z9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return f$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function Y9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class Q9 extends Z0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new h8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new h8;return{}}}class h8 extends q0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:G9("csrf","Invalid CSRF token",403)}},view:{}}}class B9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class V9{all($,Z){return!0}}class p8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new LZ:new O6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new A,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends Z0{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof LZ:$ instanceof O6}}function $F($){return new p8($)}async function M6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await UF($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return FF(z,Z,J,$.url)}async function FF($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:V}=await Y.read();if(Q)break;if(z+V.byteLength>Z){if(!J)throw new L6(W,Z);j.push(V.subarray(0,Z-z)),z=Z;break}j.push(V),z+=V.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function UF($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function H6($){return new TextDecoder("utf-8").decode($)}var OF={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function q$($){return $.replace(/[&<>"']/g,(Z)=>OF[Z])}var DF={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function d8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return DF[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function c8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function F9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(d8($.slice(W)));return}if(Y>W)Z.text(d8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(c8($.slice(Y+2,j).trim())),W=j+1}else{let j=LF($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=c8(z.slice(0,G));if(Q){if(Z.open(Q,MF(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function LF($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function MF($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[c8(W[1])]=d8(W[2]??W[3]??"");return Z}class j0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var M9="http://www.sitemaps.org/schemas/sitemap/0.9",HF="http://www.w3.org/1999/xhtml",i8=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  `,U9=`<urlset xmlns="${M9}" xmlns:xhtml="${HF}">
4
4
  `,O9=`</urlset>
5
5
  `,v$=50000,Q3=52428800,D9=2048,KF=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),TF=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,PF="application/xml; charset=utf-8",L9=new TextEncoder;function s8($,Z){let J;try{J=new URL($)}catch{throw new j0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new j0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>D9)throw new j0(`Sitemap: ${Z} is over ${D9} characters: "${W.slice(0,80)}\u2026".`);return W}function H9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new j0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!TF.test($))throw new j0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function NF($){let Z=s8($.loc,"loc"),J=`<url><loc>${q$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${q$(H9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!KF.has($.changefreq))throw new j0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);J+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let W=$.priority;if(!Number.isFinite(W)||W<0||W>1)throw new j0(`Sitemap: priority ${W} of ${Z} is not between 0 and 1.`);J+=`<priority>${Number(W.toFixed(4))}</priority>`}for(let W of $.alternates??[]){let Y=W.hrefLang?.trim();if(!Y)throw new j0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=s8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${q$(Y)}" href="${q$(j)}"/>`}return`${J}</url>
@@ -20,7 +20,7 @@ c.remove(e==='dark'?'light':'dark');c.add(e);d.style.colorScheme=e}catch(x){}}($
20
20
  `)),Z.onSettle((V)=>{if(X||V.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([V.path,V.variantKey,V.data])}
21
21
  `))});let Q=setTimeout(()=>G(!0),J);Z.allSettled().then(()=>G(!1),()=>G(!1))},cancel(){j(!1)}})}import{Fragment as lx,createContext as XM,createElement as ix,lazy as sx,use as nx,useContext as ox}from"react";import{createContext as dL}from"react";var cL=dL(null);import{createContext as iL,useContext as Kx}from"react";import{useContext as Ox}from"react";import{createContext as uL}from"react";import{jsx as Vx}from"react/jsx-runtime";var lL=uL({});var sL="gemi.islandI18n",nL=globalThis[Symbol.for(sL)]??=iL(null);import{createContext as pQ,useMemo as vx,useRef as gx}from"react";class TW{subscribers=new Set;value;constructor($){this.value=$,this.subscribe=this.subscribe.bind(this),this.next=this.next.bind(this),this.getValue=this.getValue.bind(this)}subscribe($){return this.subscribers.add($),()=>{this.subscribers.delete($)}}next($){this.value=$,this.subscribers.forEach((Z)=>Z($))}getValue(){return this.value}}function wQ($,Z=Date.now()){if($==null)return;let J=$.trim();if(J==="")return;if(/^\d+$/.test(J))return Number(J)*1000;let W=Date.parse(J);if(Number.isNaN(W))return;return Math.max(0,W-Z)}function fQ($){if($.status===204||$.status===205)return Promise.resolve(null);let Z=$.headers?.get?.("Content-Type")??"";if(/^text\/plain\b/i.test(Z))return $.text();return $.json()}var qQ="/auth/sign-in",oL=1000,aL=2,PW,NW=null,J3="idle",vQ=0,_W=[];function yQ($,Z){if($!==401)return!1;let J=Z&&typeof Z==="object"?Z.error:void 0;if(typeof J==="string")return J==="Authentication error";return!!J&&typeof J==="object"&&J.kind==="authentication"}function tL($){let Z=$?.get?.(IW);if(typeof Z!=="string"||Z==="")return qQ;if(/^https?:\/\//i.test(Z))return Z;if(Z.startsWith("/")&&!Z.startsWith("//")&&!Z.includes("\\"))return Z;return qQ}function rL(){let $=NW?.current();if($)return $;if(typeof window>"u")return null;return{pathname:window.location.pathname,search:window.location.search}}var gQ=($)=>$.replace(/\/+$/,"")||"/";function eL($,Z){let J=q8($),W=new URL($,"http://gemi.invalid");if(!J&&gQ(W.pathname)===gQ(Z.pathname))return null;return W.searchParams.set(l0,J?Z.pathname:`${Z.pathname}${Z.search}`),J?W.href:`${W.pathname}${W.search}`}function $M($){if(!q8($)&&NW)NW.replace($);else window.location.replace($)}function mQ($){if(!PW||typeof window>"u")return;if(!yQ($.status,$.body))return;if($.path.split("?")[0]==="/auth/me")return;if(J3==="handled")return;if(J3==="idle"&&vQ>=aL)return;if($.refetch)_W.push($.refetch);if(J3==="checking")return;J3="checking",vQ++;let Z=$;setTimeout(()=>{ZM(Z)},oL)}async function ZM($){let Z=!1,J=$.headers?.get?.(IW)?$.headers:null;try{let X=await fetch("/api/auth/me",{cache:"no-store",headers:{Accept:"application/json"}}),G=null;try{G=await X.json()}catch{}if(Z=yQ(X.status,G),Z&&!J)J=X.headers}catch{}let W=_W;if(_W=[],!Z){J3="idle";for(let X of W)try{X()}catch(G){console.error(G)}return}J3="handled";let Y=rL();if(!Y)return;let j=eL(tL(J),Y);if(!j)return;let z={source:$.source,path:$.path,error:$.error,signInUrl:j,redirect:()=>$M(j)};try{if(PW==="redirect")z.redirect();else PW?.(z)}catch(X){console.error(X)}}var xW=5000,JM=2147483647;class zZ{store;staleVariants=new Set;lastFetchRecord=new Map;key;inflight=new Set;pending=new Map;watchers=new Map;failures=new Map;retryTimers=new Map;seq=0;issued=new Map;applied=new Map;controllers=new Map;streamed=new Set;constructor($,Z){this.key=$,this.store=new TW(new Map),this.hydrate(Z)}hydrate($,Z=!1){let J=this.store.getValue(),W=Date.now(),Y=!1;for(let[j,z]of Object.entries($??{})){if(z===void 0)continue;let X=J.get(j);if(X?.loading)continue;if(X?.hasData&&X.data===z)continue;if(this.fill(J,j,z,W),Z)this.streamed.add(j);Y=!0}if(Y)this.store.next(J)}pendingFor($){let Z=this.pending.get($);if(!Z){let J;Z={promise:new Promise((Y)=>{J=Y}),resolve:J},this.pending.set($,Z)}return Z}settle($){let Z=this.pending.get($);if(Z)this.pending.delete($),Z.resolve()}isStale($,Z){if(this.staleVariants.has($))return!0;let J=Date.now();return J-(this.lastFetchRecord.get($)??J)>=Z}peek($){return this.store.getValue().get($)}peekForHydration($){return this.streamed.has($)?void 0:this.peek($)}isFetching($){return this.inflight.has($)}start($){if(typeof window>"u")return;if(this.store.getValue().has($))return;if(this.inflight.has($))return;this.resolveVariant($,!0)}read($,Z=xW){let J=this.peek($);if(J?.hasData){if(!this.inflight.has($)&&this.isStale($,Z))this.lastFetchRecord.set($,Date.now()),this.resolveVariant($,!0);return{state:J}}if(J?.error)return{state:J};if(typeof window>"u")return{state:J};let W=this.pendingFor($);if(!this.inflight.has($))this.resolveVariant($,!0);return{state:J,promise:W.promise}}getVariant($,Z=xW){let J=this.store.getValue();if(!J.has($)){if(!this.inflight.has($))this.resolveVariant($)}else{let W=J.get($);if(!W.loading&&!this.inflight.has($)){if(!W.hasData)return this.resolveVariant($),J.get($);if(this.isStale($,Z))return this.lastFetchRecord.set($,Date.now()),this.resolveVariant($,!0),J.get($)}}return J.get($)}revalidate($,Z=xW){if(typeof window>"u")return;if(this.inflight.has($))return;let J=this.peek($);if(J?.loading)return;if(J?.hasData){if(!this.isStale($,Z))return;this.lastFetchRecord.set($,Date.now())}this.resolveVariant($,!0)}clearError($){let Z=this.store.getValue(),J=!1;for(let[W,Y]of Z){if($!==void 0&&W!==$)continue;if(Y.error)Z.set(W,{...Y,error:null}),J=!0}if(J)this.store.next(Z)}retain($){this.watchers.set($,(this.watchers.get($)??0)+1);let Z=!1;return()=>{if(Z)return;Z=!0;let J=(this.watchers.get($)??1)-1;if(J>0)this.watchers.set($,J);else this.watchers.delete($),this.cancelRetry($),this.scheduleAbort($)}}scheduleAbort($){if(!this.controllers.has($))return;setTimeout(()=>{if(this.watchers.has($))return;this.abort($)},0)}abort($){let Z=this.controllers.get($);if(!Z)return;this.controllers.delete($);for(let J of Z)J.abort()}failureCount($){return this.failures.get($)??0}scheduleRetry($,Z){if(typeof window>"u")return;if(this.retryTimers.has($)||this.inflight.has($))return;let J=Math.min(Math.max(0,Z||0),JM),W=setTimeout(()=>{if(this.retryTimers.delete($),!this.watchers.has($))return;if(this.inflight.has($))return;let Y=this.peek($);if(!Y?.error||Y.loading)return;this.resolveVariant($,Y.hasData,!0,!0)},J);this.retryTimers.set($,W)}cancelRetry($){let Z=this.retryTimers.get($);if(Z!==void 0)clearTimeout(Z),this.retryTimers.delete($)}retryNow($){if(typeof window>"u")return;if(this.inflight.has($))return;let Z=this.peek($);if(!Z?.error||Z.loading)return;this.resolveVariant($,!0)}variantKeys(){return[...this.store.getValue().keys()]}invalidate($,Z){this.dropHttpCache($);let J=this.store.getValue(),W=J.get($);if(Z&&W?.hasData)this.markApplied($),this.store.next(J.set($,{...W,data:Z(W.data),error:null}));if(this.staleVariants.add($),this.watchers.has($))this.resolveVariant($,!1,!1)}dropHttpCache($){let Z=[typeof window<"u"&&window.location?.origin?window.location.origin:"",this.key,$].filter((J)=>J.length>0).join("?");try{if(caches)caches?.delete(Z)}catch{}}mutate($,Z=(J)=>J){this.dropHttpCache($);let J=this.store.getValue(),W=J.get($);if(!W||!W.hasData){this.resolveVariant($,!1,!1);return}let Y=Z(W.data);this.markApplied($),this.staleVariants.add($),this.store.next(J.set($,{loading:!1,data:Y,hasData:!0,error:null,version:W.version})),this.resolveVariant($,!1,!1)}fill($,Z,J,W){$.set(Z,{loading:!1,data:J,hasData:!0,error:null,version:W}),this.staleVariants.delete(Z),this.lastFetchRecord.set(Z,W),this.failures.delete(Z),this.cancelRetry(Z),this.settle(Z)}refetch($){this.resolveVariant($,!1,!1)}markApplied($){this.applied.set($,this.seq)}async resolveVariant($,Z=!1,J=!0,W=!1){if(typeof window>"u")return;this.cancelRetry($),this.inflight.add($);let Y=++this.seq;this.issued.set($,Y);let j=typeof AbortController>"u"?null:new AbortController;if(j){let F=this.controllers.get($);if(!F)F=new Set,this.controllers.set($,F);F.add(j)}let z=()=>this.issued.get($)===Y,X=()=>(this.applied.get($)??0)>=Y,G=()=>{this.failures.set($,W?(this.failures.get($)??0)+1:1)},Q=this.store.getValue(),V=(F)=>{if(!z())return;G();let B=Q.get($);this.store.next(Q.set($,{loading:!1,data:B?.data,hasData:B?.hasData??!1,error:F,version:B?.version}))};try{let F=Q.get($);if(!Z)Q.set($,{loading:!0,data:F?.data,hasData:F?.hasData??!1,error:F?.error,version:F?.version});let B=null,U=null,D=[this.key,$].filter((O)=>O.length).join("?");try{U=await fetch(`/api${D}`,{cache:J&&!this.staleVariants.has($)?"default":"reload",signal:j?.signal});try{B=await fQ(U)}catch(O){if(U.ok)throw O;B=null}}catch(O){if(j?.signal.aborted){let L=Q.get($);if(z()&&L?.loading)this.store.next(Q.set($,{...L,loading:!1}));return}console.error(`Error fetching url /api${D}`,O),V(O);return}if(U.ok){if(X()){let L=Q.get($);if(z()&&L?.loading)this.store.next(Q.set($,{...L,loading:!1}));return}this.applied.set($,Y);let O=Q.get($);this.store.next(Q.set($,{loading:z()?!1:O?.loading??!1,data:B,hasData:!0,error:null,version:Date.now()})),this.staleVariants.delete($),this.lastFetchRecord.set($,Date.now()),this.failures.delete($)}else{let O=new t0(this.key,$,U.status,B,wQ(U.headers?.get?.("retry-after")));if(V(O),z())mQ({source:"query",path:this.key,status:U.status,body:B,headers:U.headers,error:O,refetch:()=>this.resolveVariant($,!0,!1)})}}finally{if(j){let F=this.controllers.get($);if(F?.delete(j),F?.size===0)this.controllers.delete($)}if(z())this.inflight.delete($);this.settle($)}}}import{jsx as YM}from"react/jsx-runtime";var mx=pQ(null);var dQ=pQ({getResource:($,Z={})=>{return new zZ($,Z)},hydrate:()=>{},clearErrors:()=>{}});function WM(){let $=new Map;return{getResource(Z,J){let W=$.get(Z);if(!W)W=new zZ(Z,J??{}),$.set(Z,W);return W},hydrate(Z,J=!1){if(!Z)return;for(let[W,Y]of Object.entries(Z)){if(!Y||typeof Y!=="object")continue;let j=$.get(W);if(!j)j=new zZ(W,{}),$.set(W,j);j.hydrate(Y,J)}},clearErrors(){for(let Z of $.values())Z.clearError()}}}var hQ="gemi.islandQueries";if(typeof window<"u"){let $=globalThis;if(!$[Symbol.for(hQ)]){let Z=WM(),J={seed:Z.hydrate,Provider:({children:W})=>YM(dQ.Provider,{value:Z,children:W})};$[Symbol.for(hQ)]=J}}import{createContext as jM}from"react";var zM=jM(null);function cQ($,Z={},J){let W=new Set,Y=new Map,j=J?{ensure(Q,V){let F=J.find(Q,V);if(!F||F.source!=="prefetch"||F.status==="rejected")return null;return z(F),F}}:null,z=(Q)=>Y.set(`${Q.path}?${Q.variantKey}`,Q),G={queries:j,queriesRead:Y,createQueryManager:()=>{if(!J)return null;let Q=new Map;return{getResource(V,F){let B=Q.get(V);if(!B){let U=new Map(J.entriesFor(V).filter((O)=>O.source==="prefetch"&&O.status==="resolved").map((O)=>[O.variantKey,O]));B=new zZ(V,U.size>0?Object.fromEntries(Array.from(U,([O,L])=>[O,L.data])):F??{});let D=B.peek.bind(B);B.peek=(O)=>{let L=U.get(O);if(L)z(L);return D(O)},Q.set(V,B)}return B},hydrate(){},clearErrors(){}}},islands:[],render:$,instances:new WeakMap,count:0,i18n:{},localeAware:Boolean(Z.currentLocale),i18nUsed:!1,dictionaries:[],sink:{use(Q,V,F){let B=`${Q} ${V}`;if(W.has(B))return;W.add(B),G.dictionaries.push([Q,V,F])},onUse(){}}};for(let Q of["currentLocale","defaultLocale","timeZone"])Object.defineProperty(G.i18n,Q,{enumerable:!0,get(){return G.i18nUsed=!0,Z[Q]}});return G}function uQ($){if(!$.i18nUsed&&!$.localeAware)return;let{currentLocale:Z,defaultLocale:J,timeZone:W}=$.i18n;return{...Z?{currentLocale:Z}:{},...J?{defaultLocale:J}:{},...W?{timeZone:W}:{},...$.dictionaries.length>0?{dictionaries:$.dictionaries}:{}}}function lQ($){let Z;for(let J of $.queriesRead.values()){if(J.status!=="resolved")continue;Z??={},(Z[J.path]??={})[J.variantKey]=J.data}return Z}var a3="gemi-slot",iQ="data-slot",sQ="data-gemi-slot";var GM=Symbol.for("gemi.staticRender"),nQ=globalThis[GM]??=XM(null);import{createHash as eQ}from"crypto";var CW='var r=document,i=window,a=history;i.__gemi_nav?.d();var C=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:C.signal,...s}),q=i.__gemi_nav={d:()=>C.abort()},y=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},L=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},D=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")y(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>y(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),y(n,s)});for(let m of n.children)l.observe(m)}}},R=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(R)?.content,O=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],N=O(r),p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},v={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,Y=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},j=(t)=>{let e=r.body,n=t.body,s=L(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),D(e,s)},H=async(t,e)=>{let n=++b,s=!e&&v[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||O(d)!=N)throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),j(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)Y(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),v[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=v[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(v[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(R)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();D(r,L(r));_(!0);';import{createHash as QM}from"crypto";import{existsSync as aQ,readFileSync as BM}from"fs";import{join as bW}from"path";var tQ=".script",VM=[".ts",".js"],FM="document-scripts.json",rQ="data-gemi-script",UM=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function OM($){if(typeof $!=="string"||!UM.test($))throw Error(`A static view's \`script\` is a path under app/views without the ".script.ts" suffix, e.g. "site/clicks". Got ${JSON.stringify($)}.`)}function DM($,Z){for(let J of VM){let W=bW($,"views",`${Z}${tQ}${J}`);if(aQ(W))return W}return null}async function oQ($){let Z=await Bun.build({entrypoints:[$],target:"browser",format:"iife",minify:!0,throw:!1});if(!Z.success||!Z.outputs[0]){let W=Z.logs.map((Y)=>String(Y)).join(`
22
22
  `);throw Error(`The document script ${$} does not bundle.
23
- ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function RW($){return`'sha256-${QM("sha256").update($).digest("base64")}'`}var AW,SW=new Map;function LM(){if(AW===void 0){let $=bW(EW(),"dist","server",FM);AW=aQ($)?JSON.parse(BM($,"utf8")):null}return AW??null}async function kW($){OM($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=LM()?.[$];if(j!==void 0)return j;let z=SW.get($);if(z)return z}let J=bW(EW(),"app"),W=DM(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${tQ}.ts (or .js).`);if(!Z)return oQ(W);let Y=oQ(W);return SW.set($,Y),Y.catch(()=>SW.delete($)),Y}async function XC($){return RW(await kW($))}var MM="gemi-islands",HM="gemi-island-i18n",KM="gemi-island-queries",DC=`'sha256-${eQ("sha256").update(qW).digest("base64")}'`;function wW($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var fW=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),LC=`'sha256-${eQ("sha256").update(CW).digest("base64")}'`,TM='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',PM="gemi-static";function $B($,Z,J,W,Y,j,z){let X=new Set,G=[];if(J)G=Z.islands.map((T)=>{let K=T.module?J(T.module):void 0;if(!K)return console.error(`[gemi] island ${T.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(T.load==="eager"){for(let N of K.preload)X.add(N);if(T.preloadDynamic)for(let N of K.dynamicPreload??[])X.add(N)}return{s:K.src,e:T.export,l:T.load}});let Q=G.some((T)=>T!==null),V=j?`<script type="module" ${rQ}="${fW(j.name)}">${j.source}</script>`:"";if(j)z?.push(j.source);if(!Q&&!Y)return wW($,"</head>",V,!1);let B=(Y?`<meta name="${PM}" content="${fW(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...X].map((T)=>`<link rel="modulepreload" href="${fW(T)}"/>`).join("")+V,U=Y?CW:qW,D=W?TM+U:U;z?.push(D);let O=Q?uQ(Z):void 0,L=Q?lQ(Z):void 0,M=(Q?`<script type="application/json" id="${MM}">${i0({i:G})}</script>`:"")+(O?`<script type="application/json" id="${HM}">${i0(O)}</script>`:"")+(L?`<script type="application/json" id="${KM}">${i0(L)}</script>`:"")+`<script type="module">${D}</script>`;return wW(wW($,"</head>",B,!1),"</body>",M,!0)}function NM($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let Y=J.exec($);Y;Y=J.exec($))if(W+=Y[1]?-1:1,W===0)return J.lastIndex;return-1}function ZB($){let Z=`<template ${sQ}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=NM($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let G=`<${a3} ${iQ}="${j}" style="display:contents"></${a3}>`;$=$.split(G).join(`<${a3} style="display:contents">${X}</${a3}>`)}return $}function vW($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function jB($,Z){if($.getSetCookie().length>0){if(Z.cacheControl&&Bun.env.NODE_ENV!=="production")console.warn(`[gemi] A static view with cacheControl "${Z.cacheControl}" set a cookie, so it was sent "private, no-store" instead. Static pages are cacheable only when nothing on them sets a cookie.`);$.set("Cache-Control","private, no-store");return}if(Z.cacheControl&&!$.has("Cache-Control"))$.set("Cache-Control",Z.cacheControl)}function _M($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var JB=new Set,IM=new Set(["public","private","s-maxage","proxy-revalidate"]);function gW($,Z){let J=$.get("Cache-Control");if(!J||$.getSetCookie().length===0)return;if(!/(^|[\s,])(public|s-maxage)\b/i.test(J))return;let W=zB(J);if(Bun.env.NODE_ENV!=="production"&&!JB.has(Z)){JB.add(Z);let Y=[...new Set($.getSetCookie().map((j)=>j.split("=")[0]))];console.warn(`[gemi] The view "${Z??""}" sets cookies (${Y.join(", ")}) on a response with Cache-Control "${J}", so it was sent "${W}" instead: a shared cache would hand those cookies to every visitor. To let a CDN cache the page, make it a static view with .static({ cacheControl }).`)}$.set("Cache-Control",W)}function zB($){return["private",...$.split(",").map((J)=>J.trim()).filter((J)=>{let W=J.split("=")[0].trim().toLowerCase();return W!==""&&!IM.has(W)})].join(", ")}var WB=new Set;function XB($,Z,J){let W=$.get("Cache-Control");if(!W||!/(^|[\s,])(public|s-maxage)\b/i.test(W))return;let Y=zB(W);if(J&&Bun.env.NODE_ENV!=="production"&&!WB.has(Z))WB.add(Z),console.warn(`[gemi] The static view "${Z??""}" asked for a CSP nonce (cspNonce()) on a response with Cache-Control "${W}", so it was sent "${Y}" instead: a shared cache would hand the same nonce to every visitor. Allow a static page's scripts by hash instead (route.view.csp does).`);$.set("Cache-Control",Y)}var YB=new Set;function GB($,Z){if(!_M($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!YB.has(Z))YB.add(Z),console.warn(`[gemi] The file route "${Z??""}" set a cookie on a response with Cache-Control "${$.headers.get("Cache-Control")}", so the cookie was not sent: a shared cache would hand it to every visitor. Make the response private, or set the cookie elsewhere.`);try{return $.headers.delete("Set-Cookie"),$}catch{let J=new Headers($.headers);return J.delete("Set-Cookie"),new Response($.body,{status:$.status,statusText:$.statusText,headers:J})}}var xM="'strict-dynamic' 'self' https: 'unsafe-inline'",QB="Content-Security-Policy",BB="Content-Security-Policy-Report-Only";function CM($,Z={}){let J=[...$.nonce?[`'nonce-${$.nonce}'`]:[],...$.hashes??[]],W=[J.length>0?`script-src ${J.join(" ")} ${xM}`:"script-src 'none'","object-src 'none'","base-uri 'self'"];if(Z.reportUri)W.push(`report-uri ${Z.reportUri}`);return W.join("; ")}function yW($,Z,J){if(!Z)return;if($.has(QB)||$.has(BB))return;let W=Z===!0?{}:Z;$.set(W.reportOnly?BB:QB,CM({nonce:J.nonce,hashes:[...new Set(J.inlineScripts??[])].map(RW)},W))}var SM=async()=>(await import("./chunk-k8peybx0.js")).default,mW,t3=async(...$)=>{return mW??=import("react-dom/server.browser").catch((Z)=>{throw mW=void 0,Z}),(await mW).renderToReadableStream(...$)},FB=1e4,UB="no-locale",EM="no-theme";async function bM($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var lW="/assets";function RM($){return $===lW||$.startsWith(`${lW}/`)}function kM($){let Z=$.filter(RM);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${lW}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else, or set \`assetRoutes: true\` on these views' config (route.view or a route.domains group's view).`)}}function wM($){let Z=H(B1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function hW($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function fM($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class r3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=bQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;translate;csp;constructor($,Z={}){let J=aG();if(this.partialRendering=$.partialRendering??J.partialRendering,this.localeRouting=$.localeRouting??J.localeRouting,this.detectLocale=$.detectLocale,this.detectLocale&&this.localeRouting!=="off")throw Error('`view.detectLocale` needs `view.localeRouting: "off"`: on locale-routed views the URL, the `i18n-locale` cookie and `Accept-Language` decide the locale. A `route.domains` group that inherits it and keeps locale routing can set `detectLocale: undefined`.');this.theme=$.theme??J.theme,this.defaultMeta=$.meta,this.notFound=$.notFound,this.publicFiles=$.publicFiles??J.publicFiles,this.assetRoutes=$.assetRoutes??J.assetRoutes,this.translate=$.translate,this.csp=$.csp,this.hooks={onNotFound:$.onNotFound??J.onNotFound,onRequestStart:$.onRequestStart??J.onRequestStart,onRequestEnd:$.onRequestEnd??J.onRequestEnd,onRequestFail:$.onRequestFail??J.onRequestFail,onStreamComplete:$.onStreamComplete??J.onStreamComplete};let W={"/":$.rootRouter,"/auth":dG(Z)};if(this.requiredViews=Object.fromEntries(hG(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=t4(W),!this.assetRoutes)kM(Object.keys(this.flatViewRoutes));this.routeManifest=r4(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=$8(W),this.flatComponentTree=MW(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,Y])=>Y.static).map(([Y])=>Y);for(let Y of this.staticRoutes){let j=this.flatViewRoutes[Y].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}if(this.notFound){for(let Y of[this.notFound.view,this.notFound.static?.layout])if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=H(W$);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)J8();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{XZ.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let G=new Set(Z?.preload??[]);for(let Q of W)for(let V of J?.[Q]??[])G.add(V);return[...G].map((Q)=>i1("link",{key:`modulepreload:${Q}`,rel:"modulepreload",href:Q}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,G;if(W.layout){if(G=$.viewImportMap[W.layout],!G)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let Q=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let V=uW(),F=new AbortController,B=setTimeout(()=>F.abort(),FB),U=(O)=>{if(Bun.env.NODE_ENV!=="production")console.error(O)},D=cQ(async(O,L)=>{let M=await t3(O,{signal:F.signal,identifierPrefix:L,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});return await M.allReady.catch(()=>{}),await new Response(M).text()},{currentLocale:j?.i18n?.currentLocale,defaultLocale:j?.i18n?.defaultLocale,timeZone:j?.i18n?.timeZone},z);try{let O,L=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(L)O={name:L,source:await kW(L)};let M;if(W.navigation){let C=W.navigation===!0?{}:W.navigation,S=C.version?String(await J(()=>C.version(Z))):"";M={identity:[W.layout??"",$.buildId??"",O?.name??"",S].join("|"),prefetch:C.prefetch==="none"?"none":"intent"}}let T=await t3(i1(nQ.Provider,{value:D,children:i1(VB,{children:[...Q,i1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:V,rootLayout:G,key:"root"})]})}),{signal:F.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});await T.allReady.catch(()=>{});let K=ZB(await new Response(T).text()),N=[],R=$B(K,D,$.resolveIsland,Bun.env.NODE_ENV!=="production",M,O,N);return yW(X,this.csp,{nonce:pW(Z.rawRequest),inlineScripts:N}),new Response(R,{status:$.status,headers:X})}finally{clearTimeout(B),J(()=>this.completeStream(Z,z.summarize(F.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:V,noStream:F,noTheme:B,url:U,user:D,viewData:O,breadcrumbs:L,urlLocaleSegment:M,meta:T,isOgRequest:K,appId:N,features:R,staticView:C,cspNonce:S}=$,w=this.theme===!1||B||C?null:{cookie:this.theme.cookie??DW,default:this.theme.default??null,value:qM(Z,this.theme.cookie??DW)},x=M?SQ(G,[M]).pathname:G,f={kind:"view",data:{meta:T,pageData:{[x]:O},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:D},routeManifest:this.clientRouteManifest,breadcrumbs:L,router:{urlLocaleSegment:M,pathname:Y,params:X,currentPath:G,searchParams:U.search,is404:!Y?!0:!1,domain:Z.domain?wM(Z):null},appId:N,features:R,theme:w,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},_=this.root,k=this.routeManifest[Y];return async(H0)=>{let{bootstrapModules:j3=[],loaders:BZ,getStyles:x$,viewImportMap:d,cssManifest:g,ogMap:F0,viewModules:V1,clientEntry:C$,modulePreloadManifest:z3,assetBase:u0,resolveIsland:A$,buildId:S1}=H0,E1=C$?[]:j3,l=(y)=>[y,`window.loaders=${BZ}`,...C$?[`import(${JSON.stringify(C$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(K){let y=null,F1=null;for(let E of k??[])if(typeof F0[E]==="function")F1=E,y=F0[E];if(!y)return new Response("Not found",{status:404});let Z6=Object.values(f.data.pageData)[0];try{await t3(i1(y,Z6[F1]),{onError:()=>{}})}catch(E){let{fonts:r,...o1}=E.satoriOptions,J6=await Promise.all(r.map((W6)=>{return bM(W6.name,W6.weight,W6.style).then((CV)=>({...W6,data:CV}))})),T2=new Headers(j);T2.set("Content-Type","image/png");let[NV,_V]=await Promise.all([SM(),n4("Rendering an OG image")]),IV=await NV(E.jsx,{...o1,fonts:J6}),xV=await _V(Buffer.from(IV)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(xV),{headers:T2})}return new Response("data")}if(C&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:C,currentViews:k,data:f.data,serverQueries:Q,headers:j,getStyles:x$,viewImportMap:d,viewModules:V1,resolveIsland:A$,buildId:S1,status:200});if(C&&!Y&&this.notFound){let y=this.notFound.view;if(!d[y])throw Error(`The not-found view "${y}" (route.view.notFound) was not found. It is a view path: a file at app/views/${y}.tsx.`);return await this.renderStatic({req:Z,runInRequestScope:J,staticView:C,currentViews:[y],data:f.data,serverQueries:Q,headers:j,getStyles:x$,viewImportMap:{...d,"404":d[y]},viewModules:V1&&{...V1,"404":V1[y]},resolveIsland:A$,buildId:S1,status:$.refusedStatus??404})}if(f.data.cssManifest=g,f.data.modulePreloadManifest=z3??{},u0&&u0!=="/")f.data.assetBase=u0;if(S1&&S1!=="dev")f.data.buildId=S1;let P8=OB(this.modulePreloadLinks({clientEntry:C$,modulePreloadManifest:z3,views:k??["404"],routeKey:Y??"404"}),S),N8=OB(await x$(k??["404"]),S);f.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let r0=new AbortController,VZ=setTimeout(()=>r0.abort(),FB),S$=I6(V)||F,n1=Bun.env.NODE_ENV!=="production"&&!S$&&Y&&this.shellReporter.shouldObserve(Y)?RQ():null,E$=uW();try{let y=await t3(i1(VB,{children:AQ(P8,[...N8,...w?[i1("script",{key:"theme-script",nonce:S,dangerouslySetInnerHTML:{__html:NQ(i0({cookie:w.cookie,default:w.default}))}})]:[]],i1(_,{data:f.data,viewImportMap:d,viewModules:V1,serverQueries:Q,dictionarySink:E$,cspNonce:S,key:"root"}))}),{bootstrapScriptContent:l(`window.__GEMI_DATA__ = ${i0(f.data)}`),bootstrapModules:E1,nonce:S,signal:r0.signal,...S$?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(F1){if(Bun.env.NODE_ENV!=="production")console.error(F1)}});if(y.allReady.catch(()=>{}).finally(()=>clearTimeout(VZ)),S$)await y.allReady.catch(()=>{});return new Response(X7(y,Q,{onShell:S$?void 0:()=>Q.markShell(),onChunk:n1?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(r0.signal.aborted)),n1)this.shellReporter.report(Y,n1.measure())})},E$,S),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(y){if(clearTimeout(VZ),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,Q.summarize(r0.signal.aborted))),y;let F1=await t3(i1("div"),{bootstrapScriptContent:l(`window.error= ${i0(y.message)}; window.stack_trace=${i0(y.stack)};window.__GEMI_DATA__ = ${i0(f.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...E1]:E1,nonce:S});return new Response(X7(F1,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(r0.signal.aborted)))},void 0,S),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(k$(Z))return 404;if(Z?.kind===e1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if($$(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof t0&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),G=j,Q=null,V=null,F=H(c),B=n3(this.flatViewRoutes,j),U=F.isLocaleAware&&this.localeRouting==="prefix"&&!B?.route.middleware.includes(UB);if(U&&F.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,V=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&B===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),k=U&&F.supportedLocales.includes(_.slice(1));if(_&&!k)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(U&&!Y&&V===null&&!(V===null&&B!==null)){let _=dW(z,F.supportedLocales,F.defaultLocale);if(_){let k=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${k}${W?".json":""}${J.search}`}})}}if(U&&!Y){let _=H(c).detectLocale(new A($,{},"view",G));if(V===null&&_!==F.defaultLocale){let k=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${k}${J.search}`}})}}G=G.replace("//","/");let O=[],L=[],M=null,T={},K=null,N=!1,R=!1,C=[],S,w=!1,x=!1;try{let _=n3(this.flatViewRoutes,G);if(V&&_?.route.middleware.includes(UB))_=null;if(_){if(w=!0,M=_.routePath,T=_.params,O=_.route.exec,L=_.route.middleware,C=_.route.features,N=L.includes("no-stream"),R=L.includes(EM),S=_.route.static,x=_.route.segments.at(-1)?.viewPath==="FILE",W&&this.partialRendering){let k=$.headers.get(LW),H0=IQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:H(c).supportedLocales,from:k,origin:J.origin,to:{segments:_.route.segments,params:T,search:J.search}});if(H0.startIndex>0)O=O.slice(H0.startIndex),K={from:k,carriedViews:H0.carriedViews}}}}catch(_){throw _}if(S&&W)return new Response("Not found",{status:404});let f=new A($,T,"view",M);return this.hooks.onRequestStart(f),await P.run(f,async()=>{let _=null,k=P.getStore(),H0=$3.getStore(),j3=(g)=>$3.run(H0,()=>P.runWith(k,g));k.serverQueries=new rZ(o3($));let BZ=new Set;k.serverQueries.onQueryFail((g)=>{BZ.add(g.error);try{j3(()=>Promise.resolve(this.hooks.onRequestFail(d,g.error)).catch(()=>{}))}catch{}});let x$=vW(x?{}:S??(M===null&&!W?this.notFound?.static:void 0));if(V){let g=V.replaceAll("/","");_$.setLocale(g,{cookie:x$.locale})}else if(F.isLocaleAware&&!U)k.setLocale(F.defaultLocale);else _$.setLocale(void 0,{cookie:x$.locale});let d=k.req;if(x$.session)J8();try{let g=null;if(this.detectLocale&&!U&&H(c).isLocaleAware){let{supportedLocales:E,defaultLocale:r}=H(c),o1=await this.detectLocale(d,{supportedLocales:E,defaultLocale:r}),J6=typeof o1==="string"?dW(o1,E,r):null;if(J6)k.setLocale(J6)}try{await H(r1).runMiddleware(L)}catch(E){if(g=this.viewRefusalStatus(d,E,BZ),g===null)throw E}if(g!==null||C.length>0&&!await this.passesFeatureGates(C))M=null,O=[],d.routePath="";let F0=H(c),V1=F0.isEnabled,C$=F0.isLocaleAware,z3=new A($,d.params),u0={defaultLocale:F0.defaultLocale,timeZone:F0.detectTimeZone(z3)};if(C$){let E=null;if(V)E=V.replaceAll("/",""),k.setLocale(E);else if(!U)E=k.locale??F0.defaultLocale;else E=F0.detectLocale(z3),k.setLocale(E);let r=V1?F0.getPageTranslations(E,d.routePath):{};u0={...u0,supportedLocales:F0.supportedLocales,currentLocale:E,dictionary:{[E]:r},defaultLocale:F0.defaultLocale,...U?{}:{localeRouting:"off"}}}await cW(u0.currentLocale??"");let A$;try{A$=await Promise.all(O.map((E)=>E(d)))}catch(E){if(g=this.viewRefusalStatus(d,E,BZ),g===null)throw E;M=null,O=[],d.routePath="",A$=[]}let S1=void 0;if(M===null){if(S1=await this.hooks.onNotFound(d,{status:g??404}),C$&&!U&&k.locale&&k.locale!==u0.currentLocale){let E=k.locale;u0={...u0,currentLocale:E,dictionary:{[E]:V1?F0.getPageTranslations(E,d.routePath):{}}},await cW(E)}}if(this.defaultMeta&&!k.metadata.hasAllDefaultFields)k.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(d):this.defaultMeta);if(this.translate!==void 0)k.metadata.applyTranslateDefault(this.translate);let{cookies:E1,headers:l}=k;if(g!==null)l.set("Cache-Control","no-store");_={data:A$,cookies:E1,headers:l,user:k.user,prefetchedData:k.serverQueries.snapshotResolved(),currentPathName:M,params:d.params,urlLocaleSegment:Q,meta:k.renderMeta(),appId:H(HW).id,features:await H(W$).forClient()};let{params:P8,user:N8}=_,r0={},VZ={};for(let E of A$??[]){let[r,o1]=Object.entries(E)?.[0]??[];if(!r||!o1)continue;VZ[`${r}:${M}`]=o1.breadcrumb,r0[r]=o1}let S$=M===null&&this.notFound&&!W?this.notFound.static:void 0;if(S$&&S1)r0["404"]=S1;let n1=r0.FILE;if(n1){try{await this.onRequestEnd(d,{mintSession:!1})}catch(r){XZ.error(r?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(r)})}let E;if(n1 instanceof Response)E=Y8(n1,l,E1);else{for(let r of E1)l.append("Set-Cookie",r.toString());E=await f8(n1,l)}return GB(E,M)}if(W){l.set("Content-Type","application/x-ndjson; charset=utf-8"),l.append("Vary",LW),E1.forEach((r)=>l.append("Set-Cookie",r.toString())),gW(l,M),await this.hooks.onRequestEnd(d);let E={meta:K&&!k.metadata.touched?null:_.meta,data:{[G]:r0},breadcrumbs:VZ,prefetchedData:k.serverQueries.snapshotResolved(),i18n:u0,features:_.features,is404:!M,appId:_.appId,partial:K};return new Response(kQ(E,k.serverQueries,void 0,({aborted:r})=>j3(()=>this.completeStream(d,k.serverQueries.summarize(r)))),{headers:l})}l.set("Content-Type","text/html; charset=utf-8");let E$=M?S:S$,y=Boolean(E$),F1=vW(E$);if(!N&&!y)l.append("Vary","User-Agent");if(!y||F1.session)J8();for(let E of E1)l.append("Set-Cookie",E.toString());if(!y||F1.csrf){let E=Bun.CSRF.generate(process.env.SECRET);l.append("Set-Cookie",`csrf_token=${E}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(d,{mintSession:!y||F1.session})}catch(E){XZ.error(E?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(E)})}if(y&&(M||!w))jB(l,E$);gW(l,M);let Z6=y?void 0:DB($);if(!y)yW(l,this.csp,{nonce:Z6});if(pW($))XB(l,M,y);return await this.render({req:d,runInRequestScope:j3,csrfTokenHMAC:Buffer.from(""),currentPathName:M,headers:l,i18n:u0,params:P8,pathname:J.pathname,serverQueries:k.serverQueries,userAgent:$.headers.get("user-agent"),noStream:N,noTheme:R,url:J,user:N8,viewData:r0,breadcrumbs:VZ,urlLocaleSegment:Q,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:E$,refusedStatus:g??void 0,cspNonce:Z6})}catch(g){if(g.kind===e1){let F0=W?fM(g.payload.viewData??g.payload.api):hW(g.payload.view);for(let V1 of k.cookies)F0.headers.append("Set-Cookie",V1.toString());return F0}if(!BZ.has(g))this.hooks.onRequestFail(d,g);if($$(g))return console.error(g),W?eZ():hW(KW());if(g instanceof t0&&g.status===403)return W?eZ():hW(KW());throw g}},Z)}}function OB($,Z){return Z?$.map((J)=>AM(J,{nonce:Z})):$}function qM($,Z){let J=$.cookies?.get(Z);return PQ(J)?J:null}function iW(){let $=JSON.stringify({error:Z$("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class KB extends x0{routes={"/api-routes":this.get(()=>{let $=H(j8).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=H(r3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var vM=new Set([t1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),gM=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,yM=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function mM($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(vM.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===t1)throw Error(`dispatchAs: credentials may not set the "${t1}" cookie. The access token stays the initiator's.`);if(!gM.test(Y)||!yM.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function hM($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(G){Y(),z.error(G);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function LB($){let{status:Z=400,data:J,headers:W}=$,Y=new Headers({"Content-Type":"application/json",...W});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function Y8($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,G]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,G)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}function pM(){return Bun.env.NODE_ENV==="development"}class j8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=oG();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=r5({"/":$.rootRouter,"/auth":i5,"/__gemi__/services/i18n":s5,"/__gemi__/services/image":a5,...pM()?{"/__gemi__/services/logs":t5,"/__gemi__/debug":KB}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=HB(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:j});if(z.test({pathname:J})){Y=j,W=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await H(r1).runMiddleware(W)}catch(Y){if(Y.kind===e1)return LB(Y.payload.api);else{if(k$(Y))return iW();if(this.onRequestFail(Z,Y),console.error(Y),$$(Y))return eZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=P.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===e1)return LB(j.payload.api);if(k$(j))return iW();if(this.onRequestFail(J.req,j),console.error(j),$$(j))return eZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){XZ.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(!Y||!Y[$.method])return new Response(JSON.stringify({error:Z$("not_found","Not found",404)}),{status:404});let j=new A($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await P.run(j,async()=>{let z=P.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,W)};try{let Q=H(c);if(Q.isEnabled){let O=Q.detectLocale(j);z.setLocale(O)}z.setRequest(j),H(r1).applyDefaultBodyLimit($,Y[$.method].bodyLimitDefault);let V=await this.runRouteMiddleware(W,j);if(V instanceof Response){let O=Y8(V,z.headers,z.cookies);return await G(),O}let F=await this.getRouteData(W),B=z.headers,U=z.cookies;if(F instanceof Response){let O=Y8(F,B,U);if(this.isOpenEndedBody($,O)){let L=hM(O,()=>this.endRequest(z,j,W));return X=!0,L}return await G(),O}let D=(a1(F)?F:U1.json(F)).toResponse(B,U);return await G(),D}catch(Q){if(!X)try{await G()}catch(V){console.error(V)}throw Q}},Z)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let G=Y?.identity;if(G!==void 0&&(typeof G!=="object"||!G?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let Q=new Headers,V=[],F=G?null:$.cookies.get(t1);if(F)V.push(`${t1}=${F}`);if(Y?.credentials)mM(Q,V,Y.credentials,G!==void 0);if(V.length>0)Q.set("Cookie",V.join("; "));let B=G?null:$.headers.get(t1);if(B)Q.set(t1,B);let U=$.headers.get("User-Agent");if(U)Q.set("User-Agent",U);let D;if(W instanceof FormData)D=W;else if(W!==void 0)Q.set("Content-Type","application/json"),D=JSON.stringify(W);let O=new Request(z,{method:Z,headers:Q,body:D,...Y?.signal?{signal:Y.signal}:{}});if(MB(O,DZ($),G?.grant,Y?.progress),$.domain)Z3(O,$.domain);let L=G?{user:G.user}:void 0;return P.exit(()=>B6.exit(()=>this.handleApiRequest(O,L)))}}import{timingSafeEqual as dM}from"crypto";var G8="",oW="*",cM=60000,uM=1e4,z8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,X8=16,sW=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,nW="x-forwarded-host";function PB($){return $.startsWith(":")}function e3($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&dM(J,W)}function lM($){if(!$)return[];if($===!0)return[{header:nW,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:nW;return Z.map((W)=>({header:W.hostHeader?.toLowerCase()??J,clientIpHeader:W.clientIpHeader?.toLowerCase()??null,secret:W.secret?{header:W.secret.header.toLowerCase(),value:W.secret.value}:null}))}function iM($){if(!$||$===!0)return;if(!Array.isArray($)){TB($,"route.domains.trustProxy",nW);return}if($.length===0)throw Error("`route.domains.trustProxy` is an empty list. List at least one proxy, or leave `trustProxy` out.");let Z=new Map;$.forEach((J,W)=>{let Y=`route.domains.trustProxy[${W}]`;if(typeof J!=="object"||J===null||Array.isArray(J))throw Error(`\`${Y}\` must be an object: { hostHeader?, clientIpHeader?, secret }. \`true\` is only accepted on its own.`);if(!J.secret)throw Error(`\`${Y}.secret\` is required: in a list, each proxy proves itself with a secret of its own.`);if(J.hostHeader===void 0&&J.clientIpHeader===void 0)throw Error(`\`${Y}\` names neither \`hostHeader\` nor \`clientIpHeader\`, so it would trust nothing.`);TB(J,Y,null);let j=Z.get(J.secret.value);if(j!==void 0)throw Error(`\`${Y}.secret.value\` is the same as \`route.domains.trustProxy[${j}].secret.value\`. Give each proxy a secret of its own.`);Z.set(J.secret.value,W)})}function TB($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!sW.test(W)))throw Error(`\`${Z}.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(W)}.`);let z=(W??J)?.toLowerCase()??null;if(Y!==void 0){if(typeof Y!=="string"||!sW.test(Y))throw Error(`\`${Z}.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(Y)}.`);if(!j)throw Error(`\`${Z}.clientIpHeader\` needs \`secret\`: without proof the proxy sent it, any client that reaches the app directly picks its own address.`);if(Y.toLowerCase()===z)throw Error(`\`${Z}.clientIpHeader\` names the same header as \`hostHeader\`.`);if(typeof j.header==="string"&&Y.toLowerCase()===j.header.toLowerCase())throw Error(`\`${Z}.clientIpHeader\` names the same header as \`secret.header\`.`)}if(!j)return;if(typeof j.header!=="string"||!sW.test(j.header))throw Error(`\`${Z}.secret.header\` must be a header name. Got "${j.header}".`);if(j.header.toLowerCase()===z)throw Error(`\`${Z}.secret.header\` names the same header as \`hostHeader\`; the secret needs a header of its own.`);if(typeof j.value!=="string"||j.value.length<X8)throw Error(`\`${Z}.secret.value\` must be at least ${X8} characters. A guessable one lets any client name its own host.`)}function x1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function sM($){try{let Z=new URL(`http://${$.trim()}`),J=Z.hostname.toLowerCase().replace(/\.$/,"");return J?Z.port?`${J}:${Z.port}`:J:null}catch{return null}}function NB($){if($===void 0)return[];if($===!0)return!0;if(!Array.isArray($))throw Error(`\`route.domains.devHosts\` must be a list of hostnames (or \`true\`). Got ${JSON.stringify($)}.`);return $.map((Z,J)=>{let W=typeof Z==="string"?Z.trim().toLowerCase():"",Y=W.startsWith(".")?W.slice(1):W;if(!Y||!Y.split(".").every((j)=>z8.test(j)))throw Error(`\`route.domains.devHosts[${J}]\` must be a bare hostname, e.g. "app.acme.test", or ".acme.test" for the domain and its subdomains \u2014 no scheme, port, path or "*". Got ${JSON.stringify(Z)}.`);return W})}function nM($){let Z=x1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>z8.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<X8)throw Error(`\`route.domains.ask.secret\` must be at least ${X8} characters. A guessable one is worse than leaving \`ask\` out.`);iM($.trustProxy),NB($.devHosts);let W=new Set,Y=null;for(let j of $.groups??[]){let{subdomain:z}=j;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),PB(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>z8.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class aW{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){nM($),this.root=x1($.root),this.devHosts=NB($.devHosts),this.hostTrusts=lM($.trustProxy);for(let Z of $.groups??[])if(PB(Z.subdomain))this.param={...Z,name:Z.subdomain.slice(1)};else this.fixed.set(Z.subdomain.toLowerCase(),Z);this.custom=$.custom??null,this.cacheTtlMs=this.custom?.cacheTtlMs??cM,this.askSecret=$.ask?.secret??null,this.proxySecretHeaders=Array.from(new Set(this.hostTrusts.flatMap((Z)=>Z.secret?[Z.secret.header]:[])))}trustOf($){let Z=null;for(let J of this.hostTrusts)if((!J.secret||e3($.headers.get(J.secret.header),J.secret.value))&&!Z)Z=J;return Z}forwardedHost($){let Z=this.trustOf($)?.header;if(!Z)return null;return $.headers.get(Z)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.trustOf($);if(!Z?.clientIpHeader||!Z.secret)return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:f$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return x1(this.forwardedHost($))??x1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&x1(Y)?sM(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:oW,params:{},custom:!0};return null}async allows($,Z){let J=x1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:G8,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&z8.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=uM)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=x1($);if(Z)this.cache.delete(Z)}}}var oM={kind:"none"};function iA($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return oM;if(Z==="true")return{kind:"all"};if(/^[1-9]\d*$/.test(Z))return{kind:"hops",hops:Number(Z)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify($)}.`)}function sA($,Z,J){if(J.kind==="all"){if(!$.get("x-forwarded-for")&&Z)$.set("x-forwarded-for",Z);return}$.delete("x-real-ip");let W=Z;if(J.kind==="hops"){let Y=($.get("x-forwarded-for")??"").split(",").map((X)=>X.trim()).filter(Boolean),j=Y.length-J.hops,z=j>=0?Y[j]:Y[0];W=(z===void 0?null:f$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var _B=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,IB=16;function nA($){let Z=$.GEMI_CLIENT_IP_HEADER?.trim()??"",J=$.GEMI_PROXY_SECRET_HEADER?.trim()??"",W=$.GEMI_PROXY_SECRET??"";if(Z===""&&J===""&&W==="")return null;if(Z===""||J===""||W==="")throw Error("GEMI_CLIENT_IP_HEADER, GEMI_PROXY_SECRET_HEADER and GEMI_PROXY_SECRET go together: the client-IP header is only believed on a request that carries the proxy's secret. Set all three, or none.");if(!_B.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!_B.test(J))throw Error(`GEMI_PROXY_SECRET_HEADER must be a single header name, e.g. "x-azure-fdid". Got ${JSON.stringify(J)}.`);if(Z.toLowerCase()===J.toLowerCase())throw Error("GEMI_CLIENT_IP_HEADER and GEMI_PROXY_SECRET_HEADER name the same header.");if(W.length<IB)throw Error(`GEMI_PROXY_SECRET must be at least ${IB} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function xB($,Z){if(!e3($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:f$(J)}var aM="/__gemi__/domains/ask";class B1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;staticFilesVary=!1;constructor($,Z){this.groups.set(G8,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new aW(J);let W=(Y)=>({api:Y.api?new j8({...Z.api,...Y.api}):$.api,view:Y.view?new r3({...Z.view,...Y.view},Z.auth):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(oW,W(J.custom.fallback));this.staticFilesVary=this.viewDispatchers().some((Y)=>Y.publicFiles!==$.view.publicFiles||Y.assetRoutes!==$.view.assetRoutes)}async staticFiles($){let Z=(this.staticFilesVary?await this.route($):null)?.view??this.dispatchers(null).view;return{publicFiles:Z.publicFiles,assetRoutes:Z.assetRoutes}}applyClientIp($){let Z=this.clientIpTrust;if(Z)tW($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?xB($.headers,Z):null);if(!J)return;$.headers.set("x-forwarded-for",J),$.headers.delete("x-real-ip")}async route($){if(!this.resolver)return this.dispatchers(null);for(let J of this.resolver.proxySecretHeaders)tW($,J);let Z=Z8($)??await this.resolver.resolve($);if(!Z)return null;return Z3($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==aM)return null;if(!e3(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??G8)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function W3($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var CB=600000;function AB($,Z){return[T6($,Z),T6($,Z-1)]}class b{static token="auth";config;provider;constructor($={},Z=new F7){l9($.oauthProviders),this.config={..._1(i9($),$),emailCode:z7($.emailCode),passwordLimits:j7($.passwordLimits)},this.provider=Z}async oauthProvider($){return await TZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await GY(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=H().bound(B1)?H(B1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?H(B1).resolver?.root:x1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??x1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!t8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=W3(J.expiresAt),j=W3(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=P.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/CB),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let Q=T6($,j),V=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:Q,userId:V,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=Q}if(!z){for(let Q of AB($,j))if((await this.userProvider.findSession({token:Q,userAgent:Z}))?.user){z=Q;break}}if(!z)return null;let G=await this.getSession(z,Z);if(G)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(G.expiresAt)));return G}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(t8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/CB),W=AB($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=P.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new A;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new A,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new w$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=E9(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=null;try{z=await this.userProvider.findSession({token:Y,userAgent:W??""})}catch(X){console.error("Reading the new session back failed:",X)}return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){let{activeCodes:J,expiresInMinutes:W,linkExpiresInMinutes:Y}=this.config.emailCode,j=await this.config.generateMagicLinkToken($),z=await this.config.generateCode($),X=typeof z==="string"&&z!==""?z:q9(Z),G=P6("link",$,j),Q=P6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let V=Math.max(W,Y)*60000,B=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((U)=>W3(U.createdAt)+V>Date.now()&&U.pin!==Q&&U.token!==G);await this.userProvider.deleteMagicLinkTokensExcept($,B.map((U)=>U.id))}return await this.userProvider.createMagicLinkToken({email:$,token:G,pin:Q}),{email:$,pin:X,token:j}}async oneTimeCodeRows($){let{activeCodes:Z}=this.config.emailCode;if(Z===1){let J=await this.userProvider.findMagicLinkTokenByEmail($);return J?[J]:[]}return await this.userProvider.listMagicLinkTokensByEmail($,Z)}async claimOneTimeCode($,Z){if(!await this.userProvider.claimMagicLinkToken(Z))return!1;if(this.config.emailCode.activeCodes>1)await this.userProvider.deleteMagicLinkToken($);return!0}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.oneTimeCodeRows($);if(j.length===0)return KZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((Q)=>W3(Q.createdAt)+W*60000>Date.now());if(z.length===0)return KZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let Q of z)if(!await y9(Q.id,W3(Q.createdAt),Y,W))X=!1;if(!X){if(this.config.emailCode.activeCodes===1)await this.userProvider.claimMagicLinkToken(z[0].id);else await this.userProvider.deleteMagicLinkToken($);return{status:"too_many_attempts"}}let G=null;for(let Q of z)if(KZ("pin",$,Q.pin,Z))G??=Q;if(!G)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,G.id))return{status:"invalid"};return{status:"ok",row:G}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return KZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(KZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(W3(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class f0 extends h{static getFacadeAccessor(){return b}static async user(){let $=await f0.userOrNull();if($)return $;throw new w$({redirectTo:F6(P.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=P.getStore();if($?.user)return $.user;let Z=await z6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=P.getStore()?.req;return O1(Z?.search.get(l0),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await f0.user();if(!await $(Z))throw new LZ}static async guardSafe($){let Z=await f0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class Q8{static ensure($,Z={}){let J=P.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new rZ(o3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=Q8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){Q8.ensure($,Z[0])}static noPrefetch(){let $=P.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new rZ(o3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function tM($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function rW($,Z={}){let J=$.replace(/\/:(\w+)([*?]?)/g,(W,Y,j)=>{let z=Object.hasOwn(Z,Y)?Z[Y]:void 0;if(z===void 0||z===""){if(j)return"";throw Error(`\`${$}\` needs a value for :${Y}.`)}return`/${j==="*"?tM(z):encodeURIComponent(String(z))}`});return`${B8}${J==="/"?"":J}`||B8}var SB=new Map;function EB($,Z){let J=SB.get($);if(!J)J=new URLPattern({pathname:`${B8}${$==="/"?"":$}`}),SB.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;if(!Y)return null;let j={};for(let[z,X]of Object.entries(Y)){if(X===void 0)continue;try{j[z]=decodeURIComponent(X)}catch{return null}}return j}function bB($,Z,J="/"){let W=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(J.startsWith("/")?J:`/${J}`,W),z=rM(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(j.hostname=z.hostname,z.port)j.port=z.port;return j.toString()}function rM($){try{let Z=new URL(`http://${$.trim()}`);return Z.host===$.trim().toLowerCase()&&Z.pathname==="/"?{hostname:Z.hostname,port:Z.port}:null}catch{return null}}class RB{static origin($){return eW($)}static absolute($,...Z){return`${WZ()}${O0(String($),Z[0]??{})}`}static relative($,...Z){return O0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=H(B1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=P.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):WZ();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return bB({root:W.root,origin:j},$,O0(String(Z),J[0]??{}))}static api($,...Z){return rW(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${eW()}${rW(String($),Z[0]??{})}`}static matchApi($,Z){return EB(String($),Z)}}class kB{name="Meta";static description($){P.getStore().metadata.description($)}static title($){P.getStore().metadata.title($)}static openGraph($){P.getStore().metadata.openGraph($)}static htmlAttributes($){P.getStore().metadata.htmlAttributes($)}static canonical($){P.getStore().metadata.canonical($)}static alternates($){P.getStore().metadata.alternates($)}static tags($){P.getStore().metadata.tags($)}static robots($){P.getStore().metadata.robots($)}static translate($=!0){P.getStore().metadata.translate($)}static fonts($){P.getStore().metadata.fonts($)}}var eM={set($,Z,J){P.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(P.getStore().req.cookies.has($))return!1;return P.getStore().setCookie($,Z,J),!0},delete($,Z){P.getStore().deleteCookie($,Z)}};class s1 extends h{static getFacadeAccessor(){return GZ}static get client(){return this.getFacadeRoot().client}static get($){return s1.client.get($)}static set($,Z){return s1.client.set($,Z)}static del(...$){return s1.client.del(...$)}static exists($){return s1.client.exists($)}static incr($){return s1.client.incr($)}static expire($,Z){return s1.client.expire($,Z)}static ttl($){return s1.client.ttl($)}}function lS($){return $}function wB(){return{store:"memory",ttl:null}}class $2{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var $H="500";class Z2{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${ZH(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",$H]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=H(),Z=$.bound(GZ)?$.make(GZ).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function ZH($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var JH="k:",fB="tag:",WH="t:";class J2{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class W2 extends J2{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=_1(wB(),$),this.config.ttl!==null&&this.config.ttl!==void 0)QZ(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new vB(this,Z)}async flush(){await this.store.flush()}async storeKey($){return JH+gB($)}async read($){let Z=await this.store.get($);if(Z===null)return{found:!1};try{return{found:!0,value:JSON.parse(Z)}}catch{return{found:!1}}}async write($,Z,J){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let W=this.ttlMs(J);if(W===0){await this.store.delete($);return}let Y=JSON.stringify(Z);if(Y===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,Y,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let Y=this.inflight.get($);if(Y)return Y;let j=(async()=>{try{let z=await J();if(z!==void 0)await this.write($,z,Z);return z}finally{this.inflight.delete($)}})();return this.inflight.set($,j),j}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=fB+Z,W=await this.store.get(J);if(W!==null)return W;let Y=qB();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(fB+Z,qB(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:QZ(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new $2(this.config.memory);if($==="redis"){let Z=this.options.application;return new Z2({...this.config.redis,client:Z?{send:(J,W)=>Z.make(GZ).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class vB extends J2{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){gB($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${WH}${Z.join(",")}:${$}`}}function gB($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function qB(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class yB extends h{static getFacadeAccessor(){return W2}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class mB extends h{static getFacadeAccessor(){return D1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class pB extends h{static getFacadeAccessor(){return hB}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class cB extends h{static getFacadeAccessor(){return dB}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class uB extends h{static getFacadeAccessor(){return i3}static for($,Z,J){return this.getFacadeRoot().for($,Z,J)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,J){return this.getFacadeRoot().save($,Z,J)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}function KE($){return $}function lB(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function V8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function Y2($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:YH}=globalThis.Bun;function jH(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var zH=async($)=>{let Z=new YH($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},XH=async($)=>{let Z;try{Z=(await import("./chunk-qc0e278w.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,Y,j)=>J.listen(W,Y,j),close:()=>J.end({timeout:1}).catch(()=>{})}},iB=($)=>jH()?zH($):XH($);var GH=/^[A-Za-z_][A-Za-z0-9_]*$/;class j2{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!GH.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let j=Z.retain??1000;if(!Number.isInteger(j)||j<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${j}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=j,this.listener=Z.listener??iB}async createTable(){for(let $ of QH(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let j=this.sqliteTurn.then(Y);return this.sqliteTurn=j.catch(()=>{}),j}let W=this.append(J,$,Z);return sB(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
23
+ ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function RW($){return`'sha256-${QM("sha256").update($).digest("base64")}'`}var AW,SW=new Map;function LM(){if(AW===void 0){let $=bW(EW(),"dist","server",FM);AW=aQ($)?JSON.parse(BM($,"utf8")):null}return AW??null}async function kW($){OM($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=LM()?.[$];if(j!==void 0)return j;let z=SW.get($);if(z)return z}let J=bW(EW(),"app"),W=DM(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${tQ}.ts (or .js).`);if(!Z)return oQ(W);let Y=oQ(W);return SW.set($,Y),Y.catch(()=>SW.delete($)),Y}async function XC($){return RW(await kW($))}var MM="gemi-islands",HM="gemi-island-i18n",KM="gemi-island-queries",DC=`'sha256-${eQ("sha256").update(qW).digest("base64")}'`;function wW($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var fW=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),LC=`'sha256-${eQ("sha256").update(CW).digest("base64")}'`,TM='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',PM="gemi-static";function $B($,Z,J,W,Y,j,z){let X=new Set,G=[];if(J)G=Z.islands.map((T)=>{let K=T.module?J(T.module):void 0;if(!K)return console.error(`[gemi] island ${T.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(T.load==="eager"){for(let N of K.preload)X.add(N);if(T.preloadDynamic)for(let N of K.dynamicPreload??[])X.add(N)}return{s:K.src,e:T.export,l:T.load}});let Q=G.some((T)=>T!==null),V=j?`<script type="module" ${rQ}="${fW(j.name)}">${j.source}</script>`:"";if(j)z?.push(j.source);if(!Q&&!Y)return wW($,"</head>",V,!1);let B=(Y?`<meta name="${PM}" content="${fW(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...X].map((T)=>`<link rel="modulepreload" href="${fW(T)}"/>`).join("")+V,U=Y?CW:qW,D=W?TM+U:U;z?.push(D);let O=Q?uQ(Z):void 0,L=Q?lQ(Z):void 0,M=(Q?`<script type="application/json" id="${MM}">${i0({i:G})}</script>`:"")+(O?`<script type="application/json" id="${HM}">${i0(O)}</script>`:"")+(L?`<script type="application/json" id="${KM}">${i0(L)}</script>`:"")+`<script type="module">${D}</script>`;return wW(wW($,"</head>",B,!1),"</body>",M,!0)}function NM($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let Y=J.exec($);Y;Y=J.exec($))if(W+=Y[1]?-1:1,W===0)return J.lastIndex;return-1}function ZB($){let Z=`<template ${sQ}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=NM($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let G=`<${a3} ${iQ}="${j}" style="display:contents"></${a3}>`;$=$.split(G).join(`<${a3} style="display:contents">${X}</${a3}>`)}return $}function vW($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function jB($,Z){if($.getSetCookie().length>0){if(Z.cacheControl&&Bun.env.NODE_ENV!=="production")console.warn(`[gemi] A static view with cacheControl "${Z.cacheControl}" set a cookie, so it was sent "private, no-store" instead. Static pages are cacheable only when nothing on them sets a cookie.`);$.set("Cache-Control","private, no-store");return}if(Z.cacheControl&&!$.has("Cache-Control"))$.set("Cache-Control",Z.cacheControl)}function _M($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var JB=new Set,IM=new Set(["public","private","s-maxage","proxy-revalidate"]);function gW($,Z){let J=$.get("Cache-Control");if(!J||$.getSetCookie().length===0)return;if(!/(^|[\s,])(public|s-maxage)\b/i.test(J))return;let W=zB(J);if(Bun.env.NODE_ENV!=="production"&&!JB.has(Z)){JB.add(Z);let Y=[...new Set($.getSetCookie().map((j)=>j.split("=")[0]))];console.warn(`[gemi] The view "${Z??""}" sets cookies (${Y.join(", ")}) on a response with Cache-Control "${J}", so it was sent "${W}" instead: a shared cache would hand those cookies to every visitor. To let a CDN cache the page, make it a static view with .static({ cacheControl }).`)}$.set("Cache-Control",W)}function zB($){return["private",...$.split(",").map((J)=>J.trim()).filter((J)=>{let W=J.split("=")[0].trim().toLowerCase();return W!==""&&!IM.has(W)})].join(", ")}var WB=new Set;function XB($,Z,J){let W=$.get("Cache-Control");if(!W||!/(^|[\s,])(public|s-maxage)\b/i.test(W))return;let Y=zB(W);if(J&&Bun.env.NODE_ENV!=="production"&&!WB.has(Z))WB.add(Z),console.warn(`[gemi] The static view "${Z??""}" asked for a CSP nonce (cspNonce()) on a response with Cache-Control "${W}", so it was sent "${Y}" instead: a shared cache would hand the same nonce to every visitor. Allow a static page's scripts by hash instead (route.view.csp does).`);$.set("Cache-Control",Y)}var YB=new Set;function GB($,Z){if(!_M($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!YB.has(Z))YB.add(Z),console.warn(`[gemi] The file route "${Z??""}" set a cookie on a response with Cache-Control "${$.headers.get("Cache-Control")}", so the cookie was not sent: a shared cache would hand it to every visitor. Make the response private, or set the cookie elsewhere.`);try{return $.headers.delete("Set-Cookie"),$}catch{let J=new Headers($.headers);return J.delete("Set-Cookie"),new Response($.body,{status:$.status,statusText:$.statusText,headers:J})}}var xM="'strict-dynamic' 'self' https: 'unsafe-inline'",QB="Content-Security-Policy",BB="Content-Security-Policy-Report-Only";function CM($,Z={}){let J=[...$.nonce?[`'nonce-${$.nonce}'`]:[],...$.hashes??[]],W=[J.length>0?`script-src ${J.join(" ")} ${xM}`:"script-src 'none'","object-src 'none'","base-uri 'self'"];if(Z.reportUri)W.push(`report-uri ${Z.reportUri}`);return W.join("; ")}function yW($,Z,J){if(!Z)return;if($.has(QB)||$.has(BB))return;let W=Z===!0?{}:Z;$.set(W.reportOnly?BB:QB,CM({nonce:J.nonce,hashes:[...new Set(J.inlineScripts??[])].map(RW)},W))}var SM=async()=>(await import("./chunk-3rgf7rsy.js")).default,mW,t3=async(...$)=>{return mW??=import("react-dom/server.browser").catch((Z)=>{throw mW=void 0,Z}),(await mW).renderToReadableStream(...$)},FB=1e4,UB="no-locale",EM="no-theme";async function bM($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var lW="/assets";function RM($){return $===lW||$.startsWith(`${lW}/`)}function kM($){let Z=$.filter(RM);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${lW}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else, or set \`assetRoutes: true\` on these views' config (route.view or a route.domains group's view).`)}}function wM($){let Z=H(B1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function hW($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function fM($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class r3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=bQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;translate;csp;constructor($,Z={}){let J=aG();if(this.partialRendering=$.partialRendering??J.partialRendering,this.localeRouting=$.localeRouting??J.localeRouting,this.detectLocale=$.detectLocale,this.detectLocale&&this.localeRouting!=="off")throw Error('`view.detectLocale` needs `view.localeRouting: "off"`: on locale-routed views the URL, the `i18n-locale` cookie and `Accept-Language` decide the locale. A `route.domains` group that inherits it and keeps locale routing can set `detectLocale: undefined`.');this.theme=$.theme??J.theme,this.defaultMeta=$.meta,this.notFound=$.notFound,this.publicFiles=$.publicFiles??J.publicFiles,this.assetRoutes=$.assetRoutes??J.assetRoutes,this.translate=$.translate,this.csp=$.csp,this.hooks={onNotFound:$.onNotFound??J.onNotFound,onRequestStart:$.onRequestStart??J.onRequestStart,onRequestEnd:$.onRequestEnd??J.onRequestEnd,onRequestFail:$.onRequestFail??J.onRequestFail,onStreamComplete:$.onStreamComplete??J.onStreamComplete};let W={"/":$.rootRouter,"/auth":dG(Z)};if(this.requiredViews=Object.fromEntries(hG(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=t4(W),!this.assetRoutes)kM(Object.keys(this.flatViewRoutes));this.routeManifest=r4(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=$8(W),this.flatComponentTree=MW(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,Y])=>Y.static).map(([Y])=>Y);for(let Y of this.staticRoutes){let j=this.flatViewRoutes[Y].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}if(this.notFound){for(let Y of[this.notFound.view,this.notFound.static?.layout])if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=H(W$);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)J8();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{XZ.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let G=new Set(Z?.preload??[]);for(let Q of W)for(let V of J?.[Q]??[])G.add(V);return[...G].map((Q)=>i1("link",{key:`modulepreload:${Q}`,rel:"modulepreload",href:Q}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,G;if(W.layout){if(G=$.viewImportMap[W.layout],!G)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let Q=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let V=uW(),F=new AbortController,B=setTimeout(()=>F.abort(),FB),U=(O)=>{if(Bun.env.NODE_ENV!=="production")console.error(O)},D=cQ(async(O,L)=>{let M=await t3(O,{signal:F.signal,identifierPrefix:L,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});return await M.allReady.catch(()=>{}),await new Response(M).text()},{currentLocale:j?.i18n?.currentLocale,defaultLocale:j?.i18n?.defaultLocale,timeZone:j?.i18n?.timeZone},z);try{let O,L=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(L)O={name:L,source:await kW(L)};let M;if(W.navigation){let C=W.navigation===!0?{}:W.navigation,S=C.version?String(await J(()=>C.version(Z))):"";M={identity:[W.layout??"",$.buildId??"",O?.name??"",S].join("|"),prefetch:C.prefetch==="none"?"none":"intent"}}let T=await t3(i1(nQ.Provider,{value:D,children:i1(VB,{children:[...Q,i1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:V,rootLayout:G,key:"root"})]})}),{signal:F.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});await T.allReady.catch(()=>{});let K=ZB(await new Response(T).text()),N=[],R=$B(K,D,$.resolveIsland,Bun.env.NODE_ENV!=="production",M,O,N);return yW(X,this.csp,{nonce:pW(Z.rawRequest),inlineScripts:N}),new Response(R,{status:$.status,headers:X})}finally{clearTimeout(B),J(()=>this.completeStream(Z,z.summarize(F.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:V,noStream:F,noTheme:B,url:U,user:D,viewData:O,breadcrumbs:L,urlLocaleSegment:M,meta:T,isOgRequest:K,appId:N,features:R,staticView:C,cspNonce:S}=$,w=this.theme===!1||B||C?null:{cookie:this.theme.cookie??DW,default:this.theme.default??null,value:qM(Z,this.theme.cookie??DW)},x=M?SQ(G,[M]).pathname:G,f={kind:"view",data:{meta:T,pageData:{[x]:O},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:D},routeManifest:this.clientRouteManifest,breadcrumbs:L,router:{urlLocaleSegment:M,pathname:Y,params:X,currentPath:G,searchParams:U.search,is404:!Y?!0:!1,domain:Z.domain?wM(Z):null},appId:N,features:R,theme:w,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},_=this.root,k=this.routeManifest[Y];return async(H0)=>{let{bootstrapModules:j3=[],loaders:BZ,getStyles:x$,viewImportMap:d,cssManifest:g,ogMap:F0,viewModules:V1,clientEntry:C$,modulePreloadManifest:z3,assetBase:u0,resolveIsland:A$,buildId:S1}=H0,E1=C$?[]:j3,l=(y)=>[y,`window.loaders=${BZ}`,...C$?[`import(${JSON.stringify(C$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(K){let y=null,F1=null;for(let E of k??[])if(typeof F0[E]==="function")F1=E,y=F0[E];if(!y)return new Response("Not found",{status:404});let Z6=Object.values(f.data.pageData)[0];try{await t3(i1(y,Z6[F1]),{onError:()=>{}})}catch(E){let{fonts:r,...o1}=E.satoriOptions,J6=await Promise.all(r.map((W6)=>{return bM(W6.name,W6.weight,W6.style).then((CV)=>({...W6,data:CV}))})),T2=new Headers(j);T2.set("Content-Type","image/png");let[NV,_V]=await Promise.all([SM(),n4("Rendering an OG image")]),IV=await NV(E.jsx,{...o1,fonts:J6}),xV=await _V(Buffer.from(IV)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(xV),{headers:T2})}return new Response("data")}if(C&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:C,currentViews:k,data:f.data,serverQueries:Q,headers:j,getStyles:x$,viewImportMap:d,viewModules:V1,resolveIsland:A$,buildId:S1,status:200});if(C&&!Y&&this.notFound){let y=this.notFound.view;if(!d[y])throw Error(`The not-found view "${y}" (route.view.notFound) was not found. It is a view path: a file at app/views/${y}.tsx.`);return await this.renderStatic({req:Z,runInRequestScope:J,staticView:C,currentViews:[y],data:f.data,serverQueries:Q,headers:j,getStyles:x$,viewImportMap:{...d,"404":d[y]},viewModules:V1&&{...V1,"404":V1[y]},resolveIsland:A$,buildId:S1,status:$.refusedStatus??404})}if(f.data.cssManifest=g,f.data.modulePreloadManifest=z3??{},u0&&u0!=="/")f.data.assetBase=u0;if(S1&&S1!=="dev")f.data.buildId=S1;let P8=OB(this.modulePreloadLinks({clientEntry:C$,modulePreloadManifest:z3,views:k??["404"],routeKey:Y??"404"}),S),N8=OB(await x$(k??["404"]),S);f.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let r0=new AbortController,VZ=setTimeout(()=>r0.abort(),FB),S$=I6(V)||F,n1=Bun.env.NODE_ENV!=="production"&&!S$&&Y&&this.shellReporter.shouldObserve(Y)?RQ():null,E$=uW();try{let y=await t3(i1(VB,{children:AQ(P8,[...N8,...w?[i1("script",{key:"theme-script",nonce:S,dangerouslySetInnerHTML:{__html:NQ(i0({cookie:w.cookie,default:w.default}))}})]:[]],i1(_,{data:f.data,viewImportMap:d,viewModules:V1,serverQueries:Q,dictionarySink:E$,cspNonce:S,key:"root"}))}),{bootstrapScriptContent:l(`window.__GEMI_DATA__ = ${i0(f.data)}`),bootstrapModules:E1,nonce:S,signal:r0.signal,...S$?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(F1){if(Bun.env.NODE_ENV!=="production")console.error(F1)}});if(y.allReady.catch(()=>{}).finally(()=>clearTimeout(VZ)),S$)await y.allReady.catch(()=>{});return new Response(X7(y,Q,{onShell:S$?void 0:()=>Q.markShell(),onChunk:n1?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(r0.signal.aborted)),n1)this.shellReporter.report(Y,n1.measure())})},E$,S),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(y){if(clearTimeout(VZ),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,Q.summarize(r0.signal.aborted))),y;let F1=await t3(i1("div"),{bootstrapScriptContent:l(`window.error= ${i0(y.message)}; window.stack_trace=${i0(y.stack)};window.__GEMI_DATA__ = ${i0(f.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...E1]:E1,nonce:S});return new Response(X7(F1,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(r0.signal.aborted)))},void 0,S),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(k$(Z))return 404;if(Z?.kind===e1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if($$(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof t0&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),G=j,Q=null,V=null,F=H(c),B=n3(this.flatViewRoutes,j),U=F.isLocaleAware&&this.localeRouting==="prefix"&&!B?.route.middleware.includes(UB);if(U&&F.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,V=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&B===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),k=U&&F.supportedLocales.includes(_.slice(1));if(_&&!k)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(U&&!Y&&V===null&&!(V===null&&B!==null)){let _=dW(z,F.supportedLocales,F.defaultLocale);if(_){let k=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${k}${W?".json":""}${J.search}`}})}}if(U&&!Y){let _=H(c).detectLocale(new A($,{},"view",G));if(V===null&&_!==F.defaultLocale){let k=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${k}${J.search}`}})}}G=G.replace("//","/");let O=[],L=[],M=null,T={},K=null,N=!1,R=!1,C=[],S,w=!1,x=!1;try{let _=n3(this.flatViewRoutes,G);if(V&&_?.route.middleware.includes(UB))_=null;if(_){if(w=!0,M=_.routePath,T=_.params,O=_.route.exec,L=_.route.middleware,C=_.route.features,N=L.includes("no-stream"),R=L.includes(EM),S=_.route.static,x=_.route.segments.at(-1)?.viewPath==="FILE",W&&this.partialRendering){let k=$.headers.get(LW),H0=IQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:H(c).supportedLocales,from:k,origin:J.origin,to:{segments:_.route.segments,params:T,search:J.search}});if(H0.startIndex>0)O=O.slice(H0.startIndex),K={from:k,carriedViews:H0.carriedViews}}}}catch(_){throw _}if(S&&W)return new Response("Not found",{status:404});let f=new A($,T,"view",M);return this.hooks.onRequestStart(f),await P.run(f,async()=>{let _=null,k=P.getStore(),H0=$3.getStore(),j3=(g)=>$3.run(H0,()=>P.runWith(k,g));k.serverQueries=new rZ(o3($));let BZ=new Set;k.serverQueries.onQueryFail((g)=>{BZ.add(g.error);try{j3(()=>Promise.resolve(this.hooks.onRequestFail(d,g.error)).catch(()=>{}))}catch{}});let x$=vW(x?{}:S??(M===null&&!W?this.notFound?.static:void 0));if(V){let g=V.replaceAll("/","");_$.setLocale(g,{cookie:x$.locale})}else if(F.isLocaleAware&&!U)k.setLocale(F.defaultLocale);else _$.setLocale(void 0,{cookie:x$.locale});let d=k.req;if(x$.session)J8();try{let g=null;if(this.detectLocale&&!U&&H(c).isLocaleAware){let{supportedLocales:E,defaultLocale:r}=H(c),o1=await this.detectLocale(d,{supportedLocales:E,defaultLocale:r}),J6=typeof o1==="string"?dW(o1,E,r):null;if(J6)k.setLocale(J6)}try{await H(r1).runMiddleware(L)}catch(E){if(g=this.viewRefusalStatus(d,E,BZ),g===null)throw E}if(g!==null||C.length>0&&!await this.passesFeatureGates(C))M=null,O=[],d.routePath="";let F0=H(c),V1=F0.isEnabled,C$=F0.isLocaleAware,z3=new A($,d.params),u0={defaultLocale:F0.defaultLocale,timeZone:F0.detectTimeZone(z3)};if(C$){let E=null;if(V)E=V.replaceAll("/",""),k.setLocale(E);else if(!U)E=k.locale??F0.defaultLocale;else E=F0.detectLocale(z3),k.setLocale(E);let r=V1?F0.getPageTranslations(E,d.routePath):{};u0={...u0,supportedLocales:F0.supportedLocales,currentLocale:E,dictionary:{[E]:r},defaultLocale:F0.defaultLocale,...U?{}:{localeRouting:"off"}}}await cW(u0.currentLocale??"");let A$;try{A$=await Promise.all(O.map((E)=>E(d)))}catch(E){if(g=this.viewRefusalStatus(d,E,BZ),g===null)throw E;M=null,O=[],d.routePath="",A$=[]}let S1=void 0;if(M===null){if(S1=await this.hooks.onNotFound(d,{status:g??404}),C$&&!U&&k.locale&&k.locale!==u0.currentLocale){let E=k.locale;u0={...u0,currentLocale:E,dictionary:{[E]:V1?F0.getPageTranslations(E,d.routePath):{}}},await cW(E)}}if(this.defaultMeta&&!k.metadata.hasAllDefaultFields)k.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(d):this.defaultMeta);if(this.translate!==void 0)k.metadata.applyTranslateDefault(this.translate);let{cookies:E1,headers:l}=k;if(g!==null)l.set("Cache-Control","no-store");_={data:A$,cookies:E1,headers:l,user:k.user,prefetchedData:k.serverQueries.snapshotResolved(),currentPathName:M,params:d.params,urlLocaleSegment:Q,meta:k.renderMeta(),appId:H(HW).id,features:await H(W$).forClient()};let{params:P8,user:N8}=_,r0={},VZ={};for(let E of A$??[]){let[r,o1]=Object.entries(E)?.[0]??[];if(!r||!o1)continue;VZ[`${r}:${M}`]=o1.breadcrumb,r0[r]=o1}let S$=M===null&&this.notFound&&!W?this.notFound.static:void 0;if(S$&&S1)r0["404"]=S1;let n1=r0.FILE;if(n1){try{await this.onRequestEnd(d,{mintSession:!1})}catch(r){XZ.error(r?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(r)})}let E;if(n1 instanceof Response)E=Y8(n1,l,E1);else{for(let r of E1)l.append("Set-Cookie",r.toString());E=await f8(n1,l)}return GB(E,M)}if(W){l.set("Content-Type","application/x-ndjson; charset=utf-8"),l.append("Vary",LW),E1.forEach((r)=>l.append("Set-Cookie",r.toString())),gW(l,M),await this.hooks.onRequestEnd(d);let E={meta:K&&!k.metadata.touched?null:_.meta,data:{[G]:r0},breadcrumbs:VZ,prefetchedData:k.serverQueries.snapshotResolved(),i18n:u0,features:_.features,is404:!M,appId:_.appId,partial:K};return new Response(kQ(E,k.serverQueries,void 0,({aborted:r})=>j3(()=>this.completeStream(d,k.serverQueries.summarize(r)))),{headers:l})}l.set("Content-Type","text/html; charset=utf-8");let E$=M?S:S$,y=Boolean(E$),F1=vW(E$);if(!N&&!y)l.append("Vary","User-Agent");if(!y||F1.session)J8();for(let E of E1)l.append("Set-Cookie",E.toString());if(!y||F1.csrf){let E=Bun.CSRF.generate(process.env.SECRET);l.append("Set-Cookie",`csrf_token=${E}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(d,{mintSession:!y||F1.session})}catch(E){XZ.error(E?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(E)})}if(y&&(M||!w))jB(l,E$);gW(l,M);let Z6=y?void 0:DB($);if(!y)yW(l,this.csp,{nonce:Z6});if(pW($))XB(l,M,y);return await this.render({req:d,runInRequestScope:j3,csrfTokenHMAC:Buffer.from(""),currentPathName:M,headers:l,i18n:u0,params:P8,pathname:J.pathname,serverQueries:k.serverQueries,userAgent:$.headers.get("user-agent"),noStream:N,noTheme:R,url:J,user:N8,viewData:r0,breadcrumbs:VZ,urlLocaleSegment:Q,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:E$,refusedStatus:g??void 0,cspNonce:Z6})}catch(g){if(g.kind===e1){let F0=W?fM(g.payload.viewData??g.payload.api):hW(g.payload.view);for(let V1 of k.cookies)F0.headers.append("Set-Cookie",V1.toString());return F0}if(!BZ.has(g))this.hooks.onRequestFail(d,g);if($$(g))return console.error(g),W?eZ():hW(KW());if(g instanceof t0&&g.status===403)return W?eZ():hW(KW());throw g}},Z)}}function OB($,Z){return Z?$.map((J)=>AM(J,{nonce:Z})):$}function qM($,Z){let J=$.cookies?.get(Z);return PQ(J)?J:null}function iW(){let $=JSON.stringify({error:Z$("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class KB extends x0{routes={"/api-routes":this.get(()=>{let $=H(j8).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=H(r3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var vM=new Set([t1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),gM=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,yM=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function mM($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(vM.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===t1)throw Error(`dispatchAs: credentials may not set the "${t1}" cookie. The access token stays the initiator's.`);if(!gM.test(Y)||!yM.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function hM($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(G){Y(),z.error(G);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function LB($){let{status:Z=400,data:J,headers:W}=$,Y=new Headers({"Content-Type":"application/json",...W});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function Y8($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,G]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,G)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}function pM(){return Bun.env.NODE_ENV==="development"}class j8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=oG();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=r5({"/":$.rootRouter,"/auth":i5,"/__gemi__/services/i18n":s5,"/__gemi__/services/image":a5,...pM()?{"/__gemi__/services/logs":t5,"/__gemi__/debug":KB}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=HB(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:j});if(z.test({pathname:J})){Y=j,W=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await H(r1).runMiddleware(W)}catch(Y){if(Y.kind===e1)return LB(Y.payload.api);else{if(k$(Y))return iW();if(this.onRequestFail(Z,Y),console.error(Y),$$(Y))return eZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=P.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===e1)return LB(j.payload.api);if(k$(j))return iW();if(this.onRequestFail(J.req,j),console.error(j),$$(j))return eZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){XZ.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(!Y||!Y[$.method])return new Response(JSON.stringify({error:Z$("not_found","Not found",404)}),{status:404});let j=new A($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await P.run(j,async()=>{let z=P.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,W)};try{let Q=H(c);if(Q.isEnabled){let O=Q.detectLocale(j);z.setLocale(O)}z.setRequest(j),H(r1).applyDefaultBodyLimit($,Y[$.method].bodyLimitDefault);let V=await this.runRouteMiddleware(W,j);if(V instanceof Response){let O=Y8(V,z.headers,z.cookies);return await G(),O}let F=await this.getRouteData(W),B=z.headers,U=z.cookies;if(F instanceof Response){let O=Y8(F,B,U);if(this.isOpenEndedBody($,O)){let L=hM(O,()=>this.endRequest(z,j,W));return X=!0,L}return await G(),O}let D=(a1(F)?F:U1.json(F)).toResponse(B,U);return await G(),D}catch(Q){if(!X)try{await G()}catch(V){console.error(V)}throw Q}},Z)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let G=Y?.identity;if(G!==void 0&&(typeof G!=="object"||!G?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let Q=new Headers,V=[],F=G?null:$.cookies.get(t1);if(F)V.push(`${t1}=${F}`);if(Y?.credentials)mM(Q,V,Y.credentials,G!==void 0);if(V.length>0)Q.set("Cookie",V.join("; "));let B=G?null:$.headers.get(t1);if(B)Q.set(t1,B);let U=$.headers.get("User-Agent");if(U)Q.set("User-Agent",U);let D;if(W instanceof FormData)D=W;else if(W!==void 0)Q.set("Content-Type","application/json"),D=JSON.stringify(W);let O=new Request(z,{method:Z,headers:Q,body:D,...Y?.signal?{signal:Y.signal}:{}});if(MB(O,DZ($),G?.grant,Y?.progress),$.domain)Z3(O,$.domain);let L=G?{user:G.user}:void 0;return P.exit(()=>B6.exit(()=>this.handleApiRequest(O,L)))}}import{timingSafeEqual as dM}from"crypto";var G8="",oW="*",cM=60000,uM=1e4,z8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,X8=16,sW=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,nW="x-forwarded-host";function PB($){return $.startsWith(":")}function e3($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&dM(J,W)}function lM($){if(!$)return[];if($===!0)return[{header:nW,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:nW;return Z.map((W)=>({header:W.hostHeader?.toLowerCase()??J,clientIpHeader:W.clientIpHeader?.toLowerCase()??null,secret:W.secret?{header:W.secret.header.toLowerCase(),value:W.secret.value}:null}))}function iM($){if(!$||$===!0)return;if(!Array.isArray($)){TB($,"route.domains.trustProxy",nW);return}if($.length===0)throw Error("`route.domains.trustProxy` is an empty list. List at least one proxy, or leave `trustProxy` out.");let Z=new Map;$.forEach((J,W)=>{let Y=`route.domains.trustProxy[${W}]`;if(typeof J!=="object"||J===null||Array.isArray(J))throw Error(`\`${Y}\` must be an object: { hostHeader?, clientIpHeader?, secret }. \`true\` is only accepted on its own.`);if(!J.secret)throw Error(`\`${Y}.secret\` is required: in a list, each proxy proves itself with a secret of its own.`);if(J.hostHeader===void 0&&J.clientIpHeader===void 0)throw Error(`\`${Y}\` names neither \`hostHeader\` nor \`clientIpHeader\`, so it would trust nothing.`);TB(J,Y,null);let j=Z.get(J.secret.value);if(j!==void 0)throw Error(`\`${Y}.secret.value\` is the same as \`route.domains.trustProxy[${j}].secret.value\`. Give each proxy a secret of its own.`);Z.set(J.secret.value,W)})}function TB($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!sW.test(W)))throw Error(`\`${Z}.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(W)}.`);let z=(W??J)?.toLowerCase()??null;if(Y!==void 0){if(typeof Y!=="string"||!sW.test(Y))throw Error(`\`${Z}.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(Y)}.`);if(!j)throw Error(`\`${Z}.clientIpHeader\` needs \`secret\`: without proof the proxy sent it, any client that reaches the app directly picks its own address.`);if(Y.toLowerCase()===z)throw Error(`\`${Z}.clientIpHeader\` names the same header as \`hostHeader\`.`);if(typeof j.header==="string"&&Y.toLowerCase()===j.header.toLowerCase())throw Error(`\`${Z}.clientIpHeader\` names the same header as \`secret.header\`.`)}if(!j)return;if(typeof j.header!=="string"||!sW.test(j.header))throw Error(`\`${Z}.secret.header\` must be a header name. Got "${j.header}".`);if(j.header.toLowerCase()===z)throw Error(`\`${Z}.secret.header\` names the same header as \`hostHeader\`; the secret needs a header of its own.`);if(typeof j.value!=="string"||j.value.length<X8)throw Error(`\`${Z}.secret.value\` must be at least ${X8} characters. A guessable one lets any client name its own host.`)}function x1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function sM($){try{let Z=new URL(`http://${$.trim()}`),J=Z.hostname.toLowerCase().replace(/\.$/,"");return J?Z.port?`${J}:${Z.port}`:J:null}catch{return null}}function NB($){if($===void 0)return[];if($===!0)return!0;if(!Array.isArray($))throw Error(`\`route.domains.devHosts\` must be a list of hostnames (or \`true\`). Got ${JSON.stringify($)}.`);return $.map((Z,J)=>{let W=typeof Z==="string"?Z.trim().toLowerCase():"",Y=W.startsWith(".")?W.slice(1):W;if(!Y||!Y.split(".").every((j)=>z8.test(j)))throw Error(`\`route.domains.devHosts[${J}]\` must be a bare hostname, e.g. "app.acme.test", or ".acme.test" for the domain and its subdomains \u2014 no scheme, port, path or "*". Got ${JSON.stringify(Z)}.`);return W})}function nM($){let Z=x1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>z8.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<X8)throw Error(`\`route.domains.ask.secret\` must be at least ${X8} characters. A guessable one is worse than leaving \`ask\` out.`);iM($.trustProxy),NB($.devHosts);let W=new Set,Y=null;for(let j of $.groups??[]){let{subdomain:z}=j;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),PB(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>z8.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class aW{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){nM($),this.root=x1($.root),this.devHosts=NB($.devHosts),this.hostTrusts=lM($.trustProxy);for(let Z of $.groups??[])if(PB(Z.subdomain))this.param={...Z,name:Z.subdomain.slice(1)};else this.fixed.set(Z.subdomain.toLowerCase(),Z);this.custom=$.custom??null,this.cacheTtlMs=this.custom?.cacheTtlMs??cM,this.askSecret=$.ask?.secret??null,this.proxySecretHeaders=Array.from(new Set(this.hostTrusts.flatMap((Z)=>Z.secret?[Z.secret.header]:[])))}trustOf($){let Z=null;for(let J of this.hostTrusts)if((!J.secret||e3($.headers.get(J.secret.header),J.secret.value))&&!Z)Z=J;return Z}forwardedHost($){let Z=this.trustOf($)?.header;if(!Z)return null;return $.headers.get(Z)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.trustOf($);if(!Z?.clientIpHeader||!Z.secret)return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:f$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return x1(this.forwardedHost($))??x1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&x1(Y)?sM(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:oW,params:{},custom:!0};return null}async allows($,Z){let J=x1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:G8,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&z8.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=uM)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=x1($);if(Z)this.cache.delete(Z)}}}var oM={kind:"none"};function iA($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return oM;if(Z==="true")return{kind:"all"};if(/^[1-9]\d*$/.test(Z))return{kind:"hops",hops:Number(Z)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify($)}.`)}function sA($,Z,J){if(J.kind==="all"){if(!$.get("x-forwarded-for")&&Z)$.set("x-forwarded-for",Z);return}$.delete("x-real-ip");let W=Z;if(J.kind==="hops"){let Y=($.get("x-forwarded-for")??"").split(",").map((X)=>X.trim()).filter(Boolean),j=Y.length-J.hops,z=j>=0?Y[j]:Y[0];W=(z===void 0?null:f$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var _B=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,IB=16;function nA($){let Z=$.GEMI_CLIENT_IP_HEADER?.trim()??"",J=$.GEMI_PROXY_SECRET_HEADER?.trim()??"",W=$.GEMI_PROXY_SECRET??"";if(Z===""&&J===""&&W==="")return null;if(Z===""||J===""||W==="")throw Error("GEMI_CLIENT_IP_HEADER, GEMI_PROXY_SECRET_HEADER and GEMI_PROXY_SECRET go together: the client-IP header is only believed on a request that carries the proxy's secret. Set all three, or none.");if(!_B.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!_B.test(J))throw Error(`GEMI_PROXY_SECRET_HEADER must be a single header name, e.g. "x-azure-fdid". Got ${JSON.stringify(J)}.`);if(Z.toLowerCase()===J.toLowerCase())throw Error("GEMI_CLIENT_IP_HEADER and GEMI_PROXY_SECRET_HEADER name the same header.");if(W.length<IB)throw Error(`GEMI_PROXY_SECRET must be at least ${IB} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function xB($,Z){if(!e3($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:f$(J)}var aM="/__gemi__/domains/ask";class B1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;staticFilesVary=!1;constructor($,Z){this.groups.set(G8,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new aW(J);let W=(Y)=>({api:Y.api?new j8({...Z.api,...Y.api}):$.api,view:Y.view?new r3({...Z.view,...Y.view},Z.auth):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(oW,W(J.custom.fallback));this.staticFilesVary=this.viewDispatchers().some((Y)=>Y.publicFiles!==$.view.publicFiles||Y.assetRoutes!==$.view.assetRoutes)}async staticFiles($){let Z=(this.staticFilesVary?await this.route($):null)?.view??this.dispatchers(null).view;return{publicFiles:Z.publicFiles,assetRoutes:Z.assetRoutes}}applyClientIp($){let Z=this.clientIpTrust;if(Z)tW($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?xB($.headers,Z):null);if(!J)return;$.headers.set("x-forwarded-for",J),$.headers.delete("x-real-ip")}async route($){if(!this.resolver)return this.dispatchers(null);for(let J of this.resolver.proxySecretHeaders)tW($,J);let Z=Z8($)??await this.resolver.resolve($);if(!Z)return null;return Z3($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==aM)return null;if(!e3(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??G8)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function W3($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var CB=600000;function AB($,Z){return[T6($,Z),T6($,Z-1)]}class b{static token="auth";config;provider;constructor($={},Z=new F7){l9($.oauthProviders),this.config={..._1(i9($),$),emailCode:z7($.emailCode),passwordLimits:j7($.passwordLimits)},this.provider=Z}async oauthProvider($){return await TZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await GY(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=H().bound(B1)?H(B1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?H(B1).resolver?.root:x1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??x1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!t8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=W3(J.expiresAt),j=W3(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=P.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/CB),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let Q=T6($,j),V=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:Q,userId:V,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=Q}if(!z){for(let Q of AB($,j))if((await this.userProvider.findSession({token:Q,userAgent:Z}))?.user){z=Q;break}}if(!z)return null;let G=await this.getSession(z,Z);if(G)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(G.expiresAt)));return G}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(t8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/CB),W=AB($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=P.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new A;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new A,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new w$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=E9(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=null;try{z=await this.userProvider.findSession({token:Y,userAgent:W??""})}catch(X){console.error("Reading the new session back failed:",X)}return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){let{activeCodes:J,expiresInMinutes:W,linkExpiresInMinutes:Y}=this.config.emailCode,j=await this.config.generateMagicLinkToken($),z=await this.config.generateCode($),X=typeof z==="string"&&z!==""?z:q9(Z),G=P6("link",$,j),Q=P6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let V=Math.max(W,Y)*60000,B=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((U)=>W3(U.createdAt)+V>Date.now()&&U.pin!==Q&&U.token!==G);await this.userProvider.deleteMagicLinkTokensExcept($,B.map((U)=>U.id))}return await this.userProvider.createMagicLinkToken({email:$,token:G,pin:Q}),{email:$,pin:X,token:j}}async oneTimeCodeRows($){let{activeCodes:Z}=this.config.emailCode;if(Z===1){let J=await this.userProvider.findMagicLinkTokenByEmail($);return J?[J]:[]}return await this.userProvider.listMagicLinkTokensByEmail($,Z)}async claimOneTimeCode($,Z){if(!await this.userProvider.claimMagicLinkToken(Z))return!1;if(this.config.emailCode.activeCodes>1)await this.userProvider.deleteMagicLinkToken($);return!0}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.oneTimeCodeRows($);if(j.length===0)return KZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((Q)=>W3(Q.createdAt)+W*60000>Date.now());if(z.length===0)return KZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let Q of z)if(!await y9(Q.id,W3(Q.createdAt),Y,W))X=!1;if(!X){if(this.config.emailCode.activeCodes===1)await this.userProvider.claimMagicLinkToken(z[0].id);else await this.userProvider.deleteMagicLinkToken($);return{status:"too_many_attempts"}}let G=null;for(let Q of z)if(KZ("pin",$,Q.pin,Z))G??=Q;if(!G)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,G.id))return{status:"invalid"};return{status:"ok",row:G}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return KZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(KZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(W3(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class f0 extends h{static getFacadeAccessor(){return b}static async user(){let $=await f0.userOrNull();if($)return $;throw new w$({redirectTo:F6(P.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=P.getStore();if($?.user)return $.user;let Z=await z6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=P.getStore()?.req;return O1(Z?.search.get(l0),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await f0.user();if(!await $(Z))throw new LZ}static async guardSafe($){let Z=await f0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class Q8{static ensure($,Z={}){let J=P.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new rZ(o3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=Q8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){Q8.ensure($,Z[0])}static noPrefetch(){let $=P.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new rZ(o3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function tM($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function rW($,Z={}){let J=$.replace(/\/:(\w+)([*?]?)/g,(W,Y,j)=>{let z=Object.hasOwn(Z,Y)?Z[Y]:void 0;if(z===void 0||z===""){if(j)return"";throw Error(`\`${$}\` needs a value for :${Y}.`)}return`/${j==="*"?tM(z):encodeURIComponent(String(z))}`});return`${B8}${J==="/"?"":J}`||B8}var SB=new Map;function EB($,Z){let J=SB.get($);if(!J)J=new URLPattern({pathname:`${B8}${$==="/"?"":$}`}),SB.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;if(!Y)return null;let j={};for(let[z,X]of Object.entries(Y)){if(X===void 0)continue;try{j[z]=decodeURIComponent(X)}catch{return null}}return j}function bB($,Z,J="/"){let W=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(J.startsWith("/")?J:`/${J}`,W),z=rM(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(j.hostname=z.hostname,z.port)j.port=z.port;return j.toString()}function rM($){try{let Z=new URL(`http://${$.trim()}`);return Z.host===$.trim().toLowerCase()&&Z.pathname==="/"?{hostname:Z.hostname,port:Z.port}:null}catch{return null}}class RB{static origin($){return eW($)}static absolute($,...Z){return`${WZ()}${O0(String($),Z[0]??{})}`}static relative($,...Z){return O0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=H(B1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=P.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):WZ();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return bB({root:W.root,origin:j},$,O0(String(Z),J[0]??{}))}static api($,...Z){return rW(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${eW()}${rW(String($),Z[0]??{})}`}static matchApi($,Z){return EB(String($),Z)}}class kB{name="Meta";static description($){P.getStore().metadata.description($)}static title($){P.getStore().metadata.title($)}static openGraph($){P.getStore().metadata.openGraph($)}static htmlAttributes($){P.getStore().metadata.htmlAttributes($)}static canonical($){P.getStore().metadata.canonical($)}static alternates($){P.getStore().metadata.alternates($)}static tags($){P.getStore().metadata.tags($)}static robots($){P.getStore().metadata.robots($)}static translate($=!0){P.getStore().metadata.translate($)}static fonts($){P.getStore().metadata.fonts($)}}var eM={set($,Z,J){P.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(P.getStore().req.cookies.has($))return!1;return P.getStore().setCookie($,Z,J),!0},delete($,Z){P.getStore().deleteCookie($,Z)}};class s1 extends h{static getFacadeAccessor(){return GZ}static get client(){return this.getFacadeRoot().client}static get($){return s1.client.get($)}static set($,Z){return s1.client.set($,Z)}static del(...$){return s1.client.del(...$)}static exists($){return s1.client.exists($)}static incr($){return s1.client.incr($)}static expire($,Z){return s1.client.expire($,Z)}static ttl($){return s1.client.ttl($)}}function lS($){return $}function wB(){return{store:"memory",ttl:null}}class $2{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var $H="500";class Z2{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${ZH(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",$H]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=H(),Z=$.bound(GZ)?$.make(GZ).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function ZH($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var JH="k:",fB="tag:",WH="t:";class J2{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class W2 extends J2{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=_1(wB(),$),this.config.ttl!==null&&this.config.ttl!==void 0)QZ(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new vB(this,Z)}async flush(){await this.store.flush()}async storeKey($){return JH+gB($)}async read($){let Z=await this.store.get($);if(Z===null)return{found:!1};try{return{found:!0,value:JSON.parse(Z)}}catch{return{found:!1}}}async write($,Z,J){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let W=this.ttlMs(J);if(W===0){await this.store.delete($);return}let Y=JSON.stringify(Z);if(Y===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,Y,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let Y=this.inflight.get($);if(Y)return Y;let j=(async()=>{try{let z=await J();if(z!==void 0)await this.write($,z,Z);return z}finally{this.inflight.delete($)}})();return this.inflight.set($,j),j}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=fB+Z,W=await this.store.get(J);if(W!==null)return W;let Y=qB();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(fB+Z,qB(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:QZ(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new $2(this.config.memory);if($==="redis"){let Z=this.options.application;return new Z2({...this.config.redis,client:Z?{send:(J,W)=>Z.make(GZ).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class vB extends J2{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){gB($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${WH}${Z.join(",")}:${$}`}}function gB($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function qB(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class yB extends h{static getFacadeAccessor(){return W2}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class mB extends h{static getFacadeAccessor(){return D1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class pB extends h{static getFacadeAccessor(){return hB}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class cB extends h{static getFacadeAccessor(){return dB}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class uB extends h{static getFacadeAccessor(){return i3}static for($,Z,J){return this.getFacadeRoot().for($,Z,J)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,J){return this.getFacadeRoot().save($,Z,J)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}function KE($){return $}function lB(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function V8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function Y2($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:YH}=globalThis.Bun;function jH(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var zH=async($)=>{let Z=new YH($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},XH=async($)=>{let Z;try{Z=(await import("./chunk-12gthjxx.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,Y,j)=>J.listen(W,Y,j),close:()=>J.end({timeout:1}).catch(()=>{})}},iB=($)=>jH()?zH($):XH($);var GH=/^[A-Za-z_][A-Za-z0-9_]*$/;class j2{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!GH.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let j=Z.retain??1000;if(!Number.isInteger(j)||j<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${j}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=j,this.listener=Z.listener??iB}async createTable(){for(let $ of QH(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let j=this.sqliteTurn.then(Y);return this.sqliteTurn=j.catch(()=>{}),j}let W=this.append(J,$,Z);return sB(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
24
24
  INSERT INTO ${W} (channel, seq) VALUES (${Z}, 1)
25
25
  ON CONFLICT (channel) DO UPDATE SET seq = ${W}.seq + 1
26
26
  RETURNING seq
@@ -112,6 +112,6 @@ data: ${JSON.stringify(Z)}
112
112
  "updated_at" BIGINT NOT NULL,
113
113
  "finished_at" BIGINT,
114
114
  "deadline_at" BIGINT${W}
115
- )`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var GV=191,QV=30000;class L8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class M8 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class H2{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=_1(jV(),$),this.store=MH(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(Y3);return this.ownFeed??=new Y3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){FV("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;FV("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:QZ($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return LH(Z),this.change($,C1,{status:"running",progress:Z})}complete($,Z){return this.change($,C1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,C1,{status:"failed",error:VV(Z)})}cancel($,Z){return this.change($,C1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new L8($);if(A1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(G)=>{if(Y.signal.aborted)return;await this.progress($,G)}},X;try{let G=await Z(z);X=await this.complete($,G)}catch(G){if(!(G instanceof M8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,C1,{status:"failed",error:G instanceof M8?VV(G):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+QZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new L8($);let z=null;for(;;){if(A1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let G=W-Date.now();if(G<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await BV(z,Math.min(G,X??1/0,QV),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new L8($);if(yield W,A1(W.status))return;for await(let Y of J){let j=DH(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,A1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=QZ($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||A1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,C1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(A1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,BV(j,Math.min(z??1/0,QV))]);if(X==="ended")return;if(X)j=null;Z=await this.store.get($)??Z}}catch(z){console.error(`[gemi] Run ${$}: could not follow the run for a cancel.`,z)}}async change($,Z,J){let W=await this.store.transition($,Z,J);if(W)await this.publish(W);return W}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function BV($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>G(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},G=(Q)=>{X(),W(Q)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>G(!0),()=>G(!0))})}function DH($,Z){if($.type!=="change")return null;let J=$.data;if(!J||typeof J!=="object"||J.id!==Z||typeof J.version!=="number")return null;return J}function VV($){if(typeof $==="string")return{message:$};if($ instanceof M8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function FV($,Z){if(typeof Z!=="string"||Z===""||Z.length>GV)throw TypeError(`A run's ${$} is a string of 1 to ${GV} characters; got ${JSON.stringify(Z)}.`)}function LH($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function MH($,Z){if($==="memory")return new U2;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(q1).connection();return new M2(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class UV extends h{static getFacadeAccessor(){return H2}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class OV extends h{static getFacadeAccessor(){return W$}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class K2{value;constructor($){this.value=$}}var HH=/^[A-Za-z_][A-Za-z0-9_$]*$/;function KH($){let Z=["SET TRANSACTION READ ONLY"],J=[["statementTimeoutMs","statement_timeout"],["lockTimeoutMs","lock_timeout"],["idleInTransactionTimeoutMs","idle_in_transaction_session_timeout"]];for(let[W,Y]of J){let j=$[W];if(j===void 0)continue;if(typeof j!=="number"||!Number.isInteger(j)||j<=0)throw TypeError(`DB.readOnly: ${W} must be a positive whole number of milliseconds, got ${String(j)}.`);Z.push(`SET LOCAL ${Y} = ${j}`)}if($.role!==void 0){if(typeof $.role!=="string"||!HH.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class T8{bound;constructor($){this.bound=$}get name(){return this.bound??f1()}get sql(){return this.connection().sql}get dialect(){return this.connection().dialect}async query($){return await this.run($,"query")}async execute($){let Z=await this.run($,"execute");return Number(Z?.count??0)}async transaction($){let Z=this.name,J=this.connection(Z);return K8(J.sql,(W)=>H8(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async readOnly($,Z){let J=typeof $==="function"?{}:$,W=typeof $==="function"?$:Z;if(typeof W!=="function")throw TypeError("DB.readOnly needs a callback: readOnly(options, async (tx) => ...).");let Y=KH(J??{}),j=this.name,z=this.connection(j);if(z.dialect!=="postgres")throw Error(`DB.readOnly is supported on Postgres only, and the "${j}" connection is ${z.dialect}.`);if(s0()!==void 0)throw Error("DB.readOnly cannot run inside a transaction: SET TRANSACTION READ ONLY has to be the first statement of its own transaction. Call it outside the transaction.");try{await K8(z.sql,async(X)=>{for(let Q of Y)await X.unsafe(Q);await MV();let G=await H8(j,()=>W(X));throw new K2(G)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j,deferSettings:!0})}catch(X){if(X instanceof K2)return X.value;throw X}throw Error("DB.readOnly: the transaction committed, which it never should.")}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-8ncqxja2.js");return Z(this.handle()??$.sql,$.dialect)}async withSettings($,Z){let J=this.connection();if(J.dialect!=="postgres")throw Error(`DB.withSettings is supported on Postgres only, and the "${J.name}" connection is ${J.dialect}.`);return HV($,Z)}run($,Z){let J=this.connection(),{text:W,values:Y}=TV($,KV(J.dialect),Z),j=this.handle();if(j===void 0&&LV()){let z=this.name;return K8(J.sql,(X)=>H8(z,()=>X.unsafe(W,Y)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:z})}return(j??J.sql).unsafe(W,Y)}handle(){let $=s0();if($===void 0)return;return f1()===this.name?$:void 0}connection($=this.name){return DV($),H(q1).connection($)}}var I$=new T8;class PV extends h{static getFacadeAccessor(){return q1}static connection($){return new T8($)}static get sql(){return I$.sql}static get dialect(){return I$.dialect}static query($){return I$.query($)}static execute($){return I$.execute($)}static transaction($){return I$.transaction($)}static withSettings($,Z){return I$.withSettings($,Z)}static readOnly($,Z){return I$.readOnly($,Z)}static schema(){return I$.schema()}static close(){return this.getFacadeRoot().close()}}export{U1 as Me,SV as Ne,e0 as Oe,X3 as Pe,C8 as Qe,x0 as Re,z6 as Se,a8 as Te,t8 as Ue,E9 as Ve,J$ as We,D1 as Xe,f$ as Ye,Z0 as Ze,X9 as _e,DZ as $e,b9 as af,R9 as bf,e8 as cf,$7 as df,P6 as ef,KZ as ff,d9 as gf,cF as hf,c9 as if,uF as jf,pP as kf,i9 as lf,$Y as mf,G7 as nf,ZY as of,JY as pf,rF as qf,WY as rf,Q7 as sf,ZU as tf,JU as uf,B7 as vf,YY as wf,jY as xf,W$ as yf,zY as zf,zU as Af,F7 as Bf,g8 as Cf,U6 as Df,b1 as Ef,f8 as Ff,R1 as Gf,_$ as Hf,Q8 as If,RB as Jf,kB as Kf,eM as Lf,s1 as Mf,lS as Nf,wB as Of,$2 as Pf,Z2 as Qf,W2 as Rf,vB as Sf,yB as Tf,mB as Uf,pB as Vf,cB as Wf,uB as Xf,KE as Yf,lB as Zf,V8 as _f,Y2 as $f,j2 as ag,z2 as bg,F8 as cg,Y3 as dg,JV as eg,WV as fg,i as gg,G3 as hg,y4 as ig,CN as jg,AN as kg,SN as lg,kN as mg,UG as ng,y5 as og,LG as pg,gN as qg,KG as rg,d0 as sg,d3 as tg,TG as ug,YV as vg,rE as wg,F2 as xg,C1 as yg,A1 as zg,U2 as Ag,M2 as Bg,OH as Cg,L8 as Dg,M8 as Eg,H2 as Fg,UV as Gg,OV as Hg,T8 as Ig,PV as Jg,h5 as Kg,WL as Lg,n5 as Mg,o5 as Ng,a_ as Og,cG as Pg,sG as Qg,G6 as Rg,r1 as Sg,VI as Tg,oG as Ug,aG as Vg,HW as Wg,eZ as Xg,KW as Yg,XC as Zg,DC as _g,LC as $g,_M as ah,gW as bh,CM as ch,lW as dh,RM as eh,hW as fh,fM as gh,r3 as hh,iW as ih,LB as jh,Y8 as kh,j8 as lh,iA as mh,sA as nh,nA as oh,B1 as ph,b as qh,f0 as rh,Q6 as sh,c2 as th,hV as uh,h2 as vh,l2 as wh,R8 as xh,V6 as yh,k8 as zh,i2 as Ah,sV as Bh,nV as Ch,r2 as Dh,$9 as Eh,J9 as Fh,Q9 as Gh,B9 as Hh,V9 as Ih,p8 as Jh,$F as Kh,j0 as Lh,N9 as Mh,MZ as Nh,A9 as Oh};
115
+ )`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var GV=191,QV=30000;class L8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class M8 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class H2{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=_1(jV(),$),this.store=MH(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(Y3);return this.ownFeed??=new Y3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){FV("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;FV("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:QZ($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return LH(Z),this.change($,C1,{status:"running",progress:Z})}complete($,Z){return this.change($,C1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,C1,{status:"failed",error:VV(Z)})}cancel($,Z){return this.change($,C1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new L8($);if(A1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(G)=>{if(Y.signal.aborted)return;await this.progress($,G)}},X;try{let G=await Z(z);X=await this.complete($,G)}catch(G){if(!(G instanceof M8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,C1,{status:"failed",error:G instanceof M8?VV(G):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+QZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new L8($);let z=null;for(;;){if(A1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let G=W-Date.now();if(G<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await BV(z,Math.min(G,X??1/0,QV),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new L8($);if(yield W,A1(W.status))return;for await(let Y of J){let j=DH(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,A1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=QZ($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||A1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,C1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(A1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,BV(j,Math.min(z??1/0,QV))]);if(X==="ended")return;if(X)j=null;Z=await this.store.get($)??Z}}catch(z){console.error(`[gemi] Run ${$}: could not follow the run for a cancel.`,z)}}async change($,Z,J){let W=await this.store.transition($,Z,J);if(W)await this.publish(W);return W}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function BV($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>G(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},G=(Q)=>{X(),W(Q)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>G(!0),()=>G(!0))})}function DH($,Z){if($.type!=="change")return null;let J=$.data;if(!J||typeof J!=="object"||J.id!==Z||typeof J.version!=="number")return null;return J}function VV($){if(typeof $==="string")return{message:$};if($ instanceof M8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function FV($,Z){if(typeof Z!=="string"||Z===""||Z.length>GV)throw TypeError(`A run's ${$} is a string of 1 to ${GV} characters; got ${JSON.stringify(Z)}.`)}function LH($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function MH($,Z){if($==="memory")return new U2;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(q1).connection();return new M2(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class UV extends h{static getFacadeAccessor(){return H2}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class OV extends h{static getFacadeAccessor(){return W$}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class K2{value;constructor($){this.value=$}}var HH=/^[A-Za-z_][A-Za-z0-9_$]*$/;function KH($){let Z=["SET TRANSACTION READ ONLY"],J=[["statementTimeoutMs","statement_timeout"],["lockTimeoutMs","lock_timeout"],["idleInTransactionTimeoutMs","idle_in_transaction_session_timeout"]];for(let[W,Y]of J){let j=$[W];if(j===void 0)continue;if(typeof j!=="number"||!Number.isInteger(j)||j<=0)throw TypeError(`DB.readOnly: ${W} must be a positive whole number of milliseconds, got ${String(j)}.`);Z.push(`SET LOCAL ${Y} = ${j}`)}if($.role!==void 0){if(typeof $.role!=="string"||!HH.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class T8{bound;constructor($){this.bound=$}get name(){return this.bound??f1()}get sql(){return this.connection().sql}get dialect(){return this.connection().dialect}async query($){return await this.run($,"query")}async execute($){let Z=await this.run($,"execute");return Number(Z?.count??0)}async transaction($){let Z=this.name,J=this.connection(Z);return K8(J.sql,(W)=>H8(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async readOnly($,Z){let J=typeof $==="function"?{}:$,W=typeof $==="function"?$:Z;if(typeof W!=="function")throw TypeError("DB.readOnly needs a callback: readOnly(options, async (tx) => ...).");let Y=KH(J??{}),j=this.name,z=this.connection(j);if(z.dialect!=="postgres")throw Error(`DB.readOnly is supported on Postgres only, and the "${j}" connection is ${z.dialect}.`);if(s0()!==void 0)throw Error("DB.readOnly cannot run inside a transaction: SET TRANSACTION READ ONLY has to be the first statement of its own transaction. Call it outside the transaction.");try{await K8(z.sql,async(X)=>{for(let Q of Y)await X.unsafe(Q);await MV();let G=await H8(j,()=>W(X));throw new K2(G)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j,deferSettings:!0})}catch(X){if(X instanceof K2)return X.value;throw X}throw Error("DB.readOnly: the transaction committed, which it never should.")}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-9d8tz60r.js");return Z(this.handle()??$.sql,$.dialect)}async withSettings($,Z){let J=this.connection();if(J.dialect!=="postgres")throw Error(`DB.withSettings is supported on Postgres only, and the "${J.name}" connection is ${J.dialect}.`);return HV($,Z)}run($,Z){let J=this.connection(),{text:W,values:Y}=TV($,KV(J.dialect),Z),j=this.handle();if(j===void 0&&LV()){let z=this.name;return K8(J.sql,(X)=>H8(z,()=>X.unsafe(W,Y)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:z})}return(j??J.sql).unsafe(W,Y)}handle(){let $=s0();if($===void 0)return;return f1()===this.name?$:void 0}connection($=this.name){return DV($),H(q1).connection($)}}var I$=new T8;class PV extends h{static getFacadeAccessor(){return q1}static connection($){return new T8($)}static get sql(){return I$.sql}static get dialect(){return I$.dialect}static query($){return I$.query($)}static execute($){return I$.execute($)}static transaction($){return I$.transaction($)}static withSettings($,Z){return I$.withSettings($,Z)}static readOnly($,Z){return I$.readOnly($,Z)}static schema(){return I$.schema()}static close(){return this.getFacadeRoot().close()}}export{U1 as Ne,SV as Oe,e0 as Pe,X3 as Qe,C8 as Re,x0 as Se,z6 as Te,a8 as Ue,t8 as Ve,E9 as We,J$ as Xe,D1 as Ye,f$ as Ze,Z0 as _e,X9 as $e,DZ as af,b9 as bf,R9 as cf,e8 as df,$7 as ef,P6 as ff,KZ as gf,d9 as hf,cF as if,c9 as jf,uF as kf,pP as lf,i9 as mf,$Y as nf,G7 as of,ZY as pf,JY as qf,rF as rf,WY as sf,Q7 as tf,ZU as uf,JU as vf,B7 as wf,YY as xf,jY as yf,W$ as zf,zY as Af,zU as Bf,F7 as Cf,g8 as Df,U6 as Ef,b1 as Ff,f8 as Gf,R1 as Hf,_$ as If,Q8 as Jf,RB as Kf,kB as Lf,eM as Mf,s1 as Nf,lS as Of,wB as Pf,$2 as Qf,Z2 as Rf,W2 as Sf,vB as Tf,yB as Uf,mB as Vf,pB as Wf,cB as Xf,uB as Yf,KE as Zf,lB as _f,V8 as $f,Y2 as ag,j2 as bg,z2 as cg,F8 as dg,Y3 as eg,JV as fg,WV as gg,i as hg,G3 as ig,y4 as jg,CN as kg,AN as lg,SN as mg,kN as ng,UG as og,y5 as pg,LG as qg,gN as rg,KG as sg,d0 as tg,d3 as ug,TG as vg,YV as wg,rE as xg,F2 as yg,C1 as zg,A1 as Ag,U2 as Bg,M2 as Cg,OH as Dg,L8 as Eg,M8 as Fg,H2 as Gg,UV as Hg,OV as Ig,T8 as Jg,PV as Kg,h5 as Lg,WL as Mg,n5 as Ng,o5 as Og,a_ as Pg,cG as Qg,sG as Rg,G6 as Sg,r1 as Tg,VI as Ug,oG as Vg,aG as Wg,HW as Xg,eZ as Yg,KW as Zg,XC as _g,DC as $g,LC as ah,_M as bh,gW as ch,CM as dh,lW as eh,RM as fh,hW as gh,fM as hh,r3 as ih,iW as jh,LB as kh,Y8 as lh,j8 as mh,iA as nh,sA as oh,nA as ph,B1 as qh,b as rh,f0 as sh,Q6 as th,c2 as uh,hV as vh,h2 as wh,l2 as xh,R8 as yh,V6 as zh,k8 as Ah,i2 as Bh,sV as Ch,nV as Dh,r2 as Eh,$9 as Fh,J9 as Gh,Q9 as Hh,B9 as Ih,V9 as Jh,p8 as Kh,$F as Lh,j0 as Mh,N9 as Nh,MZ as Oh,A9 as Ph};
116
116
 
117
- //# debugId=02D5CF6DA791675164756E2164756E21
117
+ //# debugId=F13E01C18F11BC2B64756E2164756E21