gemi 0.113.0 → 0.114.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 (226) hide show
  1. package/dist/ai/index.js +32 -32
  2. package/dist/ai/index.js.map +3 -5
  3. package/dist/app/App.d.ts.map +1 -1
  4. package/dist/app/index.js +1 -1
  5. package/dist/bin/gemi.js +8 -1
  6. package/dist/bin/gemi.js.map +3 -3
  7. package/dist/bun/plugin.js +1 -1
  8. package/dist/bun/preload.js +1 -1
  9. package/dist/chunk-0n9vs1ad.js +14 -0
  10. package/dist/{chunk-cqnfp0n9.js.map → chunk-0n9vs1ad.js.map} +4 -4
  11. package/dist/{chunk-68s1f5d5.js → chunk-1f9sqht5.js} +2 -2
  12. package/dist/{chunk-68s1f5d5.js.map → chunk-1f9sqht5.js.map} +1 -1
  13. package/dist/{chunk-qt8nvpqp.js → chunk-1p0dazvk.js} +2 -2
  14. package/dist/{chunk-qt8nvpqp.js.map → chunk-1p0dazvk.js.map} +1 -1
  15. package/dist/{chunk-3f1kq32g.js → chunk-2rphhsr7.js} +2 -2
  16. package/dist/{chunk-3f1kq32g.js.map → chunk-2rphhsr7.js.map} +1 -1
  17. package/dist/{chunk-qx87cdfg.js → chunk-2z1981d0.js} +2 -2
  18. package/dist/{chunk-qx87cdfg.js.map → chunk-2z1981d0.js.map} +1 -1
  19. package/dist/{chunk-zng3qexn.js → chunk-329ggbcw.js} +2 -2
  20. package/dist/{chunk-zng3qexn.js.map → chunk-329ggbcw.js.map} +1 -1
  21. package/dist/{chunk-v4gwmhtf.js → chunk-37qk5dh8.js} +2 -2
  22. package/dist/{chunk-v4gwmhtf.js.map → chunk-37qk5dh8.js.map} +1 -1
  23. package/dist/{chunk-7jnpnjth.js → chunk-3ma9m432.js} +2 -2
  24. package/dist/{chunk-7jnpnjth.js.map → chunk-3ma9m432.js.map} +1 -1
  25. package/dist/{chunk-fnkjmq94.js → chunk-4szjp84e.js} +2 -2
  26. package/dist/{chunk-fnkjmq94.js.map → chunk-4szjp84e.js.map} +1 -1
  27. package/dist/{chunk-fr0arqdj.js → chunk-56fgk5rq.js} +2 -2
  28. package/dist/{chunk-fr0arqdj.js.map → chunk-56fgk5rq.js.map} +1 -1
  29. package/dist/{chunk-y6v0x869.js → chunk-583vxa2v.js} +2 -2
  30. package/dist/{chunk-y6v0x869.js.map → chunk-583vxa2v.js.map} +1 -1
  31. package/dist/{chunk-vqa3agzw.js → chunk-5j76r5q8.js} +3 -3
  32. package/dist/{chunk-vqa3agzw.js.map → chunk-5j76r5q8.js.map} +1 -1
  33. package/dist/chunk-60nyk1w8.js +10 -0
  34. package/dist/chunk-60nyk1w8.js.map +38 -0
  35. package/dist/{chunk-vwprq300.js → chunk-6h9j3f1x.js} +2 -2
  36. package/dist/{chunk-vwprq300.js.map → chunk-6h9j3f1x.js.map} +1 -1
  37. package/dist/{chunk-r7b12dmm.js → chunk-75wk4jxd.js} +2 -2
  38. package/dist/{chunk-r7b12dmm.js.map → chunk-75wk4jxd.js.map} +1 -1
  39. package/dist/{chunk-de03dewf.js → chunk-7fwp7vwh.js} +2 -2
  40. package/dist/{chunk-de03dewf.js.map → chunk-7fwp7vwh.js.map} +1 -1
  41. package/dist/{chunk-9vsj0ksk.js → chunk-7rmjr8p7.js} +3 -3
  42. package/dist/{chunk-9vsj0ksk.js.map → chunk-7rmjr8p7.js.map} +1 -1
  43. package/dist/{chunk-atmzm0z3.js → chunk-7v8sgqen.js} +2 -2
  44. package/dist/{chunk-atmzm0z3.js.map → chunk-7v8sgqen.js.map} +1 -1
  45. package/dist/{chunk-4t1pbt9p.js → chunk-8c2fs0n0.js} +3 -3
  46. package/dist/{chunk-4t1pbt9p.js.map → chunk-8c2fs0n0.js.map} +1 -1
  47. package/dist/{chunk-vzf5pbx3.js → chunk-8h7dh2h2.js} +2 -2
  48. package/dist/{chunk-vzf5pbx3.js.map → chunk-8h7dh2h2.js.map} +1 -1
  49. package/dist/{chunk-c7mp2kyp.js → chunk-8k8534kg.js} +2 -2
  50. package/dist/{chunk-c7mp2kyp.js.map → chunk-8k8534kg.js.map} +1 -1
  51. package/dist/{chunk-g8kx549d.js → chunk-8rt4wx8z.js} +3 -3
  52. package/dist/{chunk-g8kx549d.js.map → chunk-8rt4wx8z.js.map} +1 -1
  53. package/dist/{chunk-bq5nqqeq.js → chunk-a5sbgffr.js} +1 -1
  54. package/dist/{chunk-szr1k584.js → chunk-ap5gek56.js} +2 -2
  55. package/dist/{chunk-szr1k584.js.map → chunk-ap5gek56.js.map} +1 -1
  56. package/dist/{chunk-4tp2cr02.js → chunk-awp3n119.js} +2 -2
  57. package/dist/{chunk-4tp2cr02.js.map → chunk-awp3n119.js.map} +1 -1
  58. package/dist/{chunk-5q4a7yqf.js → chunk-cna105t6.js} +2 -2
  59. package/dist/{chunk-5q4a7yqf.js.map → chunk-cna105t6.js.map} +1 -1
  60. package/dist/{chunk-rg4hhxj3.js → chunk-d4m4amy4.js} +2 -2
  61. package/dist/{chunk-rg4hhxj3.js.map → chunk-d4m4amy4.js.map} +1 -1
  62. package/dist/{chunk-8mbyyh8j.js → chunk-e6fp6dxx.js} +2 -2
  63. package/dist/{chunk-8mbyyh8j.js.map → chunk-e6fp6dxx.js.map} +1 -1
  64. package/dist/{chunk-1se4t9rg.js → chunk-e7axa0d5.js} +3 -3
  65. package/dist/{chunk-1se4t9rg.js.map → chunk-e7axa0d5.js.map} +1 -1
  66. package/dist/{chunk-9tpx9ag3.js → chunk-erxv1jz7.js} +2 -2
  67. package/dist/{chunk-9tpx9ag3.js.map → chunk-erxv1jz7.js.map} +1 -1
  68. package/dist/chunk-fakvf9wb.js +5 -0
  69. package/dist/{chunk-fsfbyg5e.js.map → chunk-fakvf9wb.js.map} +1 -1
  70. package/dist/{chunk-nysqgzp1.js → chunk-fv9mr1t4.js} +2 -2
  71. package/dist/{chunk-nysqgzp1.js.map → chunk-fv9mr1t4.js.map} +1 -1
  72. package/dist/{chunk-p3zmc8k8.js → chunk-gdmsn3f5.js} +2 -2
  73. package/dist/{chunk-p3zmc8k8.js.map → chunk-gdmsn3f5.js.map} +1 -1
  74. package/dist/{chunk-y6frz1vm.js → chunk-gv91vjeb.js} +1 -1
  75. package/dist/{chunk-5x0aacrn.js → chunk-h2r2rdhj.js} +2 -2
  76. package/dist/{chunk-5x0aacrn.js.map → chunk-h2r2rdhj.js.map} +1 -1
  77. package/dist/{chunk-1p85fdrk.js → chunk-h4pazcgg.js} +2 -2
  78. package/dist/{chunk-1p85fdrk.js.map → chunk-h4pazcgg.js.map} +1 -1
  79. package/dist/{chunk-mk0rtgd1.js → chunk-hrvzchxd.js} +2 -2
  80. package/dist/{chunk-mk0rtgd1.js.map → chunk-hrvzchxd.js.map} +1 -1
  81. package/dist/{chunk-w45agtch.js → chunk-hytt9qyj.js} +2 -2
  82. package/dist/{chunk-w45agtch.js.map → chunk-hytt9qyj.js.map} +1 -1
  83. package/dist/{chunk-5nqkwa2w.js → chunk-hz6yzzbz.js} +1 -1
  84. package/dist/{chunk-z5hrymvn.js → chunk-j3nr4cg0.js} +3 -3
  85. package/dist/{chunk-z5hrymvn.js.map → chunk-j3nr4cg0.js.map} +1 -1
  86. package/dist/{chunk-dbwhgyg3.js → chunk-jk97wv0q.js} +2 -2
  87. package/dist/{chunk-dbwhgyg3.js.map → chunk-jk97wv0q.js.map} +1 -1
  88. package/dist/{chunk-x5sert1k.js → chunk-jv4g8grc.js} +2 -2
  89. package/dist/{chunk-x5sert1k.js.map → chunk-jv4g8grc.js.map} +1 -1
  90. package/dist/{chunk-yyzexrnb.js → chunk-jyrsd1dn.js} +2 -2
  91. package/dist/{chunk-yyzexrnb.js.map → chunk-jyrsd1dn.js.map} +1 -1
  92. package/dist/{chunk-y596ghpz.js → chunk-jzp0fs6h.js} +2 -2
  93. package/dist/{chunk-y596ghpz.js.map → chunk-jzp0fs6h.js.map} +1 -1
  94. package/dist/{chunk-kz4yp5n7.js → chunk-kcx468qv.js} +2 -2
  95. package/dist/{chunk-kz4yp5n7.js.map → chunk-kcx468qv.js.map} +1 -1
  96. package/dist/{chunk-zyer1g7k.js → chunk-kg1nbxvm.js} +4 -4
  97. package/dist/{chunk-zyer1g7k.js.map → chunk-kg1nbxvm.js.map} +1 -1
  98. package/dist/{chunk-qpttgn4k.js → chunk-kqb4s1r0.js} +3 -3
  99. package/dist/{chunk-qpttgn4k.js.map → chunk-kqb4s1r0.js.map} +1 -1
  100. package/dist/{chunk-rh2fad7n.js → chunk-m17ktssc.js} +1 -1
  101. package/dist/{chunk-k2fh4r0p.js → chunk-m2yfvwrn.js} +2 -2
  102. package/dist/{chunk-k2fh4r0p.js.map → chunk-m2yfvwrn.js.map} +1 -1
  103. package/dist/{chunk-wr3e4sez.js → chunk-mqcy5vja.js} +2 -2
  104. package/dist/{chunk-wr3e4sez.js.map → chunk-mqcy5vja.js.map} +1 -1
  105. package/dist/{chunk-f1y8eggf.js → chunk-n672d4g8.js} +2 -2
  106. package/dist/{chunk-f1y8eggf.js.map → chunk-n672d4g8.js.map} +1 -1
  107. package/dist/{chunk-xqwdn9kb.js → chunk-nek1gzz2.js} +3 -3
  108. package/dist/{chunk-xqwdn9kb.js.map → chunk-nek1gzz2.js.map} +1 -1
  109. package/dist/{chunk-01qd6xx3.js → chunk-pmywkp1w.js} +3 -3
  110. package/dist/{chunk-01qd6xx3.js.map → chunk-pmywkp1w.js.map} +1 -1
  111. package/dist/chunk-q95k1ymq.js +4 -0
  112. package/dist/{chunk-kp7k4s5c.js.map → chunk-q95k1ymq.js.map} +3 -3
  113. package/dist/{chunk-vdwagp7y.js → chunk-r4namj39.js} +2 -2
  114. package/dist/{chunk-vdwagp7y.js.map → chunk-r4namj39.js.map} +1 -1
  115. package/dist/{chunk-571rvxe6.js → chunk-rrqr1dwq.js} +2 -2
  116. package/dist/{chunk-571rvxe6.js.map → chunk-rrqr1dwq.js.map} +1 -1
  117. package/dist/{chunk-sr18y2ck.js → chunk-tp3mzj4v.js} +2 -2
  118. package/dist/{chunk-sr18y2ck.js.map → chunk-tp3mzj4v.js.map} +1 -1
  119. package/dist/{chunk-6wymbbes.js → chunk-ty4aj41k.js} +3 -3
  120. package/dist/{chunk-6wymbbes.js.map → chunk-ty4aj41k.js.map} +1 -1
  121. package/dist/chunk-v9na3dny.js +46 -0
  122. package/dist/{chunk-6g20zec2.js.map → chunk-v9na3dny.js.map} +6 -6
  123. package/dist/{chunk-d04r0hdf.js → chunk-w2fpr99k.js} +2 -2
  124. package/dist/{chunk-d04r0hdf.js.map → chunk-w2fpr99k.js.map} +1 -1
  125. package/dist/{chunk-vc9phr57.js → chunk-wwmdqhzy.js} +2 -2
  126. package/dist/{chunk-vc9phr57.js.map → chunk-wwmdqhzy.js.map} +1 -1
  127. package/dist/chunk-wysm6qte.js +5 -0
  128. package/dist/chunk-wysm6qte.js.map +12 -0
  129. package/dist/{chunk-mepaedy5.js → chunk-x157wrgy.js} +2 -2
  130. package/dist/{chunk-mepaedy5.js.map → chunk-x157wrgy.js.map} +1 -1
  131. package/dist/{chunk-nksn6xcd.js → chunk-xrh6k13s.js} +2 -2
  132. package/dist/{chunk-nksn6xcd.js.map → chunk-xrh6k13s.js.map} +1 -1
  133. package/dist/{chunk-g8sc6scv.js → chunk-y0wx6w80.js} +2 -2
  134. package/dist/{chunk-g8sc6scv.js.map → chunk-y0wx6w80.js.map} +1 -1
  135. package/dist/{chunk-kexsfyjj.js → chunk-yp5979we.js} +2 -2
  136. package/dist/{chunk-kexsfyjj.js.map → chunk-yp5979we.js.map} +1 -1
  137. package/dist/{chunk-essqp1ek.js → chunk-z32xfe8c.js} +2 -2
  138. package/dist/{chunk-essqp1ek.js.map → chunk-z32xfe8c.js.map} +1 -1
  139. package/dist/{chunk-x5yq097b.js → chunk-zgn0p8qr.js} +3 -3
  140. package/dist/{chunk-x5yq097b.js.map → chunk-zgn0p8qr.js.map} +1 -1
  141. package/dist/{chunk-agw3anaf.js → chunk-zns7xcz9.js} +1 -1
  142. package/dist/config/index.js +1 -1
  143. package/dist/console/run.js +2 -2
  144. package/dist/console/run.js.map +1 -1
  145. package/dist/container/index.js +2 -2
  146. package/dist/container/index.js.map +1 -1
  147. package/dist/database/index.js +2 -2
  148. package/dist/database/index.js.map +1 -1
  149. package/dist/email/index.js +2 -2
  150. package/dist/email/index.js.map +1 -1
  151. package/dist/facades/index.js +2 -2
  152. package/dist/facades/index.js.map +1 -1
  153. package/dist/foundation/index.js +2 -2
  154. package/dist/foundation/index.js.map +1 -1
  155. package/dist/http/HttpRequest.d.ts +31 -0
  156. package/dist/http/HttpRequest.d.ts.map +1 -1
  157. package/dist/http/McpRouter.d.ts +54 -1
  158. package/dist/http/McpRouter.d.ts.map +1 -1
  159. package/dist/http/RateLimitMiddleware.d.ts +4 -1
  160. package/dist/http/RateLimitMiddleware.d.ts.map +1 -1
  161. package/dist/http/index.d.ts +1 -0
  162. package/dist/http/index.d.ts.map +1 -1
  163. package/dist/http/index.js +2 -2
  164. package/dist/http/index.js.map +1 -1
  165. package/dist/http/modelOriginated.d.ts +36 -2
  166. package/dist/http/modelOriginated.d.ts.map +1 -1
  167. package/dist/i18n/dictionaryRuntime.js +2 -2
  168. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  169. package/dist/i18n/index.js +2 -2
  170. package/dist/i18n/index.js.map +1 -1
  171. package/dist/kernel/Kernel.d.ts +3 -0
  172. package/dist/kernel/Kernel.d.ts.map +1 -1
  173. package/dist/kernel/index.js +3 -3
  174. package/dist/kernel/index.js.map +3 -3
  175. package/dist/orm/index.js +2 -2
  176. package/dist/orm/index.js.map +1 -1
  177. package/dist/server/index.js +2 -2
  178. package/dist/server/index.js.map +1 -1
  179. package/dist/services/index.d.ts +6 -1
  180. package/dist/services/index.d.ts.map +1 -1
  181. package/dist/services/index.js +44 -9
  182. package/dist/services/index.js.map +6 -3
  183. package/dist/services/mcp/McpRegistry.d.ts +190 -29
  184. package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
  185. package/dist/services/mcp/http/McpHttpServer.d.ts +153 -0
  186. package/dist/services/mcp/http/McpHttpServer.d.ts.map +1 -0
  187. package/dist/services/mcp/http/callers.d.ts +131 -0
  188. package/dist/services/mcp/http/callers.d.ts.map +1 -0
  189. package/dist/services/mcp/http/limits.d.ts +11 -0
  190. package/dist/services/mcp/http/limits.d.ts.map +1 -0
  191. package/dist/services/mcp/http/oauth/McpOAuthServer.d.ts +150 -0
  192. package/dist/services/mcp/http/oauth/McpOAuthServer.d.ts.map +1 -0
  193. package/dist/services/mcp/http/oauth/consentPage.d.ts +14 -0
  194. package/dist/services/mcp/http/oauth/consentPage.d.ts.map +1 -0
  195. package/dist/services/mcp/http/oauth/store.d.ts +98 -0
  196. package/dist/services/mcp/http/oauth/store.d.ts.map +1 -0
  197. package/dist/services/mcp/http/protocol.d.ts +95 -0
  198. package/dist/services/mcp/http/protocol.d.ts.map +1 -0
  199. package/dist/services/mcp/http/signedState.d.ts +25 -0
  200. package/dist/services/mcp/http/signedState.d.ts.map +1 -0
  201. package/dist/services/queue/work.js +2 -2
  202. package/dist/services/queue/work.js.map +1 -1
  203. package/dist/services/router/ApiRouteDispatcher.d.ts +29 -0
  204. package/dist/services/router/ApiRouteDispatcher.d.ts.map +1 -1
  205. package/dist/services/router/RouteServiceProvider.d.ts +6 -0
  206. package/dist/services/router/RouteServiceProvider.d.ts.map +1 -1
  207. package/dist/services/router/config.d.ts +16 -0
  208. package/dist/services/router/config.d.ts.map +1 -1
  209. package/dist/stats/route-table.js +1 -1
  210. package/dist/support/index.js +2 -2
  211. package/dist/support/index.js.map +1 -1
  212. package/dist/vitest/index.js +1 -1
  213. package/package.json +1 -1
  214. package/dist/chunk-3z9vhjd7.js +0 -5
  215. package/dist/chunk-3z9vhjd7.js.map +0 -10
  216. package/dist/chunk-5zzhypmt.js +0 -5
  217. package/dist/chunk-5zzhypmt.js.map +0 -33
  218. package/dist/chunk-6g20zec2.js +0 -46
  219. package/dist/chunk-cqnfp0n9.js +0 -14
  220. package/dist/chunk-fsfbyg5e.js +0 -5
  221. package/dist/chunk-kp7k4s5c.js +0 -4
  222. /package/dist/{chunk-bq5nqqeq.js.map → chunk-a5sbgffr.js.map} +0 -0
  223. /package/dist/{chunk-y6frz1vm.js.map → chunk-gv91vjeb.js.map} +0 -0
  224. /package/dist/{chunk-5nqkwa2w.js.map → chunk-hz6yzzbz.js.map} +0 -0
  225. /package/dist/{chunk-rh2fad7n.js.map → chunk-m17ktssc.js.map} +0 -0
  226. /package/dist/{chunk-agw3anaf.js.map → chunk-zns7xcz9.js.map} +0 -0
