gemi 0.111.0 → 0.112.1

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 (265) hide show
  1. package/dist/ai/Agent.d.ts +54 -1
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentController.d.ts +41 -0
  4. package/dist/ai/AgentController.d.ts.map +1 -1
  5. package/dist/ai/client/index.d.ts +1 -1
  6. package/dist/ai/client/index.d.ts.map +1 -1
  7. package/dist/ai/contextCompaction.d.ts +247 -0
  8. package/dist/ai/contextCompaction.d.ts.map +1 -0
  9. package/dist/ai/contextWindow.d.ts +18 -0
  10. package/dist/ai/contextWindow.d.ts.map +1 -1
  11. package/dist/ai/index.d.ts +5 -1
  12. package/dist/ai/index.d.ts.map +1 -1
  13. package/dist/ai/index.js +93 -14
  14. package/dist/ai/index.js.map +16 -10
  15. package/dist/ai/jobs/AgentJob.d.ts +259 -0
  16. package/dist/ai/jobs/AgentJob.d.ts.map +1 -0
  17. package/dist/ai/jobs/AgentJobDeadlineSweep.d.ts +18 -0
  18. package/dist/ai/jobs/AgentJobDeadlineSweep.d.ts.map +1 -0
  19. package/dist/ai/jobs/AgentJobStore.d.ts +141 -0
  20. package/dist/ai/jobs/AgentJobStore.d.ts.map +1 -0
  21. package/dist/ai/jobs/DatabaseAgentJobStore.d.ts +82 -0
  22. package/dist/ai/jobs/DatabaseAgentJobStore.d.ts.map +1 -0
  23. package/dist/ai/jobs/contextBlock.d.ts +31 -0
  24. package/dist/ai/jobs/contextBlock.d.ts.map +1 -0
  25. package/dist/ai/jobs/index.d.ts +6 -0
  26. package/dist/ai/jobs/index.d.ts.map +1 -0
  27. package/dist/ai/jobs/overlay.d.ts +49 -0
  28. package/dist/ai/jobs/overlay.d.ts.map +1 -0
  29. package/dist/ai/providers/request.d.ts.map +1 -1
  30. package/dist/ai/store/Attachments.d.ts +6 -0
  31. package/dist/ai/store/Attachments.d.ts.map +1 -1
  32. package/dist/ai/store/MemoryAgentStore.d.ts +3 -0
  33. package/dist/ai/store/MemoryAgentStore.d.ts.map +1 -1
  34. package/dist/ai/types.d.ts +28 -0
  35. package/dist/ai/types.d.ts.map +1 -1
  36. package/dist/app/index.js +1 -1
  37. package/dist/bin/gemi.js +13 -2
  38. package/dist/bin/gemi.js.map +4 -4
  39. package/dist/bun/plugin.js +1 -1
  40. package/dist/bun/preload.js +1 -1
  41. package/dist/{chunk-30xjcyzh.js → chunk-0z2h35d7.js} +2 -2
  42. package/dist/{chunk-30xjcyzh.js.map → chunk-0z2h35d7.js.map} +1 -1
  43. package/dist/{chunk-358sdcx9.js → chunk-15a1mrdv.js} +2 -2
  44. package/dist/{chunk-358sdcx9.js.map → chunk-15a1mrdv.js.map} +1 -1
  45. package/dist/{chunk-hf7a51s3.js → chunk-18c3y8m3.js} +2 -2
  46. package/dist/{chunk-hf7a51s3.js.map → chunk-18c3y8m3.js.map} +1 -1
  47. package/dist/{chunk-tq85n8zh.js → chunk-1pvkw2pq.js} +2 -2
  48. package/dist/{chunk-tq85n8zh.js.map → chunk-1pvkw2pq.js.map} +1 -1
  49. package/dist/{chunk-8afxrmdc.js → chunk-2taa0brj.js} +2 -2
  50. package/dist/{chunk-8afxrmdc.js.map → chunk-2taa0brj.js.map} +1 -1
  51. package/dist/{chunk-5cygrbxv.js → chunk-30yg31sz.js} +2 -2
  52. package/dist/{chunk-5cygrbxv.js.map → chunk-30yg31sz.js.map} +1 -1
  53. package/dist/{chunk-3y8q8x11.js → chunk-3z9vhjd7.js} +2 -2
  54. package/dist/{chunk-3y8q8x11.js.map → chunk-3z9vhjd7.js.map} +1 -1
  55. package/dist/chunk-4sb1484x.js +46 -0
  56. package/dist/{chunk-h3864a8z.js.map → chunk-4sb1484x.js.map} +13 -4
  57. package/dist/{chunk-0sjh5v1n.js → chunk-53bek7sp.js} +1 -1
  58. package/dist/{chunk-xkc7ftnq.js → chunk-57edag57.js} +3 -3
  59. package/dist/{chunk-xkc7ftnq.js.map → chunk-57edag57.js.map} +1 -1
  60. package/dist/{chunk-ddr4qvvt.js → chunk-5az0mq4p.js} +3 -3
  61. package/dist/{chunk-ddr4qvvt.js.map → chunk-5az0mq4p.js.map} +1 -1
  62. package/dist/{chunk-nsvktvp4.js → chunk-5waxjsvv.js} +2 -2
  63. package/dist/{chunk-nsvktvp4.js.map → chunk-5waxjsvv.js.map} +1 -1
  64. package/dist/{chunk-rfcygmf5.js → chunk-6w79zajj.js} +3 -3
  65. package/dist/{chunk-rfcygmf5.js.map → chunk-6w79zajj.js.map} +1 -1
  66. package/dist/{chunk-gb37722w.js → chunk-75ptmewf.js} +3 -3
  67. package/dist/{chunk-gb37722w.js.map → chunk-75ptmewf.js.map} +1 -1
  68. package/dist/{chunk-pyj7cd9t.js → chunk-851k0b26.js} +2 -2
  69. package/dist/{chunk-pyj7cd9t.js.map → chunk-851k0b26.js.map} +1 -1
  70. package/dist/{chunk-m6ystvtk.js → chunk-8reepafh.js} +2 -2
  71. package/dist/{chunk-m6ystvtk.js.map → chunk-8reepafh.js.map} +1 -1
  72. package/dist/{chunk-nvv9wej6.js → chunk-9hr0bcfy.js} +3 -3
  73. package/dist/{chunk-nvv9wej6.js.map → chunk-9hr0bcfy.js.map} +1 -1
  74. package/dist/{chunk-yqavgpwd.js → chunk-a9q2cr4w.js} +2 -2
  75. package/dist/{chunk-yqavgpwd.js.map → chunk-a9q2cr4w.js.map} +1 -1
  76. package/dist/{chunk-cy5qp6mz.js → chunk-amvy4r59.js} +2 -2
  77. package/dist/{chunk-cy5qp6mz.js.map → chunk-amvy4r59.js.map} +1 -1
  78. package/dist/{chunk-twnn7r66.js → chunk-b1mk12xg.js} +2 -2
  79. package/dist/{chunk-twnn7r66.js.map → chunk-b1mk12xg.js.map} +1 -1
  80. package/dist/{chunk-a6453d9s.js → chunk-b7cqwcbm.js} +2 -2
  81. package/dist/{chunk-a6453d9s.js.map → chunk-b7cqwcbm.js.map} +1 -1
  82. package/dist/{chunk-nncz308h.js → chunk-b7qjp7r1.js} +2 -2
  83. package/dist/{chunk-nncz308h.js.map → chunk-b7qjp7r1.js.map} +1 -1
  84. package/dist/chunk-beks65me.js +19 -0
  85. package/dist/{chunk-mb7q7s0a.js.map → chunk-beks65me.js.map} +3 -4
  86. package/dist/chunk-bf1ets45.js +5 -0
  87. package/dist/{chunk-11fsn5mr.js.map → chunk-bf1ets45.js.map} +4 -3
  88. package/dist/{chunk-9rchedr4.js → chunk-bhw7k8vp.js} +2 -2
  89. package/dist/{chunk-9rchedr4.js.map → chunk-bhw7k8vp.js.map} +1 -1
  90. package/dist/{chunk-k1vw22t2.js → chunk-ck0v2kzw.js} +2 -2
  91. package/dist/{chunk-k1vw22t2.js.map → chunk-ck0v2kzw.js.map} +1 -1
  92. package/dist/{chunk-6vr7f5fq.js → chunk-csbc1fxa.js} +3 -3
  93. package/dist/{chunk-6vr7f5fq.js.map → chunk-csbc1fxa.js.map} +1 -1
  94. package/dist/{chunk-kf71mjxa.js → chunk-d0trs736.js} +3 -3
  95. package/dist/{chunk-kf71mjxa.js.map → chunk-d0trs736.js.map} +1 -1
  96. package/dist/{chunk-zhs1r1z0.js → chunk-d8ekyng4.js} +3 -3
  97. package/dist/{chunk-zhs1r1z0.js.map → chunk-d8ekyng4.js.map} +1 -1
  98. package/dist/chunk-d9an2nra.js +5 -0
  99. package/dist/{chunk-hn67spz6.js.map → chunk-d9an2nra.js.map} +1 -1
  100. package/dist/{chunk-0d9qsmx2.js → chunk-dan79jab.js} +2 -2
  101. package/dist/{chunk-0d9qsmx2.js.map → chunk-dan79jab.js.map} +1 -1
  102. package/dist/{chunk-1yx2e0bh.js → chunk-ddad3902.js} +2 -2
  103. package/dist/{chunk-1yx2e0bh.js.map → chunk-ddad3902.js.map} +1 -1
  104. package/dist/{chunk-3cg7y62b.js → chunk-dm59ze55.js} +2 -2
  105. package/dist/{chunk-3cg7y62b.js.map → chunk-dm59ze55.js.map} +1 -1
  106. package/dist/{chunk-wvsv1jgg.js → chunk-dx7wpz5b.js} +2 -2
  107. package/dist/{chunk-wvsv1jgg.js.map → chunk-dx7wpz5b.js.map} +1 -1
  108. package/dist/{chunk-q9s7kwgt.js → chunk-eazqda9z.js} +3 -3
  109. package/dist/{chunk-q9s7kwgt.js.map → chunk-eazqda9z.js.map} +1 -1
  110. package/dist/{chunk-td8tha3j.js → chunk-es487acc.js} +1 -1
  111. package/dist/{chunk-9s851qz8.js → chunk-et3vhkbf.js} +2 -2
  112. package/dist/{chunk-9s851qz8.js.map → chunk-et3vhkbf.js.map} +1 -1
  113. package/dist/{chunk-qd2v93y4.js → chunk-f1y8eggf.js} +2 -2
  114. package/dist/{chunk-qd2v93y4.js.map → chunk-f1y8eggf.js.map} +1 -1
  115. package/dist/{chunk-1pem26zc.js → chunk-ga7c7tq0.js} +3 -3
  116. package/dist/{chunk-1pem26zc.js.map → chunk-ga7c7tq0.js.map} +1 -1
  117. package/dist/{chunk-c098fzvk.js → chunk-gcs9ydjv.js} +2 -2
  118. package/dist/{chunk-c098fzvk.js.map → chunk-gcs9ydjv.js.map} +1 -1
  119. package/dist/{chunk-bn5yn731.js → chunk-hfyxvdjj.js} +2 -2
  120. package/dist/{chunk-bn5yn731.js.map → chunk-hfyxvdjj.js.map} +1 -1
  121. package/dist/chunk-j0sncgxc.js +14 -0
  122. package/dist/{chunk-mn5xw79b.js.map → chunk-j0sncgxc.js.map} +6 -5
  123. package/dist/{chunk-p7r2w4qw.js → chunk-j9jqxv1d.js} +3 -3
  124. package/dist/{chunk-p7r2w4qw.js.map → chunk-j9jqxv1d.js.map} +1 -1
  125. package/dist/{chunk-jbrwt3cs.js → chunk-jdtn0zk2.js} +4 -4
  126. package/dist/{chunk-jbrwt3cs.js.map → chunk-jdtn0zk2.js.map} +1 -1
  127. package/dist/{chunk-s6jjy4y9.js → chunk-jn59bsww.js} +2 -2
  128. package/dist/{chunk-s6jjy4y9.js.map → chunk-jn59bsww.js.map} +1 -1
  129. package/dist/chunk-jn8hh25v.js +24 -0
  130. package/dist/{chunk-wqvvjd5r.js.map → chunk-jn8hh25v.js.map} +2 -2
  131. package/dist/chunk-k7rbkhhw.js +6 -0
  132. package/dist/{chunk-tdsfke9q.js.map → chunk-k7rbkhhw.js.map} +2 -2
  133. package/dist/{chunk-he7z7y9j.js → chunk-kk502yk2.js} +2 -2
  134. package/dist/{chunk-he7z7y9j.js.map → chunk-kk502yk2.js.map} +1 -1
  135. package/dist/{chunk-wsttx9rg.js → chunk-mrdarm2q.js} +2 -2
  136. package/dist/{chunk-wsttx9rg.js.map → chunk-mrdarm2q.js.map} +1 -1
  137. package/dist/chunk-mvtgx1mr.js +4 -0
  138. package/dist/{chunk-x78jrs4y.js.map → chunk-mvtgx1mr.js.map} +2 -2
  139. package/dist/{chunk-et4pv1b1.js → chunk-mx9y9mtx.js} +1 -1
  140. package/dist/{chunk-cttmy1jp.js → chunk-p2fhtf5r.js} +3 -3
  141. package/dist/{chunk-cttmy1jp.js.map → chunk-p2fhtf5r.js.map} +1 -1
  142. package/dist/{chunk-w7jsh3xd.js → chunk-qtbf3w6w.js} +2 -2
  143. package/dist/{chunk-w7jsh3xd.js.map → chunk-qtbf3w6w.js.map} +1 -1
  144. package/dist/chunk-qx87cdfg.js +5 -0
  145. package/dist/chunk-qx87cdfg.js.map +10 -0
  146. package/dist/{chunk-1kr25rcg.js → chunk-qyp652jz.js} +3 -3
  147. package/dist/{chunk-1kr25rcg.js.map → chunk-qyp652jz.js.map} +1 -1
  148. package/dist/{chunk-8b2tw2yp.js → chunk-rend2sbk.js} +1 -1
  149. package/dist/chunk-rx2shb3t.js +25 -0
  150. package/dist/chunk-rx2shb3t.js.map +19 -0
  151. package/dist/{chunk-mwqg079k.js → chunk-ryzcfxq7.js} +2 -2
  152. package/dist/{chunk-mwqg079k.js.map → chunk-ryzcfxq7.js.map} +1 -1
  153. package/dist/{chunk-7tx5y712.js → chunk-s9rfgxj5.js} +2 -2
  154. package/dist/{chunk-7tx5y712.js.map → chunk-s9rfgxj5.js.map} +1 -1
  155. package/dist/{chunk-1c1d0e60.js → chunk-scbvv2e4.js} +3 -3
  156. package/dist/{chunk-1c1d0e60.js.map → chunk-scbvv2e4.js.map} +1 -1
  157. package/dist/{chunk-1bkr5wnt.js → chunk-tb126j80.js} +2 -2
  158. package/dist/{chunk-1bkr5wnt.js.map → chunk-tb126j80.js.map} +1 -1
  159. package/dist/{chunk-pwmgqq7z.js → chunk-teny6xkw.js} +2 -2
  160. package/dist/{chunk-pwmgqq7z.js.map → chunk-teny6xkw.js.map} +1 -1
  161. package/dist/{chunk-09ypnhjv.js → chunk-tmrmwthr.js} +2 -2
  162. package/dist/{chunk-09ypnhjv.js.map → chunk-tmrmwthr.js.map} +1 -1
  163. package/dist/{chunk-h4sw6nt3.js → chunk-vgdcz7tk.js} +3 -3
  164. package/dist/{chunk-h4sw6nt3.js.map → chunk-vgdcz7tk.js.map} +1 -1
  165. package/dist/{chunk-xk930yaw.js → chunk-wexs11yy.js} +2 -2
  166. package/dist/{chunk-xk930yaw.js.map → chunk-wexs11yy.js.map} +1 -1
  167. package/dist/{chunk-k1xt2tw7.js → chunk-xs4c2nvz.js} +2 -2
  168. package/dist/{chunk-k1xt2tw7.js.map → chunk-xs4c2nvz.js.map} +1 -1
  169. package/dist/{chunk-1va15sfq.js → chunk-xv74rhay.js} +2 -2
  170. package/dist/{chunk-1va15sfq.js.map → chunk-xv74rhay.js.map} +1 -1
  171. package/dist/{chunk-sq2wkynk.js → chunk-yv1psptb.js} +2 -2
  172. package/dist/{chunk-sq2wkynk.js.map → chunk-yv1psptb.js.map} +1 -1
  173. package/dist/{chunk-tk5q8hkv.js → chunk-zfter1x0.js} +4 -4
  174. package/dist/{chunk-tk5q8hkv.js.map → chunk-zfter1x0.js.map} +1 -1
  175. package/dist/client/ClientRouter.d.ts.map +1 -1
  176. package/dist/client/index.d.ts +2 -0
  177. package/dist/client/index.d.ts.map +1 -1
  178. package/dist/client/index.js +215 -2
  179. package/dist/client/index.js.map +1 -1
  180. package/dist/client/useSubscription.d.ts +70 -0
  181. package/dist/client/useSubscription.d.ts.map +1 -0
  182. package/dist/config/index.js +1 -1
  183. package/dist/console/run.js +2 -2
  184. package/dist/console/run.js.map +2 -2
  185. package/dist/container/index.js +2 -2
  186. package/dist/container/index.js.map +1 -1
  187. package/dist/database/index.js +2 -2
  188. package/dist/database/index.js.map +1 -1
  189. package/dist/email/index.js +2 -2
  190. package/dist/email/index.js.map +1 -1
  191. package/dist/facades/ChangeFeed.d.ts +42 -0
  192. package/dist/facades/ChangeFeed.d.ts.map +1 -0
  193. package/dist/facades/index.d.ts +1 -0
  194. package/dist/facades/index.d.ts.map +1 -1
  195. package/dist/facades/index.js +2 -2
  196. package/dist/facades/index.js.map +1 -1
  197. package/dist/foundation/index.js +2 -2
  198. package/dist/foundation/index.js.map +1 -1
  199. package/dist/http/ResourcePolicy.d.ts +141 -0
  200. package/dist/http/ResourcePolicy.d.ts.map +1 -0
  201. package/dist/http/errors.d.ts +13 -0
  202. package/dist/http/errors.d.ts.map +1 -1
  203. package/dist/http/index.d.ts +2 -1
  204. package/dist/http/index.d.ts.map +1 -1
  205. package/dist/http/index.js +2 -2
  206. package/dist/http/index.js.map +1 -1
  207. package/dist/i18n/dictionaryRuntime.js +2 -2
  208. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  209. package/dist/i18n/index.js +2 -2
  210. package/dist/i18n/index.js.map +2 -2
  211. package/dist/kernel/index.js +3 -3
  212. package/dist/kernel/index.js.map +3 -3
  213. package/dist/kernel/providers.d.ts.map +1 -1
  214. package/dist/orm/index.js +2 -2
  215. package/dist/orm/index.js.map +1 -1
  216. package/dist/server/index.js +2 -2
  217. package/dist/server/index.js.map +1 -1
  218. package/dist/services/change-feed/ChangeFeedDriver.d.ts +94 -0
  219. package/dist/services/change-feed/ChangeFeedDriver.d.ts.map +1 -0
  220. package/dist/services/change-feed/ChangeFeedManager.d.ts +166 -0
  221. package/dist/services/change-feed/ChangeFeedManager.d.ts.map +1 -0
  222. package/dist/services/change-feed/ChangeFeedServiceProvider.d.ts +11 -0
  223. package/dist/services/change-feed/ChangeFeedServiceProvider.d.ts.map +1 -0
  224. package/dist/services/change-feed/DatabaseChangeFeedDriver.d.ts +84 -0
  225. package/dist/services/change-feed/DatabaseChangeFeedDriver.d.ts.map +1 -0
  226. package/dist/services/change-feed/MemoryChangeFeedDriver.d.ts +26 -0
  227. package/dist/services/change-feed/MemoryChangeFeedDriver.d.ts.map +1 -0
  228. package/dist/services/change-feed/changeFeedDriverContract.d.ts +8 -0
  229. package/dist/services/change-feed/changeFeedDriverContract.d.ts.map +1 -0
  230. package/dist/services/change-feed/config.d.ts +42 -0
  231. package/dist/services/change-feed/config.d.ts.map +1 -0
  232. package/dist/services/change-feed/cursor.d.ts +17 -0
  233. package/dist/services/change-feed/cursor.d.ts.map +1 -0
  234. package/dist/services/change-feed/postgresListen.d.ts +30 -0
  235. package/dist/services/change-feed/postgresListen.d.ts.map +1 -0
  236. package/dist/services/change-feed/stream.d.ts +16 -0
  237. package/dist/services/change-feed/stream.d.ts.map +1 -0
  238. package/dist/services/change-feed/wire.d.ts +20 -0
  239. package/dist/services/change-feed/wire.d.ts.map +1 -0
  240. package/dist/services/index.d.ts +9 -0
  241. package/dist/services/index.d.ts.map +1 -1
  242. package/dist/services/index.js +3 -3
  243. package/dist/services/index.js.map +2 -2
  244. package/dist/services/queue/work.js +2 -2
  245. package/dist/services/queue/work.js.map +1 -1
  246. package/dist/services/router/ViewRouteDispatcher.d.ts +16 -0
  247. package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
  248. package/dist/stats/route-table.js +1 -1
  249. package/dist/support/index.js +2 -2
  250. package/dist/support/index.js.map +1 -1
  251. package/dist/vitest/index.js +1 -1
  252. package/package.json +6 -2
  253. package/skills/gemi-react-best-practices/rules/controller-authorize-every-tenant-read.md +16 -1
  254. package/dist/chunk-11fsn5mr.js +0 -5
  255. package/dist/chunk-h3864a8z.js +0 -17
  256. package/dist/chunk-hn67spz6.js +0 -5
  257. package/dist/chunk-mb7q7s0a.js +0 -19
  258. package/dist/chunk-mn5xw79b.js +0 -9
  259. package/dist/chunk-tdsfke9q.js +0 -6
  260. package/dist/chunk-wqvvjd5r.js +0 -24
  261. package/dist/chunk-x78jrs4y.js +0 -4
  262. /package/dist/{chunk-0sjh5v1n.js.map → chunk-53bek7sp.js.map} +0 -0
  263. /package/dist/{chunk-td8tha3j.js.map → chunk-es487acc.js.map} +0 -0
  264. /package/dist/{chunk-et4pv1b1.js.map → chunk-mx9y9mtx.js.map} +0 -0
  265. /package/dist/{chunk-8b2tw2yp.js.map → chunk-rend2sbk.js.map} +0 -0
