gemi 0.184.0 → 0.185.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 (203) hide show
  1. package/dist/ai/generate.d.ts +29 -0
  2. package/dist/ai/generate.d.ts.map +1 -1
  3. package/dist/ai/index.d.ts +3 -1
  4. package/dist/ai/index.d.ts.map +1 -1
  5. package/dist/ai/index.js +90 -90
  6. package/dist/ai/index.js.map +2 -2
  7. package/dist/ai/partialJson.d.ts +68 -0
  8. package/dist/ai/partialJson.d.ts.map +1 -0
  9. package/dist/app/index.js +1 -1
  10. package/dist/bun/plugin.js +1 -1
  11. package/dist/bun/preload.js +1 -1
  12. package/dist/{chunk-adsbv4rm.js → chunk-00sj67nx.js} +2 -2
  13. package/dist/{chunk-adsbv4rm.js.map → chunk-00sj67nx.js.map} +1 -1
  14. package/dist/{chunk-r1sjx2q9.js → chunk-0ahecas6.js} +2 -2
  15. package/dist/{chunk-r1sjx2q9.js.map → chunk-0ahecas6.js.map} +1 -1
  16. package/dist/{chunk-g06f1xf3.js → chunk-0rkastve.js} +4 -4
  17. package/dist/{chunk-g06f1xf3.js.map → chunk-0rkastve.js.map} +1 -1
  18. package/dist/{chunk-vm3ayd1b.js → chunk-2qac05gb.js} +3 -3
  19. package/dist/{chunk-vm3ayd1b.js.map → chunk-2qac05gb.js.map} +1 -1
  20. package/dist/{chunk-k6x35rn5.js → chunk-2rpz1p8g.js} +1 -1
  21. package/dist/{chunk-ztvewkks.js → chunk-3derdn99.js} +3 -3
  22. package/dist/{chunk-ztvewkks.js.map → chunk-3derdn99.js.map} +1 -1
  23. package/dist/{chunk-g57cg31m.js → chunk-3fm7gmp5.js} +2 -2
  24. package/dist/{chunk-g57cg31m.js.map → chunk-3fm7gmp5.js.map} +1 -1
  25. package/dist/{chunk-yrd14jjt.js → chunk-3jpj6hjh.js} +1 -1
  26. package/dist/{chunk-neh2zrp0.js → chunk-4q505by7.js} +2 -2
  27. package/dist/{chunk-neh2zrp0.js.map → chunk-4q505by7.js.map} +1 -1
  28. package/dist/{chunk-7g90w0t6.js → chunk-64r5cs5g.js} +1 -1
  29. package/dist/{chunk-6s7bb50m.js → chunk-6d3527qt.js} +3 -3
  30. package/dist/{chunk-6s7bb50m.js.map → chunk-6d3527qt.js.map} +1 -1
  31. package/dist/{chunk-3jnnma7m.js → chunk-6daabbfj.js} +2 -2
  32. package/dist/{chunk-3jnnma7m.js.map → chunk-6daabbfj.js.map} +1 -1
  33. package/dist/{chunk-am9gmm5a.js → chunk-6tferehw.js} +2 -2
  34. package/dist/{chunk-am9gmm5a.js.map → chunk-6tferehw.js.map} +1 -1
  35. package/dist/{chunk-q9xsgn2s.js → chunk-7b10n8m8.js} +2 -2
  36. package/dist/{chunk-q9xsgn2s.js.map → chunk-7b10n8m8.js.map} +1 -1
  37. package/dist/{chunk-rz6npg3r.js → chunk-7bz43qbt.js} +3 -3
  38. package/dist/{chunk-rz6npg3r.js.map → chunk-7bz43qbt.js.map} +1 -1
  39. package/dist/{chunk-07ttfngb.js → chunk-7dhvb6nn.js} +2 -2
  40. package/dist/{chunk-07ttfngb.js.map → chunk-7dhvb6nn.js.map} +1 -1
  41. package/dist/{chunk-ambptjfh.js → chunk-7gnspwra.js} +2 -2
  42. package/dist/{chunk-ambptjfh.js.map → chunk-7gnspwra.js.map} +1 -1
  43. package/dist/{chunk-njrnn5dw.js → chunk-7tm669mw.js} +2 -2
  44. package/dist/{chunk-njrnn5dw.js.map → chunk-7tm669mw.js.map} +1 -1
  45. package/dist/{chunk-btt706nx.js → chunk-810nrvt4.js} +2 -2
  46. package/dist/{chunk-btt706nx.js.map → chunk-810nrvt4.js.map} +1 -1
  47. package/dist/{chunk-7fzwgvyg.js → chunk-84j5b07n.js} +1 -1
  48. package/dist/{chunk-tr8s1z7k.js → chunk-87nekrjj.js} +3 -3
  49. package/dist/{chunk-tr8s1z7k.js.map → chunk-87nekrjj.js.map} +1 -1
  50. package/dist/{chunk-1kcv4dyh.js → chunk-87pn20z5.js} +2 -2
  51. package/dist/{chunk-1kcv4dyh.js.map → chunk-87pn20z5.js.map} +1 -1
  52. package/dist/{chunk-t797crcj.js → chunk-96r16t57.js} +3 -3
  53. package/dist/{chunk-t797crcj.js.map → chunk-96r16t57.js.map} +1 -1
  54. package/dist/{chunk-vfaen5tf.js → chunk-9mf6qzxy.js} +2 -2
  55. package/dist/{chunk-vfaen5tf.js.map → chunk-9mf6qzxy.js.map} +1 -1
  56. package/dist/{chunk-fzwaybhd.js → chunk-a1414jdv.js} +3 -3
  57. package/dist/{chunk-fzwaybhd.js.map → chunk-a1414jdv.js.map} +1 -1
  58. package/dist/chunk-a1r1r1z7.js +42 -0
  59. package/dist/{chunk-91vxf94n.js.map → chunk-a1r1r1z7.js.map} +5 -4
  60. package/dist/{chunk-pt159v3n.js → chunk-b55zt46z.js} +2 -2
  61. package/dist/{chunk-pt159v3n.js.map → chunk-b55zt46z.js.map} +1 -1
  62. package/dist/{chunk-1863jd18.js → chunk-beqhakdf.js} +2 -2
  63. package/dist/{chunk-1863jd18.js.map → chunk-beqhakdf.js.map} +1 -1
  64. package/dist/{chunk-s9etcqcq.js → chunk-bg2e7stx.js} +2 -2
  65. package/dist/{chunk-s9etcqcq.js.map → chunk-bg2e7stx.js.map} +1 -1
  66. package/dist/{chunk-skyt9hyg.js → chunk-bm3pyh9m.js} +2 -2
  67. package/dist/{chunk-skyt9hyg.js.map → chunk-bm3pyh9m.js.map} +1 -1
  68. package/dist/{chunk-wa7rtfkk.js → chunk-c07s6w45.js} +1 -1
  69. package/dist/{chunk-g09qz75d.js → chunk-cf5a958j.js} +2 -2
  70. package/dist/{chunk-g09qz75d.js.map → chunk-cf5a958j.js.map} +1 -1
  71. package/dist/{chunk-5d6h1znx.js → chunk-d5ftst76.js} +2 -2
  72. package/dist/{chunk-5d6h1znx.js.map → chunk-d5ftst76.js.map} +1 -1
  73. package/dist/{chunk-tvvqhwa3.js → chunk-d9pnjkxr.js} +2 -2
  74. package/dist/{chunk-tvvqhwa3.js.map → chunk-d9pnjkxr.js.map} +1 -1
  75. package/dist/{chunk-7pbwmt7j.js → chunk-dezd1fn5.js} +2 -2
  76. package/dist/{chunk-7pbwmt7j.js.map → chunk-dezd1fn5.js.map} +1 -1
  77. package/dist/{chunk-6dzm2pv7.js → chunk-dh4ax9cj.js} +2 -2
  78. package/dist/{chunk-6dzm2pv7.js.map → chunk-dh4ax9cj.js.map} +1 -1
  79. package/dist/{chunk-eyehyb9v.js → chunk-e38xa29v.js} +2 -2
  80. package/dist/{chunk-eyehyb9v.js.map → chunk-e38xa29v.js.map} +1 -1
  81. package/dist/{chunk-h5s56wzw.js → chunk-ecv4mtgh.js} +2 -2
  82. package/dist/{chunk-h5s56wzw.js.map → chunk-ecv4mtgh.js.map} +1 -1
  83. package/dist/chunk-f25x1sn1.js +5 -0
  84. package/dist/{chunk-y82d4w0m.js.map → chunk-f25x1sn1.js.map} +1 -1
  85. package/dist/{chunk-9beqhac6.js → chunk-f2tjtwm0.js} +2 -2
  86. package/dist/{chunk-9beqhac6.js.map → chunk-f2tjtwm0.js.map} +1 -1
  87. package/dist/{chunk-vgmmftm2.js → chunk-fdpvgeey.js} +2 -2
  88. package/dist/{chunk-vgmmftm2.js.map → chunk-fdpvgeey.js.map} +1 -1
  89. package/dist/{chunk-3m791vwf.js → chunk-g32mpf79.js} +2 -2
  90. package/dist/{chunk-3m791vwf.js.map → chunk-g32mpf79.js.map} +1 -1
  91. package/dist/{chunk-gprc53rf.js → chunk-gtdf51jz.js} +1 -1
  92. package/dist/{chunk-xnfkz18n.js → chunk-h2t135y3.js} +3 -3
  93. package/dist/{chunk-xnfkz18n.js.map → chunk-h2t135y3.js.map} +1 -1
  94. package/dist/{chunk-9brq77q6.js → chunk-hq710s2a.js} +3 -3
  95. package/dist/{chunk-9brq77q6.js.map → chunk-hq710s2a.js.map} +1 -1
  96. package/dist/{chunk-k1v0xgwe.js → chunk-kcvzs31p.js} +2 -2
  97. package/dist/{chunk-k1v0xgwe.js.map → chunk-kcvzs31p.js.map} +1 -1
  98. package/dist/{chunk-5f4k3n9x.js → chunk-krgwft9w.js} +2 -2
  99. package/dist/{chunk-5f4k3n9x.js.map → chunk-krgwft9w.js.map} +1 -1
  100. package/dist/{chunk-7rmsc511.js → chunk-kzv3v0tm.js} +3 -3
  101. package/dist/{chunk-7rmsc511.js.map → chunk-kzv3v0tm.js.map} +1 -1
  102. package/dist/{chunk-8z1z4zbq.js → chunk-m906xc76.js} +2 -2
  103. package/dist/{chunk-8z1z4zbq.js.map → chunk-m906xc76.js.map} +1 -1
  104. package/dist/{chunk-xh3qqmbk.js → chunk-mpreff3t.js} +2 -2
  105. package/dist/{chunk-xh3qqmbk.js.map → chunk-mpreff3t.js.map} +1 -1
  106. package/dist/{chunk-6bf04rk5.js → chunk-mpt1zsfv.js} +2 -2
  107. package/dist/{chunk-6bf04rk5.js.map → chunk-mpt1zsfv.js.map} +1 -1
  108. package/dist/{chunk-ry9jard2.js → chunk-nadkwh8a.js} +3 -3
  109. package/dist/{chunk-ry9jard2.js.map → chunk-nadkwh8a.js.map} +1 -1
  110. package/dist/{chunk-g0ps09h7.js → chunk-przahq2e.js} +2 -2
  111. package/dist/{chunk-g0ps09h7.js.map → chunk-przahq2e.js.map} +1 -1
  112. package/dist/{chunk-y16jhwrv.js → chunk-q19cs1qf.js} +2 -2
  113. package/dist/{chunk-y16jhwrv.js.map → chunk-q19cs1qf.js.map} +1 -1
  114. package/dist/{chunk-p9avgpzd.js → chunk-q6rse2fh.js} +2 -2
  115. package/dist/{chunk-p9avgpzd.js.map → chunk-q6rse2fh.js.map} +1 -1
  116. package/dist/{chunk-62v0y132.js → chunk-rdnxkecg.js} +2 -2
  117. package/dist/{chunk-62v0y132.js.map → chunk-rdnxkecg.js.map} +1 -1
  118. package/dist/{chunk-n6hd9swg.js → chunk-skq4g7qa.js} +2 -2
  119. package/dist/{chunk-n6hd9swg.js.map → chunk-skq4g7qa.js.map} +1 -1
  120. package/dist/{chunk-n31hppcx.js → chunk-spmxhsze.js} +2 -2
  121. package/dist/{chunk-n31hppcx.js.map → chunk-spmxhsze.js.map} +1 -1
  122. package/dist/{chunk-f3s8pz3m.js → chunk-srsmhbpt.js} +2 -2
  123. package/dist/{chunk-f3s8pz3m.js.map → chunk-srsmhbpt.js.map} +1 -1
  124. package/dist/{chunk-nhyx0gec.js → chunk-tbss13e8.js} +2 -2
  125. package/dist/{chunk-nhyx0gec.js.map → chunk-tbss13e8.js.map} +1 -1
  126. package/dist/{chunk-zscd52sv.js → chunk-tvkdqnhv.js} +3 -3
  127. package/dist/{chunk-zscd52sv.js.map → chunk-tvkdqnhv.js.map} +1 -1
  128. package/dist/{chunk-fagkv8sm.js → chunk-ty3kycy4.js} +2 -2
  129. package/dist/{chunk-fagkv8sm.js.map → chunk-ty3kycy4.js.map} +1 -1
  130. package/dist/{chunk-4b5rpya9.js → chunk-vhyabcw9.js} +2 -2
  131. package/dist/{chunk-4b5rpya9.js.map → chunk-vhyabcw9.js.map} +1 -1
  132. package/dist/{chunk-dcwsya9e.js → chunk-vv8vjjez.js} +2 -2
  133. package/dist/{chunk-dcwsya9e.js.map → chunk-vv8vjjez.js.map} +1 -1
  134. package/dist/{chunk-5467avf1.js → chunk-vvg3yxrc.js} +2 -2
  135. package/dist/{chunk-5467avf1.js.map → chunk-vvg3yxrc.js.map} +1 -1
  136. package/dist/{chunk-73svx8gr.js → chunk-wtdmwmm7.js} +3 -3
  137. package/dist/{chunk-73svx8gr.js.map → chunk-wtdmwmm7.js.map} +1 -1
  138. package/dist/{chunk-syqvk994.js → chunk-xgg9w7ep.js} +2 -2
  139. package/dist/{chunk-syqvk994.js.map → chunk-xgg9w7ep.js.map} +1 -1
  140. package/dist/{chunk-0jery7ys.js → chunk-xjb2kzkj.js} +4 -4
  141. package/dist/{chunk-0jery7ys.js.map → chunk-xjb2kzkj.js.map} +1 -1
  142. package/dist/{chunk-5sjteb6f.js → chunk-xmjzyzn6.js} +3 -3
  143. package/dist/{chunk-5sjteb6f.js.map → chunk-xmjzyzn6.js.map} +1 -1
  144. package/dist/{chunk-jc48hhha.js → chunk-yaacfbky.js} +2 -2
  145. package/dist/{chunk-jc48hhha.js.map → chunk-yaacfbky.js.map} +1 -1
  146. package/dist/{chunk-j1j0438r.js → chunk-ye72q3kx.js} +2 -2
  147. package/dist/{chunk-j1j0438r.js.map → chunk-ye72q3kx.js.map} +1 -1
  148. package/dist/{chunk-yantbc9e.js → chunk-ykpc18d1.js} +2 -2
  149. package/dist/{chunk-yantbc9e.js.map → chunk-ykpc18d1.js.map} +1 -1
  150. package/dist/{chunk-cxh9qe1c.js → chunk-yx03gndz.js} +2 -2
  151. package/dist/{chunk-cxh9qe1c.js.map → chunk-yx03gndz.js.map} +1 -1
  152. package/dist/{chunk-7stvx6x7.js → chunk-z2k8m02z.js} +2 -2
  153. package/dist/{chunk-7stvx6x7.js.map → chunk-z2k8m02z.js.map} +1 -1
  154. package/dist/{chunk-7n6vnmtv.js → chunk-z65e3vdy.js} +2 -2
  155. package/dist/{chunk-7n6vnmtv.js.map → chunk-z65e3vdy.js.map} +1 -1
  156. package/dist/{chunk-5nqwxjf1.js → chunk-zenfs4e2.js} +3 -3
  157. package/dist/{chunk-5nqwxjf1.js.map → chunk-zenfs4e2.js.map} +1 -1
  158. package/dist/{chunk-xwvm54dx.js → chunk-zyzhqnbm.js} +2 -2
  159. package/dist/{chunk-xwvm54dx.js.map → chunk-zyzhqnbm.js.map} +1 -1
  160. package/dist/config/index.js +1 -1
  161. package/dist/console/run.js +2 -2
  162. package/dist/console/run.js.map +1 -1
  163. package/dist/container/index.js +2 -2
  164. package/dist/container/index.js.map +1 -1
  165. package/dist/database/index.js +2 -2
  166. package/dist/database/index.js.map +1 -1
  167. package/dist/email/index.js +2 -2
  168. package/dist/email/index.js.map +1 -1
  169. package/dist/facades/index.js +2 -2
  170. package/dist/facades/index.js.map +1 -1
  171. package/dist/foundation/index.js +2 -2
  172. package/dist/foundation/index.js.map +1 -1
  173. package/dist/http/index.js +2 -2
  174. package/dist/http/index.js.map +1 -1
  175. package/dist/i18n/dictionaryRuntime.js +2 -2
  176. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  177. package/dist/i18n/index.js +2 -2
  178. package/dist/i18n/index.js.map +1 -1
  179. package/dist/kernel/index.js +2 -2
  180. package/dist/kernel/index.js.map +1 -1
  181. package/dist/orm/index.js +2 -2
  182. package/dist/orm/index.js.map +1 -1
  183. package/dist/probe/index.js +2 -2
  184. package/dist/probe/index.js.map +1 -1
  185. package/dist/server/index.js +2 -2
  186. package/dist/server/index.js.map +1 -1
  187. package/dist/services/index.js +2 -2
  188. package/dist/services/index.js.map +1 -1
  189. package/dist/services/queue/work.js +2 -2
  190. package/dist/services/queue/work.js.map +1 -1
  191. package/dist/stats/route-table.js +1 -1
  192. package/dist/support/index.js +2 -2
  193. package/dist/support/index.js.map +1 -1
  194. package/dist/vitest/index.js +1 -1
  195. package/package.json +1 -1
  196. package/dist/chunk-91vxf94n.js +0 -41
  197. package/dist/chunk-y82d4w0m.js +0 -5
  198. /package/dist/{chunk-k6x35rn5.js.map → chunk-2rpz1p8g.js.map} +0 -0
  199. /package/dist/{chunk-yrd14jjt.js.map → chunk-3jpj6hjh.js.map} +0 -0
  200. /package/dist/{chunk-7g90w0t6.js.map → chunk-64r5cs5g.js.map} +0 -0
  201. /package/dist/{chunk-7fzwgvyg.js.map → chunk-84j5b07n.js.map} +0 -0
  202. /package/dist/{chunk-wa7rtfkk.js.map → chunk-c07s6w45.js.map} +0 -0
  203. /package/dist/{chunk-gprc53rf.js.map → chunk-gtdf51jz.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ph as vK}from"./chunk-vm3ayd1b.js";import{Jh as yK}from"./chunk-ztvewkks.js";import{$h as d,Bi as O6,Ji as b1,Kh as V3,Ni as qQ,Oh as vG,Oi as YZ,Ph as t5,Pi as jZ,Qh as e5,Qi as DK,Rh as C8,Sh as T8,Si as OK,Vh as P8,Wh as N8,Xh as Z3,Yh as Z8,Zh as hY,_h as N5,fi as C,gi as i8,hi as OZ,ii as A8,ji as U6,li as R$,mi as m,ni as n4,vi as D6}from"./chunk-5nqwxjf1.js";import{Vi as Z$,Wi as H0,Xi as W$,Yi as Zj}from"./chunk-p9avgpzd.js";import{Zi as ZZ,_i as cY,cj as gj,dj as J8,ej as T}from"./chunk-n31hppcx.js";import{hj as IQ,kj as n3}from"./chunk-rz6npg3r.js";import{oj as rj,rj as QK}from"./chunk-fzwaybhd.js";import{Jj as b$,Oj as J$}from"./chunk-4b5rpya9.js";import{ak as jQ}from"./chunk-xwvm54dx.js";import{bk as zZ,ek as zK}from"./chunk-dcwsya9e.js";import{fk as P1}from"./chunk-h5s56wzw.js";import{gk as K6,hk as l0,ik as k1,jk as Q5,kk as qK,mk as iZ,nk as FK,wk as G5}from"./chunk-73svx8gr.js";import{Lk as f1}from"./chunk-ambptjfh.js";import{Qk as kY,Vk as fY}from"./chunk-cxh9qe1c.js";import{al as RY,fl as c}from"./chunk-g09qz75d.js";import{gl as $3,jl as M}from"./chunk-ry9jard2.js";import{rl as CY}from"./chunk-7stvx6x7.js";import{sl as LK}from"./chunk-8z1z4zbq.js";import{Cl as PY}from"./chunk-62v0y132.js";import{Dl as K8,Fl as gG}from"./chunk-r1sjx2q9.js";import{Kl as W8}from"./chunk-xh3qqmbk.js";function Y6($){return typeof $==="function"&&$.prototype!==void 0}var F5=Symbol.for("gemi.HttpResponse"),uK=new Set([301,302,303,307,308]);class K1{kind;body;status;headers;[F5]=!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 V5(J,"json"),new K1("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 K1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!uK.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 K1("empty",void 0,J,Y)}static noContent($={}){return new K1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return V5(J,"text"),new K1("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 V5($,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 t1($){return typeof $==="object"&&$!==null&&$[F5]===!0}function lK($,Z,J={}){return K1.error($,Z,J)}function a0($){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 iK($){return"total"in $&&"partial"in $&&"body"in $}function U5(){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":N8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function sK($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(iK($))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 _8($,Z){if($ instanceof Response)return $;if(!$)return U5();let J=await sK($),{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 U5()}let{range:Q}=Z;if(Q){if(z<=0)return X3(Math.max(z,0));if(!X){if(W instanceof Blob){let K=T8(Q,z);if(!K)return X3(z);W=W.slice(K.start,K.end+1),Y=K.start,j=K.end,X=!0}}}let G=Boolean(Q)&&X,B=G?206:J.status,V=new Headers;if(V.set("Accept-Ranges","bytes"),V.set("Content-Type",J.type||"application/octet-stream"),V.set("X-Content-Type-Options","nosniff"),G)V.set("Content-Range",P8(Y,j,z)),V.set("Content-Length",String(j-Y+1));else if(z>=0)V.set("Content-Length",String(z));if(J.name)V.set("Content-Disposition",j6(J.name,J.download));if(J.etag)V.set("ETag",J.etag);if(J.lastModified)V.set("Last-Modified",J.lastModified.toUTCString());for(let[K,F]of Object.entries(J.extraHeaders))V.set(K,F);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:B,headers:V})}return new Response(W,{status:B,headers:V})}class BZ extends H0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var D5={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function G3($){if(typeof $==="number"){if(Number.isFinite($)&&$>=0)return Math.floor($);if($===1/0)return 1/0}else{let Z=$.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let J=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(J&&(J[2]===""||(J[2]in D5)))return Math.floor(Number(J[1])*(D5[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var Q3=new WeakMap;function L5($){return Q3.has($)}function M5($){return Q3.get($)?.limit??null}function H5($){let Z=Q3.get($);return Z?Z.read>Z.limit:!1}function nK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function x8($,Z){let J=nK($);if(J!==null&&J>Z)throw new BZ(Z)}function z6($,Z,J={}){let W=Q3.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};Q3.set($,Y),aK($,Y)}if(J.checkDeclared!==!1)x8($,Z)}function oK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function I8($,Z){if(Z.stream!==void 0)return Z.stream;let J=oK($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(Y){W??=J.getReader();let{done:j,value:z}=await W.read();if(j){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new BZ(Z.limit);Y.error(X),W.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return W?W.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function KZ($,Z){if(x8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=I8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:Q,value:G}=await W.read();if(Q)break;Y.push(G),j+=G.byteLength}let z=new Uint8Array(j),X=0;for(let Q of Y)z.set(Q,X),X+=Q.byteLength;return z}function O5($){return $.headers.get("Content-Type")??""}function aK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>I8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>KZ($,Z)}),J("arrayBuffer",{value:async()=>{let W=await KZ($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await KZ($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await KZ($,Z)))}),J("blob",{value:async()=>new Blob([await KZ($,Z)],{type:O5($)})}),J("formData",{value:async()=>new Response(await KZ($,Z),{headers:{"Content-Type":O5($)}}).formData()}),J("clone",{value:()=>{x8($,Z.limit);let W=I8($,Z),Y=null;if(W){let[j,z]=W.tee();Z.stream=j,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function rK($){return Y6($)}function T5($,Z){if($.length===0)return $();return $(Z??new C)}class o{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!rK(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 T5(Z[this.methodName].bind(Z),$)}return T5(this.handler,$)}middleware($){return this.middlewares=a0($),this}}class _5{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=a0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of N5($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(H5($.rawRequest))throw new BZ(M5($.rawRequest));throw J}}}class I5{constructor(...$){return new o(...$)}}class x5 extends o{__internal_brand="StreamHandler";async run($){let Z=T.getStore(),J=Z?.req?.rawRequest,W=C8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(t1(Y))return Y;return await _8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof A8)return X3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class C5{constructor(...$){return new x5(...$)}}class A5{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new o("GET",$,"list"),post:new o("POST",$,"store")},this.second={get:new o("GET",$,"show"),put:new o("PUT",$,"update"),delete:new o("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 C0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new o("GET",$,Z)}post($,Z){return new o("POST",$,Z)}put($,Z){return new o("PUT",$,Z)}patch($,Z){return new o("PATCH",$,Z)}delete($,Z){return new o("DELETE",$,Z)}resource($){return new A5($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${P5($)}.`);return tK($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${P5($)}.`);return eK($)}file($,Z){return new I5("GET",$,Z)}stream($,Z){return new C5("GET",$,Z)}proxy($,Z={}){return new _5($,Z)}}function P5($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function tK($){let Z={stream:new o("POST",$,"stream"),attach:new o("POST",$,"attach"),stop:new o("POST",$,"stop"),upload:new o("POST",$,"upload")};return class extends C0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/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);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function eK($){let Z={start:new o("POST",$,"voiceStart"),update:new o("PATCH",$,"voiceUpdate"),end:new o("DELETE",$,"voiceEnd")};return class extends C0{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 e1="access_token";function E$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function X6($,Z){let J=E$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var $B=/^[A-Za-z0-9_-]+$/,ZB=/^:[A-Za-z_][A-Za-z0-9_]*$/,S5=/^[A-Za-z0-9_-]{1,128}$/,JB=/^[A-Za-z0-9_.:-]+$/;class u extends Error{constructor($){super($);this.name="InvalidChannelError"}}function E5($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function VZ($){if(typeof $!=="string"||$.length===0)throw new u("A channel pattern must be a non-empty string.");if($.length>255)throw new u(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(ZB.test(W)){let Y=W.slice(1);if(J.has(Y))throw new u(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new u(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!$B.test(W))throw new u(`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 K3($,Z={}){let J=VZ($),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 u(`The channel "${$}" needs the param "${z}".`);let Q=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof Q!=="string"||!S5.test(Q))throw new u(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return Q}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new u(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new u(`The topic built from "${$}" is longer than 255 characters.`);return Y}function S8($){if(VZ($).some((J)=>J.startsWith(":")))throw new u(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function b5($){if(typeof $!=="string"||$.length===0||$.length>64||!JB.test($))throw new u(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function R5($,Z){if($===Z)return!0;if($===F0)return Z.startsWith(`${F0}.`)&&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(":")&&S5.test(W[j]))}var F0="user";function FZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return K3(`${F0}.:id`,{id:Z})}class J0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class Q6 extends J0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return z6(this.req.rawRequest,G3(Z)),{}}}function WB($){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}var YB={"body-limit":Q6};class $${config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:G3($.bodyLimit)}get aliases(){return{...YB,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!L5($))z6($,this.defaultBodyLimit,{checkDeclared:!1})}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 C,J=this.aliases,W=[];for(let[Y,j]of WB($).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:k5(z)})}}else if(Y6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:k5(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 jB(W.slice(j+1)),z}return Y})()}}function k5($){return $?.runsOnRefusal===!0}async function jB($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class G6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...a0($)],this}events(...$){return this}}class y5{static __brand="ChannelRouter";channels={};public(){return new G6("public")}private($){return new G6("private",$)}async authorize($,Z,J={},W={}){try{GB(this)}catch(Q){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",Q),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!v5(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===F0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=K3(Z,J??{})}catch(Q){if(Q instanceof u)return{ok:!1,code:"invalid_params"};throw Q}let z=Object.fromEntries(Object.entries(J??{}).map(([Q,G])=>[Q,String(G)])),X=new C($,z,"api",Z);return T.exit(()=>K6.exit(()=>T.run(X,async()=>{let Q=T.getStore();try{if(Y.middlewares.length>0)await M($$).runMiddleware(Y.middlewares);if(Z===F0){let G=await f5(X);if(!G)return{ok:!1,code:"denied"};if(j=FZ(G),Y.visibility==="private"&&Y.authorizer){if(await w5(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 w5(Y.authorizer,X,z):await f5(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(G){if(QB(G))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,G),{ok:!1,code:"error"}}finally{Q.destroy()}},W.carried)))}}async function zB($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;g5(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 v5($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function f5($){if(!T.getStore().user&&E$($)===null)return null;try{return await q0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function w5($,Z,J){if(XB($))return new $().authorize(Z,J);return $(Z,J)}function XB($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function QB($){return $?.kind===Z$||J$($)||b$($)}var q5=new WeakSet;function GB($){if(q5.has($))return;g5($),q5.add($)}function g5($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!v5(Y))throw new u(`The channel "${W}" is not declared with this.public() or this.private().`);let j=VZ(W);if(j[0].startsWith(":"))throw new u(`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!==F0&&j.length===2&&j[0]===F0)throw new u(`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!==F0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new u(`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===F0?[F0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(KB(J[W].segments,J[Y].segments))throw new u(`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 KB($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class E8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class B6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class b8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function BB($){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 VB($,Z){let J=BB($);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 m5{static __brand="McpRouter";routes={};scopes;param($){return new E8($.as,$.input,$.bind)}fromTool($,Z={}){return new b8($,Z)}fromApiRoute($,Z,J){return new B6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...Q}=J,G=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,B=Object.keys(Y??{});if(B.length===0)throw Error(`${G}: declare at least one audience.`);let V={},K=new Map;for(let F of B){let{name:D,casing:U,description:O,params:L,files:P,...H}=Y[F],I=D??(U?VB(W,U):W);if(K.has(I))throw Error(`${G}: the audiences "${K.get(I)}" and "${F}" are both named "${I}". Give one its own name or casing.`);K.set(I,F);let b=typeof O==="function"?j===void 0?void 0:O(j):O??j;if(typeof b!=="string")throw Error(`${G}: the audience "${F}" has no description, and there is no shared one.`);let S={...Q,...H,description:b};if(z||L)S.params={...z,...L};if(X||P)S.files={...X,...P};V[I]=new B6($,Z,S)}return V}}function U0($,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 R8 extends H0{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 S1{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 R8([U0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new R8($,Z)}}class h5{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 S1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=a0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function k8($,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[Q,G]of Object.entries($.headers??{}))Z.set(Q,G);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 p5{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=a0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function c5($,Z){if(t1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class d5{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=c5(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=a0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class u5{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends E1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends E1{routes=J??{}}}else this.children=class extends E1{routes=Z},this.handler=()=>({})}async run($,Z){let J=c5(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=a0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class E1{middlewares=[];featureGates=[];routes={};view($,Z){return new d5($,Z)}file($){return new p5($)}redirect($){return new h5($)}layout($,Z,J){return new u5($,Z,J)}}function FB($){return $}function UB(){return{aliases:{},global:[],bodyLimit:null}}var B1="redirect";function V1($,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 UZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function DB($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(M(c).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function OB($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function V6($,Z){let J=Z||M(E).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=DB($,!W);if(W||!OB(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(B1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class l5 extends J0{async run($){let Z=T.getStore(),J=Z.req;if(Z.user)return{};let W=await X6(M(E),J);if(!W)throw new R$({redirectTo:V6(J,$)});return Z.setUser(W),{}}}var w8="gemi_same_site",f8="private, no-cache, no-store, max-age=0, must-revalidate";class F6 extends J0{run(){let $=T.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(w8))return{};if(E$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(w8,"1"),new i5(`${W.pathname}${W.search}`)}}class i5 extends H0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=LB($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":f8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":f8}},viewData:{status:200,data:{},headers:{"Cache-Control":f8},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 LB($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class s5 extends J0{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 n5={"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 o5 extends J0{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={...n5,...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={...n5,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var MB="Rate limit exceeded";class Y$ extends H0{result;retryAfter;constructor($,Z=MB){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?q8($):{}};this.payload={api:{status:429,data:{error:{...W$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function q8($){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 F1{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(a5("window",W),a5("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 Y$(W,typeof J==="function"?J(W):J);return W}}function a5($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as y8}from"net";function k$($){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 y8(j)===6?j:null}if(y8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&y8(J[1])===4?J[1]:null}class $j extends J0{async run($,Z){let J=HB();if(!J)return{};let W=await J.consume(this.key(),{limit:r5($)??this.config.limit,window:r5(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(q8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new Y$(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=t5(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${DZ(this.req)}:${this.req.routePath??"*"}`}}function HB(){try{let $=M();return $.bound(F1)?$.make(F1):null}catch{return null}}function DZ($){let Z=e5($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return k$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function r5($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class Jj extends J0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new v8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new v8;return{}}}class v8 extends H0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:Zj("csrf","Invalid CSRF token",403)}},view:{}}}class Wj{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class Yj{all($,Z){return!0}}class g8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new OZ:new U6}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 C,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 J0{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 OZ:$ instanceof U6}}function TB($){return new g8($)}async function L6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await fB($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return kB(z,Z,J,$.url)}async function kB($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:G,value:B}=await Y.read();if(G)break;if(z+B.byteLength>Z){if(!J)throw new O6(W,Z);j.push(B.subarray(0,Z-z)),z=Z;break}j.push(B),z+=B.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),Q=0;for(let G of j)X.set(G,Q),Q+=G.byteLength;return X}async function fB($){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 M6($){return new TextDecoder("utf-8").decode($)}var wB={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function f$($){return $.replace(/[&<>"']/g,(Z)=>wB[Z])}var qB={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function m8($){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 qB[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 h8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function jj($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(m8($.slice(W)));return}if(Y>W)Z.text(m8($.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 Q=$.indexOf(">",X+1);if(Q===-1)return;W=Q+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(h8($.slice(Y+2,j).trim())),W=j+1}else{let j=yB($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let Q=z.search(/[\s]|$/),G=h8(z.slice(0,Q));if(G){if(Z.open(G,vB(z.slice(Q)),X),X)Z.close(G)}W=j+1}}}function yB($,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 vB($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[h8(W[1])]=m8(W[2]??W[3]??"");return Z}class z0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var Kj="http://www.sitemaps.org/schemas/sitemap/0.9",gB="http://www.w3.org/1999/xhtml",d8=`<?xml version="1.0" encoding="UTF-8"?>
2
+ import{qh as vK}from"./chunk-2qac05gb.js";import{Kh as yK}from"./chunk-3derdn99.js";import{$h as N5,Ci as O6,Ki as b1,Lh as V3,Oi as qQ,Ph as vG,Pi as YZ,Qh as t5,Qi as jZ,Rh as e5,Ri as DK,Sh as C8,Th as T8,Ti as OK,Wh as P8,Xh as N8,Yh as Z3,Zh as Z8,_h as hY,ai as d,gi as C,hi as i8,ii as OZ,ji as A8,ki as U6,mi as R$,ni as m,oi as n4,wi as D6}from"./chunk-zenfs4e2.js";import{Wi as Z$,Xi as H0,Yi as W$,Zi as Zj}from"./chunk-q6rse2fh.js";import{$i as cY,_i as ZZ,dj as gj,ej as J8,fj as T}from"./chunk-spmxhsze.js";import{ij as IQ,lj as n3}from"./chunk-7bz43qbt.js";import{pj as rj,sj as QK}from"./chunk-a1414jdv.js";import{Kj as b$,Pj as J$}from"./chunk-vhyabcw9.js";import{bk as jQ}from"./chunk-zyzhqnbm.js";import{ck as zZ,fk as zK}from"./chunk-vv8vjjez.js";import{gk as P1}from"./chunk-ecv4mtgh.js";import{hk as K6,ik as l0,jk as k1,kk as Q5,lk as qK,nk as iZ,ok as FK,xk as G5}from"./chunk-wtdmwmm7.js";import{Mk as f1}from"./chunk-7gnspwra.js";import{Rk as kY,Wk as fY}from"./chunk-yx03gndz.js";import{bl as RY,gl as c}from"./chunk-cf5a958j.js";import{hl as $3,kl as M}from"./chunk-nadkwh8a.js";import{sl as CY}from"./chunk-z2k8m02z.js";import{tl as LK}from"./chunk-m906xc76.js";import{Dl as PY}from"./chunk-rdnxkecg.js";import{El as K8,Gl as gG}from"./chunk-0ahecas6.js";import{Ll as W8}from"./chunk-mpreff3t.js";function Y6($){return typeof $==="function"&&$.prototype!==void 0}var F5=Symbol.for("gemi.HttpResponse"),uK=new Set([301,302,303,307,308]);class K1{kind;body;status;headers;[F5]=!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 V5(J,"json"),new K1("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 K1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!uK.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 K1("empty",void 0,J,Y)}static noContent($={}){return new K1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return V5(J,"text"),new K1("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 V5($,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 t1($){return typeof $==="object"&&$!==null&&$[F5]===!0}function lK($,Z,J={}){return K1.error($,Z,J)}function a0($){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 iK($){return"total"in $&&"partial"in $&&"body"in $}function U5(){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":N8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function sK($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(iK($))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 _8($,Z){if($ instanceof Response)return $;if(!$)return U5();let J=await sK($),{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 U5()}let{range:Q}=Z;if(Q){if(z<=0)return X3(Math.max(z,0));if(!X){if(W instanceof Blob){let K=T8(Q,z);if(!K)return X3(z);W=W.slice(K.start,K.end+1),Y=K.start,j=K.end,X=!0}}}let G=Boolean(Q)&&X,B=G?206:J.status,V=new Headers;if(V.set("Accept-Ranges","bytes"),V.set("Content-Type",J.type||"application/octet-stream"),V.set("X-Content-Type-Options","nosniff"),G)V.set("Content-Range",P8(Y,j,z)),V.set("Content-Length",String(j-Y+1));else if(z>=0)V.set("Content-Length",String(z));if(J.name)V.set("Content-Disposition",j6(J.name,J.download));if(J.etag)V.set("ETag",J.etag);if(J.lastModified)V.set("Last-Modified",J.lastModified.toUTCString());for(let[K,F]of Object.entries(J.extraHeaders))V.set(K,F);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:B,headers:V})}return new Response(W,{status:B,headers:V})}class BZ extends H0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var D5={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function G3($){if(typeof $==="number"){if(Number.isFinite($)&&$>=0)return Math.floor($);if($===1/0)return 1/0}else{let Z=$.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let J=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(J&&(J[2]===""||(J[2]in D5)))return Math.floor(Number(J[1])*(D5[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var Q3=new WeakMap;function L5($){return Q3.has($)}function M5($){return Q3.get($)?.limit??null}function H5($){let Z=Q3.get($);return Z?Z.read>Z.limit:!1}function nK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function x8($,Z){let J=nK($);if(J!==null&&J>Z)throw new BZ(Z)}function z6($,Z,J={}){let W=Q3.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};Q3.set($,Y),aK($,Y)}if(J.checkDeclared!==!1)x8($,Z)}function oK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function I8($,Z){if(Z.stream!==void 0)return Z.stream;let J=oK($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(Y){W??=J.getReader();let{done:j,value:z}=await W.read();if(j){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new BZ(Z.limit);Y.error(X),W.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return W?W.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function KZ($,Z){if(x8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=I8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:Q,value:G}=await W.read();if(Q)break;Y.push(G),j+=G.byteLength}let z=new Uint8Array(j),X=0;for(let Q of Y)z.set(Q,X),X+=Q.byteLength;return z}function O5($){return $.headers.get("Content-Type")??""}function aK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>I8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>KZ($,Z)}),J("arrayBuffer",{value:async()=>{let W=await KZ($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await KZ($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await KZ($,Z)))}),J("blob",{value:async()=>new Blob([await KZ($,Z)],{type:O5($)})}),J("formData",{value:async()=>new Response(await KZ($,Z),{headers:{"Content-Type":O5($)}}).formData()}),J("clone",{value:()=>{x8($,Z.limit);let W=I8($,Z),Y=null;if(W){let[j,z]=W.tee();Z.stream=j,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function rK($){return Y6($)}function T5($,Z){if($.length===0)return $();return $(Z??new C)}class o{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!rK(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 T5(Z[this.methodName].bind(Z),$)}return T5(this.handler,$)}middleware($){return this.middlewares=a0($),this}}class _5{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=a0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of N5($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(H5($.rawRequest))throw new BZ(M5($.rawRequest));throw J}}}class I5{constructor(...$){return new o(...$)}}class x5 extends o{__internal_brand="StreamHandler";async run($){let Z=T.getStore(),J=Z?.req?.rawRequest,W=C8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(t1(Y))return Y;return await _8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof A8)return X3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class C5{constructor(...$){return new x5(...$)}}class A5{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new o("GET",$,"list"),post:new o("POST",$,"store")},this.second={get:new o("GET",$,"show"),put:new o("PUT",$,"update"),delete:new o("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 C0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new o("GET",$,Z)}post($,Z){return new o("POST",$,Z)}put($,Z){return new o("PUT",$,Z)}patch($,Z){return new o("PATCH",$,Z)}delete($,Z){return new o("DELETE",$,Z)}resource($){return new A5($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${P5($)}.`);return tK($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${P5($)}.`);return eK($)}file($,Z){return new I5("GET",$,Z)}stream($,Z){return new C5("GET",$,Z)}proxy($,Z={}){return new _5($,Z)}}function P5($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function tK($){let Z={stream:new o("POST",$,"stream"),attach:new o("POST",$,"attach"),stop:new o("POST",$,"stop"),upload:new o("POST",$,"upload")};return class extends C0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/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);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function eK($){let Z={start:new o("POST",$,"voiceStart"),update:new o("PATCH",$,"voiceUpdate"),end:new o("DELETE",$,"voiceEnd")};return class extends C0{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 e1="access_token";function E$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function X6($,Z){let J=E$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var $B=/^[A-Za-z0-9_-]+$/,ZB=/^:[A-Za-z_][A-Za-z0-9_]*$/,S5=/^[A-Za-z0-9_-]{1,128}$/,JB=/^[A-Za-z0-9_.:-]+$/;class u extends Error{constructor($){super($);this.name="InvalidChannelError"}}function E5($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function VZ($){if(typeof $!=="string"||$.length===0)throw new u("A channel pattern must be a non-empty string.");if($.length>255)throw new u(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(ZB.test(W)){let Y=W.slice(1);if(J.has(Y))throw new u(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new u(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!$B.test(W))throw new u(`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 K3($,Z={}){let J=VZ($),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 u(`The channel "${$}" needs the param "${z}".`);let Q=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof Q!=="string"||!S5.test(Q))throw new u(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return Q}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new u(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new u(`The topic built from "${$}" is longer than 255 characters.`);return Y}function S8($){if(VZ($).some((J)=>J.startsWith(":")))throw new u(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function b5($){if(typeof $!=="string"||$.length===0||$.length>64||!JB.test($))throw new u(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function R5($,Z){if($===Z)return!0;if($===F0)return Z.startsWith(`${F0}.`)&&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(":")&&S5.test(W[j]))}var F0="user";function FZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return K3(`${F0}.:id`,{id:Z})}class J0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class Q6 extends J0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return z6(this.req.rawRequest,G3(Z)),{}}}function WB($){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}var YB={"body-limit":Q6};class $${config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:G3($.bodyLimit)}get aliases(){return{...YB,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!L5($))z6($,this.defaultBodyLimit,{checkDeclared:!1})}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 C,J=this.aliases,W=[];for(let[Y,j]of WB($).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:k5(z)})}}else if(Y6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:k5(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 jB(W.slice(j+1)),z}return Y})()}}function k5($){return $?.runsOnRefusal===!0}async function jB($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class G6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...a0($)],this}events(...$){return this}}class y5{static __brand="ChannelRouter";channels={};public(){return new G6("public")}private($){return new G6("private",$)}async authorize($,Z,J={},W={}){try{GB(this)}catch(Q){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",Q),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!v5(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===F0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=K3(Z,J??{})}catch(Q){if(Q instanceof u)return{ok:!1,code:"invalid_params"};throw Q}let z=Object.fromEntries(Object.entries(J??{}).map(([Q,G])=>[Q,String(G)])),X=new C($,z,"api",Z);return T.exit(()=>K6.exit(()=>T.run(X,async()=>{let Q=T.getStore();try{if(Y.middlewares.length>0)await M($$).runMiddleware(Y.middlewares);if(Z===F0){let G=await f5(X);if(!G)return{ok:!1,code:"denied"};if(j=FZ(G),Y.visibility==="private"&&Y.authorizer){if(await w5(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 w5(Y.authorizer,X,z):await f5(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(G){if(QB(G))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,G),{ok:!1,code:"error"}}finally{Q.destroy()}},W.carried)))}}async function zB($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;g5(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 v5($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function f5($){if(!T.getStore().user&&E$($)===null)return null;try{return await q0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function w5($,Z,J){if(XB($))return new $().authorize(Z,J);return $(Z,J)}function XB($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function QB($){return $?.kind===Z$||J$($)||b$($)}var q5=new WeakSet;function GB($){if(q5.has($))return;g5($),q5.add($)}function g5($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!v5(Y))throw new u(`The channel "${W}" is not declared with this.public() or this.private().`);let j=VZ(W);if(j[0].startsWith(":"))throw new u(`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!==F0&&j.length===2&&j[0]===F0)throw new u(`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!==F0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new u(`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===F0?[F0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(KB(J[W].segments,J[Y].segments))throw new u(`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 KB($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class E8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class B6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class b8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function BB($){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 VB($,Z){let J=BB($);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 m5{static __brand="McpRouter";routes={};scopes;param($){return new E8($.as,$.input,$.bind)}fromTool($,Z={}){return new b8($,Z)}fromApiRoute($,Z,J){return new B6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...Q}=J,G=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,B=Object.keys(Y??{});if(B.length===0)throw Error(`${G}: declare at least one audience.`);let V={},K=new Map;for(let F of B){let{name:D,casing:U,description:O,params:L,files:P,...H}=Y[F],I=D??(U?VB(W,U):W);if(K.has(I))throw Error(`${G}: the audiences "${K.get(I)}" and "${F}" are both named "${I}". Give one its own name or casing.`);K.set(I,F);let b=typeof O==="function"?j===void 0?void 0:O(j):O??j;if(typeof b!=="string")throw Error(`${G}: the audience "${F}" has no description, and there is no shared one.`);let S={...Q,...H,description:b};if(z||L)S.params={...z,...L};if(X||P)S.files={...X,...P};V[I]=new B6($,Z,S)}return V}}function U0($,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 R8 extends H0{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 S1{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 R8([U0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new R8($,Z)}}class h5{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 S1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=a0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function k8($,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[Q,G]of Object.entries($.headers??{}))Z.set(Q,G);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 p5{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=a0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function c5($,Z){if(t1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class d5{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=c5(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=a0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class u5{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends E1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends E1{routes=J??{}}}else this.children=class extends E1{routes=Z},this.handler=()=>({})}async run($,Z){let J=c5(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=a0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class E1{middlewares=[];featureGates=[];routes={};view($,Z){return new d5($,Z)}file($){return new p5($)}redirect($){return new h5($)}layout($,Z,J){return new u5($,Z,J)}}function FB($){return $}function UB(){return{aliases:{},global:[],bodyLimit:null}}var B1="redirect";function V1($,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 UZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function DB($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(M(c).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function OB($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function V6($,Z){let J=Z||M(E).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=DB($,!W);if(W||!OB(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(B1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class l5 extends J0{async run($){let Z=T.getStore(),J=Z.req;if(Z.user)return{};let W=await X6(M(E),J);if(!W)throw new R$({redirectTo:V6(J,$)});return Z.setUser(W),{}}}var w8="gemi_same_site",f8="private, no-cache, no-store, max-age=0, must-revalidate";class F6 extends J0{run(){let $=T.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(w8))return{};if(E$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(w8,"1"),new i5(`${W.pathname}${W.search}`)}}class i5 extends H0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=LB($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":f8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":f8}},viewData:{status:200,data:{},headers:{"Cache-Control":f8},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 LB($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class s5 extends J0{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 n5={"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 o5 extends J0{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={...n5,...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={...n5,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var MB="Rate limit exceeded";class Y$ extends H0{result;retryAfter;constructor($,Z=MB){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?q8($):{}};this.payload={api:{status:429,data:{error:{...W$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function q8($){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 F1{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(a5("window",W),a5("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 Y$(W,typeof J==="function"?J(W):J);return W}}function a5($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as y8}from"net";function k$($){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 y8(j)===6?j:null}if(y8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&y8(J[1])===4?J[1]:null}class $j extends J0{async run($,Z){let J=HB();if(!J)return{};let W=await J.consume(this.key(),{limit:r5($)??this.config.limit,window:r5(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(q8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new Y$(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=t5(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${DZ(this.req)}:${this.req.routePath??"*"}`}}function HB(){try{let $=M();return $.bound(F1)?$.make(F1):null}catch{return null}}function DZ($){let Z=e5($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return k$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function r5($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class Jj extends J0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new v8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new v8;return{}}}class v8 extends H0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:Zj("csrf","Invalid CSRF token",403)}},view:{}}}class Wj{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class Yj{all($,Z){return!0}}class g8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new OZ:new U6}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 C,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 J0{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 OZ:$ instanceof U6}}function TB($){return new g8($)}async function L6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await fB($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return kB(z,Z,J,$.url)}async function kB($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:G,value:B}=await Y.read();if(G)break;if(z+B.byteLength>Z){if(!J)throw new O6(W,Z);j.push(B.subarray(0,Z-z)),z=Z;break}j.push(B),z+=B.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),Q=0;for(let G of j)X.set(G,Q),Q+=G.byteLength;return X}async function fB($){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 M6($){return new TextDecoder("utf-8").decode($)}var wB={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function f$($){return $.replace(/[&<>"']/g,(Z)=>wB[Z])}var qB={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function m8($){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 qB[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 h8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function jj($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(m8($.slice(W)));return}if(Y>W)Z.text(m8($.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 Q=$.indexOf(">",X+1);if(Q===-1)return;W=Q+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(h8($.slice(Y+2,j).trim())),W=j+1}else{let j=yB($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let Q=z.search(/[\s]|$/),G=h8(z.slice(0,Q));if(G){if(Z.open(G,vB(z.slice(Q)),X),X)Z.close(G)}W=j+1}}}function yB($,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 vB($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[h8(W[1])]=m8(W[2]??W[3]??"");return Z}class z0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var Kj="http://www.sitemaps.org/schemas/sitemap/0.9",gB="http://www.w3.org/1999/xhtml",d8=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  `,zj=`<urlset xmlns="${Kj}" xmlns:xhtml="${gB}">
4
4
  `,Xj=`</urlset>
5
5
  `,w$=50000,B3=52428800,Qj=2048,mB=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),hB=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,pB="application/xml; charset=utf-8",Gj=new TextEncoder;function u8($,Z){let J;try{J=new URL($)}catch{throw new z0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new z0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>Qj)throw new z0(`Sitemap: ${Z} is over ${Qj} characters: "${W.slice(0,80)}\u2026".`);return W}function Bj($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new z0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!hB.test($))throw new z0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function cB($){let Z=u8($.loc,"loc"),J=`<url><loc>${f$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${f$(Bj($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!mB.has($.changefreq))throw new z0(`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 z0(`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 z0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=u8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${f$(Y)}" href="${f$(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((B)=>{if(X||B.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([B.path,B.variantKey,B.data])}
21
21
  `))});let G=setTimeout(()=>Q(!0),J);Z.allSettled().then(()=>Q(!1),()=>Q(!1))},cancel(){j(!1)}})}import{Fragment as OI,createContext as BO,createElement as LI,lazy as MI,use as HI,useContext as TI}from"react";import{createContext as YO}from"react";var jO=YO(null);import{createContext as QO,useContext as VI}from"react";import{useContext as XI}from"react";import{createContext as zO}from"react";import{jsx as YI}from"react/jsx-runtime";var XO=zO({});var GO="gemi.islandI18n",KO=globalThis[Symbol.for(GO)]??=QO(null);function LG($,Z={}){let J=new Set,W={islands:[],render:$,instances:new WeakMap,count:0,i18n:{},localeAware:Boolean(Z.currentLocale),i18nUsed:!1,dictionaries:[],sink:{use(Y,j,z){let X=`${Y} ${j}`;if(J.has(X))return;J.add(X),W.dictionaries.push([Y,j,z])},onUse(){}}};for(let Y of["currentLocale","defaultLocale","timeZone"])Object.defineProperty(W.i18n,Y,{enumerable:!0,get(){return W.i18nUsed=!0,Z[Y]}});return W}function MG($){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}:{}}}var r3="gemi-slot",HG="data-slot",TG="data-gemi-slot";var VO=Symbol.for("gemi.staticRender"),PG=globalThis[VO]??=BO(null);import{createHash as CG}from"crypto";var MY='var r=document,i=window,a=history;i.__gemi_nav?.d();var L=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:L.signal,...s}),q=i.__gemi_nav={d:()=>L.abort()},v=(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))},D=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},R=(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")v(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>v(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),v(n,s)});for(let m of n.children)l.observe(m)}}},O=\'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(O)?.content,C=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],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},y={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,N=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},Y=(t)=>{let e=r.body,n=t.body,s=D(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),R(e,s)},H=async(t,e)=>{let n=++b,s=!e&&y[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)||C(d)!=C(r))throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),Y(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)N(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(),y[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=y[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&&(y[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(O)?.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();R(r,D(r));_(!0);';import{createHash as FO}from"crypto";import{existsSync as _G,readFileSync as UO}from"fs";import{join as NY}from"path";var IG=".script",DO=[".ts",".js"],OO="document-scripts.json",xG="data-gemi-script",LO=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function MO($){if(typeof $!=="string"||!LO.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 HO($,Z){for(let J of DO){let W=NY($,"views",`${Z}${IG}${J}`);if(_G(W))return W}return null}async function NG($){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 TO($){return`'sha256-${FO("sha256").update($).digest("base64")}'`}var HY,TY=new Map;function PO(){if(HY===void 0){let $=NY(PY(),"dist","server",OO);HY=_G($)?JSON.parse(UO($,"utf8")):null}return HY??null}async function _Y($){MO($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=PO()?.[$];if(j!==void 0)return j;let z=TY.get($);if(z)return z}let J=NY(PY(),"app"),W=HO(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${IG}.ts (or .js).`);if(!Z)return NG(W);let Y=NG(W);return TY.set($,Y),Y.catch(()=>TY.delete($)),Y}async function EI($){return TO(await _Y($))}var NO="gemi-islands",_O="gemi-island-i18n",vI=`'sha256-${CG("sha256").update(CY).digest("base64")}'`;function IY($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var xY=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),gI=`'sha256-${CG("sha256").update(MY).digest("base64")}'`,IO='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',xO="gemi-static";function AG($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((U)=>{let O=U.module?J(U.module):void 0;if(!O)return console.error(`[gemi] island ${U.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(U.load==="eager"){for(let L of O.preload)z.add(L);if(U.preloadDynamic)for(let L of O.dynamicPreload??[])z.add(L)}return{s:O.src,e:U.export,l:U.load}});let Q=X.some((U)=>U!==null),G=j?`<script type="module" ${xG}="${xY(j.name)}">${j.source}</script>`:"";if(!Q&&!Y)return IY($,"</head>",G,!1);let V=(Y?`<meta name="${xO}" content="${xY(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((U)=>`<link rel="modulepreload" href="${xY(U)}"/>`).join("")+G,K=Y?MY:CY,F=Q?MG(Z):void 0,D=(Q?`<script type="application/json" id="${NO}">${r0({i:X})}</script>`:"")+(F?`<script type="application/json" id="${_O}">${r0(F)}</script>`:"")+`<script type="module">${W?IO+K:K}</script>`;return IY(IY($,"</head>",V,!1),"</body>",D,!0)}function CO($,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 SG($){let Z=`<template ${TG}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=CO($,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 Q=`<${r3} ${HG}="${j}" style="display:contents"></${r3}>`;$=$.split(Q).join(`<${r3} style="display:contents">${X}</${r3}>`)}return $}function AY($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function RG($,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 AO($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var EG=new Set,SO=new Set(["public","private","s-maxage","proxy-revalidate"]);function SY($,Z){let J=$.get("Cache-Control");if(!J||$.getSetCookie().length===0)return;if(!/(^|[\s,])(public|s-maxage)\b/i.test(J))return;let Y=["private",...J.split(",").map((j)=>j.trim()).filter((j)=>{let z=j.split("=")[0].trim().toLowerCase();return z!==""&&!SO.has(z)})].join(", ");if(Bun.env.NODE_ENV!=="production"&&!EG.has(Z)){EG.add(Z);let j=[...new Set($.getSetCookie().map((z)=>z.split("=")[0]))];console.warn(`[gemi] The view "${Z??""}" sets cookies (${j.join(", ")}) on a response with Cache-Control "${J}", so it was sent "${Y}" 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",Y)}var bG=new Set;function kG($,Z){if(!AO($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!bG.has(Z))bG.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 EO=async()=>(await import("./chunk-9brq77q6.js")).default,EY,t3=async(...$)=>{return EY??=import("react-dom/server.browser").catch((Z)=>{throw EY=void 0,Z}),(await EY).renderToReadableStream(...$)},wG=1e4,qG="no-locale",bO="no-theme";async function RO($,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 wY="/assets";function kO($){return $===wY||$.startsWith(`${wY}/`)}function fO($){let Z=$.filter(kO);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 "${wY}" 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 wO($){let Z=M(Q1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function bY($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function qO($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class e3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=UG();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;translate;constructor($,Z={}){let J=vQ();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.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":EQ(Z)};if(this.requiredViews=Object.fromEntries(AQ(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=a4(W),!this.assetRoutes)fO(Object.keys(this.flatViewRoutes));this.routeManifest=t4(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=$8(W),this.flatComponentTree=DY(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=M(j$);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)=>{YZ.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 Q=new Set(Z?.preload??[]);for(let G of W)for(let B of J?.[G]??[])Q.add(B);return[...Q].map((G)=>l1("link",{key:`modulepreload:${G}`,rel:"modulepreload",href:G}))};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}=$,Q;if(W.layout){if(Q=$.viewImportMap[W.layout],!Q)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 G=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let B=fY(),V=new AbortController,K=setTimeout(()=>V.abort(),wG),F=(U)=>{if(Bun.env.NODE_ENV!=="production")console.error(U)},D=LG(async(U,O)=>{let L=await t3(U,{signal:V.signal,identifierPrefix:O,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:F});return await L.allReady.catch(()=>{}),await new Response(L).text()},{currentLocale:j?.i18n?.currentLocale,defaultLocale:j?.i18n?.defaultLocale,timeZone:j?.i18n?.timeZone});try{let U,O=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(O)U={name:O,source:await _Y(O)};let L;if(W.navigation){let I=W.navigation===!0?{}:W.navigation,b=I.version?String(await J(()=>I.version(Z))):"";L={identity:[W.layout??"",$.buildId??"",U?.name??"",b].join("|"),prefetch:I.prefetch==="none"?"none":"intent"}}let P=await t3(l1(PG.Provider,{value:D,children:l1(fG,{children:[...G,l1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:B,rootLayout:Q,key:"root"})]})}),{signal:V.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:F});await P.allReady.catch(()=>{});let H=SG(await new Response(P).text());return new Response(AG(H,D,$.resolveIsland,Bun.env.NODE_ENV!=="production",L,U),{status:$.status,headers:X})}finally{clearTimeout(K),J(()=>this.completeStream(Z,z.summarize(V.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:Q,serverQueries:G,userAgent:B,noStream:V,noTheme:K,url:F,user:D,viewData:U,breadcrumbs:O,urlLocaleSegment:L,meta:P,isOgRequest:H,appId:I,features:b,staticView:S}=$,R=this.theme===!1||K||S?null:{cookie:this.theme.cookie??tW,default:this.theme.default??null,value:yO(Z,this.theme.cookie??tW)},f=L?VG(Q,[L]).pathname:Q,N={kind:"view",data:{meta:P,pageData:{[f]:U},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:D},routeManifest:this.clientRouteManifest,breadcrumbs:O,router:{urlLocaleSegment:L,pathname:Y,params:X,currentPath:Q,searchParams:F.search,is404:!Y?!0:!1,domain:Z.domain?wO(Z):null},appId:I,features:b,theme:R,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},v=this.root,_=this.routeManifest[Y];return async(k)=>{let{bootstrapModules:M0=[],loaders:Y3,getStyles:s1,viewImportMap:C1,cssManifest:i,ogMap:y,viewModules:r,clientEntry:A1,modulePreloadManifest:j3,assetBase:QZ,resolveIsland:o0,buildId:G1}=k,C$=A1?[]:M0,n1=(p)=>[p,`window.loaders=${Y3}`,...A1?[`import(${JSON.stringify(A1.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(H){let p=null,u0=null;for(let A of _??[])if(typeof y[A]==="function")u0=A,p=y[A];if(!p)return new Response("Not found",{status:404});let z3=Object.values(N.data.pageData)[0];try{await t3(l1(p,z3[u0]),{onError:()=>{}})}catch(A){let{fonts:e,...r1}=A.satoriOptions,J6=await Promise.all(e.map((W6)=>{return RO(W6.name,W6.weight,W6.style).then((dK)=>({...W6,data:dK}))})),B5=new Headers(j);B5.set("Content-Type","image/png");let[mK,hK]=await Promise.all([EO(),n4("Rendering an OG image")]),pK=await mK(A.jsx,{...r1,fonts:J6}),cK=await hK(Buffer.from(pK)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(cK),{headers:B5})}return new Response("data")}if(S&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:S,currentViews:_,data:N.data,serverQueries:G,headers:j,getStyles:s1,viewImportMap:C1,viewModules:r,resolveIsland:o0,buildId:G1,status:200});if(S&&!Y&&this.notFound){let p=this.notFound.view;if(!C1[p])throw Error(`The not-found view "${p}" (route.view.notFound) was not found. It is a view path: a file at app/views/${p}.tsx.`);return await this.renderStatic({req:Z,runInRequestScope:J,staticView:S,currentViews:[p],data:N.data,serverQueries:G,headers:j,getStyles:s1,viewImportMap:{...C1,"404":C1[p]},viewModules:r&&{...r,"404":r[p]},resolveIsland:o0,buildId:G1,status:$.refusedStatus??404})}if(N.data.cssManifest=i,N.data.modulePreloadManifest=j3??{},QZ&&QZ!=="/")N.data.assetBase=QZ;if(G1&&G1!=="dev")N.data.buildId=G1;let t=this.modulePreloadLinks({clientEntry:A1,modulePreloadManifest:j3,views:_??["404"],routeKey:Y??"404"}),H8=await s1(_??["404"]);N.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let A$=new AbortController,o1=setTimeout(()=>A$.abort(),wG),a1=I6(B)||V,GZ=Bun.env.NODE_ENV!=="production"&&!a1&&Y&&this.shellReporter.shouldObserve(Y)?DG():null,S$=fY();try{let p=await t3(l1(fG,{children:[...t,...H8,...R?[l1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:pQ(r0({cookie:R.cookie,default:R.default}))}})]:[],l1(v,{data:N.data,viewImportMap:C1,viewModules:r,serverQueries:G,dictionarySink:S$,key:"root"})]}),{bootstrapScriptContent:n1(`window.__GEMI_DATA__ = ${r0(N.data)}`),bootstrapModules:C$,signal:A$.signal,...a1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(u0){if(Bun.env.NODE_ENV!=="production")console.error(u0)}});if(p.allReady.catch(()=>{}).finally(()=>clearTimeout(o1)),a1)await p.allReady.catch(()=>{});return new Response(Y7(p,G,{onShell:a1?void 0:()=>G.markShell(),onChunk:GZ?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,G.summarize(A$.signal.aborted)),GZ)this.shellReporter.report(Y,GZ.measure())})},S$),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(p){if(clearTimeout(o1),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(A$.signal.aborted))),p;let u0=await t3(l1("div"),{bootstrapScriptContent:n1(`window.error= ${r0(p.message)}; window.stack_trace=${r0(p.stack)};window.__GEMI_DATA__ = ${r0(N.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...C$]:C$});return new Response(Y7(u0,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(A$.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(b$(Z))return 404;if(Z?.kind===Z$){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(J$(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof u1&&(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("/"),Q=j,G=null,B=null,V=M(c),K=o3(this.flatViewRoutes,j),F=V.isLocaleAware&&this.localeRouting==="prefix"&&!K?.route.middleware.includes(qG);if(F&&V.supportedLocales.includes(z))Q=`/${X.join("/")}`,G=z,B=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&K===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),k=F&&V.supportedLocales.includes(_.slice(1));if(_&&!k)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(F&&!Y&&B===null&&!(B===null&&K!==null)){let _=RY(z,V.supportedLocales,V.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(F&&!Y){let _=M(c).detectLocale(new C($,{},"view",Q));if(B===null&&_!==V.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}`}})}}Q=Q.replace("//","/");let U=[],O=[],L=null,P={},H=null,I=!1,b=!1,S=[],R,f=!1,N=!1;try{let _=o3(this.flatViewRoutes,Q);if(B&&_?.route.middleware.includes(qG))_=null;if(_){if(f=!0,L=_.routePath,P=_.params,U=_.route.exec,O=_.route.middleware,S=_.route.features,I=O.includes("no-stream"),b=O.includes(bO),R=_.route.static,N=_.route.segments.at(-1)?.viewPath==="FILE",W&&this.partialRendering){let k=$.headers.get(UY),M0=BG({flatViewRoutes:this.flatViewRoutes,supportedLocales:M(c).supportedLocales,from:k,origin:J.origin,to:{segments:_.route.segments,params:P,search:J.search}});if(M0.startIndex>0)U=U.slice(M0.startIndex),H={from:k,carriedViews:M0.carriedViews}}}}catch(_){throw _}if(R&&W)return new Response("Not found",{status:404});let v=new C($,P,"view",L);return this.hooks.onRequestStart(v),await T.run(v,async()=>{let _=null,k=T.getStore(),M0=$3.getStore(),Y3=(y)=>$3.run(M0,()=>T.runWith(k,y));k.serverQueries=new tZ(a3($));let s1=new Set;k.serverQueries.onQueryFail((y)=>{s1.add(y.error);try{Y3(()=>Promise.resolve(this.hooks.onRequestFail(i,y.error)).catch(()=>{}))}catch{}});let C1=AY(N?{}:R??(L===null&&!W?this.notFound?.static:void 0));if(B){let y=B.replaceAll("/","");x$.setLocale(y,{cookie:C1.locale})}else if(V.isLocaleAware&&!F)k.setLocale(V.defaultLocale);else x$.setLocale(void 0,{cookie:C1.locale});let i=k.req;if(C1.session)J8();try{let y=null;if(this.detectLocale&&!F&&M(c).isLocaleAware){let{supportedLocales:A,defaultLocale:e}=M(c),r1=await this.detectLocale(i,{supportedLocales:A,defaultLocale:e}),J6=typeof r1==="string"?RY(r1,A,e):null;if(J6)k.setLocale(J6)}try{await M($$).runMiddleware(O)}catch(A){if(y=this.viewRefusalStatus(i,A,s1),y===null)throw A}if(y!==null||S.length>0&&!await this.passesFeatureGates(S))L=null,U=[],i.routePath="";let r=M(c),A1=r.isEnabled,j3=r.isLocaleAware,QZ=new C($,i.params),o0={defaultLocale:r.defaultLocale,timeZone:r.detectTimeZone(QZ)};if(j3){let A=null;if(B)A=B.replaceAll("/",""),k.setLocale(A);else if(!F)A=k.locale??r.defaultLocale;else A=r.detectLocale(QZ),k.setLocale(A);let e=A1?r.getPageTranslations(A,i.routePath):{};o0={...o0,supportedLocales:r.supportedLocales,currentLocale:A,dictionary:{[A]:e},defaultLocale:r.defaultLocale,...F?{}:{localeRouting:"off"}}}await kY(o0.currentLocale??"");let G1;try{G1=await Promise.all(U.map((A)=>A(i)))}catch(A){if(y=this.viewRefusalStatus(i,A,s1),y===null)throw A;L=null,U=[],i.routePath="",G1=[]}let C$=void 0;if(L===null){if(C$=await this.hooks.onNotFound(i,{status:y??404}),j3&&!F&&k.locale&&k.locale!==o0.currentLocale){let A=k.locale;o0={...o0,currentLocale:A,dictionary:{[A]:A1?r.getPageTranslations(A,i.routePath):{}}},await kY(A)}}if(this.defaultMeta&&!k.metadata.hasAllDefaultFields)k.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(i):this.defaultMeta);if(this.translate!==void 0)k.metadata.applyTranslateDefault(this.translate);let{cookies:n1,headers:t}=k;if(y!==null)t.set("Cache-Control","no-store");_={data:G1,cookies:n1,headers:t,user:k.user,prefetchedData:k.serverQueries.snapshotResolved(),currentPathName:L,params:i.params,urlLocaleSegment:G,meta:k.renderMeta(),appId:M(OY).id,features:await M(j$).forClient()};let{params:H8,user:A$}=_,o1={},a1={};for(let A of G1??[]){let[e,r1]=Object.entries(A)?.[0]??[];if(!e||!r1)continue;a1[`${e}:${L}`]=r1.breadcrumb,o1[e]=r1}let GZ=L===null&&this.notFound&&!W?this.notFound.static:void 0;if(GZ&&C$)o1["404"]=C$;let S$=o1.FILE;if(S$){try{await this.onRequestEnd(i,{mintSession:!1})}catch(e){YZ.error(e?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(e)})}let A;if(S$ instanceof Response)A=Y8(S$,t,n1);else{for(let e of n1)t.append("Set-Cookie",e.toString());A=await k8(S$,t)}return kG(A,L)}if(W){t.set("Content-Type","application/x-ndjson; charset=utf-8"),t.append("Vary",UY),n1.forEach((e)=>t.append("Set-Cookie",e.toString())),SY(t,L),await this.hooks.onRequestEnd(i);let A={meta:H&&!k.metadata.touched?null:_.meta,data:{[Q]:o1},breadcrumbs:a1,prefetchedData:k.serverQueries.snapshotResolved(),i18n:o0,features:_.features,is404:!L,appId:_.appId,partial:H};return new Response(OG(A,k.serverQueries,void 0,({aborted:e})=>Y3(()=>this.completeStream(i,k.serverQueries.summarize(e)))),{headers:t})}t.set("Content-Type","text/html; charset=utf-8");let p=L?R:GZ,u0=Boolean(p),z3=AY(p);if(!I&&!u0)t.append("Vary","User-Agent");if(!u0||z3.session)J8();for(let A of n1)t.append("Set-Cookie",A.toString());if(!u0||z3.csrf){let A=Bun.CSRF.generate(process.env.SECRET);t.append("Set-Cookie",`csrf_token=${A}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(i,{mintSession:!u0||z3.session})}catch(A){YZ.error(A?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(A)})}if(u0&&(L||!f))RG(t,p);return SY(t,L),await this.render({req:i,runInRequestScope:Y3,csrfTokenHMAC:Buffer.from(""),currentPathName:L,headers:t,i18n:o0,params:H8,pathname:J.pathname,serverQueries:k.serverQueries,userAgent:$.headers.get("user-agent"),noStream:I,noTheme:b,url:J,user:A$,viewData:o1,breadcrumbs:a1,urlLocaleSegment:G,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:p,refusedStatus:y??void 0})}catch(y){if(y.kind===Z$){let r=W?qO(y.payload.viewData??y.payload.api):bY(y.payload.view);for(let A1 of k.cookies)r.headers.append("Set-Cookie",A1.toString());return r}if(!s1.has(y))this.hooks.onRequestFail(i,y);if(J$(y))return console.error(y),W?eZ():bY(LY());if(y instanceof u1&&y.status===403)return W?eZ():bY(LY());throw y}},Z)}}function yO($,Z){let J=$.cookies?.get(Z);return hQ(J)?J:null}function qY(){let $=JSON.stringify({error:W$("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 mG extends C0{routes={"/api-routes":this.get(()=>{let $=M(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 $=M(e3).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 vO=new Set([e1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),gO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,mO=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function hO($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(vO.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===e1)throw Error(`dispatchAs: credentials may not set the "${e1}" cookie. The access token stays the initiator's.`);if(!gO.test(Y)||!mO.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function pO($,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(Q){Y(),z.error(Q);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 yG($){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,Q]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,Q)}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 cO(){return Bun.env.NODE_ENV==="development"}class j8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=yQ();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=oW({"/":$.rootRouter,"/auth":dW,"/__gemi__/services/i18n":uW,"/__gemi__/services/image":sW,...cO()?{"/__gemi__/services/logs":nW,"/__gemi__/debug":mG}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=gG(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 M($$).runMiddleware(W)}catch(Y){if(Y.kind===Z$)return yG(Y.payload.api);else{if(b$(Y))return qY();if(this.onRequestFail(Z,Y),console.error(Y),J$(Y))return eZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=T.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===Z$)return yG(j.payload.api);if(b$(j))return qY();if(this.onRequestFail(J.req,j),console.error(j),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){YZ.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:W$("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await T.run(j,async()=>{let z=T.getStore(),X=!1,Q=async()=>{X=!0,await this.endRequest(z,j,W)};try{let G=M(c);if(G.isEnabled){let U=G.detectLocale(j);z.setLocale(U)}z.setRequest(j),M($$).applyDefaultBodyLimit($);let B=await this.runRouteMiddleware(W,j);if(B instanceof Response){let U=Y8(B,z.headers,z.cookies);return await Q(),U}let V=await this.getRouteData(W),K=z.headers,F=z.cookies;if(V instanceof Response){let U=Y8(V,K,F);if(this.isOpenEndedBody($,U)){let O=pO(U,()=>this.endRequest(z,j,W));return X=!0,O}return await Q(),U}let D=(t1(V)?V:K1.json(V)).toResponse(K,F);return await Q(),D}catch(G){if(!X)try{await Q()}catch(B){console.error(B)}throw G}},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 Q=Y?.identity;if(Q!==void 0&&(typeof Q!=="object"||!Q?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let G=new Headers,B=[],V=Q?null:$.cookies.get(e1);if(V)B.push(`${e1}=${V}`);if(Y?.credentials)hO(G,B,Y.credentials,Q!==void 0);if(B.length>0)G.set("Cookie",B.join("; "));let K=Q?null:$.headers.get(e1);if(K)G.set(e1,K);let F=$.headers.get("User-Agent");if(F)G.set("User-Agent",F);let D;if(W instanceof FormData)D=W;else if(W!==void 0)G.set("Content-Type","application/json"),D=JSON.stringify(W);let U=new Request(z,{method:Z,headers:G,body:D,...Y?.signal?{signal:Y.signal}:{}});if(vG(U,DZ($),Q?.grant,Y?.progress),$.domain)Z3(U,$.domain);let O=Q?{user:Q.user}:void 0;return T.exit(()=>K6.exit(()=>this.handleApiRequest(U,O)))}}import{timingSafeEqual as dO}from"crypto";var Q8="",gY="*",uO=60000,lO=1e4,z8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,X8=16,yY=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,vY="x-forwarded-host";function pG($){return $.startsWith(":")}function $6($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&dO(J,W)}function iO($){if(!$)return[];if($===!0)return[{header:vY,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:vY;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 sO($){if(!$||$===!0)return;if(!Array.isArray($)){hG($,"route.domains.trustProxy",vY);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.`);hG(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 hG($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!yY.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"||!yY.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"||!yY.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 _1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function nO($){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 cG($){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 oO($){let Z=_1($.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.`);sO($.trustProxy),cG($.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),pG(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 mY{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){oO($),this.root=_1($.root),this.devHosts=cG($.devHosts),this.hostTrusts=iO($.trustProxy);for(let Z of $.groups??[])if(pG(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??uO,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||$6($.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:k$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return _1(this.forwardedHost($))??_1(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&&_1(Y)?nO(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:gY,params:{},custom:!0};return null}async allows($,Z){let J=_1($);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:Q8,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>=lO)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=_1($);if(Z)this.cache.delete(Z)}}}var aO={kind:"none"};function QC($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return aO;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 GC($,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:k$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var dG=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,uG=16;function KC($){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(!dG.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!dG.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<uG)throw Error(`GEMI_PROXY_SECRET must be at least ${uG} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function lG($,Z){if(!$6($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:k$(J)}var rO="/__gemi__/domains/ask";class Q1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;staticFilesVary=!1;constructor($,Z){this.groups.set(Q8,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new mY(J);let W=(Y)=>({api:Y.api?new j8({...Z.api,...Y.api}):$.api,view:Y.view?new e3({...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(gY,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)hY($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?lG($.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)hY($,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!==rO)return null;if(!$6(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??Q8)}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 J3($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var iG=600000;function sG($,Z){return[T6($,Z),T6($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new G7){fj($.oauthProviders),this.config={...P1(wj($),$),emailCode:W7($.emailCode),passwordLimits:J7($.passwordLimits)},this.provider=Z}async oauthProvider($){return await TZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await oj(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=M().bound(Q1)?M(Q1).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"?M(Q1).resolver?.root:_1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??_1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!n8($))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=J3(J.expiresAt),j=J3(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=T.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/iG),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 G=T6($,j),B=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:G,userId:B,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=G}if(!z){for(let G of sG($,j))if((await this.userProvider.findSession({token:G,userAgent:Z}))?.user){z=G;break}}if(!z)return null;let Q=await this.getSession(z,Z);if(Q)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(Q.expiresAt)));return Q}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(n8($)||!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()/iG),W=sG($,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=T.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 C;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 C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new R$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=Nj(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:Sj(Z),Q=P6("link",$,j),G=P6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let B=Math.max(W,Y)*60000,K=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((F)=>J3(F.createdAt)+B>Date.now()&&F.pin!==G&&F.token!==Q);await this.userProvider.deleteMagicLinkTokensExcept($,K.map((F)=>F.id))}return await this.userProvider.createMagicLinkToken({email:$,token:Q,pin:G}),{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 HZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((G)=>J3(G.createdAt)+W*60000>Date.now());if(z.length===0)return HZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let G of z)if(!await Rj(G.id,J3(G.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 Q=null;for(let G of z)if(HZ("pin",$,G.pin,Z))Q??=G;if(!Q)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,Q.id))return{status:"invalid"};return{status:"ok",row:Q}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return HZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(HZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(J3(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class q0 extends m{static getFacadeAccessor(){return E}static async user(){let $=await q0.userOrNull();if($)return $;throw new R$({redirectTo:V6(T.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=T.getStore();if($?.user)return $.user;let Z=await X6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=T.getStore()?.req;return V1(Z?.search.get(B1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await q0.user();if(!await $(Z))throw new OZ}static async guardSafe($){let Z=await q0.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 G8{static ensure($,Z={}){let J=T.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new tZ(a3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=G8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){G8.ensure($,Z[0])}static noPrefetch(){let $=T.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new tZ(a3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function tO($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function pY($,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==="*"?tO(z):encodeURIComponent(String(z))}`});return`${K8}${J==="/"?"":J}`||K8}var nG=new Map;function oG($,Z){let J=nG.get($);if(!J)J=new URLPattern({pathname:`${K8}${$==="/"?"":$}`}),nG.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 aG($,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=eO(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 eO($){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 rG{static origin($){return cY($)}static absolute($,...Z){return`${ZZ()}${U0(String($),Z[0]??{})}`}static relative($,...Z){return U0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=M(Q1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=T.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):ZZ();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return aG({root:W.root,origin:j},$,U0(String(Z),J[0]??{}))}static api($,...Z){return pY(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${cY()}${pY(String($),Z[0]??{})}`}static matchApi($,Z){return oG(String($),Z)}}class tG{name="Meta";static description($){T.getStore().metadata.description($)}static title($){T.getStore().metadata.title($)}static openGraph($){T.getStore().metadata.openGraph($)}static htmlAttributes($){T.getStore().metadata.htmlAttributes($)}static canonical($){T.getStore().metadata.canonical($)}static alternates($){T.getStore().metadata.alternates($)}static tags($){T.getStore().metadata.tags($)}static robots($){T.getStore().metadata.robots($)}static translate($=!0){T.getStore().metadata.translate($)}static fonts($){T.getStore().metadata.fonts($)}}var $L={set($,Z,J){T.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(T.getStore().req.cookies.has($))return!1;return T.getStore().setCookie($,Z,J),!0},delete($,Z){T.getStore().deleteCookie($,Z)}};class i1 extends m{static getFacadeAccessor(){return jZ}static get client(){return this.getFacadeRoot().client}static get($){return i1.client.get($)}static set($,Z){return i1.client.set($,Z)}static del(...$){return i1.client.del(...$)}static exists($){return i1.client.exists($)}static incr($){return i1.client.incr($)}static expire($,Z){return i1.client.expire($,Z)}static ttl($){return i1.client.ttl($)}}function XA($){return $}function eG(){return{store:"memory",ttl:null}}class dY{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 ZL="500";class uY{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=`${JL(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",ZL]),[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 $=M(),Z=$.bound(jZ)?$.make(jZ).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 JL($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var WL="k:",$K="tag:",YL="t:";class lY{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 iY extends lY{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=P1(eG(),$),this.config.ttl!==null&&this.config.ttl!==void 0)zZ(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 JK(this,Z)}async flush(){await this.store.flush()}async storeKey($){return WL+WK($)}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=$K+Z,W=await this.store.get(J);if(W!==null)return W;let Y=ZK();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set($K+Z,ZK(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:zZ(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new dY(this.config.memory);if($==="redis"){let Z=this.options.application;return new uY({...this.config.redis,client:Z?{send:(J,W)=>Z.make(jZ).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 JK extends lY{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){WK($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${YL}${Z.join(",")}:${$}`}}function WK($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function ZK(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class YK extends m{static getFacadeAccessor(){return iY}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 jK extends m{static getFacadeAccessor(){return F1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class XK extends m{static getFacadeAccessor(){return zK}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class GK extends m{static getFacadeAccessor(){return QK}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class KK extends m{static getFacadeAccessor(){return n3}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 qA($){return $}function BK(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function B8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function sY($){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:jL}=globalThis.Bun;function zL(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var XL=async($)=>{let Z=new jL($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},QL=async($)=>{let Z;try{Z=(await import("./chunk-gprc53rf.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(()=>{})}},VK=($)=>zL()?XL($):QL($);var GL=/^[A-Za-z_][A-Za-z0-9_]*$/;class nY{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(!GL.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??VK}async createTable(){for(let $ of KL(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 FK(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 TO($){return`'sha256-${FO("sha256").update($).digest("base64")}'`}var HY,TY=new Map;function PO(){if(HY===void 0){let $=NY(PY(),"dist","server",OO);HY=_G($)?JSON.parse(UO($,"utf8")):null}return HY??null}async function _Y($){MO($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=PO()?.[$];if(j!==void 0)return j;let z=TY.get($);if(z)return z}let J=NY(PY(),"app"),W=HO(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${IG}.ts (or .js).`);if(!Z)return NG(W);let Y=NG(W);return TY.set($,Y),Y.catch(()=>TY.delete($)),Y}async function EI($){return TO(await _Y($))}var NO="gemi-islands",_O="gemi-island-i18n",vI=`'sha256-${CG("sha256").update(CY).digest("base64")}'`;function IY($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var xY=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),gI=`'sha256-${CG("sha256").update(MY).digest("base64")}'`,IO='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',xO="gemi-static";function AG($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((U)=>{let O=U.module?J(U.module):void 0;if(!O)return console.error(`[gemi] island ${U.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(U.load==="eager"){for(let L of O.preload)z.add(L);if(U.preloadDynamic)for(let L of O.dynamicPreload??[])z.add(L)}return{s:O.src,e:U.export,l:U.load}});let Q=X.some((U)=>U!==null),G=j?`<script type="module" ${xG}="${xY(j.name)}">${j.source}</script>`:"";if(!Q&&!Y)return IY($,"</head>",G,!1);let V=(Y?`<meta name="${xO}" content="${xY(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((U)=>`<link rel="modulepreload" href="${xY(U)}"/>`).join("")+G,K=Y?MY:CY,F=Q?MG(Z):void 0,D=(Q?`<script type="application/json" id="${NO}">${r0({i:X})}</script>`:"")+(F?`<script type="application/json" id="${_O}">${r0(F)}</script>`:"")+`<script type="module">${W?IO+K:K}</script>`;return IY(IY($,"</head>",V,!1),"</body>",D,!0)}function CO($,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 SG($){let Z=`<template ${TG}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=CO($,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 Q=`<${r3} ${HG}="${j}" style="display:contents"></${r3}>`;$=$.split(Q).join(`<${r3} style="display:contents">${X}</${r3}>`)}return $}function AY($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function RG($,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 AO($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var EG=new Set,SO=new Set(["public","private","s-maxage","proxy-revalidate"]);function SY($,Z){let J=$.get("Cache-Control");if(!J||$.getSetCookie().length===0)return;if(!/(^|[\s,])(public|s-maxage)\b/i.test(J))return;let Y=["private",...J.split(",").map((j)=>j.trim()).filter((j)=>{let z=j.split("=")[0].trim().toLowerCase();return z!==""&&!SO.has(z)})].join(", ");if(Bun.env.NODE_ENV!=="production"&&!EG.has(Z)){EG.add(Z);let j=[...new Set($.getSetCookie().map((z)=>z.split("=")[0]))];console.warn(`[gemi] The view "${Z??""}" sets cookies (${j.join(", ")}) on a response with Cache-Control "${J}", so it was sent "${Y}" 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",Y)}var bG=new Set;function kG($,Z){if(!AO($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!bG.has(Z))bG.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 EO=async()=>(await import("./chunk-hq710s2a.js")).default,EY,t3=async(...$)=>{return EY??=import("react-dom/server.browser").catch((Z)=>{throw EY=void 0,Z}),(await EY).renderToReadableStream(...$)},wG=1e4,qG="no-locale",bO="no-theme";async function RO($,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 wY="/assets";function kO($){return $===wY||$.startsWith(`${wY}/`)}function fO($){let Z=$.filter(kO);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 "${wY}" 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 wO($){let Z=M(Q1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function bY($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function qO($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class e3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=UG();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;translate;constructor($,Z={}){let J=vQ();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.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":EQ(Z)};if(this.requiredViews=Object.fromEntries(AQ(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=a4(W),!this.assetRoutes)fO(Object.keys(this.flatViewRoutes));this.routeManifest=t4(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=$8(W),this.flatComponentTree=DY(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=M(j$);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)=>{YZ.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 Q=new Set(Z?.preload??[]);for(let G of W)for(let B of J?.[G]??[])Q.add(B);return[...Q].map((G)=>l1("link",{key:`modulepreload:${G}`,rel:"modulepreload",href:G}))};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}=$,Q;if(W.layout){if(Q=$.viewImportMap[W.layout],!Q)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 G=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let B=fY(),V=new AbortController,K=setTimeout(()=>V.abort(),wG),F=(U)=>{if(Bun.env.NODE_ENV!=="production")console.error(U)},D=LG(async(U,O)=>{let L=await t3(U,{signal:V.signal,identifierPrefix:O,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:F});return await L.allReady.catch(()=>{}),await new Response(L).text()},{currentLocale:j?.i18n?.currentLocale,defaultLocale:j?.i18n?.defaultLocale,timeZone:j?.i18n?.timeZone});try{let U,O=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(O)U={name:O,source:await _Y(O)};let L;if(W.navigation){let I=W.navigation===!0?{}:W.navigation,b=I.version?String(await J(()=>I.version(Z))):"";L={identity:[W.layout??"",$.buildId??"",U?.name??"",b].join("|"),prefetch:I.prefetch==="none"?"none":"intent"}}let P=await t3(l1(PG.Provider,{value:D,children:l1(fG,{children:[...G,l1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:B,rootLayout:Q,key:"root"})]})}),{signal:V.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:F});await P.allReady.catch(()=>{});let H=SG(await new Response(P).text());return new Response(AG(H,D,$.resolveIsland,Bun.env.NODE_ENV!=="production",L,U),{status:$.status,headers:X})}finally{clearTimeout(K),J(()=>this.completeStream(Z,z.summarize(V.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:Q,serverQueries:G,userAgent:B,noStream:V,noTheme:K,url:F,user:D,viewData:U,breadcrumbs:O,urlLocaleSegment:L,meta:P,isOgRequest:H,appId:I,features:b,staticView:S}=$,R=this.theme===!1||K||S?null:{cookie:this.theme.cookie??tW,default:this.theme.default??null,value:yO(Z,this.theme.cookie??tW)},f=L?VG(Q,[L]).pathname:Q,N={kind:"view",data:{meta:P,pageData:{[f]:U},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:D},routeManifest:this.clientRouteManifest,breadcrumbs:O,router:{urlLocaleSegment:L,pathname:Y,params:X,currentPath:Q,searchParams:F.search,is404:!Y?!0:!1,domain:Z.domain?wO(Z):null},appId:I,features:b,theme:R,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},v=this.root,_=this.routeManifest[Y];return async(k)=>{let{bootstrapModules:M0=[],loaders:Y3,getStyles:s1,viewImportMap:C1,cssManifest:i,ogMap:y,viewModules:r,clientEntry:A1,modulePreloadManifest:j3,assetBase:QZ,resolveIsland:o0,buildId:G1}=k,C$=A1?[]:M0,n1=(p)=>[p,`window.loaders=${Y3}`,...A1?[`import(${JSON.stringify(A1.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(H){let p=null,u0=null;for(let A of _??[])if(typeof y[A]==="function")u0=A,p=y[A];if(!p)return new Response("Not found",{status:404});let z3=Object.values(N.data.pageData)[0];try{await t3(l1(p,z3[u0]),{onError:()=>{}})}catch(A){let{fonts:e,...r1}=A.satoriOptions,J6=await Promise.all(e.map((W6)=>{return RO(W6.name,W6.weight,W6.style).then((dK)=>({...W6,data:dK}))})),B5=new Headers(j);B5.set("Content-Type","image/png");let[mK,hK]=await Promise.all([EO(),n4("Rendering an OG image")]),pK=await mK(A.jsx,{...r1,fonts:J6}),cK=await hK(Buffer.from(pK)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(cK),{headers:B5})}return new Response("data")}if(S&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:S,currentViews:_,data:N.data,serverQueries:G,headers:j,getStyles:s1,viewImportMap:C1,viewModules:r,resolveIsland:o0,buildId:G1,status:200});if(S&&!Y&&this.notFound){let p=this.notFound.view;if(!C1[p])throw Error(`The not-found view "${p}" (route.view.notFound) was not found. It is a view path: a file at app/views/${p}.tsx.`);return await this.renderStatic({req:Z,runInRequestScope:J,staticView:S,currentViews:[p],data:N.data,serverQueries:G,headers:j,getStyles:s1,viewImportMap:{...C1,"404":C1[p]},viewModules:r&&{...r,"404":r[p]},resolveIsland:o0,buildId:G1,status:$.refusedStatus??404})}if(N.data.cssManifest=i,N.data.modulePreloadManifest=j3??{},QZ&&QZ!=="/")N.data.assetBase=QZ;if(G1&&G1!=="dev")N.data.buildId=G1;let t=this.modulePreloadLinks({clientEntry:A1,modulePreloadManifest:j3,views:_??["404"],routeKey:Y??"404"}),H8=await s1(_??["404"]);N.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let A$=new AbortController,o1=setTimeout(()=>A$.abort(),wG),a1=I6(B)||V,GZ=Bun.env.NODE_ENV!=="production"&&!a1&&Y&&this.shellReporter.shouldObserve(Y)?DG():null,S$=fY();try{let p=await t3(l1(fG,{children:[...t,...H8,...R?[l1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:pQ(r0({cookie:R.cookie,default:R.default}))}})]:[],l1(v,{data:N.data,viewImportMap:C1,viewModules:r,serverQueries:G,dictionarySink:S$,key:"root"})]}),{bootstrapScriptContent:n1(`window.__GEMI_DATA__ = ${r0(N.data)}`),bootstrapModules:C$,signal:A$.signal,...a1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(u0){if(Bun.env.NODE_ENV!=="production")console.error(u0)}});if(p.allReady.catch(()=>{}).finally(()=>clearTimeout(o1)),a1)await p.allReady.catch(()=>{});return new Response(Y7(p,G,{onShell:a1?void 0:()=>G.markShell(),onChunk:GZ?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,G.summarize(A$.signal.aborted)),GZ)this.shellReporter.report(Y,GZ.measure())})},S$),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(p){if(clearTimeout(o1),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(A$.signal.aborted))),p;let u0=await t3(l1("div"),{bootstrapScriptContent:n1(`window.error= ${r0(p.message)}; window.stack_trace=${r0(p.stack)};window.__GEMI_DATA__ = ${r0(N.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...C$]:C$});return new Response(Y7(u0,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(A$.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(b$(Z))return 404;if(Z?.kind===Z$){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(J$(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof u1&&(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("/"),Q=j,G=null,B=null,V=M(c),K=o3(this.flatViewRoutes,j),F=V.isLocaleAware&&this.localeRouting==="prefix"&&!K?.route.middleware.includes(qG);if(F&&V.supportedLocales.includes(z))Q=`/${X.join("/")}`,G=z,B=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&K===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),k=F&&V.supportedLocales.includes(_.slice(1));if(_&&!k)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(F&&!Y&&B===null&&!(B===null&&K!==null)){let _=RY(z,V.supportedLocales,V.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(F&&!Y){let _=M(c).detectLocale(new C($,{},"view",Q));if(B===null&&_!==V.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}`}})}}Q=Q.replace("//","/");let U=[],O=[],L=null,P={},H=null,I=!1,b=!1,S=[],R,f=!1,N=!1;try{let _=o3(this.flatViewRoutes,Q);if(B&&_?.route.middleware.includes(qG))_=null;if(_){if(f=!0,L=_.routePath,P=_.params,U=_.route.exec,O=_.route.middleware,S=_.route.features,I=O.includes("no-stream"),b=O.includes(bO),R=_.route.static,N=_.route.segments.at(-1)?.viewPath==="FILE",W&&this.partialRendering){let k=$.headers.get(UY),M0=BG({flatViewRoutes:this.flatViewRoutes,supportedLocales:M(c).supportedLocales,from:k,origin:J.origin,to:{segments:_.route.segments,params:P,search:J.search}});if(M0.startIndex>0)U=U.slice(M0.startIndex),H={from:k,carriedViews:M0.carriedViews}}}}catch(_){throw _}if(R&&W)return new Response("Not found",{status:404});let v=new C($,P,"view",L);return this.hooks.onRequestStart(v),await T.run(v,async()=>{let _=null,k=T.getStore(),M0=$3.getStore(),Y3=(y)=>$3.run(M0,()=>T.runWith(k,y));k.serverQueries=new tZ(a3($));let s1=new Set;k.serverQueries.onQueryFail((y)=>{s1.add(y.error);try{Y3(()=>Promise.resolve(this.hooks.onRequestFail(i,y.error)).catch(()=>{}))}catch{}});let C1=AY(N?{}:R??(L===null&&!W?this.notFound?.static:void 0));if(B){let y=B.replaceAll("/","");x$.setLocale(y,{cookie:C1.locale})}else if(V.isLocaleAware&&!F)k.setLocale(V.defaultLocale);else x$.setLocale(void 0,{cookie:C1.locale});let i=k.req;if(C1.session)J8();try{let y=null;if(this.detectLocale&&!F&&M(c).isLocaleAware){let{supportedLocales:A,defaultLocale:e}=M(c),r1=await this.detectLocale(i,{supportedLocales:A,defaultLocale:e}),J6=typeof r1==="string"?RY(r1,A,e):null;if(J6)k.setLocale(J6)}try{await M($$).runMiddleware(O)}catch(A){if(y=this.viewRefusalStatus(i,A,s1),y===null)throw A}if(y!==null||S.length>0&&!await this.passesFeatureGates(S))L=null,U=[],i.routePath="";let r=M(c),A1=r.isEnabled,j3=r.isLocaleAware,QZ=new C($,i.params),o0={defaultLocale:r.defaultLocale,timeZone:r.detectTimeZone(QZ)};if(j3){let A=null;if(B)A=B.replaceAll("/",""),k.setLocale(A);else if(!F)A=k.locale??r.defaultLocale;else A=r.detectLocale(QZ),k.setLocale(A);let e=A1?r.getPageTranslations(A,i.routePath):{};o0={...o0,supportedLocales:r.supportedLocales,currentLocale:A,dictionary:{[A]:e},defaultLocale:r.defaultLocale,...F?{}:{localeRouting:"off"}}}await kY(o0.currentLocale??"");let G1;try{G1=await Promise.all(U.map((A)=>A(i)))}catch(A){if(y=this.viewRefusalStatus(i,A,s1),y===null)throw A;L=null,U=[],i.routePath="",G1=[]}let C$=void 0;if(L===null){if(C$=await this.hooks.onNotFound(i,{status:y??404}),j3&&!F&&k.locale&&k.locale!==o0.currentLocale){let A=k.locale;o0={...o0,currentLocale:A,dictionary:{[A]:A1?r.getPageTranslations(A,i.routePath):{}}},await kY(A)}}if(this.defaultMeta&&!k.metadata.hasAllDefaultFields)k.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(i):this.defaultMeta);if(this.translate!==void 0)k.metadata.applyTranslateDefault(this.translate);let{cookies:n1,headers:t}=k;if(y!==null)t.set("Cache-Control","no-store");_={data:G1,cookies:n1,headers:t,user:k.user,prefetchedData:k.serverQueries.snapshotResolved(),currentPathName:L,params:i.params,urlLocaleSegment:G,meta:k.renderMeta(),appId:M(OY).id,features:await M(j$).forClient()};let{params:H8,user:A$}=_,o1={},a1={};for(let A of G1??[]){let[e,r1]=Object.entries(A)?.[0]??[];if(!e||!r1)continue;a1[`${e}:${L}`]=r1.breadcrumb,o1[e]=r1}let GZ=L===null&&this.notFound&&!W?this.notFound.static:void 0;if(GZ&&C$)o1["404"]=C$;let S$=o1.FILE;if(S$){try{await this.onRequestEnd(i,{mintSession:!1})}catch(e){YZ.error(e?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(e)})}let A;if(S$ instanceof Response)A=Y8(S$,t,n1);else{for(let e of n1)t.append("Set-Cookie",e.toString());A=await k8(S$,t)}return kG(A,L)}if(W){t.set("Content-Type","application/x-ndjson; charset=utf-8"),t.append("Vary",UY),n1.forEach((e)=>t.append("Set-Cookie",e.toString())),SY(t,L),await this.hooks.onRequestEnd(i);let A={meta:H&&!k.metadata.touched?null:_.meta,data:{[Q]:o1},breadcrumbs:a1,prefetchedData:k.serverQueries.snapshotResolved(),i18n:o0,features:_.features,is404:!L,appId:_.appId,partial:H};return new Response(OG(A,k.serverQueries,void 0,({aborted:e})=>Y3(()=>this.completeStream(i,k.serverQueries.summarize(e)))),{headers:t})}t.set("Content-Type","text/html; charset=utf-8");let p=L?R:GZ,u0=Boolean(p),z3=AY(p);if(!I&&!u0)t.append("Vary","User-Agent");if(!u0||z3.session)J8();for(let A of n1)t.append("Set-Cookie",A.toString());if(!u0||z3.csrf){let A=Bun.CSRF.generate(process.env.SECRET);t.append("Set-Cookie",`csrf_token=${A}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(i,{mintSession:!u0||z3.session})}catch(A){YZ.error(A?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(A)})}if(u0&&(L||!f))RG(t,p);return SY(t,L),await this.render({req:i,runInRequestScope:Y3,csrfTokenHMAC:Buffer.from(""),currentPathName:L,headers:t,i18n:o0,params:H8,pathname:J.pathname,serverQueries:k.serverQueries,userAgent:$.headers.get("user-agent"),noStream:I,noTheme:b,url:J,user:A$,viewData:o1,breadcrumbs:a1,urlLocaleSegment:G,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:p,refusedStatus:y??void 0})}catch(y){if(y.kind===Z$){let r=W?qO(y.payload.viewData??y.payload.api):bY(y.payload.view);for(let A1 of k.cookies)r.headers.append("Set-Cookie",A1.toString());return r}if(!s1.has(y))this.hooks.onRequestFail(i,y);if(J$(y))return console.error(y),W?eZ():bY(LY());if(y instanceof u1&&y.status===403)return W?eZ():bY(LY());throw y}},Z)}}function yO($,Z){let J=$.cookies?.get(Z);return hQ(J)?J:null}function qY(){let $=JSON.stringify({error:W$("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 mG extends C0{routes={"/api-routes":this.get(()=>{let $=M(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 $=M(e3).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 vO=new Set([e1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),gO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,mO=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function hO($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(vO.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===e1)throw Error(`dispatchAs: credentials may not set the "${e1}" cookie. The access token stays the initiator's.`);if(!gO.test(Y)||!mO.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function pO($,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(Q){Y(),z.error(Q);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 yG($){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,Q]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,Q)}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 cO(){return Bun.env.NODE_ENV==="development"}class j8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=yQ();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=oW({"/":$.rootRouter,"/auth":dW,"/__gemi__/services/i18n":uW,"/__gemi__/services/image":sW,...cO()?{"/__gemi__/services/logs":nW,"/__gemi__/debug":mG}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=gG(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 M($$).runMiddleware(W)}catch(Y){if(Y.kind===Z$)return yG(Y.payload.api);else{if(b$(Y))return qY();if(this.onRequestFail(Z,Y),console.error(Y),J$(Y))return eZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=T.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===Z$)return yG(j.payload.api);if(b$(j))return qY();if(this.onRequestFail(J.req,j),console.error(j),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){YZ.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:W$("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await T.run(j,async()=>{let z=T.getStore(),X=!1,Q=async()=>{X=!0,await this.endRequest(z,j,W)};try{let G=M(c);if(G.isEnabled){let U=G.detectLocale(j);z.setLocale(U)}z.setRequest(j),M($$).applyDefaultBodyLimit($);let B=await this.runRouteMiddleware(W,j);if(B instanceof Response){let U=Y8(B,z.headers,z.cookies);return await Q(),U}let V=await this.getRouteData(W),K=z.headers,F=z.cookies;if(V instanceof Response){let U=Y8(V,K,F);if(this.isOpenEndedBody($,U)){let O=pO(U,()=>this.endRequest(z,j,W));return X=!0,O}return await Q(),U}let D=(t1(V)?V:K1.json(V)).toResponse(K,F);return await Q(),D}catch(G){if(!X)try{await Q()}catch(B){console.error(B)}throw G}},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 Q=Y?.identity;if(Q!==void 0&&(typeof Q!=="object"||!Q?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let G=new Headers,B=[],V=Q?null:$.cookies.get(e1);if(V)B.push(`${e1}=${V}`);if(Y?.credentials)hO(G,B,Y.credentials,Q!==void 0);if(B.length>0)G.set("Cookie",B.join("; "));let K=Q?null:$.headers.get(e1);if(K)G.set(e1,K);let F=$.headers.get("User-Agent");if(F)G.set("User-Agent",F);let D;if(W instanceof FormData)D=W;else if(W!==void 0)G.set("Content-Type","application/json"),D=JSON.stringify(W);let U=new Request(z,{method:Z,headers:G,body:D,...Y?.signal?{signal:Y.signal}:{}});if(vG(U,DZ($),Q?.grant,Y?.progress),$.domain)Z3(U,$.domain);let O=Q?{user:Q.user}:void 0;return T.exit(()=>K6.exit(()=>this.handleApiRequest(U,O)))}}import{timingSafeEqual as dO}from"crypto";var Q8="",gY="*",uO=60000,lO=1e4,z8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,X8=16,yY=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,vY="x-forwarded-host";function pG($){return $.startsWith(":")}function $6($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&dO(J,W)}function iO($){if(!$)return[];if($===!0)return[{header:vY,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:vY;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 sO($){if(!$||$===!0)return;if(!Array.isArray($)){hG($,"route.domains.trustProxy",vY);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.`);hG(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 hG($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!yY.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"||!yY.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"||!yY.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 _1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function nO($){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 cG($){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 oO($){let Z=_1($.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.`);sO($.trustProxy),cG($.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),pG(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 mY{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){oO($),this.root=_1($.root),this.devHosts=cG($.devHosts),this.hostTrusts=iO($.trustProxy);for(let Z of $.groups??[])if(pG(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??uO,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||$6($.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:k$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return _1(this.forwardedHost($))??_1(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&&_1(Y)?nO(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:gY,params:{},custom:!0};return null}async allows($,Z){let J=_1($);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:Q8,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>=lO)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=_1($);if(Z)this.cache.delete(Z)}}}var aO={kind:"none"};function QC($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return aO;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 GC($,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:k$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var dG=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,uG=16;function KC($){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(!dG.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!dG.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<uG)throw Error(`GEMI_PROXY_SECRET must be at least ${uG} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function lG($,Z){if(!$6($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:k$(J)}var rO="/__gemi__/domains/ask";class Q1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;staticFilesVary=!1;constructor($,Z){this.groups.set(Q8,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new mY(J);let W=(Y)=>({api:Y.api?new j8({...Z.api,...Y.api}):$.api,view:Y.view?new e3({...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(gY,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)hY($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?lG($.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)hY($,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!==rO)return null;if(!$6(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??Q8)}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 J3($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var iG=600000;function sG($,Z){return[T6($,Z),T6($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new G7){fj($.oauthProviders),this.config={...P1(wj($),$),emailCode:W7($.emailCode),passwordLimits:J7($.passwordLimits)},this.provider=Z}async oauthProvider($){return await TZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await oj(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=M().bound(Q1)?M(Q1).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"?M(Q1).resolver?.root:_1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??_1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!n8($))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=J3(J.expiresAt),j=J3(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=T.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/iG),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 G=T6($,j),B=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:G,userId:B,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=G}if(!z){for(let G of sG($,j))if((await this.userProvider.findSession({token:G,userAgent:Z}))?.user){z=G;break}}if(!z)return null;let Q=await this.getSession(z,Z);if(Q)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(Q.expiresAt)));return Q}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(n8($)||!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()/iG),W=sG($,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=T.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 C;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 C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new R$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=Nj(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:Sj(Z),Q=P6("link",$,j),G=P6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let B=Math.max(W,Y)*60000,K=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((F)=>J3(F.createdAt)+B>Date.now()&&F.pin!==G&&F.token!==Q);await this.userProvider.deleteMagicLinkTokensExcept($,K.map((F)=>F.id))}return await this.userProvider.createMagicLinkToken({email:$,token:Q,pin:G}),{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 HZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((G)=>J3(G.createdAt)+W*60000>Date.now());if(z.length===0)return HZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let G of z)if(!await Rj(G.id,J3(G.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 Q=null;for(let G of z)if(HZ("pin",$,G.pin,Z))Q??=G;if(!Q)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,Q.id))return{status:"invalid"};return{status:"ok",row:Q}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return HZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(HZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(J3(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class q0 extends m{static getFacadeAccessor(){return E}static async user(){let $=await q0.userOrNull();if($)return $;throw new R$({redirectTo:V6(T.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=T.getStore();if($?.user)return $.user;let Z=await X6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=T.getStore()?.req;return V1(Z?.search.get(B1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await q0.user();if(!await $(Z))throw new OZ}static async guardSafe($){let Z=await q0.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 G8{static ensure($,Z={}){let J=T.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new tZ(a3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=G8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){G8.ensure($,Z[0])}static noPrefetch(){let $=T.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new tZ(a3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function tO($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function pY($,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==="*"?tO(z):encodeURIComponent(String(z))}`});return`${K8}${J==="/"?"":J}`||K8}var nG=new Map;function oG($,Z){let J=nG.get($);if(!J)J=new URLPattern({pathname:`${K8}${$==="/"?"":$}`}),nG.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 aG($,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=eO(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 eO($){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 rG{static origin($){return cY($)}static absolute($,...Z){return`${ZZ()}${U0(String($),Z[0]??{})}`}static relative($,...Z){return U0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=M(Q1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=T.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):ZZ();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return aG({root:W.root,origin:j},$,U0(String(Z),J[0]??{}))}static api($,...Z){return pY(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${cY()}${pY(String($),Z[0]??{})}`}static matchApi($,Z){return oG(String($),Z)}}class tG{name="Meta";static description($){T.getStore().metadata.description($)}static title($){T.getStore().metadata.title($)}static openGraph($){T.getStore().metadata.openGraph($)}static htmlAttributes($){T.getStore().metadata.htmlAttributes($)}static canonical($){T.getStore().metadata.canonical($)}static alternates($){T.getStore().metadata.alternates($)}static tags($){T.getStore().metadata.tags($)}static robots($){T.getStore().metadata.robots($)}static translate($=!0){T.getStore().metadata.translate($)}static fonts($){T.getStore().metadata.fonts($)}}var $L={set($,Z,J){T.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(T.getStore().req.cookies.has($))return!1;return T.getStore().setCookie($,Z,J),!0},delete($,Z){T.getStore().deleteCookie($,Z)}};class i1 extends m{static getFacadeAccessor(){return jZ}static get client(){return this.getFacadeRoot().client}static get($){return i1.client.get($)}static set($,Z){return i1.client.set($,Z)}static del(...$){return i1.client.del(...$)}static exists($){return i1.client.exists($)}static incr($){return i1.client.incr($)}static expire($,Z){return i1.client.expire($,Z)}static ttl($){return i1.client.ttl($)}}function XA($){return $}function eG(){return{store:"memory",ttl:null}}class dY{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 ZL="500";class uY{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=`${JL(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",ZL]),[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 $=M(),Z=$.bound(jZ)?$.make(jZ).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 JL($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var WL="k:",$K="tag:",YL="t:";class lY{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 iY extends lY{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=P1(eG(),$),this.config.ttl!==null&&this.config.ttl!==void 0)zZ(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 JK(this,Z)}async flush(){await this.store.flush()}async storeKey($){return WL+WK($)}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=$K+Z,W=await this.store.get(J);if(W!==null)return W;let Y=ZK();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set($K+Z,ZK(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:zZ(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new dY(this.config.memory);if($==="redis"){let Z=this.options.application;return new uY({...this.config.redis,client:Z?{send:(J,W)=>Z.make(jZ).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 JK extends lY{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){WK($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${YL}${Z.join(",")}:${$}`}}function WK($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function ZK(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class YK extends m{static getFacadeAccessor(){return iY}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 jK extends m{static getFacadeAccessor(){return F1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class XK extends m{static getFacadeAccessor(){return zK}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class GK extends m{static getFacadeAccessor(){return QK}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class KK extends m{static getFacadeAccessor(){return n3}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 qA($){return $}function BK(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function B8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function sY($){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:jL}=globalThis.Bun;function zL(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var XL=async($)=>{let Z=new jL($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},QL=async($)=>{let Z;try{Z=(await import("./chunk-gtdf51jz.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(()=>{})}},VK=($)=>zL()?XL($):QL($);var GL=/^[A-Za-z_][A-Za-z0-9_]*$/;class nY{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(!GL.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??VK}async createTable(){for(let $ of KL(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 FK(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 SK=191,EK=30000;class O8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class L8 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 X5{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=P1(xK(),$),this.store=ML(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(W3);return this.ownFeed??=new W3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){kK("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;kK("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:zZ($.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 LL(Z),this.change($,I1,{status:"running",progress:Z})}complete($,Z){return this.change($,I1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,I1,{status:"failed",error:RK(Z)})}cancel($,Z){return this.change($,I1,{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 O8($);if(x1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(Q)=>{if(Y.signal.aborted)return;await this.progress($,Q)}},X;try{let Q=await Z(z);X=await this.complete($,Q)}catch(Q){if(!(Q instanceof L8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,Q);X=await this.change($,I1,{status:"failed",error:Q instanceof L8?RK(Q):{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()+zZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new O8($);let z=null;for(;;){if(x1(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 Q=W-Date.now();if(Q<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await bK(z,Math.min(Q,X??1/0,EK),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 O8($);if(yield W,x1(W.status))return;for await(let Y of J){let j=OL(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,x1(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=zZ($);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||x1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,I1,{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(x1(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,bK(j,Math.min(z??1/0,EK))]);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 bK($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>Q(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},Q=(G)=>{X(),W(G)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>Q(!0),()=>Q(!0))})}function OL($,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 RK($){if(typeof $==="string")return{message:$};if($ instanceof L8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function kK($,Z){if(typeof Z!=="string"||Z===""||Z.length>SK)throw TypeError(`A run's ${$} is a string of 1 to ${SK} characters; got ${JSON.stringify(Z)}.`)}function LL($){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 ML($,Z){if($==="memory")return new J5;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(f1).connection();return new z5(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 fK extends m{static getFacadeAccessor(){return X5}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 wK extends m{static getFacadeAccessor(){return j$}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 K5{value;constructor($){this.value=$}}var HL=/^[A-Za-z_][A-Za-z0-9_$]*$/;function TL($){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"||!HL.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 M8{bound;constructor($){this.bound=$}get name(){return this.bound??k1()}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 G5(J.sql,(W)=>Q5(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=TL(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(l0()!==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 G5(z.sql,async(X)=>{for(let G of Y)await X.unsafe(G);let Q=await Q5(j,()=>W(X));throw new K5(Q)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j})}catch(X){if(X instanceof K5)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-k6x35rn5.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=vK($,yK(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=l0();if($===void 0)return;return k1()===this.name?$:void 0}connection($=this.name){return qK($),M(f1).connection($)}}var XZ=new M8;class gK extends m{static getFacadeAccessor(){return f1}static connection($){return new M8($)}static get sql(){return XZ.sql}static get dialect(){return XZ.dialect}static query($){return XZ.query($)}static execute($){return XZ.execute($)}static transaction($){return XZ.transaction($)}static readOnly($,Z){return XZ.readOnly($,Z)}static schema(){return XZ.schema()}static close(){return this.getFacadeRoot().close()}}export{K1 as ke,lK as le,a0 as me,X3 as ne,_8 as oe,BZ as pe,G3 as qe,C0 as re,X6 as se,s8 as te,n8 as ue,Nj as ve,Y$ as we,F1 as xe,k$ as ye,J0 as ze,$j as Ae,DZ as Be,_j as Ce,Ij as De,a8 as Ee,r8 as Fe,P6 as Ge,HZ as He,zV as Ie,mT as Je,wj as Ke,pj as Le,j7 as Me,cj as Ne,dj as Oe,UV as Pe,uj as Qe,z7 as Re,LV as Se,MV as Te,X7 as Ue,lj as Ve,ij as We,j$ as Xe,sj as Ye,NV as Ze,G7 as _e,w8 as $e,F6 as af,S1 as bf,k8 as cf,E1 as df,x$ as ef,G8 as ff,rG as gf,tG as hf,$L as if,i1 as jf,XA as kf,eG as lf,dY as mf,uY as nf,iY as of,JK as pf,YK as qf,jK as rf,XK as sf,GK as tf,KK as uf,qA as vf,BK as wf,B8 as xf,sY as yf,nY as zf,oY as Af,V8 as Bf,W3 as Cf,NK as Df,_K as Ef,u as Ff,K3 as Gf,g4 as Hf,IP as If,xP as Jf,CP as Kf,bP as Lf,$Q as Mf,qW as Nf,WQ as Of,qP as Pf,zQ as Qf,c0 as Rf,u3 as Sf,XQ as Tf,IK as Uf,US as Vf,Z5 as Wf,I1 as Xf,x1 as Yf,J5 as Zf,z5 as _f,DL as $f,O8 as ag,L8 as bg,X5 as cg,fK as dg,wK as eg,M8 as fg,gK as gg,vW as hg,HD as ig,lW as jg,iW as kg,sN as lg,bQ as mg,wQ as ng,Q6 as og,$$ as pg,Q_ as qg,yQ as rg,vQ as sg,OY as tg,eZ as ug,LY as vg,EI as wg,vI as xg,gI as yg,AO as zg,SY as Ag,wY as Bg,kO as Cg,bY as Dg,qO as Eg,e3 as Fg,qY as Gg,yG as Hg,Y8 as Ig,j8 as Jg,QC as Kg,GC as Lg,KC as Mg,Q1 as Ng,E as Og,q0 as Pg,G6 as Qg,y5 as Rg,zB as Sg,f5 as Tg,g5 as Ug,E8 as Vg,B6 as Wg,b8 as Xg,m5 as Yg,FB as Zg,UB as _g,l5 as $g,s5 as ah,o5 as bh,Jj as ch,Wj as dh,Yj as eh,g8 as fh,TB as gh,z0 as hh,Dj as ih,LZ as jh,Tj as kh};
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 SK=191,EK=30000;class O8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class L8 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 X5{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=P1(xK(),$),this.store=ML(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(W3);return this.ownFeed??=new W3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){kK("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;kK("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:zZ($.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 LL(Z),this.change($,I1,{status:"running",progress:Z})}complete($,Z){return this.change($,I1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,I1,{status:"failed",error:RK(Z)})}cancel($,Z){return this.change($,I1,{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 O8($);if(x1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(Q)=>{if(Y.signal.aborted)return;await this.progress($,Q)}},X;try{let Q=await Z(z);X=await this.complete($,Q)}catch(Q){if(!(Q instanceof L8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,Q);X=await this.change($,I1,{status:"failed",error:Q instanceof L8?RK(Q):{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()+zZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new O8($);let z=null;for(;;){if(x1(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 Q=W-Date.now();if(Q<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await bK(z,Math.min(Q,X??1/0,EK),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 O8($);if(yield W,x1(W.status))return;for await(let Y of J){let j=OL(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,x1(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=zZ($);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||x1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,I1,{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(x1(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,bK(j,Math.min(z??1/0,EK))]);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 bK($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>Q(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},Q=(G)=>{X(),W(G)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>Q(!0),()=>Q(!0))})}function OL($,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 RK($){if(typeof $==="string")return{message:$};if($ instanceof L8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function kK($,Z){if(typeof Z!=="string"||Z===""||Z.length>SK)throw TypeError(`A run's ${$} is a string of 1 to ${SK} characters; got ${JSON.stringify(Z)}.`)}function LL($){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 ML($,Z){if($==="memory")return new J5;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(f1).connection();return new z5(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 fK extends m{static getFacadeAccessor(){return X5}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 wK extends m{static getFacadeAccessor(){return j$}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 K5{value;constructor($){this.value=$}}var HL=/^[A-Za-z_][A-Za-z0-9_$]*$/;function TL($){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"||!HL.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 M8{bound;constructor($){this.bound=$}get name(){return this.bound??k1()}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 G5(J.sql,(W)=>Q5(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=TL(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(l0()!==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 G5(z.sql,async(X)=>{for(let G of Y)await X.unsafe(G);let Q=await Q5(j,()=>W(X));throw new K5(Q)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j})}catch(X){if(X instanceof K5)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-2rpz1p8g.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=vK($,yK(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=l0();if($===void 0)return;return k1()===this.name?$:void 0}connection($=this.name){return qK($),M(f1).connection($)}}var XZ=new M8;class gK extends m{static getFacadeAccessor(){return f1}static connection($){return new M8($)}static get sql(){return XZ.sql}static get dialect(){return XZ.dialect}static query($){return XZ.query($)}static execute($){return XZ.execute($)}static transaction($){return XZ.transaction($)}static readOnly($,Z){return XZ.readOnly($,Z)}static schema(){return XZ.schema()}static close(){return this.getFacadeRoot().close()}}export{K1 as le,lK as me,a0 as ne,X3 as oe,_8 as pe,BZ as qe,G3 as re,C0 as se,X6 as te,s8 as ue,n8 as ve,Nj as we,Y$ as xe,F1 as ye,k$ as ze,J0 as Ae,$j as Be,DZ as Ce,_j as De,Ij as Ee,a8 as Fe,r8 as Ge,P6 as He,HZ as Ie,zV as Je,mT as Ke,wj as Le,pj as Me,j7 as Ne,cj as Oe,dj as Pe,UV as Qe,uj as Re,z7 as Se,LV as Te,MV as Ue,X7 as Ve,lj as We,ij as Xe,j$ as Ye,sj as Ze,NV as _e,G7 as $e,w8 as af,F6 as bf,S1 as cf,k8 as df,E1 as ef,x$ as ff,G8 as gf,rG as hf,tG as if,$L as jf,i1 as kf,XA as lf,eG as mf,dY as nf,uY as of,iY as pf,JK as qf,YK as rf,jK as sf,XK as tf,GK as uf,KK as vf,qA as wf,BK as xf,B8 as yf,sY as zf,nY as Af,oY as Bf,V8 as Cf,W3 as Df,NK as Ef,_K as Ff,u as Gf,K3 as Hf,g4 as If,IP as Jf,xP as Kf,CP as Lf,bP as Mf,$Q as Nf,qW as Of,WQ as Pf,qP as Qf,zQ as Rf,c0 as Sf,u3 as Tf,XQ as Uf,IK as Vf,US as Wf,Z5 as Xf,I1 as Yf,x1 as Zf,J5 as _f,z5 as $f,DL as ag,O8 as bg,L8 as cg,X5 as dg,fK as eg,wK as fg,M8 as gg,gK as hg,vW as ig,HD as jg,lW as kg,iW as lg,sN as mg,bQ as ng,wQ as og,Q6 as pg,$$ as qg,Q_ as rg,yQ as sg,vQ as tg,OY as ug,eZ as vg,LY as wg,EI as xg,vI as yg,gI as zg,AO as Ag,SY as Bg,wY as Cg,kO as Dg,bY as Eg,qO as Fg,e3 as Gg,qY as Hg,yG as Ig,Y8 as Jg,j8 as Kg,QC as Lg,GC as Mg,KC as Ng,Q1 as Og,E as Pg,q0 as Qg,G6 as Rg,y5 as Sg,zB as Tg,f5 as Ug,g5 as Vg,E8 as Wg,B6 as Xg,b8 as Yg,m5 as Zg,FB as _g,UB as $g,l5 as ah,s5 as bh,o5 as ch,Jj as dh,Wj as eh,Yj as fh,g8 as gh,TB as hh,z0 as ih,Dj as jh,LZ as kh,Tj as lh};
116
116
 
117
- //# debugId=CA4EDF318109CD9864756E2164756E21
117
+ //# debugId=64E86E6AAAB8784064756E2164756E21