@@ -0,0 +1,46 @@
1
+ // @bun
2
+ import{Ye as EW,df as yX}from"./chunk-kqb4s1r0.js";import{Wf as qX,kf as x3,pf as RZ}from"./chunk-hytt9qyj.js";import{$f as jX,Hg as o7,Ig as A$,Jg as DX,Kg as PX,Mg as _X,Xf as p8,ag as ZW,bg as JW,cg as E8,dg as _8,gg as H8,hg as x8,ig as AZ,jg as g5,kg as GX,lg as qj,mg as h,rg as A,sg as h8,tg as p$,ug as R8,vg as g3,xg as W$,yg as z0,zg as j8}from"./chunk-0n9vs1ad.js";import{Pg as EZ,Qg as q0,Rg as b1,Sg as YW}from"./chunk-75wk4jxd.js";import{Tg as f5,Ug as U8,Vg as f}from"./chunk-jzp0fs6h.js";import{Yg as VX}from"./chunk-8k8534kg.js";import{Zg as M8}from"./chunk-583vxa2v.js";import{$g as F1,_g as WX,ah as z$,bh as vX,ch as kX,eh as Hj,fh as CX,oh as wX}from"./chunk-8c2fs0n0.js";import{Dh as X$}from"./chunk-6h9j3f1x.js";import{Ih as $X,Nh as Bj}from"./chunk-erxv1jz7.js";import{Uh as e5,Yh as o}from"./chunk-fv9mr1t4.js";import{Zh as fZ,ai as N}from"./chunk-j3nr4cg0.js";import{di as HX}from"./chunk-wwmdqhzy.js";import{oi as YX}from"./chunk-4szjp84e.js";import{ti as B8}from"./chunk-e6fp6dxx.js";function b3($){return typeof $==="function"&&$.prototype!==void 0}function Q1($){return typeof $==="string"?[$]:$}function v3($,Z){let J=Z?"attachment":"inline",j=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${j}"; filename*=UTF-8''${encodeURIComponent($)}`}function nX($){return"total"in $&&"partial"in $&&"body"in $}function Aj(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function kZ($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":x8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function oX($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(nX($))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,j=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??j-1,total:j,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 S8($,Z){if($ instanceof Response)return $;if(!$)return Aj();let J=await oX($),{body:j,start:W,end:Y,total:z,partial:X}=J;if(j instanceof Blob&&"exists"in j&&typeof j.exists==="function"){if(!await j.exists())return Aj()}let{range:O}=Z;if(O){if(z<=0)return kZ(Math.max(z,0));if(!X){if(j instanceof Blob){let U=_8(O,z);if(!U)return kZ(z);j=j.slice(U.start,U.end+1),W=U.start,Y=U.end,X=!0}}}let G=Boolean(O)&&X,K=G?206:J.status,Q=new Headers;if(Q.set("Accept-Ranges","bytes"),Q.set("Content-Type",J.type||"application/octet-stream"),Q.set("X-Content-Type-Options","nosniff"),G)Q.set("Content-Range",H8(W,Y,z)),Q.set("Content-Length",String(Y-W+1));else if(z>=0)Q.set("Content-Length",String(z));if(J.name)Q.set("Content-Disposition",v3(J.name,J.download));if(J.etag)Q.set("ETag",J.etag);if(J.lastModified)Q.set("Last-Modified",J.lastModified.toUTCString());for(let[U,F]of Object.entries(J.extraHeaders))Q.set(U,F);if((Z.method??"GET").toUpperCase()==="HEAD"){if(j&&"cancel"in j&&typeof j.cancel==="function")await j.cancel();return new Response(null,{status:K,headers:Q})}return new Response(j,{status:K,headers:Q})}class w$ extends q0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var Ej={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function qZ($){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 Ej)))return Math.floor(Number(J[1])*(Ej[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var wZ=new WeakMap;function bj($){return wZ.has($)}function vj($){return wZ.get($)?.limit??null}function kj($){let Z=wZ.get($);return Z?Z.read>Z.limit:!1}function aX($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function A8($,Z){let J=aX($);if(J!==null&&J>Z)throw new w$(Z)}function k3($,Z,J={}){let j=wZ.get($);if(j)j.limit=Z;else{let W={limit:Z,read:0,stream:void 0,used:!1};wZ.set($,W),tX($,W)}if(J.checkDeclared!==!1)A8($,Z)}function rX($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function f8($,Z){if(Z.stream!==void 0)return Z.stream;let J=rX($);if(!J)return Z.stream=null;let j;return Z.stream=new ReadableStream({async pull(W){j??=J.getReader();let{done:Y,value:z}=await j.read();if(Y){W.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new w$(Z.limit);W.error(X),j.cancel(X).catch(()=>{});return}W.enqueue(z)},cancel(W){return j?j.cancel(W):J.cancel(W)}},{highWaterMark:0}),Z.stream}async function k$($,Z){if(A8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=f8($,Z);if(!J)return new Uint8Array(0);let j=J.getReader(),W=[],Y=0;for(;;){let{done:O,value:G}=await j.read();if(O)break;W.push(G),Y+=G.byteLength}let z=new Uint8Array(Y),X=0;for(let O of W)z.set(O,X),X+=O.byteLength;return z}function Rj($){return $.headers.get("Content-Type")??""}function tX($,Z){let J=(j,W)=>Object.defineProperty($,j,{configurable:!0,...W});J("body",{get:()=>f8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>k$($,Z)}),J("arrayBuffer",{value:async()=>{let j=await k$($,Z);return j.buffer.slice(j.byteOffset,j.byteOffset+j.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await k$($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await k$($,Z)))}),J("blob",{value:async()=>new Blob([await k$($,Z)],{type:Rj($)})}),J("formData",{value:async()=>new Response(await k$($,Z),{headers:{"Content-Type":Rj($)}}).formData()}),J("clone",{value:()=>{A8($,Z.limit);let j=f8($,Z),W=null;if(j){let[Y,z]=j.tee();Z.stream=Y,W=z}return new Request($.url,{method:$.method,headers:$.headers,body:W,signal:$.signal,duplex:"half"})}})}function wj($){return b3($)}class $0{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(!wj(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(wj(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=Q1($),this}}class yj{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=Q1($),this}async run(){let $=new A,Z=$.headers.toJSON();for(let J of qj($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(kj($.rawRequest))throw new w$(vj($.rawRequest));throw J}}}class gj{constructor(...$){return new $0(...$)}}class mj extends $0{__internal_brand="StreamHandler";async run($){let Z=f.getStore(),J=Z?.req?.rawRequest,j=E8(J?.headers.get("Range"));if(Z)Z.rangeRequest=j;try{let W=await super.run($);return await S8(W,{range:j,method:J?.method})}catch(W){if(W instanceof R8)return kZ(W.total);throw W}finally{if(Z)Z.rangeRequest=null}}}class pj{constructor(...$){return new mj(...$)}}class hj{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new $0("GET",$,"list"),post:new $0("POST",$,"store")},this.second={get:new $0("GET",$,"show"),put:new $0("PUT",$,"update"),delete:new $0("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 S0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new $0("GET",$,Z)}post($,Z){return new $0("POST",$,Z)}put($,Z){return new $0("PUT",$,Z)}patch($,Z){return new $0("PATCH",$,Z)}delete($,Z){return new $0("DELETE",$,Z)}resource($){return new hj($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${eX($)}.`);return $O($,this)}file($,Z){return new gj("GET",$,Z)}stream($,Z){return new pj("GET",$,Z)}proxy($,Z={}){return new yj($,Z)}}function eX($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function $O($,Z){let J={stream:new $0("POST",$,"stream"),attach:new $0("POST",$,"attach"),stop:new $0("POST",$,"stop"),upload:new $0("POST",$,"upload")};return class extends S0{static __internal_brand="AgentRoute";static controller=$;static handlers=J;constructor(){super();this.middlewares=[...Z?.middlewares??[]]}routes={"/":J.stream,"/attach":J.attach,"/stop":J.stop,"/files":J.upload};static middleware(W){if(W.stream)J.stream.middleware(W.stream);if(W.attach)J.attach.middleware(W.attach);if(W.stop)J.stop.middleware(W.stop);if(W.upload)J.upload.middleware(W.upload);return this}}}class b8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class v8{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class cj{static __brand="McpRouter";routes={};scopes;param($){return new b8($.as,$.input,$.bind)}fromApiRoute($,Z,J){return new v8($,Z,J)}}function X0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,j)=>{let W=j.endsWith("?")||j.endsWith("*"),Y=W?j.slice(0,-1):j,z=Z[Y];if(z===void 0){if(W)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${Y}`);console.error(`Missing parameter: ${Y} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class k8 extends q0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class q${static to($,...Z){let[J={}]=Z,{search:j={},params:W={},permanent:Y,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(j).toString();throw new k8([X0($,W)||"/",X.toString()].filter(Boolean).join("?"),z??(Y?301:307))}static external($,Z=307){throw new k8($,Z)}}var uj=Symbol.for("gemi.HttpResponse");class J${kind;body;status;headers;[uj]=!0;constructor($,Z,J,j){this.kind=$;this.body=Z;this.status=J;this.headers=j}static json($,Z={}){let J=Z.status??200;return ZO(J),new J$("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 J$.json({error:Z},{...J,status:$})}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,j=this.serialize(J);for(let W of Z)J.append("Set-Cookie",W);this.headers.forEach((W,Y)=>{if(Y.toLowerCase()!=="set-cookie")J.set(Y,W)});for(let W of this.headers.getSetCookie())J.append("Set-Cookie",W);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(j,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null}}}function ZO($){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.json: a ${$} response has no body.`)}function y$($){return typeof $==="object"&&$!==null&&$[uj]===!0}function JO($,Z,J={}){return J$.error($,Z,J)}class dj{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(j)=>{return new Z()[J](j)}}}async run($,Z){let{destination:J,permanent:j=!1,status:W=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return q$.to(J,{permanent:j,status:W}),{}}middleware($){return this.middlewares=Q1($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function w8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,j=J?$:$.file,W=J?$.name:$.name??$.file?.name,Y=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[O,G]of Object.entries($.headers??{}))Z.set(O,G);if(j instanceof Blob&&"exists"in j&&typeof j.exists==="function"){if(!await j.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",Y||"application/octet-stream"),j instanceof Blob)Z.set("Content-Length",String(j.size));if(W)Z.set("Content-Disposition",v3(W,z));return new Response(j instanceof Blob?j.stream():j,{status:X,headers:Z})}class lj{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(j)=>{return new Z()[J](j)}}}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=Q1($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function ij($,Z){if(y$($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class sj{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,j]=Z;this.handler=(W)=>{return new J()[j](W)}}}async run($,Z){let J=ij(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=Q1($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class nj{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[j,W]=Z;this.handler=(Y)=>{return new j()[W](Y)},this.children=class extends E1{routes=J??{}}}else this.children=class extends E1{routes=Z},this.handler=()=>({})}async run($,Z){let J=ij(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=Q1($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class E1{middlewares=[];featureGates=[];routes={};view($,Z){return new sj($,Z)}file($){return new lj($)}redirect($){return new dj($)}layout($,Z,J){return new nj($,Z,J)}}class O0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}function jO($){return $}function WO(){return{aliases:{},global:[],bodyLimit:null}}var j$="redirect";function g$($,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 j=`${J.search}${J.hash}`.replaceAll("/","%2F"),W=`${J.pathname}${j}`.replaceAll(":","%3A");return W.startsWith("//")?Z:W}catch{return Z}}function q8($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function YO($,Z=!0){let J=new URL($.rawRequest.url),j=J.pathname.replace(/\.(json|og)$/,""),[,W,...Y]=j.split("/");if(N(o).supportedLocales.includes(W))j=`/${Y.join("/")}`;return Z?`${j}${J.search}`:j}function zO($,Z){let J=(j)=>j.replace(/\/+$/,"")||"/";return J($)===J(Z)}function w3($,Z){let J=Z||N(E).config.signInPath,j=/^[a-z][a-z\d+.-]*:/i.test(J);if(j?!/^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 W=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let Y=YO($,!j);if(j||!zO(new URL(Y,W).pathname,W.pathname))W.searchParams.set(j$,Y)}return j?W.href:`${W.pathname}${W.search}`}var R1="access_token";function y8($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function q3($,Z){let J=y8(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}class oj extends O0{async run($){let Z=f.getStore(),J=Z.req;if(Z.user)return{};let j=await q3(N(E),J);if(!j)throw new W$({redirectTo:w3(J,$)});return Z.setUser(j),{}}}class aj extends O0{async run(...$){let[Z="public",J="864000",...j]=$,W=`${Z}, max-age=${J}${j.length>0?", ":""}${j.join(", ")}`;if($.length===0)W="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")W="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")W="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",W);return{}}}var rj={"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 tj extends O0{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={...rj,...this.config.origins[Z]};for(let[j,W]of Object.entries(J))$.ctx().setHeaders(j,W)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...rj,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[j,W]of Object.entries(J))$.ctx().setHeaders(j,W)}return{}}}class e0{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,j=Z.window??this.config.window,W=Z.cost??1;if(ej("window",j),ej("limit",J),!Number.isFinite(W)||W<0)throw Error(`Rate limiter cost must be zero or greater, got ${W}`);return await this.config.driver.consume({key:$,limit:J,window:j*1000,cost:W})}}function ej($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}class yZ extends q0{constructor($){super("Rate limit exceeded");let Z={"Content-Type":"application/json",...$?WW($):{}};this.payload={api:{status:429,data:{error:b1("rate_limit","Rate limit exceeded",429)},headers:Z},view:{error:{message:"Rate limit exceeded"},status:429,headers:Z}}}}class jW extends O0{async run($,Z){let J=XO();if(!J)return{};let j=await J.consume(this.key(),{limit:$W($)??this.config.limit,window:$W(Z)??this.config.window});if(this.config.headers!==!1){let W=this.req.ctx?.();if(W)for(let[Y,z]of Object.entries(WW(j)))W.setHeaders(Y,z)}if(!j.allowed)throw new yZ(j);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=ZW(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${m$(this.req)}:${this.req.routePath??"*"}`}}function XO(){try{let $=N();return $.bound(e0)?$.make(e0):null}catch{return null}}function m$($){let Z=JW($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[j]=J.split(",");if(j?.trim())return j.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function WW($){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}function $W($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class zW extends O0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new g8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new g8;return{}}}class g8 extends q0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:YW("csrf","Invalid CSRF token",403)}},view:{}}}class y3 extends O0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return k3(this.req.rawRequest,qZ(Z)),{}}}class XW{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class OW{all($,Z){return!0}}class m8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new p$:new g3}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 j=J.get(Z);if(!j)j=this.decide($,Z),J.set(Z,j);return j}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new A,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends O0{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:j})=>{let W;if(J!==void 0){if(W=$.thread?await $.thread(J,Z):null,W===null||W===void 0)throw this.refusal()}if(j!==void 0){let Y=await $.body(j,Z);if(await this.authorize(Z,Y),J!==void 0&&String(W)!==String(Y))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,W)}}}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 p$:$ instanceof g3}}function OO($){return new m8($)}import{lookup as MO}from"dns/promises";import*as IO from"http";import*as NO from"https";import*as s$ from"zlib";function GO($){if($==="")return null;let Z=$.split(".");if(Z.length>1&&Z[Z.length-1]==="")Z.pop();if(Z.length===0||Z.length>4)return null;let J=[];for(let Y of Z){let z=KO(Y);if(z===null)return null;J.push(z)}let j=J.pop();for(let Y of J)if(Y>255)return null;if(j>=256**(4-J.length))return null;let W=j;return J.forEach((Y,z)=>{W+=Y*256**(3-z)}),new Uint8Array([Math.floor(W/16777216)&255,Math.floor(W/65536)&255,Math.floor(W/256)&255,W&255])}function KO($){if($==="")return null;let Z=$,J=10;if(/^0x/i.test(Z)){if(Z=Z.slice(2),J=16,Z==="")return 0}else if(Z.length>1&&Z.startsWith("0"))Z=Z.slice(1),J=8;if(!(J===16?/^[0-9a-f]+$/i:J===8?/^[0-7]+$/:/^[0-9]+$/).test(Z))return null;let W=parseInt(Z,J);return Number.isSafeInteger(W)?W:null}function GW($){let Z=$;if(Z.startsWith("[")&&Z.endsWith("]"))Z=Z.slice(1,-1);let J=Z.indexOf("%");if(J!==-1)Z=Z.slice(0,J);if(!Z.includes(":"))return null;let j=Z.split("::");if(j.length>2)return null;let W=(G,K)=>{if(G==="")return[];let Q=[],U=G.split(":");for(let F=0;F<U.length;F++){let B=U[F];if(K&&F===U.length-1&&B.includes(".")){if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(B))return null;let D=B.split(".").map(Number);if(D.some((T)=>T>255))return null;Q.push(D[0]<<8|D[1],D[2]<<8|D[3]);continue}if(!/^[0-9a-f]{1,4}$/i.test(B))return null;Q.push(parseInt(B,16))}return Q},Y=W(j[0],j.length===1),z=j.length===2?W(j[1],!0):[];if(!Y||!z)return null;let X;if(j.length===2){let G=8-Y.length-z.length;if(G<1)return null;X=[...Y,...Array.from({length:G},()=>0),...z]}else X=Y;if(X.length!==8)return null;let O=new Uint8Array(16);return X.forEach((G,K)=>{O[K*2]=G>>8,O[K*2+1]=G&255}),O}function gZ($){let Z=GW($);if(Z)return{family:6,bytes:Z};let J=GO($);if(J)return{family:4,bytes:J};return null}function Y$($){if($.family===6&&QO($.bytes))return{family:4,bytes:$.bytes.slice(12)};return $}function QO($){for(let Z=0;Z<10;Z++)if($[Z]!==0)return!1;return $[10]===255&&$[11]===255}function mZ($){if($.family===4)return Array.from($.bytes).join(".");let Z=[];for(let J=0;J<16;J+=2)Z.push(($.bytes[J]<<8|$.bytes[J+1]).toString(16));return Z.join(":")}function c$($){let Z=$.lastIndexOf("/"),J=Z===-1?$:$.slice(0,Z),j=/^[0-9.]+$/.test(J)?UO(J):GW(J);if(!j)return null;let W=Y$(j.length===4?{family:4,bytes:j}:{family:6,bytes:j}),Y=W.family===4?32:128,z=Y;if(Z!==-1){let X=$.slice(Z+1);if(!/^\d{1,3}$/.test(X))return null;if(z=Number(X),j.length===16&&W.family===4)z-=96;if(z<0||z>Y)return null}return{family:W.family,bytes:W.bytes,prefix:z}}function UO($){return/^\d{1,3}(\.\d{1,3}){3}$/.test($)&&$.split(".").every((Z)=>Number(Z)<=255)?new Uint8Array($.split(".").map(Number)):null}function U1($,Z){let J=Y$($);if(J.family!==Z.family)return!1;let j=Z.prefix;for(let W=0;j>0;W++){let Y=Math.min(8,j),z=255<<8-Y&255;if((J.bytes[W]&z)!==(Z.bytes[W]&z))return!1;j-=Y}return!0}var k=($,Z)=>({cidr:c$($),kind:Z,text:$}),BO=[k("0.0.0.0/8","unspecified"),k("10.0.0.0/8","private"),k("100.64.0.0/10","shared"),k("127.0.0.0/8","loopback"),k("169.254.169.254/32","metadata"),k("169.254.0.0/16","link-local"),k("168.63.129.16/32","metadata"),k("172.16.0.0/12","private"),k("192.0.0.0/24","reserved"),k("192.0.2.0/24","documentation"),k("192.88.99.0/24","reserved"),k("192.168.0.0/16","private"),k("198.18.0.0/15","benchmarking"),k("198.51.100.0/24","documentation"),k("203.0.113.0/24","documentation"),k("224.0.0.0/4","multicast"),k("255.255.255.255/32","broadcast"),k("240.0.0.0/4","reserved")],FO=[k("::/128","unspecified"),k("::1/128","loopback"),k("64:ff9b:1::/48","private"),k("::/8","reserved"),k("100::/64","reserved"),k("2001:db8::/32","documentation"),k("2001::/23","reserved"),k("3fff::/20","documentation"),k("fd00:ec2::254/128","metadata"),k("fc00::/7","unique-local"),k("fe80::/10","link-local"),k("fec0::/10","private"),k("ff00::/8","multicast")],DO=c$("64:ff9b::/96"),TO=c$("2002::/16"),VO=c$("2000::/3");function h$($){let Z=typeof $==="string"?gZ($):$;if(!Z)return{kind:"reserved",range:"not an IP address"};let J=Y$(Z);if(J.family===4){let W=BO.find((Y)=>U1(J,Y.cidr));return W?{kind:W.kind,range:W.text}:null}if(U1(J,DO))return h$({family:4,bytes:J.bytes.slice(12)});if(U1(J,TO))return h$({family:4,bytes:J.bytes.slice(2,6)});let j=FO.find((W)=>U1(J,W.cidr));if(j)return{kind:j.kind,range:j.text};return U1(J,VO)?null:{kind:"reserved",range:"outside 2000::/3"}}function KW($,Z){let J=Y$($),j=Y$(Z);return J.family===j.family&&J.bytes.every((W,Y)=>W===j.bytes[Y])}class U0 extends Error{code="safe-fetch";url;constructor($,Z,J){super($,J);this.name=new.target.name,this.url=Z}}class B1 extends U0{reason;code="invalid-url";constructor($,Z,J){super(J,$);this.reason=Z}}class u$ extends U0{host;reason;code="blocked-host";constructor($,Z,J){super(J==="denied"?`Requests to ${Z} are not allowed.`:`${Z} is not on the list of hosts this request may reach.`,$);this.host=Z;this.reason=J}}class v1 extends U0{host;address;range;code="blocked-address";constructor($,Z,J,j){super(Z===J?`${J} is not a public address (${j}).`:`${Z} resolves to ${J}, which is not a public address (${j}).`,$);this.host=Z;this.address=J;this.range=j}}class d$ extends U0{host;code="dns";constructor($,Z,J){super(`Couldn't resolve ${Z}.`,$,{cause:J});this.host=Z}}class l$ extends U0{phase;ms;code="timeout";constructor($,Z,J){super(Z==="connect"?`Couldn't connect within ${J} ms.`:`The request didn't finish within ${J} ms.`,$);this.phase=Z;this.ms=J}}class i$ extends U0{limit;code="too-large";constructor($,Z){super(`The response is larger than ${Z} bytes.`,$);this.limit=Z}}class pZ extends U0{contentType;allowed;code="content-type";constructor($,Z,J){super(`The response is ${Z??"of no content type"}, not ${J.join(" or ")}.`,$);this.contentType=Z;this.allowed=J}}class hZ extends U0{limit;code="too-many-redirects";constructor($,Z){super(`More than ${Z} redirects.`,$);this.limit=Z}}class k1 extends U0{code="network";constructor($,Z){super(`The request failed: ${Z instanceof Error?Z.message:String(Z)}`,$,{cause:Z})}}class uZ extends Response{#W;#Z;address;constructor($,Z,J){super($,Z);this.#W=J.url,this.#Z=J.redirected,this.address=J.address}get url(){return this.#W}get redirected(){return this.#Z}}var cZ={timeout:30000,connectTimeout:1e4,maxSize:10485760,maxRedirects:5,ports:[80,443]},CO=new Set([301,302,303,307,308]),LO=new Set([101,103,204,205,304]),PO=["host","connection","content-length","transfer-encoding","keep-alive","upgrade"],_O=["authorization","cookie","proxy-authorization"];async function BW($,Z={}){let J=HO(Z),j=Z.signal;j?.throwIfAborted();let W=new AbortController,Y=W.signal,z=String($),X=(Q)=>{if(!Y.aborted)W.abort(Q)},O=setTimeout(()=>X(new l$(z,"total",J.timeout)),J.timeout),G=()=>X(j.reason);j?.addEventListener("abort",G,{once:!0});let K=()=>{clearTimeout(O),j?.removeEventListener("abort",G)};try{let Q=UW(z,J),U=(Z.method??"GET").toUpperCase(),F=new Headers(Z.headers);for(let D of PO)F.delete(D);if(!F.has("accept"))F.set("accept","*/*");if(!F.has("user-agent"))F.set("user-agent","gemi");if(!F.has("accept-encoding"))F.set("accept-encoding","gzip, deflate, br");let B=await AO(U,Z.body,F);for(let D=0;;D++){z=Q.href;let{request:T,response:M,address:L}=await EO(Q,U,F,B,J,Y),I=M.statusCode??0,_=M.headers.location;if(CO.has(I)&&_&&Z.redirect!=="manual"){if(T.destroy(),D>=J.maxRedirects)throw new hZ(Q.href,J.maxRedirects);let H;try{H=new URL(_,Q)}catch{throw new B1(_,"malformed",`The redirect to "${_}" is not a URL.`)}if(I===303?U!=="HEAD":(I===301||I===302)&&U==="POST"){U="GET",B=null;let P=[];F.forEach((V,C)=>{if(C.startsWith("content-"))P.push(C)});for(let V of P)F.delete(V)}if(H.origin!==Q.origin)for(let P of _O)F.delete(P);Q=UW(H.href,J);continue}return RO({url:Q,hop:D,method:U,request:T,response:M,address:L,policy:J,signal:Y,release:K})}}catch(Q){throw K(),Y.aborted?Y.reason:Q}}function HO($){let Z=(j,W)=>{let Y={hosts:[],ranges:[]};for(let z of j){let X=z.includes("/")||z.includes(":")||/^[\d.]+$/.test(z),O=X?c$(z):null;if(O)Y.ranges.push(O);else if(!X&&/^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/i.test(z))Y.hosts.push(FW(z));else throw TypeError(`safeFetch: "${z}" in ${W} is not a host name or an IP range.`)}return Y},J=$.allowPrivate;return{timeout:$.timeout??cZ.timeout,connectTimeout:$.connectTimeout??cZ.connectTimeout,maxSize:$.maxSize??cZ.maxSize,maxRedirects:$.maxRedirects??cZ.maxRedirects,ports:$.ports??cZ.ports,allow:$.allow&&$.allow.length>0?Z($.allow,"allow"):null,deny:Z($.deny??[],"deny"),allowPrivate:J===!0?!0:Z(J||[],"allowPrivate").ranges,contentTypes:$.contentTypes?.length?$.contentTypes:null,resolve:$.resolve??xO}}async function xO($){return(await MO($,{all:!0,verbatim:!0})).map((J)=>J.address)}function FW($){return $.toLowerCase().replace(/\.$/,"")}function QW($,Z){return Z.some((J)=>J.startsWith("*.")?$.endsWith(J.slice(1)):$===J)}function UW($,Z){let J;try{J=new URL($)}catch{throw new B1($,"malformed",`"${$}" is not a URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new B1(J.href,"scheme",`Only http and https URLs can be fetched, not ${J.protocol.slice(0,-1)}.`);if(J.username||J.password)throw new B1(J.href,"credentials","The URL has a username or password in it.");let j=DW(J);if(Z.ports!=="any"&&!Z.ports.includes(j))throw new B1(J.href,"port",`Port ${j} is not allowed.`);return J}function DW($){return $.port?Number($.port):$.protocol==="https:"?443:80}async function SO($,Z,J){let j=FW($.hostname.replace(/^\[(.*)\]$/,"$1")),W=gZ(j),Y=W!==null&&(j.includes(":")||/^\d+\.\d+\.\d+\.\d+$/.test(j));if(!Y&&QW(j,Z.deny.hosts))throw new u$($.href,j,"denied");let z=!Y&&Z.allow!==null&&QW(j,Z.allow.hosts);if(Z.allow&&!z&&Z.allow.ranges.length===0)throw new u$($.href,j,"not-allowed");let X;if(Y)X=[W];else{let O;try{O=await fO(Z.resolve(j),J)}catch(G){if(J.aborted)throw J.reason;throw new d$($.href,j,G)}if(X=O.map((G)=>gZ(G)).filter((G)=>G!==null),X.length===0)throw new d$($.href,j)}for(let O of X){let G=mZ(O);if(Z.deny.ranges.some((Q)=>U1(O,Q)))throw new v1($.href,j,G,"denied");if(Z.allow&&!z&&!Z.allow.ranges.some((Q)=>U1(O,Q)))throw new v1($.href,j,G,"not-allowed");let K=h$(O);if(K&&Z.allowPrivate!==!0&&!Z.allowPrivate.some((Q)=>U1(O,Q)))throw new v1($.href,j,G,K.kind)}return{host:j,addresses:X,isLiteral:Y}}function fO($,Z){if(Z.aborted)return Promise.reject(Z.reason);return new Promise((J,j)=>{let W=()=>j(Z.reason);Z.addEventListener("abort",W,{once:!0}),$.then((Y)=>{Z.removeEventListener("abort",W),J(Y)},(Y)=>{Z.removeEventListener("abort",W),j(Y)})})}async function AO($,Z,J){if(Z===void 0||Z===null)return null;if($==="GET"||$==="HEAD")throw TypeError(`safeFetch: a ${$} request can't have a body.`);let j=new Request("http://body.invalid/",{method:"POST",body:Z}),W=j.headers.get("content-type");if(W&&!J.has("content-type"))J.set("content-type",W);return new Uint8Array(await j.arrayBuffer())}async function EO($,Z,J,j,W,Y){let z=new AbortController,X=setTimeout(()=>z.abort(new l$($.href,"connect",W.connectTimeout)),W.connectTimeout),O=AbortSignal.any([Y,z.signal]);try{let{host:G,addresses:K,isLiteral:Q}=await SO($,W,O),U=$.protocol==="https:",F={};if(J.forEach((B,D)=>{F[D]=B}),j)F["content-length"]=String(j.byteLength);return await new Promise((B,D)=>{let T={method:Z,host:G,port:DW($),path:`${$.pathname}${$.search}`,headers:F,agent:!1,lookup:(P,V,C)=>{let S=V?.family,b=K.filter((g)=>!S||g.family===S);if(b.length===0)C(Object.assign(Error(`No IPv${S} address for ${G}`),{code:"ENOTFOUND"}));else if(V?.all)C(null,b.map((g)=>({address:mZ(g),family:g.family})));else C(null,mZ(b[0]),b[0].family)}};if(U&&!Q)T.servername=G;let M=(U?NO:IO).request(T),L=null,I=(P)=>{O.removeEventListener("abort",_),M.destroy(),D(P)},_=()=>I(O.aborted?O.reason:Y.reason);O.addEventListener("abort",_,{once:!0});let H=(P)=>{let V=P?.remoteAddress;if(!V||L!==null)return!0;let C=gZ(V);if(!C||!K.some((S)=>KW(S,C)))return I(new v1($.href,G,V,"not-allowed")),!1;return L=mZ(Y$(C)),!0};M.once("socket",(P)=>{let V=()=>{if(H(P)&&!U)clearTimeout(X)};if(P.connecting)P.once("connect",V);else V();if(U)P.once("secureConnect",()=>clearTimeout(X))}),M.once("response",(P)=>{if(clearTimeout(X),P.on("error",()=>{}),!H(P.socket))return;O.removeEventListener("abort",_),B({request:M,response:P,address:L})}),M.on("error",(P)=>{if(O.aborted)return I(O.reason);I(P instanceof U0?P:new k1($.href,P))}),M.end(j??void 0)})}finally{clearTimeout(X)}}function RO({url:$,hop:Z,method:J,request:j,response:W,address:Y,policy:z,signal:X,release:O}){let G=W.statusCode??0;if(G<200||G>599)throw j.destroy(),new k1($.href,Error(`Unexpected status ${G}`));let K=new Headers,Q=W.rawHeaders;for(let V=0;V<Q.length;V+=2)K.append(Q[V],Q[V+1]);if(z.contentTypes){let V=K.get("content-type")?.split(";")[0].trim().toLowerCase()??null;if(!V||!z.contentTypes.some((C)=>bO(V,C)))throw j.destroy(),new pZ($.href,V,z.contentTypes)}let U={url:$.href,redirected:Z>0,address:Y},F={status:G,statusText:W.statusMessage??"",headers:K};if(J==="HEAD"||LO.has(G))return j.destroy(),O(),new uZ(null,F,U);let B=K.get("content-encoding")?.trim().toLowerCase(),D=B==="gzip"||B==="x-gzip"?s$.createGunzip():B==="deflate"?s$.createInflate():B==="br"?s$.createBrotliDecompress():null,T=Number(K.get("content-length"));if(!D&&Number.isFinite(T)&&T>z.maxSize)throw j.destroy(),new i$($.href,z.maxSize);if(D)K.delete("content-encoding"),K.delete("content-length");let M=D?W.pipe(D):W,L=0,I=!1,_=()=>{},H=()=>{I=!0,X.removeEventListener("abort",_),O()},P=new ReadableStream({start(V){let C=(b)=>{if(I)return;if(H(),b===void 0)V.close();else j.destroy(),D?.destroy(),V.error(b)};if(_=()=>C(X.reason),X.addEventListener("abort",_,{once:!0}),X.aborted)return _();M.on("data",(b)=>{if(I)return;if(L+=b.byteLength,L>z.maxSize)return C(new i$($.href,z.maxSize));if(V.enqueue(new Uint8Array(b)),(V.desiredSize??1)<=0)M.pause()}),M.once("end",()=>C());let S=(b)=>C(b instanceof U0?b:new k1($.href,b));if(M.on("error",S),D)W.on("error",S);W.once("aborted",()=>C(new k1($.href,Error("The response was cut off."))))},pull(){M.resume()},cancel(){if(I)return;H(),j.destroy(),D?.destroy()}});return new uZ(P,F,U)}function bO($,Z){let J=Z.toLowerCase();return J.endsWith("/*")?$.startsWith(J.slice(0,-1)):$===J}import{createHmac as TW,randomBytes as vO}from"crypto";var c8="v2.";function u8($){return $.startsWith(c8)}function n$(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function VW($){let Z=vO(16).toString("hex"),J=TW("sha256",n$()).update(`${$}:${Z}`).digest("hex");return`${c8}${J}`}function m3($,Z){let J=TW("sha256",n$()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${c8}${J}`}import{createHash as qO,createHmac as yO,randomInt as gO,timingSafeEqual as NW}from"crypto";function MW($,Z){return Math.floor($/Z)*Z}function kO($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function d8($,Z,J,j){return Z*kO(J,j)+$}function wO($){let{current:Z,previous:J,elapsed:j,window:W,limit:Y,cost:z}=$,X=Y-z;if(X<0)return W;let O=Math.max(0,W-j);if(J>0){let K=W*(1-(X-Z)/J);if(K<=W)return Math.max(0,Math.ceil(K-j))}if(Z<=X)return O;if(Z<=0)return O;let G=W*(1-X/Z);return O+Math.max(0,Math.ceil(G))}function IW($){let{allowed:Z,current:J,previous:j,now:W,elapsed:Y,window:z,limit:X,cost:O}=$;if(Z){let K=d8(J,j,Y,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-K)),resetAt:W-Y+z,retryAfter:0}}let G=wO({current:J,previous:j,elapsed:Y,window:z,limit:X,cost:O});return{allowed:!1,limit:X,remaining:0,resetAt:W+G,retryAfter:G}}class l8{}class i8 extends l8{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:j}=$,W=$.cost??1,Y=Date.now(),z=MW(Y,j),X=Y-z,O=this.roll(Z,j,z);O.limit=J;let K=d8(O.current,O.previous,X,j)+W<=J;if(K)O.current+=W;if(this.buckets.delete(Z),this.buckets.set(Z,O),this.buckets.size>this.maxKeys)this.evict(Y);return IW({allowed:K,current:O.current,previous:O.previous,now:Y,elapsed:X,window:j,limit:J,cost:W})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,J){let j=this.buckets.get($);if(!j||j.window!==Z)return{window:Z,limit:0,windowStart:J,current:0,previous:0};if(j.windowStart===J)return j;if(j.windowStart+Z===J)return j.previous=j.current,j.current=0,j.windowStart=J,j;return j.previous=0,j.current=0,j.windowStart=J,j}evict($){for(let[j,W]of this.buckets)if($-W.windowStart>=W.window*2)this.buckets.delete(j);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let J=[...this.buckets].map(([j,W],Y)=>({key:j,order:Y,spent:W.limit>0?(W.current+W.previous)/W.limit:0}));J.sort((j,W)=>j.spent-W.spent||j.order-W.order);for(let{key:j}of J){if(this.buckets.size<=Z)break;this.buckets.delete(j)}}}var PW="h1.";function p3($,Z,J){let j=yO("sha256",n$()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${PW}${j}`}function dZ($,Z,J,j){let W=typeof j==="string"?j:"",Y=typeof J==="string"?J:"",z=Y.startsWith(PW),X=p3($,Z,W),O=Buffer.from(z?X:W),G=Buffer.from(Y);if(O.length!==G.length||W===""||Y==="")return NW(O,O),!1;return NW(O,G)}function _W($){let Z="";for(let J=0;J<$;J++)Z+=String(gO(0,10));return Z}var HW=320;function lZ($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>HW)return null;return Z.toLowerCase()}function h3($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>HW)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var CW=null;function xW(){try{let $=N();if(typeof $?.bound==="function"&&$.bound(e0))return $.make(e0)}catch{}return CW??=new e0({driver:new i8,limit:1000,window:60}),CW}function LW($){return $.length<=64?$:`sha256:${qO("sha256").update($).digest("hex")}`}async function o$($,Z,J,j){let W=xW(),Y=[[`auth:code-${$}:ip:${LW(m$(J))}`,j.perIp]];if(Z!==null)Y.push([`auth:code-${$}:email:${LW(Z)}`,j.perEmail]);for(let[z,X]of Y){if(!X)continue;let[O,G]=X,K=await W.consume(z,{limit:O,window:G});if(!K.allowed)throw new yZ(K)}}async function SW($,Z,J,j=10){let W=Math.max(86400,Math.ceil(j*60*(J+1)));return(await xW().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:W})).allowed}import{randomBytes as n8}from"crypto";class s8 extends A{schema={name:{string:"Invalid name",required:"Name is required","min:2":"Name must be at least 3 characters"},email:{string:"Invalid email",required:"Email is required",email:"Invalid email"},password:{"min:8":"Password must be at least 9 characters"}}}function c3($,Z,J,j=1/0){if(!Number.isInteger(Z)||Z<J||Z>j){let W=j===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${j}`;throw Error(`auth.emailCode.${$} must be ${W}, got ${Z}`)}}function o8($={}){let Z=$.length??6,J=$.expiresInMinutes??10,j=$.linkExpiresInMinutes??10080,W=$.maxAttempts??5;return c3("length",Z,4,12),c3("expiresInMinutes",J,1),c3("linkExpiresInMinutes",j,1),c3("maxAttempts",W,1),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:j,maxAttempts:W,requestLimit:{perEmail:$.requestLimit?.perEmail??[5,900],perIp:$.requestLimit?.perIp??[20,900]},verifyLimit:{perEmail:$.verifyLimit?.perEmail??[10,900],perIp:$.verifyLimit?.perIp??[50,900]},uniformMagicLinkResponse:$.uniformMagicLinkResponse??!1,send:$.send??(({email:Y,code:z})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${Y}: ${z} (set auth.emailCode.send to deliver it)`)})}}async function mO($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function AD($){return $}function fW($={}){return{basePath:"/auth",verifyEmail:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:s8,oauthProviders:{},oauthFailurePath:null,verifyPassword:mO,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>n8(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return n8(32).toString("hex")},generateMagicLinkToken:()=>n8(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:o8($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}function a8($){if($&&typeof $==="object")delete $.password;return $}function pO(){return new Proxy({},{get:($,Z)=>EW(Z)})}var AW=new WeakMap;function RW($){if($&&typeof $==="object"){for(let Z of Object.values($))RW(Z);Object.freeze($)}return $}var hO={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},cO=RW({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:hO});class r8{models;constructor($=pO()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return cO}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??z$(),j=N(X$).connection(J),W=()=>this.transaction(async()=>{if(j.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await F1()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(j.dialect!=="sqlite"||F1())return W();let z=(AW.get(j)??Promise.resolve()).then(W,W);return AW.set(j,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return a8(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return a8(Z)}async findUserByEmailAddress($,Z){return await this.run(()=>this.models.User.findUnique({where:Z?{email:$,emailVerifiedAt:{not:null}}:{email:$}}))}async findUserByVerificationToken($){if(typeof $!=="string"||$==="")return null;return await this.run(()=>this.models.User.findFirst({where:{verificationToken:$}}))}async verifyUser($){return await this.run(()=>this.models.User.update({where:{email:$},data:{emailVerifiedAt:new Date}}))}async createSession($){return await this.run(()=>this.models.Session.create({data:$,include:{user:!0}}))}async createSessionV2($){return await this.run(()=>this.models.Session.create({data:$,select:this.sessionSelect()}))}async findSession($){if(!$.token)return null;try{return await this.run(()=>this.models.Session.findUnique({where:{token:$.token},select:this.sessionSelect()}))}catch(Z){return console.error("findSession failed:",Z),null}}async updateSession($){return await this.run(()=>this.models.Session.update({where:{token:$.token},data:{expiresAt:$.expiresAt},select:this.sessionSelect()}))}async deleteSession($){if(!$.token)return;await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}))}async claimLegacySession($){if(!$.token)return!1;let{count:Z}=await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}));return Z>0}async deleteAllUserSessions($){await this.run(()=>this.models.Session.deleteMany({where:{userId:$}}))}async createPasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.create({data:{token:$.token,user:{connect:{id:$.user.id}}}}))}async findPasswordResetToken($){if(typeof $.token!=="string"||$.token==="")return null;return await this.run(()=>this.models.PasswordResetToken.findUnique({where:{token:$.token},include:{user:!0}}))}async deletePasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.delete({where:{token:$.token}}))}async findInvitation($,Z){if(typeof $!=="string"||typeof Z!=="string")return null;return await this.run(()=>this.models.OrganizationInvitation.findFirst({where:{publicId:$,email:Z}}))}async deleteInvitationById($){await this.run(()=>this.models.OrganizationInvitation.delete({where:{publicId:$}}))}async createAccount($){return await this.run(()=>this.models.Account.create({data:{userId:$.userId,organizationId:$.organizationId,organizationRole:$.organizationRole}}))}async createMagicLinkToken($){return await this.run(()=>this.models.MagicLinkToken.create({data:{email:$.email,token:$.token,pin:$.pin}}))}async findUserMagicLinkToken($){let Z=(J)=>typeof J==="string"&&J!=="";if(!Z($.email))return null;if($.token!==void 0&&!Z($.token))return null;if($.token===void 0&&!Z($.pin))return null;return await this.run(()=>$.token?this.models.MagicLinkToken.findUnique({where:{token_email:{token:$.token,email:$.email}}}):this.models.MagicLinkToken.findUnique({where:{pin_email:{pin:$.pin,email:$.email}}}))}async findMagicLinkTokenByEmail($){return await this.run(()=>this.models.MagicLinkToken.findFirst({where:{email:$},orderBy:{id:"desc"}}))}async claimMagicLinkToken($){let{count:Z}=await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{id:$}}));return Z===1}async deleteMagicLinkToken($){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$}}))}async createSocialAccount($){return await this.run(()=>this.models.SocialAccount.create({data:$}))}async findUserBySocialAccount($,Z){if(!Z)return null;let J=await this.run(()=>this.models.SocialAccount.findFirst({where:{provider:$,providerId:Z},include:{user:!0}}));return J?a8(J.user):null}async findSocialAccounts($,Z){return await this.run(()=>this.models.SocialAccount.findMany({where:{userId:$,provider:Z},orderBy:{id:"asc"}}))}async claimSocialAccount($,Z){let{count:J}=await this.run(()=>this.models.SocialAccount.updateMany({where:{id:$.id,providerId:$.providerId},data:{providerId:Z}}));return J===1}}import{randomBytes as bQ}from"crypto";function f0($,Z,J,j,W){return p0(Z,sW($,Z),J,j,W)}function p0($,Z,J,j,W,Y){let z=J2(Z,J,j);if(W&&Z!==z)throw RangeError(Ez($,Z,J,j,Y));return z}function sW($,Z){let J=$[Z];if(J===void 0)throw TypeError(RJ(Z));return J}function K0($){return $!==null&&/object|function/.test(typeof $)}function R0($,Z=Map){let J=new Z;return(j,...W)=>{if(J.has(j))return J.get(j);let Y=$(j,...W);return J.set(j,Y),Y}}function K2($){return Q$({name:$},1)}function Q$($,Z){return d0((J)=>({value:J,configurable:1,writable:!Z}),$)}function nW($){return d0((Z)=>({get:Z,configurable:1}),$)}function W6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function JZ($,Z){let J={},j=$.length;for(let W of Z)J[$[--j]]=W;return J}function d0($,Z,J){let j={};for(let W in Z)j[W]=$(Z[W],W,J);return j}function $3($,Z,J){let j={};for(let W=0;W<Z.length;W++){let Y=Z[W];j[Y]=$(Y,W,J)}return j}function uO($,Z,J){let j={};for(let W=0;W<$.length;W++)j[Z[W]]=J[$[W]];return j}function v0($,Z){let J={};for(let j of $)J[j]=Z[j];return J}function Q2($,Z){let J={};for(let j in Z)$.has(j)||(J[j]=Z[j]);return J}function U2($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function oW($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function aW($,Z,J){for(let j of $)if(Z[j]!==J[j])return 0;return 1}function rW($,Z,J){let j={...J};for(let W=0;W<Z;W++)j[$[W]]=0;return j}function v($,...Z){return(...J)=>$(...Z,...J)}function bW($){return $[0].toUpperCase()+$.substring(1)}function Z3($){return $.slice().sort()}function o3($,Z){return String(Z).padStart($,"0")}function w1($,Z){return Math.sign($-Z)}function J2($,Z,J){return Math.min(Math.max($,Z),J)}function T1($,Z){return[Math.floor($/Z),sZ($,Z)]}function sZ($,Z){return($%Z+Z)%Z}function g1($,Z){return[Y6($,Z),B2($,Z)]}function Y6($,Z){return Math.trunc($/Z)||0}function B2($,Z){return $%Z||0}function u3($){return Math.abs($%1)===0.5}function tW($,Z,J){let j=0,W=0;for(let X=0;X<=Z;X++){let O=$[J[X]],G=Z1[X],K=c/G,[Q,U]=g1(O,K);j+=U*G,W+=Q}let[Y,z]=g1(j,c);return[W+Y,z]}function z6($,Z,J){let j={};for(let W=Z;W>=0;W--){let Y=Z1[W];j[J[W]]=Y6($,Y),$=B2($,Y)}return j}function eW($){return $===w?p6:[]}function $Y($){return $===w?Q3:[]}function ZY($){return $===w?["year","day"]:[]}function JY($){if($!==void 0)return a($)}function jY($){if($!==void 0)return l0($)}function F2($){if($!==void 0)return J3($)}function l0($){return zY(J3($))}function J3($){return YY(kG($))}function D2($){if($==null)throw TypeError("Cannot be null or undefined");return $}function WY($,Z){if(Z==null)throw RangeError(RJ($));return Z}function M1($){if(!K0($))throw TypeError(Az);return $}function X6($,Z,J=$){if(typeof Z!==$)throw TypeError(O3(J,Z));return Z}function YY($,Z="number"){if(!Number.isInteger($))throw RangeError(YG(Z,$));return $||0}function zY($,Z="number"){if($<=0)throw RangeError(zG(Z,$));return $}function T2($){if(typeof $=="symbol")throw TypeError(KG);return String($)}function a3($,Z){return K0($)?String($):a($,Z)}function O6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(GG($));return $}function XY($,Z="number"){if(typeof $=="bigint")throw TypeError(OG(Z));if($=Number($),!Number.isFinite($))throw RangeError(XG(Z,$));return $}function I0($,Z){return Math.trunc(XY($,Z))||0}function OY($,Z){return YY(XY($,Z),Z)}function vW($,Z){return zY(I0($,Z),Z)}function V2($,Z){let[J,j]=g1(Z,c),W=$+J,Y=Math.sign(W);return Y&&Y===-Math.sign(j)&&(W-=Y,j+=Y*c),[W,j]}function r$($,Z,J=1){return V2($[0]+Z[0]*J,$[1]+Z[1]*J)}function t$($,Z){return V2($[0],$[1]+Z)}function y0($,Z){return r$(Z,$,-1)}function C0($,Z){return w1($[0],Z[0])||w1($[1],Z[1])}function GY($,Z,J){return C0($,Z)===-1||C0($,J)===1}function G6($,Z=1){let J=BigInt(c/Z);return[Number($/J),Number($%J)*Z]}function e$($,Z=1){let J=c/Z,[j,W]=g1($,J);return[j,W*Z]}function KY($,Z=1){let[J,j]=$,W=Math.floor(j/Z),Y=c/Z;return BigInt(J)*BigInt(Y)+BigInt(W)}function g0($,Z=1,J){let[j,W]=$,[Y,z]=g1(W,Z);return j*(c/Z)+(Y+(J?z/Z:0))}function M2($,Z,J=T1){let[j,W]=$,[Y,z]=J(W,Z);return[j*(c/Z)+Y,z]}function I2($,Z){let J=$.formatToParts(Z),j={};for(let W of J)j[W.type]=W.value;return j}function N2($){return f0($,"isoYear",eZ,tZ,1),$.isoYear===eZ?f0($,"isoMonth",4,12,1):$.isoYear===tZ&&f0($,"isoMonth",1,9,1),$}function q1($){return I1({...$,...u0,isoHour:12}),$}function I1($){let Z=f0($,"isoYear",eZ,tZ,1),J=Z===eZ?1:Z===tZ?-1:0;return J&&m0(N0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function m0($){if(!$||GY($,hG,pG))throw RangeError(q6);return $}function m1($){return tW($,5,o0)[1]}function K6($){let[Z,J]=T1($,c);return[z6(J,5,o0),Z]}function QY($){return UY($)[0]}function UY($){return M2($,c0)}function L0($){return jZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function N0($){let Z=L0($);if(Z!==void 0){let[J,j]=g1(Z,E0);return[J,j*J1+($.isoMicrosecond||0)*N$+($.isoNanosecond||0)]}}function C2($,Z){let[J,j]=K6(m1($)-Z);return m0(N0({...$,isoDay:$.isoDay+j,...J}))}function r3(...$){return jZ(...$)/hz}function jZ(...$){let[Z,J]=BY(...$),j=Z.valueOf();if(!isNaN(j))return j-J*E0}function BY($,Z=1,J=1,j=0,W=0,Y=0,z=0){let X=$===eZ?1:$===tZ?-1:0,O=new Date;return O.setUTCHours(j,W,Y,z),O.setUTCFullYear($,Z-1,J+X),[O,X]}function h1($,Z){let[J,j]=t$($,Z);j<0&&(j+=c,J-=1);let[W,Y]=T1(j,J1),[z,X]=T1(Y,N$);return Q6(J*E0+W,z,X)}function Q6($,Z=0,J=0){let j=Math.ceil(Math.max(0,Math.abs($)-mG)/E0)*Math.sign($),W=new Date($-j*E0);return JZ(c6,[W.getUTCFullYear(),W.getUTCMonth()+1,W.getUTCDate()+j,W.getUTCHours(),W.getUTCMinutes(),W.getUTCSeconds(),W.getUTCMilliseconds(),Z,J])}function FY($){return[$.isoYear,$.isoMonth,$.isoDay]}function DY(){return D1}function L2($,Z){switch(Z){case 2:return P2($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function TY($){return P2($)?366:365}function P2($){return $%4==0&&($%100!=0||$%400==0)}function VY($){let[Z,J]=BY($.isoYear,$.isoMonth,$.isoDay);return sZ(Z.getUTCDay()-J,7)||7}function MY({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function dO($){let Z=L0($);if(Z<uG)return MY($);let J=I2(oJ($Z),Z),{era:j,eraYear:W}=A9(J,$Z);return[j,W]}function U6($){return U$($),B6($,1),$}function U$($){return IY($,1),$}function kW($){return aW(hJ,$,IY($))}function IY($,Z){let{isoYear:J}=$,j=f0($,"isoMonth",1,DY(),Z);return{isoYear:J,isoMonth:j,isoDay:f0($,"isoDay",1,L2(J,j),Z)}}function B6($,Z){return JZ(o0,[f0($,"isoHour",0,23,Z),f0($,"isoMinute",0,59,Z),f0($,"isoSecond",0,59,Z),f0($,"isoMillisecond",0,999,Z),f0($,"isoMicrosecond",0,999,Z),f0($,"isoNanosecond",0,999,Z)])}function y($){return $===void 0?0:W7(M1($))}function j3($,Z=0){$=i0($);let J=Y7($),j=eG($,Z);return[W7($),j,J]}function _2($){return Y7(i0($))}function NY($){return $=i0($),dJ($,9,6,1)}function WZ($,Z,J,j=9,W=0,Y=4){Z=i0(Z);let z=dJ(Z,j,W),X=S2(Z),O=B3(Z,Y),G=U3(Z,j,W,1);return z==null?z=Math.max(J,G):_Y(z,G),X=f2(X,G,1),$&&(O=((K)=>K<4?(K+2)%4:K)(O)),[z,G,X,O]}function F6($,Z=6,J){let j=S2($=A2($,j6)),W=B3($,7),Y=U3($,Z);return Y=WY(j6,Y),j=f2(j,Y,void 0,J),[Y,j,W]}function H2($){return lJ(i0($))}function CY($,Z){return x2(i0($),Z)}function x2($,Z=4){let J=PY($);return[B3($,4),...LY(U3($,Z),J)]}function LY($,Z){return $!=null?[Z1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function S2($){let Z=$[nZ];return Z===void 0?1:I0(Z,nZ)}function f2($,Z,J,j){let W=j?c:Z1[Z+1];if(W){let Y=Z1[Z];if(W%(($=p0(nZ,$,1,W/Y-(j?0:1),1))*Y))throw RangeError(O3(nZ,$))}else $=p0(nZ,$,1,J?1e9:1,1);return $}function PY($){let Z=$[Z2];if(Z!==void 0){if(typeof Z!="number"){if(T2(Z)==="auto")return;throw RangeError(O3(Z2,Z))}Z=p0(Z2,Math.floor(Z),0,9,1)}return Z}function i0($){return $===void 0?{}:M1($)}function A2($,Z){return typeof $=="string"?{[Z]:$}:M1($)}function Z0($){if($!==void 0){if(K0($))return Object.assign(Object.create(null),$);throw TypeError(Az)}}function D6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:lG[Z]})}function E2($,Z,J=9,j=0,W){let Y=Z[$];if(Y===void 0)return W?j:void 0;if(Y=T2(Y),Y==="auto")return W?j:null;let z=z2[Y];if(z===void 0&&(z=yG[Y]),z===void 0)throw RangeError(vz($,Y,z2));return p0($,z,j,J,1,K3),z}function B$($,Z,J,j=0){let W=J[$];if(W===void 0)return j;let Y=T2(W),z=Z[Y];if(z===void 0)throw RangeError(vz($,Y,Z));return z}function _Y($,Z){if(Z>$)throw RangeError(AG)}function Q0($){return{branding:d6,epochNanoseconds:$}}function D0($,Z,J){return{branding:P1,calendar:J,timeZone:Z,epochNanoseconds:$}}function J0($,Z=$.calendar){return{branding:L$,calendar:Z,...v0($7,$)}}function j0($,Z=$.calendar){return{branding:C$,calendar:Z,...v0(cJ,$)}}function G$($,Z=$.calendar){return{branding:UZ,calendar:Z,...v0(cJ,$)}}function t3($,Z=$.calendar){return{branding:BZ,calendar:Z,...v0(cJ,$)}}function s0($){return{branding:u6,...v0(ez,$)}}function i($){return{branding:l6,sign:c1($),...v0(gJ,$)}}function HY($){return QY($.epochNanoseconds)}function T6($){return M2($.epochNanoseconds,J1)[0]}function xY($){return KY($.epochNanoseconds,N$)}function SY($){return KY($.epochNanoseconds)}function fY($){return $.epochNanoseconds}function B0($){return typeof $=="string"?$:a($.id)}function YZ($,Z){return $===Z||B0($)===B0(Z)}function AY($,Z,J,j,W){let Y=K$(j),[z,X]=((T,M)=>{let L=M((T=A2(T,G2))[J7]),I=tG(T);return I=WY(G2,I),[I,L]})(W,$);if(aZ(Math.max(z,Y),X))return wW(j,z);if(!X)throw RangeError(y6);let[O,G,K]=L6(Z,J,X),Q=$J(K),U=P6(K),F=ZJ(K),B=U(G,O,j),D=F(G,O,B,z);return aZ(z,X)?wW(D,z):((T,M,L,I,_,H,P)=>{let V=c1(T),[C,S]=R2(I,pJ(L,T),L,V,_,H,P),b=b2(M,C,S);return T[p[L]]+b*V})(D,Q(B),z,G,O,Q,U)}function wW($,Z){return g0(G0($),Z1[Z],1)}function R2($,Z,J,j,W,Y,z){let X=p[J],O={...Z,[X]:Z[X]+j},G=z($,W,Z),K=z($,W,O);return[Y(G),Y(K)]}function b2($,Z,J){let j=g0(y0(Z,J));if(!j)throw RangeError(G3);return g0(y0(Z,$))/j}function EY($,Z){let[J,j,W]=F6(Z,5,1);return Q0(M6($.epochNanoseconds,J,j,W,1))}function RY($,Z,J){let{epochNanoseconds:j,timeZone:W,calendar:Y}=Z,[z,X,O]=F6(J);if(z===0&&X===1)return Z;let G=$(W);if(z===6)j=((K,Q,U,F)=>{let B=P0(U,Q),[D,T]=K(B),M=U.epochNanoseconds,L=b0(Q,D),I=b0(Q,T);if(GY(M,L,I))throw RangeError(G3);return pY(b2(M,L,I),F)?I:L})(gY,G,Z,O);else{let K=G.getOffsetNanosecondsFor(j);j=D$(G,qY(h1(j,K),z,X,O),K,2,0,1)}return D0(j,W,Y)}function bY($,Z){return J0(qY($,...F6(Z)),$.calendar)}function vY($,Z){let[J,j,W]=F6(Z,5);var Y;return s0((Y=W,v2($,W3(J,j),Y)[0]))}function kY($,Z){let J=$(Z.timeZone),j=P0(Z,J),[W,Y]=gY(j),z=g0(y0(b0(J,W),b0(J,Y)),m6,1);if(z<=0)throw RangeError(G3);return z}function wY($,Z){let{timeZone:J,calendar:j}=Z,W=((Y,z,X)=>b0(z,Y(P0(X,z))))(mY,$(J),Z);return D0(W,J,j)}function qY($,Z,J,j){return yY($,W3(Z,J),j)}function yY($,Z,J){let[j,W]=v2($,Z,J);return I1({...T$($,W),...j})}function v2($,Z,J){return K6(p1(m1($),Z,J))}function e3($){return p1($,g6,7)}function W3($,Z){return Z1[$]*Z}function gY($){let Z=mY($);return[Z,T$(Z,1)]}function mY($){return gG(6,$)}function lO($,Z,J){let j=Math.min(K$($),6);return XZ(I6(G0($,j),Z,J),j)}function V6($,Z,J,j,W,Y,z,X,O,G){if(j===0&&W===1)return $;let K=aZ(j,X)?_6(X)&&j<6&&J>=6?sO:iO:nO,[Q,U,F]=K($,Z,J,j,W,Y,z,X,O,G);return F&&j!==7&&(Q=((B,D,T,M,L,I,_,H)=>{let P=c1(B);for(let V=M+1;V<=T;V++){if(V===7&&T!==7)continue;let C=pJ(V,B);C[p[V]]+=P;let S=g0(y0(_(H(L,I,C)),D));if(S&&Math.sign(S)!==P)break;B=C}return B})(Q,U,J,Math.max(6,j),z,X,O,G)),Q}function M6($,Z,J,j,W){if(Z===6){let Y=((z)=>z[0]+z[1]/c)($);return[p1(Y,J,j),0]}return I6($,W3(Z,J),j,W)}function I6($,Z,J,j){let[W,Y]=$;j&&Y<0&&(Y+=c,W-=1);let[z,X]=T1(p1(Y,Z,J),c);return V2(W+z,X)}function p1($,Z,J){return pY($/Z,J)*Z}function pY($,Z){return JK[Z]($)}function iO($,Z,J,j,W,Y){let z=c1($),X=G0($),O=M6(X,j,W,Y),G=y0(X,O),K=Math.sign(O[0]-X[0])===z,Q=XZ(O,Math.min(J,6));return[{...$,...Q},r$(Z,G),K]}function sO($,Z,J,j,W,Y,z,X,O,G){let K=c1($),Q=g0(G0($,5)),U=W3(j,W),F=p1(Q,U,Y),[B,D]=R2(z,{...$,...mJ},6,K,X,O,G),T=F-g0(y0(B,D)),M=0;T&&Math.sign(T)!==K?Z=t$(B,F):(M+=K,F=p1(T,U,Y),Z=t$(D,F));let L=x6(F);return[{...$,...L,days:$.days+M},Z,Boolean(M)]}function nO($,Z,J,j,W,Y,z,X,O,G){let K=c1($),Q=p[j],U=pJ(j,$);j===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let F=Y6($[Q],W)*W;U[Q]=F;let[B,D]=R2(z,U,j,W*K,X,O,G),T=F+b2(Z,B,D)*K*W,M=p1(T,W,Y),L=Math.sign(M-T)===K;return U[Q]=M,[U,L?D:B,L]}function k2($,Z,J,j){let[W,Y,z,X]=((G)=>{let K=x2(G=i0(G));return[G.timeZone,...K]})(j),O=W!==void 0;return((G,K,Q,U,F,B)=>{Q=I6(Q,F,U,1);let D=K.getOffsetNanosecondsFor(Q);return h2(h1(Q,D),B)+(G?F$(e3(D)):"Z")})(O,Z(O?$(W):P$),J.epochNanoseconds,Y,z,X)}function w2($,Z,J){let[j,W,Y,z,X,O]=((G)=>{G=i0(G);let K=lJ(G),Q=PY(G),U=ZK(G),F=B3(G,4),B=U3(G,4);return[K,$K(G),U,F,...LY(B,Q)]})(J);return((G,K,Q,U,F,B,D,T,M,L)=>{U=I6(U,M,T,1);let I=G(Q).getOffsetNanosecondsFor(U);return h2(h1(U,I),L)+F$(e3(I),D)+((_,H)=>H!==1?"["+(H===2?"!":"")+B0(_)+"]":"")(Q,B)+c2(K,F)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,j,W,Y,z,X,O)}function q2($,Z){let[J,j,W,Y]=((G)=>(G=i0(G),[lJ(G),...x2(G)]))(Z);return z=$.calendar,X=J,O=Y,h2(yY($,W,j),O)+c2(z,X);var z,X,O}function y2($,Z){return J=$.calendar,j=$,W=H2(Z),$6(j)+c2(J,W);var J,j,W}function g2($,Z){return hY($.calendar,cY,$,H2(Z))}function m2($,Z){return hY($.calendar,oO,$,H2(Z))}function p2($,Z){let[J,j,W]=CY(Z);return Y=W,uY(v2($,j,J)[0],Y);var Y}function N6($,Z){let[J,j,W]=CY(Z,3);return j>1&&($={...$,...lO($,j,J)}),((Y,z)=>{let{sign:X}=Y,O=X===-1?_0(Y):Y,{hours:G,minutes:K}=O,[Q,U]=M2(G0(O,3),c0,g1);rY(Q);let F=u2(U,z),B=z>=0||!X||F;return(X<0?"-":"")+"P"+qW({Y:O$(O.years),M:O$(O.months),W:O$(O.weeks),D:O$(O.days)})+(G||K||Q||B?"T"+qW({H:O$(G),M:O$(K),S:O$(Q,B)+F}):"")})($,W)}function hY($,Z,J,j){let W=B0($),Y=j>1||j===0&&W!==w;return j===1?W===w?Z(J):$6(J):Y?$6(J)+dY(W,j===2):Z(J)}function qW($){let Z=[];for(let J in $){let j=$[J];j&&Z.push(j,J)}return Z.join("")}function h2($,Z){return $6($)+"T"+uY($,Z)}function $6($){return cY($)+"-"+h0($.isoDay)}function cY($){let{isoYear:Z}=$;return(Z<0||Z>9999?lY(Z)+o3(6,Math.abs(Z)):o3(4,Z))+"-"+h0($.isoMonth)}function oO($){return h0($.isoMonth)+"-"+h0($.isoDay)}function uY($,Z){let J=[h0($.isoHour),h0($.isoMinute)];return Z!==-1&&J.push(h0($.isoSecond)+((j,W,Y,z)=>u2(j*J1+W*N$+Y,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function F$($,Z=0){if(Z===1)return"";let[J,j]=T1(Math.abs($),m6),[W,Y]=T1(j,g6),[z,X]=T1(Y,c0);return lY($)+h0(J)+":"+h0(W)+(z||X?":"+h0(z)+u2(X):"")}function c2($,Z){if(Z!==1){let J=B0($);if(Z>1||Z===0&&J!==w)return dY(J,Z===2)}return""}function dY($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function u2($,Z){let J=o3(9,$);return J=Z===void 0?J.replace(YK,""):J.slice(0,Z),J?"."+J:""}function lY($){return $<0?"-":"+"}function O$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function aO($,Z){let{epochNanoseconds:J}=$,j=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),W=h1(J,j);return{calendar:$.calendar,...W,offsetNanoseconds:j}}function iY($,Z){let J=P0(Z,$);return{calendar:Z.calendar,...v0($7,J),offset:F$(J.offsetNanoseconds),timeZone:Z.timeZone}}function D$($,Z,J,j=0,W=0,Y,z){if(J!==void 0&&j===1&&(j===1||z))return C2(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&j!==3){let O=((G,K,Q,U)=>{let F=N0(K);U&&(Q=e3(Q));for(let B of G){let D=g0(y0(B,F));if(U&&(D=e3(D)),D===Q)return B}})(X,Z,J,Y);if(O!==void 0)return O;if(j===0)throw RangeError(PG)}return z?N0(Z):b0($,Z,W,X)}function b0($,Z,J=0,j=$.getPossibleInstantsFor(Z)){if(j.length===1)return j[0];if(J===1)throw RangeError(_G);if(j.length)return j[J===3?1:0];let W=N0(Z),Y=((X,O)=>{let G=X.getOffsetNanosecondsFor(t$(O,-c));return l2(X.getOffsetNanosecondsFor(t$(O,c))-G)})($,W),z=Y*(J===2?-1:1);return(j=$.getPossibleInstantsFor(h1(W,z)))[J===2?0:j.length-1]}function d2($){if(Math.abs($)>=c)throw RangeError(CG);return $}function l2($){if($>c)throw RangeError(LG);return $}function i2($,Z,J){return Q0(m0(r$(Z.epochNanoseconds,((j)=>{if(tY(j))throw RangeError(SG);return G0(j,5)})($?_0(J):J))))}function s2($,Z,J,j,W,Y=Object.create(null)){let z=Z(j.timeZone),X=$(j.calendar);return{...j,...t2(z,X,j,J?_0(W):W,Y)}}function n2($,Z,J,j,W=Object.create(null)){let{calendar:Y}=J;return J0(e2($(Y),J,Z?_0(j):j,W),Y)}function o2($,Z,J,j,W){let{calendar:Y}=J;return j0(C6($(Y),J,Z?_0(j):j,W),Y)}function a2($,Z,J,j,W=Object.create(null)){let Y=J.calendar,z=$(Y),X=oZ(z,J);Z&&(j=H6(j)),j.sign<0&&(X=z.dateAdd(X,{...F0,months:1}),X=T$(X,-1));let O=z.dateAdd(X,j,W);return G$(oZ(z,O),Y)}function r2($,Z,J){return s0(sY(Z,$?_0(J):J)[0])}function t2($,Z,J,j,W){let Y=G0(j,5),z=J.epochNanoseconds;if(tY(j)){let X=P0(J,$);z=r$(b0($,{...C6(Z,X,{...j,...mJ},W),...v0(o0,X)}),Y)}else z=r$(z,Y),y(W);return{epochNanoseconds:m0(z)}}function e2($,Z,J,j){let[W,Y]=sY(Z,J);return I1({...C6($,Z,{...J,...mJ,days:J.days+Y},j),...W})}function C6($,Z,J,j){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,j);y(j);let W=J.days+G0(J,5)[0];return W?q1(T$(Z,W)):Z}function oZ($,Z,J=1){return T$(Z,J-$.day(Z))}function sY($,Z){let[J,j]=G0(Z,5),[W,Y]=K6(m1($)+j);return[W,J+Y]}function T$($,Z){return Z?{...$,...Q6(L0($)+Z*E0)}:$}function L6($,Z,J){let j=$(J.calendar);return _6(J)?[J,j,Z(J.timeZone)]:[{...J,...u0},j]}function $J($){return $?fY:N0}function P6($){return $?v(t2,$):e2}function ZJ($){return $?v(tO,$):eO}function _6($){return $&&$.epochNanoseconds}function aZ($,Z){return $<=6-(_6(Z)?1:0)}function JJ($,Z,J,j,W,Y,z){let X=$(i0(z).relativeTo),O=Math.max(K$(W),K$(Y));if(aZ(O,X))return i(zZ(((D,T,M,L)=>{let I=r$(G0(D),G0(T),L?-1:1);if(!Number.isFinite(I[0]))throw RangeError(q6);return{...F0,...XZ(I,M)}})(W,Y,O,j)));if(!X)throw RangeError(y6);j&&(Y=_0(Y));let[G,K,Q]=L6(Z,J,X),U=P6(Q),F=ZJ(Q),B=U(K,G,W);return i(F(K,G,U(K,B,Y),O))}function nY($,Z,J,j,W){let Y=K$(j),[z,X,O,G,K]=((P,V,C)=>{P=A2(P,j6);let S=dJ(P),b=C(P[J7]),g=S2(P),r0=B3(P,7),m=U3(P);if(S===void 0&&m===void 0)throw RangeError(fG);return m==null&&(m=0),S==null&&(S=Math.max(m,V)),_Y(S,m),g=f2(g,m,1),[S,m,g,r0,b]})(W,Y,$),Q=Math.max(Y,z);if(!_6(K)&&Q<=6)return i(zZ(((P,V,C,S,b)=>{let g=M6(G0(P),C,S,b);return{...F0,...XZ(g,V)}})(j,z,X,O,G)));if(!K)throw RangeError(y6);let[U,F,B]=L6(Z,J,K),D=$J(B),T=P6(B),M=ZJ(B),L=T(F,U,j),I=M(F,U,L,z),_=j.sign,H=c1(I);if(_&&H&&_!==H)throw RangeError(G3);return H&&(I=V6(I,D(L),z,X,O,G,F,U,D,T)),i(I)}function oY($){return $.sign===-1?H6($):$}function H6($){return i(_0($))}function _0($){let Z={};for(let J of p)Z[J]=-1*$[J]||0;return Z}function aY($){return!$.sign}function c1($,Z=p){let J=0;for(let j of Z){let W=Math.sign($[j]);if(W){if(J&&J!==W)throw RangeError(xG);J=W}}return J}function zZ($){for(let Z of qG)p0(Z,$[Z],-uW,uW,1);return rY(g0(G0($),c0)),$}function rY($){if(!Number.isSafeInteger($))throw RangeError(HG)}function G0($,Z=6){return tW($,Z,p)}function XZ($,Z=6){let[J,j]=$,W=z6(j,Z,p);if(W[p[Z]]+=J*(c/Z1[Z]),!Number.isFinite(W[p[Z]]))throw RangeError(q6);return W}function x6($,Z=5){return z6($,Z,p)}function tY($){return Boolean(c1($,tz))}function K$($){let Z=9;for(;Z>0&&!$[p[Z]];Z--);return Z}function rO($,Z){return[$,Z]}function yW($){let Z=Math.floor($/s3)*s3;return[Z,Z+s3]}function eY($){let Z=u1($=a3($));if(!Z)throw RangeError(A0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(A0($));J=OZ(Z.offset)}return Z.timeZone&&zJ(Z.timeZone,1),Q0(C2(U6(Z),J))}function $9($){let Z=u1(a($));if(!Z)throw RangeError(A0($));if(Z.timeZone)return G9(Z,Z.offset?OZ(Z.offset):void 0);if(Z.m)throw RangeError(A0($));return Q9(Z)}function Z9($,Z){let J=u1(a($));if(!J||!J.timeZone)throw RangeError(A0($));let{offset:j}=J,W=j?OZ(j):void 0,[,Y,z]=j3(Z);return G9(J,W,Y,z)}function OZ($){let Z=zJ($);if(Z===void 0)throw RangeError(A0($));return Z}function J9($){let Z=u1(a($));if(!Z||Z.m)throw RangeError(A0($));return J0(K9(Z))}function S6($){let Z=u1(a($));if(!Z||Z.m)throw RangeError(A0($));return j0(Z.p?K9(Z):Q9(Z))}function j9($,Z){let J=WJ(a(Z));if(J)return jJ(J),G$(N2(U$(J)));let j=S6(Z);return G$(oZ($(j.calendar),j))}function jJ($){if($.calendar!==w)throw RangeError(V1($.calendar))}function W9($,Z){let J=YJ(a(Z));if(J)return jJ(J),t3(U$(J));let j=S6(Z),{calendar:W}=j,Y=$(W),[z,X,O]=Y.h(j),[G,K]=Y.I(z,X),[Q,U]=Y.N(G,K,O);return t3(q1(Y.P(Q,U,O)),W)}function Y9($){let Z,J=((j)=>{let W=KK.exec(j);return W?(f6(W[10]),F9(W)):void 0})(a($));if(!J){if(J=u1($),!J)throw RangeError(A0($));if(!J.p)throw RangeError(A0($));if(J.m)throw RangeError(V1("Z"));jJ(J)}if((Z=WJ($))&&kW(Z))throw RangeError(A0($));if((Z=YJ($))&&kW(Z))throw RangeError(A0($));return s0(B6(J,1))}function z9($){let Z=((J)=>{let j=BK.exec(J);return j?((W)=>{function Y(K,Q,U){let F=0,B=0;if(U&&([F,O]=T1(O,Z1[U])),K!==void 0){if(X)throw RangeError(V1(K));B=((D)=>{let T=parseInt(D);if(!Number.isFinite(T))throw RangeError(V1(D));return T})(K),z=1,Q&&(O=XJ(Q)*(Z1[U]/c0),X=1)}return F+B}let z=0,X=0,O=0,G={...JZ(p,[Y(W[2]),Y(W[3]),Y(W[4]),Y(W[5]),Y(W[6],W[7],5),Y(W[8],W[9],4),Y(W[10],W[11],3)]),...z6(O,2,p)};if(!z)throw RangeError(Rz(p));return OJ(W[1])<0&&(G=_0(G)),G})(j):void 0})(a($));if(!Z)throw RangeError(A0($));return i(zZ(Z))}function X9($){let Z=u1($)||WJ($)||YJ($);return Z?Z.calendar:$}function O9($){let Z=u1($);return Z&&(Z.timeZone||Z.m&&P$||Z.offset)||$}function G9($,Z,J=0,j=0){let W=A6($.timeZone),Y=i6(W);return D0(D$(Y,U6($),Z,J,j,!Y.v,$.m),W,Y3($.calendar))}function K9($){return U9(I1(U6($)))}function Q9($){return U9(q1(U$($)))}function U9($){return{...$,calendar:Y3($.calendar)}}function u1($){let Z=GK.exec($);return Z?((J)=>{let j=J[10],W=(j||"").toUpperCase()==="Z";return{isoYear:B9(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...F9(J.slice(5)),...f6(J[16]),p:Boolean(J[6]),m:W,offset:W?void 0:j}})(Z):void 0}function WJ($){let Z=XK.exec($);return Z?((J)=>({isoYear:B9(J),isoMonth:parseInt(J[4]),isoDay:1,...f6(J[5])}))(Z):void 0}function YJ($){let Z=OK.exec($);return Z?((J)=>({isoYear:ZZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...f6(J[3])}))(Z):void 0}function zJ($,Z){let J=QK.exec($);return J?((j,W)=>{let Y=j[4]||j[5];if(W&&Y)throw RangeError(V1(Y));return d2((a$(j[2])*m6+a$(j[3])*g6+a$(j[4])*c0+XJ(j[5]||""))*OJ(j[1]))})(J,Z):void 0}function B9($){let Z=OJ($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(V1(-0));return Z*J}function F9($){let Z=a$($[3]);return{...K6(XJ($[4]||""))[0],isoHour:a$($[1]),isoMinute:a$($[2]),isoSecond:Z===60?59:Z}}function f6($){let Z,J,j=[];if($.replace(UK,(W,Y,z)=>{let X=Boolean(Y),[O,G]=z.split("=").reverse();if(G){if(G==="u-ca")j.push(O),Z||(Z=X);else if(X||/[A-Z]/.test(G))throw RangeError(V1(W))}else{if(J)throw RangeError(V1(W));J=O}return""}),j.length>1&&Z)throw RangeError(V1($));return{timeZone:J,calendar:j[0]||w}}function XJ($){return parseInt($.padEnd(9,"0"))}function GZ($){return new RegExp(`^${$}$`,"i")}function OJ($){return $&&$!=="+"?-1:1}function a$($){return $===void 0?0:parseInt($)}function D9($){return A6(a($))}function A6($){let Z=GJ($);return typeof Z=="number"?F$(Z):Z?((J)=>{if(DK.test(J))throw RangeError(NG);return J.toLowerCase().split("/").map((j,W)=>(j.length<=3||/\d/.test(j))&&!/etc|yap/.test(j)?j.toUpperCase():j.replace(/baja|dumont|[a-z]+/g,(Y,z)=>Y.length<=2&&!W||Y==="in"||Y==="chat"?Y.toUpperCase():Y.length>2||!z?bW(Y).replace(/island|noronha|murdo|rivadavia|urville/,bW):Y)).join("/")})($):P$}function gW($){let Z=GJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:P$}function GJ($){let Z=zJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==P$?FK($):void 0}function KJ($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function QJ($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function T9($,Z,J,j,W,Y){let z=$(i0(Y).relativeTo),X=Math.max(K$(j),K$(W));if(aW(p,j,W))return 0;if(aZ(X,z))return C0(G0(j),G0(W));if(!z)throw RangeError(y6);let[O,G,K]=L6(Z,J,z),Q=$J(K),U=P6(K);return C0(Q(U(G,O,j)),Q(U(G,O,W)))}function UJ($,Z){return V$($,Z)||E6($,Z)}function V$($,Z){return w1(L0($),L0(Z))}function E6($,Z){return w1(m1($),m1(Z))}function V9($,Z){return!KJ($,Z)}function M9($,Z){return!QJ($,Z)&&!!R6($.timeZone,Z.timeZone)&&YZ($.calendar,Z.calendar)}function I9($,Z){return!UJ($,Z)&&YZ($.calendar,Z.calendar)}function N9($,Z){return!V$($,Z)&&YZ($.calendar,Z.calendar)}function C9($,Z){return!V$($,Z)&&YZ($.calendar,Z.calendar)}function L9($,Z){return!V$($,Z)&&YZ($.calendar,Z.calendar)}function P9($,Z){return!E6($,Z)}function R6($,Z){if($===Z)return 1;let J=B0($),j=B0(Z);if(J===j)return 1;try{return gW(J)===gW(j)}catch(W){}}function BJ($,Z,J,j){let W=WZ($,Z0(j),3,5),Y=b6(Z.epochNanoseconds,J.epochNanoseconds,...W);return i($?_0(Y):Y)}function FJ($,Z,J,j,W,Y){let z=k6(j.calendar,W.calendar),X=Z0(Y),[O,G,K,Q]=WZ(J,X,5),U=j.epochNanoseconds,F=W.epochNanoseconds,B=C0(F,U),D;if(B)if(O<6)D=b6(U,F,O,G,K,Q);else{let T=Z(((L,I)=>{if(!R6(L,I))throw RangeError(yz);return L})(j.timeZone,W.timeZone)),M=$(z);D=H9(M,T,j,W,B,O,X),D=V6(D,F,O,G,K,Q,M,j,fY,v(t2,T))}else D=F0;return i(J?_0(D):D)}function DJ($,Z,J,j,W){let Y=k6(J.calendar,j.calendar),z=Z0(W),[X,O,G,K]=WZ(Z,z,6),Q=N0(J),U=N0(j),F=C0(U,Q),B;if(F)if(X<=6)B=b6(Q,U,X,O,G,K);else{let D=$(Y);B=x9(D,J,j,F,X,z),B=V6(B,U,X,O,G,K,D,J,N0,e2)}else B=F0;return i(Z?_0(B):B)}function TJ($,Z,J,j,W){let Y=k6(J.calendar,j.calendar),z=Z0(W);return _9(Z,()=>$(Y),J,j,...WZ(Z,z,6,9,6),z)}function VJ($,Z,J,j,W){let Y=k6(J.calendar,j.calendar),z=Z0(W),X=WZ(Z,z,9,9,8),O=$(Y);return _9(Z,()=>O,oZ(O,J),oZ(O,j),...X,z)}function _9($,Z,J,j,W,Y,z,X,O){let G=N0(J),K=N0(j),Q;if(C0(K,G))if(W===6)Q=b6(G,K,W,Y,z,X);else{let U=Z();Q=U.dateUntil(J,j,W,O),Y===6&&z===1||(Q=V6(Q,K,W,Y,z,X,U,J,N0,C6))}else Q=F0;return i($?_0(Q):Q)}function MJ($,Z,J,j){let W=Z0(j),[Y,z,X,O]=WZ($,W,5,5),G=p1(IJ(Z,J),W3(z,X),O),K={...F0,...x6(G,Y)};return i($?_0(K):K)}function tO($,Z,J,j,W,Y){let z=C0(j.epochNanoseconds,J.epochNanoseconds);return z?W<6?S9(J.epochNanoseconds,j.epochNanoseconds,W):H9(Z,$,J,j,z,W,Y):F0}function eO($,Z,J,j,W){let Y=N0(Z),z=N0(J),X=C0(z,Y);return X?j<=6?S9(Y,z,j):x9($,Z,J,X,j,W):F0}function H9($,Z,J,j,W,Y,z){let[X,O,G]=((U,F,B,D)=>{function T(){return V={...T$(I,H++*-D),...L},C=b0(U,V),C0(_,C)===-D}let M=P0(F,U),L=v0(o0,M),I=P0(B,U),_=B.epochNanoseconds,H=0,P=IJ(M,I),V,C;if(Math.sign(P)===-D&&H++,T()&&(D===-1||T()))throw RangeError(G3);let S=g0(y0(C,_));return[M,V,S]})(Z,J,j,W);var K,Q;return{...Y===6?(K=X,Q=O,{...F0,days:f9(K,Q)}):$.dateUntil(X,O,Y,z),...x6(G)}}function x9($,Z,J,j,W,Y){let[z,X,O]=((G,K,Q)=>{let U=K,F=IJ(G,K);return Math.sign(F)===-Q&&(U=T$(K,-Q),F+=c*Q),[G,U,F]})(Z,J,j);return{...$.dateUntil(z,X,W,Y),...x6(O)}}function b6($,Z,J,j,W,Y){return{...F0,...XZ(M6(y0($,Z),j,W,Y),J)}}function S9($,Z,J){return{...F0,...XZ(y0($,Z),J)}}function f9($,Z){return v6(L0($),L0(Z))}function v6($,Z){return Math.trunc((Z-$)/E0)}function IJ($,Z){return m1(Z)-m1($)}function k6($,Z){if(!YZ($,Z))throw RangeError(kJ);return $}function $G($){function Z(W){return((Y,z)=>({...A9(Y,z),F:Y.month,day:parseInt(Y.day)}))(I2(J,W),j)}let J=oJ($),j=Z6($);return{id:$,O:ZG(Z),B:JG(Z)}}function ZG($){return R0((Z)=>{let J=L0(Z);return $(J)},WeakMap)}function JG($){let Z=$(0).year-cG;return R0((J)=>{let j,W=jZ(J-Z),Y=[],z=[];do W+=400*E0;while((j=$(W)).year<=J);do W+=(1-j.day)*E0,j.year===J&&(Y.push(W),z.push(j.F)),W-=E0;while((j=$(W)).year>=J);return{k:Y.reverse(),C:pz(z.reverse())}})}function A9($,Z){let J,j,W=E9($);if($.era){let Y=oz[Z];Y!==void 0&&(J=Z==="islamic"?"ah":$.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,""),J==="bc"||J==="b"?J="bce":J!=="ad"&&J!=="a"||(J="ce"),j=W,W=w9(j,Y[J]||0))}return{era:J,eraYear:j,year:W}}function E9($){return parseInt($.relatedYear||$.year)}function j2($){let{year:Z,F:J,day:j}=this.O($),{C:W}=this.B(Z);return[Z,W[J]+1,j]}function rZ($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*E0}function d3($){let Z=pW(this,$),J=pW(this,$-1),j=Z.length;if(j>J.length){let W=q9(this);if(W<0)return-W;for(let Y=0;Y<j;Y++)if(Z[Y]!==J[Y])return Y+1}}function l3($){return v6(rZ.call(this,$),rZ.call(this,$+1))}function mW($,Z){let{k:J}=this.B($),j=Z+1,W=J;return j>J.length&&(j=1,W=this.B($+1).k),v6(J[Z-1],W[j-1])}function i3($){return this.B($).k.length}function pW($,Z){return Object.keys($.B(Z).C)}function R9($){return Y3(a($))}function Y3($){if(($=$.toLowerCase())!==w&&$!==h6&&Z6($)!==Z6(oJ($).resolvedOptions().calendar))throw RangeError(IG($));return $}function Z6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function b9($){return this.R($)[0]}function v9($){return this.R($)[1]}function NJ($){let[Z]=this.h($);return v6(this.q(Z),L0($))+1}function k9($){let Z=VK.exec($);if(!Z)throw RangeError(VG($));return[parseInt(Z[1]),Boolean(Z[2])]}function J6($,Z,J){return $+(Z||J&&$>=J?1:0)}function W2($,Z){return $-(Z&&$>=Z?1:0)}function w9($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function Y2($){return oz[y9($)]}function q9($){return vG[y9($)]}function y9($){return Z6($.id||w)}function g9($,Z,J,j){let W=d1(J,j,n0,[],lz);if(W.timeZone!==void 0){let Y=J.dateFromFields(W),z=M$(W),X=$(W.timeZone);return{epochNanoseconds:D$(Z(X),{...Y,...z},W.offset!==void 0?OZ(W.offset):void 0),timeZone:X}}return{...J.dateFromFields(W),...u0}}function m9($,Z,J,j,W,Y){let z=d1(J,W,n0,uz,lz),X=$(z.timeZone),[O,G,K]=j3(Y),Q=J.dateFromFields(z,D6(Y,O)),U=M$(z,O);return D0(D$(Z(X),{...Q,...U},z.offset!==void 0?OZ(z.offset):void 0,G,K),X,j)}function p9($,Z,J){let j=d1($,Z,n0,[],L1),W=y(J);return J0(I1({...$.dateFromFields(j,D6(J,W)),...M$(j,W)}))}function CJ($,Z,J,j=[]){let W=d1($,Z,n0,j);return $.dateFromFields(W,J)}function LJ($,Z,J,j){let W=d1($,Z,yJ,j);return $.yearMonthFromFields(W,J)}function PJ($,Z,J,j,W=[]){let Y=d1($,J,n0,W);return Z&&Y.month!==void 0&&Y.monthCode===void 0&&Y.year===void 0&&(Y.year=ZZ),$.monthDayFromFields(Y,j)}function h9($,Z){let J=y(Z);return s0(M$($1($,X2,[],1),J))}function c9($){let Z=$1($,gJ);return i(zZ({...F0,...Z}))}function d1($,Z,J,j=[],W=[]){return $1(Z,[...$.fields(J),...W].sort(),j)}function $1($,Z,J,j=!J){let W={},Y,z=0;for(let X of Z){if(X===Y)throw RangeError(QG(X));if(X==="constructor"||X==="__proto__")throw RangeError(bJ(X));let O=$[X];if(O!==void 0)z=1,dW[X]&&(O=dW[X](O,X)),W[X]=O;else if(J){if(J.includes(X))throw TypeError(RJ(X));W[X]=nz[X]}Y=X}if(j&&!z)throw TypeError(Rz(Z));return W}function M$($,Z){return B6(CK({...nz,...$}),Z)}function u9($,Z,J,j,W,Y){let z=Z0(Y),{calendar:X,timeZone:O}=J;return D0(((G,K,Q,U,F)=>{let B=z3(G,Q,U,n0,dz,cz),[D,T,M]=j3(F,2);return D$(K,{...G.dateFromFields(B,D6(F,D)),...M$(B,D)},OZ(B.offset),T,M)})($(X),Z(O),j,W,z),O,X)}function d9($,Z,J,j,W){let Y=Z0(W);return J0(((z,X,O,G)=>{let K=z3(z,X,O,n0,L1),Q=y(G);return I1({...z.dateFromFields(K,D6(G,Q)),...M$(K,Q)})})($(Z.calendar),J,j,Y))}function l9($,Z,J,j,W){let Y=Z0(W);return((z,X,O,G)=>{let K=z3(z,X,O,n0);return z.dateFromFields(K,G)})($(Z.calendar),J,j,Y)}function i9($,Z,J,j,W){let Y=Z0(W);return G$(((z,X,O,G)=>{let K=z3(z,X,O,yJ);return z.yearMonthFromFields(K,G)})($(Z.calendar),J,j,Y))}function s9($,Z,J,j,W){let Y=Z0(W);return((z,X,O,G)=>{let K=z3(z,X,O,n0);return z.monthDayFromFields(K,G)})($(Z.calendar),J,j,Y)}function n9($,Z,J){return s0(((j,W,Y)=>{let z=y(Y);return M$({...v0(X2,j),...$1(W,X2)},z)})($,Z,J))}function o9($,Z){return i((J=$,j=Z,zZ({...J,...$1(j,gJ)})));var J,j}function z3($,Z,J,j,W=[],Y=[]){let z=[...$.fields(j),...W].sort(),X=$1(Z,z,Y),O=$1(J,z);return X=$.mergeFields(X,O),$1(X,z,[])}function _J($,Z){let J=d1($,Z,sz);return $.monthDayFromFields(J)}function HJ($,Z,J){let j=d1($,Z,iz);return $.yearMonthFromFields(j,J)}function a9($,Z,J,j,W){Z=v0(J=$.fields(J),Z),j=$1(j,W=$.fields(W),[]);let Y=$.mergeFields(Z,j);return Y=$1(Y,[...J,...W].sort(),[]),$.dateFromFields(Y)}function t8($,Z){let{era:J,eraYear:j,year:W}=Z,Y=Y2($);if(J!==void 0||j!==void 0){if(J===void 0||j===void 0)throw TypeError(BG);if(!Y)throw RangeError(UG);let z=Y[J];if(z===void 0)throw RangeError(DG(J));let X=w9(j,z);if(W!==void 0&&W!==X)throw RangeError(FG);W=X}else if(W===void 0)throw TypeError(TG(Y));return W}function e8($,Z,J,j){let{month:W,monthCode:Y}=Z;if(Y!==void 0){let z=((X,O,G,K)=>{let Q=X.U(G),[U,F]=k9(O),B=J6(U,F,Q);if(F){let D=q9(X);if(D===void 0)throw RangeError(iZ);if(D>0){if(B>D)throw RangeError(iZ);if(Q===void 0){if(K===1)throw RangeError(iZ);B--}}else{if(B!==-D)throw RangeError(iZ);if(Q===void 0&&K===1)throw RangeError(iZ)}}return B})($,Y,J,j);if(W!==void 0&&W!==z)throw RangeError(wz);W=z,j=1}else if(W===void 0)throw TypeError(MG);return p0("month",W,1,$.L(J),j)}function hW($,Z,J,j,W){return f0(Z,"day",1,$.j(j,J),W)}function $2($,Z,J,j){let W=0,Y=[];for(let z of J)Z[z]!==void 0?W=1:Y.push(z);if(Object.assign($,Z),W)for(let z of j||Y)delete $[z]}function r9($){return Q0(m0(G6(O6($))))}function t9($,Z,J,j,W=w){return D0(m0(G6(O6(J))),Z(j),$(W))}function e9($,Z,J,j,W=0,Y=0,z=0,X=0,O=0,G=0,K=w){return J0(I1(U6(d0(I0,JZ(c6,[Z,J,j,W,Y,z,X,O,G])))),$(K))}function $z($,Z,J,j,W=w){return j0(q1(U$(d0(I0,{isoYear:Z,isoMonth:J,isoDay:j}))),$(W))}function Zz($,Z,J,j=w,W=1){let Y=I0(Z),z=I0(J),X=$(j);return G$(N2(U$({isoYear:Y,isoMonth:z,isoDay:I0(W)})),X)}function Jz($,Z,J,j=w,W=ZZ){let Y=I0(Z),z=I0(J),X=$(j);return t3(q1(U$({isoYear:I0(W),isoMonth:Y,isoDay:z})),X)}function jz($=0,Z=0,J=0,j=0,W=0,Y=0){return s0(B6(d0(I0,JZ(o0,[$,Z,J,j,W,Y])),1))}function Wz($=0,Z=0,J=0,j=0,W=0,Y=0,z=0,X=0,O=0,G=0){return i(zZ(d0(OY,JZ(p,[$,Z,J,j,W,Y,z,X,O,G]))))}function xJ($,Z,J=w){return D0($.epochNanoseconds,Z,J)}function Yz($){return Q0($.epochNanoseconds)}function SJ($,Z){return J0(P0(Z,$))}function fJ($,Z){return j0(P0(Z,$))}function zz($,Z,J){return HJ($(Z.calendar),J)}function Xz($,Z,J){return _J($(Z.calendar),J)}function AJ($,Z){return s0(P0(Z,$))}function Oz($,Z,J,j){let W=((Y,z,X,O)=>{let G=_2(O);return b0(Y(z),X,G)})($,J,Z,j);return D0(m0(W),J,Z.calendar)}function Gz($,Z,J){let j=$(Z.calendar);return G$({...Z,...HJ(j,J)})}function Kz($,Z,J){return _J($(Z.calendar),J)}function Qz($,Z,J,j,W){let Y=$(W.timeZone),z=W.plainTime,X=z!==void 0?Z(z):u0;return D0(b0(J(Y),{...j,...X}),Y,j.calendar)}function Uz($,Z=u0){return J0(I1({...$,...Z}))}function Bz($,Z,J){return HJ($(Z.calendar),J)}function Fz($,Z,J){return _J($(Z.calendar),J)}function Dz($,Z,J,j){return((W,Y,z)=>a9(W,Y,iz,M1(z),Q3))($(Z.calendar),J,j)}function Tz($,Z,J,j){return((W,Y,z)=>a9(W,Y,sz,M1(z),p6))($(Z.calendar),J,j)}function Vz($,Z,J,j,W){let Y=M1(W),z=Z(Y.plainDate),X=$(Y.timeZone);return D0(b0(J(X),{...z,...j}),X,z.calendar)}function Mz($,Z){return J0(I1({...$,...Z}))}function Iz($){return Q0(m0(e$($,c0)))}function Nz($){return Q0(m0(e$($,J1)))}function Cz($){return Q0(m0(G6(O6($),N$)))}function Lz($){return Q0(m0(G6(O6($))))}function Pz($,Z,J=u0){let j=Z.timeZone,W=$(j),Y={...P0(Z,W),...J};return D0(D$(W,Y,Y.offsetNanoseconds,2),j,Z.calendar)}function _z($,Z,J){let j=Z.timeZone,W=$(j),Y={...P0(Z,W),...J},z=fz(Z.calendar,J.calendar);return D0(D$(W,Y,Y.offsetNanoseconds,2),j,z)}function Hz($,Z=u0){return J0({...$,...Z})}function xz($,Z){return J0({...$,...Z},fz($.calendar,Z.calendar))}function w6($,Z){return{...$,calendar:Z}}function Sz($,Z){return{...$,timeZone:Z}}function fz($,Z){if($===Z)return $;let J=B0($),j=B0(Z);if(J===j||J===w)return Z;if(j===w)return $;throw RangeError(kJ)}function jG($,Z){return(J)=>J===w?$:J===h6||J===$Z?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),TK(J))}function I$($,Z,J){let j=new Set(J);return(W)=>(((Y,z)=>{for(let X of z)if(X in Y)return 1;return 0})(W=Q2(j,W),$)||Object.assign(W,Z),J&&(W.timeZone=P$,["full","long"].includes(W.timeStyle)&&(W.timeStyle="medium")),W)}function N1($,Z=EJ){let[J,,,j]=$;return(W,Y=yK,...z)=>{let X=Z(j&&j(...z),W,Y,J),O=X.resolvedOptions();return[X,...WG($,O,z)]}}function EJ($,Z,J,j){if(J=j(J),$){if(J.timeZone!==void 0)throw TypeError(EG);J.timeZone=$}return new l1(Z,J)}function WG($,Z,J){let[,j,W]=$;return J.map((Y)=>(Y.calendar&&((z,X,O)=>{if((O||z!==w)&&z!==X)throw RangeError(kJ)})(B0(Y.calendar),Z.calendar,W),j(Y,Z)))}function KZ($){let Z=X3();return h1(Z,$.getOffsetNanosecondsFor(Z))}function X3(){return e$(Date.now(),J1)}function C1(){return iW||(iW=new l1().resolvedOptions().timeZone)}var YG=($,Z)=>`Non-integer ${$}: ${Z}`,zG=($,Z)=>`Non-positive ${$}: ${Z}`,XG=($,Z)=>`Non-finite ${$}: ${Z}`,OG=($)=>`Cannot convert bigint to ${$}`,GG=($)=>`Invalid bigint: ${$}`,KG="Cannot convert Symbol to string",Az="Invalid object",Ez=($,Z,J,j,W)=>W?Ez($,W[Z],W[J],W[j]):O3($,Z)+`; must be between ${J}-${j}`,O3=($,Z)=>`Invalid ${$}: ${Z}`,RJ=($)=>`Missing ${$}`,bJ=($)=>`Invalid field ${$}`,QG=($)=>`Duplicate field ${$}`,Rz=($)=>"No valid fields: "+$.join(),bz="Invalid bag",vz=($,Z,J)=>O3($,Z)+"; must be "+Object.keys(J).join(),kz="Cannot use valueOf",vJ="Invalid calling context",UG="Forbidden era/eraYear",BG="Mismatching era/eraYear",FG="Mismatching year/eraYear",DG=($)=>`Invalid era: ${$}`,TG=($)=>"Missing year"+($?"/era/eraYear":""),VG=($)=>`Invalid monthCode: ${$}`,wz="Mismatching month/monthCode",MG="Missing month/monthCode",cW="Cannot guess year",iZ="Invalid leap month",qz="Invalid protocol",G3="Invalid protocol results",kJ="Mismatching Calendars",IG=($)=>`Invalid Calendar: ${$}`,yz="Mismatching TimeZones",NG="Forbidden ICU TimeZone",CG="Out-of-bounds offset",LG="Out-of-bounds TimeZone gap",PG="Invalid TimeZone offset",_G="Ambiguous offset",q6="Out-of-bounds date",HG="Out-of-bounds duration",xG="Cannot mix duration signs",y6="Missing relativeTo",SG="Cannot use large units",fG="Required smallestUnit or largestUnit",AG="smallestUnit > largestUnit",A0=($)=>`Cannot parse: ${$}`,V1=($)=>`Invalid substring: ${$}`,gz=($)=>`Cannot format ${$}`,mz="Mismatching types for formatting",EG="Cannot specify TimeZone",pz=v($3,($,Z)=>Z),QZ=v($3,($,Z,J)=>J),h0=v(o3,2),z2={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},K3=Object.keys(z2),E0=86400000,hz=1000,N$=1000,J1=1e6,c0=1e9,g6=60000000000,m6=3600000000000,c=86400000000000,Z1=[1,N$,J1,c0,g6,m6,c],L1=K3.slice(0,6),X2=Z3(L1),cz=["offset"],uz=["timeZone"],dz=L1.concat(cz),lz=dz.concat(uz),O2=["era","eraYear"],RG=O2.concat(["year"]),p6=["year"],wJ=["monthCode"],qJ=["month"].concat(wJ),Q3=["day"],yJ=qJ.concat(p6),iz=wJ.concat(p6),n0=Q3.concat(yJ),bG=Q3.concat(qJ),sz=Q3.concat(wJ),nz=QZ(L1,0),w="iso8601",h6="gregory",$Z="japanese",oz={[h6]:{bce:-1,ce:0},[$Z]:{bce:-1,ce:0,meiji:1867,taisho:1911,showa:1925,heisei:1988,reiwa:2018},ethioaa:{era0:0},ethiopic:{era0:0,era1:5500},coptic:{era0:-1,era1:0},roc:{beforeroc:-1,minguo:0},buddhist:{be:0},islamic:{ah:0},indian:{saka:0},persian:{ap:0}},vG={chinese:13,dangi:13,hebrew:-6},a=v(X6,"string"),az=v(X6,"boolean"),kG=v(X6,"number"),rz=v(X6,"function"),p=K3.map(($)=>$+"s"),gJ=Z3(p),wG=p.slice(0,6),tz=p.slice(6),qG=tz.slice(1),yG=pz(p),F0=QZ(p,0),mJ=QZ(wG,0),pJ=v(rW,p),o0=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],hJ=["isoDay","isoMonth","isoYear"],c6=o0.concat(hJ),cJ=Z3(hJ),ez=Z3(o0),$7=Z3(c6),u0=QZ(ez,0),gG=v(rW,c6),l1=Intl.DateTimeFormat,Z7="en-GB",uJ=1e8,mG=uJ*E0,pG=[uJ,0],hG=[-uJ,0],tZ=275760,eZ=-271821,cG=1970,ZZ=1972,D1=12,uG=jZ(1868,9,8),dG=R0(dO,WeakMap),j6="smallestUnit",G2="unit",nZ="roundingIncrement",Z2="fractionalSecondDigits",J7="relativeTo",j7={constrain:0,reject:1},lG=Object.keys(j7),iG={compatible:0,reject:1,earlier:2,later:3},sG={reject:0,use:1,prefer:2,ignore:3},nG={auto:0,never:1,critical:2,always:3},oG={auto:0,never:1,critical:2},aG={auto:0,never:1},rG={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},U3=v(E2,j6),dJ=v(E2,"largestUnit"),tG=v(E2,G2),W7=v(B$,"overflow",j7),Y7=v(B$,"disambiguation",iG),eG=v(B$,"offset",sG),lJ=v(B$,"calendarName",nG),$K=v(B$,"timeZoneName",oG),ZK=v(B$,"offset",aG),B3=v(B$,"roundingMode",rG),UZ="PlainYearMonth",BZ="PlainMonthDay",C$="PlainDate",L$="PlainDateTime",u6="PlainTime",P1="ZonedDateTime",d6="Instant",l6="Duration",JK=[Math.floor,($)=>u3($)?Math.floor($):Math.round($),Math.ceil,($)=>u3($)?Math.ceil($):Math.round($),Math.trunc,($)=>u3($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>u3($)?($=Math.trunc($)||0)+$%2:Math.round($)],P$="UTC",s3=5184000,jK=r3(1847),WK=r3(new Date().getUTCFullYear()+10),YK=/0+$/,P0=R0(aO,WeakMap),uW=4294967295,i6=R0(($)=>{let Z=GJ($);return typeof Z=="object"?new X7(Z):new z7(Z||0)});class z7{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[C2($,this.v)]}l(){}}class X7{constructor($){this.$=((Z)=>{function J(O){let G=J2(O,z,X),[K,Q]=yW(G),U=W(K),F=W(Q);return U===F?U:j(Y(K,Q),U,F,O)}function j(O,G,K,Q){let U,F;for(;(Q===void 0||(U=Q<O[0]?G:Q>=O[1]?K:void 0)===void 0)&&(F=O[1]-O[0]);){let B=O[0]+Math.floor(F/2);Z(B)===K?O[1]=B:O[0]=B+1}return U}let W=R0(Z),Y=R0(rO),z=jK,X=WK;return{G(O){let G=J(O-86400),K=J(O+86400),Q=O-G,U=O-K;if(G===K)return[Q];let F=J(Q);return F===J(U)?[O-F]:G>K?[Q,U]:[]},V:J,l(O,G){let K=J2(O,z,X),[Q,U]=yW(K),F=s3*G,B=G<0?()=>U>z||(z=K,0):()=>Q<X||(X=K,0);for(;B();){let D=W(Q),T=W(U);if(D!==T){let M=Y(Q,U);j(M,D,T);let L=M[0];if((w1(L,O)||1)===G)return L}Q+=F,U+=F}}}})(((Z)=>(J)=>{let j=I2(Z,J*hz);return r3(E9(j),parseInt(j.month),parseInt(j.day),parseInt(j.hour),parseInt(j.minute),parseInt(j.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(QY($))*c0}getPossibleInstantsFor($){let[Z,J]=[r3((j=$).isoYear,j.isoMonth,j.isoDay,j.isoHour,j.isoMinute,j.isoSecond),j.isoMillisecond*J1+j.isoMicrosecond*N$+j.isoNanosecond];var j;return this.$.G(Z).map((W)=>m0(t$(e$(W,c0),J)))}l($,Z){let[J,j]=UY($),W=this.$.l(J+(Z>0||j?1:0),Z);if(W!==void 0)return e$(W,c0)}}var iJ="([+\u2212-])",n3="(?:[.,](\\d{1,9}))?",O7=`(?:(?:${iJ}(\\d{6}))|(\\d{4}))-?(\\d{2})`,sJ="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+n3+")?)?",nJ=iJ+sJ,zK=O7+"-?(\\d{2})(?:[T ]"+sJ+"(Z|"+nJ+")?)?",G7="\\[(!?)([^\\]]*)\\]",s6=`((?:${G7}){0,9})`,XK=GZ(O7+s6),OK=GZ("(?:--)?(\\d{2})-?(\\d{2})"+s6),GK=GZ(zK+s6),KK=GZ("T?"+sJ+"(?:"+nJ+")?"+s6),QK=GZ(nJ),UK=new RegExp(G7,"g"),BK=GZ(`${iJ}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${n3}H)?(?:(\\d+)${n3}M)?(?:(\\d+)${n3}S)?)?`),FK=R0(($)=>new l1(Z7,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),DK=/^(AC|AE|AG|AR|AS|BE|BS|CA|CN|CS|CT|EA|EC|IE|IS|JS|MI|NE|NS|PL|PN|PR|PS|SS|VS)T$/,TK=R0($G),oJ=R0(($)=>new l1(Z7,{calendar:$,timeZone:P$,era:"short",year:"numeric",month:"short",day:"numeric"})),VK=/^M(\d{2})(L?)$/,MK={era:a3,eraYear:I0,year:I0,month:vW,monthCode:a3,day:vW},IK=QZ(L1,I0),NK=QZ(p,OY),dW=Object.assign({},MK,IK,NK,{offset:a3}),CK=v(uO,L1,o0),lW={dateAdd($,Z,J){let j=y(J),W,{years:Y,months:z,weeks:X,days:O}=Z;if(O+=G0(Z,5)[0],Y||z)W=((G,K,Q,U,F)=>{let[B,D,T]=G.h(K);if(Q){let[M,L]=G.I(B,D);B+=Q,D=J6(M,L,G.U(B)),D=p0("month",D,1,G.L(B),F)}return U&&([B,D]=G._(B,D,U)),T=p0("day",T,1,G.j(B,D),F),G.q(B,D,T)})(this,$,Y,z,j);else{if(!X&&!O)return $;W=L0($)}return W+=(7*X+O)*E0,q1(Q6(W))},dateUntil($,Z,J){if(J<=7){let O=0,G=f9({...$,...u0},{...Z,...u0});return J===7&&([O,G]=g1(G,7)),{...F0,weeks:O,days:G}}let j=this.h($),W=this.h(Z),[Y,z,X]=((O,G,K,Q,U,F,B)=>{let D=U-G,T=F-K,M=B-Q;if(D||T){let L=Math.sign(D||T),I=O.j(U,F),_=0;if(Math.sign(M)===-L){let H=I;[U,F]=O._(U,F,-L),D=U-G,T=F-K,I=O.j(U,F),_=L<0?-H:I}if(M=B-Math.min(Q,I)+_,D){let[H,P]=O.I(G,K),[V,C]=O.I(U,F);if(T=V-H||Number(C)-Number(P),Math.sign(T)===-L){let S=L<0&&-O.L(U);D=(U-=L)-G,T=F-J6(H,P,O.U(U))+(S||O.L(U))}}}return[D,T,M]})(this,...j,...W);return J===8&&(z+=this.J(Y,j[0]),Y=0),{...F0,years:Y,months:z,days:X}},dateFromFields($,Z){let J=y(Z),j=t8(this,$),W=e8(this,$,j,J),Y=hW(this,$,W,j,J);return j0(q1(this.P(j,W,Y)),this.id||w)},yearMonthFromFields($,Z){let J=y(Z),j=t8(this,$),W=e8(this,$,j,J);return G$(N2(this.P(j,W,1)),this.id||w)},monthDayFromFields($,Z){let J=y(Z),j=!this.id,{monthCode:W,year:Y,month:z}=$,X,O,G,K,Q;if(W!==void 0){[X,O]=k9(W),Q=sW($,"day");let U=this.N(X,O,Q);if(!U)throw RangeError(cW);if([G,K]=U,z!==void 0&&z!==K)throw RangeError(wz);j&&(K=p0("month",K,1,D1,1),Q=p0("day",Q,1,L2(Y!==void 0?Y:G,K),J))}else{G=Y===void 0&&j?ZZ:t8(this,$),K=e8(this,$,G,J),Q=hW(this,$,K,G,J);let U=this.U(G);O=K===U,X=W2(K,U);let F=this.N(X,O,Q);if(!F)throw RangeError(cW);[G,K]=F}return t3(q1(this.P(G,K,Q)),this.id||w)},fields($){return Y2(this)&&$.includes("year")?[...$,...O2]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return $2(J,Z,qJ),Y2(this)&&($2(J,Z,RG),this.id===$Z&&$2(J,Z,bG,O2)),J},inLeapYear($){let[Z]=this.h($);return this.K(Z)},monthsInYear($){let[Z]=this.h($);return this.L(Z)},daysInMonth($){let[Z,J]=this.h($);return this.j(Z,J)},daysInYear($){let[Z]=this.h($);return this.X(Z)},dayOfYear:NJ,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[j,W]=this.I(Z,J);return((Y,z)=>"M"+h0(Y)+(z?"L":""))(j,W)},dayOfWeek:VY,daysInWeek(){return 7}},LK={dayOfYear:NJ,h:FY,q:jZ},PK=Object.assign({},LK,{weekOfYear:b9,yearOfWeek:v9,R($){function Z(F){return(7-F<j?7:0)-F}function J(F){let B=TY(U+F),D=F||1,T=Z(sZ(O+B*D,7));return K=(B+(T-G)*D)/7}let j=this.id?1:4,W=VY($),Y=this.dayOfYear($),z=sZ(W-1,7),X=Y-1,O=sZ(z-X,7),G=Z(O),K,Q=Math.floor((X-G)/7)+1,U=$.isoYear;return Q?Q>J(0)&&(Q=1,U++):(Q=J(-1),U--),[Q,U,K]}}),_K={dayOfYear:NJ,h:j2,q:rZ,weekOfYear:b9,yearOfWeek:v9,R(){return[]}},FZ=jG(Object.assign({},lW,PK,{h:FY,ee($){return this.id===h6?MY($):this.id===$Z?dG($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[ZZ,$]},K:P2,U(){},L:DY,J:($)=>$*D1,j:L2,X:TY,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:jZ,_:($,Z,J)=>($+=Y6(J,D1),(Z+=B2(J,D1))<1?($--,Z+=D1):Z>D1&&($++,Z-=D1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},lW,_K,{h:j2,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=d3.call(this,$);return[W2(Z,J),J===Z]},N($,Z,J){let[j,W,Y]=j2.call(this,{isoYear:ZZ,isoMonth:D1,isoDay:31}),z=d3.call(this,j),X=W===z;(w1($,W2(W,z))||w1(Number(Z),Number(X))||w1(J,Y))===1&&j--;for(let O=0;O<100;O++){let G=j-O,K=d3.call(this,G),Q=J6($,Z,K);if(Z===(Q===K)&&J<=mW.call(this,G,Q))return[G,Q]}},K($){let Z=l3.call(this,$);return Z>l3.call(this,$-1)&&Z>l3.call(this,$+1)},U:d3,L:i3,J($,Z){let J=Z+$,j=Math.sign($),W=j<0?-1:0,Y=0;for(let z=Z;z!==J;z+=j)Y+=i3.call(this,z+W);return Y},j:mW,X:l3,P($,Z,J){return Q6(rZ.call(this,$,Z,J))},q:rZ,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(q6);if(J<0)for(;Z<1;)Z+=i3.call(this,--$);else{let j;for(;Z>(j=i3.call(this,$));)Z-=j,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:J}=this.O($),{C:j}=this.B(Z);return j[J]+1},day($){return this.O($).day}})),y1="numeric",DZ=["timeZoneName"],K7={month:y1,day:y1},aJ={year:y1,month:y1},rJ=Object.assign({},aJ,{day:y1}),tJ={hour:y1,minute:y1,second:y1},eJ=Object.assign({},rJ,tJ),HK=Object.assign({},eJ,{timeZoneName:"short"}),xK=Object.keys(aJ),SK=Object.keys(K7),fK=Object.keys(rJ),AK=Object.keys(tJ),$4=["dateStyle"],EK=xK.concat($4),RK=SK.concat($4),Z4=fK.concat($4,["weekday"]),F3=AK.concat(["dayPeriod","timeStyle"]),J4=Z4.concat(F3),bK=J4.concat(DZ),vK=DZ.concat(F3),kK=DZ.concat(Z4),wK=DZ.concat(["day","weekday"],F3),qK=DZ.concat(["year","weekday"],F3),yK={},j4=[I$(J4,eJ),T6],Q7=[I$(bK,HK),T6,0,($,Z)=>{let J=B0($.timeZone);if(Z&&B0(Z.timeZone)!==J)throw RangeError(yz);return J}],W4=[I$(J4,eJ,DZ),L0],Y4=[I$(Z4,rJ,vK),L0],z4=[I$(F3,tJ,kK),($)=>m1($)/J1],X4=[I$(EK,aJ,wK),L0,1],O4=[I$(RK,K7,qK),L0,1],iW;function Y1($,Z,J,j,W){function Y(...O){if(!(this instanceof Y))throw TypeError(vJ);D7(this,Z(...O))}function z(O,G){return Object.defineProperties(function(...K){return O.call(this,X(this),...K)},K2(G))}function X(O){let G=M0(O);if(!G||G.branding!==$)throw TypeError(vJ);return G}return Object.defineProperties(Y.prototype,{...nW(d0(z,J)),...Q$(d0(z,j)),...W6("Temporal."+$)}),Object.defineProperties(Y,{...Q$(W),...K2($)}),[Y,(O)=>{let G=Object.create(Y.prototype);return D7(G,O),G},X]}function M7($){return $=$.concat("id").sort(),(Z)=>{if(!oW(Z,$))throw TypeError(qz);return Z}}function IZ($){if(M0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(bz);return $}function n6($,Z){let J={};for(let j in $)J[j]=({o:W},Y)=>{let z=M0(Y)||{},{branding:X}=z,O=X===C$||Z.includes(X)?z:x0(Y);return W[j](O)};return J}function Q4($){let Z={};for(let J in $)Z[J]=(j)=>{let{calendar:W}=j;return(Y=W,typeof Y=="string"?FZ(Y):(z=Y,Object.assign(Object.create(eK),{i:z})))[J](j);var Y,z};return Z}function a1(){throw TypeError(kz)}function T3({calendar:$}){return typeof $=="string"?new N4($):$}function U7($,Z){if(Z=Z0(Z),K0($)){let j=M0($);if(j&&j.branding===BZ)return y(Z),j;let W=C7($);return PJ(Z8(W||w),!W,$,Z)}let J=W9(FZ,$);return y(Z),J}function I7($,Z,J){return j=Z.call($,H0(Q0(J))),d2(J3(j));var j}function o6($,Z=H7){let J=Object.keys(Z).sort(),j={};for(let W of J)j[W]=v(Z[W],$,rz($[W]));return j}function u($,Z){return typeof $=="string"?i6($):o6($,Z)}function Y0($){return u($,K4)}function j1($){if(K0($)){let Z=M0($);if(Z)switch(Z.branding){case d6:return Z;case P1:return Q0(Z.epochNanoseconds)}}return eY($)}function B7($,Z,J){let j=Z.l(j1(J).epochNanoseconds,$);return j?H0(Q0(j)):null}function l($){return K0($)?(M0($)||{}).timeZone||YQ($):((Z)=>A6(O9(a(Z))))($)}function i1($,Z){if(K0($)){let J=M0($)||{};switch(J.branding){case u6:return y(Z),J;case L$:return y(Z),s0(J);case P1:return y(Z),AJ(Y0,J)}return h9($,Z)}return y(Z),Y9($)}function U4($){return $===void 0?void 0:i1($)}function TZ($,Z){if(Z=Z0(Z),K0($)){let j=M0($);return j&&j.branding===UZ?(y(Z),j):LJ(e6(V3($)),$,Z)}let J=j9(FZ,$);return y(Z),J}function s1($,Z){if(Z=Z0(Z),K0($)){let j=M0($)||{};switch(j.branding){case L$:return y(Z),j;case C$:return y(Z),J0({...j,...u0});case P1:return y(Z),SJ(Y0,j)}return p9($8(V3($)),$,Z)}let J=J9($);return y(Z),J}function x0($,Z){if(Z=Z0(Z),K0($)){let j=M0($)||{};switch(j.branding){case C$:return y(Z),j;case L$:return y(Z),j0(j);case P1:return y(Z),fJ(Y0,j)}return CJ($8(V3($)),$,Z)}let J=S6($);return y(Z),J}function N7($,Z,J){return l0(Z.call($,t(j0(J,$))))}function z1($){return(Z)=>typeof Z=="string"?FZ(Z):((J,j)=>{let W=Object.keys(j).sort(),Y={};for(let z of W)Y[z]=v(j[z],J,J[z]);return Y})(Z,$)}function r($){if(K0($)){let Z=M0($);return Z&&Z.branding===l6?Z:c9($)}return z9($)}function D3($){if($!==void 0){if(K0($)){let Z=M0($)||{};switch(Z.branding){case P1:case C$:return Z;case L$:return j0(Z)}let J=V3($);return{...g9(l,u,$8(J),$),calendar:J}}return $9($)}}function V3($){return C7($)||w}function C7($){let{calendar:Z}=$;if(Z!==void 0)return V0(Z)}function V0($){return K0($)?(M0($)||{}).calendar||NQ($):((Z)=>Y3(X9(a(Z))))($)}function VZ($,Z){if(Z=Z0(Z),K0($)){let J=M0($);if(J&&J.branding===P1)return j3(Z),J;let j=V3($);return m9(l,u,$8(j),j,$,Z)}return Z9($,Z)}function F7($){return d0((Z)=>(J)=>Z(G4(J)),$)}function G4($){return P0($,Y0)}function gK(){let $=l1.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(l1),j=function(W,Y={}){if(!(this instanceof j))return new j(W,Y);C4.set(this,((z,X={})=>{let O=new l1(z,X),G=O.resolvedOptions(),K=G.locale,Q=v0(Object.keys(X),G),U=R0(hK),F=(...B)=>{let D,T=B.map((M,L)=>{let I=M0(M),_=(I||{}).branding;if(L&&D&&D!==_)throw TypeError(mz);return D=_,I});return D?U(D)(K,Q,...T):[O,...B]};return F.u=O,F})(W,Y))};for(let W in Z){let Y=Z[W],z=W.startsWith("format")&&mK(W);typeof Y.value=="function"?Y.value=W==="constructor"?j:z||pK(W):z&&(Y.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(j,J),j}function mK($){return function(...Z){let J=C4.get(this),[j,...W]=J(...Z);return j[$](...W)}}function pK($){return function(...Z){return C4.get(this).u[$](...Z)}}function hK($){let Z=cK[$];if(!Z)throw TypeError(gz($));return N1(Z,R0(EJ))}var cK={Instant:j4,PlainDateTime:W4,PlainDate:Y4,PlainTime:z4,PlainYearMonth:X4,PlainMonthDay:O4},uK=N1(j4),dK=N1(Q7),lK=N1(W4),iK=N1(Y4),sK=N1(z4),nK=N1(X4),oK=N1(O4),B4={era:JY,eraYear:F2,year:J3,month:l0,daysInMonth:l0,daysInYear:l0,inLeapYear:az,monthsInYear:l0},r6={monthCode:a},F4={day:l0},L7={dayOfWeek:l0,dayOfYear:l0,weekOfYear:jY,yearOfWeek:F2,daysInWeek:l0},P7=Object.assign({},B4,r6,F4,L7),a6=new WeakMap,M0=a6.get.bind(a6),D7=a6.set.bind(a6),aK={...n6(B4,[UZ]),...n6(L7,[]),...n6(r6,[UZ,BZ]),...n6(F4,[BZ])},D4=Q4(P7),rK=Q4({...B4,...r6}),tK=Q4({...r6,...F4}),M3={calendarId:($)=>B0($.calendar)},eK=d0(($,Z)=>function(J){let{i:j}=this;return $(j[Z](t(j0(J,j))))},P7),$Q=$3(($)=>(Z)=>Z[$],p.concat("sign")),T4=$3(($,Z)=>(J)=>J[o0[Z]],L1),_7={epochSeconds:HY,epochMilliseconds:T6,epochMicroseconds:xY,epochNanoseconds:SY},I3=v(Q2,new Set(["branding"])),[ZQ,MZ,JQ]=Y1(BZ,v(Jz,V0),{...M3,...tK},{getISOFields:I3,getCalendar:T3,with($,Z,J){return MZ(s9(VQ,$,this,IZ(Z),J))},equals:($,Z)=>L9($,U7(Z)),toPlainDate($,Z){return t(Tz(N3,$,this,Z))},toLocaleString($,Z,J){let[j,W]=oK(Z,J,$);return j.format(W)},toString:m2,toJSON:($)=>m2($),valueOf:a1},{from:($,Z)=>MZ(U7($,Z))}),H7={getOffsetNanosecondsFor:I7,getPossibleInstantsFor($,Z,J){let j=[...Z.call($,T0(J0(J,w)))].map((Y)=>WQ(Y).epochNanoseconds),W=j.length;return W>1&&(j.sort(C0),l2(g0(y0(j[0],j[W-1])))),j}},K4={getOffsetNanosecondsFor:I7},[jQ,H0,WQ]=Y1(d6,r9,_7,{add:($,Z)=>H0(i2(0,$,r(Z))),subtract:($,Z)=>H0(i2(1,$,r(Z))),until:($,Z,J)=>d(BJ(0,$,j1(Z),J)),since:($,Z,J)=>d(BJ(1,$,j1(Z),J)),round:($,Z)=>H0(EY($,Z)),equals:($,Z)=>V9($,j1(Z)),toZonedDateTime($,Z){let J=M1(Z);return W0(xJ($,l(J.timeZone),V0(J.calendar)))},toZonedDateTimeISO:($,Z)=>W0(xJ($,l(Z))),toLocaleString($,Z,J){let[j,W]=uK(Z,J,$);return j.format(W)},toString:($,Z)=>k2(l,Y0,$,Z),toJSON:($)=>k2(l,Y0,$),valueOf:a1},{from:($)=>H0(j1($)),fromEpochSeconds:($)=>H0(Iz($)),fromEpochMilliseconds:($)=>H0(Nz($)),fromEpochMicroseconds:($)=>H0(Cz($)),fromEpochNanoseconds:($)=>H0(Lz($)),compare:($,Z)=>KJ(j1($),j1(Z))}),[t6,gD]=Y1("TimeZone",($)=>{let Z=D9($);return{branding:"TimeZone",id:Z,o:i6(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(s1(Z)).map((J)=>H0(Q0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(j1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=j1(Z).epochNanoseconds,j=o6(this,K4).getOffsetNanosecondsFor(J);return F$(j)},getPlainDateTimeFor($,Z,J=w){let j=j1(Z).epochNanoseconds,W=o6(this,K4).getOffsetNanosecondsFor(j);return T0(J0(h1(j,W),V0(J)))},getInstantFor($,Z,J){let j=s1(Z),W=_2(J),Y=o6(this);return H0(Q0(b0(Y,j,W)))},getNextTransition:({o:$},Z)=>B7(1,$,Z),getPreviousTransition:({o:$},Z)=>B7(-1,$,Z),equals($,Z){return!!R6(this,l(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=l($);return typeof Z=="string"?new t6(Z):Z}}),YQ=M7(Object.keys(H7)),[zQ,n1]=Y1(u6,jz,T4,{getISOFields:I3,with($,Z,J){return n1(n9(this,IZ(Z),J))},add:($,Z)=>n1(r2(0,$,r(Z))),subtract:($,Z)=>n1(r2(1,$,r(Z))),until:($,Z,J)=>d(MJ(0,$,i1(Z),J)),since:($,Z,J)=>d(MJ(1,$,i1(Z),J)),round:($,Z)=>n1(vY($,Z)),equals:($,Z)=>P9($,i1(Z)),toZonedDateTime:($,Z)=>W0(Vz(l,x0,u,$,Z)),toPlainDateTime:($,Z)=>T0(Mz($,x0(Z))),toLocaleString($,Z,J){let[j,W]=sK(Z,J,$);return j.format(W)},toString:p2,toJSON:($)=>p2($),valueOf:a1},{from:($,Z)=>n1(i1($,Z)),compare:($,Z)=>E6(i1($),i1(Z))}),[XQ,o1,OQ]=Y1(UZ,v(Zz,V0),{...M3,...rK},{getISOFields:I3,getCalendar:T3,with($,Z,J){return o1(i9(TQ,$,this,IZ(Z),J))},add:($,Z,J)=>o1(a2(T7,0,$,r(Z),J)),subtract:($,Z,J)=>o1(a2(T7,1,$,r(Z),J)),until:($,Z,J)=>d(VJ(V7,0,$,TZ(Z),J)),since:($,Z,J)=>d(VJ(V7,1,$,TZ(Z),J)),equals:($,Z)=>C9($,TZ(Z)),toPlainDate($,Z){return t(Dz(N3,$,this,Z))},toLocaleString($,Z,J){let[j,W]=nK(Z,J,$);return j.format(W)},toString:g2,toJSON:($)=>g2($),valueOf:a1},{from:($,Z)=>o1(TZ($,Z)),compare:($,Z)=>V$(TZ($),TZ(Z))}),[GQ,T0]=Y1(L$,v(e9,V0),{...M3,...D4,...T4},{getISOFields:I3,getCalendar:T3,with($,Z,J){return T0(d9(N3,$,this,IZ(Z),J))},withCalendar:($,Z)=>T0(w6($,V0(Z))),withPlainDate:($,Z)=>T0(xz($,x0(Z))),withPlainTime:($,Z)=>T0(Hz($,U4(Z))),add:($,Z,J)=>T0(n2(_$,0,$,r(Z),J)),subtract:($,Z,J)=>T0(n2(_$,1,$,r(Z),J)),until:($,Z,J)=>d(DJ(W1,0,$,s1(Z),J)),since:($,Z,J)=>d(DJ(W1,1,$,s1(Z),J)),round:($,Z)=>T0(bY($,Z)),equals:($,Z)=>I9($,s1(Z)),toZonedDateTime:($,Z,J)=>W0(Oz(u,$,l(Z),J)),toPlainDate:($)=>t(j0($)),toPlainTime:($)=>n1(s0($)),toPlainYearMonth($){return o1(Gz(e6,$,this))},toPlainMonthDay($){return MZ(Kz(Z8,$,this))},toLocaleString($,Z,J){let[j,W]=lK(Z,J,$);return j.format(W)},toString:q2,toJSON:($)=>q2($),valueOf:a1},{from:($,Z)=>T0(s1($,Z)),compare:($,Z)=>UJ(s1($),s1(Z))}),[KQ,t,x7]=Y1(C$,v($z,V0),{...M3,...D4},{getISOFields:I3,getCalendar:T3,with($,Z,J){return t(l9(N3,$,this,IZ(Z),J))},withCalendar:($,Z)=>t(w6($,V0(Z))),add:($,Z,J)=>t(o2(_$,0,$,r(Z),J)),subtract:($,Z,J)=>t(o2(_$,1,$,r(Z),J)),until:($,Z,J)=>d(TJ(W1,0,$,x0(Z),J)),since:($,Z,J)=>d(TJ(W1,1,$,x0(Z),J)),equals:($,Z)=>N9($,x0(Z)),toZonedDateTime($,Z){let J=!K0(Z)||Z instanceof t6?{timeZone:Z}:Z;return W0(Qz(l,i1,u,$,J))},toPlainDateTime:($,Z)=>T0(Uz($,U4(Z))),toPlainYearMonth($){return o1(Bz(e6,$,this))},toPlainMonthDay($){return MZ(Fz(Z8,$,this))},toLocaleString($,Z,J){let[j,W]=iK(Z,J,$);return j.format(W)},toString:y2,toJSON:($)=>y2($),valueOf:a1},{from:($,Z)=>t(x0($,Z)),compare:($,Z)=>V$(x0($),x0(Z))}),V4={fields($,Z,J){return[...Z.call($,J)]}},S7=Object.assign({dateFromFields($,Z,J,j){return x7(Z.call($,Object.assign(Object.create(null),J),j))}},V4),f7=Object.assign({yearMonthFromFields($,Z,J,j){return OQ(Z.call($,Object.assign(Object.create(null),J),j))}},V4),A7=Object.assign({monthDayFromFields($,Z,J,j){return JQ(Z.call($,Object.assign(Object.create(null),J),j))}},V4),M4={mergeFields($,Z,J,j){return M1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),j)))}},QQ=Object.assign({},S7,M4),UQ=Object.assign({},f7,M4),BQ=Object.assign({},A7,M4),I4={dateAdd($,Z,J,j,W){return x7(Z.call($,t(j0(J,$)),d(i(j)),W))}},E7=Object.assign({},I4,{dateUntil($,Z,J,j,W,Y){return IQ(Z.call($,t(j0(J,$)),t(j0(j,$)),Object.assign(Object.create(null),Y,{largestUnit:K3[W]})))}}),FQ=Object.assign({},I4,{day:N7}),DQ=Object.assign({},E7,{day:N7}),e6=z1(f7),$8=z1(S7),Z8=z1(A7),TQ=z1(UQ),N3=z1(QQ),VQ=z1(BQ),_$=z1(I4),W1=z1(E7),T7=z1(FQ),V7=z1(DQ),[MQ,d,IQ]=Y1(l6,Wz,{...$Q,blank:aY},{with:($,Z)=>d(o9($,Z)),negated:($)=>d(H6($)),abs:($)=>d(oY($)),add:($,Z,J)=>d(JJ(D3,W1,u,0,$,r(Z),J)),subtract:($,Z,J)=>d(JJ(D3,W1,u,1,$,r(Z),J)),round:($,Z)=>d(nY(D3,W1,u,$,Z)),total:($,Z)=>AY(D3,W1,u,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):N6($)},toString:N6,toJSON:($)=>N6($),valueOf:a1},{from:($)=>d(r($)),compare:($,Z,J)=>T9(D3,_$,u,r($),r(Z),J)}),R7={toString:($)=>$.id,toJSON:($)=>$.id,...aK,dateAdd:({id:$,o:Z},J,j,W)=>t(j0(Z.dateAdd(x0(J),r(j),W),$)),dateUntil:({o:$},Z,J,j)=>d(i($.dateUntil(x0(Z),x0(J),NY(j)))),dateFromFields:({id:$,o:Z},J,j)=>t(CJ(Z,J,j,ZY($))),yearMonthFromFields:({id:$,o:Z},J,j)=>o1(LJ(Z,J,j,eW($))),monthDayFromFields:({id:$,o:Z},J,j)=>MZ(PJ(Z,0,J,j,$Y($))),fields({o:$},Z){let J=new Set(n0),j=[];for(let W of Z){if(a(W),!J.has(W))throw RangeError(bJ(W));J.delete(W),j.push(W)}return $.fields(j)},mergeFields:({o:$},Z,J)=>$.mergeFields(U2(D2(Z)),U2(D2(J)))},[N4]=Y1("Calendar",($)=>{let Z=R9($);return{branding:"Calendar",id:Z,o:FZ(Z)}},{id:($)=>$.id},R7,{from($){let Z=V0($);return typeof Z=="string"?new N4(Z):Z}}),NQ=M7(Object.keys(R7).slice(4)),[CQ,W0]=Y1(P1,v(t9,V0,l),{..._7,...M3,...F7(D4),...F7(T4),offset:($)=>F$(G4($).offsetNanoseconds),offsetNanoseconds:($)=>G4($).offsetNanoseconds,timeZoneId:($)=>B0($.timeZone),hoursInDay:($)=>kY(u,$)},{getISOFields:($)=>iY(Y0,$),getCalendar:T3,getTimeZone:({timeZone:$})=>typeof $=="string"?new t6($):$,with($,Z,J){return W0(u9(N3,u,$,this,IZ(Z),J))},withCalendar:($,Z)=>W0(w6($,V0(Z))),withTimeZone:($,Z)=>W0(Sz($,l(Z))),withPlainDate:($,Z)=>W0(_z(u,$,x0(Z))),withPlainTime:($,Z)=>W0(Pz(u,$,U4(Z))),add:($,Z,J)=>W0(s2(_$,u,0,$,r(Z),J)),subtract:($,Z,J)=>W0(s2(_$,u,1,$,r(Z),J)),until:($,Z,J)=>d(i(FJ(W1,u,0,$,VZ(Z),J))),since:($,Z,J)=>d(i(FJ(W1,u,1,$,VZ(Z),J))),round:($,Z)=>W0(RY(u,$,Z)),startOfDay:($)=>W0(wY(u,$)),equals:($,Z)=>M9($,VZ(Z)),toInstant:($)=>H0(Yz($)),toPlainDateTime:($)=>T0(SJ(Y0,$)),toPlainDate:($)=>t(fJ(Y0,$)),toPlainTime:($)=>n1(AJ(Y0,$)),toPlainYearMonth($){return o1(zz(e6,$,this))},toPlainMonthDay($){return MZ(Xz(Z8,$,this))},toLocaleString($,Z,J={}){let[j,W]=dK(Z,J,$);return j.format(W)},toString:($,Z)=>w2(Y0,$,Z),toJSON:($)=>w2(Y0,$),valueOf:a1},{from:($,Z)=>W0(VZ($,Z)),compare:($,Z)=>QJ(VZ($),VZ(Z))}),LQ=Object.defineProperties({},{...W6("Temporal.Now"),...Q$({timeZoneId:()=>C1(),instant:()=>H0(Q0(X3())),zonedDateTime:($,Z=C1())=>W0(D0(X3(),l(Z),V0($))),zonedDateTimeISO:($=C1())=>W0(D0(X3(),l($),w)),plainDateTime:($,Z=C1())=>T0(J0(KZ(Y0(l(Z))),V0($))),plainDateTimeISO:($=C1())=>T0(J0(KZ(Y0(l($))),w)),plainDate:($,Z=C1())=>t(j0(KZ(Y0(l(Z))),V0($))),plainDateISO:($=C1())=>t(j0(KZ(Y0(l($))),w)),plainTimeISO:($=C1())=>n1(s0(KZ(Y0(l($)))))})}),NZ=Object.defineProperties({},{...W6("Temporal"),...Q$({PlainYearMonth:XQ,PlainMonthDay:ZQ,PlainDate:KQ,PlainTime:zQ,PlainDateTime:GQ,ZonedDateTime:CQ,Instant:jQ,Calendar:N4,TimeZone:t6,Duration:MQ,Now:LQ})}),PQ=gK(),C4=new WeakMap,_Q=Object.defineProperties(Object.create(Intl),Q$({DateTimeFormat:PQ}));class L4 extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class HQ{}import{createHash as P4,createHmac as xQ,randomBytes as b7,timingSafeEqual as w7}from"crypto";var _4=600,q7="gemi_oauth",SQ=`__Host-${q7}`;function H4($){return $?SQ:q7}function C3($){return $.toString("base64url")}function y7($){return xQ("sha256",n$()).update(`gemi-oauth-state:${$}`).digest()}function v7($,Z){let J=P4("sha256").update($).digest(),j=P4("sha256").update(Z).digest();return w7(J,j)&&$.length===Z.length}function g7($,Z=Date.now()){let J=C3(b7(32)),j=C3(b7(32)),W=fQ(j),Y={provider:$,state:J,codeVerifier:j,expiresAt:Z+_4*1000};return{state:J,codeVerifier:j,codeChallenge:W,cookieValue:AQ(Y)}}function fQ($){return C3(P4("sha256").update($).digest())}function AQ($){let Z=C3(Buffer.from(JSON.stringify($)));return`${Z}.${C3(y7(Z))}`}function EQ($){if(typeof $!=="string"||$==="")return null;let Z=$.indexOf(".");if(Z<=0||Z!==$.lastIndexOf("."))return null;let J=$.slice(0,Z),j=Buffer.from($.slice(Z+1),"base64url"),W=y7(J);if(j.length!==W.length||!w7(j,W))return null;try{let Y=JSON.parse(Buffer.from(J,"base64url").toString("utf8"));if(typeof Y?.provider!=="string"||typeof Y?.state!=="string"||typeof Y?.codeVerifier!=="string"||typeof Y?.expiresAt!=="number")return null;return Y}catch{return null}}var r1=new Map,k7=1e4;function RQ($,Z,J){if(r1.size>=k7){for(let[j,W]of r1)if(W<=J)r1.delete(j);while(r1.size>=k7){let j=r1.keys().next().value;if(j===void 0)break;r1.delete(j)}}r1.set($,Z)}function m7($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=EQ($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let j=v7(J.state,$.returnedState),W=v7(J.provider,$.provider);if(!j||!W)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(r1.has(J.state))return{ok:!1,reason:"invalid_state"};return RQ(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var x4=new WeakMap;function vQ($){let Z=x4.get($);if(!Z)Z=$(bQ(32).toString("hex")),x4.set($,Z),Z.catch(()=>x4.delete($));return Z}async function S4($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await vQ($.hashPassword))}catch{}return!1}async function H$($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:j,...W}=J;await $.onAuthenticated({...Z,user:W})}class A4 extends Error{}function f4($){return typeof $==="string"&&$!==""?$:null}function p7($){return lZ($)}var kQ=256;function h7($){return typeof $==="string"&&$!==""&&$.length<=kQ?$:null}var J8="intended_url";function u7($){if($.cookies.get(J8))$.ctx().setCookie(J8,"",{maxAge:-1})}function c7($){let Z=$.cookies.get(J8);if(!Z)return null;u7($);try{return g$(decodeURIComponent(Z),"")||null}catch{return null}}class E4 extends A{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class d7 extends A{schema={email:{required:"Email is required",email:"Invalid email"}}}class l7 extends A{schema={password:{required:"Password is required",password:"Invalid password"}}}class s extends p8{async me(){let $=await x$.user();if(!$)throw new h8;return $}async verifyEmail($=new A){let Z=await $.input(),{userProvider:J}=N(E),j=f4(Z.get("token"));if(!j)return{email:null};let W=await J.findUserByVerificationToken(j);if(!W)return{email:null};return await J.verifyUser(W.email),{email:W.email}}async signInWithMagicLink($=new A){let Z=N(E),{userProvider:J}=Z,j=f4($.search.get("token")),W=null;try{W=lZ(decodeURIComponent($.search.get("email")??""))}catch{}if(await o$("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp}),!W||!j||!await Z.verifyMagicLinkToken(W,j))return{error:"Invalid token"};await J.verifyUser(W);let Y=await Z.createOrUpdateSession({email:W});return $.ctx().setCookie("access_token",Y.token,N(E).accessTokenCookieOptions($,Y.expiresAt)),await Z.config.onSignIn(Y,$.search.toJSON()),await H$(Z.config,{session:Y,isNewUser:!1,method:"magic-link",req:$}),{session:Y}}async verifyPinRequest($){let Z=N(E),J=await $.input(),{email:j,pin:W}=J.toJSON(),Y=lZ(j),z=h7(W);if(await o$("verify",Y,$,Z.config.emailCode.verifyLimit),!Y||!z)throw new h({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(Y,z);if(X.status==="too_many_attempts")throw new h({pin:["Too many attempts"]});if(X.status!=="ok")throw new h({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(Y),Y}async signInWithPinV2($=new A){let Z=N(E),J=await this.verifyPinRequest($),j=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",j.token,N(E).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await H$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),j}async signInWithPin($=new A){let Z=N(E),J=await this.verifyPinRequest($),j=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",j.token,N(E).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await H$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async signInV2($=new E4){let Z=await $.input(),{email:J,password:j}=Z.toJSON(),W=J.toLowerCase().trim(),Y=N(E),z=await Y.userProvider.findUserByEmailAddress(W,Y.config.verifyEmail),X=typeof j==="string"&&await S4(Y.config,j,z?.password);if(!z||!X)throw new h({invalid_credentials:["Invalid credentials"]});let O=await Y.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",O.token,N(E).accessTokenCookieOptions($,O.expiresAt)),await Y.config.onSignIn(z,$.search.toJSON()),await H$(Y.config,{session:O,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...K}=z;return K}async signIn($=new E4){let Z=await $.input(),{email:J,password:j}=Z.toJSON(),W=J.toLowerCase().trim(),Y=N(E),z=await Y.userProvider.findUserByEmailAddress(W,Y.config.verifyEmail),X=typeof j==="string"&&await S4(Y.config,j,z?.password);if(!z||!X)throw new h({invalid_credentials:["Invalid credentials"]});let O=await Y.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",O.token,N(E).accessTokenCookieOptions($,O.expiresAt)),await Y.config.onSignIn(z,$.search.toJSON()),await H$(Y.config,{session:O,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...K}=z;return K}async signUp(){let $=N(E),{userProvider:Z,config:J}=$,j=new J.signUpRequest,W=await j.input(),{email:Y,password:z,name:X,invitationId:O}=W.toJSON(),G=p7(Y);if(!G)throw new h({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new h({password:["Invalid password"]});if(O!=null&&typeof O!=="string")throw new h({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(G,!1))throw new h({email:["Email address already exists"]});let Q=await J.hashPassword(z),U=N(o).detectLocale(j),F;if(O)F=await Z.findInvitation(O,G);let B,D="";if(F)B=await Z.transaction(async()=>{await Z.deleteInvitationById(O);let T=await Z.createUser({email:G,name:X,password:Q,emailVerifiedAt:new Date,locale:U});return await Z.createAccount({organizationId:F.organizationId,userId:T.id,organizationRole:F.role}),await J.onUserCreated(T),T});else D=await J.generateEmailVerificationToken(G),B=await Z.transaction(async()=>{let T=await Z.createUser({email:G,name:X,password:Q,verificationToken:D,locale:U});return await J.onUserCreated(T),T});return await J.onSignUp(B,D,j.search.toJSON()),B}async signOut($=new A){let Z=y8($),J=N(E),{config:j}=J,W=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",N(E).accessTokenCookieOptions($,new Date(0))),N(E).cookieDomain($))$.ctx().setCookie("access_token","",{...N(E).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(W?.user)W.user.extension=await j.extendSession(W.user),await j.onSignOut(W.user);return{}}async forgotPassword($=new d7){let Z=await $.input(),J=p7(Z.get("email"));if(!J)return{};let{userProvider:j,config:W}=N(E),Y=await j.findUserByEmailAddress(J,W.verifyEmail);if(!Y)return{};let z=await W.generateForgotPasswordToken(Y);return await j.createPasswordResetToken({user:Y,token:z}),await W.onForgotPassword(Y,z),{}}async resetPassword($=new l7){let{userProvider:Z,config:J}=N(E),j=await $.input(),{password:W,token:Y}=j.toJSON(),z=f4(Y),X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new h({token:["Invalid token"]});if(NZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(NZ.Now.instant()).sign>=0)throw new h({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let G=await Z.findUserByEmailAddress(X.user.email,J.verifyEmail);if(!G)throw new h({email:["User not found"]});let K=await J.hashPassword(W);return await Z.updateUserPassword({id:G.id,password:K}),await Z.deleteAllUserSessions(G.id),await J.onResetPassword(G),{}}async changePassword($=new A){let{userProvider:Z,config:J}=N(E),j=await x$.user(),W=await $.input(),{oldPassword:Y,newPassword:z}=W.toJSON();if(typeof z!=="string")throw new h({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(j.email,J.verifyEmail);if(!(typeof Y==="string"&&await S4(J,Y,X?.password)))throw new h({oldPassword:["Incorrect password"]});let G=await J.hashPassword(z);return await Z.updateUserPassword({id:j.id,password:G}),await Z.deleteAllUserSessions(j.id),{}}async oauthRedirect($=new A){let{provider:Z}=$.params,J=N(E).config.oauthProviders[Z];if(!J)throw Error(`Invalid provider: ${Z}`);let j=q8($.rawRequest),W=g$($.search.get(j$),"");if(W)$.ctx().setCookie(J8,encodeURIComponent(W),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else u7($);let{state:Y,codeChallenge:z,cookieValue:X}=g7(Z);return $.ctx().setCookie(H4(j),X,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:_4}),{destination:await J.getRedirectUrl($,{state:Y,codeChallenge:z,codeChallengeMethod:"S256"})}}async oauthCallback($=new A){let{provider:Z}=$.params,J=N(E),{userProvider:j,config:W}=J,Y=W.oauthProviders[Z],z=q8($.rawRequest),X=H4(z),O=$.cookies.get(X);if(O!==void 0&&O!==null)$.ctx().setCookie(X,"",{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:-1});if(!Y)return this.oauthFailure($,"unknown_provider");let G=$.search.get("error");if(G)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(G)?G:"provider_error");let K=m7({provider:Z,cookieValue:O,returnedState:$.search.get("state")});if("reason"in K)return console.error(`Authentication error: OAuth callback refused (${K.reason})`),this.oauthFailure($,K.reason);if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let Q;try{Q=await Y.onCallback($,{state:K.payload.state,codeVerifier:K.payload.codeVerifier})}catch(P){if(P instanceof L4)return this.oauthFailure($,P.code);return console.error("Authentication error: OAuth provider callback failed",P),this.oauthFailure($,"provider_error")}let{name:U,username:F,providerId:B,emailVerified:D}=Q??{},T=typeof Q?.email==="string"?Q.email:void 0,M=T?h3(T):null,L=B?await j.findUserBySocialAccount(Z,B):null,I="signin";if(!L){if(!M)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,T?"invalid_email":B?"missing_email":"no_identity");if(D===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let P=N(o).detectLocale($);try{let V=await this.linkOAuthAccount({provider:Z,providerId:B,email:M,rawEmail:T,name:U,username:F,locale:P});if(V)L=V.user,I=V.action}catch(V){let C=B?await j.findUserBySocialAccount(Z,B):null;if(!C)throw V;L=C}if(!L)return this.oauthFailure($,"account_conflict")}let _=await J.createOrUpdateSessionV2({email:L.email,id:L.id});if($.ctx().setCookie("access_token",_.token,N(E).accessTokenCookieOptions($,_.expiresAt)),I==="signup")await W.onSignUp(L,"",$.search.toJSON());else await W.onSignIn(L,$.search.toJSON());await H$(J.config,{session:_,user:L,isNewUser:I==="signup",method:"oauth",req:$});let H=c7($)??W.redirectPath;return{session:_,redirectTo:H}}oauthFailure($,Z){let J=c7($),j=N(E).config.oauthFailurePath;if(j){let W=g$(j,"");if(W){let Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("error",Z),J)Y.searchParams.set(j$,J);q$.external(`${Y.pathname}${Y.search}${Y.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(j)}`)}return{session:null,error:Z,redirectTo:J}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:j,rawEmail:W,name:Y,username:z,locale:X}=$,{userProvider:O,config:G}=N(E),K=(B)=>({provider:Z,userId:B,email:j,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),Q=await O.findUserByEmailAddress(j,!1),U=W?.trim();if(!Q&&U&&U!==j)Q=await O.findUserByEmailAddress(U,!1);if(Q){if(!J)return{user:Q,action:"signin"};let B=await O.findSocialAccounts(Q.id,Z);if(B.some((T)=>T.providerId===J))return{user:Q,action:"signin"};if(B.some((T)=>T.providerId))return console.error(`Authentication error: user ${Q.id} is already linked to a different ${Z} account`),null;let D=B[0];if(D){if(!await O.claimSocialAccount(D,J))throw Error(`${Z} account link changed concurrently`)}else await O.createSocialAccount(K(Q.id));return{user:Q,action:"signin"}}return{user:await O.transaction(async()=>{let B=await O.createUser({email:j,name:Y,locale:X,emailVerifiedAt:new Date});if(J)await O.createSocialAccount(K(B.id));return await G.onUserCreated(B),B}),action:"signup"}}async createMagicLinkToken($=new A){let Z=await $.input(),J=lZ(Z.get("email")),j=N(E),{uniformMagicLinkResponse:W,requestLimit:Y}=j.config.emailCode;if(await o$("request",J,$,Y),!J)return{email:null};let{user:z,pin:X,token:O}=await j.createMagicLinkToken(J);if(z)return await j.config.onMagicLinkCreated(z,{email:J,pin:X,token:O}),{email:J};return{email:W?J:null}}async requestEmailCode($=new A){let Z=N(E),J=Z.config.emailCode;if(!J.enabled)throw new q0("Not found",{status:404});let j=await $.input(),W=h3(j.get("email"));if(await o$("request",W,$,J.requestLimit),!W)throw new h({email:["Invalid email"]});let Y=await Z.userProvider.findUserByEmailAddress(W,!1);if(Y||J.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(W,J.length);await J.send({email:W,code:z,token:X,isNewUser:!Y,req:$})}return{ok:!0}}async verifyEmailCode($=new A){let Z=N(E),{userProvider:J,config:j}=Z;if(!j.emailCode.enabled)throw new q0("Not found",{status:404});let W=await $.input(),{email:Y,code:z,name:X}=W.toJSON(),O=h3(Y),G=h7(z);if(await o$("verify",O,$,j.emailCode.verifyLimit),!O||!G)throw new h({code:["invalid_code"]});let K=await Z.verifyOneTimeCode(O,G,{claim:!1});if(K.status==="too_many_attempts")throw new h({code:["too_many_attempts"]});if(K.status!=="ok")throw new h({code:["invalid_code"]});let Q=K.row,U=await J.findUserByEmailAddress(O,!1),F=!1;if(U){if(!await J.claimMagicLinkToken(Q.id))throw new h({code:["invalid_code"]});await J.verifyUser(O)}else if(j.emailCode.createUser){let D=N(o).detectLocale($);try{U=await J.transaction(async()=>{if(!await J.claimMagicLinkToken(Q.id))throw new A4;let T=await J.createUser({email:O,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:D});return await j.onUserCreated(T),T}),F=!0}catch(T){if(T instanceof A4)throw new h({code:["invalid_code"]});throw T}}else throw await J.claimMagicLinkToken(Q.id),new h({code:["invalid_code"]});let B=await Z.createOrUpdateSessionV2({email:O,id:U.id});return $.ctx().setCookie("access_token",B.token,N(E).accessTokenCookieOptions($,B.expiresAt)),await j.onSignIn(B,$.search.toJSON()),await H$(Z.config,{session:B,isNewUser:F,method:"email-code",req:$}),{session:B,isNewUser:F}}}class i7 extends E1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[s,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[s,"oauthCallback"])}}class R4 extends E1{middlewares=["cache:private"];routes={"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[s,"signInWithMagicLink"]),"/oauth":i7}}class b4 extends S0{middlewares=["cache:private"];routes={"/sign-in":this.post(s,"signIn"),"/sign-in-v2":this.post(s,"signInV2"),"/sign-up":this.post(s,"signUp"),"/sign-out":this.post(s,"signOut"),"/forgot-password":this.post(s,"forgotPassword"),"/reset-password":this.post(s,"resetPassword"),"/change-password":this.post(s,"changePassword"),"/verify-email":this.post(s,"verifyEmail"),"/me":this.get(s,"me").middleware(["auth"]),"/magic-link":this.post(s,"createMagicLinkToken"),"/sign-in-with-pin":this.post(s,"signInWithPin"),"/sign-in-with-pin-v2":this.post(s,"signInWithPinV2"),"/email-code":this.post(s,"requestEmailCode"),"/email-code/verify":this.post(s,"verifyEmailCode")}}class v4 extends S0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new A().params.locale;return await N(o).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new A,Z=`/${$.params.scope??""}`,J=$.params.locale,j=N(o),W=J??j.detectLocale($),Y=j.getPageTranslations(W,Z);return $.ctx().setCookie("i18n-locale",W,{expires:new Date(Date.now()+31536000000)}),{[W]:Y}})}}class k4{}class w4 extends k4{async resize($,Z){let{height:J,width:j,quality:W,fit:Y}=Z;return await(await j8("The Sharp image optimization driver"))($).resize(j>0?j:void 0,J>0?J:void 0,{fit:Y}).webp({quality:W>0?W:80,force:!0}).toBuffer()}}function _T($){return $}function s7(){return{driver:new w4}}class q4 extends S0{routes={"/resize":this.file(async()=>{let $=new A,Z=new URL($.rawRequest.url),J=Z.searchParams.get("url"),j=Number(Z.searchParams.get("w")),W=Number(Z.searchParams.get("h")),Y=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!J)return new Response(JSON.stringify({error:"url query parameter is required"}),{headers:{"Content-Type":"application/json"},status:404});let O=`${J.startsWith("http")?"":`http://localhost:${process.env.PORT||5173}`}${J}`,G=await fetch(O);if(!G.ok)return new Response(JSON.stringify({error:"Image not found",info:O}),{headers:{"Content-Type":"application/json"},status:404});let K=Buffer.from(await G.arrayBuffer()),Q=await N(n7).resize(K,{height:W,width:j,fit:Y,quality:z});G.headers.delete("Content-Type"),G.headers.delete("Content-Length");let U=new Headers(G.headers);return U.set("Content-Type","image/webp"),U.set("Content-Length",`${Q.byteLength}`),new Response(new Uint8Array(Q),{headers:U})})}}class n7{static token="image";driver;constructor($={}){this.driver=$.driver??s7().driver}resize($,Z){return this.driver.resize($,Z)}}class y4 extends S0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(N(o7).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function wQ($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[j,W=""]=J.split(":");if(j.startsWith("-")){if(Z.has(j.replace("-","")))Z.delete(j.replace("-",""))}else Z.set(j,W.split(",").filter(Boolean))}else Z.set(J,[]);return Z}var qQ={"body-limit":y3};class CZ{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:qZ($.bodyLimit)}get aliases(){return{...qQ,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!bj($))k3($,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 A,J=this.aliases,j=[];for(let[W,Y]of wQ($).entries())if(typeof W==="string"){let z=J[W];if(z){let X=new z(Z);j.push({run:()=>X.run.call(X,...Y),runsOnRefusal:a7(z)})}}else if(b3(W)){let z=new W(Z);j.push({run:z.run.bind(z),runsOnRefusal:a7(W)})}else j.push({run:W,runsOnRefusal:!1});return(async()=>{let W={};for(let Y=0;Y<j.length;Y++)try{W={...W,...await j[Y].run()}}catch(z){throw await yQ(j.slice(Y+1)),z}return W})()}}function a7($){return $?.runsOnRefusal===!0}async function yQ($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}function pT($){return $}function r7(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function t7(){return{partialRendering:!0,onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function gQ($){return"run"in $}function mQ($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function pQ($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function hQ($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function cQ($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function e7($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function g4($,Z="",J=[]){let j={};function W(Y,z,X,O,G){let K=Y==="/"?"":Y,Q=Z==="/"?"":Z,U=(`${Q}${K}`===""?"/":`${Q}${K}`).replaceAll("//","/");if(!j[U])j[U]={};j[U][z.toUpperCase()]={exec:X,middleware:[...J,...O],...G?{source:G}:{}},j[U].OPTIONS={exec:()=>{let B=new A().ctx().headers;return new Response(null,{headers:B,status:204})},middleware:[]}}for(let[Y,z]of Object.entries($)){if(cQ(z)){let X=z;for(let O of["GET","POST","PUT","DELETE"])W(Y,O,X.run.bind(X),X.middlewares);continue}if(gQ(z)){let X=z,O=X.method,G=X.middlewares,K=X.run.bind(X);if(W(Y,O,K,G,X.source),e7(z))W(Y,"HEAD",K,G,X.source)}if(mQ(z))for(let[X,O]of Object.entries(z)){let G=O,K=G.middlewares,Q=G.run.bind(G);if(W(Y,X,Q,K,G.source),X==="get"&&e7(G))W(Y,"HEAD",Q,K,G.source)}if(hQ(z)){let X=new z,O=g4(X.routes,`${Z}${Y}`,X.middlewares);for(let[G,K]of Object.entries(O))j[G.replaceAll("//","/")]=K}if(pQ(z)){let{first:X,second:O}=z;for(let[G,K]of Object.entries(X)){let Q=K.middlewares,U=K.run.bind(K),[F,...B]=Y.split("/").reverse();if(!F.startsWith(":"))throw Error("Resource route must end with a dynamic segment");W(B.reverse().join("/"),G,U,Q,K.source)}for(let[G,K]of Object.entries(O)){let Q=K.middlewares,U=K.run.bind(K);W(Y,G,U,Q,K.source)}}}return Object.fromEntries(Object.entries(j).sort(([Y],[z])=>{let X=Y.split("/").length+Y.split(":").length,O=z.split("/").length+z.split(":").length;return X-O}))}function W8($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function m4($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function p4($){let Z=W8($);return Z.length>1?Z.replace(/\/$/,""):Z}function $5($,Z){return Z.map((J)=>({...J,path:p4(m4($,J.path))}))}function Y8($){let Z={};for(let[J,j]of Object.entries($))if("run"in j){let W=j;if("children"in W){let Y=new W.children,z=Y8(Y.routes);for(let[X,{exec:O,middleware:G,segments:K,features:Q,static:U}]of Object.entries(z)){let F=m4(J,X),B=(D)=>W.run.call(W,D,J);Z[W8(F)]={exec:[B,...O],middleware:[...W.middlewares,...G],features:[...W.featureGates,...Q],viewPath:W.viewPath,segments:[{path:p4(J),viewPath:W.viewPath,...W.alwaysRuns?{alwaysRun:!0}:{}},...$5(J,K)],...U?{static:U}:{}}}}else{let Y=(z)=>W.run.call(W,z,J);Z[W8(J)]={exec:[Y],middleware:W.middlewares,features:W.featureGates,viewPath:W.viewPath,segments:[{path:p4(J),viewPath:W.viewPath}],..."staticOptions"in W&&W.staticOptions?{static:W.staticOptions}:{}}}}else{let W=new j,Y=Y8(W.routes);for(let[z,{exec:X,middleware:O,viewPath:G,segments:K,features:Q,static:U}]of Object.entries(Y)){let F=m4(J,z);Z[W8(F)]={exec:X,middleware:[...W.middlewares,...O],features:[...W.featureGates,...Q],viewPath:G,segments:$5(J,K),...U?{static:U}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([J],[j])=>{let W=J.split("/").length+J.split(":").length,Y=j.split("/").length+j.split(":").length;return W-Y}))}var uQ=Object.defineProperty,x=($,Z)=>uQ($,"name",{value:Z,configurable:!0}),_Z=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,J,j,W,Y){this.type=$,this.name=Z,this.prefix=J,this.value=j,this.suffix=W,this.modifier=Y}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};x(_Z,"Part");var dQ=/[$_\p{ID_Start}]/u,lQ=/[$_\u200C\u200D\p{ID_Continue}]/u,c4=".*";function Z5($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}x(Z5,"isASCII");function l4($,Z=!1){let J=[],j=0;for(;j<$.length;){let W=$[j],Y=x(function(z){if(!Z)throw TypeError(z);J.push({type:"INVALID_CHAR",index:j,value:$[j++]})},"ErrorOrInvalid");if(W==="*"){J.push({type:"ASTERISK",index:j,value:$[j++]});continue}if(W==="+"||W==="?"){J.push({type:"OTHER_MODIFIER",index:j,value:$[j++]});continue}if(W==="\\"){J.push({type:"ESCAPED_CHAR",index:j++,value:$[j++]});continue}if(W==="{"){J.push({type:"OPEN",index:j,value:$[j++]});continue}if(W==="}"){J.push({type:"CLOSE",index:j,value:$[j++]});continue}if(W===":"){let z="",X=j+1;for(;X<$.length;){let O=$.substr(X,1);if(X===j+1&&dQ.test(O)||X!==j+1&&lQ.test(O)){z+=$[X++];continue}break}if(!z){Y(`Missing parameter name at ${j}`);continue}J.push({type:"NAME",index:j,value:z}),j=X;continue}if(W==="("){let z=1,X="",O=j+1,G=!1;if($[O]==="?"){Y(`Pattern cannot start with "?" at ${O}`);continue}for(;O<$.length;){if(!Z5($[O],!1)){Y(`Invalid character '${$[O]}' at ${O}.`),G=!0;break}if($[O]==="\\"){X+=$[O++]+$[O++];continue}if($[O]===")"){if(z--,z===0){O++;break}}else if($[O]==="("&&(z++,$[O+1]!=="?")){Y(`Capturing groups are not allowed at ${O}`),G=!0;break}X+=$[O++]}if(G)continue;if(z){Y(`Unbalanced pattern at ${j}`);continue}if(!X){Y(`Missing pattern at ${j}`);continue}J.push({type:"REGEX",index:j,value:X}),j=O;continue}J.push({type:"CHAR",index:j,value:$[j++]})}return J.push({type:"END",index:j,value:""}),J}x(l4,"lexer");function i4($,Z={}){let J=l4($);Z.delimiter??="/#?",Z.prefixes??="./";let j=`[^${k0(Z.delimiter)}]+?`,W=[],Y=0,z=0,X="",O=new Set,G=x((I)=>{if(z<J.length&&J[z].type===I)return J[z++].value},"tryConsume"),K=x(()=>G("OTHER_MODIFIER")??G("ASTERISK"),"tryConsumeModifier"),Q=x((I)=>{let _=G(I);if(_!==void 0)return _;let{type:H,index:P}=J[z];throw TypeError(`Unexpected ${H} at ${P}, expected ${I}`)},"mustConsume"),U=x(()=>{let I="",_;for(;_=G("CHAR")??G("ESCAPED_CHAR");)I+=_;return I},"consumeText"),F=x((I)=>I,"DefaultEncodePart"),B=Z.encodePart||F,D="",T=x((I)=>{D+=I},"appendToPendingFixedValue"),M=x(()=>{D.length&&(W.push(new _Z(3,"","",B(D),"",3)),D="")},"maybeAddPartFromPendingFixedValue"),L=x((I,_,H,P,V)=>{let C=3;switch(V){case"?":C=1;break;case"*":C=0;break;case"+":C=2;break}if(!_&&!H&&C===3){T(I);return}if(M(),!_&&!H){if(!I)return;W.push(new _Z(3,"","",B(I),"",C));return}let S;H?H==="*"?S=c4:S=H:S=j;let b=2;S===j?(b=1,S=""):S===c4&&(b=0,S="");let g;if(_?g=_:H&&(g=Y++),O.has(g))throw TypeError(`Duplicate name '${g}'.`);O.add(g),W.push(new _Z(b,g,B(I),S,B(P),C))},"addPart");for(;z<J.length;){let I=G("CHAR"),_=G("NAME"),H=G("REGEX");if(!_&&!H&&(H=G("ASTERISK")),_||H){let V=I??"";Z.prefixes.indexOf(V)===-1&&(T(V),V=""),M();let C=K();L(V,_,H,"",C);continue}let P=I??G("ESCAPED_CHAR");if(P){T(P);continue}if(G("OPEN")){let V=U(),C=G("NAME"),S=G("REGEX");!C&&!S&&(S=G("ASTERISK"));let b=U();Q("CLOSE");let g=K();L(V,C,S,b,g);continue}M(),Q("END")}return W}x(i4,"parse");function k0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}x(k0,"escapeString");function u4($){return $&&$.ignoreCase?"ui":"u"}x(u4,"flags");function J5($,Z,J){return s4(i4($,J),Z,J)}x(J5,"stringToRegexp");function S$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}x(S$,"modifierToString");function s4($,Z,J={}){J.delimiter??="/#?",J.prefixes??="./",J.sensitive??=!1,J.strict??=!1,J.end??=!0,J.start??=!0,J.endsWith="";let j=J.start?"^":"";for(let X of $){if(X.type===3){X.modifier===3?j+=k0(X.value):j+=`(?:${k0(X.value)})${S$(X.modifier)}`;continue}Z&&Z.push(X.name);let O=`[^${k0(J.delimiter)}]+?`,G=X.value;if(X.type===1?G=O:X.type===0&&(G=c4),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?j+=`(${G})${S$(X.modifier)}`:j+=`((?:${G})${S$(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){j+=`(?:${k0(X.prefix)}(${G})${k0(X.suffix)})`,j+=S$(X.modifier);continue}j+=`(?:${k0(X.prefix)}`,j+=`((?:${G})(?:`,j+=k0(X.suffix),j+=k0(X.prefix),j+=`(?:${G}))*)${k0(X.suffix)})`,X.modifier===0&&(j+="?")}let W=`[${k0(J.endsWith)}]|$`,Y=`[${k0(J.delimiter)}]`;if(J.end)return J.strict||(j+=`${Y}?`),J.endsWith.length?j+=`(?=${W})`:j+="$",new RegExp(j,u4(J));J.strict||(j+=`(?:${Y}(?=${W}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=J.delimiter.indexOf(X)>-1)}return z||(j+=`(?=${Y}|${W})`),new RegExp(j,u4(J))}x(s4,"partsToRegexp");var e1={delimiter:"",prefixes:"",sensitive:!0,strict:!0},iQ={delimiter:".",prefixes:"",sensitive:!0,strict:!0},sQ={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function j5($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}x(j5,"isAbsolutePathname");function n4($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}x(n4,"maybeStripPrefix");function W5($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}x(W5,"maybeStripSuffix");function o4($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}x(o4,"treatAsIPv6Hostname");var Y5=["ftp","file","http","https","ws","wss"];function a4($){if(!$)return!0;for(let Z of Y5)if($.test(Z))return!0;return!1}x(a4,"isSpecialScheme");function z5($,Z){if($=n4($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}x(z5,"canonicalizeHash");function X5($,Z){if($=n4($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}x(X5,"canonicalizeSearch");function O5($,Z){return Z||$===""?$:o4($)?e4($):t4($)}x(O5,"canonicalizeHostname");function G5($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}x(G5,"canonicalizePassword");function K5($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}x(K5,"canonicalizeUsername");function Q5($,Z,J){if(J||$==="")return $;if(Z&&!Y5.includes(Z))return new URL(`${Z}:${$}`).pathname;let j=$[0]=="/";return $=new URL(j?$:"/-"+$,"https://example.com").pathname,j||($=$.substring(2,$.length)),$}x(Q5,"canonicalizePathname");function U5($,Z,J){return r4(Z)===$&&($=""),J||$===""?$:$j($)}x(U5,"canonicalizePort");function B5($,Z){return $=W5($,":"),Z||$===""?$:z8($)}x(B5,"canonicalizeProtocol");function r4($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}x(r4,"defaultPortForProtocol");function z8($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}x(z8,"protocolEncodeCallback");function F5($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}x(F5,"usernameEncodeCallback");function D5($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}x(D5,"passwordEncodeCallback");function t4($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}x(t4,"hostnameEncodeCallback");function e4($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}x(e4,"ipv6HostnameEncodeCallback");function $j($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}x($j,"portEncodeCallback");function T5($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}x(T5,"standardURLPathnameEncodeCallback");function V5($){return $===""?$:new URL(`data:${$}`).pathname}x(V5,"pathURLPathnameEncodeCallback");function M5($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}x(M5,"searchEncodeCallback");function I5($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}x(I5,"hashEncodeCallback");var N5=class{#W;#Z=[];#J={};#$=0;#Y=1;#G=0;#X=0;#B=0;#F=0;#D=!1;constructor($){this.#W=$}get result(){return this.#J}parse(){for(this.#Z=l4(this.#W,!0);this.#$<this.#Z.length;this.#$+=this.#Y){if(this.#Y=1,this.#Z[this.#$].type==="END"){if(this.#X===0){this.#I(),this.#K()?this.#j(9,1):this.#Q()?this.#j(8,1):this.#j(7,0);continue}else if(this.#X===2){this.#U(5);continue}this.#j(10,0);break}if(this.#B>0)if(this.#x())this.#B-=1;else continue;if(this.#H()){this.#B+=1;continue}switch(this.#X){case 0:this.#N()&&this.#U(1);break;case 1:if(this.#N()){this.#A();let $=7,Z=1;this.#L()?($=2,Z=3):this.#D&&($=2),this.#j($,Z)}break;case 2:this.#V()?this.#U(3):(this.#M()||this.#Q()||this.#K())&&this.#U(5);break;case 3:this.#P()?this.#j(4,1):this.#V()&&this.#j(5,1);break;case 4:this.#V()&&this.#j(5,1);break;case 5:this.#S()?this.#F+=1:this.#f()&&(this.#F-=1),this.#_()&&!this.#F?this.#j(6,1):this.#M()?this.#j(7,0):this.#Q()?this.#j(8,1):this.#K()&&this.#j(9,1);break;case 6:this.#M()?this.#j(7,0):this.#Q()?this.#j(8,1):this.#K()&&this.#j(9,1);break;case 7:this.#Q()?this.#j(8,1):this.#K()&&this.#j(9,1);break;case 8:this.#K()&&this.#j(9,1);break;case 9:break;case 10:break}}this.#J.hostname!==void 0&&this.#J.port===void 0&&(this.#J.port="")}#j($,Z){switch(this.#X){case 0:break;case 1:this.#J.protocol=this.#O();break;case 2:break;case 3:this.#J.username=this.#O();break;case 4:this.#J.password=this.#O();break;case 5:this.#J.hostname=this.#O();break;case 6:this.#J.port=this.#O();break;case 7:this.#J.pathname=this.#O();break;case 8:this.#J.search=this.#O();break;case 9:this.#J.hash=this.#O();break;case 10:break}this.#X!==0&&$!==10&&([1,2,3,4].includes(this.#X)&&[6,7,8,9].includes($)&&(this.#J.hostname??=""),[1,2,3,4,5,6].includes(this.#X)&&[8,9].includes($)&&(this.#J.pathname??=this.#D?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#J.search??="")),this.#C($,Z)}#C($,Z){this.#X=$,this.#G=this.#$+Z,this.#$+=Z,this.#Y=0}#I(){this.#$=this.#G,this.#Y=0}#U($){this.#I(),this.#X=$}#T($){return $<0&&($=this.#Z.length-$),$<this.#Z.length?this.#Z[$]:this.#Z[this.#Z.length-1]}#z($,Z){let J=this.#T($);return J.value===Z&&(J.type==="CHAR"||J.type==="ESCAPED_CHAR"||J.type==="INVALID_CHAR")}#N(){return this.#z(this.#$,":")}#L(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#V(){return this.#z(this.#$,"@")}#P(){return this.#z(this.#$,":")}#_(){return this.#z(this.#$,":")}#M(){return this.#z(this.#$,"/")}#Q(){if(this.#z(this.#$,"?"))return!0;if(this.#Z[this.#$].value!=="?")return!1;let $=this.#T(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#K(){return this.#z(this.#$,"#")}#H(){return this.#Z[this.#$].type=="OPEN"}#x(){return this.#Z[this.#$].type=="CLOSE"}#S(){return this.#z(this.#$,"[")}#f(){return this.#z(this.#$,"]")}#O(){let $=this.#Z[this.#$],Z=this.#T(this.#G).index;return this.#W.substring(Z,$.index)}#A(){let $={};Object.assign($,e1),$.encodePart=z8;let Z=J5(this.#O(),void 0,$);this.#D=a4(Z)}};x(N5,"Parser");var h4=["protocol","username","password","hostname","port","pathname","search","hash"],t1="*";function d4($,Z){if(typeof $!="string")throw TypeError("parameter 1 is not of type 'string'.");let J=new URL($,Z);return{protocol:J.protocol.substring(0,J.protocol.length-1),username:J.username,password:J.password,hostname:J.hostname,port:J.port,pathname:J.pathname,search:J.search!==""?J.search.substring(1,J.search.length):void 0,hash:J.hash!==""?J.hash.substring(1,J.hash.length):void 0}}x(d4,"extractValues");function X1($,Z){return Z?PZ($):$}x(X1,"processBaseURLString");function LZ($,Z,J){let j;if(typeof Z.baseURL=="string")try{j=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=X1(j.protocol.substring(0,j.protocol.length-1),J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&($.username=X1(j.username,J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&Z.password===void 0&&($.password=X1(j.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=X1(j.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=X1(j.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=X1(j.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=X1(j.search.substring(1,j.search.length),J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&Z.hash===void 0&&($.hash=X1(j.hash.substring(1,j.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=B5(Z.protocol,J)),typeof Z.username=="string"&&($.username=K5(Z.username,J)),typeof Z.password=="string"&&($.password=G5(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=O5(Z.hostname,J)),typeof Z.port=="string"&&($.port=U5(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,j&&!j5($.pathname,J)){let W=j.pathname.lastIndexOf("/");W>=0&&($.pathname=X1(j.pathname.substring(0,W+1),J)+$.pathname)}$.pathname=Q5($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=X5(Z.search,J)),typeof Z.hash=="string"&&($.hash=z5(Z.hash,J)),$}x(LZ,"applyInit");function PZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}x(PZ,"escapePatternString");function C5($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}x(C5,"escapeRegexpString");function L5($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",j=`[^${C5(Z.delimiter)}]+?`,W=/[$_\u200C\u200D\p{ID_Continue}]/u,Y="";for(let z=0;z<$.length;++z){let X=$[z];if(X.type===3){if(X.modifier===3){Y+=PZ(X.value);continue}Y+=`{${PZ(X.value)}}${S$(X.modifier)}`;continue}let O=X.hasCustomName(),G=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),K=z>0?$[z-1]:null,Q=z<$.length-1?$[z+1]:null;if(!G&&O&&X.type===1&&X.modifier===3&&Q&&!Q.prefix.length&&!Q.suffix.length)if(Q.type===3){let U=Q.value.length>0?Q.value[0]:"";G=W.test(U)}else G=!Q.hasCustomName();if(!G&&!X.prefix.length&&K&&K.type===3){let U=K.value[K.value.length-1];G=Z.prefixes.includes(U)}G&&(Y+="{"),Y+=PZ(X.prefix),O&&(Y+=`:${X.name}`),X.type===2?Y+=`(${X.value})`:X.type===1?O||(Y+=`(${j})`):X.type===0&&(!O&&(!K||K.type===3||K.modifier!==3||G||X.prefix!=="")?Y+="*":Y+=`(${J})`),X.type===1&&O&&X.suffix.length&&W.test(X.suffix[0])&&(Y+="\\"),Y+=PZ(X.suffix),G&&(Y+="}"),X.modifier!==3&&(Y+=S$(X.modifier))}return Y}x(L5,"partsToPattern");var Zj=class{#W;#Z={};#J={};#$={};#Y={};#G=!1;constructor($={},Z,J){try{let j;if(typeof Z=="string"?j=Z:J=Z,typeof $=="string"){let X=new N5($);if(X.parse(),$=X.result,j===void 0&&typeof $.protocol!="string")throw TypeError("A base URL must be provided for a relative constructor string.");$.baseURL=j}else{if(!$||typeof $!="object")throw TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(j)throw TypeError("parameter 1 is not of type 'string'.")}typeof J>"u"&&(J={ignoreCase:!1});let W={ignoreCase:J.ignoreCase===!0},Y={pathname:t1,protocol:t1,username:t1,password:t1,hostname:t1,port:t1,search:t1,hash:t1};this.#W=LZ(Y,$,!0),r4(this.#W.protocol)===this.#W.port&&(this.#W.port="");let z;for(z of h4){if(!(z in this.#W))continue;let X={},O=this.#W[z];switch(this.#J[z]=[],z){case"protocol":Object.assign(X,e1),X.encodePart=z8;break;case"username":Object.assign(X,e1),X.encodePart=F5;break;case"password":Object.assign(X,e1),X.encodePart=D5;break;case"hostname":Object.assign(X,iQ),o4(O)?X.encodePart=e4:X.encodePart=t4;break;case"port":Object.assign(X,e1),X.encodePart=$j;break;case"pathname":a4(this.#Z.protocol)?(Object.assign(X,sQ,W),X.encodePart=T5):(Object.assign(X,e1,W),X.encodePart=V5);break;case"search":Object.assign(X,e1,W),X.encodePart=M5;break;case"hash":Object.assign(X,e1,W),X.encodePart=I5;break}try{this.#Y[z]=i4(O,X),this.#Z[z]=s4(this.#Y[z],this.#J[z],X),this.#$[z]=L5(this.#Y[z],X),this.#G=this.#G||this.#Y[z].some((G)=>G.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#W[z]}'.`)}}}catch(j){throw TypeError(`Failed to construct 'URLPattern': ${j.message}`)}}get[Symbol.toStringTag](){return"URLPattern"}test($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return!1;try{typeof $=="object"?J=LZ(J,$,!1):J=LZ(J,d4($,Z),!1)}catch{return!1}let j;for(j of h4)if(!this.#Z[j].exec(J[j]))return!1;return!0}exec($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return;try{typeof $=="object"?J=LZ(J,$,!1):J=LZ(J,d4($,Z),!1)}catch{return null}let j={};Z?j.inputs=[$,Z]:j.inputs=[$];let W;for(W of h4){let Y=this.#Z[W].exec(J[W]);if(!Y)return null;let z={};for(let[X,O]of this.#J[W].entries())if(typeof O=="string"||typeof O=="number"){let G=Y[X+1];z[O]=G}j[W]={input:J[W]??"",groups:z}}return j}static compareComponent($,Z,J){let j=x((X,O)=>{for(let G of["type","modifier","prefix","value","suffix"]){if(X[G]<O[G])return-1;if(X[G]===O[G])continue;return 1}return 0},"comparePart"),W=new _Z(3,"","","","",3),Y=new _Z(0,"","","","",3),z=x((X,O)=>{let G=0;for(;G<Math.min(X.length,O.length);++G){let K=j(X[G],O[G]);if(K)return K}return X.length===O.length?0:j(X[G]??W,O[G]??W)},"comparePartList");return!Z.#$[$]&&!J.#$[$]?0:Z.#$[$]&&!J.#$[$]?z(Z.#Y[$],[Y]):!Z.#$[$]&&J.#$[$]?z([Y],J.#Y[$]):z(Z.#Y[$],J.#Y[$])}get protocol(){return this.#$.protocol}get username(){return this.#$.username}get password(){return this.#$.password}get hostname(){return this.#$.hostname}get port(){return this.#$.port}get pathname(){return this.#$.pathname}get search(){return this.#$.search}get hash(){return this.#$.hash}get hasRegExpGroups(){return this.#G}};x(Zj,"URLPattern");function L3($,Z){for(let[J,j]of Object.entries($)){let W=new Zj({pathname:J});if(W.test({pathname:Z}))return{routePath:J,params:W.exec({pathname:Z})?.pathname.groups??{},route:j}}return null}var f$={startIndex:0,carriedViews:[]};function P5($,Z){let J=X0($.path,Z);return J.includes("*")?null:J}function nQ($,Z){if(!$)return f$;if($.search!==Z.search)return f$;let J=Math.min($.segments.length,Z.segments.length-1),j=0;while(j<J){let W=$.segments[j],Y=Z.segments[j];if(Y.alwaysRun)break;if(W.viewPath!==Y.viewPath)break;let z=P5(W,$.params),X=P5(Y,Z.params);if(z===null||X===null||z!==X)break;j++}if(j===0)return f$;return{startIndex:j,carriedViews:Z.segments.slice(0,j).map(({viewPath:W})=>W)}}function oQ($,Z){let[,J,...j]=$.split("/");if(!Z.includes(J))return $;let W=`/${j.join("/")}`;return W==="/"?"/":W.replace(/\/$/,"")}function _5($){let{flatViewRoutes:Z,supportedLocales:J,from:j,origin:W,to:Y}=$;if(!j)return f$;let z;try{z=new URL(j,W)}catch{return f$}if(z.origin!==W)return f$;let X=L3(Z,oQ(z.pathname,J));if(!X)return f$;return nQ({segments:X.route.segments,params:X.params,search:z.search},Y)}var Jj="x-gemi-from";import{createElement as x1,Fragment as r5}from"react";function aQ($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function X8($){let Z={};for(let[J,j]of Object.entries($))if("run"in j){let W=j.viewPath;if("children"in j){Z[J]=[W];let Y=new j.children,z=X8(Y.routes);for(let[X,O]of Object.entries(z)){let G=J==="/"?X:`${J}${X}`,K=X==="/"&&J!=="/"?J:G;Z[K]=[W,...O]}if(Z[J].length===1)delete Z[J]}else Z[J]=[W]}else{let W=new j,Y=X8(W.routes);for(let[z,X]of Object.entries(Y)){let O=J==="/"?z:`${J}${z}`,G=z==="/"&&J!=="/"?J:O;Z[G]=X}}return Object.fromEntries(Object.entries(Z).map(([J,j])=>[aQ(J),j]))}function O8($,Z){let[J,j]=Z,W=$.find(([Y])=>Y===J);if(!W){$.push([J,[...j]]);return}for(let Y of j)O8(W[1],Y)}function G8($){let Z=[];for(let[J,j]of Object.entries($))if("run"in j){let W=j.viewPath;if(W==="__")continue;if(W==="REDIRECT")continue;if(W==="FILE")continue;if("children"in j){let Y=new j.children,z=G8(Y.routes);O8(Z,[W,z])}else O8(Z,[W,[]])}else{let W=new j,Y=G8(W.routes);for(let z of Y)O8(Z,z)}return Z}function jj($){let Z=[];for(let[J,j]of $)Z.push(J,...jj(j).flat());return Array.from(new Set(Z))}class $$ extends z0{static getFacadeAccessor(){return o}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=f.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(f.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??$$.locale(),$.timeZone??$$.timeZone())}static setLocale($=$$.locale(),Z={}){let J=this.getFacadeRoot(),j=$;if(!J.supportedLocales.includes($))j=J.defaultLocale;let W=f.getStore();if(Z.cookie!==!1)W.setCookie("i18n-locale",j,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return W.setLocale(j),j}}class Wj{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}var rQ=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),tQ=new Set(["svg","math"]);function H5($){return $===32||$===9||$===10||$===12||$===13}function x5($){return $>=65&&$<=90||$>=97&&$<=122}function K8($){return $>=65&&$<=90?$+32:$}function S5(){let $="data",Z="",J=!1,j="",W=0,Y=0,z=!1,X=0,O=0,G=()=>$==="data"&&X===0&&O===0,K=()=>{if(!J&&rQ.has(Z)){$="rawText",j=`</${Z}`,W=0,Z="";return}if($="data",Z==="template")if(J)X=Math.max(0,X-1);else X+=1;else if(tQ.has(Z)){if(J)O=Math.max(0,O-1);else if(!z)O+=1}Z=""},Q=(U)=>{switch($){case"data":if(U===60)$="tagOpen";return;case"tagOpen":if(U===33)$="bang",Y=0;else if(U===47)$="endTagOpen";else if(x5(U))$="tagName",J=!1,z=!1,Z=String.fromCharCode(K8(U));else if(U===63)$="bogus";else if(U===60)$="tagOpen";else $="data";return;case"endTagOpen":if(x5(U))$="tagName",J=!0,z=!1,Z=String.fromCharCode(K8(U));else if(U===62)$="data";else $="bogus";return;case"tagName":if(H5(U)||U===47)$="inTag",z=U===47;else if(U===62)K();else Z+=String.fromCharCode(K8(U));return;case"inTag":if(U===62){K();return}if(z=U===47,U===34)$="attrDouble";else if(U===39)$="attrSingle";return;case"attrDouble":if(U===34)$="inTag";z=!1;return;case"attrSingle":if(U===39)$="inTag";z=!1;return;case"bang":if(U===45){if(Y+=1,Y===2)$="comment",Y=0}else if(U===62)$="data";else $="bogus";return;case"bogus":if(U===62)$="data";return;case"comment":if(U===45)Y=Y<2?Y+1:2;else if(U===62&&Y>=2)$="data",Y=0;else Y=0;return;case"rawText":{if(W<j.length){if(K8(U)===j.charCodeAt(W))W+=1;else W=U===60?1:0;return}if(U===62)$="data",Z="";else if(H5(U)||U===47)$="inTag",Z="";else W=U===60?1:0;return}}};return{scanToInsertionPoint(U){for(let F=0;F<U.length;F++){if(G())return F;Q(U[F])}return U.length},write(U){for(let F=0;F<U.length;F++)Q(U[F])},isSafe:G}}function _1($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function eQ($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${_1([$.path,$.variantKey,$.data])})</script>`}function $U($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${_1([$.id,$.locale,$.strings])})</script>`}function Yj($,Z,J={},j){let W=new TextEncoder,Y=[],z=!1,X=!1,O=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((B)=>{if(B.status!=="resolved")return;Y.push(eQ(B))}),j?.onUse((B)=>{Y.push($U(B))});let G=$.getReader(),K=S5(),Q=(B,D)=>{B.enqueue(D),J.onChunk?.(D)},U=(B)=>{while(Y.length>0){let D=W.encode(Y.shift());K.write(D),Q(B,D)}},F=(B,D)=>{if(Y.length===0){K.write(D),Q(B,D);return}let T=K.scanToInsertionPoint(D);if(T>0)Q(B,D.subarray(0,T));if(K.isSafe())U(B);let M=D.subarray(T);if(M.length>0)K.write(M),Q(B,M)};return new ReadableStream({async pull(B){let D;try{D=await G.read()}catch(L){throw O(),L}let{done:T,value:M}=D;if(T){U(B),B.close(),O();return}if(!z){if(z=!0,K.write(M),Q(B,M),J.onShell?.(),K.isSafe())U(B);return}F(B,M)},cancel(B){return O(),G.cancel(B)}})}var ZU=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function Q8($){if(!$)return!1;return ZU.test($)}async function A5($,Z=()=>{}){let J=f.getStore(),j=J?.req??null,W=null;if(j?.rawRequest?.url)try{W=new URL(j.rawRequest.url).pathname}catch{W=null}return{user:J?.user??null,attributes:await JU($,Z),request:{path:W,routePath:j?.routePath??null,locale:J?.locale??null},anonymousId:f5(),isBot:Q8(j?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function E5($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function JU($,Z){if(!$.context)return{};try{let J=f.getStore();return await $.context(J?.req??null)??{}}catch(J){return Z(`The \`context\` hook in app/config/features.ts threw; evaluating with no attributes. ${J instanceof Error?J.message:String(J)}`),{}}}function R5($,Z){return`${$}:${Z}`}function zj($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function b5($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function v5($,Z,J,j){if(j.unavailable)return{value:!1,reason:"unavailable"};if(j.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let Y;try{Y=Z.when(J)}catch(z){return j.warn?.(`The \`when\` for feature "${$}" threw; treating it as off. ${z instanceof Error?z.message:String(z)}`),{value:!1,reason:"error"}}if(typeof Y==="boolean")return{value:Y,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(J.isBot)return{value:!1,reason:"bot"};let W=WU($,Z,J,j.buckets);return b5(W,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function jU($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function WU($,Z,J,j){let W=R5(Z.salt??$,jU(J));if(!j)return zj(W);let Y=j.get(W);if(Y!==void 0)return Y;let z=zj(W);return j.set(W,z),z}class k5 extends Error{cause;kind="FeatureReloadFailed";constructor($){super(`Could not reload feature switches after a write, so the cached switches may still predate it: ${$ instanceof Error?$.message:String($)}`);this.cause=$}}class Xj{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,J,j=()=>{}){this.source=$;this.declared=Z;this.ttlMs=J;this.warn=j}async get(){let $=this.snapshot;if($&&Date.now()-$.loadedAt<this.ttlMs)return $;if($){if(Date.now()>=this.retryAfter)this.refresh().catch(()=>{});return $}return await this.refresh()}refresh(){return this.inflight??=this.load().finally(()=>{this.inflight=null}),this.inflight}async invalidate(){await this.inflight?.catch(()=>{});let $=this.generation,Z=await this.refresh();if(this.generation===$)throw new k5(this.lastError);return Z}peek(){return this.snapshot}async load(){try{let $=await this.source.load(),{active:Z,audit:J}=this.readRows($);return this.snapshot={active:Z,audit:J,loadedAt:Date.now(),unavailable:!1},this.generation++,this.lastError=null,this.retryAfter=0,this.snapshot}catch($){return this.handleFailure($)}}readRows($){let Z=new Map,J=new Map;for(let j of $??[]){let W=typeof j?.key==="string"?j.key:null;if(!W){this.warn("Ignoring a feature row with no `key`.");continue}if(!(W in this.declared)){this.warn(`Feature row "${W}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(W,j.active===!0);let Y=YU(j);if(Y)J.set(W,Y)}return{active:Z,audit:J}}handleFailure($){let Z=$ instanceof Error?$.message:String($),J=Date.now();if(this.lastError=$,this.retryAfter=J+this.ttlMs,J-this.lastFailureLoggedAt>=this.ttlMs)this.lastFailureLoggedAt=J,this.warn(`Could not load feature switches: ${Z}`);if(this.snapshot)return this.snapshot;return this.snapshot={active:new Map,audit:new Map,loadedAt:J,unavailable:!0},this.snapshot}}function YU($){let Z={},J=$.updatedBy;if(typeof J==="string")Z.updatedBy=J;else if(J===null)Z.updatedBy=null;let j=$.updatedAt;if(j instanceof Date||typeof j==="string"||typeof j==="number"){let W=j instanceof Date?j:new Date(j);if(!Number.isNaN(W.getTime()))Z.updatedAt=W}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class zU{}class XU extends Error{modelName;kind="FeatureModelMissing";constructor($){super(`No "${$}" model is registered, so every feature stays off. Add the model to prisma/schema.prisma and export it from app/models \u2014 see docs/feature-flags.md.`);this.modelName=$}}class Oj extends Error{sourceName;kind="FeatureSourceReadOnly";constructor($){super(`The feature source (${$}) is read-only, so Features.set() cannot write to it. Change the switch where that source reads from, or give the source a write() method.`);this.sourceName=$}}class w5 extends Error{key;kind="UndeclaredFeature";constructor($){super(`"${$}" is not declared in app/features, so it cannot be switched. A row for it would be ignored \u2014 declare the feature first.`);this.key=$}}class q5{manager;ctx;constructor($,Z){this.manager=$;this.ctx=Z}async enabled($){return(await this.explain($)).value}async explain($){return await this.manager.evaluateIn($,this.ctx,new Map)}async all(){return await this.manager.evaluateAllIn(this.ctx,new Map,{clientOnly:!1})}}class HZ{config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new Xj($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:J}=await this.switches();return{unavailable:J,features:Object.entries(this.declared).map(([j,W])=>({key:j,describe:W.describe,rollout:W.rollout,targeted:W.when!==void 0,serverOnly:W.serverOnly,salt:W.salt,active:$.get(j),...Z.get(j)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{f.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new w5(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let j=OU(J.actor),W=this.config.source;if(typeof W.write!=="function")throw new Oj(W.constructor?.name||"an anonymous source");let{actorRecorded:Y}=await W.write($,Z,{actor:j});if(j!==null&&!Y&&!this.warnedAboutActor)this.warnedAboutActor=!0,this.log('Features.set() was given an actor, but the feature source has nowhere to record it. For the database source, add a nullable `updatedBy String?` column to the feature flag model to keep "last changed by".');await this.invalidate()}async enabled($){return(await this.explain($)).value}async explain($){let Z=await this.requestContext();return await this.evaluateIn($,Z,this.requestBuckets())}async all(){let $=await this.requestContext();return await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!1})}async forClient(){if(!this.config.enabled)return{};let $=await this.requestContext(),Z=await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!0});return this.warnIfOversized(Object.keys(Z).length),Z}for($){return new q5(this,E5($))}async evaluateIn($,Z,J){let j=this.memoFor(Z),W=j?.get($);if(W)return W;let Y=this.declared[$];if(!Y)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),O=v5($,Y,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return j?.set($,O),this.notify($,O,Z),O}async evaluateAllIn($,Z,J){let j={};for(let[W,Y]of Object.entries(this.declared)){if(J.clientOnly&&Y.serverOnly)continue;j[W]=(await this.evaluateIn(W,$,Z)).value}return j}async switches(){if(!this.config.enabled||Object.keys(this.declared).length===0)return{active:new Map,audit:new Map,unavailable:!1};let $=await this.store.get();return{active:$.active,audit:$.audit,unavailable:$.unavailable}}async switchFor($){if(!this.config.enabled)return{active:!1,unavailable:!1};let Z=await this.store.get();return{active:Z.active.get($),unavailable:Z.unavailable}}async requestContext(){let $=f.getStore();if($?.featureContext)return $.featureContext;let Z=await A5(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=f.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=f.getStore();if(!$)return new Map;return $.featureBuckets??=new Map,$.featureBuckets}notify($,Z,J){if(!this.config.onEvaluate)return;try{this.config.onEvaluate($,Z,J)}catch(j){this.log(`The \`onEvaluate\` hook in app/config/features.ts threw for "${$}". ${j instanceof Error?j.message:String(j)}`)}}warnIfOversized($){if(this.warnedAboutSize||$<=this.config.maxClientFlags)return;this.warnedAboutSize=!0,this.log(`${$} client-visible features are embedded in every document. Mark the ones only the server reads with \`serverOnly: true\` to keep them out of the payload.`)}}function OU($){if($===void 0||$===null)return null;if(typeof $==="string"){if($.length>0)return $}else if(typeof $==="object"){let{publicId:Z,id:J}=$;if(typeof Z==="string"&&Z.length>0)return Z;if(typeof J==="string"&&J.length>0||typeof J==="number")return String(J)}throw TypeError("Features.set() was given an `actor` that identifies nobody. Pass a string, or a user with a `publicId` or an `id`.")}function y5($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var GU=50;class xZ{fetcher;entries=new Map;settleListener=null;failListener=null;shellAt=null;settledBacklog=[];shipped=new Set;requestStartedAt=performance.now();renderStartedAt=null;discoveryHintsMuted=!1;constructor($){this.fetcher=$}elapsed(){return Math.round(performance.now()-this.requestStartedAt)}keyFor($,Z){return[$,Z].filter((J)=>J.length>0).join("?")}markRenderStart(){if(this.renderStartedAt===null)this.renderStartedAt=performance.now()}markShell(){if(this.shellAt===null)this.shellAt=this.elapsed()}summarize($){let Z=this.elapsed();return{shellAt:this.shellAt??Z,settledAt:Z,aborted:$,queries:Array.from(this.entries.values(),(J)=>({path:J.path,variantKey:J.variantKey,startedAt:J.startedAt,settledAt:J.settledAt,status:J.status,source:J.source}))}}onQueryFail($){this.failListener=$}muteDiscoveryHints(){this.discoveryHintsMuted=!0}maybeLogLateDiscovery($){if(!$.lateBy||this.discoveryHintsMuted)return;if($.status!=="resolved")return;if(Bun.env.NODE_ENV==="production")return;let Z="";try{let W=JSON.stringify($.data)?.length??0;Z=W>=1024?`${(W/1024).toFixed(1)} kB`:`${W} B`}catch{Z="an unserializable payload"}let J=($.settledAt??0)-$.startedAt,j=$.variantKey?`, { search: ${JSON.stringify(Object.fromEntries(new URLSearchParams($.variantKey)))} }`:"";console.warn(`[gemi] useQuery("${$.patternPath}") was discovered ${$.lateBy}ms into the `+`server render \u2014 under a suspended segment, so its fetch (${J}ms, resolved ${Z}) could not overlap the others. It still streamed. If the query belongs on this route, \`Query.prefetch("${$.patternPath}"${j})\` in the view `+"handler starts it at request time \u2014 but note prefetched data is also re-fetched and "+`streamed into every client-side navigation payload for the route, even when the client already holds it, so weigh that bandwidth against the ${Z}. If the data is only needed conditionally (a closed popover, a hidden tab), \`{ lazy: true }\` + \`trigger()\` avoids running it here at all. \`Query.noPrefetch()\` in the handler marks the omission intentional and silences this hint for the route.`)}read($,Z){return this.entries.get(this.keyFor($,Z))}ensure($,Z={},J="render"){let j=Z.params??{},W=new URLSearchParams(y5(Z.search??{}));W.delete("json"),W.sort();let Y=X0($,j),z=W.toString(),X=this.keyFor(Y,z),O=this.entries.get(X);if(O)return O;let G;if(J==="render"&&this.renderStartedAt!==null){let F=Math.round(performance.now()-this.renderStartedAt);if(F>GU)G=F}let K,Q=new Promise((F)=>{K=F}),U={path:Y,patternPath:$,variantKey:z,lateBy:G,status:"pending",promise:Q,source:J,startedAt:this.elapsed()};return this.entries.set(X,U),this.fetcher($,j,W).then((F)=>{U.status="resolved",U.data=F},(F)=>{U.status="rejected",U.error=F}).then(()=>{if(U.settledAt=this.elapsed(),this.maybeLogLateDiscovery(U),U.status==="rejected"&&this.failListener)this.failListener(U);if(this.settleListener)this.settleListener(U);else this.settledBacklog.push(U);K()}),U}async allSettled(){let $=0;while($!==this.entries.size)$=this.entries.size,await Promise.all(Array.from(this.entries.values(),(Z)=>Z.promise))}snapshotResolved(){let $={};for(let[Z,J]of this.entries){if(J.status!=="resolved")continue;this.shipped.add(Z),$[J.path]??={},$[J.path][J.variantKey]=J.data}return $}onSettle($){this.settleListener=(J)=>{if(this.shipped.has(this.keyFor(J.path,J.variantKey)))return;$(J)};let Z=this.settledBacklog;this.settledBacklog=[];for(let J of Z)this.settleListener(J)}}class H1 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,J,j,W){super(typeof j?.message==="string"?j.message:`Request to /api${$} failed with status ${J}`);this.path=$;this.variantKey=Z;this.status=J;this.body=j;this.retryAfter=W;this.name="QueryError"}}function SZ(){let $=JSON.stringify({error:b1("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function Gj(){return{status:403,error:{message:"Forbidden"}}}function P3($){let Z=fZ.getStore();return(J,j,W)=>{let Y=new URL($.url).origin,z=[X0(J,j),W.toString()].filter((K)=>K.length>0).join("?"),X=new Request(`${Y}/${z}`,{headers:$.headers,signal:$.signal}),O=g5($);if(O)AZ(X,O);let G=new A(X,j);return fZ.run(Z,()=>f.run(G,async()=>{try{let K=await N(a0).dispatchers(O).api.getRouteData(J);if(y$(K)){if(!K.ok)throw new H1(X0(J,j),W.toString(),K.status,K.body);return K.body}if(K instanceof Response){let Q=await K.json().catch(()=>null);if(!K.ok)throw new H1(X0(J,j),W.toString(),K.status,Q);return Q}return K}catch(K){if(K instanceof H1)throw K;let Q=new H1(X0(J,j),W.toString(),500,{message:K instanceof Error?K.message:String(K)});throw Q.cause=K,Q}}))}}var KU=new Set(["script","style","template","title"]),QU=/\shidden([\s=/]|$)/i,UU=/"[^"]*"|'[^']*'/g;function BU($){let Z=0,J=0,j=0,W=0;while(W<$.length){let Y=$.indexOf("<",W),z=Y===-1?$.length:Y;if(z>W){let Q=$.slice(W,z).replace(/\s+/g,"").length;if(j>0)J+=Q;else Z+=Q}if(Y===-1)break;if($.startsWith("<!--",Y)){let Q=$.indexOf("-->",Y+4);W=Q===-1?$.length:Q+3;continue}let X=$.indexOf(">",Y);if(X===-1)break;let O=$.slice(Y+1,X);W=X+1;let G=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(O)?.[1]?.toLowerCase();if(!G)continue;let K=O.startsWith("/");if(!K&&KU.has(G)&&!O.endsWith("/")){let Q=$.indexOf(`</${G}`,W);W=Q===-1?$.length:Q;continue}if(G!=="div")continue;if(K){if(j>0)j-=1}else if(j>0)j+=1;else if(QU.test(O.replace(UU,'""')))j=1}return{shellChars:Z,deferredChars:J}}var FU=1000,DU=64;function TU($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function VU($,Z){if(Z.deferredChars<FU)return null;if(Z.shellChars>=DU)return null;return`[gemi] GET ${$} streams ${TU(Z.deferredChars)} of its `+`content behind reveal scripts \u2014 a no-JS visitor sees ~${Z.shellChars} chars. If this is a public/content route, add "no-stream" to its middleware.`}function m5($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,j){if(Z.has(J))return;let W=VU(J,j);if(!W)return;Z.add(J),$(W)}}}function p5(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),BU(Z)}}}function h5($,Z,J=1e4,j){let W=new TextEncoder,Y=()=>{};return new ReadableStream({start(z){let X=!1,O=(K)=>{if(X)return;X=!0,clearTimeout(G);try{z.close()}catch{}j?.({aborted:K})};Y=O,z.enqueue(W.encode(`${JSON.stringify($)}
3
+ `)),Z.onSettle((K)=>{if(X||K.status!=="resolved")return;z.enqueue(W.encode(`${JSON.stringify([K.path,K.variantKey,K.data])}
4
+ `))});let G=setTimeout(()=>O(!0),J);Z.allSettled().then(()=>O(!1),()=>O(!1))},cancel(){Y(!1)}})}import{Fragment as sV,createContext as MU,createElement as nV,lazy as oV,use as aV,useContext as rV}from"react";function c5($){return{islands:[],render:$,instances:new WeakMap,count:0}}var _3="gemi-slot",u5="data-slot",d5="data-gemi-slot";var IU=Symbol.for("gemi.staticRender"),l5=globalThis[IU]??=MU(null);import{createHash as NU}from"crypto";var CU="gemi-islands",Kj='const d=document,c=JSON.parse(d.getElementById("gemi-islands").textContent),w=f=>(window.requestIdleCallback||setTimeout)(f),m=(e,o)=>{if(!e.g){e.g=1;import(o.s).then(x=>x.h(e,x.m[o.e])).catch(r=>console.error(r))}};for(const e of d.querySelectorAll("gemi-island")){const o=c.i[e.dataset.island];if(!o)continue;if(o.l=="eager")m(e,o);else if(o.l=="idle"||!window.IntersectionObserver||!e.children.length)w(()=>m(e,o));else{const v=new IntersectionObserver(n=>{if(n.some(x=>x.isIntersecting)){v.disconnect();m(e,o)}});for(const k of e.children)v.observe(k)}}',JM=`'sha256-${NU("sha256").update(Kj).digest("base64")}'`,LU='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});'+Kj;function i5($,Z,J,j){if(!J)return $;let W=j?$.lastIndexOf(Z):$.indexOf(Z);return W===-1?$+J:$.slice(0,W)+J+$.slice(W)}var PU=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;");function s5($,Z,J,j){if(Z.islands.length===0||!J)return $;let W=new Set,Y=Z.islands.map((O)=>{let G=O.module?J(O.module):void 0;if(!G)return console.error(`[gemi] island ${O.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(O.load==="eager")for(let K of G.preload)W.add(K);return{s:G.src,e:O.export,l:O.load}});if(Y.every((O)=>O===null))return $;let z=[...W].map((O)=>`<link rel="modulepreload" href="${PU(O)}"/>`).join(""),X=`<script type="application/json" id="${CU}">${_1({i:Y})}</script><script type="module">${j?LU:Kj}</script>`;return i5(i5($,"</head>",z,!1),"</body>",X,!0)}function _U($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let j=0;for(let W=J.exec($);W;W=J.exec($))if(j+=W[1]?-1:1,j===0)return J.lastIndex;return-1}function n5($){let Z=`<template ${d5}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let j=_U($,J);if(j===-1)break;let W=J+Z.length,Y=$.slice(W,$.indexOf('"',W)),z=$.indexOf(">",W)+1,X=$.slice(z,j-11);$=$.slice(0,J)+$.slice(j);let O=`<${_3} ${u5}="${Y}" style="display:contents"></${_3}>`;$=$.split(O).join(`<${_3} style="display:contents">${X}</${_3}>`)}return $}function o5($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function a5($,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)}var HU=async()=>(await import("./chunk-e7axa0d5.js")).default,Qj,H3=async(...$)=>{return Qj??=import("react-dom/server.browser").catch((Z)=>{throw Qj=void 0,Z}),(await Qj).renderToReadableStream(...$)},t5=1e4,xU=`
5
+ !function(){try{var d=document.documentElement,c=d.classList;
6
+ c.remove('light','dark');
7
+ var e=localStorage.getItem('theme');
8
+ if('system'===e||(!e&&'system'===defaultTheme)){
9
+ var t='(prefers-color-scheme: dark)',m=window.matchMedia(t);
10
+ if(m.media!==t||m.matches){d.style.colorScheme='dark';c.add('dark')}
11
+ else{d.style.colorScheme='light';c.add('light')}
12
+ }else if(e){
13
+ c.add(e||'')
14
+ }}catch(e){}}()
15
+ `;async function SU($,Z,J){let j=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${j}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var Fj="/assets";function fU($){return $===Fj||$.startsWith(`${Fj}/`)}function AU($){let Z=$.filter(fU);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((j)=>`"${j}"`).join(", ")} use${J?"":"s"} the reserved "${Fj}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function EU($){let Z=N(a0).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function Uj($){let{status:Z=400,error:J}=$;return new Response(J?.message,{...$,status:Z})}function RU($){let{status:Z=400,data:J,directive:j,headers:W}=$;return new Response(JSON.stringify({data:J,directive:j}),{headers:W,status:Z})}class S3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];staticRoutes=[];root=null;shellReporter=m5();preloadCache=new WeakMap;hooks;partialRendering;constructor($){let Z=t7();this.partialRendering=$.partialRendering??Z.partialRendering,this.hooks={onRequestStart:$.onRequestStart??Z.onRequestStart,onRequestEnd:$.onRequestEnd??Z.onRequestEnd,onRequestFail:$.onRequestFail??Z.onRequestFail,onStreamComplete:$.onStreamComplete??Z.onStreamComplete};let J={"/":$.rootRouter,"/auth":R4};this.flatViewRoutes=Y8(J),AU(Object.keys(this.flatViewRoutes)),this.routeManifest=X8(J),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,j])=>j.at(-1)!=="FILE")),this.componentTree=G8(J),this.flatComponentTree=jj(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,j])=>j.static).map(([j])=>j);for(let j of this.staticRoutes){let W=this.flatViewRoutes[j].static?.layout;if(W&&!this.flatComponentTree.includes(W))this.flatComponentTree.push(W)}this.root=$.root}async passesFeatureGates($){let Z=N(HZ);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)U8();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(j)=>{A$.error(j?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(j)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(j){J(j)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:j,routeKey:W}=$,Y=()=>{let O=new Set(Z?.preload??[]);for(let G of j)for(let K of J?.[G]??[])O.add(K);return[...O].map((G)=>x1("link",{key:`modulepreload:${G}`,rel:"modulepreload",href:G}))};if(!J)return Y();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(W);if(!X)X=Y(),z.byRoute.set(W,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:j,currentViews:W,data:Y,serverQueries:z,headers:X}=$,O;if(j.layout){if(O=$.viewImportMap[j.layout],!O)throw Error(`The static layout "${j.layout}" was not found. It is a view path: a file at app/views/${j.layout}.tsx whose default export renders the document.`)}let G=await $.getStyles(W,{static:!0,layout:j.layout});z.markRenderStart();let K=Bj(),Q=new AbortController,U=setTimeout(()=>Q.abort(),t5),F=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},B=c5(async(D,T)=>{let M=await H3(D,{signal:Q.signal,identifierPrefix:T,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:F});return await M.allReady.catch(()=>{}),await new Response(M).text()});try{let D=await H3(x1(l5.Provider,{value:B,children:x1(r5,{children:[...G,x1(this.root,{data:Y,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:K,rootLayout:O,key:"root"})]})}),{signal:Q.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:F});await D.allReady.catch(()=>{});let T=n5(await new Response(D).text());return new Response(s5(T,B,$.resolveIsland,Bun.env.NODE_ENV!=="production"),{status:200,headers:X})}finally{clearTimeout(U),J(()=>this.completeStream(Z,z.summarize(Q.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:j,currentPathName:W,headers:Y,i18n:z,params:X,pathname:O,serverQueries:G,userAgent:K,noStream:Q,url:U,user:F,viewData:B,breadcrumbs:D,urlLocaleSegment:T,meta:M,isOgRequest:L,appId:I,features:_,staticView:H}=$,P=O.replace(`/${T}`,""),V={kind:"view",data:{meta:M,pageData:{[P]:B},__csrf:j.toString("base64"),prefetchedData:{},i18n:z,auth:{user:F},routeManifest:this.clientRouteManifest,breadcrumbs:D,router:{urlLocaleSegment:T,pathname:W,params:X,currentPath:O,searchParams:U.search,is404:!W?!0:!1,domain:Z.domain?EU(Z):null},appId:I,features:_,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},C=this.root,S=this.routeManifest[W];return async(b)=>{let{bootstrapModules:g=[],loaders:r0,getStyles:m,viewImportMap:q,cssManifest:t0,ogMap:f3,viewModules:A3,clientEntry:Z$,modulePreloadManifest:f1,assetBase:A1,resolveIsland:E$}=b,n=Z$?[]:g,E3=(e)=>[e,`window.loaders=${r0}`,...Z$?[`import(${JSON.stringify(Z$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(L){let e=null,b$=null;for(let v$ of S??[])if(typeof f3[v$]==="function")b$=v$,e=f3[v$];if(!e)return new Response("Not found",{status:404});let mX=Object.values(V.data.pageData)[0];try{await H3(x1(e,mX[b$]),{onError:()=>{}})}catch(v$){let{fonts:pX,...hX}=v$.satoriOptions,cX=await Promise.all(pX.map((R3)=>{return SU(R3.name,R3.weight,R3.style).then((sX)=>({...R3,data:sX}))})),fj=new Headers(Y);fj.set("Content-Type","image/png");let[uX,dX]=await Promise.all([HU(),j8("Rendering an OG image")]),lX=await uX(v$.jsx,{...hX,fonts:cX}),iX=await dX(Buffer.from(lX)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(iX),{headers:fj})}return new Response("data")}if(H&&W)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:H,currentViews:S,data:V.data,serverQueries:G,headers:Y,getStyles:m,viewImportMap:q,viewModules:A3,resolveIsland:E$});if(V.data.cssManifest=t0,V.data.modulePreloadManifest=f1??{},A1&&A1!=="/")V.data.assetBase=A1;let P8=this.modulePreloadLinks({clientEntry:Z$,modulePreloadManifest:f1,views:S??["404"],routeKey:W??"404"}),R$=await m(S);V.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let G1=new AbortController,vZ=setTimeout(()=>G1.abort(),t5),K1=Q8(K)||Q,R=Bun.env.NODE_ENV!=="production"&&!K1&&W&&this.shellReporter.shouldObserve(W)?p5():null,w0=Bj();try{let e=await H3(x1(r5,{children:[...P8,...R$,x1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:xU}}),x1(C,{data:V.data,viewImportMap:q,viewModules:A3,serverQueries:G,dictionarySink:w0,key:"root"})]}),{bootstrapScriptContent:E3(`window.__GEMI_DATA__ = ${_1(V.data)}`),bootstrapModules:n,signal:G1.signal,...K1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(b$){if(Bun.env.NODE_ENV!=="production")console.error(b$)}});if(e.allReady.catch(()=>{}).finally(()=>clearTimeout(vZ)),K1)await e.allReady.catch(()=>{});return new Response(Yj(e,G,{onShell:K1?void 0:()=>G.markShell(),onChunk:R?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,G.summarize(G1.signal.aborted)),R)this.shellReporter.report(W,R.measure())})},w0),{status:!W?$.refusedStatus??404:200,headers:Y})}catch(e){if(clearTimeout(vZ),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(G1.signal.aborted))),e;let b$=await H3(x1("div"),{bootstrapScriptContent:E3(`window.error= ${_1(e.message)}; window.stack_trace=${_1(e.stack)};window.__GEMI_DATA__ = ${_1(V.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...n]:n});return new Response(Yj(b$,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(G1.signal.aborted)))}),{status:!W?$.refusedStatus??404:200,headers:Y})}}}viewRefusalStatus($,Z,J){if(x3(Z))return 404;if(Z?.kind===EZ){let j=Z.payload?.view?.status;return j===403||j===404?j:null}if(RZ(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof H1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),j=J.pathname.endsWith(".json"),W=J.pathname.endsWith(".og"),Y=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=Y.split("/"),O=`/${X.join("/")}`,G=null,K=null,Q=N(o);if(!Q.supportedLocales.includes(z))O=Y;else G=z,K=z;let F=K===null&&L3(this.flatViewRoutes,O)!==null;if(Q.isLocaleAware&&!W&&K===null&&!F){let V=e5(z,Q.supportedLocales,Q.defaultLocale);if(V){let C=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${V}${C}${j?".json":""}${J.search}`}})}}if(Q.isLocaleAware&&!W){let V=N(o).detectLocale(new A($,{},"view",O));if(K===null&&V!==Q.defaultLocale){let C=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${V}${C}${J.search}`}})}}O=O.replace("//","/");let B=[],D=[],T=null,M={},L=null,I=!1,_=[],H;try{let V=L3(this.flatViewRoutes,O);if(V){if(T=V.routePath,M=V.params,B=V.route.exec,D=V.route.middleware,_=V.route.features,I=D.includes("no-stream"),H=V.route.static,j&&this.partialRendering){let C=$.headers.get(Jj),S=_5({flatViewRoutes:this.flatViewRoutes,supportedLocales:N(o).supportedLocales,from:C,origin:J.origin,to:{segments:V.route.segments,params:M,search:J.search}});if(S.startIndex>0)B=B.slice(S.startIndex),L={from:C,carriedViews:S.carriedViews}}}}catch(V){throw V}if(H&&j)return new Response("Not found",{status:404});let P=new A($,M,"view",T);return this.hooks.onRequestStart(P),await f.run(P,async()=>{let V=null,C=f.getStore(),S=fZ.getStore(),b=(q)=>fZ.run(S,()=>f.runWith(C,q));C.serverQueries=new xZ(P3($));let g=new Set;C.serverQueries.onQueryFail((q)=>{g.add(q.error);try{b(()=>Promise.resolve(this.hooks.onRequestFail(m,q.error)).catch(()=>{}))}catch{}});let r0=o5(H);if(K){let q=K.replaceAll("/","");$$.setLocale(q,{cookie:r0.locale})}else $$.setLocale(void 0,{cookie:r0.locale});let m=C.req;if(r0.session)U8();try{let q=null;try{await N(CZ).runMiddleware(D)}catch(R){if(q=this.viewRefusalStatus(m,R,g),q===null)throw R}if(q!==null||_.length>0&&!await this.passesFeatureGates(_))T=null,B=[],m.routePath="";let t0=N(o),f3=t0.isEnabled,A3=t0.isLocaleAware,Z$=new A($,m.params),f1={defaultLocale:t0.defaultLocale,timeZone:t0.detectTimeZone(Z$)};if(A3){let R=null;if(K)R=K.replaceAll("/",""),C.setLocale(R);else R=t0.detectLocale(Z$),C.setLocale(R);let w0=f3?t0.getPageTranslations(R,m.routePath):{};f1={...f1,supportedLocales:t0.supportedLocales,currentLocale:R,dictionary:{[R]:w0},defaultLocale:t0.defaultLocale}}await $X(f1.currentLocale??"");let A1;try{A1=await Promise.all(B.map((R)=>R(m)))}catch(R){if(q=this.viewRefusalStatus(m,R,g),q===null)throw R;T=null,B=[],m.routePath="",A1=[]}let{cookies:E$,headers:n}=C;if(q!==null)n.set("Cache-Control","no-store");V={data:A1,cookies:E$,headers:n,user:C.user,prefetchedData:C.serverQueries.snapshotResolved(),currentPathName:T,params:m.params,urlLocaleSegment:G,meta:C.renderMeta(),appId:N(Wj).id,features:await N(HZ).forClient()};let{params:E3,user:P8}=V,R$={},G1={};for(let R of A1??[]){let[w0,e]=Object.entries(R)?.[0]??[];if(!w0||!e)continue;G1[`${w0}:${T}`]=e.breadcrumb,R$[w0]=e}let vZ=R$.FILE;if(vZ){for(let R of E$)n.append("Set-Cookie",R.toString());try{await this.onRequestEnd(m)}catch(R){A$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}return await w8(vZ,n)}if(j){n.set("Content-Type","application/x-ndjson; charset=utf-8"),n.append("Vary",Jj),E$.forEach((w0)=>n.append("Set-Cookie",w0.toString())),await this.hooks.onRequestEnd(m);let R={meta:L&&!C.metadata.touched?null:V.meta,data:{[O]:R$},breadcrumbs:G1,prefetchedData:C.serverQueries.snapshotResolved(),i18n:f1,features:V.features,is404:!T,appId:V.appId,partial:L};return new Response(h5(R,C.serverQueries,void 0,({aborted:w0})=>b(()=>this.completeStream(m,C.serverQueries.summarize(w0)))),{headers:n})}if(n.set("Content-Type","text/html; charset=utf-8"),!I&&!(H&&T))n.append("Vary","User-Agent");let K1=Boolean(H&&T);if(!K1||r0.session)U8();for(let R of E$)n.append("Set-Cookie",R.toString());if(!K1||r0.csrf){let R=Bun.CSRF.generate(process.env.SECRET);n.append("Set-Cookie",`csrf_token=${R}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(m,{mintSession:!K1||r0.session})}catch(R){A$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}if(K1)a5(n,H);return await this.render({req:m,runInRequestScope:b,csrfTokenHMAC:Buffer.from(""),currentPathName:T,headers:n,i18n:f1,params:E3,pathname:J.pathname,serverQueries:C.serverQueries,userAgent:$.headers.get("user-agent"),noStream:I,url:J,user:P8,viewData:R$,breadcrumbs:G1,urlLocaleSegment:G,meta:V.meta,appId:V.appId,features:V.features,isOgRequest:W,staticView:T?H:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===EZ)if(j)return RU(q.payload.viewData??q.payload.api);else return Uj(q.payload.view);if(!g.has(q))this.hooks.onRequestFail(m,q);if(RZ(q))return console.error(q),j?SZ():Uj(Gj());if(q instanceof H1&&q.status===403)return j?SZ():Uj(Gj());throw q}},Z)}}function Dj(){let $=JSON.stringify({error:b1("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 zX extends S0{routes={"/api-routes":this.get(()=>{let $=N(F8).flatRoutes,Z=[];for(let[J,j]of Object.entries($))for(let[W,Y]of Object.entries(j)){let{exec:z,middleware:X}=Y;Z.push({path:J,method:W,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=N(S3).flatViewRoutes,Z=[];for(let[J,{middleware:j,viewPath:W}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:W,middleware:j});return Z})}}var bU=new Set([R1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),vU=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,kU=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function wU($,Z,J,j){for(let[W,Y]of Object.entries(J.headers??{})){if(Y===void 0||Y===null)continue;let z=W.toLowerCase();if(bU.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${W}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(j&&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(W,Y)}for(let[W,Y]of Object.entries(J.cookies??{})){if(Y===void 0||Y===null)continue;if(W===R1)throw Error(`dispatchAs: credentials may not set the "${R1}" cookie. The access token stays the initiator's.`);if(!vU.test(W)||!kU.test(Y))throw Error(`dispatchAs: "${W}" is not a cookie a Cookie header can carry.`);Z.push(`${W}=${Y}`)}}function qU($,Z){let J=$.body.getReader(),j=!1,W=()=>{if(j)return;j=!0;try{Z()}catch(z){console.error(z)}},Y=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(O){W(),z.error(O);return}if(X.done){W();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{W()}}},{highWaterMark:0});return new Response(Y,{status:$.status,statusText:$.statusText,headers:$.headers})}function ZX($){let{status:Z=400,data:J,headers:j}=$,W=new Headers({"Content-Type":"application/json",...j});if(!W.has("Cache-Control"))W.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:W})}function JX($,Z,J){let j=[];Z?.forEach((z,X)=>j.push([X,z]));let W=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(j.length===0&&W.length===0)return $;let Y=(z)=>{for(let[X,O]of j){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,O)}for(let X of W)z.append("Set-Cookie",X)};try{return Y($.headers),$}catch{let z=new Headers($.headers);return Y(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}class F8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=r7();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=g4({"/":$.rootRouter,"/auth":b4,"/__gemi__/services/i18n":v4,"/__gemi__/services/logs":y4,"/__gemi__/services/image":q4,"/__gemi__/debug":zX})}getRouteHandlerAndParams($){let Z=new URL($.url),J=YX(Z.pathname),j={},W;for(let[Y]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:Y});if(z.test({pathname:J})){W=Y,j=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:j,path:W}}async runRouteMiddleware($,Z){let j=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await N(CZ).runMiddleware(j)}catch(W){if(W.kind===EZ)return ZX(W.payload.api);else{if(x3(W))return Dj();if(this.onRequestFail(Z,W),console.error(W),RZ(W))return SZ();throw W}}}async getRouteData($){let Z=this.flatRoutes[$],J=f.getStore(),j=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),W={};try{W=await j()}catch(Y){if(Y.kind===EZ)return ZX(Y.payload.api);if(x3(Y))return Dj();if(this.onRequestFail(J.req,Y),console.error(Y),RZ(Y))return SZ();throw Y}return W}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let j=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(W){A$.error(W?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(W)})}finally{$.destroy()}};if(!$.hasPendingWork()){await j();return}$.whenIdle().then(j).catch((W)=>{console.error(W)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:j}=this.getRouteHandlerAndParams($),W=this.flatRoutes[j];if(!W||!W[$.method])return new Response(JSON.stringify({error:b1("not_found","Not found",404)}),{status:404});let Y=new A($,J,"api",j);if(!this.isFrameworkRoute(j))this.onRequestStart(Y);return await f.run(Y,async()=>{let z=f.getStore(),X=!1,O=async()=>{X=!0,await this.endRequest(z,Y,j)};try{let G=N(o);if(G.isEnabled){let D=G.detectLocale(Y);z.setLocale(D)}z.setRequest(Y),N(CZ).applyDefaultBodyLimit($);let K=await this.runRouteMiddleware(j,Y);if(K instanceof Response){let D=JX(K,z.headers,z.cookies);return await O(),D}let Q=await this.getRouteData(j),U=z.headers,F=z.cookies;if(Q instanceof Response){let D=JX(Q,U,F);if(this.isOpenEndedBody($,D)){let T=qU(D,()=>this.endRequest(z,Y,j));return X=!0,T}return await O(),D}let B=(y$(Q)?Q:J$.json(Q)).toResponse(U,F);return await O(),B}catch(G){if(!X)try{await O()}catch(K){console.error(K)}throw G}},Z)}async dispatchAs($,Z,J,j,W){let Y=new URL($.rawRequest.url).origin,z=new URL(`${Y}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==Y||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 O=W?.identity;if(O!==void 0&&(typeof O!=="object"||!O?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let G=new Headers,K=[],Q=O?null:$.cookies.get(R1);if(Q)K.push(`${R1}=${Q}`);if(W?.credentials)wU(G,K,W.credentials,O!==void 0);if(K.length>0)G.set("Cookie",K.join("; "));let U=O?null:$.headers.get(R1);if(U)G.set(R1,U);let F=$.headers.get("User-Agent");if(F)G.set("User-Agent",F);let B;if(j instanceof FormData)B=j;else if(j!==void 0)G.set("Content-Type","application/json"),B=JSON.stringify(j);let D=new Request(z,{method:Z,headers:G,body:B,...W?.signal?{signal:W.signal}:{}});if(jX(D,m$($),O?.grant,W?.progress),$.domain)AZ(D,$.domain);let T=O?{user:O.user}:void 0;return f.exit(()=>WX.exit(()=>this.handleApiRequest(D,T)))}}import{timingSafeEqual as yU}from"crypto";var T8="",Mj="*",gU=60000,mU=1e4,Tj=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,D8=16,XX=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,Vj="x-forwarded-host";function OX($){return $.startsWith(":")}function Ij($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),j=Buffer.from(Z,"utf8");return J.length===j.length&&yU(J,j)}function pU($){if(!$)return null;if($===!0)return{header:Vj,secret:null};return{header:($.hostHeader??Vj).toLowerCase(),secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function hU($){if(!$||$===!0)return;let{hostHeader:Z,secret:J}=$;if(Z!==void 0&&(typeof Z!=="string"||!XX.test(Z)))throw Error(`\`route.domains.trustProxy.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(Z)}.`);if(!J)return;if(typeof J.header!=="string"||!XX.test(J.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${J.header}".`);if(J.header.toLowerCase()===(Z??Vj).toLowerCase())throw Error("`route.domains.trustProxy.secret.header` names the same header as `hostHeader`; the secret needs a header of its own.");if(typeof J.value!=="string"||J.value.length<D8)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${D8} characters. A guessable one lets any client name its own host.`)}function O1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function cU($){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 uU($){let Z=O1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((Y)=>Tj.test(Y)))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<D8)throw Error(`\`route.domains.ask.secret\` must be at least ${D8} characters. A guessable one is worse than leaving \`ask\` out.`);hU($.trustProxy);let j=new Set,W=null;for(let Y of $.groups??[]){let{subdomain:z}=Y;if(j.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(j.add(z),OX(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(W)throw Error(`\`route.domains\` declares two param subdomains, "${W.subdomain}" and "${z}"; a host could match either.`);W=Y;continue}if(Y.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)=>Tj.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!j.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&W&&!W.exists)throw Error(`\`route.domains.ask\` is set, so "${W.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class Nj{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){uU($),this.root=O1($.root),this.hostTrust=pU($.trustProxy);for(let Z of $.groups??[])if(OX(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??gU,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!Ij($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}hostOf($){return O1(this.forwardedHost($))??O1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),j=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),W=this.forwardedHost($),Y=W&&O1(W)?cU(W):null;return`${j}://${Y??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:Mj,params:{},custom:!0};return null}async allows($,Z){let J=O1($);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:T8,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let j=$.slice(0,-(this.root.length+1)),W=this.fixed.get(j);if(W)return{host:$,group:W.subdomain,params:{},custom:!1};if(this.param&&Tj.test(j)){let Y={[this.param.name]:j};if(this.param.exists&&!await this.param.exists(Y,Z))return null;return{host:$,group:this.param.subdomain,params:Y,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 j=this.inFlight.get($);if(j)return j;let W=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,W);let Y;try{Y=await W}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=mU)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:Y,expiresAt:Date.now()+this.cacheTtlMs})}return Y}forget($){if($===void 0)this.cache.clear();else{let Z=O1($);if(Z)this.cache.delete(Z)}}}var dU="/__gemi__/domains/ask";class a0{static token="router.domains";resolver;acceptsCustomDomains;groups=new Map;constructor($,Z){this.groups.set(T8,$);let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new Nj(J);let j=(W)=>({api:W.api?new F8({...Z.api,...W.api}):$.api,view:W.view?new S3({...Z.view,...W.view}):$.view});for(let W of J.groups??[])this.groups.set(W.subdomain,j(W));if(J.custom?.fallback)this.groups.set(Mj,j(J.custom.fallback))}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)GX($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return AZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==dU)return null;if(!Ij(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),j=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:j?200:404})}dispatchers($){return this.groups.get($?.group??T8)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,j]of this.groups){if($.has(j.view))continue;$.add(j.view),Z.push({group:J,view:j.view})}return Z}}function V8($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var KX=600000;function QX($,Z){return[m3($,Z),m3($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new r8){this.config={...M8(fW($),$),emailCode:o8($.emailCode)},this.provider=Z}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=N().bound(a0)?N(a0).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"?N(a0).resolver?.root:O1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let j=$.domain?.host??O1(new URL($.rawRequest.url).host);return j===J||j?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!u8($))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 j=Date.now(),W=V8(J.expiresAt),Y=V8(J.absoluteExpiresAt);if(W<=j||Y<=j)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,j);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let j=f.getStore()?.req;if(!j)return null;let W=Date.now(),Y=Math.floor(W/KX),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:j,userAgent:Z}))return null;let G=m3($,Y),K=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:K,userAgent:Z,...this.freshLifetime(W)}),!0}))z=G}if(!z){for(let G of QX($,Y))if((await this.userProvider.findSession({token:G,userAgent:Z}))?.user){z=G;break}}if(!z)return null;let O=await this.getSession(z,Z);if(O)j.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(j,new Date(O.expiresAt)));return O}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(u8($)||!this.config.migrateLegacySession){let W=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),W}let J=Math.floor(Date.now()/KX),j=QX($,J);return this.userProvider.withLegacySessionLock($,async()=>{let W=await this.userProvider.findSession({token:$,userAgent:Z});for(let Y of j){if(W?.user)break;W=await this.userProvider.findSession({token:Y,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let Y of j)await this.userProvider.deleteSession({token:Y});return W})}requestCarryingCookie($){let Z=f.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 j=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),W=await this.userProvider.updateSession({token:$.token,expiresAt:j}),Y=this.requestCarryingCookie($.token);if(Y)Y.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(Y,j));if(!W)return $;return{...$,expiresAt:W.expiresAt??j}}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}),j=new A;if(j.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(j,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new A,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new W$;let j=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),W=VW(J),Y=await this.userProvider.createSessionV2({token:W,userId:J,userAgent:j,...this.freshLifetime(Date.now())}),z=await this.userProvider.findSession({token:W,userAgent:j??""});return z?.user?z:Y}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:j}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:j}}return{}}async issueOneTimeCode($,Z){await this.userProvider.deleteMagicLinkToken($);let J=await this.config.generateMagicLinkToken($),j=await this.config.generateCode($),W=typeof j==="string"&&j!==""?j:_W(Z);return await this.userProvider.createMagicLinkToken({email:$,token:p3("link",$,J),pin:p3("pin",$,W)}),{email:$,pin:W,token:J}}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:j,maxAttempts:W}=this.config.emailCode,Y=await this.userProvider.findMagicLinkTokenByEmail($);if(!Y)return dZ("pin",$,null,Z),{status:"invalid"};let z=V8(Y.createdAt);if(z+j*60000<=Date.now())return dZ("pin",$,null,Z),{status:"expired"};if(!await SW(Y.id,z,W,j))return await this.userProvider.claimMagicLinkToken(Y.id),{status:"too_many_attempts"};if(!dZ("pin",$,Y.pin,Z))return{status:"invalid"};if(J.claim!==!1&&!await this.userProvider.claimMagicLinkToken(Y.id))return{status:"invalid"};return{status:"ok",row:Y}}async verifyMagicLinkToken($,Z){let J=await this.userProvider.findMagicLinkTokenByEmail($),j=dZ("link",$,J?.token,Z);if(!J||!j)return!1;if(V8(J.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.userProvider.claimMagicLinkToken(J.id)}}class x$ extends z0{static getFacadeAccessor(){return E}static async user(){let $=f.getStore(),Z=$?.user;if(!Z){if(Z=await q3(this.getFacadeRoot(),$?.req),Z)$?.setUser(Z)}if(Z)return Z;throw new W$({redirectTo:w3($?.req,this.getFacadeRoot().config.signInPath)})}static intendedUrl($){let Z=f.getStore()?.req;return g$(Z?.search.get(j$),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await x$.user();if(!await $(Z))throw new p$}static async guardSafe($){let Z=await x$.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class I8{static ensure($,Z={}){let J=f.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new xZ(P3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=I8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){I8.ensure($,Z[0])}static noPrefetch(){let $=f.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new xZ(P3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function UX($,Z,J="/"){let j=new URL($.origin),W=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,Y=new URL(J.startsWith("/")?J:`/${J}`,j),z=lU(W);if(!z)throw Error(`"${W}" 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(Y.hostname=z.hostname,z.port)Y.port=z.port;return Y.toString()}function lU($){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 BX{static absolute($,...Z){return`${process.env.HOST_NAME}${X0(String($),Z[0]??{})}`}static relative($,...Z){return X0(String($),Z[0]??{})}static forDomain($,Z,...J){let j=N(a0).resolver;if(!j)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let W=f.getStore()?.req?.rawRequest,Y=W?j.publicOrigin(W):process.env.HOST_NAME;if(!Y)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` for the protocol.");return UX({root:j.root,origin:Y},$,X0(String(Z),J[0]??{}))}}class FX{name="Meta";static description($){f.getStore().metadata.description($)}static title($){f.getStore().metadata.title($)}static openGraph($){f.getStore().metadata.openGraph($)}}var iU={set($,Z,J){f.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(f.getStore().req.cookies.has($))return!1;return f.getStore().setCookie($,Z,J),!0},delete($,Z){f.getStore().deleteCookie($,Z)}};class S1 extends z0{static getFacadeAccessor(){return DX}static get client(){return this.getFacadeRoot().client}static get($){return S1.client.get($)}static set($,Z){return S1.client.set($,Z)}static del(...$){return S1.client.del(...$)}static exists($){return S1.client.exists($)}static incr($){return S1.client.incr($)}static expire($,Z){return S1.client.expire($,Z)}static ttl($){return S1.client.ttl($)}}class TX extends z0{static getFacadeAccessor(){return e0}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}}class MX extends z0{static getFacadeAccessor(){return VX}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}function FN($){return $}function IX(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function N8($){let Z=new URLSearchParams;for(let[J,j]of $)Z.append(J,String(j));return Z.toString()}function Cj($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[j,W]of J){let Y=Number(W);if(W!==""&&Number.isSafeInteger(Y)&&Y>=0)Z.set(j,Y)}return Z}var{SQL:sU}=globalThis.Bun;function nU(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var oU=async($)=>{let Z=new sU($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,j,W)=>Z.listen(J,j,W),close:()=>Z.close({timeout:1})}},aU=async($)=>{let Z;try{Z=(await import("./chunk-zns7xcz9.js")).default}catch(j){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:j})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(j,W,Y)=>J.listen(j,W,Y),close:()=>J.end({timeout:1}).catch(()=>{})}},NX=($)=>nU()?oU($):aU($);var rU=/^[A-Za-z_][A-Za-z0-9_]*$/;class Lj{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",j=Z.entriesTable??"gemi_changes",W=Z.notifyChannel??"gemi_changes";for(let z of[J,j,W])if(!rU.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let Y=Z.retain??1000;if(!Number.isInteger(Y)||Y<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Y}.`);this.headsTable=J,this.entriesTable=j,this.notifyChannel=W,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=Y,this.listener=Z.listener??NX}async createTable(){for(let $ of tU(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let W=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return W();let Y=this.sqliteTurn.then(W);return this.sqliteTurn=Y.catch(()=>{}),Y}let j=this.append(J,$,Z);return CX(j),j}async append($,Z,J){let j=$.unsafe(`"${this.headsTable}"`),W=$.unsafe(`"${this.entriesTable}"`),[Y]=await $`
16
+ INSERT INTO ${j} (channel, seq) VALUES (${Z}, 1)
17
+ ON CONFLICT (channel) DO UPDATE SET seq = ${j}.seq + 1
18
+ RETURNING seq
19
+ `,z=Number(Y.seq);if(await $`
20
+ INSERT INTO ${W} (channel, seq, data, created_at)
21
+ VALUES (${Z}, ${z}, ${JSON.stringify(J??null)}, ${Date.now()})
22
+ `,z>this.retain)await $`DELETE FROM ${W} WHERE channel = ${Z} AND seq <= ${z-this.retain}`;if(this.dialect==="postgres")await $`SELECT pg_notify(${this.notifyChannel}, ${`${z} ${Z}`})`;return z}async heads($){let Z=new Map($.map((W)=>[W,0]));if($.length===0)return Z;let J=this.sql,j=await J`
23
+ SELECT channel, seq FROM ${J.unsafe(`"${this.headsTable}"`)}
24
+ WHERE channel IN ${J([...$])}
25
+ `;for(let W of j)Z.set(W.channel,Number(W.seq));return Z}async read($,Z,J){let j=this.sql,[W]=await j`
26
+ SELECT seq FROM ${j.unsafe(`"${this.headsTable}"`)} WHERE channel = ${$}
27
+ `,Y=W?Number(W.seq):0;if(Z>Y)return{entries:[],head:Y,gap:!0};if(Z===Y)return{entries:[],head:Y,gap:!1};let z=await j`
28
+ SELECT seq, data FROM ${j.unsafe(`"${this.entriesTable}"`)}
29
+ WHERE channel = ${$} AND seq > ${Z}
30
+ ORDER BY seq
31
+ LIMIT ${J}
32
+ `;if(z.length===0||Number(z[0].seq)!==Z+1)return{entries:[],head:Y,gap:!0};return{entries:z.map((X)=>({seq:Number(X.seq),data:JSON.parse(X.data)})),head:Y,gap:!1}}async listen($,Z){if(this.dialect!=="postgres")return{close:async()=>{}};if(!this.url)throw Error("The change feed's database driver needs the connection's url to LISTEN. Build it from a DatabaseManager connection, which has one.");let J=await this.listener(this.url);try{await J.listen(this.notifyChannel,(j)=>{let W=j.indexOf(" "),Y=Number(j.slice(0,W));if(W>0&&Number.isInteger(Y))$(j.slice(W+1),Y)},Z)}catch(j){throw await J.close(),j}return{close:()=>J.close()}}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let $=F1();if($===void 0||z$()!==this.connection)return;return $}}function tU($,Z){return[`CREATE TABLE IF NOT EXISTS "${$}" (
33
+ "channel" TEXT NOT NULL PRIMARY KEY,
34
+ "seq" BIGINT NOT NULL
35
+ )`,`CREATE TABLE IF NOT EXISTS "${Z}" (
36
+ "channel" TEXT NOT NULL,
37
+ "seq" BIGINT NOT NULL,
38
+ "data" TEXT NOT NULL,
39
+ "created_at" BIGINT NOT NULL,
40
+ PRIMARY KEY ("channel", "seq")
41
+ )`]}class Pj{logs=new Map;retain;constructor($={}){let Z=$.retain??1000;if(!Number.isInteger(Z)||Z<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Z}.`);this.retain=Z}async publish($,Z){let J=this.logs.get($);if(!J)J={head:0,entries:[]},this.logs.set($,J);let j=++J.head;if(J.entries.push({seq:j,data:Z===void 0?null:structuredClone(Z)}),J.entries.length>this.retain)J.entries.splice(0,J.entries.length-this.retain);return j}async heads($){return new Map($.map((Z)=>[Z,this.logs.get(Z)?.head??0]))}async read($,Z,J){let j=this.logs.get($),W=j?.head??0;if(Z>W)return{entries:[],head:W,gap:!0};if(!j||Z===W)return{entries:[],head:W,gap:!1};let Y=j.entries[0]?.seq??W+1;if(Y>Z+1)return{entries:[],head:W,gap:!0};let z=Z+1-Y;return{entries:j.entries.slice(z,z+J),head:W,gap:!1}}}var xX=new TextEncoder;function LX($,Z){return xX.encode(`id: ${$}
42
+ data: ${JSON.stringify(Z)}
43
+
44
+ `)}function SX($,Z,J,j){let W=Z instanceof Request?Z:Z.rawRequest,Y=j.cursor??W.headers.get("Last-Event-ID")??new URL(W.url).searchParams.get("cursor"),z;try{z=$.subscribe(J,{cursor:Y,signal:W.signal})}catch(U){if(!(U instanceof C8))throw U;return new Response(JSON.stringify({error:"The change feed is at capacity."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":String(j.retryAfter??5)}})}let X=null,O=!1,G=!1,K=(U)=>{if(X)clearInterval(X);if(X=null,z.close(),G)return;G=!0;try{U.close()}catch{}},Q=new ReadableStream({start(U){X=setInterval(()=>{if(HX())return K(U);try{U.enqueue(xX.encode(PX))}catch{K(U)}},$.config.keepaliveInterval)},async pull(U){try{if(!O){if(await z.ready(),O=!0,!G)U.enqueue(LX(z.cursor,{type:"ready"}));return}let F=await z.next();if(F.done||G)return K(U);U.enqueue(LX(z.cursor,F.value))}catch(F){if(!G)console.error("[gemi] A change feed stream failed.",F);K(U)}},cancel(){if(G=!0,X)clearInterval(X);X=null,z.close()}});return new Response(Q,{headers:_X()})}var fX=255,AX=500,eU=30000;class C8 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class Sj{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=AX;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=M8(IX(),$),this.driver=ZB(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){xj($);let J=Z===void 0?null:Z;if(F1()!==void 0&&!this.driver.joinsTransaction?.())return Hj(async()=>{this.wake($,await this.driver.publish($,J))}),null;let j=await this.driver.publish($,J);return Hj(()=>this.wake($,j)),j}async head($){return xj($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=_j($);return N8(await this.driver.heads(Z))}subscribe($,Z={}){let J=_j($);if(this.all.size>=this.config.maxSubscriptions)throw new C8(this.config.maxSubscriptions);let j=new EX(this,J,$B(Z.cursor),this.config,Z.signal);this.all.add(j);for(let W of J){let Y=this.followers.get(W);if(!Y)this.followers.set(W,Y=new Set);Y.add(j)}return this.startListening(),this.startPolling(),j}stream($,Z,J={}){return SX(this,$,_j(Z),J)}async close(){if(this.listenState="closed",this.retryTimer)clearTimeout(this.retryTimer);this.retryTimer=null,this.stopPolling();for(let Z of this.all)Z.close();let $=this.listening;this.listening=null,await $?.close(),await this.driver.close?.()}forget($){if(!this.all.delete($))return;for(let Z of $.channels){let J=this.followers.get(Z);if(J?.delete($),J?.size===0)this.followers.delete(Z)}if(this.all.size===0)this.stopPolling()}poll(){return this.polling??=(async()=>{try{let $=[...this.followers.keys()];for(let Z=0;Z<$.length;Z+=500){let J=await this.driver.heads($.slice(Z,Z+500));for(let[j,W]of J)this.wake(j,W)}}catch($){console.error("[gemi] The change feed could not read its channels' heads.",$)}finally{this.polling=null}})(),this.polling}startPolling(){if(this.pollTimer)return;this.pollTimer=setInterval(()=>void this.poll(),this.config.pollInterval),this.pollTimer.unref?.()}stopPolling(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null}wake($,Z){for(let J of this.followers.get($)??[])J.moved($,Z)}resync(){this.poll()}startListening(){if(this.listenState!=="off"||!this.driver.listen)return;this.connect()}async connect(){this.listenState="connecting",this.retryTimer=null;try{let $=await this.driver.listen((Z,J)=>this.wake(Z,J),()=>this.resync());if(this.listenState!=="connecting"){await $.close();return}this.listening=$,this.listenState="listening",this.backoffMs=AX,this.resync()}catch($){if(this.listenState!=="connecting")return;console.error(`[gemi] The change feed could not listen for other instances' changes; retrying in ${this.backoffMs}ms.`,$),this.listenState="retrying",this.retryTimer=setTimeout(()=>void this.connect(),this.backoffMs),this.retryTimer.unref?.(),this.backoffMs=Math.min(this.backoffMs*2,eU)}}}class EX{manager;config;signal;channels;positions=new Map;readTo=new Map;dirty=new Set;pending=[];started=null;wakeUp=null;closed=!1;onAbort=()=>this.close();constructor($,Z,J,j,W){this.manager=$;this.config=j;this.signal=W;this.channels=Z;for(let Y of Z){let z=J.get(Y);if(z!==void 0)this.positions.set(Y,z),this.readTo.set(Y,z),this.dirty.add(Y)}if(W?.aborted)this.close();else W?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return N8(this.positions)}get isClosed(){return this.closed}ready(){return this.started??=(async()=>{let $=this.channels.filter((J)=>!this.positions.has(J));if($.length===0)return;let Z=await this.manager.driver.heads($);for(let J of $){let j=Z.get(J)??0;this.positions.set(J,j),this.readTo.set(J,j)}})(),this.started}async next(){await this.ready();for(;;){if(this.closed)return{done:!0,value:void 0};let $=this.pending.shift();if($)return this.positions.set($.channel,$.seq),{done:!1,value:$};let Z=this.dirty.values().next().value;if(Z!==void 0){await this.read(Z);continue}await this.idle()}}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}close(){if(this.closed)return;this.closed=!0,this.pending.length=0,this.signal?.removeEventListener("abort",this.onAbort),this.manager.forget(this),this.wake()}moved($,Z){let J=this.readTo.get($);if(J!==void 0&&Z===J)return;this.dirty.add($),this.wake()}async read($){let Z=this.readTo.get($)??0;this.dirty.delete($);let{batchSize:J}=this.config,{entries:j,head:W,gap:Y}=await this.manager.driver.read($,Z,J);if(this.closed)return;if(Y){this.readTo.set($,W),this.pending.push({type:"reset",channel:$,seq:W});return}for(let z of j)this.readTo.set($,z.seq),this.pending.push({type:"change",channel:$,seq:z.seq,data:z.data});if(j.length===J)this.dirty.add($)}idle(){return new Promise(($)=>{this.wakeUp=$})}wake(){let $=this.wakeUp;this.wakeUp=null,$?.()}}function xj($){if(typeof $!=="string"||$===""||$.length>fX)throw Error(`A change feed channel is a string of 1 to ${fX} characters; got ${JSON.stringify($)}.`)}function _j($){let Z=[...new Set(typeof $==="string"?[$]:$)];if(Z.length===0)throw Error("A change feed subscription needs at least one channel.");for(let J of Z)xj(J);return Z}function $B($){if($===void 0||$===null)return new Map;if(typeof $==="string")return Cj($);let Z=$ instanceof Map?[...$]:Object.entries($);return Cj(N8(new Map(Z)))}function ZB($,Z){if($==="memory")return new Pj;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The change feed driver needs the application it belongs to, and this ChangeFeedManager was built without one. Pass { application }.");if($==="database")return new Lj(Z.make(X$));return $(Z)}if(typeof $==="string")throw Error(`Unknown change feed driver "${$}". The changeFeed slice's driver is "memory", "database", a ChangeFeedDriver, or a function returning one.`);return $}class RX extends z0{static getFacadeAccessor(){return Sj}static publish($,Z){return this.getFacadeRoot().publish($,Z)}static head($){return this.getFacadeRoot().head($)}static cursor($){return this.getFacadeRoot().cursor($)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}}class bX extends z0{static getFacadeAccessor(){return HZ}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 L8{bound;constructor($){this.bound=$}get name(){return this.bound??z$()}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 wX(J.sql,(j)=>vX(Z,()=>$(j)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-hz6yzzbz.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:j,values:W}=yX($,qX(J.dialect),Z);return(this.handle()??J.sql).unsafe(j,W)}handle(){let $=F1();if($===void 0)return;return z$()===this.name?$:void 0}connection($=this.name){return kX($),N(X$).connection($)}}var bZ=new L8;class gX extends z0{static getFacadeAccessor(){return X$}static connection($){return new L8($)}static get sql(){return bZ.sql}static get dialect(){return bZ.dialect}static query($){return bZ.query($)}static execute($){return bZ.execute($)}static transaction($){return bZ.transaction($)}static schema(){return bZ.schema()}static close(){return this.getFacadeRoot().close()}}export{Q1 as Mc,kZ as Nc,S8 as Oc,w$ as Pc,qZ as Qc,S0 as Rc,b8 as Sc,v8 as Tc,cj as Uc,q$ as Vc,J$ as Wc,JO as Xc,w8 as Yc,E1 as Zc,O0 as _c,jO as $c,WO as ad,c8 as bd,u8 as cd,VW as dd,e0 as ed,yZ as fd,jW as gd,m$ as hd,MW as id,IW as jd,l8 as kd,i8 as ld,p3 as md,dZ as nd,AD as od,fW as pd,cO as qd,r8 as rd,q3 as sd,x$ as td,$$ as ud,I8 as vd,BX as wd,FX as xd,iU as yd,S1 as zd,TX as Ad,MX as Bd,FN as Cd,IX as Dd,N8 as Ed,Cj as Fd,Lj as Gd,Pj as Hd,C8 as Id,Sj as Jd,EX as Kd,RX as Ld,R5 as Md,zj as Nd,b5 as Od,v5 as Pd,jU as Qd,k5 as Rd,Xj as Sd,zU as Td,XU as Ud,Oj as Vd,w5 as Wd,q5 as Xd,HZ as Yd,bX as Zd,L8 as _d,gX as $d,L4 as ae,HQ as be,k4 as ce,w4 as de,_T as ee,s7 as fe,n7 as ge,y3 as he,CZ as ie,pT as je,r7 as ke,t7 as le,Wj as me,SZ as ne,Gj as oe,JM as pe,Fj as qe,fU as re,Uj as se,RU as te,S3 as ue,Dj as ve,ZX as we,JX as xe,F8 as ye,a0 as ze,E as Ae,oj as Be,aj as Ce,tj as De,zW as Ee,XW as Fe,OW as Ge,m8 as He,OO as Ie,h$ as Je,U0 as Ke,B1 as Le,u$ as Me,v1 as Ne,d$ as Oe,l$ as Pe,i$ as Qe,pZ as Re,hZ as Se,k1 as Te,uZ as Ue,BW as Ve};
45
+
46
+ //# debugId=3D21A2DD833DCA1864756E2164756E21