@@ -0,0 +1,46 @@
1
+ // @bun
2
+ import{Ae as LW,He as NO}from"./chunk-9hr0bcfy.js";import{Oe as _3,Te as xZ,yf as IO}from"./chunk-1pvkw2pq.js";import{$f as z0,Df as pz,Ef as oj,Ff as S8,Gf as N8,Jf as C8,Kf as _8,Lf as HZ,Mf as Cz,Nf as iz,Of as Aj,Pf as h,Uf as A,Vf as q8,Wf as y$,Xf as x8,Yf as w3,_f as J$,ag as e6,ig as b5,jg as x$,kg as tz,lg as zO,ng as OO,zf as w8}from"./chunk-j0sncgxc.js";import{qg as SZ,rg as q0,sg as b1,tg as tj}from"./chunk-teny6xkw.js";import{ug as Uz,vg as X8,wg as f}from"./chunk-yv1psptb.js";import{zg as $O}from"./chunk-b1mk12xg.js";import{Ag as F8}from"./chunk-hfyxvdjj.js";import{Bg as hz,Cg as F1,Dg as W$,Eg as TO,Fg as VO,Hg as Mj,Ig as WO,Rg as MO}from"./chunk-57edag57.js";import{eh as Y$}from"./chunk-jn59bsww.js";import{jh as yz,oh as zj}from"./chunk-dx7wpz5b.js";import{vh as qz,zh as o}from"./chunk-s9rfgxj5.js";import{Ah as PZ,Dh as N}from"./chunk-eazqda9z.js";import{Gh as XO}from"./chunk-et3vhkbf.js";import{Rh as cz}from"./chunk-5waxjsvv.js";import{Wh as G8}from"./chunk-ddad3902.js";function f3($){return typeof $==="function"&&$.prototype!==void 0}function U1($){return typeof $==="string"?[$]:$}function A3($,Z){let J=Z?"attachment":"inline",j=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${J}; filename="${j}"; filename*=UTF-8''${encodeURIComponent($)}`}function RO($){return"total"in $&&"partial"in $&&"body"in $}function _j(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function EZ($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":_8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function bO($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(RO($))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 L8($,Z){if($ instanceof Response)return $;if(!$)return _j();let J=await bO($),{body:j,start:W,end:Y,total:z,partial:O}=J;if(j instanceof Blob&&"exists"in j&&typeof j.exists==="function"){if(!await j.exists())return _j()}let{range:X}=Z;if(X){if(z<=0)return EZ(Math.max(z,0));if(!O){if(j instanceof Blob){let U=N8(X,z);if(!U)return EZ(z);j=j.slice(U.start,U.end+1),W=U.start,Y=U.end,O=!0}}}let G=Boolean(X)&&O,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",C8(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",A3(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,B]of Object.entries(J.extraHeaders))Q.set(U,B);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 v$ extends q0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var Lj={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function bZ($){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 Lj)))return Math.floor(Number(J[1])*(Lj[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var RZ=new WeakMap;function Hj($){return RZ.has($)}function Sj($){return RZ.get($)?.limit??null}function xj($){let Z=RZ.get($);return Z?Z.read>Z.limit:!1}function vO($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function H8($,Z){let J=vO($);if(J!==null&&J>Z)throw new v$(Z)}function E3($,Z,J={}){let j=RZ.get($);if(j)j.limit=Z;else{let W={limit:Z,read:0,stream:void 0,used:!1};RZ.set($,W),wO($,W)}if(J.checkDeclared!==!1)H8($,Z)}function kO($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function P8($,Z){if(Z.stream!==void 0)return Z.stream;let J=kO($);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 O=new v$(Z.limit);W.error(O),j.cancel(O).catch(()=>{});return}W.enqueue(z)},cancel(W){return j?j.cancel(W):J.cancel(W)}},{highWaterMark:0}),Z.stream}async function b$($,Z){if(H8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=P8($,Z);if(!J)return new Uint8Array(0);let j=J.getReader(),W=[],Y=0;for(;;){let{done:X,value:G}=await j.read();if(X)break;W.push(G),Y+=G.byteLength}let z=new Uint8Array(Y),O=0;for(let X of W)z.set(X,O),O+=X.byteLength;return z}function Pj($){return $.headers.get("Content-Type")??""}function wO($,Z){let J=(j,W)=>Object.defineProperty($,j,{configurable:!0,...W});J("body",{get:()=>P8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>b$($,Z)}),J("arrayBuffer",{value:async()=>{let j=await b$($,Z);return j.buffer.slice(j.byteOffset,j.byteOffset+j.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await b$($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await b$($,Z)))}),J("blob",{value:async()=>new Blob([await b$($,Z)],{type:Pj($)})}),J("formData",{value:async()=>new Response(await b$($,Z),{headers:{"Content-Type":Pj($)}}).formData()}),J("clone",{value:()=>{H8($,Z.limit);let j=P8($,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 fj($){return f3($)}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(!fj(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(fj(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=U1($),this}}class Ej{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=U1($),this}async run(){let $=new A,Z=$.headers.toJSON();for(let J of Aj($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(xj($.rawRequest))throw new v$(Sj($.rawRequest));throw J}}}class Rj{constructor(...$){return new $0(...$)}}class bj extends $0{__internal_brand="StreamHandler";async run($){let Z=f.getStore(),J=Z?.req?.rawRequest,j=S8(J?.headers.get("Range"));if(Z)Z.rangeRequest=j;try{let W=await super.run($);return await L8(W,{range:j,method:J?.method})}catch(W){if(W instanceof x8)return EZ(W.total);throw W}finally{if(Z)Z.rangeRequest=null}}}class vj{constructor(...$){return new bj(...$)}}class kj{__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 x0{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 kj($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${qO($)}.`);return yO($,this)}file($,Z){return new Rj("GET",$,Z)}stream($,Z){return new vj("GET",$,Z)}proxy($,Z={}){return new Ej($,Z)}}function qO($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function yO($,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 x0{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 f8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class A8{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class wj{static __brand="McpRouter";routes={};param($){return new f8($.as,$.input,$.bind)}fromApiRoute($,Z,J){return new A8($,Z,J)}}function O0($,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 E8 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 R3{static to($,...Z){let[J={}]=Z,{search:j={},params:W={},permanent:Y,status:z}={params:{},status:307,permanent:!1,...J},O=new URLSearchParams(j).toString();throw new E8([O0($,W)||"/",O.toString()].filter(Boolean).join("?"),z??(Y?301:307))}static external($,Z=307){throw new E8($,Z)}}var qj=Symbol.for("gemi.HttpResponse");class Z${kind;body;status;headers;[qj]=!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 gO(J),new Z$("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 Z$.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 gO($){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 k$($){return typeof $==="object"&&$!==null&&$[qj]===!0}function mO($,Z,J={}){return Z$.error($,Z,J)}class yj{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 R3.to(J,{permanent:j,status:W}),{}}middleware($){return this.middlewares=U1($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function R8($,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,O=J?200:$.status??200;if(!J)for(let[X,G]of Object.entries($.headers??{}))Z.set(X,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",A3(W,z));return new Response(j instanceof Blob?j.stream():j,{status:O,headers:Z})}class gj{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=U1($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function mj($,Z){if(k$($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class pj{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=mj(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=U1($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class hj{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=mj(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=U1($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class E1{middlewares=[];featureGates=[];routes={};view($,Z){return new pj($,Z)}file($){return new gj($)}redirect($){return new yj($)}layout($,Z,J){return new hj($,Z,J)}}class X0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}function pO($){return $}function hO(){return{aliases:{},global:[],bodyLimit:null}}var w$="redirect";function vZ($,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 cj($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function cO($,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 uO($,Z){let J=(j)=>j.replace(/\/+$/,"")||"/";return J($)===J(Z)}function b3($,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=cO($,!j);if(j||!uO(new URL(Y,W).pathname,W.pathname))W.searchParams.set(w$,Y)}return j?W.href:`${W.pathname}${W.search}`}var R1="access_token";function b8($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function v3($,Z){let J=b8(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}class uj extends X0{async run($){let Z=f.getStore(),J=Z.req;if(Z.user)return{};let j=await v3(N(E),J);if(!j)throw new J$({redirectTo:b3(J,$)});return Z.setUser(j),{}}}class dj extends X0{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 lj={"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 ij extends X0{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={...lj,...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={...lj,...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(sj("window",j),sj("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 sj($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}class kZ extends q0{constructor($){super("Rate limit exceeded");let Z={"Content-Type":"application/json",...$?rj($):{}};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 aj extends X0{async run($,Z){let J=dO();if(!J)return{};let j=await J.consume(this.key(),{limit:nj($)??this.config.limit,window:nj(Z)??this.config.window});if(this.config.headers!==!1){let W=this.req.ctx?.();if(W)for(let[Y,z]of Object.entries(rj(j)))W.setHeaders(Y,z)}if(!j.allowed)throw new kZ(j);return{}}key(){if(this.config.key)return this.config.key(this.req);return`${q$(this.req)}:${this.req.routePath??"*"}`}}function dO(){try{let $=N();return $.bound(e0)?$.make(e0):null}catch{return null}}function q$($){let Z=oj($.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 rj($){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 nj($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class ej extends X0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new v8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new v8;return{}}}class v8 extends q0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:tj("csrf","Invalid CSRF token",403)}},view:{}}}class k3 extends X0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return E3(this.req.rawRequest,bZ(Z)),{}}}class $W{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class ZW{all($,Z){return!0}}class k8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new y$:new w3}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 X0{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 y$:$ instanceof w3}}function lO($){return new k8($)}import{lookup as ZX}from"dns/promises";import*as JX from"http";import*as jX from"https";import*as d$ from"zlib";function iO($){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=sO(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 sO($){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 JW($){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 B=0;B<U.length;B++){let F=U[B];if(K&&B===U.length-1&&F.includes(".")){if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(F))return null;let D=F.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(F))return null;Q.push(parseInt(F,16))}return Q},Y=W(j[0],j.length===1),z=j.length===2?W(j[1],!0):[];if(!Y||!z)return null;let O;if(j.length===2){let G=8-Y.length-z.length;if(G<1)return null;O=[...Y,...Array.from({length:G},()=>0),...z]}else O=Y;if(O.length!==8)return null;let X=new Uint8Array(16);return O.forEach((G,K)=>{X[K*2]=G>>8,X[K*2+1]=G&255}),X}function wZ($){let Z=JW($);if(Z)return{family:6,bytes:Z};let J=iO($);if(J)return{family:4,bytes:J};return null}function j$($){if($.family===6&&nO($.bytes))return{family:4,bytes:$.bytes.slice(12)};return $}function nO($){for(let Z=0;Z<10;Z++)if($[Z]!==0)return!1;return $[10]===255&&$[11]===255}function qZ($){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 m$($){let Z=$.lastIndexOf("/"),J=Z===-1?$:$.slice(0,Z),j=/^[0-9.]+$/.test(J)?oO(J):JW(J);if(!j)return null;let W=j$(j.length===4?{family:4,bytes:j}:{family:6,bytes:j}),Y=W.family===4?32:128,z=Y;if(Z!==-1){let O=$.slice(Z+1);if(!/^\d{1,3}$/.test(O))return null;if(z=Number(O),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 oO($){return/^\d{1,3}(\.\d{1,3}){3}$/.test($)&&$.split(".").every((Z)=>Number(Z)<=255)?new Uint8Array($.split(".").map(Number)):null}function Q1($,Z){let J=j$($);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:m$($),kind:Z,text:$}),aO=[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")],rO=[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")],tO=m$("64:ff9b::/96"),eO=m$("2002::/16"),$X=m$("2000::/3");function g$($){let Z=typeof $==="string"?wZ($):$;if(!Z)return{kind:"reserved",range:"not an IP address"};let J=j$(Z);if(J.family===4){let W=aO.find((Y)=>Q1(J,Y.cidr));return W?{kind:W.kind,range:W.text}:null}if(Q1(J,tO))return g$({family:4,bytes:J.bytes.slice(12)});if(Q1(J,eO))return g$({family:4,bytes:J.bytes.slice(2,6)});let j=rO.find((W)=>Q1(J,W.cidr));if(j)return{kind:j.kind,range:j.text};return Q1(J,$X)?null:{kind:"reserved",range:"outside 2000::/3"}}function jW($,Z){let J=j$($),j=j$(Z);return J.family===j.family&&J.bytes.every((W,Y)=>W===j.bytes[Y])}class Q0 extends Error{code="safe-fetch";url;constructor($,Z,J){super($,J);this.name=new.target.name,this.url=Z}}class B1 extends Q0{reason;code="invalid-url";constructor($,Z,J){super(J,$);this.reason=Z}}class p$ extends Q0{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 Q0{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 h$ extends Q0{host;code="dns";constructor($,Z,J){super(`Couldn't resolve ${Z}.`,$,{cause:J});this.host=Z}}class c$ extends Q0{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 u$ extends Q0{limit;code="too-large";constructor($,Z){super(`The response is larger than ${Z} bytes.`,$);this.limit=Z}}class yZ extends Q0{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 gZ extends Q0{limit;code="too-many-redirects";constructor($,Z){super(`More than ${Z} redirects.`,$);this.limit=Z}}class k1 extends Q0{code="network";constructor($,Z){super(`The request failed: ${Z instanceof Error?Z.message:String(Z)}`,$,{cause:Z})}}class pZ 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 mZ={timeout:30000,connectTimeout:1e4,maxSize:10485760,maxRedirects:5,ports:[80,443]},WX=new Set([301,302,303,307,308]),YX=new Set([101,103,204,205,304]),zX=["host","connection","content-length","transfer-encoding","keep-alive","upgrade"],OX=["authorization","cookie","proxy-authorization"];async function zW($,Z={}){let J=XX(Z),j=Z.signal;j?.throwIfAborted();let W=new AbortController,Y=W.signal,z=String($),O=(Q)=>{if(!Y.aborted)W.abort(Q)},X=setTimeout(()=>O(new c$(z,"total",J.timeout)),J.timeout),G=()=>O(j.reason);j?.addEventListener("abort",G,{once:!0});let K=()=>{clearTimeout(X),j?.removeEventListener("abort",G)};try{let Q=YW(z,J),U=(Z.method??"GET").toUpperCase(),B=new Headers(Z.headers);for(let D of zX)B.delete(D);if(!B.has("accept"))B.set("accept","*/*");if(!B.has("user-agent"))B.set("user-agent","gemi");if(!B.has("accept-encoding"))B.set("accept-encoding","gzip, deflate, br");let F=await QX(U,Z.body,B);for(let D=0;;D++){z=Q.href;let{request:T,response:M,address:_}=await BX(Q,U,B,F,J,Y),I=M.statusCode??0,H=M.headers.location;if(WX.has(I)&&H&&Z.redirect!=="manual"){if(T.destroy(),D>=J.maxRedirects)throw new gZ(Q.href,J.maxRedirects);let P;try{P=new URL(H,Q)}catch{throw new B1(H,"malformed",`The redirect to "${H}" is not a URL.`)}if(I===303?U!=="HEAD":(I===301||I===302)&&U==="POST"){U="GET",F=null;let L=[];B.forEach((V,C)=>{if(C.startsWith("content-"))L.push(C)});for(let V of L)B.delete(V)}if(P.origin!==Q.origin)for(let L of OX)B.delete(L);Q=YW(P.href,J);continue}return FX({url:Q,hop:D,method:U,request:T,response:M,address:_,policy:J,signal:Y,release:K})}}catch(Q){throw K(),Y.aborted?Y.reason:Q}}function XX($){let Z=(j,W)=>{let Y={hosts:[],ranges:[]};for(let z of j){let O=z.includes("/")||z.includes(":")||/^[\d.]+$/.test(z),X=O?m$(z):null;if(X)Y.ranges.push(X);else if(!O&&/^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/i.test(z))Y.hosts.push(OW(z));else throw TypeError(`safeFetch: "${z}" in ${W} is not a host name or an IP range.`)}return Y},J=$.allowPrivate;return{timeout:$.timeout??mZ.timeout,connectTimeout:$.connectTimeout??mZ.connectTimeout,maxSize:$.maxSize??mZ.maxSize,maxRedirects:$.maxRedirects??mZ.maxRedirects,ports:$.ports??mZ.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??GX}}async function GX($){return(await ZX($,{all:!0,verbatim:!0})).map((J)=>J.address)}function OW($){return $.toLowerCase().replace(/\.$/,"")}function WW($,Z){return Z.some((J)=>J.startsWith("*.")?$.endsWith(J.slice(1)):$===J)}function YW($,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=XW(J);if(Z.ports!=="any"&&!Z.ports.includes(j))throw new B1(J.href,"port",`Port ${j} is not allowed.`);return J}function XW($){return $.port?Number($.port):$.protocol==="https:"?443:80}async function KX($,Z,J){let j=OW($.hostname.replace(/^\[(.*)\]$/,"$1")),W=wZ(j),Y=W!==null&&(j.includes(":")||/^\d+\.\d+\.\d+\.\d+$/.test(j));if(!Y&&WW(j,Z.deny.hosts))throw new p$($.href,j,"denied");let z=!Y&&Z.allow!==null&&WW(j,Z.allow.hosts);if(Z.allow&&!z&&Z.allow.ranges.length===0)throw new p$($.href,j,"not-allowed");let O;if(Y)O=[W];else{let X;try{X=await UX(Z.resolve(j),J)}catch(G){if(J.aborted)throw J.reason;throw new h$($.href,j,G)}if(O=X.map((G)=>wZ(G)).filter((G)=>G!==null),O.length===0)throw new h$($.href,j)}for(let X of O){let G=qZ(X);if(Z.deny.ranges.some((Q)=>Q1(X,Q)))throw new v1($.href,j,G,"denied");if(Z.allow&&!z&&!Z.allow.ranges.some((Q)=>Q1(X,Q)))throw new v1($.href,j,G,"not-allowed");let K=g$(X);if(K&&Z.allowPrivate!==!0&&!Z.allowPrivate.some((Q)=>Q1(X,Q)))throw new v1($.href,j,G,K.kind)}return{host:j,addresses:O,isLiteral:Y}}function UX($,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 QX($,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 BX($,Z,J,j,W,Y){let z=new AbortController,O=setTimeout(()=>z.abort(new c$($.href,"connect",W.connectTimeout)),W.connectTimeout),X=AbortSignal.any([Y,z.signal]);try{let{host:G,addresses:K,isLiteral:Q}=await KX($,W,X),U=$.protocol==="https:",B={};if(J.forEach((F,D)=>{B[D]=F}),j)B["content-length"]=String(j.byteLength);return await new Promise((F,D)=>{let T={method:Z,host:G,port:XW($),path:`${$.pathname}${$.search}`,headers:B,agent:!1,lookup:(L,V,C)=>{let x=V?.family,b=K.filter((g)=>!x||g.family===x);if(b.length===0)C(Object.assign(Error(`No IPv${x} address for ${G}`),{code:"ENOTFOUND"}));else if(V?.all)C(null,b.map((g)=>({address:qZ(g),family:g.family})));else C(null,qZ(b[0]),b[0].family)}};if(U&&!Q)T.servername=G;let M=(U?jX:JX).request(T),_=null,I=(L)=>{X.removeEventListener("abort",H),M.destroy(),D(L)},H=()=>I(X.aborted?X.reason:Y.reason);X.addEventListener("abort",H,{once:!0});let P=(L)=>{let V=L?.remoteAddress;if(!V||_!==null)return!0;let C=wZ(V);if(!C||!K.some((x)=>jW(x,C)))return I(new v1($.href,G,V,"not-allowed")),!1;return _=qZ(j$(C)),!0};M.once("socket",(L)=>{let V=()=>{if(P(L)&&!U)clearTimeout(O)};if(L.connecting)L.once("connect",V);else V();if(U)L.once("secureConnect",()=>clearTimeout(O))}),M.once("response",(L)=>{if(clearTimeout(O),L.on("error",()=>{}),!P(L.socket))return;X.removeEventListener("abort",H),F({request:M,response:L,address:_})}),M.on("error",(L)=>{if(X.aborted)return I(X.reason);I(L instanceof Q0?L:new k1($.href,L))}),M.end(j??void 0)})}finally{clearTimeout(O)}}function FX({url:$,hop:Z,method:J,request:j,response:W,address:Y,policy:z,signal:O,release:X}){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)=>DX(V,C)))throw j.destroy(),new yZ($.href,V,z.contentTypes)}let U={url:$.href,redirected:Z>0,address:Y},B={status:G,statusText:W.statusMessage??"",headers:K};if(J==="HEAD"||YX.has(G))return j.destroy(),X(),new pZ(null,B,U);let F=K.get("content-encoding")?.trim().toLowerCase(),D=F==="gzip"||F==="x-gzip"?d$.createGunzip():F==="deflate"?d$.createInflate():F==="br"?d$.createBrotliDecompress():null,T=Number(K.get("content-length"));if(!D&&Number.isFinite(T)&&T>z.maxSize)throw j.destroy(),new u$($.href,z.maxSize);if(D)K.delete("content-encoding"),K.delete("content-length");let M=D?W.pipe(D):W,_=0,I=!1,H=()=>{},P=()=>{I=!0,O.removeEventListener("abort",H),X()},L=new ReadableStream({start(V){let C=(b)=>{if(I)return;if(P(),b===void 0)V.close();else j.destroy(),D?.destroy(),V.error(b)};if(H=()=>C(O.reason),O.addEventListener("abort",H,{once:!0}),O.aborted)return H();M.on("data",(b)=>{if(I)return;if(_+=b.byteLength,_>z.maxSize)return C(new u$($.href,z.maxSize));if(V.enqueue(new Uint8Array(b)),(V.desiredSize??1)<=0)M.pause()}),M.once("end",()=>C());let x=(b)=>C(b instanceof Q0?b:new k1($.href,b));if(M.on("error",x),D)W.on("error",x);W.once("aborted",()=>C(new k1($.href,Error("The response was cut off."))))},pull(){M.resume()},cancel(){if(I)return;P(),j.destroy(),D?.destroy()}});return new pZ(L,B,U)}function DX($,Z){let J=Z.toLowerCase();return J.endsWith("/*")?$.startsWith(J.slice(0,-1)):$===J}import{createHmac as GW,randomBytes as TX}from"crypto";var y8="v2.";function g8($){return $.startsWith(y8)}function q3(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function KW($){let Z=TX(16).toString("hex"),J=GW("sha256",q3()).update(`${$}:${Z}`).digest("hex");return`${y8}${J}`}function y3($,Z){let J=GW("sha256",q3()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${y8}${J}`}import{createHash as IX,createHmac as NX,randomInt as CX,timingSafeEqual as BW}from"crypto";function UW($,Z){return Math.floor($/Z)*Z}function VX($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function m8($,Z,J,j){return Z*VX(J,j)+$}function MX($){let{current:Z,previous:J,elapsed:j,window:W,limit:Y,cost:z}=$,O=Y-z;if(O<0)return W;let X=Math.max(0,W-j);if(J>0){let K=W*(1-(O-Z)/J);if(K<=W)return Math.max(0,Math.ceil(K-j))}if(Z<=O)return X;if(Z<=0)return X;let G=W*(1-O/Z);return X+Math.max(0,Math.ceil(G))}function QW($){let{allowed:Z,current:J,previous:j,now:W,elapsed:Y,window:z,limit:O,cost:X}=$;if(Z){let K=m8(J,j,Y,z);return{allowed:!0,limit:O,remaining:Math.max(0,Math.floor(O-K)),resetAt:W-Y+z,retryAfter:0}}let G=MX({current:J,previous:j,elapsed:Y,window:z,limit:O,cost:X});return{allowed:!1,limit:O,remaining:0,resetAt:W+G,retryAfter:G}}class p8{}class h8 extends p8{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=UW(Y,j),O=Y-z,X=this.roll(Z,j,z);X.limit=J;let K=m8(X.current,X.previous,O,j)+W<=J;if(K)X.current+=W;if(this.buckets.delete(Z),this.buckets.set(Z,X),this.buckets.size>this.maxKeys)this.evict(Y);return QW({allowed:K,current:X.current,previous:X.previous,now:Y,elapsed:O,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 TW="h1.";function g3($,Z,J){let j=NX("sha256",q3()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${TW}${j}`}function hZ($,Z,J,j){let W=typeof j==="string"?j:"",Y=typeof J==="string"?J:"",z=Y.startsWith(TW),O=g3($,Z,W),X=Buffer.from(z?O:W),G=Buffer.from(Y);if(X.length!==G.length||W===""||Y==="")return BW(X,X),!1;return BW(X,G)}function VW($){let Z="";for(let J=0;J<$;J++)Z+=String(CX(0,10));return Z}var MW=320;function cZ($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>MW)return null;return Z.toLowerCase()}function c8($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>MW)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var FW=null;function IW(){try{let $=N();if(typeof $?.bound==="function"&&$.bound(e0))return $.make(e0)}catch{}return FW??=new e0({driver:new h8,limit:1000,window:60}),FW}function DW($){return $.length<=64?$:`sha256:${IX("sha256").update($).digest("hex")}`}async function l$($,Z,J,j){let W=IW(),Y=[[`auth:code-${$}:ip:${DW(q$(J))}`,j.perIp]];if(Z!==null)Y.push([`auth:code-${$}:email:${DW(Z)}`,j.perEmail]);for(let[z,O]of Y){if(!O)continue;let[X,G]=O,K=await W.consume(z,{limit:X,window:G});if(!K.allowed)throw new kZ(K)}}async function NW($,Z,J,j=10){let W=Math.max(86400,Math.ceil(j*60*(J+1)));return(await IW().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:W})).allowed}import{randomBytes as d8}from"crypto";class u8 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 m3($,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 l8($={}){let Z=$.length??6,J=$.expiresInMinutes??10,j=$.linkExpiresInMinutes??10080,W=$.maxAttempts??5;return m3("length",Z,4,12),m3("expiresInMinutes",J,1),m3("linkExpiresInMinutes",j,1),m3("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 _X($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function YD($){return $}function CW($={}){return{basePath:"/auth",verifyEmail:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:u8,oauthProviders:{},verifyPassword:_X,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>d8(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return d8(32).toString("hex")},generateMagicLinkToken:()=>d8(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:l8($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}function i8($){if($&&typeof $==="object")delete $.password;return $}function LX(){return new Proxy({},{get:($,Z)=>LW(Z)})}var _W=new WeakMap;function PW($){if($&&typeof $==="object"){for(let Z of Object.values($))PW(Z);Object.freeze($)}return $}var PX={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},HX=PW({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:PX});class s8{models;constructor($=LX()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return HX}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??W$(),j=N(Y$).connection(J),W=()=>this.transaction(async()=>{if(j.dialect==="postgres"){let O=`gemi:legacy-session:${$}`;await F1()`SELECT pg_advisory_xact_lock(hashtextextended(${O}, 0))`}return Z()});if(j.dialect!=="sqlite"||F1())return W();let z=(_W.get(j)??Promise.resolve()).then(W,W);return _W.set(j,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return i8(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return i8(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?i8(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 XU}from"crypto";function f0($,Z,J,j,W){return p0(Z,pW($,Z),J,j,W)}function p0($,Z,J,j,W,Y){let z=t8(Z,J,j);if(W&&Z!==z)throw RangeError(L7($,Z,J,j,Y));return z}function pW($,Z){let J=$[Z];if(J===void 0)throw TypeError(xJ(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 z2($){return G$({name:$},1)}function G$($,Z){return d0((J)=>({value:J,configurable:1,writable:!Z}),$)}function hW($){return d0((Z)=>({get:Z,configurable:1}),$)}function Z6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function t$($,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 rZ($,Z,J){let j={};for(let W=0;W<Z.length;W++){let Y=Z[W];j[Y]=$(Y,W,J)}return j}function SX($,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 O2($,Z){let J={};for(let j in Z)$.has(j)||(J[j]=Z[j]);return J}function X2($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function cW($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function uW($,Z,J){for(let j of $)if(Z[j]!==J[j])return 0;return 1}function dW($,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 HW($){return $[0].toUpperCase()+$.substring(1)}function tZ($){return $.slice().sort()}function i3($,Z){return String(Z).padStart($,"0")}function w1($,Z){return Math.sign($-Z)}function t8($,Z,J){return Math.min(Math.max($,Z),J)}function T1($,Z){return[Math.floor($/Z),dZ($,Z)]}function dZ($,Z){return($%Z+Z)%Z}function g1($,Z){return[J6($,Z),G2($,Z)]}function J6($,Z){return Math.trunc($/Z)||0}function G2($,Z){return $%Z||0}function p3($){return Math.abs($%1)===0.5}function lW($,Z,J){let j=0,W=0;for(let O=0;O<=Z;O++){let X=$[J[O]],G=Z1[O],K=c/G,[Q,U]=g1(X,K);j+=U*G,W+=Q}let[Y,z]=g1(j,c);return[W+Y,z]}function j6($,Z,J){let j={};for(let W=Z;W>=0;W--){let Y=Z1[W];j[J[W]]=J6($,Y),$=G2($,Y)}return j}function iW($){return $===w?y6:[]}function sW($){return $===w?X3:[]}function nW($){return $===w?["year","day"]:[]}function oW($){if($!==void 0)return a($)}function aW($){if($!==void 0)return l0($)}function K2($){if($!==void 0)return eZ($)}function l0($){return eW(eZ($))}function eZ($){return tW(VG($))}function U2($){if($==null)throw TypeError("Cannot be null or undefined");return $}function rW($,Z){if(Z==null)throw RangeError(xJ($));return Z}function M1($){if(!K0($))throw TypeError(_7);return $}function W6($,Z,J=$){if(typeof Z!==$)throw TypeError(Y3(J,Z));return Z}function tW($,Z="number"){if(!Number.isInteger($))throw RangeError(cX(Z,$));return $||0}function eW($,Z="number"){if($<=0)throw RangeError(uX(Z,$));return $}function Q2($){if(typeof $=="symbol")throw TypeError(sX);return String($)}function s3($,Z){return K0($)?String($):a($,Z)}function Y6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(iX($));return $}function $Y($,Z="number"){if(typeof $=="bigint")throw TypeError(lX(Z));if($=Number($),!Number.isFinite($))throw RangeError(dX(Z,$));return $}function I0($,Z){return Math.trunc($Y($,Z))||0}function ZY($,Z){return tW($Y($,Z),Z)}function SW($,Z){return eW(I0($,Z),Z)}function B2($,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 s$($,Z,J=1){return B2($[0]+Z[0]*J,$[1]+Z[1]*J)}function n$($,Z){return B2($[0],$[1]+Z)}function y0($,Z){return s$(Z,$,-1)}function C0($,Z){return w1($[0],Z[0])||w1($[1],Z[1])}function JY($,Z,J){return C0($,Z)===-1||C0($,J)===1}function z6($,Z=1){let J=BigInt(c/Z);return[Number($/J),Number($%J)*Z]}function o$($,Z=1){let J=c/Z,[j,W]=g1($,J);return[j,W*Z]}function jY($,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 F2($,Z,J=T1){let[j,W]=$,[Y,z]=J(W,Z);return[j*(c/Z)+Y,z]}function D2($,Z){let J=$.formatToParts(Z),j={};for(let W of J)j[W.type]=W.value;return j}function T2($){return f0($,"isoYear",aZ,oZ,1),$.isoYear===aZ?f0($,"isoMonth",4,12,1):$.isoYear===oZ&&f0($,"isoMonth",1,9,1),$}function q1($){return I1({...$,...u0,isoHour:12}),$}function I1($){let Z=f0($,"isoYear",aZ,oZ,1),J=Z===aZ?1:Z===oZ?-1:0;return J&&m0(N0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function m0($){if(!$||JY($,PG,LG))throw RangeError(v6);return $}function m1($){return lW($,5,o0)[1]}function O6($){let[Z,J]=T1($,c);return[j6(J,5,o0),Z]}function WY($){return YY($)[0]}function YY($){return F2($,c0)}function _0($){return e$($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function N0($){let Z=_0($);if(Z!==void 0){let[J,j]=g1(Z,E0);return[J,j*J1+($.isoMicrosecond||0)*M$+($.isoNanosecond||0)]}}function V2($,Z){let[J,j]=O6(m1($)-Z);return m0(N0({...$,isoDay:$.isoDay+j,...J}))}function n3(...$){return e$(...$)/k7}function e$(...$){let[Z,J]=zY(...$),j=Z.valueOf();if(!isNaN(j))return j-J*E0}function zY($,Z=1,J=1,j=0,W=0,Y=0,z=0){let O=$===aZ?1:$===oZ?-1:0,X=new Date;return X.setUTCHours(j,W,Y,z),X.setUTCFullYear($,Z-1,J+O),[X,O]}function h1($,Z){let[J,j]=n$($,Z);j<0&&(j+=c,J-=1);let[W,Y]=T1(j,J1),[z,O]=T1(Y,M$);return X6(J*E0+W,z,O)}function X6($,Z=0,J=0){let j=Math.ceil(Math.max(0,Math.abs($)-_G)/E0)*Math.sign($),W=new Date($-j*E0);return t$(m6,[W.getUTCFullYear(),W.getUTCMonth()+1,W.getUTCDate()+j,W.getUTCHours(),W.getUTCMinutes(),W.getUTCSeconds(),W.getUTCMilliseconds(),Z,J])}function OY($){return[$.isoYear,$.isoMonth,$.isoDay]}function XY(){return D1}function M2($,Z){switch(Z){case 2:return I2($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function GY($){return I2($)?366:365}function I2($){return $%4==0&&($%100!=0||$%400==0)}function KY($){let[Z,J]=zY($.isoYear,$.isoMonth,$.isoDay);return dZ(Z.getUTCDay()-J,7)||7}function UY({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function xX($){let Z=_0($);if(Z<SG)return UY($);let J=D2(lJ(a$),Z),{era:j,eraYear:W}=_9(J,a$);return[j,W]}function G6($){return K$($),K6($,1),$}function K$($){return QY($,1),$}function xW($){return uW(yJ,$,QY($))}function QY($,Z){let{isoYear:J}=$,j=f0($,"isoMonth",1,XY(),Z);return{isoYear:J,isoMonth:j,isoDay:f0($,"isoDay",1,M2(J,j),Z)}}function K6($,Z){return t$(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:r7(M1($))}function $3($,Z=0){$=i0($);let J=t7($),j=qG($,Z);return[r7($),j,J]}function N2($){return t7(i0($))}function BY($){return $=i0($),pJ($,9,6,1)}function $Z($,Z,J,j=9,W=0,Y=4){Z=i0(Z);let z=pJ(Z,j,W),O=L2(Z),X=K3(Z,Y),G=G3(Z,j,W,1);return z==null?z=Math.max(J,G):VY(z,G),O=P2(O,G,1),$&&(X=((K)=>K<4?(K+2)%4:K)(X)),[z,G,O,X]}function U6($,Z=6,J){let j=L2($=H2($,$6)),W=K3($,7),Y=G3($,Z);return Y=rW($6,Y),j=P2(j,Y,void 0,J),[Y,j,W]}function C2($){return hJ(i0($))}function FY($,Z){return _2(i0($),Z)}function _2($,Z=4){let J=TY($);return[K3($,4),...DY(G3($,Z),J)]}function DY($,Z){return $!=null?[Z1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function L2($){let Z=$[lZ];return Z===void 0?1:I0(Z,lZ)}function P2($,Z,J,j){let W=j?c:Z1[Z+1];if(W){let Y=Z1[Z];if(W%(($=p0(lZ,$,1,W/Y-(j?0:1),1))*Y))throw RangeError(Y3(lZ,$))}else $=p0(lZ,$,1,J?1e9:1,1);return $}function TY($){let Z=$[r8];if(Z!==void 0){if(typeof Z!="number"){if(Q2(Z)==="auto")return;throw RangeError(Y3(r8,Z))}Z=p0(r8,Math.floor(Z),0,9,1)}return Z}function i0($){return $===void 0?{}:M1($)}function H2($,Z){return typeof $=="string"?{[Z]:$}:M1($)}function Z0($){if($!==void 0){if(K0($))return Object.assign(Object.create(null),$);throw TypeError(_7)}}function Q6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:fG[Z]})}function S2($,Z,J=9,j=0,W){let Y=Z[$];if(Y===void 0)return W?j:void 0;if(Y=Q2(Y),Y==="auto")return W?j:null;let z=J2[Y];if(z===void 0&&(z=NG[Y]),z===void 0)throw RangeError(S7($,Y,J2));return p0($,z,j,J,1,O3),z}function U$($,Z,J,j=0){let W=J[$];if(W===void 0)return j;let Y=Q2(W),z=Z[Y];if(z===void 0)throw RangeError(S7($,Y,Z));return z}function VY($,Z){if(Z>$)throw RangeError(QG)}function U0($){return{branding:h6,epochNanoseconds:$}}function D0($,Z,J){return{branding:L1,calendar:J,timeZone:Z,epochNanoseconds:$}}function J0($,Z=$.calendar){return{branding:N$,calendar:Z,...v0(s7,$)}}function j0($,Z=$.calendar){return{branding:I$,calendar:Z,...v0(gJ,$)}}function O$($,Z=$.calendar){return{branding:XZ,calendar:Z,...v0(gJ,$)}}function o3($,Z=$.calendar){return{branding:GZ,calendar:Z,...v0(gJ,$)}}function s0($){return{branding:p6,...v0(i7,$)}}function i($){return{branding:c6,sign:c1($),...v0(kJ,$)}}function MY($){return WY($.epochNanoseconds)}function B6($){return F2($.epochNanoseconds,J1)[0]}function IY($){return jY($.epochNanoseconds,M$)}function NY($){return jY($.epochNanoseconds)}function CY($){return $.epochNanoseconds}function B0($){return typeof $=="string"?$:a($.id)}function ZZ($,Z){return $===Z||B0($)===B0(Z)}function _Y($,Z,J,j,W){let Y=X$(j),[z,O]=((T,M)=>{let _=M((T=H2(T,Y2))[o7]),I=wG(T);return I=rW(Y2,I),[I,_]})(W,$);if(sZ(Math.max(z,Y),O))return fW(j,z);if(!O)throw RangeError(k6);let[X,G,K]=I6(Z,J,O),Q=a2(K),U=N6(K),B=r2(K),F=U(G,X,j),D=B(G,X,F,z);return sZ(z,O)?fW(D,z):((T,M,_,I,H,P,L)=>{let V=c1(T),[C,x]=x2(I,qJ(_,T),_,V,H,P,L),b=f2(M,C,x);return T[p[_]]+b*V})(D,Q(F),z,G,X,Q,U)}function fW($,Z){return g0(G0($),Z1[Z],1)}function x2($,Z,J,j,W,Y,z){let O=p[J],X={...Z,[O]:Z[O]+j},G=z($,W,Z),K=z($,W,X);return[Y(G),Y(K)]}function f2($,Z,J){let j=g0(y0(Z,J));if(!j)throw RangeError(z3);return g0(y0(Z,$))/j}function LY($,Z){let[J,j,W]=U6(Z,5,1);return U0(D6($.epochNanoseconds,J,j,W,1))}function PY($,Z,J){let{epochNanoseconds:j,timeZone:W,calendar:Y}=Z,[z,O,X]=U6(J);if(z===0&&O===1)return Z;let G=$(W);if(z===6)j=((K,Q,U,B)=>{let F=L0(U,Q),[D,T]=K(F),M=U.epochNanoseconds,_=b0(Q,D),I=b0(Q,T);if(JY(M,_,I))throw RangeError(z3);return vY(f2(M,_,I),B)?I:_})(RY,G,Z,X);else{let K=G.getOffsetNanosecondsFor(j);j=B$(G,AY(h1(j,K),z,O,X),K,2,0,1)}return D0(j,W,Y)}function HY($,Z){return J0(AY($,...U6(Z)),$.calendar)}function SY($,Z){let[J,j,W]=U6(Z,5);var Y;return s0((Y=W,A2($,Z3(J,j),Y)[0]))}function xY($,Z){let J=$(Z.timeZone),j=L0(Z,J),[W,Y]=RY(j),z=g0(y0(b0(J,W),b0(J,Y)),q6,1);if(z<=0)throw RangeError(z3);return z}function fY($,Z){let{timeZone:J,calendar:j}=Z,W=((Y,z,O)=>b0(z,Y(L0(O,z))))(bY,$(J),Z);return D0(W,J,j)}function AY($,Z,J,j){return EY($,Z3(Z,J),j)}function EY($,Z,J){let[j,W]=A2($,Z,J);return I1({...F$($,W),...j})}function A2($,Z,J){return O6(p1(m1($),Z,J))}function a3($){return p1($,w6,7)}function Z3($,Z){return Z1[$]*Z}function RY($){let Z=bY($);return[Z,F$(Z,1)]}function bY($){return CG(6,$)}function fX($,Z,J){let j=Math.min(X$($),6);return jZ(T6(G0($,j),Z,J),j)}function F6($,Z,J,j,W,Y,z,O,X,G){if(j===0&&W===1)return $;let K=sZ(j,O)?C6(O)&&j<6&&J>=6?EX:AX:RX,[Q,U,B]=K($,Z,J,j,W,Y,z,O,X,G);return B&&j!==7&&(Q=((F,D,T,M,_,I,H,P)=>{let L=c1(F);for(let V=M+1;V<=T;V++){if(V===7&&T!==7)continue;let C=qJ(V,F);C[p[V]]+=L;let x=g0(y0(H(P(_,I,C)),D));if(x&&Math.sign(x)!==L)break;F=C}return F})(Q,U,J,Math.max(6,j),z,O,X,G)),Q}function D6($,Z,J,j,W){if(Z===6){let Y=((z)=>z[0]+z[1]/c)($);return[p1(Y,J,j),0]}return T6($,Z3(Z,J),j,W)}function T6($,Z,J,j){let[W,Y]=$;j&&Y<0&&(Y+=c,W-=1);let[z,O]=T1(p1(Y,Z,J),c);return B2(W+z,O)}function p1($,Z,J){return vY($/Z,J)*Z}function vY($,Z){return mG[Z]($)}function AX($,Z,J,j,W,Y){let z=c1($),O=G0($),X=D6(O,j,W,Y),G=y0(O,X),K=Math.sign(X[0]-O[0])===z,Q=jZ(X,Math.min(J,6));return[{...$,...Q},s$(Z,G),K]}function EX($,Z,J,j,W,Y,z,O,X,G){let K=c1($),Q=g0(G0($,5)),U=Z3(j,W),B=p1(Q,U,Y),[F,D]=x2(z,{...$,...wJ},6,K,O,X,G),T=B-g0(y0(F,D)),M=0;T&&Math.sign(T)!==K?Z=n$(F,B):(M+=K,B=p1(T,U,Y),Z=n$(D,B));let _=L6(B);return[{...$,..._,days:$.days+M},Z,Boolean(M)]}function RX($,Z,J,j,W,Y,z,O,X,G){let K=c1($),Q=p[j],U=qJ(j,$);j===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let B=J6($[Q],W)*W;U[Q]=B;let[F,D]=x2(z,U,j,W*K,O,X,G),T=B+f2(Z,F,D)*K*W,M=p1(T,W,Y),_=Math.sign(M-T)===K;return U[Q]=M,[U,_?D:F,_]}function E2($,Z,J,j){let[W,Y,z,O]=((G)=>{let K=_2(G=i0(G));return[G.timeZone,...K]})(j),X=W!==void 0;return((G,K,Q,U,B,F)=>{Q=T6(Q,B,U,1);let D=K.getOffsetNanosecondsFor(Q);return y2(h1(Q,D),F)+(G?Q$(a3(D)):"Z")})(X,Z(X?$(W):C$),J.epochNanoseconds,Y,z,O)}function R2($,Z,J){let[j,W,Y,z,O,X]=((G)=>{G=i0(G);let K=hJ(G),Q=TY(G),U=gG(G),B=K3(G,4),F=G3(G,4);return[K,yG(G),U,B,...DY(F,Q)]})(J);return((G,K,Q,U,B,F,D,T,M,_)=>{U=T6(U,M,T,1);let I=G(Q).getOffsetNanosecondsFor(U);return y2(h1(U,I),_)+Q$(a3(I),D)+((H,P)=>P!==1?"["+(P===2?"!":"")+B0(H)+"]":"")(Q,F)+g2(K,B)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,j,W,Y,z,O,X)}function b2($,Z){let[J,j,W,Y]=((G)=>(G=i0(G),[hJ(G),..._2(G)]))(Z);return z=$.calendar,O=J,X=Y,y2(EY($,W,j),X)+g2(z,O);var z,O,X}function v2($,Z){return J=$.calendar,j=$,W=C2(Z),r3(j)+g2(J,W);var J,j,W}function k2($,Z){return kY($.calendar,wY,$,C2(Z))}function w2($,Z){return kY($.calendar,bX,$,C2(Z))}function q2($,Z){let[J,j,W]=FY(Z);return Y=W,qY(A2($,j,J)[0],Y);var Y}function V6($,Z){let[J,j,W]=FY(Z,3);return j>1&&($={...$,...fX($,j,J)}),((Y,z)=>{let{sign:O}=Y,X=O===-1?P0(Y):Y,{hours:G,minutes:K}=X,[Q,U]=F2(G0(X,3),c0,g1);dY(Q);let B=m2(U,z),F=z>=0||!O||B;return(O<0?"-":"")+"P"+AW({Y:z$(X.years),M:z$(X.months),W:z$(X.weeks),D:z$(X.days)})+(G||K||Q||F?"T"+AW({H:z$(G),M:z$(K),S:z$(Q,F)+B}):"")})($,W)}function kY($,Z,J,j){let W=B0($),Y=j>1||j===0&&W!==w;return j===1?W===w?Z(J):r3(J):Y?r3(J)+yY(W,j===2):Z(J)}function AW($){let Z=[];for(let J in $){let j=$[J];j&&Z.push(j,J)}return Z.join("")}function y2($,Z){return r3($)+"T"+qY($,Z)}function r3($){return wY($)+"-"+h0($.isoDay)}function wY($){let{isoYear:Z}=$;return(Z<0||Z>9999?gY(Z)+i3(6,Math.abs(Z)):i3(4,Z))+"-"+h0($.isoMonth)}function bX($){return h0($.isoMonth)+"-"+h0($.isoDay)}function qY($,Z){let J=[h0($.isoHour),h0($.isoMinute)];return Z!==-1&&J.push(h0($.isoSecond)+((j,W,Y,z)=>m2(j*J1+W*M$+Y,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function Q$($,Z=0){if(Z===1)return"";let[J,j]=T1(Math.abs($),q6),[W,Y]=T1(j,w6),[z,O]=T1(Y,c0);return gY($)+h0(J)+":"+h0(W)+(z||O?":"+h0(z)+m2(O):"")}function g2($,Z){if(Z!==1){let J=B0($);if(Z>1||Z===0&&J!==w)return yY(J,Z===2)}return""}function yY($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function m2($,Z){let J=i3(9,$);return J=Z===void 0?J.replace(cG,""):J.slice(0,Z),J?"."+J:""}function gY($){return $<0?"-":"+"}function z$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function vX($,Z){let{epochNanoseconds:J}=$,j=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),W=h1(J,j);return{calendar:$.calendar,...W,offsetNanoseconds:j}}function mY($,Z){let J=L0(Z,$);return{calendar:Z.calendar,...v0(s7,J),offset:Q$(J.offsetNanoseconds),timeZone:Z.timeZone}}function B$($,Z,J,j=0,W=0,Y,z){if(J!==void 0&&j===1&&(j===1||z))return V2(Z,J);let O=$.getPossibleInstantsFor(Z);if(J!==void 0&&j!==3){let X=((G,K,Q,U)=>{let B=N0(K);U&&(Q=a3(Q));for(let F of G){let D=g0(y0(F,B));if(U&&(D=a3(D)),D===Q)return F}})(O,Z,J,Y);if(X!==void 0)return X;if(j===0)throw RangeError(zG)}return z?N0(Z):b0($,Z,W,O)}function b0($,Z,J=0,j=$.getPossibleInstantsFor(Z)){if(j.length===1)return j[0];if(J===1)throw RangeError(OG);if(j.length)return j[J===3?1:0];let W=N0(Z),Y=((O,X)=>{let G=O.getOffsetNanosecondsFor(n$(X,-c));return h2(O.getOffsetNanosecondsFor(n$(X,c))-G)})($,W),z=Y*(J===2?-1:1);return(j=$.getPossibleInstantsFor(h1(W,z)))[J===2?0:j.length-1]}function p2($){if(Math.abs($)>=c)throw RangeError(WG);return $}function h2($){if($>c)throw RangeError(YG);return $}function c2($,Z,J){return U0(m0(s$(Z.epochNanoseconds,((j)=>{if(lY(j))throw RangeError(KG);return G0(j,5)})($?P0(J):J))))}function u2($,Z,J,j,W,Y=Object.create(null)){let z=Z(j.timeZone),O=$(j.calendar);return{...j,...n2(z,O,j,J?P0(W):W,Y)}}function d2($,Z,J,j,W=Object.create(null)){let{calendar:Y}=J;return J0(o2($(Y),J,Z?P0(j):j,W),Y)}function l2($,Z,J,j,W){let{calendar:Y}=J;return j0(M6($(Y),J,Z?P0(j):j,W),Y)}function i2($,Z,J,j,W=Object.create(null)){let Y=J.calendar,z=$(Y),O=iZ(z,J);Z&&(j=_6(j)),j.sign<0&&(O=z.dateAdd(O,{...F0,months:1}),O=F$(O,-1));let X=z.dateAdd(O,j,W);return O$(iZ(z,X),Y)}function s2($,Z,J){return s0(pY(Z,$?P0(J):J)[0])}function n2($,Z,J,j,W){let Y=G0(j,5),z=J.epochNanoseconds;if(lY(j)){let O=L0(J,$);z=s$(b0($,{...M6(Z,O,{...j,...wJ},W),...v0(o0,O)}),Y)}else z=s$(z,Y),y(W);return{epochNanoseconds:m0(z)}}function o2($,Z,J,j){let[W,Y]=pY(Z,J);return I1({...M6($,Z,{...J,...wJ,days:J.days+Y},j),...W})}function M6($,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(F$(Z,W)):Z}function iZ($,Z,J=1){return F$(Z,J-$.day(Z))}function pY($,Z){let[J,j]=G0(Z,5),[W,Y]=O6(m1($)+j);return[W,J+Y]}function F$($,Z){return Z?{...$,...X6(_0($)+Z*E0)}:$}function I6($,Z,J){let j=$(J.calendar);return C6(J)?[J,j,Z(J.timeZone)]:[{...J,...u0},j]}function a2($){return $?CY:N0}function N6($){return $?v(n2,$):o2}function r2($){return $?v(wX,$):qX}function C6($){return $&&$.epochNanoseconds}function sZ($,Z){return $<=6-(C6(Z)?1:0)}function t2($,Z,J,j,W,Y,z){let O=$(i0(z).relativeTo),X=Math.max(X$(W),X$(Y));if(sZ(X,O))return i(JZ(((D,T,M,_)=>{let I=s$(G0(D),G0(T),_?-1:1);if(!Number.isFinite(I[0]))throw RangeError(v6);return{...F0,...jZ(I,M)}})(W,Y,X,j)));if(!O)throw RangeError(k6);j&&(Y=P0(Y));let[G,K,Q]=I6(Z,J,O),U=N6(Q),B=r2(Q),F=U(K,G,W);return i(B(K,G,U(K,F,Y),X))}function hY($,Z,J,j,W){let Y=X$(j),[z,O,X,G,K]=((L,V,C)=>{L=H2(L,$6);let x=pJ(L),b=C(L[o7]),g=L2(L),r0=K3(L,7),m=G3(L);if(x===void 0&&m===void 0)throw RangeError(UG);return m==null&&(m=0),x==null&&(x=Math.max(m,V)),VY(x,m),g=P2(g,m,1),[x,m,g,r0,b]})(W,Y,$),Q=Math.max(Y,z);if(!C6(K)&&Q<=6)return i(JZ(((L,V,C,x,b)=>{let g=D6(G0(L),C,x,b);return{...F0,...jZ(g,V)}})(j,z,O,X,G)));if(!K)throw RangeError(k6);let[U,B,F]=I6(Z,J,K),D=a2(F),T=N6(F),M=r2(F),_=T(B,U,j),I=M(B,U,_,z),H=j.sign,P=c1(I);if(H&&P&&H!==P)throw RangeError(z3);return P&&(I=F6(I,D(_),z,O,X,G,B,U,D,T)),i(I)}function cY($){return $.sign===-1?_6($):$}function _6($){return i(P0($))}function P0($){let Z={};for(let J of p)Z[J]=-1*$[J]||0;return Z}function uY($){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(GG);J=W}}return J}function JZ($){for(let Z of IG)p0(Z,$[Z],-qW,qW,1);return dY(g0(G0($),c0)),$}function dY($){if(!Number.isSafeInteger($))throw RangeError(XG)}function G0($,Z=6){return lW($,Z,p)}function jZ($,Z=6){let[J,j]=$,W=j6(j,Z,p);if(W[p[Z]]+=J*(c/Z1[Z]),!Number.isFinite(W[p[Z]]))throw RangeError(v6);return W}function L6($,Z=5){return j6($,Z,p)}function lY($){return Boolean(c1($,l7))}function X$($){let Z=9;for(;Z>0&&!$[p[Z]];Z--);return Z}function kX($,Z){return[$,Z]}function EW($){let Z=Math.floor($/d3)*d3;return[Z,Z+d3]}function iY($){let Z=u1($=s3($));if(!Z)throw RangeError(A0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(A0($));J=WZ(Z.offset)}return Z.timeZone&&JJ(Z.timeZone,1),U0(V2(G6(Z),J))}function sY($){let Z=u1(a($));if(!Z)throw RangeError(A0($));if(Z.timeZone)return J9(Z,Z.offset?WZ(Z.offset):void 0);if(Z.m)throw RangeError(A0($));return W9(Z)}function nY($,Z){let J=u1(a($));if(!J||!J.timeZone)throw RangeError(A0($));let{offset:j}=J,W=j?WZ(j):void 0,[,Y,z]=$3(Z);return J9(J,W,Y,z)}function WZ($){let Z=JJ($);if(Z===void 0)throw RangeError(A0($));return Z}function oY($){let Z=u1(a($));if(!Z||Z.m)throw RangeError(A0($));return J0(j9(Z))}function P6($){let Z=u1(a($));if(!Z||Z.m)throw RangeError(A0($));return j0(Z.p?j9(Z):W9(Z))}function aY($,Z){let J=$J(a(Z));if(J)return e2(J),O$(T2(K$(J)));let j=P6(Z);return O$(iZ($(j.calendar),j))}function e2($){if($.calendar!==w)throw RangeError(V1($.calendar))}function rY($,Z){let J=ZJ(a(Z));if(J)return e2(J),o3(K$(J));let j=P6(Z),{calendar:W}=j,Y=$(W),[z,O,X]=Y.h(j),[G,K]=Y.I(z,O),[Q,U]=Y.N(G,K,X);return o3(q1(Y.P(Q,U,X)),W)}function tY($){let Z,J=((j)=>{let W=sG.exec(j);return W?(H6(W[10]),O9(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"));e2(J)}if((Z=$J($))&&xW(Z))throw RangeError(A0($));if((Z=ZJ($))&&xW(Z))throw RangeError(A0($));return s0(K6(J,1))}function eY($){let Z=((J)=>{let j=aG.exec(J);return j?((W)=>{function Y(K,Q,U){let B=0,F=0;if(U&&([B,X]=T1(X,Z1[U])),K!==void 0){if(O)throw RangeError(V1(K));F=((D)=>{let T=parseInt(D);if(!Number.isFinite(T))throw RangeError(V1(D));return T})(K),z=1,Q&&(X=jJ(Q)*(Z1[U]/c0),O=1)}return B+F}let z=0,O=0,X=0,G={...t$(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)]),...j6(X,2,p)};if(!z)throw RangeError(P7(p));return WJ(W[1])<0&&(G=P0(G)),G})(j):void 0})(a($));if(!Z)throw RangeError(A0($));return i(JZ(Z))}function $9($){let Z=u1($)||$J($)||ZJ($);return Z?Z.calendar:$}function Z9($){let Z=u1($);return Z&&(Z.timeZone||Z.m&&C$||Z.offset)||$}function J9($,Z,J=0,j=0){let W=S6($.timeZone),Y=u6(W);return D0(B$(Y,G6($),Z,J,j,!Y.v,$.m),W,J3($.calendar))}function j9($){return Y9(I1(G6($)))}function W9($){return Y9(q1(K$($)))}function Y9($){return{...$,calendar:J3($.calendar)}}function u1($){let Z=iG.exec($);return Z?((J)=>{let j=J[10],W=(j||"").toUpperCase()==="Z";return{isoYear:z9(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...O9(J.slice(5)),...H6(J[16]),p:Boolean(J[6]),m:W,offset:W?void 0:j}})(Z):void 0}function $J($){let Z=dG.exec($);return Z?((J)=>({isoYear:z9(J),isoMonth:parseInt(J[4]),isoDay:1,...H6(J[5])}))(Z):void 0}function ZJ($){let Z=lG.exec($);return Z?((J)=>({isoYear:r$,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...H6(J[3])}))(Z):void 0}function JJ($,Z){let J=nG.exec($);return J?((j,W)=>{let Y=j[4]||j[5];if(W&&Y)throw RangeError(V1(Y));return p2((i$(j[2])*q6+i$(j[3])*w6+i$(j[4])*c0+jJ(j[5]||""))*WJ(j[1]))})(J,Z):void 0}function z9($){let Z=WJ($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(V1(-0));return Z*J}function O9($){let Z=i$($[3]);return{...O6(jJ($[4]||""))[0],isoHour:i$($[1]),isoMinute:i$($[2]),isoSecond:Z===60?59:Z}}function H6($){let Z,J,j=[];if($.replace(oG,(W,Y,z)=>{let O=Boolean(Y),[X,G]=z.split("=").reverse();if(G){if(G==="u-ca")j.push(X),Z||(Z=O);else if(O||/[A-Z]/.test(G))throw RangeError(V1(W))}else{if(J)throw RangeError(V1(W));J=X}return""}),j.length>1&&Z)throw RangeError(V1($));return{timeZone:J,calendar:j[0]||w}}function jJ($){return parseInt($.padEnd(9,"0"))}function YZ($){return new RegExp(`^${$}$`,"i")}function WJ($){return $&&$!=="+"?-1:1}function i$($){return $===void 0?0:parseInt($)}function X9($){return S6(a($))}function S6($){let Z=YJ($);return typeof Z=="number"?Q$(Z):Z?((J)=>{if(tG.test(J))throw RangeError(jG);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?HW(Y).replace(/island|noronha|murdo|rivadavia|urville/,HW):Y)).join("/")})($):C$}function RW($){let Z=YJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:C$}function YJ($){let Z=JJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==C$?rG($):void 0}function zJ($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function OJ($,Z){return C0($.epochNanoseconds,Z.epochNanoseconds)}function G9($,Z,J,j,W,Y){let z=$(i0(Y).relativeTo),O=Math.max(X$(j),X$(W));if(uW(p,j,W))return 0;if(sZ(O,z))return C0(G0(j),G0(W));if(!z)throw RangeError(k6);let[X,G,K]=I6(Z,J,z),Q=a2(K),U=N6(K);return C0(Q(U(G,X,j)),Q(U(G,X,W)))}function XJ($,Z){return D$($,Z)||x6($,Z)}function D$($,Z){return w1(_0($),_0(Z))}function x6($,Z){return w1(m1($),m1(Z))}function K9($,Z){return!zJ($,Z)}function U9($,Z){return!OJ($,Z)&&!!f6($.timeZone,Z.timeZone)&&ZZ($.calendar,Z.calendar)}function Q9($,Z){return!XJ($,Z)&&ZZ($.calendar,Z.calendar)}function B9($,Z){return!D$($,Z)&&ZZ($.calendar,Z.calendar)}function F9($,Z){return!D$($,Z)&&ZZ($.calendar,Z.calendar)}function D9($,Z){return!D$($,Z)&&ZZ($.calendar,Z.calendar)}function T9($,Z){return!x6($,Z)}function f6($,Z){if($===Z)return 1;let J=B0($),j=B0(Z);if(J===j)return 1;try{return RW(J)===RW(j)}catch(W){}}function GJ($,Z,J,j){let W=$Z($,Z0(j),3,5),Y=A6(Z.epochNanoseconds,J.epochNanoseconds,...W);return i($?P0(Y):Y)}function KJ($,Z,J,j,W,Y){let z=R6(j.calendar,W.calendar),O=Z0(Y),[X,G,K,Q]=$Z(J,O,5),U=j.epochNanoseconds,B=W.epochNanoseconds,F=C0(B,U),D;if(F)if(X<6)D=A6(U,B,X,G,K,Q);else{let T=Z(((_,I)=>{if(!f6(_,I))throw RangeError(E7);return _})(j.timeZone,W.timeZone)),M=$(z);D=M9(M,T,j,W,F,X,O),D=F6(D,B,X,G,K,Q,M,j,CY,v(n2,T))}else D=F0;return i(J?P0(D):D)}function UJ($,Z,J,j,W){let Y=R6(J.calendar,j.calendar),z=Z0(W),[O,X,G,K]=$Z(Z,z,6),Q=N0(J),U=N0(j),B=C0(U,Q),F;if(B)if(O<=6)F=A6(Q,U,O,X,G,K);else{let D=$(Y);F=I9(D,J,j,B,O,z),F=F6(F,U,O,X,G,K,D,J,N0,o2)}else F=F0;return i(Z?P0(F):F)}function QJ($,Z,J,j,W){let Y=R6(J.calendar,j.calendar),z=Z0(W);return V9(Z,()=>$(Y),J,j,...$Z(Z,z,6,9,6),z)}function BJ($,Z,J,j,W){let Y=R6(J.calendar,j.calendar),z=Z0(W),O=$Z(Z,z,9,9,8),X=$(Y);return V9(Z,()=>X,iZ(X,J),iZ(X,j),...O,z)}function V9($,Z,J,j,W,Y,z,O,X){let G=N0(J),K=N0(j),Q;if(C0(K,G))if(W===6)Q=A6(G,K,W,Y,z,O);else{let U=Z();Q=U.dateUntil(J,j,W,X),Y===6&&z===1||(Q=F6(Q,K,W,Y,z,O,U,J,N0,M6))}else Q=F0;return i($?P0(Q):Q)}function FJ($,Z,J,j){let W=Z0(j),[Y,z,O,X]=$Z($,W,5,5),G=p1(DJ(Z,J),Z3(z,O),X),K={...F0,...L6(G,Y)};return i($?P0(K):K)}function wX($,Z,J,j,W,Y){let z=C0(j.epochNanoseconds,J.epochNanoseconds);return z?W<6?N9(J.epochNanoseconds,j.epochNanoseconds,W):M9(Z,$,J,j,z,W,Y):F0}function qX($,Z,J,j,W){let Y=N0(Z),z=N0(J),O=C0(z,Y);return O?j<=6?N9(Y,z,j):I9($,Z,J,O,j,W):F0}function M9($,Z,J,j,W,Y,z){let[O,X,G]=((U,B,F,D)=>{function T(){return V={...F$(I,P++*-D),..._},C=b0(U,V),C0(H,C)===-D}let M=L0(B,U),_=v0(o0,M),I=L0(F,U),H=F.epochNanoseconds,P=0,L=DJ(M,I),V,C;if(Math.sign(L)===-D&&P++,T()&&(D===-1||T()))throw RangeError(z3);let x=g0(y0(C,H));return[M,V,x]})(Z,J,j,W);var K,Q;return{...Y===6?(K=O,Q=X,{...F0,days:C9(K,Q)}):$.dateUntil(O,X,Y,z),...L6(G)}}function I9($,Z,J,j,W,Y){let[z,O,X]=((G,K,Q)=>{let U=K,B=DJ(G,K);return Math.sign(B)===-Q&&(U=F$(K,-Q),B+=c*Q),[G,U,B]})(Z,J,j);return{...$.dateUntil(z,O,W,Y),...L6(X)}}function A6($,Z,J,j,W,Y){return{...F0,...jZ(D6(y0($,Z),j,W,Y),J)}}function N9($,Z,J){return{...F0,...jZ(y0($,Z),J)}}function C9($,Z){return E6(_0($),_0(Z))}function E6($,Z){return Math.trunc((Z-$)/E0)}function DJ($,Z){return m1(Z)-m1($)}function R6($,Z){if(!ZZ($,Z))throw RangeError(EJ);return $}function yX($){function Z(W){return((Y,z)=>({..._9(Y,z),F:Y.month,day:parseInt(Y.day)}))(D2(J,W),j)}let J=lJ($),j=t3($);return{id:$,O:gX(Z),B:mX(Z)}}function gX($){return R0((Z)=>{let J=_0(Z);return $(J)},WeakMap)}function mX($){let Z=$(0).year-HG;return R0((J)=>{let j,W=e$(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:v7(z.reverse())}})}function _9($,Z){let J,j,W=L9($);if($.era){let Y=c7[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=f9(j,Y[J]||0))}return{era:J,eraYear:j,year:W}}function L9($){return parseInt($.relatedYear||$.year)}function e8($){let{year:Z,F:J,day:j}=this.O($),{C:W}=this.B(Z);return[Z,W[J]+1,j]}function nZ($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*E0}function h3($){let Z=vW(this,$),J=vW(this,$-1),j=Z.length;if(j>J.length){let W=A9(this);if(W<0)return-W;for(let Y=0;Y<j;Y++)if(Z[Y]!==J[Y])return Y+1}}function c3($){return E6(nZ.call(this,$),nZ.call(this,$+1))}function bW($,Z){let{k:J}=this.B($),j=Z+1,W=J;return j>J.length&&(j=1,W=this.B($+1).k),E6(J[Z-1],W[j-1])}function u3($){return this.B($).k.length}function vW($,Z){return Object.keys($.B(Z).C)}function P9($){return J3(a($))}function J3($){if(($=$.toLowerCase())!==w&&$!==g6&&t3($)!==t3(lJ($).resolvedOptions().calendar))throw RangeError(JG($));return $}function t3($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function H9($){return this.R($)[0]}function S9($){return this.R($)[1]}function TJ($){let[Z]=this.h($);return E6(this.q(Z),_0($))+1}function x9($){let Z=$K.exec($);if(!Z)throw RangeError($G($));return[parseInt(Z[1]),Boolean(Z[2])]}function e3($,Z,J){return $+(Z||J&&$>=J?1:0)}function $2($,Z){return $-(Z&&$>=Z?1:0)}function f9($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function Z2($){return c7[E9($)]}function A9($){return TG[E9($)]}function E9($){return t3($.id||w)}function R9($,Z,J,j){let W=d1(J,j,n0,[],g7);if(W.timeZone!==void 0){let Y=J.dateFromFields(W),z=T$(W),O=$(W.timeZone);return{epochNanoseconds:B$(Z(O),{...Y,...z},W.offset!==void 0?WZ(W.offset):void 0),timeZone:O}}return{...J.dateFromFields(W),...u0}}function b9($,Z,J,j,W,Y){let z=d1(J,W,n0,q7,g7),O=$(z.timeZone),[X,G,K]=$3(Y),Q=J.dateFromFields(z,Q6(Y,X)),U=T$(z,X);return D0(B$(Z(O),{...Q,...U},z.offset!==void 0?WZ(z.offset):void 0,G,K),O,j)}function v9($,Z,J){let j=d1($,Z,n0,[],_1),W=y(J);return J0(I1({...$.dateFromFields(j,Q6(J,W)),...T$(j,W)}))}function VJ($,Z,J,j=[]){let W=d1($,Z,n0,j);return $.dateFromFields(W,J)}function MJ($,Z,J,j){let W=d1($,Z,vJ,j);return $.yearMonthFromFields(W,J)}function IJ($,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=r$),$.monthDayFromFields(Y,j)}function k9($,Z){let J=y(Z);return s0(T$($1($,j2,[],1),J))}function w9($){let Z=$1($,kJ);return i(JZ({...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 O of Z){if(O===Y)throw RangeError(nX(O));if(O==="constructor"||O==="__proto__")throw RangeError(fJ(O));let X=$[O];if(X!==void 0)z=1,yW[O]&&(X=yW[O](X,O)),W[O]=X;else if(J){if(J.includes(O))throw TypeError(xJ(O));W[O]=h7[O]}Y=O}if(j&&!z)throw TypeError(P7(Z));return W}function T$($,Z){return K6(WK({...h7,...$}),Z)}function q9($,Z,J,j,W,Y){let z=Z0(Y),{calendar:O,timeZone:X}=J;return D0(((G,K,Q,U,B)=>{let F=j3(G,Q,U,n0,y7,w7),[D,T,M]=$3(B,2);return B$(K,{...G.dateFromFields(F,Q6(B,D)),...T$(F,D)},WZ(F.offset),T,M)})($(O),Z(X),j,W,z),X,O)}function y9($,Z,J,j,W){let Y=Z0(W);return J0(((z,O,X,G)=>{let K=j3(z,O,X,n0,_1),Q=y(G);return I1({...z.dateFromFields(K,Q6(G,Q)),...T$(K,Q)})})($(Z.calendar),J,j,Y))}function g9($,Z,J,j,W){let Y=Z0(W);return((z,O,X,G)=>{let K=j3(z,O,X,n0);return z.dateFromFields(K,G)})($(Z.calendar),J,j,Y)}function m9($,Z,J,j,W){let Y=Z0(W);return O$(((z,O,X,G)=>{let K=j3(z,O,X,vJ);return z.yearMonthFromFields(K,G)})($(Z.calendar),J,j,Y))}function p9($,Z,J,j,W){let Y=Z0(W);return((z,O,X,G)=>{let K=j3(z,O,X,n0);return z.monthDayFromFields(K,G)})($(Z.calendar),J,j,Y)}function h9($,Z,J){return s0(((j,W,Y)=>{let z=y(Y);return T$({...v0(j2,j),...$1(W,j2)},z)})($,Z,J))}function c9($,Z){return i((J=$,j=Z,JZ({...J,...$1(j,kJ)})));var J,j}function j3($,Z,J,j,W=[],Y=[]){let z=[...$.fields(j),...W].sort(),O=$1(Z,z,Y),X=$1(J,z);return O=$.mergeFields(O,X),$1(O,z,[])}function NJ($,Z){let J=d1($,Z,p7);return $.monthDayFromFields(J)}function CJ($,Z,J){let j=d1($,Z,m7);return $.yearMonthFromFields(j,J)}function u9($,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 n8($,Z){let{era:J,eraYear:j,year:W}=Z,Y=Z2($);if(J!==void 0||j!==void 0){if(J===void 0||j===void 0)throw TypeError(aX);if(!Y)throw RangeError(oX);let z=Y[J];if(z===void 0)throw RangeError(tX(J));let O=f9(j,z);if(W!==void 0&&W!==O)throw RangeError(rX);W=O}else if(W===void 0)throw TypeError(eX(Y));return W}function o8($,Z,J,j){let{month:W,monthCode:Y}=Z;if(Y!==void 0){let z=((O,X,G,K)=>{let Q=O.U(G),[U,B]=x9(X),F=e3(U,B,Q);if(B){let D=A9(O);if(D===void 0)throw RangeError(uZ);if(D>0){if(F>D)throw RangeError(uZ);if(Q===void 0){if(K===1)throw RangeError(uZ);F--}}else{if(F!==-D)throw RangeError(uZ);if(Q===void 0&&K===1)throw RangeError(uZ)}}return F})($,Y,J,j);if(W!==void 0&&W!==z)throw RangeError(f7);W=z,j=1}else if(W===void 0)throw TypeError(ZG);return p0("month",W,1,$.L(J),j)}function kW($,Z,J,j,W){return f0(Z,"day",1,$.j(j,J),W)}function a8($,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 d9($){return U0(m0(z6(Y6($))))}function l9($,Z,J,j,W=w){return D0(m0(z6(Y6(J))),Z(j),$(W))}function i9($,Z,J,j,W=0,Y=0,z=0,O=0,X=0,G=0,K=w){return J0(I1(G6(d0(I0,t$(m6,[Z,J,j,W,Y,z,O,X,G])))),$(K))}function s9($,Z,J,j,W=w){return j0(q1(K$(d0(I0,{isoYear:Z,isoMonth:J,isoDay:j}))),$(W))}function n9($,Z,J,j=w,W=1){let Y=I0(Z),z=I0(J),O=$(j);return O$(T2(K$({isoYear:Y,isoMonth:z,isoDay:I0(W)})),O)}function o9($,Z,J,j=w,W=r$){let Y=I0(Z),z=I0(J),O=$(j);return o3(q1(K$({isoYear:I0(W),isoMonth:Y,isoDay:z})),O)}function a9($=0,Z=0,J=0,j=0,W=0,Y=0){return s0(K6(d0(I0,t$(o0,[$,Z,J,j,W,Y])),1))}function r9($=0,Z=0,J=0,j=0,W=0,Y=0,z=0,O=0,X=0,G=0){return i(JZ(d0(ZY,t$(p,[$,Z,J,j,W,Y,z,O,X,G]))))}function _J($,Z,J=w){return D0($.epochNanoseconds,Z,J)}function t9($){return U0($.epochNanoseconds)}function LJ($,Z){return J0(L0(Z,$))}function PJ($,Z){return j0(L0(Z,$))}function e9($,Z,J){return CJ($(Z.calendar),J)}function $7($,Z,J){return NJ($(Z.calendar),J)}function HJ($,Z){return s0(L0(Z,$))}function Z7($,Z,J,j){let W=((Y,z,O,X)=>{let G=N2(X);return b0(Y(z),O,G)})($,J,Z,j);return D0(m0(W),J,Z.calendar)}function J7($,Z,J){let j=$(Z.calendar);return O$({...Z,...CJ(j,J)})}function j7($,Z,J){return NJ($(Z.calendar),J)}function W7($,Z,J,j,W){let Y=$(W.timeZone),z=W.plainTime,O=z!==void 0?Z(z):u0;return D0(b0(J(Y),{...j,...O}),Y,j.calendar)}function Y7($,Z=u0){return J0(I1({...$,...Z}))}function z7($,Z,J){return CJ($(Z.calendar),J)}function O7($,Z,J){return NJ($(Z.calendar),J)}function X7($,Z,J,j){return((W,Y,z)=>u9(W,Y,m7,M1(z),X3))($(Z.calendar),J,j)}function G7($,Z,J,j){return((W,Y,z)=>u9(W,Y,p7,M1(z),y6))($(Z.calendar),J,j)}function K7($,Z,J,j,W){let Y=M1(W),z=Z(Y.plainDate),O=$(Y.timeZone);return D0(b0(J(O),{...z,...j}),O,z.calendar)}function U7($,Z){return J0(I1({...$,...Z}))}function Q7($){return U0(m0(o$($,c0)))}function B7($){return U0(m0(o$($,J1)))}function F7($){return U0(m0(z6(Y6($),M$)))}function D7($){return U0(m0(z6(Y6($))))}function T7($,Z,J=u0){let j=Z.timeZone,W=$(j),Y={...L0(Z,W),...J};return D0(B$(W,Y,Y.offsetNanoseconds,2),j,Z.calendar)}function V7($,Z,J){let j=Z.timeZone,W=$(j),Y={...L0(Z,W),...J},z=C7(Z.calendar,J.calendar);return D0(B$(W,Y,Y.offsetNanoseconds,2),j,z)}function M7($,Z=u0){return J0({...$,...Z})}function I7($,Z){return J0({...$,...Z},C7($.calendar,Z.calendar))}function b6($,Z){return{...$,calendar:Z}}function N7($,Z){return{...$,timeZone:Z}}function C7($,Z){if($===Z)return $;let J=B0($),j=B0(Z);if(J===j||J===w)return Z;if(j===w)return $;throw RangeError(EJ)}function pX($,Z){return(J)=>J===w?$:J===g6||J===a$?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),eG(J))}function V$($,Z,J){let j=new Set(J);return(W)=>(((Y,z)=>{for(let O of z)if(O in Y)return 1;return 0})(W=O2(j,W),$)||Object.assign(W,Z),J&&(W.timeZone=C$,["full","long"].includes(W.timeStyle)&&(W.timeStyle="medium")),W)}function N1($,Z=SJ){let[J,,,j]=$;return(W,Y=NK,...z)=>{let O=Z(j&&j(...z),W,Y,J),X=O.resolvedOptions();return[O,...hX($,X,z)]}}function SJ($,Z,J,j){if(J=j(J),$){if(J.timeZone!==void 0)throw TypeError(BG);J.timeZone=$}return new l1(Z,J)}function hX($,Z,J){let[,j,W]=$;return J.map((Y)=>(Y.calendar&&((z,O,X)=>{if((X||z!==w)&&z!==O)throw RangeError(EJ)})(B0(Y.calendar),Z.calendar,W),j(Y,Z)))}function zZ($){let Z=W3();return h1(Z,$.getOffsetNanosecondsFor(Z))}function W3(){return o$(Date.now(),J1)}function C1(){return mW||(mW=new l1().resolvedOptions().timeZone)}var cX=($,Z)=>`Non-integer ${$}: ${Z}`,uX=($,Z)=>`Non-positive ${$}: ${Z}`,dX=($,Z)=>`Non-finite ${$}: ${Z}`,lX=($)=>`Cannot convert bigint to ${$}`,iX=($)=>`Invalid bigint: ${$}`,sX="Cannot convert Symbol to string",_7="Invalid object",L7=($,Z,J,j,W)=>W?L7($,W[Z],W[J],W[j]):Y3($,Z)+`; must be between ${J}-${j}`,Y3=($,Z)=>`Invalid ${$}: ${Z}`,xJ=($)=>`Missing ${$}`,fJ=($)=>`Invalid field ${$}`,nX=($)=>`Duplicate field ${$}`,P7=($)=>"No valid fields: "+$.join(),H7="Invalid bag",S7=($,Z,J)=>Y3($,Z)+"; must be "+Object.keys(J).join(),x7="Cannot use valueOf",AJ="Invalid calling context",oX="Forbidden era/eraYear",aX="Mismatching era/eraYear",rX="Mismatching year/eraYear",tX=($)=>`Invalid era: ${$}`,eX=($)=>"Missing year"+($?"/era/eraYear":""),$G=($)=>`Invalid monthCode: ${$}`,f7="Mismatching month/monthCode",ZG="Missing month/monthCode",wW="Cannot guess year",uZ="Invalid leap month",A7="Invalid protocol",z3="Invalid protocol results",EJ="Mismatching Calendars",JG=($)=>`Invalid Calendar: ${$}`,E7="Mismatching TimeZones",jG="Forbidden ICU TimeZone",WG="Out-of-bounds offset",YG="Out-of-bounds TimeZone gap",zG="Invalid TimeZone offset",OG="Ambiguous offset",v6="Out-of-bounds date",XG="Out-of-bounds duration",GG="Cannot mix duration signs",k6="Missing relativeTo",KG="Cannot use large units",UG="Required smallestUnit or largestUnit",QG="smallestUnit > largestUnit",A0=($)=>`Cannot parse: ${$}`,V1=($)=>`Invalid substring: ${$}`,R7=($)=>`Cannot format ${$}`,b7="Mismatching types for formatting",BG="Cannot specify TimeZone",v7=v(rZ,($,Z)=>Z),OZ=v(rZ,($,Z,J)=>J),h0=v(i3,2),J2={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},O3=Object.keys(J2),E0=86400000,k7=1000,M$=1000,J1=1e6,c0=1e9,w6=60000000000,q6=3600000000000,c=86400000000000,Z1=[1,M$,J1,c0,w6,q6,c],_1=O3.slice(0,6),j2=tZ(_1),w7=["offset"],q7=["timeZone"],y7=_1.concat(w7),g7=y7.concat(q7),W2=["era","eraYear"],FG=W2.concat(["year"]),y6=["year"],RJ=["monthCode"],bJ=["month"].concat(RJ),X3=["day"],vJ=bJ.concat(y6),m7=RJ.concat(y6),n0=X3.concat(vJ),DG=X3.concat(bJ),p7=X3.concat(RJ),h7=OZ(_1,0),w="iso8601",g6="gregory",a$="japanese",c7={[g6]:{bce:-1,ce:0},[a$]:{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}},TG={chinese:13,dangi:13,hebrew:-6},a=v(W6,"string"),u7=v(W6,"boolean"),VG=v(W6,"number"),d7=v(W6,"function"),p=O3.map(($)=>$+"s"),kJ=tZ(p),MG=p.slice(0,6),l7=p.slice(6),IG=l7.slice(1),NG=v7(p),F0=OZ(p,0),wJ=OZ(MG,0),qJ=v(dW,p),o0=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],yJ=["isoDay","isoMonth","isoYear"],m6=o0.concat(yJ),gJ=tZ(yJ),i7=tZ(o0),s7=tZ(m6),u0=OZ(i7,0),CG=v(dW,m6),l1=Intl.DateTimeFormat,n7="en-GB",mJ=1e8,_G=mJ*E0,LG=[mJ,0],PG=[-mJ,0],oZ=275760,aZ=-271821,HG=1970,r$=1972,D1=12,SG=e$(1868,9,8),xG=R0(xX,WeakMap),$6="smallestUnit",Y2="unit",lZ="roundingIncrement",r8="fractionalSecondDigits",o7="relativeTo",a7={constrain:0,reject:1},fG=Object.keys(a7),AG={compatible:0,reject:1,earlier:2,later:3},EG={reject:0,use:1,prefer:2,ignore:3},RG={auto:0,never:1,critical:2,always:3},bG={auto:0,never:1,critical:2},vG={auto:0,never:1},kG={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},G3=v(S2,$6),pJ=v(S2,"largestUnit"),wG=v(S2,Y2),r7=v(U$,"overflow",a7),t7=v(U$,"disambiguation",AG),qG=v(U$,"offset",EG),hJ=v(U$,"calendarName",RG),yG=v(U$,"timeZoneName",bG),gG=v(U$,"offset",vG),K3=v(U$,"roundingMode",kG),XZ="PlainYearMonth",GZ="PlainMonthDay",I$="PlainDate",N$="PlainDateTime",p6="PlainTime",L1="ZonedDateTime",h6="Instant",c6="Duration",mG=[Math.floor,($)=>p3($)?Math.floor($):Math.round($),Math.ceil,($)=>p3($)?Math.ceil($):Math.round($),Math.trunc,($)=>p3($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>p3($)?($=Math.trunc($)||0)+$%2:Math.round($)],C$="UTC",d3=5184000,pG=n3(1847),hG=n3(new Date().getUTCFullYear()+10),cG=/0+$/,L0=R0(vX,WeakMap),qW=4294967295,u6=R0(($)=>{let Z=YJ($);return typeof Z=="object"?new $5(Z):new e7(Z||0)});class e7{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[V2($,this.v)]}l(){}}class $5{constructor($){this.$=((Z)=>{function J(X){let G=t8(X,z,O),[K,Q]=EW(G),U=W(K),B=W(Q);return U===B?U:j(Y(K,Q),U,B,X)}function j(X,G,K,Q){let U,B;for(;(Q===void 0||(U=Q<X[0]?G:Q>=X[1]?K:void 0)===void 0)&&(B=X[1]-X[0]);){let F=X[0]+Math.floor(B/2);Z(F)===K?X[1]=F:X[0]=F+1}return U}let W=R0(Z),Y=R0(kX),z=pG,O=hG;return{G(X){let G=J(X-86400),K=J(X+86400),Q=X-G,U=X-K;if(G===K)return[Q];let B=J(Q);return B===J(U)?[X-B]:G>K?[Q,U]:[]},V:J,l(X,G){let K=t8(X,z,O),[Q,U]=EW(K),B=d3*G,F=G<0?()=>U>z||(z=K,0):()=>Q<O||(O=K,0);for(;F();){let D=W(Q),T=W(U);if(D!==T){let M=Y(Q,U);j(M,D,T);let _=M[0];if((w1(_,X)||1)===G)return _}Q+=B,U+=B}}}})(((Z)=>(J)=>{let j=D2(Z,J*k7);return n3(L9(j),parseInt(j.month),parseInt(j.day),parseInt(j.hour),parseInt(j.minute),parseInt(j.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(WY($))*c0}getPossibleInstantsFor($){let[Z,J]=[n3((j=$).isoYear,j.isoMonth,j.isoDay,j.isoHour,j.isoMinute,j.isoSecond),j.isoMillisecond*J1+j.isoMicrosecond*M$+j.isoNanosecond];var j;return this.$.G(Z).map((W)=>m0(n$(o$(W,c0),J)))}l($,Z){let[J,j]=YY($),W=this.$.l(J+(Z>0||j?1:0),Z);if(W!==void 0)return o$(W,c0)}}var cJ="([+\u2212-])",l3="(?:[.,](\\d{1,9}))?",Z5=`(?:(?:${cJ}(\\d{6}))|(\\d{4}))-?(\\d{2})`,uJ="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+l3+")?)?",dJ=cJ+uJ,uG=Z5+"-?(\\d{2})(?:[T ]"+uJ+"(Z|"+dJ+")?)?",J5="\\[(!?)([^\\]]*)\\]",d6=`((?:${J5}){0,9})`,dG=YZ(Z5+d6),lG=YZ("(?:--)?(\\d{2})-?(\\d{2})"+d6),iG=YZ(uG+d6),sG=YZ("T?"+uJ+"(?:"+dJ+")?"+d6),nG=YZ(dJ),oG=new RegExp(J5,"g"),aG=YZ(`${cJ}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${l3}H)?(?:(\\d+)${l3}M)?(?:(\\d+)${l3}S)?)?`),rG=R0(($)=>new l1(n7,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),tG=/^(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$/,eG=R0(yX),lJ=R0(($)=>new l1(n7,{calendar:$,timeZone:C$,era:"short",year:"numeric",month:"short",day:"numeric"})),$K=/^M(\d{2})(L?)$/,ZK={era:s3,eraYear:I0,year:I0,month:SW,monthCode:s3,day:SW},JK=OZ(_1,I0),jK=OZ(p,ZY),yW=Object.assign({},ZK,JK,jK,{offset:s3}),WK=v(SX,_1,o0),gW={dateAdd($,Z,J){let j=y(J),W,{years:Y,months:z,weeks:O,days:X}=Z;if(X+=G0(Z,5)[0],Y||z)W=((G,K,Q,U,B)=>{let[F,D,T]=G.h(K);if(Q){let[M,_]=G.I(F,D);F+=Q,D=e3(M,_,G.U(F)),D=p0("month",D,1,G.L(F),B)}return U&&([F,D]=G._(F,D,U)),T=p0("day",T,1,G.j(F,D),B),G.q(F,D,T)})(this,$,Y,z,j);else{if(!O&&!X)return $;W=_0($)}return W+=(7*O+X)*E0,q1(X6(W))},dateUntil($,Z,J){if(J<=7){let X=0,G=C9({...$,...u0},{...Z,...u0});return J===7&&([X,G]=g1(G,7)),{...F0,weeks:X,days:G}}let j=this.h($),W=this.h(Z),[Y,z,O]=((X,G,K,Q,U,B,F)=>{let D=U-G,T=B-K,M=F-Q;if(D||T){let _=Math.sign(D||T),I=X.j(U,B),H=0;if(Math.sign(M)===-_){let P=I;[U,B]=X._(U,B,-_),D=U-G,T=B-K,I=X.j(U,B),H=_<0?-P:I}if(M=F-Math.min(Q,I)+H,D){let[P,L]=X.I(G,K),[V,C]=X.I(U,B);if(T=V-P||Number(C)-Number(L),Math.sign(T)===-_){let x=_<0&&-X.L(U);D=(U-=_)-G,T=B-e3(P,L,X.U(U))+(x||X.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:O}},dateFromFields($,Z){let J=y(Z),j=n8(this,$),W=o8(this,$,j,J),Y=kW(this,$,W,j,J);return j0(q1(this.P(j,W,Y)),this.id||w)},yearMonthFromFields($,Z){let J=y(Z),j=n8(this,$),W=o8(this,$,j,J);return O$(T2(this.P(j,W,1)),this.id||w)},monthDayFromFields($,Z){let J=y(Z),j=!this.id,{monthCode:W,year:Y,month:z}=$,O,X,G,K,Q;if(W!==void 0){[O,X]=x9(W),Q=pW($,"day");let U=this.N(O,X,Q);if(!U)throw RangeError(wW);if([G,K]=U,z!==void 0&&z!==K)throw RangeError(f7);j&&(K=p0("month",K,1,D1,1),Q=p0("day",Q,1,M2(Y!==void 0?Y:G,K),J))}else{G=Y===void 0&&j?r$:n8(this,$),K=o8(this,$,G,J),Q=kW(this,$,K,G,J);let U=this.U(G);X=K===U,O=$2(K,U);let B=this.N(O,X,Q);if(!B)throw RangeError(wW);[G,K]=B}return o3(q1(this.P(G,K,Q)),this.id||w)},fields($){return Z2(this)&&$.includes("year")?[...$,...W2]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return a8(J,Z,bJ),Z2(this)&&(a8(J,Z,FG),this.id===a$&&a8(J,Z,DG,W2)),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:TJ,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:KY,daysInWeek(){return 7}},YK={dayOfYear:TJ,h:OY,q:e$},zK=Object.assign({},YK,{weekOfYear:H9,yearOfWeek:S9,R($){function Z(B){return(7-B<j?7:0)-B}function J(B){let F=GY(U+B),D=B||1,T=Z(dZ(X+F*D,7));return K=(F+(T-G)*D)/7}let j=this.id?1:4,W=KY($),Y=this.dayOfYear($),z=dZ(W-1,7),O=Y-1,X=dZ(z-O,7),G=Z(X),K,Q=Math.floor((O-G)/7)+1,U=$.isoYear;return Q?Q>J(0)&&(Q=1,U++):(Q=J(-1),U--),[Q,U,K]}}),OK={dayOfYear:TJ,h:e8,q:nZ,weekOfYear:H9,yearOfWeek:S9,R(){return[]}},KZ=pX(Object.assign({},gW,zK,{h:OY,ee($){return this.id===g6?UY($):this.id===a$?xG($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[r$,$]},K:I2,U(){},L:XY,J:($)=>$*D1,j:M2,X:GY,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:e$,_:($,Z,J)=>($+=J6(J,D1),(Z+=G2(J,D1))<1?($--,Z+=D1):Z>D1&&($++,Z-=D1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},gW,OK,{h:e8,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=h3.call(this,$);return[$2(Z,J),J===Z]},N($,Z,J){let[j,W,Y]=e8.call(this,{isoYear:r$,isoMonth:D1,isoDay:31}),z=h3.call(this,j),O=W===z;(w1($,$2(W,z))||w1(Number(Z),Number(O))||w1(J,Y))===1&&j--;for(let X=0;X<100;X++){let G=j-X,K=h3.call(this,G),Q=e3($,Z,K);if(Z===(Q===K)&&J<=bW.call(this,G,Q))return[G,Q]}},K($){let Z=c3.call(this,$);return Z>c3.call(this,$-1)&&Z>c3.call(this,$+1)},U:h3,L:u3,J($,Z){let J=Z+$,j=Math.sign($),W=j<0?-1:0,Y=0;for(let z=Z;z!==J;z+=j)Y+=u3.call(this,z+W);return Y},j:bW,X:c3,P($,Z,J){return X6(nZ.call(this,$,Z,J))},q:nZ,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(v6);if(J<0)for(;Z<1;)Z+=u3.call(this,--$);else{let j;for(;Z>(j=u3.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",UZ=["timeZoneName"],j5={month:y1,day:y1},iJ={year:y1,month:y1},sJ=Object.assign({},iJ,{day:y1}),nJ={hour:y1,minute:y1,second:y1},oJ=Object.assign({},sJ,nJ),XK=Object.assign({},oJ,{timeZoneName:"short"}),GK=Object.keys(iJ),KK=Object.keys(j5),UK=Object.keys(sJ),QK=Object.keys(nJ),aJ=["dateStyle"],BK=GK.concat(aJ),FK=KK.concat(aJ),rJ=UK.concat(aJ,["weekday"]),U3=QK.concat(["dayPeriod","timeStyle"]),tJ=rJ.concat(U3),DK=tJ.concat(UZ),TK=UZ.concat(U3),VK=UZ.concat(rJ),MK=UZ.concat(["day","weekday"],U3),IK=UZ.concat(["year","weekday"],U3),NK={},eJ=[V$(tJ,oJ),B6],W5=[V$(DK,XK),B6,0,($,Z)=>{let J=B0($.timeZone);if(Z&&B0(Z.timeZone)!==J)throw RangeError(E7);return J}],$4=[V$(tJ,oJ,UZ),_0],Z4=[V$(rJ,sJ,TK),_0],J4=[V$(U3,nJ,VK),($)=>m1($)/J1],j4=[V$(BK,iJ,MK),_0,1],W4=[V$(FK,j5,IK),_0,1],mW;function Y1($,Z,J,j,W){function Y(...X){if(!(this instanceof Y))throw TypeError(AJ);X5(this,Z(...X))}function z(X,G){return Object.defineProperties(function(...K){return X.call(this,O(this),...K)},z2(G))}function O(X){let G=M0(X);if(!G||G.branding!==$)throw TypeError(AJ);return G}return Object.defineProperties(Y.prototype,{...hW(d0(z,J)),...G$(d0(z,j)),...Z6("Temporal."+$)}),Object.defineProperties(Y,{...G$(W),...z2($)}),[Y,(X)=>{let G=Object.create(Y.prototype);return X5(G,X),G},O]}function U5($){return $=$.concat("id").sort(),(Z)=>{if(!cW(Z,$))throw TypeError(A7);return Z}}function DZ($){if(M0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(H7);return $}function l6($,Z){let J={};for(let j in $)J[j]=({o:W},Y)=>{let z=M0(Y)||{},{branding:O}=z,X=O===I$||Z.includes(O)?z:S0(Y);return W[j](X)};return J}function O4($){let Z={};for(let J in $)Z[J]=(j)=>{let{calendar:W}=j;return(Y=W,typeof Y=="string"?KZ(Y):(z=Y,Object.assign(Object.create(qK),{i:z})))[J](j);var Y,z};return Z}function a1(){throw TypeError(x7)}function B3({calendar:$}){return typeof $=="string"?new T4($):$}function Y5($,Z){if(Z=Z0(Z),K0($)){let j=M0($);if(j&&j.branding===GZ)return y(Z),j;let W=F5($);return IJ(t6(W||w),!W,$,Z)}let J=rY(KZ,$);return y(Z),J}function Q5($,Z,J){return j=Z.call($,H0(U0(J))),p2(eZ(j));var j}function i6($,Z=M5){let J=Object.keys(Z).sort(),j={};for(let W of J)j[W]=v(Z[W],$,d7($[W]));return j}function u($,Z){return typeof $=="string"?u6($):i6($,Z)}function Y0($){return u($,z4)}function j1($){if(K0($)){let Z=M0($);if(Z)switch(Z.branding){case h6:return Z;case L1:return U0(Z.epochNanoseconds)}}return iY($)}function z5($,Z,J){let j=Z.l(j1(J).epochNanoseconds,$);return j?H0(U0(j)):null}function l($){return K0($)?(M0($)||{}).timeZone||cK($):((Z)=>S6(Z9(a(Z))))($)}function i1($,Z){if(K0($)){let J=M0($)||{};switch(J.branding){case p6:return y(Z),J;case N$:return y(Z),s0(J);case L1:return y(Z),HJ(Y0,J)}return k9($,Z)}return y(Z),tY($)}function X4($){return $===void 0?void 0:i1($)}function QZ($,Z){if(Z=Z0(Z),K0($)){let j=M0($);return j&&j.branding===XZ?(y(Z),j):MJ(a6(F3($)),$,Z)}let J=aY(KZ,$);return y(Z),J}function s1($,Z){if(Z=Z0(Z),K0($)){let j=M0($)||{};switch(j.branding){case N$:return y(Z),j;case I$:return y(Z),J0({...j,...u0});case L1:return y(Z),LJ(Y0,j)}return v9(r6(F3($)),$,Z)}let J=oY($);return y(Z),J}function S0($,Z){if(Z=Z0(Z),K0($)){let j=M0($)||{};switch(j.branding){case I$:return y(Z),j;case N$:return y(Z),j0(j);case L1:return y(Z),PJ(Y0,j)}return VJ(r6(F3($)),$,Z)}let J=P6($);return y(Z),J}function B5($,Z,J){return l0(Z.call($,t(j0(J,$))))}function z1($){return(Z)=>typeof Z=="string"?KZ(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===c6?Z:w9($)}return eY($)}function Q3($){if($!==void 0){if(K0($)){let Z=M0($)||{};switch(Z.branding){case L1:case I$:return Z;case N$:return j0(Z)}let J=F3($);return{...R9(l,u,r6(J),$),calendar:J}}return sY($)}}function F3($){return F5($)||w}function F5($){let{calendar:Z}=$;if(Z!==void 0)return V0(Z)}function V0($){return K0($)?(M0($)||{}).calendar||jU($):((Z)=>J3($9(a(Z))))($)}function BZ($,Z){if(Z=Z0(Z),K0($)){let J=M0($);if(J&&J.branding===L1)return $3(Z),J;let j=F3($);return b9(l,u,r6(j),j,$,Z)}return nY($,Z)}function O5($){return d0((Z)=>(J)=>Z(Y4(J)),$)}function Y4($){return L0($,Y0)}function CK(){let $=l1.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(l1),j=function(W,Y={}){if(!(this instanceof j))return new j(W,Y);V4.set(this,((z,O={})=>{let X=new l1(z,O),G=X.resolvedOptions(),K=G.locale,Q=v0(Object.keys(O),G),U=R0(PK),B=(...F)=>{let D,T=F.map((M,_)=>{let I=M0(M),H=(I||{}).branding;if(_&&D&&D!==H)throw TypeError(b7);return D=H,I});return D?U(D)(K,Q,...T):[X,...F]};return B.u=X,B})(W,Y))};for(let W in Z){let Y=Z[W],z=W.startsWith("format")&&_K(W);typeof Y.value=="function"?Y.value=W==="constructor"?j:z||LK(W):z&&(Y.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(j,J),j}function _K($){return function(...Z){let J=V4.get(this),[j,...W]=J(...Z);return j[$](...W)}}function LK($){return function(...Z){return V4.get(this).u[$](...Z)}}function PK($){let Z=HK[$];if(!Z)throw TypeError(R7($));return N1(Z,R0(SJ))}var HK={Instant:eJ,PlainDateTime:$4,PlainDate:Z4,PlainTime:J4,PlainYearMonth:j4,PlainMonthDay:W4},SK=N1(eJ),xK=N1(W5),fK=N1($4),AK=N1(Z4),EK=N1(J4),RK=N1(j4),bK=N1(W4),G4={era:oW,eraYear:K2,year:eZ,month:l0,daysInMonth:l0,daysInYear:l0,inLeapYear:u7,monthsInYear:l0},n6={monthCode:a},K4={day:l0},D5={dayOfWeek:l0,dayOfYear:l0,weekOfYear:aW,yearOfWeek:K2,daysInWeek:l0},T5=Object.assign({},G4,n6,K4,D5),s6=new WeakMap,M0=s6.get.bind(s6),X5=s6.set.bind(s6),vK={...l6(G4,[XZ]),...l6(D5,[]),...l6(n6,[XZ,GZ]),...l6(K4,[GZ])},U4=O4(T5),kK=O4({...G4,...n6}),wK=O4({...n6,...K4}),D3={calendarId:($)=>B0($.calendar)},qK=d0(($,Z)=>function(J){let{i:j}=this;return $(j[Z](t(j0(J,j))))},T5),yK=rZ(($)=>(Z)=>Z[$],p.concat("sign")),Q4=rZ(($,Z)=>(J)=>J[o0[Z]],_1),V5={epochSeconds:MY,epochMilliseconds:B6,epochMicroseconds:IY,epochNanoseconds:NY},T3=v(O2,new Set(["branding"])),[gK,FZ,mK]=Y1(GZ,v(o9,V0),{...D3,...wK},{getISOFields:T3,getCalendar:B3,with($,Z,J){return FZ(p9($U,$,this,DZ(Z),J))},equals:($,Z)=>D9($,Y5(Z)),toPlainDate($,Z){return t(G7(V3,$,this,Z))},toLocaleString($,Z,J){let[j,W]=bK(Z,J,$);return j.format(W)},toString:w2,toJSON:($)=>w2($),valueOf:a1},{from:($,Z)=>FZ(Y5($,Z))}),M5={getOffsetNanosecondsFor:Q5,getPossibleInstantsFor($,Z,J){let j=[...Z.call($,T0(J0(J,w)))].map((Y)=>hK(Y).epochNanoseconds),W=j.length;return W>1&&(j.sort(C0),h2(g0(y0(j[0],j[W-1])))),j}},z4={getOffsetNanosecondsFor:Q5},[pK,H0,hK]=Y1(h6,d9,V5,{add:($,Z)=>H0(c2(0,$,r(Z))),subtract:($,Z)=>H0(c2(1,$,r(Z))),until:($,Z,J)=>d(GJ(0,$,j1(Z),J)),since:($,Z,J)=>d(GJ(1,$,j1(Z),J)),round:($,Z)=>H0(LY($,Z)),equals:($,Z)=>K9($,j1(Z)),toZonedDateTime($,Z){let J=M1(Z);return W0(_J($,l(J.timeZone),V0(J.calendar)))},toZonedDateTimeISO:($,Z)=>W0(_J($,l(Z))),toLocaleString($,Z,J){let[j,W]=SK(Z,J,$);return j.format(W)},toString:($,Z)=>E2(l,Y0,$,Z),toJSON:($)=>E2(l,Y0,$),valueOf:a1},{from:($)=>H0(j1($)),fromEpochSeconds:($)=>H0(Q7($)),fromEpochMilliseconds:($)=>H0(B7($)),fromEpochMicroseconds:($)=>H0(F7($)),fromEpochNanoseconds:($)=>H0(D7($)),compare:($,Z)=>zJ(j1($),j1(Z))}),[o6,FD]=Y1("TimeZone",($)=>{let Z=X9($);return{branding:"TimeZone",id:Z,o:u6(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(s1(Z)).map((J)=>H0(U0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(j1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=j1(Z).epochNanoseconds,j=i6(this,z4).getOffsetNanosecondsFor(J);return Q$(j)},getPlainDateTimeFor($,Z,J=w){let j=j1(Z).epochNanoseconds,W=i6(this,z4).getOffsetNanosecondsFor(j);return T0(J0(h1(j,W),V0(J)))},getInstantFor($,Z,J){let j=s1(Z),W=N2(J),Y=i6(this);return H0(U0(b0(Y,j,W)))},getNextTransition:({o:$},Z)=>z5(1,$,Z),getPreviousTransition:({o:$},Z)=>z5(-1,$,Z),equals($,Z){return!!f6(this,l(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=l($);return typeof Z=="string"?new o6(Z):Z}}),cK=U5(Object.keys(M5)),[uK,n1]=Y1(p6,a9,Q4,{getISOFields:T3,with($,Z,J){return n1(h9(this,DZ(Z),J))},add:($,Z)=>n1(s2(0,$,r(Z))),subtract:($,Z)=>n1(s2(1,$,r(Z))),until:($,Z,J)=>d(FJ(0,$,i1(Z),J)),since:($,Z,J)=>d(FJ(1,$,i1(Z),J)),round:($,Z)=>n1(SY($,Z)),equals:($,Z)=>T9($,i1(Z)),toZonedDateTime:($,Z)=>W0(K7(l,S0,u,$,Z)),toPlainDateTime:($,Z)=>T0(U7($,S0(Z))),toLocaleString($,Z,J){let[j,W]=EK(Z,J,$);return j.format(W)},toString:q2,toJSON:($)=>q2($),valueOf:a1},{from:($,Z)=>n1(i1($,Z)),compare:($,Z)=>x6(i1($),i1(Z))}),[dK,o1,lK]=Y1(XZ,v(n9,V0),{...D3,...kK},{getISOFields:T3,getCalendar:B3,with($,Z,J){return o1(m9(eK,$,this,DZ(Z),J))},add:($,Z,J)=>o1(i2(G5,0,$,r(Z),J)),subtract:($,Z,J)=>o1(i2(G5,1,$,r(Z),J)),until:($,Z,J)=>d(BJ(K5,0,$,QZ(Z),J)),since:($,Z,J)=>d(BJ(K5,1,$,QZ(Z),J)),equals:($,Z)=>F9($,QZ(Z)),toPlainDate($,Z){return t(X7(V3,$,this,Z))},toLocaleString($,Z,J){let[j,W]=RK(Z,J,$);return j.format(W)},toString:k2,toJSON:($)=>k2($),valueOf:a1},{from:($,Z)=>o1(QZ($,Z)),compare:($,Z)=>D$(QZ($),QZ(Z))}),[iK,T0]=Y1(N$,v(i9,V0),{...D3,...U4,...Q4},{getISOFields:T3,getCalendar:B3,with($,Z,J){return T0(y9(V3,$,this,DZ(Z),J))},withCalendar:($,Z)=>T0(b6($,V0(Z))),withPlainDate:($,Z)=>T0(I7($,S0(Z))),withPlainTime:($,Z)=>T0(M7($,X4(Z))),add:($,Z,J)=>T0(d2(_$,0,$,r(Z),J)),subtract:($,Z,J)=>T0(d2(_$,1,$,r(Z),J)),until:($,Z,J)=>d(UJ(W1,0,$,s1(Z),J)),since:($,Z,J)=>d(UJ(W1,1,$,s1(Z),J)),round:($,Z)=>T0(HY($,Z)),equals:($,Z)=>Q9($,s1(Z)),toZonedDateTime:($,Z,J)=>W0(Z7(u,$,l(Z),J)),toPlainDate:($)=>t(j0($)),toPlainTime:($)=>n1(s0($)),toPlainYearMonth($){return o1(J7(a6,$,this))},toPlainMonthDay($){return FZ(j7(t6,$,this))},toLocaleString($,Z,J){let[j,W]=fK(Z,J,$);return j.format(W)},toString:b2,toJSON:($)=>b2($),valueOf:a1},{from:($,Z)=>T0(s1($,Z)),compare:($,Z)=>XJ(s1($),s1(Z))}),[sK,t,I5]=Y1(I$,v(s9,V0),{...D3,...U4},{getISOFields:T3,getCalendar:B3,with($,Z,J){return t(g9(V3,$,this,DZ(Z),J))},withCalendar:($,Z)=>t(b6($,V0(Z))),add:($,Z,J)=>t(l2(_$,0,$,r(Z),J)),subtract:($,Z,J)=>t(l2(_$,1,$,r(Z),J)),until:($,Z,J)=>d(QJ(W1,0,$,S0(Z),J)),since:($,Z,J)=>d(QJ(W1,1,$,S0(Z),J)),equals:($,Z)=>B9($,S0(Z)),toZonedDateTime($,Z){let J=!K0(Z)||Z instanceof o6?{timeZone:Z}:Z;return W0(W7(l,i1,u,$,J))},toPlainDateTime:($,Z)=>T0(Y7($,X4(Z))),toPlainYearMonth($){return o1(z7(a6,$,this))},toPlainMonthDay($){return FZ(O7(t6,$,this))},toLocaleString($,Z,J){let[j,W]=AK(Z,J,$);return j.format(W)},toString:v2,toJSON:($)=>v2($),valueOf:a1},{from:($,Z)=>t(S0($,Z)),compare:($,Z)=>D$(S0($),S0(Z))}),B4={fields($,Z,J){return[...Z.call($,J)]}},N5=Object.assign({dateFromFields($,Z,J,j){return I5(Z.call($,Object.assign(Object.create(null),J),j))}},B4),C5=Object.assign({yearMonthFromFields($,Z,J,j){return lK(Z.call($,Object.assign(Object.create(null),J),j))}},B4),_5=Object.assign({monthDayFromFields($,Z,J,j){return mK(Z.call($,Object.assign(Object.create(null),J),j))}},B4),F4={mergeFields($,Z,J,j){return M1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),j)))}},nK=Object.assign({},N5,F4),oK=Object.assign({},C5,F4),aK=Object.assign({},_5,F4),D4={dateAdd($,Z,J,j,W){return I5(Z.call($,t(j0(J,$)),d(i(j)),W))}},L5=Object.assign({},D4,{dateUntil($,Z,J,j,W,Y){return JU(Z.call($,t(j0(J,$)),t(j0(j,$)),Object.assign(Object.create(null),Y,{largestUnit:O3[W]})))}}),rK=Object.assign({},D4,{day:B5}),tK=Object.assign({},L5,{day:B5}),a6=z1(C5),r6=z1(N5),t6=z1(_5),eK=z1(oK),V3=z1(nK),$U=z1(aK),_$=z1(D4),W1=z1(L5),G5=z1(rK),K5=z1(tK),[ZU,d,JU]=Y1(c6,r9,{...yK,blank:uY},{with:($,Z)=>d(c9($,Z)),negated:($)=>d(_6($)),abs:($)=>d(cY($)),add:($,Z,J)=>d(t2(Q3,W1,u,0,$,r(Z),J)),subtract:($,Z,J)=>d(t2(Q3,W1,u,1,$,r(Z),J)),round:($,Z)=>d(hY(Q3,W1,u,$,Z)),total:($,Z)=>_Y(Q3,W1,u,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):V6($)},toString:V6,toJSON:($)=>V6($),valueOf:a1},{from:($)=>d(r($)),compare:($,Z,J)=>G9(Q3,_$,u,r($),r(Z),J)}),P5={toString:($)=>$.id,toJSON:($)=>$.id,...vK,dateAdd:({id:$,o:Z},J,j,W)=>t(j0(Z.dateAdd(S0(J),r(j),W),$)),dateUntil:({o:$},Z,J,j)=>d(i($.dateUntil(S0(Z),S0(J),BY(j)))),dateFromFields:({id:$,o:Z},J,j)=>t(VJ(Z,J,j,nW($))),yearMonthFromFields:({id:$,o:Z},J,j)=>o1(MJ(Z,J,j,iW($))),monthDayFromFields:({id:$,o:Z},J,j)=>FZ(IJ(Z,0,J,j,sW($))),fields({o:$},Z){let J=new Set(n0),j=[];for(let W of Z){if(a(W),!J.has(W))throw RangeError(fJ(W));J.delete(W),j.push(W)}return $.fields(j)},mergeFields:({o:$},Z,J)=>$.mergeFields(X2(U2(Z)),X2(U2(J)))},[T4]=Y1("Calendar",($)=>{let Z=P9($);return{branding:"Calendar",id:Z,o:KZ(Z)}},{id:($)=>$.id},P5,{from($){let Z=V0($);return typeof Z=="string"?new T4(Z):Z}}),jU=U5(Object.keys(P5).slice(4)),[WU,W0]=Y1(L1,v(l9,V0,l),{...V5,...D3,...O5(U4),...O5(Q4),offset:($)=>Q$(Y4($).offsetNanoseconds),offsetNanoseconds:($)=>Y4($).offsetNanoseconds,timeZoneId:($)=>B0($.timeZone),hoursInDay:($)=>xY(u,$)},{getISOFields:($)=>mY(Y0,$),getCalendar:B3,getTimeZone:({timeZone:$})=>typeof $=="string"?new o6($):$,with($,Z,J){return W0(q9(V3,u,$,this,DZ(Z),J))},withCalendar:($,Z)=>W0(b6($,V0(Z))),withTimeZone:($,Z)=>W0(N7($,l(Z))),withPlainDate:($,Z)=>W0(V7(u,$,S0(Z))),withPlainTime:($,Z)=>W0(T7(u,$,X4(Z))),add:($,Z,J)=>W0(u2(_$,u,0,$,r(Z),J)),subtract:($,Z,J)=>W0(u2(_$,u,1,$,r(Z),J)),until:($,Z,J)=>d(i(KJ(W1,u,0,$,BZ(Z),J))),since:($,Z,J)=>d(i(KJ(W1,u,1,$,BZ(Z),J))),round:($,Z)=>W0(PY(u,$,Z)),startOfDay:($)=>W0(fY(u,$)),equals:($,Z)=>U9($,BZ(Z)),toInstant:($)=>H0(t9($)),toPlainDateTime:($)=>T0(LJ(Y0,$)),toPlainDate:($)=>t(PJ(Y0,$)),toPlainTime:($)=>n1(HJ(Y0,$)),toPlainYearMonth($){return o1(e9(a6,$,this))},toPlainMonthDay($){return FZ($7(t6,$,this))},toLocaleString($,Z,J={}){let[j,W]=xK(Z,J,$);return j.format(W)},toString:($,Z)=>R2(Y0,$,Z),toJSON:($)=>R2(Y0,$),valueOf:a1},{from:($,Z)=>W0(BZ($,Z)),compare:($,Z)=>OJ(BZ($),BZ(Z))}),YU=Object.defineProperties({},{...Z6("Temporal.Now"),...G$({timeZoneId:()=>C1(),instant:()=>H0(U0(W3())),zonedDateTime:($,Z=C1())=>W0(D0(W3(),l(Z),V0($))),zonedDateTimeISO:($=C1())=>W0(D0(W3(),l($),w)),plainDateTime:($,Z=C1())=>T0(J0(zZ(Y0(l(Z))),V0($))),plainDateTimeISO:($=C1())=>T0(J0(zZ(Y0(l($))),w)),plainDate:($,Z=C1())=>t(j0(zZ(Y0(l(Z))),V0($))),plainDateISO:($=C1())=>t(j0(zZ(Y0(l($))),w)),plainTimeISO:($=C1())=>n1(s0(zZ(Y0(l($)))))})}),TZ=Object.defineProperties({},{...Z6("Temporal"),...G$({PlainYearMonth:dK,PlainMonthDay:gK,PlainDate:sK,PlainTime:uK,PlainDateTime:iK,ZonedDateTime:WU,Instant:pK,Calendar:T4,TimeZone:o6,Duration:ZU,Now:YU})}),zU=CK(),V4=new WeakMap,OU=Object.defineProperties(Object.create(Intl),G$({DateTimeFormat:zU}));var M4=new WeakMap;function GU($){let Z=M4.get($);if(!Z)Z=$(XU(32).toString("hex")),M4.set($,Z),Z.catch(()=>M4.delete($));return Z}async function I4($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await GU($.hashPassword))}catch{}return!1}async function L$($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:j,...W}=J;await $.onAuthenticated({...Z,user:W})}class _4 extends Error{}function N4($){return typeof $==="string"&&$!==""?$:null}function H5($){return cZ($)}var KU=256;function S5($){return typeof $==="string"&&$!==""&&$.length<=KU?$:null}var C4="intended_url";class L4 extends A{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class x5 extends A{schema={email:{required:"Email is required",email:"Invalid email"}}}class f5 extends A{schema={password:{required:"Password is required",password:"Invalid password"}}}class s extends w8{async me(){let $=await P$.user();if(!$)throw new q8;return $}async verifyEmail($=new A){let Z=await $.input(),{userProvider:J}=N(E),j=N4(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=N4($.search.get("token")),W=null;try{W=cZ(decodeURIComponent($.search.get("email")??""))}catch{}if(await l$("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 L$(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=cZ(j),z=S5(W);if(await l$("verify",Y,$,Z.config.emailCode.verifyLimit),!Y||!z)throw new h({pin:["Invalid pin"]});let O=await Z.verifyOneTimeCode(Y,z);if(O.status==="too_many_attempts")throw new h({pin:["Too many attempts"]});if(O.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 L$(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 L$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async signInV2($=new L4){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),O=typeof j==="string"&&await I4(Y.config,j,z?.password);if(!z||!O)throw new h({invalid_credentials:["Invalid credentials"]});let X=await Y.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",X.token,N(E).accessTokenCookieOptions($,X.expiresAt)),await Y.config.onSignIn(z,$.search.toJSON()),await L$(Y.config,{session:X,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...K}=z;return K}async signIn($=new L4){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),O=typeof j==="string"&&await I4(Y.config,j,z?.password);if(!z||!O)throw new h({invalid_credentials:["Invalid credentials"]});let X=await Y.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",X.token,N(E).accessTokenCookieOptions($,X.expiresAt)),await Y.config.onSignIn(z,$.search.toJSON()),await L$(Y.config,{session:X,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:O,invitationId:X}=W.toJSON(),G=H5(Y);if(!G)throw new h({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new h({password:["Invalid password"]});if(X!=null&&typeof X!=="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),B;if(X)B=await Z.findInvitation(X,G);let F,D="";if(B)F=await Z.transaction(async()=>{await Z.deleteInvitationById(X);let T=await Z.createUser({email:G,name:O,password:Q,emailVerifiedAt:new Date,locale:U});return await Z.createAccount({organizationId:B.organizationId,userId:T.id,organizationRole:B.role}),await J.onUserCreated(T),T});else D=await J.generateEmailVerificationToken(G),F=await Z.transaction(async()=>{let T=await Z.createUser({email:G,name:O,password:Q,verificationToken:D,locale:U});return await J.onUserCreated(T),T});return await J.onSignUp(F,D,j.search.toJSON()),F}async signOut($=new A){let Z=b8($),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 x5){let Z=await $.input(),J=H5(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 f5){let{userProvider:Z,config:J}=N(E),j=await $.input(),{password:W,token:Y}=j.toJSON(),z=N4(Y),O=z?await Z.findPasswordResetToken({token:z}):null;if(!O)throw new h({token:["Invalid token"]});if(TZ.Instant.from(O.createdAt.toISOString()).add({hours:24}).until(TZ.Now.instant()).sign>=0)throw new h({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let G=await Z.findUserByEmailAddress(O.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 P$.user(),W=await $.input(),{oldPassword:Y,newPassword:z}=W.toJSON();if(typeof z!=="string")throw new h({newPassword:["Invalid password"]});let O=await Z.findUserByEmailAddress(j.email,J.verifyEmail);if(!(typeof Y==="string"&&await I4(J,Y,O?.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=vZ($.search.get(w$),"");if(j)$.ctx().setCookie(C4,encodeURIComponent(j),{httpOnly:!0,sameSite:"Lax",secure:cj($.rawRequest),maxAge:600});return{destination:await J.getRedirectUrl($)}}async oauthCallback($=new A){let{provider:Z}=$.params,J=N(E),{userProvider:j,config:W}=J,Y=W.oauthProviders[Z],{email:z,name:O,username:X,providerId:G}=await Y.onCallback($),K=G?await j.findUserBySocialAccount(Z,G):null,Q="signin";if(!K){if(!z)return console.error("Authentication error: No email returned from OAuth provider callback"),{session:null};let D=N(o).detectLocale($);try{let T=await this.linkOAuthAccount({provider:Z,providerId:G,email:z,name:O,username:X,locale:D});if(T)K=T.user,Q=T.action}catch(T){let M=G?await j.findUserBySocialAccount(Z,G):null;if(!M)throw T;K=M}if(!K)return{session:null}}let U=await J.createOrUpdateSessionV2({email:K.email,id:K.id});if($.ctx().setCookie("access_token",U.token,N(E).accessTokenCookieOptions($,U.expiresAt)),Q==="signup")await W.onSignUp(K,"",$.search.toJSON());else await W.onSignIn(K,$.search.toJSON());await L$(J.config,{session:U,user:K,isNewUser:Q==="signup",method:"oauth",req:$});let B=$.cookies.get(C4),F=W.redirectPath;if(B){try{F=vZ(decodeURIComponent(B),F)}catch{}$.ctx().setCookie(C4,"",{maxAge:-1})}return{session:U,redirectTo:F}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:j,name:W,username:Y,locale:z}=$,{userProvider:O,config:X}=N(E),G=(U)=>({provider:Z,userId:U,email:j,username:Y,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),K=await O.findUserByEmailAddress(j,!1);if(K){if(!J)return{user:K,action:"signin"};let U=await O.findSocialAccounts(K.id,Z);if(U.some((F)=>F.providerId===J))return{user:K,action:"signin"};if(U.some((F)=>F.providerId))return console.error(`Authentication error: user ${K.id} is already linked to a different ${Z} account`),null;let B=U[0];if(B){if(!await O.claimSocialAccount(B,J))throw Error(`${Z} account link changed concurrently`)}else await O.createSocialAccount(G(K.id));return{user:K,action:"signin"}}return{user:await O.transaction(async()=>{let U=await O.createUser({email:j,name:W,locale:z,emailVerifiedAt:new Date});if(J)await O.createSocialAccount(G(U.id));return await X.onUserCreated(U),U}),action:"signup"}}async createMagicLinkToken($=new A){let Z=await $.input(),J=cZ(Z.get("email")),j=N(E),{uniformMagicLinkResponse:W,requestLimit:Y}=j.config.emailCode;if(await l$("request",J,$,Y),!J)return{email:null};let{user:z,pin:O,token:X}=await j.createMagicLinkToken(J);if(z)return await j.config.onMagicLinkCreated(z,{email:J,pin:O,token:X}),{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=c8(j.get("email"));if(await l$("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:O}=await Z.issueOneTimeCode(W,J.length);await J.send({email:W,code:z,token:O,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:O}=W.toJSON(),X=c8(Y),G=S5(z);if(await l$("verify",X,$,j.emailCode.verifyLimit),!X||!G)throw new h({code:["invalid_code"]});let K=await Z.verifyOneTimeCode(X,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(X,!1),B=!1;if(U){if(!await J.claimMagicLinkToken(Q.id))throw new h({code:["invalid_code"]});await J.verifyUser(X)}else if(j.emailCode.createUser){let D=N(o).detectLocale($);try{U=await J.transaction(async()=>{if(!await J.claimMagicLinkToken(Q.id))throw new _4;let T=await J.createUser({email:X,name:typeof O==="string"?O.trim():"",emailVerifiedAt:new Date,locale:D});return await j.onUserCreated(T),T}),B=!0}catch(T){if(T instanceof _4)throw new h({code:["invalid_code"]});throw T}}else throw await J.claimMagicLinkToken(Q.id),new h({code:["invalid_code"]});let F=await Z.createOrUpdateSessionV2({email:X,id:U.id});return $.ctx().setCookie("access_token",F.token,N(E).accessTokenCookieOptions($,F.expiresAt)),await j.onSignIn(F,$.search.toJSON()),await L$(Z.config,{session:F,isNewUser:B,method:"email-code",req:$}),{session:F,isNewUser:B}}}class A5 extends E1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[s,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[s,"oauthCallback"])}}class P4 extends E1{middlewares=["cache:private"];routes={"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[s,"signInWithMagicLink"]),"/oauth":A5}}class H4 extends x0{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 S4 extends x0{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 x4{}class f4 extends x4{async resize($,Z){let{height:J,width:j,quality:W,fit:Y}=Z;return await(await e6("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 sD($){return $}function E5(){return{driver:new f4}}class A4 extends x0{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 X=`${J.startsWith("http")?"":`http://localhost:${process.env.PORT||5173}`}${J}`,G=await fetch(X);if(!G.ok)return new Response(JSON.stringify({error:"Image not found",info:X}),{headers:{"Content-Type":"application/json"},status:404});let K=Buffer.from(await G.arrayBuffer()),Q=await N(R5).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 R5{static token="image";driver;constructor($={}){this.driver=$.driver??E5().driver}resize($,Z){return this.driver.resize($,Z)}}class E4 extends x0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(N(b5).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function UU($){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 QU={"body-limit":k3};class VZ{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:bZ($.bodyLimit)}get aliases(){return{...QU,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!Hj($))E3($,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 UU($).entries())if(typeof W==="string"){let z=J[W];if(z){let O=new z(Z);j.push({run:()=>O.run.call(O,...Y),runsOnRefusal:v5(z)})}}else if(f3(W)){let z=new W(Z);j.push({run:z.run.bind(z),runsOnRefusal:v5(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 BU(j.slice(Y+1)),z}return W})()}}function v5($){return $?.runsOnRefusal===!0}async function BU($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}function GT($){return $}function k5(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function w5(){return{partialRendering:!0,onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function FU($){return"run"in $}function DU($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function TU($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function VU($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function MU($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function q5($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function R4($,Z="",J=[]){let j={};function W(Y,z,O,X,G){let K=Y==="/"?"":Y,Q=Z==="/"?"":Z,U=(`${Q}${K}`===""?"/":`${Q}${K}`).replaceAll("//","/");if(!j[U])j[U]={};j[U][z.toUpperCase()]={exec:O,middleware:[...J,...X],...G?{source:G}:{}},j[U].OPTIONS={exec:()=>{let F=new A().ctx().headers;return new Response(null,{headers:F,status:204})},middleware:[]}}for(let[Y,z]of Object.entries($)){if(MU(z)){let O=z;for(let X of["GET","POST","PUT","DELETE"])W(Y,X,O.run.bind(O),O.middlewares);continue}if(FU(z)){let O=z,X=O.method,G=O.middlewares,K=O.run.bind(O);if(W(Y,X,K,G,O.source),q5(z))W(Y,"HEAD",K,G,O.source)}if(DU(z))for(let[O,X]of Object.entries(z)){let G=X,K=G.middlewares,Q=G.run.bind(G);if(W(Y,O,Q,K,G.source),O==="get"&&q5(G))W(Y,"HEAD",Q,K,G.source)}if(VU(z)){let O=new z,X=R4(O.routes,`${Z}${Y}`,O.middlewares);for(let[G,K]of Object.entries(X))j[G.replaceAll("//","/")]=K}if(TU(z)){let{first:O,second:X}=z;for(let[G,K]of Object.entries(O)){let Q=K.middlewares,U=K.run.bind(K),[B,...F]=Y.split("/").reverse();if(!B.startsWith(":"))throw Error("Resource route must end with a dynamic segment");W(F.reverse().join("/"),G,U,Q,K.source)}for(let[G,K]of Object.entries(X)){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 O=Y.split("/").length+Y.split(":").length,X=z.split("/").length+z.split(":").length;return O-X}))}function $8($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function b4($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function v4($){let Z=$8($);return Z.length>1?Z.replace(/\/$/,""):Z}function y5($,Z){return Z.map((J)=>({...J,path:v4(b4($,J.path))}))}function Z8($){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=Z8(Y.routes);for(let[O,{exec:X,middleware:G,segments:K,features:Q,static:U}]of Object.entries(z)){let B=b4(J,O),F=(D)=>W.run.call(W,D,J);Z[$8(B)]={exec:[F,...X],middleware:[...W.middlewares,...G],features:[...W.featureGates,...Q],viewPath:W.viewPath,segments:[{path:v4(J),viewPath:W.viewPath,...W.alwaysRuns?{alwaysRun:!0}:{}},...y5(J,K)],...U?{static:U}:{}}}}else{let Y=(z)=>W.run.call(W,z,J);Z[$8(J)]={exec:[Y],middleware:W.middlewares,features:W.featureGates,viewPath:W.viewPath,segments:[{path:v4(J),viewPath:W.viewPath}],..."staticOptions"in W&&W.staticOptions?{static:W.staticOptions}:{}}}}else{let W=new j,Y=Z8(W.routes);for(let[z,{exec:O,middleware:X,viewPath:G,segments:K,features:Q,static:U}]of Object.entries(Y)){let B=b4(J,z);Z[$8(B)]={exec:O,middleware:[...W.middlewares,...X],features:[...W.featureGates,...Q],viewPath:G,segments:y5(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 IU=Object.defineProperty,S=($,Z)=>IU($,"name",{value:Z,configurable:!0}),NZ=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"}};S(NZ,"Part");var NU=/[$_\p{ID_Start}]/u,CU=/[$_\u200C\u200D\p{ID_Continue}]/u,w4=".*";function g5($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}S(g5,"isASCII");function g4($,Z=!1){let J=[],j=0;for(;j<$.length;){let W=$[j],Y=S(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="",O=j+1;for(;O<$.length;){let X=$.substr(O,1);if(O===j+1&&NU.test(X)||O!==j+1&&CU.test(X)){z+=$[O++];continue}break}if(!z){Y(`Missing parameter name at ${j}`);continue}J.push({type:"NAME",index:j,value:z}),j=O;continue}if(W==="("){let z=1,O="",X=j+1,G=!1;if($[X]==="?"){Y(`Pattern cannot start with "?" at ${X}`);continue}for(;X<$.length;){if(!g5($[X],!1)){Y(`Invalid character '${$[X]}' at ${X}.`),G=!0;break}if($[X]==="\\"){O+=$[X++]+$[X++];continue}if($[X]===")"){if(z--,z===0){X++;break}}else if($[X]==="("&&(z++,$[X+1]!=="?")){Y(`Capturing groups are not allowed at ${X}`),G=!0;break}O+=$[X++]}if(G)continue;if(z){Y(`Unbalanced pattern at ${j}`);continue}if(!O){Y(`Missing pattern at ${j}`);continue}J.push({type:"REGEX",index:j,value:O}),j=X;continue}J.push({type:"CHAR",index:j,value:$[j++]})}return J.push({type:"END",index:j,value:""}),J}S(g4,"lexer");function m4($,Z={}){let J=g4($);Z.delimiter??="/#?",Z.prefixes??="./";let j=`[^${k0(Z.delimiter)}]+?`,W=[],Y=0,z=0,O="",X=new Set,G=S((I)=>{if(z<J.length&&J[z].type===I)return J[z++].value},"tryConsume"),K=S(()=>G("OTHER_MODIFIER")??G("ASTERISK"),"tryConsumeModifier"),Q=S((I)=>{let H=G(I);if(H!==void 0)return H;let{type:P,index:L}=J[z];throw TypeError(`Unexpected ${P} at ${L}, expected ${I}`)},"mustConsume"),U=S(()=>{let I="",H;for(;H=G("CHAR")??G("ESCAPED_CHAR");)I+=H;return I},"consumeText"),B=S((I)=>I,"DefaultEncodePart"),F=Z.encodePart||B,D="",T=S((I)=>{D+=I},"appendToPendingFixedValue"),M=S(()=>{D.length&&(W.push(new NZ(3,"","",F(D),"",3)),D="")},"maybeAddPartFromPendingFixedValue"),_=S((I,H,P,L,V)=>{let C=3;switch(V){case"?":C=1;break;case"*":C=0;break;case"+":C=2;break}if(!H&&!P&&C===3){T(I);return}if(M(),!H&&!P){if(!I)return;W.push(new NZ(3,"","",F(I),"",C));return}let x;P?P==="*"?x=w4:x=P:x=j;let b=2;x===j?(b=1,x=""):x===w4&&(b=0,x="");let g;if(H?g=H:P&&(g=Y++),X.has(g))throw TypeError(`Duplicate name '${g}'.`);X.add(g),W.push(new NZ(b,g,F(I),x,F(L),C))},"addPart");for(;z<J.length;){let I=G("CHAR"),H=G("NAME"),P=G("REGEX");if(!H&&!P&&(P=G("ASTERISK")),H||P){let V=I??"";Z.prefixes.indexOf(V)===-1&&(T(V),V=""),M();let C=K();_(V,H,P,"",C);continue}let L=I??G("ESCAPED_CHAR");if(L){T(L);continue}if(G("OPEN")){let V=U(),C=G("NAME"),x=G("REGEX");!C&&!x&&(x=G("ASTERISK"));let b=U();Q("CLOSE");let g=K();_(V,C,x,b,g);continue}M(),Q("END")}return W}S(m4,"parse");function k0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}S(k0,"escapeString");function q4($){return $&&$.ignoreCase?"ui":"u"}S(q4,"flags");function m5($,Z,J){return p4(m4($,J),Z,J)}S(m5,"stringToRegexp");function H$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}S(H$,"modifierToString");function p4($,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 O of $){if(O.type===3){O.modifier===3?j+=k0(O.value):j+=`(?:${k0(O.value)})${H$(O.modifier)}`;continue}Z&&Z.push(O.name);let X=`[^${k0(J.delimiter)}]+?`,G=O.value;if(O.type===1?G=X:O.type===0&&(G=w4),!O.prefix.length&&!O.suffix.length){O.modifier===3||O.modifier===1?j+=`(${G})${H$(O.modifier)}`:j+=`((?:${G})${H$(O.modifier)})`;continue}if(O.modifier===3||O.modifier===1){j+=`(?:${k0(O.prefix)}(${G})${k0(O.suffix)})`,j+=H$(O.modifier);continue}j+=`(?:${k0(O.prefix)}`,j+=`((?:${G})(?:`,j+=k0(O.suffix),j+=k0(O.prefix),j+=`(?:${G}))*)${k0(O.suffix)})`,O.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,q4(J));J.strict||(j+=`(?:${Y}(?=${W}))?`);let z=!1;if($.length){let O=$[$.length-1];O.type===3&&O.modifier===3&&(z=J.delimiter.indexOf(O)>-1)}return z||(j+=`(?=${Y}|${W})`),new RegExp(j,q4(J))}S(p4,"partsToRegexp");var t1={delimiter:"",prefixes:"",sensitive:!0,strict:!0},_U={delimiter:".",prefixes:"",sensitive:!0,strict:!0},LU={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function p5($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}S(p5,"isAbsolutePathname");function h4($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}S(h4,"maybeStripPrefix");function h5($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}S(h5,"maybeStripSuffix");function c4($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}S(c4,"treatAsIPv6Hostname");var c5=["ftp","file","http","https","ws","wss"];function u4($){if(!$)return!0;for(let Z of c5)if($.test(Z))return!0;return!1}S(u4,"isSpecialScheme");function u5($,Z){if($=h4($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}S(u5,"canonicalizeHash");function d5($,Z){if($=h4($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}S(d5,"canonicalizeSearch");function l5($,Z){return Z||$===""?$:c4($)?i4($):l4($)}S(l5,"canonicalizeHostname");function i5($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}S(i5,"canonicalizePassword");function s5($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}S(s5,"canonicalizeUsername");function n5($,Z,J){if(J||$==="")return $;if(Z&&!c5.includes(Z))return new URL(`${Z}:${$}`).pathname;let j=$[0]=="/";return $=new URL(j?$:"/-"+$,"https://example.com").pathname,j||($=$.substring(2,$.length)),$}S(n5,"canonicalizePathname");function o5($,Z,J){return d4(Z)===$&&($=""),J||$===""?$:s4($)}S(o5,"canonicalizePort");function a5($,Z){return $=h5($,":"),Z||$===""?$:J8($)}S(a5,"canonicalizeProtocol");function d4($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}S(d4,"defaultPortForProtocol");function J8($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}S(J8,"protocolEncodeCallback");function r5($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}S(r5,"usernameEncodeCallback");function t5($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}S(t5,"passwordEncodeCallback");function l4($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}S(l4,"hostnameEncodeCallback");function i4($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}S(i4,"ipv6HostnameEncodeCallback");function s4($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}S(s4,"portEncodeCallback");function e5($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}S(e5,"standardURLPathnameEncodeCallback");function $z($){return $===""?$:new URL(`data:${$}`).pathname}S($z,"pathURLPathnameEncodeCallback");function Zz($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}S(Zz,"searchEncodeCallback");function Jz($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}S(Jz,"hashEncodeCallback");var jz=class{#W;#Z=[];#J={};#$=0;#Y=1;#G=0;#O=0;#B=0;#F=0;#D=!1;constructor($){this.#W=$}get result(){return this.#J}parse(){for(this.#Z=g4(this.#W,!0);this.#$<this.#Z.length;this.#$+=this.#Y){if(this.#Y=1,this.#Z[this.#$].type==="END"){if(this.#O===0){this.#I(),this.#K()?this.#j(9,1):this.#U()?this.#j(8,1):this.#j(7,0);continue}else if(this.#O===2){this.#Q(5);continue}this.#j(10,0);break}if(this.#B>0)if(this.#S())this.#B-=1;else continue;if(this.#H()){this.#B+=1;continue}switch(this.#O){case 0:this.#N()&&this.#Q(1);break;case 1:if(this.#N()){this.#A();let $=7,Z=1;this.#_()?($=2,Z=3):this.#D&&($=2),this.#j($,Z)}break;case 2:this.#V()?this.#Q(3):(this.#M()||this.#U()||this.#K())&&this.#Q(5);break;case 3:this.#L()?this.#j(4,1):this.#V()&&this.#j(5,1);break;case 4:this.#V()&&this.#j(5,1);break;case 5:this.#x()?this.#F+=1:this.#f()&&(this.#F-=1),this.#P()&&!this.#F?this.#j(6,1):this.#M()?this.#j(7,0):this.#U()?this.#j(8,1):this.#K()&&this.#j(9,1);break;case 6:this.#M()?this.#j(7,0):this.#U()?this.#j(8,1):this.#K()&&this.#j(9,1);break;case 7:this.#U()?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.#O){case 0:break;case 1:this.#J.protocol=this.#X();break;case 2:break;case 3:this.#J.username=this.#X();break;case 4:this.#J.password=this.#X();break;case 5:this.#J.hostname=this.#X();break;case 6:this.#J.port=this.#X();break;case 7:this.#J.pathname=this.#X();break;case 8:this.#J.search=this.#X();break;case 9:this.#J.hash=this.#X();break;case 10:break}this.#O!==0&&$!==10&&([1,2,3,4].includes(this.#O)&&[6,7,8,9].includes($)&&(this.#J.hostname??=""),[1,2,3,4,5,6].includes(this.#O)&&[8,9].includes($)&&(this.#J.pathname??=this.#D?"/":""),[1,2,3,4,5,6,7].includes(this.#O)&&$===9&&(this.#J.search??="")),this.#C($,Z)}#C($,Z){this.#O=$,this.#G=this.#$+Z,this.#$+=Z,this.#Y=0}#I(){this.#$=this.#G,this.#Y=0}#Q($){this.#I(),this.#O=$}#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.#$,":")}#_(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#V(){return this.#z(this.#$,"@")}#L(){return this.#z(this.#$,":")}#P(){return this.#z(this.#$,":")}#M(){return this.#z(this.#$,"/")}#U(){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"}#S(){return this.#Z[this.#$].type=="CLOSE"}#x(){return this.#z(this.#$,"[")}#f(){return this.#z(this.#$,"]")}#X(){let $=this.#Z[this.#$],Z=this.#T(this.#G).index;return this.#W.substring(Z,$.index)}#A(){let $={};Object.assign($,t1),$.encodePart=J8;let Z=m5(this.#X(),void 0,$);this.#D=u4(Z)}};S(jz,"Parser");var k4=["protocol","username","password","hostname","port","pathname","search","hash"],r1="*";function y4($,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}}S(y4,"extractValues");function O1($,Z){return Z?IZ($):$}S(O1,"processBaseURLString");function MZ($,Z,J){let j;if(typeof Z.baseURL=="string")try{j=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=O1(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=O1(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=O1(j.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=O1(j.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=O1(j.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=O1(j.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=O1(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=O1(j.hash.substring(1,j.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=a5(Z.protocol,J)),typeof Z.username=="string"&&($.username=s5(Z.username,J)),typeof Z.password=="string"&&($.password=i5(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=l5(Z.hostname,J)),typeof Z.port=="string"&&($.port=o5(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,j&&!p5($.pathname,J)){let W=j.pathname.lastIndexOf("/");W>=0&&($.pathname=O1(j.pathname.substring(0,W+1),J)+$.pathname)}$.pathname=n5($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=d5(Z.search,J)),typeof Z.hash=="string"&&($.hash=u5(Z.hash,J)),$}S(MZ,"applyInit");function IZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}S(IZ,"escapePatternString");function Wz($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}S(Wz,"escapeRegexpString");function Yz($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",j=`[^${Wz(Z.delimiter)}]+?`,W=/[$_\u200C\u200D\p{ID_Continue}]/u,Y="";for(let z=0;z<$.length;++z){let O=$[z];if(O.type===3){if(O.modifier===3){Y+=IZ(O.value);continue}Y+=`{${IZ(O.value)}}${H$(O.modifier)}`;continue}let X=O.hasCustomName(),G=!!O.suffix.length||!!O.prefix.length&&(O.prefix.length!==1||!Z.prefixes.includes(O.prefix)),K=z>0?$[z-1]:null,Q=z<$.length-1?$[z+1]:null;if(!G&&X&&O.type===1&&O.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&&!O.prefix.length&&K&&K.type===3){let U=K.value[K.value.length-1];G=Z.prefixes.includes(U)}G&&(Y+="{"),Y+=IZ(O.prefix),X&&(Y+=`:${O.name}`),O.type===2?Y+=`(${O.value})`:O.type===1?X||(Y+=`(${j})`):O.type===0&&(!X&&(!K||K.type===3||K.modifier!==3||G||O.prefix!=="")?Y+="*":Y+=`(${J})`),O.type===1&&X&&O.suffix.length&&W.test(O.suffix[0])&&(Y+="\\"),Y+=IZ(O.suffix),G&&(Y+="}"),O.modifier!==3&&(Y+=H$(O.modifier))}return Y}S(Yz,"partsToPattern");var n4=class{#W;#Z={};#J={};#$={};#Y={};#G=!1;constructor($={},Z,J){try{let j;if(typeof Z=="string"?j=Z:J=Z,typeof $=="string"){let O=new jz($);if(O.parse(),$=O.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:r1,protocol:r1,username:r1,password:r1,hostname:r1,port:r1,search:r1,hash:r1};this.#W=MZ(Y,$,!0),d4(this.#W.protocol)===this.#W.port&&(this.#W.port="");let z;for(z of k4){if(!(z in this.#W))continue;let O={},X=this.#W[z];switch(this.#J[z]=[],z){case"protocol":Object.assign(O,t1),O.encodePart=J8;break;case"username":Object.assign(O,t1),O.encodePart=r5;break;case"password":Object.assign(O,t1),O.encodePart=t5;break;case"hostname":Object.assign(O,_U),c4(X)?O.encodePart=i4:O.encodePart=l4;break;case"port":Object.assign(O,t1),O.encodePart=s4;break;case"pathname":u4(this.#Z.protocol)?(Object.assign(O,LU,W),O.encodePart=e5):(Object.assign(O,t1,W),O.encodePart=$z);break;case"search":Object.assign(O,t1,W),O.encodePart=Zz;break;case"hash":Object.assign(O,t1,W),O.encodePart=Jz;break}try{this.#Y[z]=m4(X,O),this.#Z[z]=p4(this.#Y[z],this.#J[z],O),this.#$[z]=Yz(this.#Y[z],O),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=MZ(J,$,!1):J=MZ(J,y4($,Z),!1)}catch{return!1}let j;for(j of k4)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=MZ(J,$,!1):J=MZ(J,y4($,Z),!1)}catch{return null}let j={};Z?j.inputs=[$,Z]:j.inputs=[$];let W;for(W of k4){let Y=this.#Z[W].exec(J[W]);if(!Y)return null;let z={};for(let[O,X]of this.#J[W].entries())if(typeof X=="string"||typeof X=="number"){let G=Y[O+1];z[X]=G}j[W]={input:J[W]??"",groups:z}}return j}static compareComponent($,Z,J){let j=S((O,X)=>{for(let G of["type","modifier","prefix","value","suffix"]){if(O[G]<X[G])return-1;if(O[G]===X[G])continue;return 1}return 0},"comparePart"),W=new NZ(3,"","","","",3),Y=new NZ(0,"","","","",3),z=S((O,X)=>{let G=0;for(;G<Math.min(O.length,X.length);++G){let K=j(O[G],X[G]);if(K)return K}return O.length===X.length?0:j(O[G]??W,X[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}};S(n4,"URLPattern");function M3($,Z){for(let[J,j]of Object.entries($)){let W=new n4({pathname:J});if(W.test({pathname:Z}))return{routePath:J,params:W.exec({pathname:Z})?.pathname.groups??{},route:j}}return null}var S$={startIndex:0,carriedViews:[]};function zz($,Z){let J=O0($.path,Z);return J.includes("*")?null:J}function PU($,Z){if(!$)return S$;if($.search!==Z.search)return S$;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=zz(W,$.params),O=zz(Y,Z.params);if(z===null||O===null||z!==O)break;j++}if(j===0)return S$;return{startIndex:j,carriedViews:Z.segments.slice(0,j).map(({viewPath:W})=>W)}}function HU($,Z){let[,J,...j]=$.split("/");if(!Z.includes(J))return $;let W=`/${j.join("/")}`;return W==="/"?"/":W.replace(/\/$/,"")}function Oz($){let{flatViewRoutes:Z,supportedLocales:J,from:j,origin:W,to:Y}=$;if(!j)return S$;let z;try{z=new URL(j,W)}catch{return S$}if(z.origin!==W)return S$;let O=M3(Z,HU(z.pathname,J));if(!O)return S$;return PU({segments:O.route.segments,params:O.params,search:z.search},Y)}var o4="x-gemi-from";import{createElement as S1,Fragment as kz}from"react";function SU($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function j8($){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=j8(Y.routes);for(let[O,X]of Object.entries(z)){let G=J==="/"?O:`${J}${O}`,K=O==="/"&&J!=="/"?J:G;Z[K]=[W,...X]}if(Z[J].length===1)delete Z[J]}else Z[J]=[W]}else{let W=new j,Y=j8(W.routes);for(let[z,O]of Object.entries(Y)){let X=J==="/"?z:`${J}${z}`,G=z==="/"&&J!=="/"?J:X;Z[G]=O}}return Object.fromEntries(Object.entries(Z).map(([J,j])=>[SU(J),j]))}function W8($,Z){let[J,j]=Z,W=$.find(([Y])=>Y===J);if(!W){$.push([J,[...j]]);return}for(let Y of j)W8(W[1],Y)}function Y8($){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=Y8(Y.routes);W8(Z,[W,z])}else W8(Z,[W,[]])}else{let W=new j,Y=Y8(W.routes);for(let z of Y)W8(Z,z)}return Z}function a4($){let Z=[];for(let[J,j]of $)Z.push(J,...a4(j).flat());return Array.from(new Set(Z))}class e1 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??e1.locale(),$.timeZone??e1.timeZone())}static setLocale($=e1.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 r4{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}var xU=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),fU=new Set(["svg","math"]);function Xz($){return $===32||$===9||$===10||$===12||$===13}function Gz($){return $>=65&&$<=90||$>=97&&$<=122}function z8($){return $>=65&&$<=90?$+32:$}function Kz(){let $="data",Z="",J=!1,j="",W=0,Y=0,z=!1,O=0,X=0,G=()=>$==="data"&&O===0&&X===0,K=()=>{if(!J&&xU.has(Z)){$="rawText",j=`</${Z}`,W=0,Z="";return}if($="data",Z==="template")if(J)O=Math.max(0,O-1);else O+=1;else if(fU.has(Z)){if(J)X=Math.max(0,X-1);else if(!z)X+=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(Gz(U))$="tagName",J=!1,z=!1,Z=String.fromCharCode(z8(U));else if(U===63)$="bogus";else if(U===60)$="tagOpen";else $="data";return;case"endTagOpen":if(Gz(U))$="tagName",J=!0,z=!1,Z=String.fromCharCode(z8(U));else if(U===62)$="data";else $="bogus";return;case"tagName":if(Xz(U)||U===47)$="inTag",z=U===47;else if(U===62)K();else Z+=String.fromCharCode(z8(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(z8(U)===j.charCodeAt(W))W+=1;else W=U===60?1:0;return}if(U===62)$="data",Z="";else if(Xz(U)||U===47)$="inTag",Z="";else W=U===60?1:0;return}}};return{scanToInsertionPoint(U){for(let B=0;B<U.length;B++){if(G())return B;Q(U[B])}return U.length},write(U){for(let B=0;B<U.length;B++)Q(U[B])},isSafe:G}}function P1($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function AU($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${P1([$.path,$.variantKey,$.data])})</script>`}function EU($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${P1([$.id,$.locale,$.strings])})</script>`}function t4($,Z,J={},j){let W=new TextEncoder,Y=[],z=!1,O=!1,X=()=>{if(O)return;O=!0,J.onClose?.()};Z.onSettle((F)=>{if(F.status!=="resolved")return;Y.push(AU(F))}),j?.onUse((F)=>{Y.push(EU(F))});let G=$.getReader(),K=Kz(),Q=(F,D)=>{F.enqueue(D),J.onChunk?.(D)},U=(F)=>{while(Y.length>0){let D=W.encode(Y.shift());K.write(D),Q(F,D)}},B=(F,D)=>{if(Y.length===0){K.write(D),Q(F,D);return}let T=K.scanToInsertionPoint(D);if(T>0)Q(F,D.subarray(0,T));if(K.isSafe())U(F);let M=D.subarray(T);if(M.length>0)K.write(M),Q(F,M)};return new ReadableStream({async pull(F){let D;try{D=await G.read()}catch(_){throw X(),_}let{done:T,value:M}=D;if(T){U(F),F.close(),X();return}if(!z){if(z=!0,K.write(M),Q(F,M),J.onShell?.(),K.isSafe())U(F);return}B(F,M)},cancel(F){return X(),G.cancel(F)}})}var RU=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function O8($){if(!$)return!1;return RU.test($)}async function Qz($,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 bU($,Z),request:{path:W,routePath:j?.routePath??null,locale:J?.locale??null},anonymousId:Uz(),isBot:O8(j?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function Bz($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function bU($,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 Fz($,Z){return`${$}:${Z}`}function e4($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function Dz($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function Tz($,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=kU($,Z,J,j.buckets);return Dz(W,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function vU($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function kU($,Z,J,j){let W=Fz(Z.salt??$,vU(J));if(!j)return e4(W);let Y=j.get(W);if(Y!==void 0)return Y;let z=e4(W);return j.set(W,z),z}class Vz 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 $j{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 Vz(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=wU(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 wU($){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 qU{}class yU 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 Zj 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 Mz 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 Iz{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 CZ{config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new $j($.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 Mz(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let j=gU(J.actor),W=this.config.source;if(typeof W.write!=="function")throw new Zj(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 Iz(this,Bz($))}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:O}=await this.switchFor($),X=Tz($,Y,Z,{active:z,unavailable:O,buckets:J,warn:this.log});return j?.set($,X),this.notify($,X,Z),X}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 Qz(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 gU($){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 Nz($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var mU=50;class _Z{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(Nz(Z.search??{}));W.delete("json"),W.sort();let Y=O0($,j),z=W.toString(),O=this.keyFor(Y,z),X=this.entries.get(O);if(X)return X;let G;if(J==="render"&&this.renderStartedAt!==null){let B=Math.round(performance.now()-this.renderStartedAt);if(B>mU)G=B}let K,Q=new Promise((B)=>{K=B}),U={path:Y,patternPath:$,variantKey:z,lateBy:G,status:"pending",promise:Q,source:J,startedAt:this.elapsed()};return this.entries.set(O,U),this.fetcher($,j,W).then((B)=>{U.status="resolved",U.data=B},(B)=>{U.status="rejected",U.error=B}).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 LZ(){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 Jj(){return{status:403,error:{message:"Forbidden"}}}function I3($){let Z=PZ.getStore();return(J,j,W)=>{let Y=new URL($.url).origin,z=[O0(J,j),W.toString()].filter((K)=>K.length>0).join("?"),O=new Request(`${Y}/${z}`,{headers:$.headers,signal:$.signal}),X=Cz($);if(X)HZ(O,X);let G=new A(O,j);return PZ.run(Z,()=>f.run(G,async()=>{try{let K=await N(a0).dispatchers(X).api.getRouteData(J);if(k$(K)){if(!K.ok)throw new H1(O0(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(O0(J,j),W.toString(),K.status,Q);return Q}return K}catch(K){if(K instanceof H1)throw K;let Q=new H1(O0(J,j),W.toString(),500,{message:K instanceof Error?K.message:String(K)});throw Q.cause=K,Q}}))}}var pU=new Set(["script","style","template","title"]),hU=/\shidden([\s=/]|$)/i,cU=/"[^"]*"|'[^']*'/g;function uU($){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 O=$.indexOf(">",Y);if(O===-1)break;let X=$.slice(Y+1,O);W=O+1;let G=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(X)?.[1]?.toLowerCase();if(!G)continue;let K=X.startsWith("/");if(!K&&pU.has(G)&&!X.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(hU.test(X.replace(cU,'""')))j=1}return{shellChars:Z,deferredChars:J}}var dU=1000,lU=64;function iU($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function sU($,Z){if(Z.deferredChars<dU)return null;if(Z.shellChars>=lU)return null;return`[gemi] GET ${$} streams ${iU(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 _z($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,j){if(Z.has(J))return;let W=sU(J,j);if(!W)return;Z.add(J),$(W)}}}function Lz(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),uU(Z)}}}function Pz($,Z,J=1e4,j){let W=new TextEncoder,Y=()=>{};return new ReadableStream({start(z){let O=!1,X=(K)=>{if(O)return;O=!0,clearTimeout(G);try{z.close()}catch{}j?.({aborted:K})};Y=X,z.enqueue(W.encode(`${JSON.stringify($)}
3
+ `)),Z.onSettle((K)=>{if(O||K.status!=="resolved")return;z.enqueue(W.encode(`${JSON.stringify([K.path,K.variantKey,K.data])}
4
+ `))});let G=setTimeout(()=>X(!0),J);Z.allSettled().then(()=>X(!1),()=>X(!1))},cancel(){Y(!1)}})}import{Fragment as TV,createContext as nU,createElement as VV,lazy as MV,use as IV,useContext as NV}from"react";function Hz($){return{islands:[],render:$,instances:new WeakMap,count:0}}var N3="gemi-slot",Sz="data-slot",xz="data-gemi-slot";var oU=Symbol.for("gemi.staticRender"),fz=globalThis[oU]??=nU(null);import{createHash as aU}from"crypto";var rU="gemi-islands",jj='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)}}',HV=`'sha256-${aU("sha256").update(jj).digest("base64")}'`,tU='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});'+jj;function Az($,Z,J,j){if(!J)return $;let W=j?$.lastIndexOf(Z):$.indexOf(Z);return W===-1?$+J:$.slice(0,W)+J+$.slice(W)}var eU=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;");function Ez($,Z,J,j){if(Z.islands.length===0||!J)return $;let W=new Set,Y=Z.islands.map((X)=>{let G=X.module?J(X.module):void 0;if(!G)return console.error(`[gemi] island ${X.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(X.load==="eager")for(let K of G.preload)W.add(K);return{s:G.src,e:X.export,l:X.load}});if(Y.every((X)=>X===null))return $;let z=[...W].map((X)=>`<link rel="modulepreload" href="${eU(X)}"/>`).join(""),O=`<script type="application/json" id="${rU}">${P1({i:Y})}</script><script type="module">${j?tU:jj}</script>`;return Az(Az($,"</head>",z,!1),"</body>",O,!0)}function $Q($,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 Rz($){let Z=`<template ${xz}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let j=$Q($,J);if(j===-1)break;let W=J+Z.length,Y=$.slice(W,$.indexOf('"',W)),z=$.indexOf(">",W)+1,O=$.slice(z,j-11);$=$.slice(0,J)+$.slice(j);let X=`<${N3} ${Sz}="${Y}" style="display:contents"></${N3}>`;$=$.split(X).join(`<${N3} style="display:contents">${O}</${N3}>`)}return $}function bz($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function vz($,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 ZQ=async()=>(await import("./chunk-qyp652jz.js")).default,Wj,C3=async(...$)=>{return Wj??=import("react-dom/server.browser").catch((Z)=>{throw Wj=void 0,Z}),(await Wj).renderToReadableStream(...$)},wz=1e4,JQ=`
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 jQ($,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((O)=>O.arrayBuffer())}var Oj="/assets";function WQ($){return $===Oj||$.startsWith(`${Oj}/`)}function YQ($){let Z=$.filter(WQ);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 "${Oj}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function zQ($){let Z=N(a0).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function Yj($){let{status:Z=400,error:J}=$;return new Response(J?.message,{...$,status:Z})}function OQ($){let{status:Z=400,data:J,directive:j,headers:W}=$;return new Response(JSON.stringify({data:J,directive:j}),{headers:W,status:Z})}class L3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];staticRoutes=[];root=null;shellReporter=_z();preloadCache=new WeakMap;hooks;partialRendering;constructor($){let Z=w5();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":P4};this.flatViewRoutes=Z8(J),YQ(Object.keys(this.flatViewRoutes)),this.routeManifest=j8(J),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,j])=>j.at(-1)!=="FILE")),this.componentTree=Y8(J),this.flatComponentTree=a4(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(CZ);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)X8();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(j)=>{x$.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 X=new Set(Z?.preload??[]);for(let G of j)for(let K of J?.[G]??[])X.add(K);return[...X].map((G)=>S1("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 O=z.byRoute.get(W);if(!O)O=Y(),z.byRoute.set(W,O);return O}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:j,currentViews:W,data:Y,serverQueries:z,headers:O}=$,X;if(j.layout){if(X=$.viewImportMap[j.layout],!X)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=zj(),Q=new AbortController,U=setTimeout(()=>Q.abort(),wz),B=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},F=Hz(async(D,T)=>{let M=await C3(D,{signal:Q.signal,identifierPrefix:T,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:B});return await M.allReady.catch(()=>{}),await new Response(M).text()});try{let D=await C3(S1(fz.Provider,{value:F,children:S1(kz,{children:[...G,S1(this.root,{data:Y,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:K,rootLayout:X,key:"root"})]})}),{signal:Q.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:B});await D.allReady.catch(()=>{});let T=Rz(await new Response(D).text());return new Response(Ez(T,F,$.resolveIsland,Bun.env.NODE_ENV!=="production"),{status:200,headers:O})}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:O,pathname:X,serverQueries:G,userAgent:K,noStream:Q,url:U,user:B,viewData:F,breadcrumbs:D,urlLocaleSegment:T,meta:M,isOgRequest:_,appId:I,features:H,staticView:P}=$,L=X.replace(`/${T}`,""),V={kind:"view",data:{meta:M,pageData:{[L]:F},__csrf:j.toString("base64"),prefetchedData:{},i18n:z,auth:{user:B},routeManifest:this.clientRouteManifest,breadcrumbs:D,router:{urlLocaleSegment:T,pathname:W,params:O,currentPath:X,searchParams:U.search,is404:!W?!0:!1,domain:Z.domain?zQ(Z):null},appId:I,features:H,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},C=this.root,x=this.routeManifest[W];return async(b)=>{let{bootstrapModules:g=[],loaders:r0,getStyles:m,viewImportMap:q,cssManifest:t0,ogMap:P3,viewModules:H3,clientEntry:$$,modulePreloadManifest:f1,assetBase:A1,resolveIsland:f$}=b,n=$$?[]:g,S3=(e)=>[e,`window.loaders=${r0}`,...$$?[`import(${JSON.stringify($$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(_){let e=null,E$=null;for(let R$ of x??[])if(typeof P3[R$]==="function")E$=R$,e=P3[R$];if(!e)return new Response("Not found",{status:404});let _O=Object.values(V.data.pageData)[0];try{await C3(S1(e,_O[E$]),{onError:()=>{}})}catch(R$){let{fonts:LO,...PO}=R$.satoriOptions,HO=await Promise.all(LO.map((x3)=>{return jQ(x3.name,x3.weight,x3.style).then((EO)=>({...x3,data:EO}))})),Cj=new Headers(Y);Cj.set("Content-Type","image/png");let[SO,xO]=await Promise.all([ZQ(),e6("Rendering an OG image")]),fO=await SO(R$.jsx,{...PO,fonts:HO}),AO=await xO(Buffer.from(fO)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(AO),{headers:Cj})}return new Response("data")}if(P&&W)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:P,currentViews:x,data:V.data,serverQueries:G,headers:Y,getStyles:m,viewImportMap:q,viewModules:H3,resolveIsland:f$});if(V.data.cssManifest=t0,V.data.modulePreloadManifest=f1??{},A1&&A1!=="/")V.data.assetBase=A1;let I8=this.modulePreloadLinks({clientEntry:$$,modulePreloadManifest:f1,views:x??["404"],routeKey:W??"404"}),A$=await m(x);V.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let G1=new AbortController,AZ=setTimeout(()=>G1.abort(),wz),K1=O8(K)||Q,R=Bun.env.NODE_ENV!=="production"&&!K1&&W&&this.shellReporter.shouldObserve(W)?Lz():null,w0=zj();try{let e=await C3(S1(kz,{children:[...I8,...A$,S1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:JQ}}),S1(C,{data:V.data,viewImportMap:q,viewModules:H3,serverQueries:G,dictionarySink:w0,key:"root"})]}),{bootstrapScriptContent:S3(`window.__GEMI_DATA__ = ${P1(V.data)}`),bootstrapModules:n,signal:G1.signal,...K1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(E$){if(Bun.env.NODE_ENV!=="production")console.error(E$)}});if(e.allReady.catch(()=>{}).finally(()=>clearTimeout(AZ)),K1)await e.allReady.catch(()=>{});return new Response(t4(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(AZ),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(G1.signal.aborted))),e;let E$=await C3(S1("div"),{bootstrapScriptContent:S3(`window.error= ${P1(e.message)}; window.stack_trace=${P1(e.stack)};window.__GEMI_DATA__ = ${P1(V.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...n]:n});return new Response(t4(E$,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(G1.signal.aborted)))}),{status:!W?$.refusedStatus??404:200,headers:Y})}}}viewRefusalStatus($,Z,J){if(_3(Z))return 404;if(Z?.kind===SZ){let j=Z.payload?.view?.status;return j===403||j===404?j:null}if(xZ(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,...O]=Y.split("/"),X=`/${O.join("/")}`,G=null,K=null,Q=N(o);if(!Q.supportedLocales.includes(z))X=Y;else G=z,K=z;let B=K===null&&M3(this.flatViewRoutes,X)!==null;if(Q.isLocaleAware&&!W&&K===null&&!B){let V=qz(z,Q.supportedLocales,Q.defaultLocale);if(V){let C=O.length?`/${O.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",X));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}`}})}}X=X.replace("//","/");let F=[],D=[],T=null,M={},_=null,I=!1,H=[],P;try{let V=M3(this.flatViewRoutes,X);if(V){if(T=V.routePath,M=V.params,F=V.route.exec,D=V.route.middleware,H=V.route.features,I=D.includes("no-stream"),P=V.route.static,j&&this.partialRendering){let C=$.headers.get(o4),x=Oz({flatViewRoutes:this.flatViewRoutes,supportedLocales:N(o).supportedLocales,from:C,origin:J.origin,to:{segments:V.route.segments,params:M,search:J.search}});if(x.startIndex>0)F=F.slice(x.startIndex),_={from:C,carriedViews:x.carriedViews}}}}catch(V){throw V}if(P&&j)return new Response("Not found",{status:404});let L=new A($,M,"view",T);return this.hooks.onRequestStart(L),await f.run(L,async()=>{let V=null,C=f.getStore(),x=PZ.getStore(),b=(q)=>PZ.run(x,()=>f.runWith(C,q));C.serverQueries=new _Z(I3($));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=bz(P);if(K){let q=K.replaceAll("/","");e1.setLocale(q,{cookie:r0.locale})}else e1.setLocale(void 0,{cookie:r0.locale});let m=C.req;if(r0.session)X8();try{let q=null;try{await N(VZ).runMiddleware(D)}catch(R){if(q=this.viewRefusalStatus(m,R,g),q===null)throw R}if(q!==null||H.length>0&&!await this.passesFeatureGates(H))T=null,F=[],m.routePath="";let t0=N(o),P3=t0.isEnabled,H3=t0.isLocaleAware,$$=new A($,m.params),f1={defaultLocale:t0.defaultLocale,timeZone:t0.detectTimeZone($$)};if(H3){let R=null;if(K)R=K.replaceAll("/",""),C.setLocale(R);else R=t0.detectLocale($$),C.setLocale(R);let w0=P3?t0.getPageTranslations(R,m.routePath):{};f1={...f1,supportedLocales:t0.supportedLocales,currentLocale:R,dictionary:{[R]:w0},defaultLocale:t0.defaultLocale}}await yz(f1.currentLocale??"");let A1;try{A1=await Promise.all(F.map((R)=>R(m)))}catch(R){if(q=this.viewRefusalStatus(m,R,g),q===null)throw R;T=null,F=[],m.routePath="",A1=[]}let{cookies:f$,headers:n}=C;if(q!==null)n.set("Cache-Control","no-store");V={data:A1,cookies:f$,headers:n,user:C.user,prefetchedData:C.serverQueries.snapshotResolved(),currentPathName:T,params:m.params,urlLocaleSegment:G,meta:C.renderMeta(),appId:N(r4).id,features:await N(CZ).forClient()};let{params:S3,user:I8}=V,A$={},G1={};for(let R of A1??[]){let[w0,e]=Object.entries(R)?.[0]??[];if(!w0||!e)continue;G1[`${w0}:${T}`]=e.breadcrumb,A$[w0]=e}let AZ=A$.FILE;if(AZ){for(let R of f$)n.append("Set-Cookie",R.toString());try{await this.onRequestEnd(m)}catch(R){x$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}return await R8(AZ,n)}if(j){n.set("Content-Type","application/x-ndjson; charset=utf-8"),n.append("Vary",o4),f$.forEach((w0)=>n.append("Set-Cookie",w0.toString())),await this.hooks.onRequestEnd(m);let R={meta:_&&!C.metadata.touched?null:V.meta,data:{[X]:A$},breadcrumbs:G1,prefetchedData:C.serverQueries.snapshotResolved(),i18n:f1,features:V.features,is404:!T,appId:V.appId,partial:_};return new Response(Pz(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&&!(P&&T))n.append("Vary","User-Agent");let K1=Boolean(P&&T);if(!K1||r0.session)X8();for(let R of f$)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){x$.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}if(K1)vz(n,P);return await this.render({req:m,runInRequestScope:b,csrfTokenHMAC:Buffer.from(""),currentPathName:T,headers:n,i18n:f1,params:S3,pathname:J.pathname,serverQueries:C.serverQueries,userAgent:$.headers.get("user-agent"),noStream:I,url:J,user:I8,viewData:A$,breadcrumbs:G1,urlLocaleSegment:G,meta:V.meta,appId:V.appId,features:V.features,isOgRequest:W,staticView:T?P:void 0,refusedStatus:q??void 0})}catch(q){if(q.kind===SZ)if(j)return OQ(q.payload.viewData??q.payload.api);else return Yj(q.payload.view);if(!g.has(q))this.hooks.onRequestFail(m,q);if(xZ(q))return console.error(q),j?LZ():Yj(Jj());if(q instanceof H1&&q.status===403)return j?LZ():Yj(Jj());throw q}},Z)}}function Xj(){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 uz extends x0{routes={"/api-routes":this.get(()=>{let $=N(K8).flatRoutes,Z=[];for(let[J,j]of Object.entries($))for(let[W,Y]of Object.entries(j)){let{exec:z,middleware:O}=Y;Z.push({path:J,method:W,middleware:O})}return Z}),"/view-routes":this.get(()=>{let $=N(L3).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 XQ=new Set([R1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),GQ=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,KQ=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function UQ($,Z,J){for(let[j,W]of Object.entries(J.headers??{})){if(W===void 0||W===null)continue;let Y=j.toLowerCase();if(XQ.has(Y)||Y.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${j}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);$.set(j,W)}for(let[j,W]of Object.entries(J.cookies??{})){if(W===void 0||W===null)continue;if(j===R1)throw Error(`dispatchAs: credentials may not set the "${R1}" cookie. The access token stays the initiator's.`);if(!GQ.test(j)||!KQ.test(W))throw Error(`dispatchAs: "${j}" is not a cookie a Cookie header can carry.`);Z.push(`${j}=${W}`)}}function QQ($,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 O;try{O=await J.read()}catch(X){W(),z.error(X);return}if(O.done){W();try{z.close()}catch{}return}try{z.enqueue(O.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 gz($){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 mz($,Z,J){let j=[];Z?.forEach((z,O)=>j.push([O,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[O,X]of j){if(O.toLowerCase()==="set-cookie")continue;if(!z.has(O))z.set(O,X)}for(let O of W)z.append("Set-Cookie",O)};try{return Y($.headers),$}catch{let z=new Headers($.headers);return Y(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}class K8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=k5();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=R4({"/":$.rootRouter,"/auth":H4,"/__gemi__/services/i18n":S4,"/__gemi__/services/logs":E4,"/__gemi__/services/image":A4,"/__gemi__/debug":uz})}getRouteHandlerAndParams($){let Z=new URL($.url),J=cz(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(VZ).runMiddleware(j)}catch(W){if(W.kind===SZ)return gz(W.payload.api);else{if(_3(W))return Xj();if(this.onRequestFail(Z,W),console.error(W),xZ(W))return LZ();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===SZ)return gz(Y.payload.api);if(_3(Y))return Xj();if(this.onRequestFail(J.req,Y),console.error(Y),xZ(Y))return LZ();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){x$.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(),O=!1,X=async()=>{O=!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(VZ).applyDefaultBodyLimit($);let K=await this.runRouteMiddleware(j,Y);if(K instanceof Response){let D=mz(K,z.headers,z.cookies);return await X(),D}let Q=await this.getRouteData(j),U=z.headers,B=z.cookies;if(Q instanceof Response){let D=mz(Q,U,B);if(this.isOpenEndedBody($,D)){let T=QQ(D,()=>this.endRequest(z,Y,j));return O=!0,T}return await X(),D}let F=(k$(Q)?Q:Z$.json(Q)).toResponse(U,B);return await X(),F}catch(G){if(!O)try{await X()}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}`),O=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==Y||z.pathname!==O||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 X=new Headers,G=[],K=$.cookies.get(R1);if(K)G.push(`${R1}=${K}`);if(W?.credentials)UQ(X,G,W.credentials);if(G.length>0)X.set("Cookie",G.join("; "));let Q=$.headers.get(R1);if(Q)X.set(R1,Q);let U=$.headers.get("User-Agent");if(U)X.set("User-Agent",U);let B;if(j instanceof FormData)B=j;else if(j!==void 0)X.set("Content-Type","application/json"),B=JSON.stringify(j);let F=new Request(z,{method:Z,headers:X,body:B});if(pz(F,q$($)),$.domain)HZ(F,$.domain);return f.exit(()=>hz.exit(()=>this.handleApiRequest(F)))}}import{timingSafeEqual as BQ}from"crypto";var Q8="",Uj="*",FQ=60000,DQ=1e4,Gj=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,U8=16,dz=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,Kj="x-forwarded-host";function lz($){return $.startsWith(":")}function Qj($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),j=Buffer.from(Z,"utf8");return J.length===j.length&&BQ(J,j)}function TQ($){if(!$)return null;if($===!0)return{header:Kj,secret:null};return{header:($.hostHeader??Kj).toLowerCase(),secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function VQ($){if(!$||$===!0)return;let{hostHeader:Z,secret:J}=$;if(Z!==void 0&&(typeof Z!=="string"||!dz.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"||!dz.test(J.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${J.header}".`);if(J.header.toLowerCase()===(Z??Kj).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<U8)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${U8} characters. A guessable one lets any client name its own host.`)}function X1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function MQ($){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 IQ($){let Z=X1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((Y)=>Gj.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<U8)throw Error(`\`route.domains.ask.secret\` must be at least ${U8} characters. A guessable one is worse than leaving \`ask\` out.`);VQ($.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),lz(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((O)=>Gj.test(O)))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 Bj{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){IQ($),this.root=X1($.root),this.hostTrust=TQ($.trustProxy);for(let Z of $.groups??[])if(lz(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??FQ,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!Qj($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}hostOf($){return X1(this.forwardedHost($))??X1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),j=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),W=this.forwardedHost($),Y=W&&X1(W)?MQ(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:Uj,params:{},custom:!0};return null}async allows($,Z){let J=X1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:Q8,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&&Gj.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>=DQ)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=X1($);if(Z)this.cache.delete(Z)}}}var NQ="/__gemi__/domains/ask";class a0{static token="router.domains";resolver;acceptsCustomDomains;groups=new Map;constructor($,Z){this.groups.set(Q8,$);let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new Bj(J);let j=(W)=>({api:W.api?new K8({...Z.api,...W.api}):$.api,view:W.view?new L3({...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(Uj,j(J.custom.fallback))}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)iz($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return HZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==NQ)return null;if(!Qj(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??Q8)}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 B8($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var sz=600000;function nz($,Z){return[y3($,Z),y3($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new s8){this.config={...F8(CW($),$),emailCode:l8($.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:X1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let j=$.domain?.host??X1(new URL($.rawRequest.url).host);return j===J||j?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!g8($))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=B8(J.expiresAt),Y=B8(J.absoluteExpiresAt);if(W<=j||Y<=j)return await this.userProvider.deleteSession({token:$}),null;let O=await this.slideSession(J,j);return O.user.extension=await this.config.extendSession(O.user),O}async convertLegacySession($,Z,J){let j=f.getStore()?.req;if(!j)return null;let W=Date.now(),Y=Math.floor(W/sz),z=null,O=await this.userProvider.findSession({token:$,userAgent:Z});if(O?.user){if(!await J(O,{token:$,req:j,userAgent:Z}))return null;let G=y3($,Y),K=O.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 nz($,Y))if((await this.userProvider.findSession({token:G,userAgent:Z}))?.user){z=G;break}}if(!z)return null;let X=await this.getSession(z,Z);if(X)j.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(j,new Date(X.expiresAt)));return X}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(g8($)||!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()/sz),j=nz($,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 J$;let j=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),W=KW(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:VW(Z);return await this.userProvider.createMagicLinkToken({email:$,token:g3("link",$,J),pin:g3("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 hZ("pin",$,null,Z),{status:"invalid"};let z=B8(Y.createdAt);if(z+j*60000<=Date.now())return hZ("pin",$,null,Z),{status:"expired"};if(!await NW(Y.id,z,W,j))return await this.userProvider.claimMagicLinkToken(Y.id),{status:"too_many_attempts"};if(!hZ("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=hZ("link",$,J?.token,Z);if(!J||!j)return!1;if(B8(J.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.userProvider.claimMagicLinkToken(J.id)}}class P$ extends z0{static getFacadeAccessor(){return E}static async user(){let $=f.getStore(),Z=$?.user;if(!Z){if(Z=await v3(this.getFacadeRoot(),$?.req),Z)$?.setUser(Z)}if(Z)return Z;throw new J$({redirectTo:b3($?.req,this.getFacadeRoot().config.signInPath)})}static intendedUrl($){let Z=f.getStore()?.req;return vZ(Z?.search.get(w$),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await P$.user();if(!await $(Z))throw new y$}static async guardSafe($){let Z=await P$.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 D8{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 _Z(I3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=D8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){D8.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 _Z(I3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function oz($,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=CQ(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 CQ($){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 az{static absolute($,...Z){return`${process.env.HOST_NAME}${O0(String($),Z[0]??{})}`}static relative($,...Z){return O0(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 oz({root:j.root,origin:Y},$,O0(String(Z),J[0]??{}))}}class rz{name="Meta";static description($){f.getStore().metadata.description($)}static title($){f.getStore().metadata.title($)}static openGraph($){f.getStore().metadata.openGraph($)}}var _Q={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 x1 extends z0{static getFacadeAccessor(){return tz}static get client(){return this.getFacadeRoot().client}static get($){return x1.client.get($)}static set($,Z){return x1.client.set($,Z)}static del(...$){return x1.client.del(...$)}static exists($){return x1.client.exists($)}static incr($){return x1.client.incr($)}static expire($,Z){return x1.client.expire($,Z)}static ttl($){return x1.client.ttl($)}}class ez extends z0{static getFacadeAccessor(){return e0}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}}class ZO extends z0{static getFacadeAccessor(){return $O}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}function yI($){return $}function JO(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function T8($){let Z=new URLSearchParams;for(let[J,j]of $)Z.append(J,String(j));return Z.toString()}function Fj($){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:LQ}=globalThis.Bun;function PQ(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var HQ=async($)=>{let Z=new LQ($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,j,W)=>Z.listen(J,j,W),close:()=>Z.close({timeout:1})}},SQ=async($)=>{let Z;try{Z=(await import("./chunk-rx2shb3t.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(()=>{})}},jO=($)=>PQ()?HQ($):SQ($);var xQ=/^[A-Za-z_][A-Za-z0-9_]*$/;class Dj{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(!xQ.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??jO}async createTable(){for(let $ of fQ(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 WO(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((O)=>({seq:Number(O.seq),data:JSON.parse(O.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||W$()!==this.connection)return;return $}}function fQ($,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 Tj{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 GO=new TextEncoder;function YO($,Z){return GO.encode(`id: ${$}
42
+ data: ${JSON.stringify(Z)}
43
+
44
+ `)}function KO($,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 V8))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 O=null,X=!1,G=!1,K=(U)=>{if(O)clearInterval(O);if(O=null,z.close(),G)return;G=!0;try{U.close()}catch{}},Q=new ReadableStream({start(U){O=setInterval(()=>{if(XO())return K(U);try{U.enqueue(GO.encode(zO))}catch{K(U)}},$.config.keepaliveInterval)},async pull(U){try{if(!X){if(await z.ready(),X=!0,!G)U.enqueue(YO(z.cursor,{type:"ready"}));return}let B=await z.next();if(B.done||G)return K(U);U.enqueue(YO(z.cursor,B.value))}catch(B){if(!G)console.error("[gemi] A change feed stream failed.",B);K(U)}},cancel(){if(G=!0,O)clearInterval(O);O=null,z.close()}});return new Response(Q,{headers:OO()})}var UO=255,QO=500,AQ=30000;class V8 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class Nj{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=QO;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=F8(JO(),$),this.driver=RQ(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){Ij($);let J=Z===void 0?null:Z;if(F1()!==void 0&&!this.driver.joinsTransaction?.())return Mj(async()=>{this.wake($,await this.driver.publish($,J))}),null;let j=await this.driver.publish($,J);return Mj(()=>this.wake($,j)),j}async head($){return Ij($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=Vj($);return T8(await this.driver.heads(Z))}subscribe($,Z={}){let J=Vj($);if(this.all.size>=this.config.maxSubscriptions)throw new V8(this.config.maxSubscriptions);let j=new BO(this,J,EQ(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 KO(this,$,Vj(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=QO,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,AQ)}}}class BO{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 T8(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 Ij($){if(typeof $!=="string"||$===""||$.length>UO)throw Error(`A change feed channel is a string of 1 to ${UO} characters; got ${JSON.stringify($)}.`)}function Vj($){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)Ij(J);return Z}function EQ($){if($===void 0||$===null)return new Map;if(typeof $==="string")return Fj($);let Z=$ instanceof Map?[...$]:Object.entries($);return Fj(T8(new Map(Z)))}function RQ($,Z){if($==="memory")return new Tj;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 Dj(Z.make(Y$));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 FO extends z0{static getFacadeAccessor(){return Nj}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 DO extends z0{static getFacadeAccessor(){return CZ}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 M8{bound;constructor($){this.bound=$}get name(){return this.bound??W$()}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 MO(J.sql,(j)=>TO(Z,()=>$(j)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-mx9y9mtx.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:j,values:W}=NO($,IO(J.dialect),Z);return(this.handle()??J.sql).unsafe(j,W)}handle(){let $=F1();if($===void 0)return;return W$()===this.name?$:void 0}connection($=this.name){return VO($),N(Y$).connection($)}}var fZ=new M8;class CO extends z0{static getFacadeAccessor(){return Y$}static connection($){return new M8($)}static get sql(){return fZ.sql}static get dialect(){return fZ.dialect}static query($){return fZ.query($)}static execute($){return fZ.execute($)}static transaction($){return fZ.transaction($)}static schema(){return fZ.schema()}static close(){return this.getFacadeRoot().close()}}export{U1 as rc,EZ as sc,L8 as tc,v$ as uc,bZ as vc,x0 as wc,f8 as xc,A8 as yc,wj as zc,R3 as Ac,Z$ as Bc,mO as Cc,R8 as Dc,E1 as Ec,X0 as Fc,pO as Gc,hO as Hc,y8 as Ic,g8 as Jc,KW as Kc,e0 as Lc,kZ as Mc,aj as Nc,q$ as Oc,UW as Pc,QW as Qc,p8 as Rc,h8 as Sc,g3 as Tc,hZ as Uc,YD as Vc,CW as Wc,HX as Xc,s8 as Yc,P$ as Zc,e1 as _c,D8 as $c,az as ad,rz as bd,_Q as cd,x1 as dd,ez as ed,ZO as fd,yI as gd,JO as hd,T8 as id,Fj as jd,Dj as kd,Tj as ld,V8 as md,Nj as nd,BO as od,FO as pd,Fz as qd,e4 as rd,Dz as sd,Tz as td,vU as ud,Vz as vd,$j as wd,qU as xd,yU as yd,Zj as zd,Mz as Ad,Iz as Bd,CZ as Cd,DO as Dd,M8 as Ed,CO as Fd,x4 as Gd,f4 as Hd,sD as Id,E5 as Jd,R5 as Kd,k3 as Ld,VZ as Md,GT as Nd,k5 as Od,w5 as Pd,r4 as Qd,LZ as Rd,Jj as Sd,HV as Td,Oj as Ud,WQ as Vd,Yj as Wd,OQ as Xd,L3 as Yd,Xj as Zd,gz as _d,mz as $d,K8 as ae,a0 as be,E as ce,uj as de,dj as ee,ij as fe,ej as ge,$W as he,ZW as ie,k8 as je,lO as ke,g$ as le,Q0 as me,B1 as ne,p$ as oe,v1 as pe,h$ as qe,c$ as re,u$ as se,yZ as te,gZ as ue,k1 as ve,pZ as we,zW as xe};
45
+
46
+ //# debugId=C4BD24F82AB4ED8A64756E2164756E21